diff --git a/.github/ISSUE_TEMPLATE/bug-report.md b/.github/ISSUE_TEMPLATE/bug-report.md new file mode 100644 index 0000000000..e2f42e5c54 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug-report.md @@ -0,0 +1,30 @@ +--- +name: "\U0001F41B Bug report" +about: Report a bug to help us improve +title: '' +labels: '' +assignees: '' + +--- + + diff --git a/.github/ISSUE_TEMPLATE/enhancement-request.md b/.github/ISSUE_TEMPLATE/enhancement-request.md new file mode 100644 index 0000000000..4d10dc77d9 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/enhancement-request.md @@ -0,0 +1,30 @@ +--- +name: "\U0001F389 Enhancement request" +about: Ask for something to be improved in this repo +title: '' +labels: '' +assignees: '' + +--- + + diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md new file mode 100644 index 0000000000..79c92c0e67 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/question.md @@ -0,0 +1,11 @@ +--- +name: "❓ Question" +about: Please use Stack Overflow (https://stackoverflow.com/questions/tagged/scala.js) + or Gitter (https://gitter.im/scala-js/scala-js) for questions +title: '' +labels: '' +assignees: '' + +--- + +Please ask questions on [Stack Overflow](https://stackoverflow.com/questions/tagged/scala.js) or [Gitter](https://gitter.im/scala-js/scala-js) instead of using this issue tracker. diff --git a/.github/workflows/cla.yml b/.github/workflows/cla.yml index 42849628e7..e3a39bd5aa 100644 --- a/.github/workflows/cla.yml +++ b/.github/workflows/cla.yml @@ -5,4 +5,4 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - - run: ./ci/check-cla.sh + - run: ./ci/check-cla.sh "${{ github.event.pull_request.user.login }}" diff --git a/.gitignore b/.gitignore index 49696008c1..5c978cc5cd 100644 --- a/.gitignore +++ b/.gitignore @@ -1,12 +1,25 @@ +# Fundamental to the build target/ +/.bsp/ +/scalalib/fetchedSources/ +/partest/fetchedSources/ +/linker-interface/**/scalajs-logging-src/ +/linker-interface/**/scalajs-logging-src-jars/ +/node_modules/ + +# IDE specific .cache .classpath .project .settings/ -/scalalib/fetchedSources/ -/partest/fetchedSources/ -/cli/pack/ /.idea/ /.idea_modules/ bin/ -/node_modules/ +/.bloop/ +/.metals/ +/project/**/metals.sbt +/.vscode/ + +# User specific +/.jvmopts +/.sbtopts diff --git a/CODINGSTYLE.md b/CODINGSTYLE.md index 5781b4dfd9..da517b020e 100644 --- a/CODINGSTYLE.md +++ b/CODINGSTYLE.md @@ -43,15 +43,44 @@ A continuation line is a line appearing because we broke something that should h Typically, this means inside parentheses (formal or actual parameters of methods and constructors), and a long `extends` clause. Note that breaking a line right after the `=` sign of an initialization or assignment is *not* considered a continuation line, because it's not really breaking the line: instead, we just choose to put the rhs on its dedicated line, indented 2 spaces (similarly to the branches of an `if`). +For example: + +```scala +val x = + aLongFunctionCall() +``` + +Further, parenthesized lists that have a single element per line are not considered continuation lines. +For example, the following two are allowed: + +```scala +// "Binpacked style" +f(arg1, arg2, + arg3, arg4) + +// "List style" +f( + arg1, + arg2, + arg3, + arg4 +) +``` + +Notes about the list style: +* The parentheses must be on individual lines. +* A trailing comma will become mandatory if/once we drop 2.11. +* This style is relatively new, so a lot of code does not comply to it; apply the boy scout rule where this does not cause unnecessary diffs. ### Blank lines * Never put two blank lines in a row * (Almost) always put a blank line between two declarations in a class -* Always put blank lines around a `case` whose body spans several lines * Insert blank lines at will between logical blocks of statements in a method +* Always put blank lines around a `case` whose body contains a blank line +* In general, if some kind of block of code *contains* a blank line inside it, it should also be *surrounded* by blank lines (this prevents the brain from visually parsing blocks in the wrong way) -The blank line between two consecutive declarations in a class can sometimes be omitted, if the declarations are single-line (which also means ScalaDocless) and strongly related. +The blank line between two consecutive declarations in a class can sometimes be omitted, if the declarations are single-line (which also means Scaladocless) and strongly related. This happens pretty rarely (mostly a series of private fields). The rule of thumb is to always put a blank line. @@ -114,7 +143,7 @@ def abs(x: Int): Int = #### Long expressions with binary operators -Very long expressions consisting of binary operators at their "top-level" can be broken *without indentation* if they are alone in their brace-delimited block. +Very long expressions consisting of binary operators at their "top-level" can be broken *without indentation* if they are alone in their brace-delimited block or their actual parameter. This happens mostly for long chains of `&&`s, `||`s, or string concatenations. Here is an example: @@ -124,6 +153,12 @@ val isValidIdent = { ident.charAt(0).isUnicodeIdentifierStart && ident.tail.forall(_.isUnicodeIdentifierPart) } + +if (!isValidIdent) { + reportError( + "This string is very long and will " + + "span several lines.") +} ``` #### Braces in lambdas @@ -145,20 +180,27 @@ val someLongIdentifierWithHighIdentation = { } ``` +If a lambda is a one-liner, we do not use braces at all: + +```scala +val f = (x: Int) => body + +val ys = xs.map(x => x + 1) +``` + ### Spaces There must not be any space before the following tokens: `:` `,` `;` `)` There must be exactly one space after the following tokens: `:` `,` `;` `if` `for` `while` -Sometimes, it is acceptable to have several spaces, for vertical alignment reasons. + +There must be exactly one space before the tokens `=` and `=>`, and either exactly one space or a new line after them. +Exception: `=>` may be vertically aligned instead in some scenarios: see [the "Pattern matching" section](#pattern-matching). There must be exactly one space before and after `{` and `}`. With the exception of partial import, where there is no space on either side. -Binary operators, including `=>`, must have a single space on both sides. -Sometimes, spaces can be removed to highlight the relatively higher priority wrt. to a neighboring operator, for easier visual parsing. -For example, instead of `x < len - 1`, it is better to write `x < len-1`, highlighting that `-` has a higher priority than `<`. - +Binary operators must have a single space on both sides. Unary operators must not be followed by a space. ### Method call style @@ -167,16 +209,15 @@ Usually, parentheses should be used for actual parameters to a method call. Braces should be used instead if an argument list has only a lambda, and that lambda does not fit in an inline one-liner. In general, dot-notation should be used for non-symbolic methods, and infix notation should be used for symbolic methods. -Infix notation is also used if the only argument is a brace lambda. Examples: ```scala -// inline lambda, hence (), hence dot-notation +// inline lambda, hence () list.map(x => x * 2) -// long lambda, hence braces, hence infix notation -list map { x => +// long lambda, hence braces +list.map { x => if (x < 5) x else x * 2 } @@ -185,20 +226,15 @@ list map { x => value :: list ``` -Using dot-notation with a brace lambda is possible to force priorities. -This is typically the case if the call is chained to a parameterless method call, as in - -```scala -list.map { x => - // complicated stuff -}.toMap -``` - -When calling a method declared with an empty pair of parentheses, use `()`, except if the method is Java-defined *and* does not have side-effects. +When calling a method declared with an empty pair of parentheses, always use `()`. +Not doing so causes (fatal) warnings when calling Scala-declared methods in Scala 2.13.3+. +For consistency, we also apply this rule to all Java-defined methods, including `toString()`. ### Method definition All public and protected methods must have an explicit result type. +Private methods are encouraged to have an explicit result type as well, as it helps reading the code. +Local methods do not need an explicit result type. Procedure syntax must not be used. `: Unit =` must be used instead. @@ -268,9 +304,8 @@ import scala.collection.mutable import java.{util => ju} -import org.scalajs.core.tools.sem._ -import org.scalajs.core.tools.javascript._ -import org.scalajs.core.tools.optimizer._ +import org.scalajs.linker._ +import org.scalajs.linker.standard._ ``` Language imports must always come first, and must always be at the top of the file (right after the `package` declaration). @@ -280,16 +315,16 @@ If you import more than 3 or so items from a namespace, use a wildcard import. Avoid importing mutable collections directly; prefer importing `mutable` and then use `mutable.ListBuffer`. -### ScalaDoc +### Scaladoc -ScalaDoc comments that fit in one line must be written as +Scaladoc comments that fit in one line must be written as ```scala /** Returns the maximum of a and b. */ def max(a: Int, b: Int): Int = ??? ``` -Multi-line ScalaDoc comments must use the following style: +Multi-line Scaladoc comments must use the following style: ```scala /** Returns the maximum of a and b. @@ -299,7 +334,7 @@ Multi-line ScalaDoc comments must use the following style: def max(a: Int, b: Int): Int = ??? ``` -### Non-ScalaDoc comments +### Non-Scaladoc comments Normal comments fitting on one-line should use `//`. A comment that does not fit on one line should use the multi-line comment syntax and follow this style: @@ -322,7 +357,7 @@ class Foo(val x: Int) extends Bar with Foobar { self => However, this tends to become too long in many cases. -If the declaration does not fit on one line, the self type must be on dedicated line, indented 2 spaces only, and followed by a blank line: +If the declaration does not fit on one line, the first thing to do is to put the self type on a dedicated line, indented 2 spaces only, and followed by a blank line: ```scala class Foo(val x: Int) extends Bar with Foobar { @@ -331,55 +366,58 @@ class Foo(val x: Int) extends Bar with Foobar { // declarations start here ``` -If too long in itself, the list of constructor parameters should be broken similarly to formal parameters to a method, i.e., indented 4 spaces, and followed by a blank line: +The second thing to do is to break the line just before the `extends` keyword, indented 4 spaces: ```scala -class Foo(val x: Int, val y: Int, - val z: Int) extends Bar with Foobar { +class Foo(val x: Int) + extends Bar with Foobar { // declarations start here ``` -As an exception, if the constructor parameters are a (long) list of "configuration" parameters, the following format should be used instead: +The `extends` clause can be further broken up before `with`s, if necessary. +Additional lines are also indented 4 spaces wrt. the `class` keyword. ```scala -class Foo( - val width: Int = 1, - val height: Int = 1, - val depthOfField: Int = 3 -) extends Bar with Foobar { +class Foo(val x: Int) + extends Bar with Foobar with AnotherTrait with YetAnotherTrait + with HowManyTraitsAreThere with TooManyTraits { + + // declarations start here ``` -Note that there is no vertical alignment, neither for the type nor the default value (if any). -If there are several parameter lists (e.g., with an implicit parameter list), each parameter list follows its rules independently of the others, i.e., organizing one parameter list vertically does not mean another list should be organized vertically as well. -For example: +If too long in itself, the list of constructor parameters should be broken similarly to formal parameters to a method, i.e., indented 4 spaces, and followed by a blank line: ```scala -class Foo[A]( - val width: Int = 1, - val height: Int = 1, - val depthOfField: Int = 3 -)(implicit ct: ClassTag[A]) extends Bar with Foobar { +class Foo(val x: Int, val y: Int, + val z: Int) + extends Bar with Foobar { + + // declarations start here ``` -If too long, the `extends` clause itself should go to the next line, indented 4 spaces, and followed by a blank line: +If the constructor parameters are a (long) list of "configuration" parameters, the list style (as opposed to binpacking) should be used: ```scala -class Foo(val x: Int) - extends Bar with Foobar with AnotherTrait { - - // declarations start here +class Foo( + val width: Int = 1, + val height: Int = 1, + val depthOfField: Int = 3 +) extends Bar with Foobar { ``` -The `extends` clause can be broken further before `with`s, if necessary. -Additional lines are also indented 4 spaces wrt. the `class` keyword. +Note that there is no vertical alignment, neither for the type nor the default value (if any). +If there are several parameter lists (e.g., with an implicit parameter list), each parameter list follows its rules independently of the others, i.e., organizing one parameter list vertically does not mean another list should be organized vertically as well. +For example: ```scala -class Foo(val x: Int) +class Foo[A]( + val width: Int = 1, + val height: Int = 1, + val depthOfField: Int = 3 +)(implicit ct: ClassTag[A]) extends Bar with Foobar with AnotherTrait with YetAnotherTrait with HowManyTraitsAreThere with TooManyTraits { - - // declarations start here ``` @@ -397,7 +435,7 @@ Higher-order methods should be favored over loops and tail-recursive methods whe Do not reinvent the wheel: use the most appropriate method in the collection API (e.g., use `forall` instead of a custom-made `foldLeft`). Methods other than `foreach` should however be avoided if the lambda that is passed to them has side-effects. -In order words, a `foldLeft` with a side-effecting function should be avoided, and a `while` loop or a `foreach` used instead. +In other words, a `foldLeft` with a side-effecting function should be avoided, and a `while` loop or a `foreach` used instead. Use `xs.map(x => x * 2)` instead of `for (x <- xs) yield x * 2` for short, one-liner `map`s, `flatMap`s and `foreach`es. Otherwise, favor for comprehensions. @@ -433,31 +471,48 @@ val x = { } ``` -If one of the brances requires braces, then put braces on both branches: +If one of the brances requires braces, then put braces on both branches (or *all* branches if it is a chain of `if/else`s): ```scala val x = { if (condition) { val x = someExpr x + 5 - } else { + } else if (secondCondition) { anotherExpr + } else { + aThirdExpr } } ``` -`if`s and `if/else`s in statement position should always have their branch(es) on dedicated lines: +`if`s and `if/else`s in statement position must always have their branch(es) on dedicated lines. +The following example is incorrect: + +```scala +if (index >= size) throw new IndexOutOfBoundsException + +if (x > y) i += 1 +else i -= 1 +``` + +and should instead be formatted as: ```scala if (index >= size) throw new IndexOutOfBoundsException + +if (x > y) + i += 1 +else + i -= 1 ``` If the `condition` of an `if` (or `while`, for that matter) is too long, it can be broken *at most once* with 4 spaces of indentation. -In that case, the if and else parts must surrounded by braces, even if they are single-line. +In that case, the if and else parts must be surrounded by braces, even if they are single-line. Obviously, the two-liner `if/else` formatting cannot be applied. -If the condition is so long that two lines are not enough, then it should be extracted in a local `def` before it, such as: +If the condition is so long that two lines are not enough, then it should be extracted in a local `val` or `def` before it, such as: ```scala val ident: String = ??? @@ -467,7 +522,6 @@ def isValidIdent = { ident.charAt(0).isUnicodeIdentifierStart && ident.tail.forall(_.isUnicodeIdentifierPart) } - if (isValidIdent) doSomething() else @@ -487,18 +541,35 @@ x match { ``` If the body of a case does not fit on the same line, then put the body on the next line, indented 2 spaces, without braces around it. -In that case, also put blank lines around that `case`, and do not align its arrow with the other groups: +In that case, also put blank lines around that `case`, and do not align its arrow with the other cases: ```scala x match { - case Foo(a, b) => a + b - + case Foo(a, b) => + val x = a + b + x * 2 case Bar(y) => if (y < 5) y else y * 2 } ``` +A single pattern match can have *both* one-liners with aligned arrows and multi-line cases. +In that case, there must be a blank line between every change of style: + +```scala +x match { + case Foo(a, b) => a + b + case Bar(y) => 2 * y + + case Foobar(y, z) => + if (y < 5) z + else z * 2 +} +``` + +The arrows of multi-line cases must never be aligned with other arrows, either from neighboring multi-line cases or from blocks of one-liner cases. + When pattern-matching based on specific subtypes of a value, reuse the same identifier for the refined binding, e.g., ```scala @@ -517,12 +588,25 @@ that match { } ``` -This is an instantiation of the rule saying that spaces can be removed around a binary operator to highlight its higher priority wrt. its neighbors. +This helps visually parsing the relative priority of `:` over `|`. As a reminder, avoid pattern-matching on `Option` types. Use `fold` instead. +## Explicit types + +As already mentioned, public and protected `def`s must always have explicit types. +Private `def`s are encouraged to have an explicit type as well. + +Public and protected `val`s and `var`s of public classes and traits should also have explicit types, as they are part of the binary API, and therefore must not be subject to the whims of type inference. + +Private `val`s and `var`s as well as local `val`s, `var`s and `def`s typically need not have an explicit type. +They can have one if it helps readability or type inference. + +Sometimes, `var`s need an explicit type because their initial value has a more specific type than required (e.g., `None.type` even though we assign it later to a `List`). + + ## Implementing the Java lib Special rules apply to implementing classes of the JDK (typically in `javalanglib/` or `javalib/`). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index abf92a2e1b..6d1f0aebea 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -3,7 +3,7 @@ ## Very important notice about the Javalib If you haven't read it, ***read the very important notice about the Javalib -in the [Developer documentation](./DEVELOPING.md)***. +in the [Javalib documentation](./JAVALIB.md)*** . ## Coding style @@ -17,19 +17,19 @@ Please consult and follow our [coding style guide](./CODINGSTYLE.md). This the general workflow for contributing to Scala.js. 1. Make sure you have signed the - [Scala CLA](http://typesafe.com/contribute/cla/scala). + [Scala CLA](https://www.lightbend.com/contribute/cla/scala). If not, sign it. 2. You should always perform your work in its own Git branch. The branch should be given a descriptive name that explains its intent. 3. When the feature or fix is completed you should open a - [Pull Request](https://help.github.com/articles/using-pull-requests) on GitHub. + [Pull Request](https://help.github.com/articles/about-pull-requests/) on GitHub. 4. The Pull Request should be reviewed by other maintainers (as many as feasible/practical), among which at least one core developer. Independent contributors can also participate in the review process, and are encouraged to do so. 5. After the review, you should resolve issues brought up by the reviewers as needed (amending or adding commits to address reviewers' comments), iterating until - the reviewers give their thumbs up, the "LGTM" (acronym for "Looks Good To Me"). + the reviewers give their thumbs up by approving the Pull Request. 6. Once the code has passed review the Pull Request can be merged into the distribution. ## Pull Request Requirements @@ -38,10 +38,10 @@ In order for a Pull Request to be considered, it has to meet these requirements: 1. Live up to the current code standard: - Follow the [coding style](./CODINGSTYLE.md) - - Not violate [DRY](http://programmer.97things.oreilly.com/wiki/index.php/Don%27t_Repeat_Yourself). - - [Boy Scout Rule](http://programmer.97things.oreilly.com/wiki/index.php/The_Boy_Scout_Rule) should be applied. + - Not violate [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself). + - The [Boy Scout Rule](https://medium.com/@biratkirat/step-8-the-boy-scout-rule-robert-c-martin-uncle-bob-9ac839778385) should be applied. 2. Be accompanied by appropriate tests. -3. Be issued from a branch *other than master* (PRs coming from master will not be accepted, as we've had trouble in the past with such PRs) +3. Be issued from a branch *other than main or master* (PRs coming from `main` or `master` will not be accepted, as we've had trouble in the past with such PRs) If not *all* of these requirements are met then the code should **not** be merged into the distribution, and need not even be reviewed. @@ -52,7 +52,7 @@ All code contributed to the user-facing standard library (the `library/` directory) should come accompanied with documentation. Pull requests containing undocumented code will not be accepted. -Code contributed to the internals (compiler, tools, JS environments, etc.) +Code contributed to the internals (compiler, IR, linker, JS environments, etc.) should come accompanied by internal documentation if the code is not self-explanatory, e.g., important design decisions that other maintainers should know about. @@ -69,7 +69,7 @@ doing merges/rebases etc.) then please do not commit it all but rewrite the history by squashing the commits into **one commit per useful unit of change**, each accompanied by a detailed commit message. For more info, see the article: -[Git Workflow](http://sandofsky.com/blog/git-workflow.html). +[Git Workflow](https://sandofsky.com/blog/git-workflow.html). Additionally, every commit should be able to be used in isolation--that is, each commit must build and pass all tests. diff --git a/DEVELOPING.md b/DEVELOPING.md index c23a4fa117..bf409ce03e 100644 --- a/DEVELOPING.md +++ b/DEVELOPING.md @@ -2,77 +2,73 @@ ## Very important notice about the Javalib -Scala.js contains a reimplementation of part of the JDK in Scala.js itself. +If you haven't read it, ***read the very important notice about the Javalib +in the [Javalib documentation](./JAVALIB.md)*** . -***To contribute to this code, it is strictly forbidden to even look at the -source code of the Oracle JDK or OpenJDK!*** +## Building -This is for license considerations: these JDKs are under a GPL-based license, -which is not compatible with our BSD 3-clause license. +Scala.js is entirely built with [sbt](https://www.scala-sbt.org/), and also +requires [Node.js](https://nodejs.org/en/) to be installed. For complete +support, Node.js >= 13.2.0 is required. -The only existing JDK source code that we can look at is the dead Apache -Harmony project. +The first time, or in the rare events where `package.json` changes +([history](https://github.com/scala-js/scala-js/commits/main/package.json)), +you need to run -## Building + $ npm install -Scala.js is entirely built with [sbt](http://www.scala-sbt.org/). -To build a local version of the compiler and standard library, run +from your shell. If you *really* do not want to do this, you can avoid that +step, but you will need to use +`set MyScalaJSPlugin.wantSourceMaps in testSuite := false` within sbt to +by-pass source-map-related tests. In addition, bootstrap tests will not pass. - > library/package +Otherwise, everything happens within sbt. -To test your changes, run +Run the normal test suite using the entire Scala.js toolchain using - > testSuite/test + > testSuite2_12/test -or test your tests on the JVM. +In order to test the tests themselves, run the cross-compiling tests on the JVM +with: - > testSuiteJVM/test + > testSuiteJVM2_12/test If you have changed the IR or the compiler, you typically need to > clean before testing anew. -If you have changed the IR, the tools, the JS environments or the sbt plugin, -you typically need to - - > reload -To test with Node.js instead of Rhino, use the usual Scala.js setting: +If you have changed the logging API, the linker interface, the JS environments, +the test adapter or the sbt plugin, you typically need to - > set scalaJSUseRhino in Global := false + > reload -and to run in fullOpt stage: +To test in fullOpt stage: > set scalaJSStage in Global := FullOptStage -When running with Node.js, by default, the test suite requires the -`source-map-support` package to be installed in `npm`. You can bypass the -source map tests locally with this setting: - - > set postLinkJSEnv in testSuite := NodeJSEnv().value.withSourceMap(false) +There are also a few additional tests in a separate testing project: -To test with PhantomJS, use this setting: - - > set inScope(ThisScope in testSuite)(Seq(postLinkJSEnv := PhantomJSEnv().value)) - -The tests for the javalibEx are in a separate testing project: - - > javalibExTestSuite/test + > testSuiteEx2_12/test The compiler tests (mostly verifying expected compile error messages) can be run with - > compiler/test + > compiler2_12/test The full partest suite (tests of the Scala language, ported in Scala.js) are run with: - > partestSuite/test + > partestSuite2_12/test or, more typically, - > partestSuite/testOnly -- --fastOpt + > partestSuite2_12/testOnly -- --fastOpt + +The JUnit tests from scala/scala can be run with + + > scalaTestSuite2_12/test ## Metals-based IDEs @@ -90,7 +86,6 @@ If you want to develop in Eclipse, use the build by default are not suited for Eclipse. You can create *somewhat* appropriate projects with: - $ sbt tools/sources $ GENERATING_ECLIPSE=true sbt "eclipse with-source=true" You will still have to fix a few things: @@ -98,6 +93,12 @@ You will still have to fix a few things: * Uncheck the "Allow output directories per source directory" in Build path * Add transitive project dependencies in Build path +## Preparing a Pull Request + +One common build failure is code styling. Reproduce results locally with: + + $ sbt scalastyleCheck + ## Organization of the repository The repository is organized as follows: @@ -106,47 +107,62 @@ The repository is organized as follows: * `ir/` The Intermediate Representation, produced by the compiler and consumed by the linker * `compiler/` The scalac compiler plugin -* `tools/` The linker, optimizer, verifier, etc.: everything that happens at link time +* `linker-private-library/` Some Scala.js files whose compiled .sjsir files are used as resources of the linker (2.12 only) +* `linker-interface/` The linker interface, without its implementation +* `linker/` The linker, optimizer, verifier, etc.: everything that happens at link time ### Library * `library/` The Scala.js standard library (everything inside `scala.scalajs.*`) * `javalanglib/` Implementation in Scala.js of the classes in `java.lang.*` * `javalib/` Implementation in Scala.js of other classes in `java.*` -* `javalib-ex/` Some more Java classes with non-standard dependencies * `scalalib/` Almost void project for recompiling the Scala library for Scala.js * `library-aux/` A few files of the Scala library that need to be compiled separately -All of these, except `javalib-ex`, are packaged in `scalajs-library.jar` as part -of `library/package`. +All of these are packaged in `scalajs-library.jar`. -### sbt plugin +### Testing infrastructure + +There is a generic infrastructure that maps the sbt-testing-interface API +across the JVM/JS boundary, so that Scala.js testing frameworks can be piloted +from JVM processes such as sbt. -Note that the sbt plugin depends on the IR and the tools. +* `test-interface/` the JS definition of the sbt-testing-interface API +* `test-bridge/` JS side of the bridge +* `test-adapter/` JVM side of the bridge +* `test-common/` Code common between `test-bridge` and `test-adapter` -* `js-envs/` The JavaScript environments and runners (Rhino, Node.js and PhantomJS) -* `sbt-plugin/` The sbt plugin itself +This repository also contains a specific implementation of JUnit: + +* `junit-runtime/` The run-time library for JUnit +* `junit-plugin/` The JUnit compiler plugin + +### sbt plugin + +* `sbt-plugin/` The sbt plugin itself (2.12 only) ### Testing projects * `test-suite/` The main test suite of Scala.js -* `javalib-ex-test-suite/` The test suite for the javalib-ex +* `test-suite-ex/` Additional tests * `partest-suite/` The partest suite of Scala +* `scala-test-suite/` The JUnit suite of Scala ### Example projects/sandboxes * `examples/helloworld/` A simple Hello World, typically used as sandbox for quick testing * `examples/reversi/` The historical Reversi demo - we use it to track the impact of changes on the emitted code size -* `examples/testing/` A simple project with tests using the DOM, mostly used to test the support for the DOM in Rhino +* `examples/testing/` A simple project with tests using the DOM, mostly used to test `testHtml` with DOM interaction -These example projects also have HTML pages to run them in real browsers. +The helloworld and reversi also have HTML pages to run them in real browsers. ### The build itself The build itself contains the entire sbt plugin (and all its dependencies) as part of its sources. -If you change any of the IR, the tools, the JS environments or the sbt plugin, -chances are you need to `reload` the build for your changes to take effect. +If you change any of the linker interface, linker, +test adapter, or the sbt plugin itself, chances are you need to `reload` the +build for your changes to take effect. ## Publish locally @@ -154,7 +170,8 @@ To publish your changes locally to be used in a separate project, use the following incantations. `SCALA_VERSION` refers to the Scala version used by the separate project. + > ;ir2_12/publishLocal;linkerInterface2_12/publishLocal;linker2_12/publishLocal;testAdapter2_12/publishLocal;sbtPlugin/publishLocal > ++SCALA_VERSION - > ;compiler/publishLocal;library/publishLocal;javalibEx/publishLocal;testInterface/publishLocal;testBridge/publishLocal;stubs/publishLocal;jUnitRuntime/publishLocal;jUnitPlugin/publishLocal - > ++2.10.7 - > ;ir/publishLocal;tools/publishLocal;jsEnvs/publishLocal;jsEnvsTestKit/publishLocal;testAdapter/publishLocal;sbtPlugin/publishLocal + > ;compiler2_12/publishLocal;library2_12/publishLocal;testInterface2_12/publishLocal;testBridge2_12/publishLocal;jUnitRuntime2_12/publishLocal;jUnitPlugin2_12/publishLocal + +If using a non-2.12.x version for the Scala version, the `2_12` suffixes must be adapted in the last command (not in the first command). diff --git a/JAVALIB.md b/JAVALIB.md new file mode 100644 index 0000000000..44ff308367 --- /dev/null +++ b/JAVALIB.md @@ -0,0 +1,82 @@ +# Javalib documentation + +## Very important notice about the Javalib + +Scala.js contains a reimplementation of part of the JDK in Scala.js itself. + +***To contribute to this code, it is strictly forbidden to even look at the +source code of the Oracle JDK or OpenJDK!*** + +This is for license considerations: these JDKs are under a GPL-based license, +which is not compatible with our Apache 2.0 license. + +It is also recommended *not to look at any other JDK implementation* (such as +Apache Harmony), to minimize the chance of copyright debate. + +## What goes into the core Scala.js javalib + +Parts of the JDK are in Scala.js itself, parts are in separate projects +(see below for examples). This section aims to provide some guidance +on when an implementation should be included in the core repo as +opposed to a separate repo. The guidance is (unfortunately) imprecise +and the decision of the core maintainers applies in case of a +disagreement. + +To determine whether a JDK API should be part of Scala.js itself, +traverse the following criteria in order until a decision is reached. + +### Does Scala.js core itself depend on the API? + +If yes, include it in core. + +Examples: +- `java.nio.charset._` +- `java.io.DataOutputStream` + +### Does the API need to be implemented in core Scala.js? + +If yes, include it in core. + +Examples: +- `java.nio.*Buffer` (for typedarray integration) +- `java.lang.Object` + +### Can the API be implemented independent of the JS runtime? + +Does the implementation only rely on standardized ES 2015 or does it +require some browser/Node.js/etc.-specific support? + +If no (i.e. it requires specific support), put it in a separate repo. + +Examples: +- Removal of `javalib-ex` that depended on `jszip`. + +### Does the core team have the expertise to maintain the API? + +If no, put it in a separate repo. + +Examples: +- `java.util.Locale` / `java.text._` (https://github.com/cquiroz/scala-java-locales) +- `java.time._` (https://github.com/cquiroz/scala-java-time, + https://github.com/zoepepper/scalajs-jsjoda, + https://github.com/scala-js/scala-js-java-time) + +### Is the core team willing to take the maintenance burden? + +If no, put it in a separate repo. + +Examples: +- `java.logging._` (https://github.com/scala-js/scala-js-java-logging) + +### Versioning / Release Frequency / Quality + +Is the versioning (i.e. pre-relese v.s. stable) and release frequency +of the core artifacts appropriate for the API? + +Are the quality expectations of the core repo appropriate for the +intended implementation? + +Is faster iteration than can be provided by the core repo needed? + +If yes, yes, no, put it in the core repo, otherwise, put it in a +separate repo. diff --git a/Jenkinsfile b/Jenkinsfile index c135a47d92..9346cf8139 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -1,8 +1,8 @@ // If not a PR, this is a long-lived branch, which should have a nightly build def triggers = [] if (!env.CHANGE_ID) { - // This is the 0.6.x series: run weekly on Saturday - triggers << cron('H H(0-2) * * 6') + // This is the 1.x series: run nightly from Sunday to Friday + triggers << cron('H H(0-2) * * 0-5') } // Setup properties of this job definition @@ -56,9 +56,16 @@ def CIScriptPrelude = ''' LOCAL_HOME="/localhome/jenkins" LOC_SBT_BASE="$LOCAL_HOME/scala-js-sbt-homes" LOC_SBT_BOOT="$LOC_SBT_BASE/sbt-boot" -LOC_SBT_HOME="$LOC_SBT_BASE/sbt-home" +LOC_IVY_HOME="$LOC_SBT_BASE/sbt-home" +LOC_CS_CACHE="$LOC_SBT_BASE/coursier/cache" +TEST_LOCAL_IVY_HOME="$(pwd)/.ivy2-test-local" -export SBT_OPTS="-J-Xmx5G -J-XX:MaxPermSize=512M -Dsbt.boot.directory=$LOC_SBT_BOOT -Dsbt.ivy.home=$LOC_SBT_HOME -Divy.home=$LOC_SBT_HOME -Dsbt.global.base=$LOC_SBT_BASE" +rm -rf $TEST_LOCAL_IVY_HOME +mkdir $TEST_LOCAL_IVY_HOME +ln -s "$LOC_IVY_HOME/cache" "$TEST_LOCAL_IVY_HOME/cache" + +export SBT_OPTS="-J-Xmx5G -J-XX:MaxPermSize=512M -Dsbt.boot.directory=$LOC_SBT_BOOT -Dsbt.ivy.home=$TEST_LOCAL_IVY_HOME -Divy.home=$TEST_LOCAL_IVY_HOME -Dsbt.global.base=$LOC_SBT_BASE" +export COURSIER_CACHE="$LOC_CS_CACHE" export NODE_PATH="$HOME/node_modules/" @@ -69,10 +76,10 @@ setJavaVersion() { export PATH=$JAVA_HOME/bin:$PATH } -# Define sbtretry +# Define sbtretry and sbtnoretry sbtretry() { - local TIMEOUT=35m + local TIMEOUT=45m echo "RUNNING timeout -k 5 $TIMEOUT sbt" "$@" timeout -k 5 $TIMEOUT sbt $SBT_OPTS "$@" local CODE=$? @@ -88,363 +95,372 @@ sbtretry() { fi if [ "$CODE" -ne 0 ]; then echo "FAILED TWICE" + echo "Command was: sbt" "$@" return $CODE fi fi } + +sbtnoretry() { + echo "RUNNING sbt" "$@" + sbt $SBT_OPTS "$@" + CODE=$? + if [ "$CODE" -ne 0 ]; then + echo "FAILED" + echo "Command was: sbt" "$@" + return $CODE + fi +} ''' def Tasks = [ "main": ''' setJavaVersion $java npm install && - sbtretry ++$scala 'set scalaJSUseRhino in Global := true' helloworld/run && - sbtretry ++$scala helloworld/run && + sbtretry ++$scala helloworld$v/run && sbtretry 'set scalaJSStage in Global := FullOptStage' \ - ++$scala helloworld/run \ - helloworld/clean && - sbtretry 'set requiresDOM in helloworld := true' \ - ++$scala helloworld/run && - sbtretry 'set requiresDOM in helloworld := true' \ - 'set scalaJSStage in Global := FullOptStage' \ - ++$scala helloworld/run \ - helloworld/clean && - sbtretry 'set scalaJSOptimizerOptions in helloworld ~= (_.withDisableOptimizer(true))' \ - 'set scalaJSUseRhino in Global := true' \ - ++$scala helloworld/run && - sbtretry 'set scalaJSOptimizerOptions in helloworld ~= (_.withDisableOptimizer(true))' \ - ++$scala helloworld/run \ - helloworld/clean && - sbtretry 'set scalaJSSemantics in helloworld ~= (_.withAsInstanceOfs(org.scalajs.core.tools.sem.CheckedBehavior.Unchecked))' \ - ++$scala helloworld/run \ - helloworld/clean && - sbtretry 'set inScope(ThisScope in helloworld)(jsEnv := new org.scalajs.jsenv.RetryingComJSEnv(PhantomJSEnv().value))' \ - ++$scala helloworld/run && - sbtretry 'set inScope(ThisScope in helloworld)(jsEnv := new org.scalajs.jsenv.RetryingComJSEnv(PhantomJSEnv().value))' \ - 'set scalaJSStage in Global := FullOptStage' \ - ++$scala helloworld/run \ - helloworld/clean && + 'set scalaJSLinkerConfig in helloworld.v$v ~= (_.withPrettyPrint(true))' \ + ++$scala helloworld$v/run && + sbtretry 'set scalaJSLinkerConfig in helloworld.v$v ~= (_.withOptimizer(false))' \ + ++$scala helloworld$v/run && + sbtretry 'set scalaJSLinkerConfig in helloworld.v$v ~= (_.withSemantics(_.withAsInstanceOfs(CheckedBehavior.Unchecked)))' \ + ++$scala helloworld$v/run && sbtretry ++$scala \ - 'set scalaJSModuleKind in helloworld := ModuleKind.CommonJSModule' \ - helloworld/run \ - helloworld/clean && + 'set scalaJSLinkerConfig in helloworld.v$v ~= (_.withModuleKind(ModuleKind.CommonJSModule))' \ + helloworld$v/run && sbtretry ++$scala \ - 'set artifactPath in (helloworld, Compile, fastOptJS) := (crossTarget in helloworld).value / "helloworld-fastopt.mjs"' \ - 'set jsEnv in helloworld := new org.scalajs.jsenv.nodejs.NodeJSEnv(org.scalajs.jsenv.nodejs.NodeJSEnv.Config().withArgs(List("--experimental-modules")).withSourceMap(false))' \ - 'set scalaJSModuleKind in helloworld := ModuleKind.ESModule' \ - helloworld/run && + 'set scalaJSLinkerConfig in helloworld.v$v ~= (_.withModuleKind(ModuleKind.CommonJSModule))' \ + 'set scalaJSLinkerConfig in helloworld.v$v ~= (_.withModuleSplitStyle(ModuleSplitStyle.SmallestModules))' \ + helloworld$v/run && sbtretry ++$scala \ - 'set artifactPath in (helloworld, Compile, fullOptJS) := (crossTarget in helloworld).value / "helloworld-opt.mjs"' \ - 'set jsEnv in helloworld := new org.scalajs.jsenv.nodejs.NodeJSEnv(org.scalajs.jsenv.nodejs.NodeJSEnv.Config().withArgs(List("--experimental-modules")).withSourceMap(false))' \ - 'set scalaJSModuleKind in helloworld := ModuleKind.ESModule' \ - 'set scalaJSStage in Global := FullOptStage' \ - helloworld/run \ - helloworld/clean && + 'set scalaJSLinkerConfig in helloworld.v$v ~= (_.withModuleKind(ModuleKind.ESModule))' \ + helloworld$v/run && sbtretry ++$scala \ - 'set Seq(scalaJSUseMainModuleInitializer in helloworld := false, persistLauncher in helloworld := true)' \ - 'set scalaJSUseRhino in Global := true' \ - helloworld/run && + 'set scalaJSLinkerConfig in helloworld.v$v ~= (_.withModuleSplitStyle(ModuleSplitStyle.SmallestModules))' \ + 'set scalaJSLinkerConfig in helloworld.v$v ~= (_.withModuleKind(ModuleKind.ESModule))' \ + helloworld$v/run && sbtretry ++$scala \ - 'set Seq(scalaJSUseMainModuleInitializer in helloworld := false, persistLauncher in helloworld := true)' \ - helloworld/run \ - helloworld/clean && - sbtretry 'set scalaJSUseRhino in Global := true' \ - ++$scala testingExample/test:run testingExample/test && - sbtretry ++$scala testingExample/test:run testingExample/test && - sbtretry 'set scalaJSStage in Global := FullOptStage' \ - ++$scala testingExample/test:run testingExample/test \ - testingExample/clean && - sbtretry 'set inScope(ThisScope in testingExample)(jsEnv := new org.scalajs.jsenv.RetryingComJSEnv(PhantomJSEnv().value))' \ - ++$scala testingExample/test:run testingExample/test && - sbtretry 'set inScope(ThisScope in testingExample)(jsEnv := new org.scalajs.jsenv.RetryingComJSEnv(PhantomJSEnv().value))' \ + 'set scalaJSLinkerConfig in helloworld.v$v ~= (_.withModuleSplitStyle(ModuleSplitStyle.SmallModulesFor(List("helloworld"))))' \ + 'set scalaJSLinkerConfig in helloworld.v$v ~= (_.withModuleKind(ModuleKind.ESModule))' \ + helloworld$v/run && + sbtretry ++$scala \ + 'set scalaJSLinkerConfig in helloworld.v$v ~= (_.withModuleKind(ModuleKind.ESModule))' \ 'set scalaJSStage in Global := FullOptStage' \ - ++$scala testingExample/test:run testingExample/test \ - testingExample/clean && - sbtretry 'set scalaJSOptimizerOptions in testingExample ~= (_.withDisableOptimizer(true))' \ - ++$scala testingExample/test:run testingExample/test && - sbtretry ++$scala library/test && - sbtretry ++$scala testSuiteJVM/test testSuiteJVM/clean && - sbtretry ++$scala 'testSuite/test:runMain org.scalajs.testsuite.junit.JUnitBootstrapTest' && - sbtretry ++$scala testSuite/test && - sbtretry ++$scala javalibExTestSuite/test && + helloworld$v/run && + sbtretry ++$scala testingExample$v/testHtmlJSDom && + sbtretry ++$scala \ + 'set scalaJSLinkerConfig in testingExample.v$v ~= (_.withModuleSplitStyle(ModuleSplitStyle.SmallestModules))' \ + 'set scalaJSLinkerConfig in testingExample.v$v ~= (_.withModuleKind(ModuleKind.ESModule))' \ + testingExample$v/testHtml && + sbtretry 'set scalaJSStage in Global := FullOptStage' \ + ++$scala testingExample$v/testHtmlJSDom && + sbtretry ++$scala testSuiteJVM$v/test testSuiteExJVM$v/test && + sbtretry ++$scala testSuite$v/test && + sbtretry ++$scala testSuiteEx$v/test && sbtretry 'set scalaJSStage in Global := FullOptStage' \ - ++$scala javalibExTestSuite/test && - sbtretry ++$scala testSuite/test:doc compiler/test reversi/fastOptJS reversi/fullOptJS && - sbtretry ++$scala compiler/compile:doc library/compile:doc javalibEx/compile:doc \ - testInterface/compile:doc testBridge/compile:doc && + ++$scala testSuiteEx$v/test && + sbtretry ++$scala \ + 'set scalaJSLinkerConfig in testSuiteEx.v$v ~= (_.withModuleSplitStyle(ModuleSplitStyle.SmallestModules))' \ + 'set scalaJSLinkerConfig in testSuiteEx.v$v ~= (_.withModuleKind(ModuleKind.ESModule))' \ + testSuiteEx$v/test && + sbtretry ++$scala testSuite$v/test:doc library$v/test compiler$v/test && + sbtretry ++$scala \ + 'set scalaJSLinkerConfig in reversi.v$v ~= (_.withModuleSplitStyle(ModuleSplitStyle.SmallestModules))' \ + 'set scalaJSLinkerConfig in reversi.v$v ~= (_.withModuleKind(ModuleKind.ESModule))' \ + reversi$v/fastLinkJS \ + reversi$v/fullLinkJS && + sbtretry ++$scala \ + 'set scalaJSLinkerConfig in reversi.v$v ~= (_.withModuleSplitStyle(ModuleSplitStyle.SmallModulesFor(List("reversi"))))' \ + 'set scalaJSLinkerConfig in reversi.v$v ~= (_.withModuleKind(ModuleKind.ESModule))' \ + reversi$v/fastLinkJS \ + reversi$v/fullLinkJS && + sbtretry ++$scala \ + reversi$v/fastLinkJS \ + reversi$v/fullLinkJS \ + reversi$v/checksizes && + sbtretry ++$scala javalibintf/compile:doc compiler$v/compile:doc library$v/compile:doc \ + testInterface$v/compile:doc testBridge$v/compile:doc && sbtretry ++$scala headerCheck && - sbtretry ++$scala partest/fetchScalaSource && - sbtretry ++$scala library/mimaReportBinaryIssues testInterface/mimaReportBinaryIssues && - sh ci/checksizes.sh $scala && - sh ci/check-partest-coverage.sh $scala + sbtretry ++$scala partest$v/fetchScalaSource && + sbtretry ++$scala \ + javalibintf/mimaReportBinaryIssues \ + library$v/mimaReportBinaryIssues \ + testInterface$v/mimaReportBinaryIssues \ + jUnitRuntime$v/mimaReportBinaryIssues ''', - "test-suite-ecma-script5": ''' + "test-suite-default-esversion": ''' setJavaVersion $java npm install && - sbtretry ++$scala jUnitTestOutputsJVM/test jUnitTestOutputsJS/test \ - 'set scalaJSStage in Global := FullOptStage' jUnitTestOutputsJS/test && - sbtretry ++$scala 'set scalaJSUseRhino in Global := true' jUnitTestOutputsJS/test && - sbtretry ++$scala 'set scalaJSUseRhino in Global := true' $testSuite/test && - sbtretry ++$scala $testSuite/test && + sbtretry ++$scala jUnitTestOutputsJVM$v/test jUnitTestOutputsJS$v/test testBridge$v/test \ + 'set scalaJSStage in Global := FullOptStage' jUnitTestOutputsJS$v/test testBridge$v/test && + sbtretry ++$scala $testSuite$v/test $testSuite$v/testHtmlJSDom && sbtretry 'set scalaJSStage in Global := FullOptStage' \ - ++$scala $testSuite/test \ - $testSuite/clean && - sbtretry 'set requiresDOM in $testSuite := true' \ - ++$scala $testSuite/test && - sbtretry 'set requiresDOM in $testSuite := true' \ + ++$scala $testSuite$v/test \ + $testSuite$v/testHtmlJSDom && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withOptimizer(false))' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withOptimizer(false))' \ 'set scalaJSStage in Global := FullOptStage' \ - ++$scala $testSuite/test \ - $testSuite/clean && - sbtretry ++$scala 'set scalaJSUseRhino in Global := true' noIrCheckTest/test && - sbtretry ++$scala noIrCheckTest/test && - sbtretry 'set scalaJSStage in Global := FullOptStage' \ - ++$scala noIrCheckTest/test \ - noIrCheckTest/clean && - sbtretry 'set scalaJSOptimizerOptions in $testSuite ~= (_.withDisableOptimizer(true))' \ - 'set scalaJSUseRhino in Global := true' \ - ++$scala $testSuite/test && - sbtretry 'set scalaJSOptimizerOptions in $testSuite ~= (_.withDisableOptimizer(true))' \ - ++$scala $testSuite/test \ - $testSuite/clean && - sbtretry 'set scalaJSSemantics in $testSuite ~= makeCompliant' \ - 'set scalaJSUseRhino in Global := true' \ - ++$scala $testSuite/test && - sbtretry 'set scalaJSSemantics in $testSuite ~= makeCompliant' \ - ++$scala $testSuite/test && - sbtretry 'set scalaJSSemantics in $testSuite ~= makeCompliant' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= makeCompliant' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= makeCompliant' \ + 'set scalaJSStage in Global := FullOptStage' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= makeCompliant' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withOptimizer(false))' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= { _.withSemantics(_.withStrictFloats(false)) }' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= { _.withSemantics(_.withStrictFloats(false)) }' \ + 'set scalaJSStage in Global := FullOptStage' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= { _.withSemantics(_.withStrictFloats(false)) }' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withOptimizer(false))' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withAllowBigIntsForLongs(true)))' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withAllowBigIntsForLongs(true)).withOptimizer(false))' \ + ++$scala $testSuite$v/test && + sbtretry \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withAvoidLetsAndConsts(false).withAvoidClasses(false)))' \ + ++$scala $testSuite$v/test && + sbtretry \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withAvoidLetsAndConsts(false).withAvoidClasses(false)))' \ 'set scalaJSStage in Global := FullOptStage' \ - ++$scala $testSuite/test \ - $testSuite/clean && - sbtretry 'set scalaJSSemantics in $testSuite ~= makeCompliant' \ - 'set scalaJSOptimizerOptions in $testSuite ~= (_.withDisableOptimizer(true))' \ - 'set scalaJSUseRhino in Global := true' \ - ++$scala $testSuite/test && - sbtretry 'set scalaJSSemantics in $testSuite ~= makeCompliant' \ - 'set scalaJSOptimizerOptions in $testSuite ~= (_.withDisableOptimizer(true))' \ - ++$scala $testSuite/test \ - $testSuite/clean && - sbtretry 'set scalacOptions in $testSuite += "-Xexperimental"' \ - 'set scalaJSUseRhino in Global := true' \ - ++$scala $testSuite/test && - sbtretry 'set scalacOptions in $testSuite += "-Xexperimental"' \ - ++$scala $testSuite/test && - sbtretry 'set scalacOptions in $testSuite += "-Xexperimental"' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalacOptions in $testSuite.v$v += "-Xexperimental"' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalacOptions in $testSuite.v$v += "-Xexperimental"' \ 'set scalaJSStage in Global := FullOptStage' \ - ++$scala $testSuite/test && - sbtretry 'set scalaJSModuleKind in $testSuite := ModuleKind.CommonJSModule' \ - ++$scala $testSuite/test && - sbtretry 'set scalaJSModuleKind in $testSuite := ModuleKind.CommonJSModule' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withModuleKind(ModuleKind.CommonJSModule))' \ + ++$scala $testSuite$v/test && + sbtretry \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withModuleKind(ModuleKind.CommonJSModule))' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withModuleSplitStyle(ModuleSplitStyle.SmallestModules))' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withModuleKind(ModuleKind.CommonJSModule))' \ 'set scalaJSStage in Global := FullOptStage' \ - ++$scala $testSuite/test \ - $testSuite/clean && - sbtretry 'set artifactPath in ($testSuite, Test, fastOptJS) := (crossTarget in $testSuite).value / "testsuite-fastopt.mjs"' \ - 'set jsEnv in $testSuite := new org.scalajs.jsenv.nodejs.NodeJSEnv(org.scalajs.jsenv.nodejs.NodeJSEnv.Config().withArgs(List("--experimental-modules")).withSourceMap(false))' \ - 'set scalaJSModuleKind in $testSuite := ModuleKind.ESModule' \ - ++$scala $testSuite/test && - sbtretry 'set artifactPath in ($testSuite, Test, fullOptJS) := (crossTarget in $testSuite).value / "testsuite-opt.mjs"' \ - 'set jsEnv in $testSuite := new org.scalajs.jsenv.nodejs.NodeJSEnv(org.scalajs.jsenv.nodejs.NodeJSEnv.Config().withArgs(List("--experimental-modules")).withSourceMap(false))' \ - 'set scalaJSModuleKind in $testSuite := ModuleKind.ESModule' \ + ++$scala $testSuite$v/test && + sbtretry \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withModuleKind(ModuleKind.ESModule))' \ + ++$scala $testSuite$v/test && + sbtretry \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withModuleSplitStyle(ModuleSplitStyle.SmallestModules))' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withModuleKind(ModuleKind.ESModule))' \ + ++$scala $testSuite$v/test && + sbtretry \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withModuleSplitStyle(ModuleSplitStyle.SmallModulesFor(List("org.scalajs.testsuite"))))' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withModuleKind(ModuleKind.ESModule))' \ + ++$scala $testSuite$v/test && + sbtretry \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withModuleKind(ModuleKind.ESModule))' \ 'set scalaJSStage in Global := FullOptStage' \ - ++$scala $testSuite/test + ++$scala $testSuite$v/test ''', - "test-suite-ecma-script6": ''' + "test-suite-custom-esversion-force-polyfills": ''' setJavaVersion $java npm install && - sbtretry 'set scalaJSLinkerConfig in $testSuite ~= (_.withESFeatures(_.withUseECMAScript2015(true)))' \ - 'set jsEnv in $testSuite := new org.scalajs.jsenv.nodejs.NodeJSEnv(org.scalajs.jsenv.nodejs.NodeJSEnv.Config().withSourceMap(false))' \ - ++$scala $testSuite/test && - sbtretry 'set scalaJSLinkerConfig in $testSuite ~= (_.withESFeatures(_.withUseECMAScript2015(true)))' \ - 'set jsEnv in $testSuite := new org.scalajs.jsenv.nodejs.NodeJSEnv(org.scalajs.jsenv.nodejs.NodeJSEnv.Config().withSourceMap(false))' \ + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withESVersion(ESVersion.$esVersion)))' \ + 'set Seq(jsEnv in $testSuite.v$v := new NodeJSEnvForcePolyfills(ESVersion.$esVersion), MyScalaJSPlugin.wantSourceMaps in $testSuite.v$v := ("$esVersion" != "ES5_1"))' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withESVersion(ESVersion.$esVersion)))' \ + 'set Seq(jsEnv in $testSuite.v$v := new NodeJSEnvForcePolyfills(ESVersion.$esVersion), MyScalaJSPlugin.wantSourceMaps in $testSuite.v$v := ("$esVersion" != "ES5_1"))' \ 'set scalaJSStage in Global := FullOptStage' \ - ++$scala $testSuite/test \ - $testSuite/clean && - sbtretry 'set scalaJSLinkerConfig in $testSuite ~= (_.withESFeatures(_.withUseECMAScript2015(true)))' \ - 'set jsEnv in noIrCheckTest := new org.scalajs.jsenv.nodejs.NodeJSEnv(org.scalajs.jsenv.nodejs.NodeJSEnv.Config().withSourceMap(false))' \ - ++$scala noIrCheckTest/test \ - noIrCheckTest/clean && - sbtretry 'set scalaJSLinkerConfig in $testSuite ~= (_.withESFeatures(_.withUseECMAScript2015(true)))' \ - 'set jsEnv in $testSuite := new org.scalajs.jsenv.nodejs.NodeJSEnv(org.scalajs.jsenv.nodejs.NodeJSEnv.Config().withSourceMap(false))' \ - 'set scalaJSOptimizerOptions in $testSuite ~= (_.withDisableOptimizer(true))' \ - ++$scala $testSuite/test && - sbtretry 'set scalaJSLinkerConfig in $testSuite ~= (_.withESFeatures(_.withUseECMAScript2015(true)))' \ - 'set jsEnv in $testSuite := new org.scalajs.jsenv.nodejs.NodeJSEnv(org.scalajs.jsenv.nodejs.NodeJSEnv.Config().withSourceMap(false))' \ - 'set scalaJSOptimizerOptions in $testSuite ~= (_.withDisableOptimizer(true))' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withESVersion(ESVersion.$esVersion)))' \ + 'set Seq(jsEnv in $testSuite.v$v := new NodeJSEnvForcePolyfills(ESVersion.$esVersion), MyScalaJSPlugin.wantSourceMaps in $testSuite.v$v := ("$esVersion" != "ES5_1"))' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withOptimizer(false))' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withESVersion(ESVersion.$esVersion)))' \ + 'set Seq(jsEnv in $testSuite.v$v := new NodeJSEnvForcePolyfills(ESVersion.$esVersion), MyScalaJSPlugin.wantSourceMaps in $testSuite.v$v := ("$esVersion" != "ES5_1"))' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= makeCompliant' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withESVersion(ESVersion.$esVersion)))' \ + 'set Seq(jsEnv in $testSuite.v$v := new NodeJSEnvForcePolyfills(ESVersion.$esVersion), MyScalaJSPlugin.wantSourceMaps in $testSuite.v$v := ("$esVersion" != "ES5_1"))' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= makeCompliant' \ + 'set scalaJSStage in Global := FullOptStage' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withESVersion(ESVersion.$esVersion)))' \ + 'set Seq(jsEnv in $testSuite.v$v := new NodeJSEnvForcePolyfills(ESVersion.$esVersion), MyScalaJSPlugin.wantSourceMaps in $testSuite.v$v := ("$esVersion" != "ES5_1"))' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= makeCompliant' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withOptimizer(false))' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withESVersion(ESVersion.$esVersion)))' \ + 'set Seq(jsEnv in $testSuite.v$v := new NodeJSEnvForcePolyfills(ESVersion.$esVersion), MyScalaJSPlugin.wantSourceMaps in $testSuite.v$v := ("$esVersion" != "ES5_1"))' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= { _.withSemantics(_.withStrictFloats(false)) }' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withESVersion(ESVersion.$esVersion)))' \ + 'set Seq(jsEnv in $testSuite.v$v := new NodeJSEnvForcePolyfills(ESVersion.$esVersion), MyScalaJSPlugin.wantSourceMaps in $testSuite.v$v := ("$esVersion" != "ES5_1"))' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= { _.withSemantics(_.withStrictFloats(false)) }' \ + 'set scalaJSStage in Global := FullOptStage' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withESVersion(ESVersion.$esVersion)))' \ + 'set Seq(jsEnv in $testSuite.v$v := new NodeJSEnvForcePolyfills(ESVersion.$esVersion), MyScalaJSPlugin.wantSourceMaps in $testSuite.v$v := ("$esVersion" != "ES5_1"))' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= { _.withSemantics(_.withStrictFloats(false)) }' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withOptimizer(false))' \ + ++$scala $testSuite$v/test + ''', + + "test-suite-custom-esversion": ''' + setJavaVersion $java + npm install && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withESVersion(ESVersion.$esVersion)))' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withESVersion(ESVersion.$esVersion)))' \ 'set scalaJSStage in Global := FullOptStage' \ - ++$scala $testSuite/test \ - $testSuite/clean && - sbtretry 'set scalaJSLinkerConfig in $testSuite ~= (_.withESFeatures(_.withUseECMAScript2015(true)))' \ - 'set jsEnv in $testSuite := new org.scalajs.jsenv.nodejs.NodeJSEnv(org.scalajs.jsenv.nodejs.NodeJSEnv.Config().withSourceMap(false))' \ - 'set scalaJSSemantics in $testSuite ~= makeCompliant' \ - ++$scala $testSuite/test && - sbtretry 'set scalaJSLinkerConfig in $testSuite ~= (_.withESFeatures(_.withUseECMAScript2015(true)))' \ - 'set jsEnv in $testSuite := new org.scalajs.jsenv.nodejs.NodeJSEnv(org.scalajs.jsenv.nodejs.NodeJSEnv.Config().withSourceMap(false))' \ - 'set scalaJSSemantics in $testSuite ~= makeCompliant' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withESVersion(ESVersion.$esVersion)))' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withOptimizer(false))' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withESVersion(ESVersion.$esVersion)))' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withOptimizer(false))' \ 'set scalaJSStage in Global := FullOptStage' \ - ++$scala $testSuite/test \ - $testSuite/clean && - sbtretry 'set scalaJSLinkerConfig in $testSuite ~= (_.withESFeatures(_.withUseECMAScript2015(true)))' \ - 'set jsEnv in $testSuite := new org.scalajs.jsenv.nodejs.NodeJSEnv(org.scalajs.jsenv.nodejs.NodeJSEnv.Config().withSourceMap(false))' \ - 'set scalaJSSemantics in $testSuite ~= makeCompliant' \ - 'set scalaJSOptimizerOptions in $testSuite ~= (_.withDisableOptimizer(true))' \ - ++$scala $testSuite/test \ - $testSuite/clean && - sbtretry 'set scalaJSLinkerConfig in $testSuite ~= (_.withESFeatures(_.withUseECMAScript2015(true)))' \ - 'set jsEnv in $testSuite := new org.scalajs.jsenv.nodejs.NodeJSEnv(org.scalajs.jsenv.nodejs.NodeJSEnv.Config().withSourceMap(false))' \ - 'set scalaJSModuleKind in $testSuite := ModuleKind.CommonJSModule' \ - ++$scala $testSuite/test && - sbtretry 'set scalaJSLinkerConfig in $testSuite ~= (_.withESFeatures(_.withUseECMAScript2015(true)))' \ - 'set jsEnv in $testSuite := new org.scalajs.jsenv.nodejs.NodeJSEnv(org.scalajs.jsenv.nodejs.NodeJSEnv.Config().withSourceMap(false))' \ - 'set scalaJSModuleKind in $testSuite := ModuleKind.CommonJSModule' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withESVersion(ESVersion.$esVersion)))' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= makeCompliant' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withESVersion(ESVersion.$esVersion)))' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= makeCompliant' \ 'set scalaJSStage in Global := FullOptStage' \ - ++$scala $testSuite/test \ - $testSuite/clean && - sbtretry 'set scalaJSLinkerConfig in $testSuite ~= (_.withESFeatures(_.withUseECMAScript2015(true)))' \ - 'set artifactPath in ($testSuite, Test, fastOptJS) := (crossTarget in $testSuite).value / "testsuite-fastopt.mjs"' \ - 'set jsEnv in $testSuite := new org.scalajs.jsenv.nodejs.NodeJSEnv(org.scalajs.jsenv.nodejs.NodeJSEnv.Config().withArgs(List("--experimental-modules")).withSourceMap(false))' \ - 'set scalaJSModuleKind in $testSuite := ModuleKind.ESModule' \ - ++$scala $testSuite/test && - sbtretry 'set scalaJSLinkerConfig in $testSuite ~= (_.withESFeatures(_.withUseECMAScript2015(true)))' \ - 'set artifactPath in ($testSuite, Test, fullOptJS) := (crossTarget in $testSuite).value / "testsuite-opt.mjs"' \ - 'set jsEnv in $testSuite := new org.scalajs.jsenv.nodejs.NodeJSEnv(org.scalajs.jsenv.nodejs.NodeJSEnv.Config().withArgs(List("--experimental-modules")).withSourceMap(false))' \ - 'set scalaJSModuleKind in $testSuite := ModuleKind.ESModule' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withESVersion(ESVersion.$esVersion)))' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= makeCompliant' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withOptimizer(false))' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withESVersion(ESVersion.$esVersion)))' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= { _.withSemantics(_.withStrictFloats(false)) }' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withESVersion(ESVersion.$esVersion)))' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= { _.withSemantics(_.withStrictFloats(false)) }' \ 'set scalaJSStage in Global := FullOptStage' \ - ++$scala $testSuite/test + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withESVersion(ESVersion.$esVersion)))' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= { _.withSemantics(_.withStrictFloats(false)) }' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withOptimizer(false))' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withESVersion(ESVersion.$esVersion).withAllowBigIntsForLongs(true)))' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withESVersion(ESVersion.$esVersion).withAllowBigIntsForLongs(true)).withOptimizer(false))' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withESVersion(ESVersion.$esVersion)))' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withModuleKind(ModuleKind.CommonJSModule))' \ + ++$scala $testSuite$v/test && + sbtretry \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withESVersion(ESVersion.$esVersion)))' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withModuleSplitStyle(ModuleSplitStyle.SmallestModules))' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withModuleKind(ModuleKind.CommonJSModule))' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withESVersion(ESVersion.$esVersion)))' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withModuleKind(ModuleKind.CommonJSModule))' \ + 'set scalaJSStage in Global := FullOptStage' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withESVersion(ESVersion.$esVersion)))' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withModuleKind(ModuleKind.ESModule))' \ + ++$scala $testSuite$v/test && + sbtretry \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withESVersion(ESVersion.$esVersion)))' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withModuleSplitStyle(ModuleSplitStyle.SmallestModules))' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withModuleKind(ModuleKind.ESModule))' \ + ++$scala $testSuite$v/test && + sbtretry 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withESFeatures(_.withESVersion(ESVersion.$esVersion)))' \ + 'set scalaJSLinkerConfig in $testSuite.v$v ~= (_.withModuleKind(ModuleKind.ESModule))' \ + 'set scalaJSStage in Global := FullOptStage' \ + ++$scala $testSuite$v/test ''', + /* For the bootstrap tests to be able to call + * `testSuite/test:fastOptJS`, `scalaJSStage in testSuite` must be + * `FastOptStage`, even when `scalaJSStage in Global` is `FullOptStage`. + */ "bootstrap": ''' setJavaVersion $java npm install && - sbt ++$scala irJS/test toolsJS/test && - sbt 'set scalaJSStage in Global := FullOptStage' \ - ++$scala irJS/test && - sbt ++$scala testSuite/test:fullOptJS && - sbt 'set scalaJSStage in Global := FullOptStage' \ - ++$scala toolsJS/test + sbtnoretry ++$scala linker$v/test && + sbtnoretry linkerPrivateLibrary/test && + sbtnoretry ++$scala irJS$v/test linkerJS$v/test linkerInterfaceJS$v/test && + sbtnoretry 'set scalaJSStage in Global := FullOptStage' \ + 'set scalaJSStage in testSuite.v$v := FastOptStage' \ + ++$scala irJS$v/test linkerJS$v/test linkerInterfaceJS$v/test && + sbtnoretry ++$scala testSuite$v/bootstrap:test && + sbtnoretry 'set scalaJSStage in Global := FullOptStage' \ + 'set scalaJSStage in testSuite.v$v := FastOptStage' \ + ++$scala testSuite$v/bootstrap:test && + sbtnoretry ++$scala irJS$v/mimaReportBinaryIssues \ + linkerInterfaceJS$v/mimaReportBinaryIssues linkerJS$v/mimaReportBinaryIssues ''', - "tools-cli-stubs": ''' + "tools": ''' setJavaVersion $java npm install && - sbt ++$scala tools/package ir/test tools/test cli/package cli/assembly \ - stubs/package jsEnvsTestSuite/test testAdapter/test \ - ir/mimaReportBinaryIssues tools/mimaReportBinaryIssues \ - jsEnvs/mimaReportBinaryIssues jsEnvsTestKit/mimaReportBinaryIssues \ - testAdapter/mimaReportBinaryIssues \ - stubs/mimaReportBinaryIssues cli/mimaReportBinaryIssues \ - irJS/mimaReportBinaryIssues toolsJS/mimaReportBinaryIssues && - sbt ++$scala ir/compile:doc tools/compile:doc jsEnvs/compile:doc \ - jsEnvsTestKit/compile:doc testAdapter/compile:doc stubs/compile:doc + sbtnoretry ++$scala ir$v/test linkerInterface$v/test \ + linker$v/compile testAdapter$v/test \ + ir$v/mimaReportBinaryIssues \ + linkerInterface$v/mimaReportBinaryIssues linker$v/mimaReportBinaryIssues \ + testAdapter$v/mimaReportBinaryIssues && + sbtnoretry ++$scala ir$v/compile:doc \ + linkerInterface$v/compile:doc linker$v/compile:doc \ + testAdapter$v/compile:doc ''', - "tools-cli-stubs-sbtplugin": ''' + "tools-sbtplugin": ''' setJavaVersion $java npm install && - sbt ++$scala tools/package ir/test tools/test cli/package cli/assembly \ - stubs/package jsEnvsTestSuite/test testAdapter/test \ + sbtnoretry ++$scala ir$v/test linkerInterface$v/compile \ + linker$v/compile testAdapter$v/test \ sbtPlugin/package \ - ir/mimaReportBinaryIssues tools/mimaReportBinaryIssues \ - jsEnvs/mimaReportBinaryIssues jsEnvsTestKit/mimaReportBinaryIssues \ - testAdapter/mimaReportBinaryIssues \ - stubs/mimaReportBinaryIssues cli/mimaReportBinaryIssues \ - sbtPlugin/mimaReportBinaryIssues \ - irJS/mimaReportBinaryIssues toolsJS/mimaReportBinaryIssues && - sbt ++$scala library/scalastyle javalanglib/scalastyle javalib/scalastyle \ - javalibEx/scalastyle ir/scalastyle compiler/scalastyle \ - compiler/test:scalastyle tools/scalastyle tools/test:scalastyle \ - jsEnvs/scalastyle jsEnvsTestKit/scalastyle \ - jsEnvsTestSuite/test:scalastyle testAdapter/scalastyle \ - sbtPlugin/scalastyle testInterface/scalastyle testBridge/scalastyle \ - testSuite/scalastyle testSuite/test:scalastyle \ - testSuiteJVM/test:scalastyle \ - javalibExTestSuite/test:scalastyle helloworld/scalastyle \ - reversi/scalastyle testingExample/scalastyle \ - testingExample/test:scalastyle \ - jUnitPlugin/scalastyle jUnitRuntime/scalastyle \ - jUnitTestOutputsJVM/scalastyle jUnitTestOutputsJVM/test:scalastyle \ - jUnitTestOutputsJS/scalastyle jUnitTestOutputsJS/test:scalastyle && - sbt ++$scala ir/compile:doc tools/compile:doc jsEnvs/compile:doc \ - jsEnvsTestKit/compile:doc testAdapter/compile:doc stubs/compile:doc \ - sbtPlugin/compile:doc + ir$v/mimaReportBinaryIssues \ + linkerInterface$v/mimaReportBinaryIssues linker$v/mimaReportBinaryIssues \ + testAdapter$v/mimaReportBinaryIssues \ + sbtPlugin/mimaReportBinaryIssues && + sbtnoretry ++$scala scalastyleCheck && + sbtnoretry ++$scala ir$v/compile:doc \ + linkerInterface$v/compile:doc linker$v/compile:doc \ + testAdapter$v/compile:doc \ + sbtPlugin/compile:doc && + sbtnoretry sbtPlugin/scripted ''', - "partestc": ''' + "partest-noopt": ''' setJavaVersion $java npm install && - sbt ++$scala partest/compile + sbtnoretry ++$scala partestSuite$v/test:compile && + sbtnoretry ++$scala "partestSuite$v/testOnly -- --showDiff" ''', - "sbtplugin-test": ''' - setJavaVersion 1.8 - SBT_VER_OVERRIDE=$sbt_version_override - # Publish Scala.js artifacts locally - # Then go into standalone project and test - npm install && - sbt ++2.11.12 compiler/publishLocal library/publishLocal javalibEx/publishLocal \ - testInterface/publishLocal testBridge/publishLocal stubs/publishLocal \ - jUnitPlugin/publishLocal jUnitRuntime/publishLocal && - sbt ++$toolsscala ${SBT_VER_OVERRIDE:+^^$SBT_VER_OVERRIDE} \ - ir/publishLocal tools/publishLocal jsEnvs/publishLocal \ - testAdapter/publishLocal sbtPlugin/publishLocal && - cd sbt-plugin-test && - setJavaVersion $java && - if [ -n "$SBT_VER_OVERRIDE" ]; then echo "sbt.version=$SBT_VER_OVERRIDE" > ./project/build.properties; fi && - sbt noDOM/run noDOM/testHtmlFastOpt noDOM/testHtmlFullOpt \ - withDOM/run withDOM/testHtmlFastOpt withDOM/testHtmlFullOpt \ - multiTestJS/test:run multiTestJS/testHtmlFastOpt multiTestJS/testHtmlFullOpt \ - jetty9/run test \ - jsDependenciesTest/packageJSDependencies \ - jsDependenciesTest/packageMinifiedJSDependencies \ - jsDependenciesTest/regressionTestForIssue2243 \ - jsNoDependenciesTest/regressionTestForIssue2243 \ - multiTestJS/test:testScalaJSSourceMapAttribute \ - 'set scalaJSUseRhino in Global := true' test - ''', - - "partest-noopt": ''' + "partest-fastopt": ''' setJavaVersion $java npm install && - sbt ++$scala package "partestSuite/testOnly -- --showDiff" + sbtnoretry ++$scala partestSuite$v/test:compile && + sbtnoretry ++$scala "partestSuite$v/testOnly -- --fastOpt --showDiff" ''', - "partest-fastopt": ''' + "partest-fullopt": ''' setJavaVersion $java npm install && - sbt ++$scala package "partestSuite/testOnly -- --fastOpt --showDiff" + sbtnoretry ++$scala partestSuite$v/test:compile && + sbtnoretry ++$scala "partestSuite$v/testOnly -- --fullOpt --showDiff" ''', - "partest-fullopt": ''' + "scala3-compat": ''' setJavaVersion $java npm install && - sbt ++$scala package "partestSuite/testOnly -- --fullOpt --showDiff" + sbtnoretry ++$scala! ir2_13/test ''' ] def mainJavaVersion = "1.8" -def otherJavaVersions = [] +def otherJavaVersions = ["11", "16"] def allJavaVersions = otherJavaVersions.clone() allJavaVersions << mainJavaVersion -def mainScalaVersion = "2.12.11" -def mainScalaVersions = ["2.10.2", "2.11.12", "2.12.11", "2.13.2"] +def mainScalaVersion = "2.12.17" +def mainScalaVersions = ["2.11.12", "2.12.17", "2.13.10"] def otherScalaVersions = [ - "2.10.3", - "2.10.4", - "2.10.5", - "2.10.6", - "2.10.7", - "2.11.0", - "2.11.1", - "2.11.2", - "2.11.4", - "2.11.5", - "2.11.6", - "2.11.7", - "2.11.8", - "2.11.11", "2.11.12", - "2.12.0", "2.12.1", "2.12.2", "2.12.3", @@ -455,34 +471,72 @@ def otherScalaVersions = [ "2.12.8", "2.12.9", "2.12.10", + "2.12.11", + "2.12.12", + "2.12.13", + "2.12.14", + "2.12.15", + "2.12.16", "2.13.0", - "2.13.1" + "2.13.1", + "2.13.2", + "2.13.3", + "2.13.4", + "2.13.5", + "2.13.6", + "2.13.7", + "2.13.8", + "2.13.9" +] + +def scala3Version = "3.2.1" + +def allESVersions = [ + "ES5_1", + "ES2015", + // "ES2016", // Technically we have the '**' operator dependent on ES2016, but it's not enough to justify testing this version + "ES2017", + "ES2018", + // "ES2019", // We do not use anything specifically from ES2019 + "ES2020", + "ES2021" // We do not use anything specifically from ES2021, but always test the latest to avoid #4675 ] +// Scala 2.11 does not support newer Java versions +def isExcludedForScala211(javaVersion) { + return javaVersion != "1.8" && javaVersion != "11" +} + +def isExcludedScalaJavaCombo(scalaVersion, javaVersion) { + return scalaVersion.startsWith("2.11.") && isExcludedForScala211(javaVersion) +} + // The 'quick' matrix def quickMatrix = [] mainScalaVersions.each { scalaVersion -> allJavaVersions.each { javaVersion -> - quickMatrix.add([task: "main", scala: scalaVersion, java: javaVersion]) - } - quickMatrix.add([task: "test-suite-ecma-script5", scala: scalaVersion, java: mainJavaVersion, testSuite: "testSuite"]) - quickMatrix.add([task: "test-suite-ecma-script6", scala: scalaVersion, java: mainJavaVersion, testSuite: "testSuite"]) - if (!scalaVersion.startsWith("2.10.")) { - quickMatrix.add([task: "test-suite-ecma-script5", scala: scalaVersion, java: mainJavaVersion, testSuite: "scalaTestSuite"]) - quickMatrix.add([task: "test-suite-ecma-script6", scala: scalaVersion, java: mainJavaVersion, testSuite: "scalaTestSuite"]) + if (!isExcludedScalaJavaCombo(scalaVersion, javaVersion)) + quickMatrix.add([task: "main", scala: scalaVersion, java: javaVersion]) } + quickMatrix.add([task: "test-suite-default-esversion", scala: scalaVersion, java: mainJavaVersion, testSuite: "testSuite"]) + quickMatrix.add([task: "test-suite-custom-esversion", scala: scalaVersion, java: mainJavaVersion, esVersion: "ES5_1", testSuite: "testSuite"]) + quickMatrix.add([task: "test-suite-default-esversion", scala: scalaVersion, java: mainJavaVersion, testSuite: "scalaTestSuite"]) + quickMatrix.add([task: "test-suite-custom-esversion", scala: scalaVersion, java: mainJavaVersion, esVersion: "ES5_1", testSuite: "scalaTestSuite"]) quickMatrix.add([task: "bootstrap", scala: scalaVersion, java: mainJavaVersion]) - if (!scalaVersion.startsWith("2.10.")) { - quickMatrix.add([task: "partest-fastopt", scala: scalaVersion, java: mainJavaVersion]) - } + quickMatrix.add([task: "partest-fastopt", scala: scalaVersion, java: mainJavaVersion]) +} +allESVersions.each { esVersion -> + quickMatrix.add([task: "test-suite-custom-esversion-force-polyfills", scala: mainScalaVersion, java: mainJavaVersion, esVersion: esVersion, testSuite: "testSuite"]) } allJavaVersions.each { javaVersion -> - quickMatrix.add([task: "tools-cli-stubs-sbtplugin", scala: "2.12.11", sbt_version_override: "", java: javaVersion]) + if (!isExcludedForScala211(javaVersion)) { + // the sbt plugin tests want to compile everything for 2.11, 2.12 and 2.13 + quickMatrix.add([task: "tools-sbtplugin", scala: "2.12.17", java: javaVersion]) + quickMatrix.add([task: "tools", scala: "2.11.12", java: javaVersion]) + } + quickMatrix.add([task: "tools", scala: "2.13.10", java: javaVersion]) } -quickMatrix.add([task: "tools-cli-stubs", scala: "2.10.7", sbt_version_override: "0.13.17", java: mainJavaVersion]) -quickMatrix.add([task: "partestc", scala: "2.11.0", java: mainJavaVersion]) -quickMatrix.add([task: "sbtplugin-test", toolsscala: "2.10.7", sbt_version_override: "0.13.17", java: mainJavaVersion]) -quickMatrix.add([task: "sbtplugin-test", toolsscala: "2.12.11", sbt_version_override: "", java: mainJavaVersion]) +quickMatrix.add([task: "scala3-compat", scala: scala3Version, java: mainJavaVersion]) // The 'full' matrix def fullMatrix = quickMatrix.clone() @@ -491,20 +545,14 @@ otherScalaVersions.each { scalaVersion -> } mainScalaVersions.each { scalaVersion -> otherJavaVersions.each { javaVersion -> - quickMatrix.add([task: "test-suite-ecma-script5", scala: scalaVersion, java: javaVersion, testSuite: "testSuite"]) - quickMatrix.add([task: "test-suite-ecma-script6", scala: scalaVersion, java: javaVersion, testSuite: "testSuite"]) - } - if (!scalaVersion.startsWith("2.10.")) { - def javaVersion = scalaVersion.startsWith("2.11.") ? "1.7" : mainJavaVersion - fullMatrix.add([task: "partest-noopt", scala: scalaVersion, java: mainJavaVersion]) - fullMatrix.add([task: "partest-fullopt", scala: scalaVersion, java: mainJavaVersion]) + if (!isExcludedScalaJavaCombo(scalaVersion, javaVersion)) + quickMatrix.add([task: "test-suite-default-esversion", scala: scalaVersion, java: javaVersion, testSuite: "testSuite"]) } + fullMatrix.add([task: "partest-noopt", scala: scalaVersion, java: mainJavaVersion]) + fullMatrix.add([task: "partest-fullopt", scala: scalaVersion, java: mainJavaVersion]) } -otherScalaVersions.each { scalaVersion -> - // Partest does not compile on Scala 2.11.4 (see #1215). - if (!scalaVersion.startsWith("2.10.") && scalaVersion != "2.11.4") { - fullMatrix.add([task: "partest-fastopt", scala: scalaVersion, java: mainJavaVersion]) - } +otherJavaVersions.each { javaVersion -> + fullMatrix.add([task: "scala3-compat", scala: scala3Version, java: javaVersion]) } def Matrices = [ @@ -533,15 +581,18 @@ matrix.each { taskDef -> } } + def suffix = taskDef.scala.split('\\.')[0..1].join('_') + taskStr = taskStr.replace('$v', suffix) + def ciScript = CIScriptPrelude + taskStr buildDefs.put(fullTaskName, { node('linuxworker') { checkout scm - sh "git clean -fdx && rm -rf partest/fetchedSources/" - writeFile file: 'ciscript.sh', text: ciScript, encoding: 'UTF-8' retry(2) { - timeout(time: 3, unit: 'HOURS') { + sh "git clean -fdx && rm -rf partest/fetchedSources/" + writeFile file: 'ciscript.sh', text: ciScript, encoding: 'UTF-8' + timeout(time: 4, unit: 'HOURS') { sh "echo '$fullTaskName' && cat ciscript.sh && sh ciscript.sh" } } diff --git a/README.md b/README.md index 261cf301b7..add1859b89 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,14 @@ +

+ + +

Scala.js

+ +

+ +Chat: [#scala-js](https://discord.com/invite/scala) on Discord. + This is the repository for -[Scala.js, the Scala to JavaScript compiler](http://www.scala-js.org/). +[Scala.js, the Scala to JavaScript compiler](https://www.scala-js.org/). * [Report an issue](https://github.com/scala-js/scala-js/issues) * [Developer documentation](./DEVELOPING.md) diff --git a/RELEASING.md b/RELEASING.md index f201eef736..60965a93fa 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -7,36 +7,35 @@ 1. Create a "Version x.y.z." commit ([example][2]) and push it to a branch on your fork. 1. Ping people on the commit for review. - 1. Once you have LGTM, push to master (do *not* create a merge commit). + 1. Once you have LGTM, push to `main` (do *not* create a merge commit). 1. Testing (post results as comments to commit): - - Nightly - - Weekly + - Full build - [Manual testing][3] 1. If all tests pass, tag the commit with the release version. 1. Perform [manual testing][3] that needs the tagging (source maps). 1. Publish: - - Sonatype, bintray (`./script/publish.sh`) - - CLI to website (simple `scp`) + - Sonatype (`./script/publish.sh`) - Docs to website: Use `~/fetchapis.sh ` on the webserver once artifacts are on maven central. 1. Once artifacts are on maven central, create a "Towards x.y.z." commit - ([example][4]). - 1. Create a "DO NOT MERGE" PR for CI and review. + ([example][5]). + 1. Create an "FF ONLY" PR for CI and review. 1. Once you have LGTM, push the commit (do *not* click the merge button) - 1. Remove the "DO NOT MERGE" from the PR title (since it will now show as - merged). -1. Prepare release announcement, taking the last one as model ([example][5]). +1. Prepare release announcement, taking the last one as model ([example][6]). 1. When merging the release announcement PR (after proper review): - Update the latest/ URLs (use `~/setlatestapi.sh ` on webserver) - Announce on Twitter using the @scala_js account - Announce on [Gitter](https://gitter.im/scala-js/scala-js) - - Announce on the mailing list (scala-js@googlegroups.com) - - Cross-post to scala-announce (scala-announce@googlegroups.com) + - Cross-post as an Announcement in Scala Users ([example][7]) + - Send a PR to Scala Steward to "unleash" the release by updating + [these lines][8] with the next possible version numbers [1]: https://github.com/scala-js/scala-js/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aclosed%20no%3Amilestone%20-label%3Ainvalid%20-label%3Aduplicate%20-label%3Aas-designed%20-label%3Aquestion%20-label%3Awontfix%20-label%3A%22can%27t%20reproduce%22%20-label%3A%22separate%20repo%22 -[2]: https://github.com/scala-js/scala-js/commit/a09e8cdd92b962e90c83ec124b9764970a4889ff -[3]: https://github.com/scala-js/scala-js/blob/master/TESTING -[4]: https://github.com/scala-js/scala-js/commit/c51f8b65d3eca45de84397f7167058c91d6b6aa1 -[5]: https://github.com/scala-js/scala-js-website/commit/8dc9e9d3ee63ec47e6eb154fa7bd5a2ae8d1d42d +[2]: https://github.com/scala-js/scala-js/commit/c3520bb9dae46757a975cccd428a77b8d6e6a75e +[3]: https://github.com/scala-js/scala-js/blob/main/TESTING.md +[5]: https://github.com/scala-js/scala-js/commit/c6c82e80f56bd2008ff8273088bbbbbbbc30f777 +[6]: https://github.com/scala-js/scala-js-website/commit/057f743c3fb8abe6077fb4debeeec45cd5c53d5d +[7]: https://users.scala-lang.org/t/announcing-scala-js-1-4-0/7013 +[8]: https://github.com/scala-steward-org/scala-steward/blob/30f3217ce11bbb0208d70070e7d5f49a3b1a25f0/modules/core/src/main/resources/default.scala-steward.conf#L19-L73 diff --git a/TESTING b/TESTING deleted file mode 100644 index 0c53b9b091..0000000000 --- a/TESTING +++ /dev/null @@ -1,70 +0,0 @@ -This file contains test cases that should be manually executed. - -## CLI Distribution - -For each major Scala version on a *NIX distro and a Windows distro: - -1. Download packaged Scala from scala-lang.org -2. Build Scala.js CLI distribution (e.g. `./assemble-cli.sh 2.10`) -3. Unpack Scala and Scala.js distro -4. Add `bin/` directories of both distributions to path (`export PATH=$PATH:/bin:/bin`) -5. Create a temporary directory and do: - - mkdir bin - echo ' - object Foo { - def main(): Unit = { - println(s"asdf ${1 + 1}") - new A - } - - class A - } - ' > foo.scala - scalajsc -d bin foo.scala - - scalajsp bin/Foo$.sjsir - # Verify output - scalajsp bin/Foo\$A.sjsir - # Verify output - - scalajsld -o test.js -mm Foo.main bin - # Verify output - - node test.js # Or your favorite thing to run JS - - # Expect "asdf 2" - -## HTML-Runners - -The following HTML-runners must be manually tested: - - examples/helloworld/helloworld-{2.10|2.11}{|-fastopt}.html - examples/reversi/reversi-{2.10|2.11}{|-fastopt}.html - -The following sbt-plugin generated test runners must be manually tested (in both -2.10 and 2.11): - - testingExample/testHtml{Fast,Full}Opt - testSuite/testHtml{Fast,Full}Opt - -## Sourcemaps - -To test source maps, do the following on: - - examples/reversi/reversi-{2.10|2.11}{|-fastopt}.html - -1. Open the respective file in Google Chrome -2. Set a break-point in the HTML launcher on the `new Reversi` statement -3. Step over calls to jQuery into constructor -4. Step into the call to `Array.tabulate` and verify that source maps - to Scala standard library sources work (should point to GitHub) -5. Single step through constructor, until you reach `buildUI()` -6. Step into `buildUI()` - - -## When releasing only - -Once all tests pass, tag the revision and verify that source maps to -Scala.js sources work correctly (should point to GitHub), following -the steps described in the section Sourcemaps. diff --git a/TESTING.md b/TESTING.md new file mode 100644 index 0000000000..f013e257f5 --- /dev/null +++ b/TESTING.md @@ -0,0 +1,47 @@ +This file contains test cases that should be manually executed. + +## HTML-Runners + +The following HTML-runners must be manually tested: + + examples/helloworld/helloworld-{2.11|2.12}{|-fastopt}.html + examples/reversi/reversi-{2.11|2.12}{|-fastopt}.html + +## HTML-Test Runner with Modules + +Still manual, because jsdom does not support modules yet +[jsdom/jsdom#2475](https://github.com/jsdom/jsdom/issues/2475). + +``` +$ sbt +> set scalaJSLinkerConfig in testingExample.v2_12 ~= (_.withModuleSplitStyle(ModuleSplitStyle.SmallestModules).withModuleKind(ModuleKind.ESModule)) +> testingExample2_12/testHtml +> set scalaJSLinkerConfig in testSuite.v2_12 ~= (_.withModuleKind(ModuleKind.ESModule)) +> testSuite2_12/testHtml +> exit +$ python3 -m http.server + +// Open http://localhost:8000/examples/testing/.2.12/target/scala-2.12/testing-fastopt-test-html/index.html +// Open http://localhost:8000/test-suite/js/.2.12/target/scala-2.12/scalajs-test-suite-fastopt-test-html/index.html +``` + +## Sourcemaps + +To test source maps, do the following on: + + examples/reversi/reversi-{2.11|2.12}{|-fastopt}.html + +1. Open the respective file in Google Chrome +2. Set a break-point in the HTML launcher on the `new Reversi` statement +3. Step over calls to jQuery into constructor +4. Step into the call to `Array.tabulate` and verify that source maps + to Scala standard library sources work (should point to GitHub) +5. Single step through constructor, until you reach `buildUI()` +6. Step into `buildUI()` + + +## When releasing only + +Once all tests pass, tag the revision and verify that source maps to +Scala.js sources work correctly (should point to GitHub), following +the steps described in the section Sourcemaps. diff --git a/VERSIONING.md b/VERSIONING.md new file mode 100644 index 0000000000..941d33977f --- /dev/null +++ b/VERSIONING.md @@ -0,0 +1,61 @@ +# Versioning + +This page describes how we version Scala.js core. Notably what compatibility +guarantees we give with respect to the version numbering. + +# Major Changes + +The following changes must cause a major version bump. + +* Backward incompatible change in the IR +* Backward binary incompatible change in the standard library +* Backward incompatible change in the contract for calling JDK APIs + +# Severe Changes + +Severe changes can break the ecosystem of sbt plugins and other build tools, but +not the ecosystem of libraries (which would be major). Severe changes should be +done only if absolutely necessary. The following are considered severe changes: + +* Backward binary incompatible changes in `linker.*` or `linker.interface.*` +* Backward binary incompatible changes in `sbtplugin.*` +* Backward binary incompatible changes in `testadapter.*` + +Severe changes are difficult from a versioning point of view, since they require +a careful tradeoff: + +* if a major bump is made, it forces libraries to re-publish unnecessarily + (because the IR is not actually affected). +* if no major bump is made, the tooling API versioning breaks the SemVer + contract. + +As such, we leave the best course of action in case of severe changes to the +maintainers. Possible courses of action are: + +* Major version bump +* Minor version bump +* Separating versioning of IR and tooling. + +# Minor Changes + +The following changes must cause a minor version bump. + +* Forward incompatible change in the IR +* Backward source incompatible change at the language level or at the standard + library level (including any addition of public API in the stdlib) +* Backward source incompatible change in `linker.*`, `linker.interface.*` + or `sbtplugin.*` (including any addition of public API) +* Backward source incompatible changes in `testadapter.*` +* Backward binary incompatible changes in `ir.*`, `linker.interface.unstable.*` + or `linker.standard.*` + +# Patch Changes + +All other changes cause a patch version bump only. Explicitly (but not +exhaustively): + +* Backward source incompatible change in `ir.*`, `linker.interface.unstable.*` + or `linker.standard.*` +* Backward source/binary incompatible changes elsewhere in `linker.**` +* Fixes or additions in the JDK libs (since they are always backward source and + binary compatible) diff --git a/appveyor.yml b/appveyor.yml new file mode 100644 index 0000000000..efdcf8ee5b --- /dev/null +++ b/appveyor.yml @@ -0,0 +1,21 @@ +version: '{build}' +image: Visual Studio 2015 +environment: + global: + NODEJS_VERSION: "16" + JAVA_HOME: C:\Program Files\Java\jdk1.8.0 +install: + - ps: Install-Product node $env:NODEJS_VERSION + - npm install + - cmd: choco install sbt --version 1.3.12 -ia "INSTALLDIR=""C:\sbt""" + - cmd: SET PATH=C:\sbt\bin;%JAVA_HOME%\bin;%PATH% + - cmd: SET "SBT_OPTS=-Xmx4g -Xms4m" +build: off +test_script: + # Very far from testing everything, but at least it is a good sanity check + # For slow things (partest and scripted), we execute only one test + - cmd: sbt ";clean;testSuite2_12/test;linker2_12/test;partestSuite2_12/testOnly -- --fastOpt run/option-fold.scala" +cache: + - C:\sbt + - C:\Users\appveyor\.ivy2\cache + - C:\Users\appveyor\.sbt diff --git a/assets/additional-doc-styles.css b/assets/additional-doc-styles.css index 89b994cb80..c0d38e0efb 100644 --- a/assets/additional-doc-styles.css +++ b/assets/additional-doc-styles.css @@ -1,36 +1,7 @@ -.badge-ecma6 { - background-color: #E68A00; -} - -.badge-ecma2015 { - background-color: #E68A00; -} - -.badge-ecma2017 { - background-color: #E68A00; -} - -.badge-ecma2019 { - background-color: #E68A00; -} - -.badge-ecma2020 { +.badge-ecma6, .badge-ecma2015, .badge-ecma2016, .badge-ecma2017, .badge-ecma2018, .badge-ecma2019, .badge-ecma2020, .badge-ecma2021 { background-color: #E68A00; } .badge-non-std { background-color: #B94A48; } - -.badge-external { - background-color: #710071; -} - -a.badge-external { - color: #FFFFFF; - text-decoration: none; -} - -a[href].badge-external:hover { - text-decoration: underline; -} diff --git a/build.sbt b/build.sbt index 9e3f949255..e3374e3358 100644 --- a/build.sbt +++ b/build.sbt @@ -4,35 +4,36 @@ val scalajs = Build.root val ir = Build.irProject val irJS = Build.irProjectJS val compiler = Build.compiler -val tools = Build.tools -val toolsJS = Build.toolsJS -val jsEnvs = Build.jsEnvs -val jsEnvsTestKit = Build.jsEnvsTestKit -val jsEnvsTestSuite = Build.jsEnvsTestSuite +val linkerInterface = Build.linkerInterface +val linkerInterfaceJS = Build.linkerInterfaceJS +val linkerPrivateLibrary = Build.linkerPrivateLibrary +val linker = Build.linker +val linkerJS = Build.linkerJS val testAdapter = Build.testAdapter val sbtPlugin = Build.plugin -val javalanglib = Build.javalanglib +val javalibintf = Build.javalibintf +val javalibInternal = Build.javalibInternal val javalib = Build.javalib val scalalib = Build.scalalib val libraryAux = Build.libraryAux val library = Build.library -val javalibEx = Build.javalibEx -val stubs = Build.stubs -val cli = Build.cli val testInterface = Build.testInterface val testBridge = Build.testBridge val jUnitRuntime = Build.jUnitRuntime val jUnitTestOutputsJS = Build.jUnitTestOutputsJS val jUnitTestOutputsJVM = Build.jUnitTestOutputsJVM val jUnitPlugin = Build.jUnitPlugin -val examples = Build.examples +val jUnitAsyncJS = Build.jUnitAsyncJS +val jUnitAsyncJVM = Build.jUnitAsyncJVM val helloworld = Build.helloworld val reversi = Build.reversi val testingExample = Build.testingExample val testSuite = Build.testSuite val testSuiteJVM = Build.testSuiteJVM -val noIrCheckTest = Build.noIrCheckTest -val javalibExTestSuite = Build.javalibExTestSuite +val javalibExtDummies = Build.javalibExtDummies +val testSuiteEx = Build.testSuiteEx +val testSuiteExJVM = Build.testSuiteExJVM +val testSuiteLinker = Build.testSuiteLinker val partest = Build.partest val partestSuite = Build.partestSuite val scalaTestSuite = Build.scalaTestSuite diff --git a/ci/check-cla.sh b/ci/check-cla.sh index 5488b73cc9..05fc9ad6b0 100755 --- a/ci/check-cla.sh +++ b/ci/check-cla.sh @@ -1,9 +1,10 @@ #!/usr/bin/env bash set -eux -AUTHOR=$GITHUB_ACTOR +AUTHOR="$1" echo "Pull request submitted by $AUTHOR"; -signed=$(curl -s https://www.lightbend.com/contribute/cla/scala/check/$AUTHOR | jq -r ".signed"); +URL_AUTHOR=$(jq -rn --arg x "$AUTHOR" '$x|@uri') +signed=$(curl -s "https://www.lightbend.com/contribute/cla/scala/check/$URL_AUTHOR" | jq -r ".signed"); if [ "$signed" = "true" ] ; then echo "CLA check for $AUTHOR successful"; else diff --git a/ci/check-partest-coverage.sh b/ci/check-partest-coverage.sh deleted file mode 100755 index ca35f3711f..0000000000 --- a/ci/check-partest-coverage.sh +++ /dev/null @@ -1,58 +0,0 @@ -#! /bin/sh - -# This script tests if all Scala partests are classified. Since -# Scala.js does not provide all the Scala functionality (see [1]), we -# have to exclude some partests from testing. Therefore, every partest -# in $TESTDIR has to be in exactly one of the following files located -# in $KNOWDIR: -# - WhitelistedTests.txt: Tests that succeed -# - BlacklistedTests.txt: Tests that fail since they test for behavior -# which is not supported in Scala.js -# - BuglistedTests.txt: Tests that fail due to a bug in Scala.js -# -# [1] http://www.scala-js.org/doc/semantics.html - -# Arguments -if [ $# -le 0 ]; then - echo "Please give full scala version as argument" >&2 - exit 42 -fi - -FULLVER="$1" - -# Config -BASEDIR="`dirname $0`/.." -TESTDIR="$BASEDIR/partest/fetchedSources/$1/test/files" -KNOWDIR="$BASEDIR/partest-suite/src/test/resources/scala/tools/partest/scalajs/$1/" - -# If the classification directory does not exist, this means (by -# definition) that we do not want to or cannot partest this scala -# version. Therefore, everything is OK. -if [ ! -d $KNOWDIR ]; then - exit 0 -fi - -# Temp files -TMP_PREF=`basename $0` -TMP_HAVE_FILE=`mktemp /tmp/${TMP_PREF}_have_XXXXX` || exit 2 -TMP_KNOW_FILE=`mktemp /tmp/${TMP_PREF}_know_XXXXX` || exit 2 - -# Trap removal of tmp files on exit -trap "rm \"$TMP_HAVE_FILE\" \"$TMP_KNOW_FILE\"" EXIT - -# Find all partests -( # Subshell to protect cwd -cd "$TESTDIR" -find "run" "neg" "pos" \ - -mindepth 1 -maxdepth 1 \( -type d -or -name '*.scala' \) \ - | sort >> $TMP_HAVE_FILE -) - -# Find classified partests -( # Subshell to protect cwd -cd "$KNOWDIR" -cat BlacklistedTests.txt BuglistedTests.txt WhitelistedTests.txt \ - | grep -E -v '^#|^\s*$' | sort >> $TMP_KNOW_FILE -) - -diff -U 0 --label 'Classified Tests' $TMP_KNOW_FILE --label 'Existing Tests' $TMP_HAVE_FILE diff --git a/ci/checksizes.sh b/ci/checksizes.sh deleted file mode 100755 index 5a27dd25cc..0000000000 --- a/ci/checksizes.sh +++ /dev/null @@ -1,74 +0,0 @@ -#!/bin/sh - -BASEDIR="`dirname $0`/.." - -FULLVER="$1" - -case $FULLVER in - 2.10.2) - VER=2.10 - ;; - 2.11.12) - VER=2.11 - ;; - 2.12.11) - VER=2.12 - ;; - 2.13.2) - VER=2.13 - ;; - 2.10.3|2.10.4|2.10.5|2.10.6|2.10.7|2.11.0|2.11.1|2.11.2|2.11.4|2.11.5|2.11.6|2.11.7|2.11.8|2.11.11|2.12.0|2.12.1|2.12.2|2.12.3|2.12.4|2.12.5|2.12.6|2.12.7|2.12.8|2.12.9|2.12.10|2.13.0|2.13.1) - echo "Ignoring checksizes for Scala $FULLVER" - exit 0 - ;; -esac - -REVERSI_PREOPT="$BASEDIR/examples/reversi/target/scala-$VER/reversi-fastopt.js" -REVERSI_OPT="$BASEDIR/examples/reversi/target/scala-$VER/reversi-opt.js" - -REVERSI_PREOPT_SIZE=$(stat '-c%s' "$REVERSI_PREOPT") -REVERSI_OPT_SIZE=$(stat '-c%s' "$REVERSI_OPT") - -gzip -c "$REVERSI_PREOPT" > "$REVERSI_PREOPT.gz" -gzip -c "$REVERSI_OPT" > "$REVERSI_OPT.gz" - -REVERSI_PREOPT_GZ_SIZE=$(stat '-c%s' "$REVERSI_PREOPT.gz") -REVERSI_OPT_GZ_SIZE=$(stat '-c%s' "$REVERSI_OPT.gz") - -case $FULLVER in - 2.10.2) - REVERSI_PREOPT_EXPECTEDSIZE=529000 - REVERSI_OPT_EXPECTEDSIZE=120000 - REVERSI_PREOPT_GZ_EXPECTEDSIZE=71000 - REVERSI_OPT_GZ_EXPECTEDSIZE=31000 - ;; - 2.11.12) - REVERSI_PREOPT_EXPECTEDSIZE=526000 - REVERSI_OPT_EXPECTEDSIZE=121000 - REVERSI_PREOPT_GZ_EXPECTEDSIZE=71000 - REVERSI_OPT_GZ_EXPECTEDSIZE=31000 - ;; - 2.12.11) - REVERSI_PREOPT_EXPECTEDSIZE=715000 - REVERSI_OPT_EXPECTEDSIZE=164000 - REVERSI_PREOPT_GZ_EXPECTEDSIZE=88000 - REVERSI_OPT_GZ_EXPECTEDSIZE=38000 - ;; - 2.13.2) - REVERSI_PREOPT_EXPECTEDSIZE=794000 - REVERSI_OPT_EXPECTEDSIZE=190000 - REVERSI_PREOPT_GZ_EXPECTEDSIZE=107000 - REVERSI_OPT_GZ_EXPECTEDSIZE=48000 - ;; -esac - -echo "Checksizes: Scala version: $FULLVER" -echo "Reversi preopt size = $REVERSI_PREOPT_SIZE (expected $REVERSI_PREOPT_EXPECTEDSIZE)" -echo "Reversi opt size = $REVERSI_OPT_SIZE (expected $REVERSI_OPT_EXPECTEDSIZE)" -echo "Reversi preopt gzip size = $REVERSI_PREOPT_GZ_SIZE (expected $REVERSI_PREOPT_GZ_EXPECTEDSIZE)" -echo "Reversi opt gzip size = $REVERSI_OPT_GZ_SIZE (expected $REVERSI_OPT_GZ_EXPECTEDSIZE)" - -[ "$REVERSI_PREOPT_SIZE" -le "$REVERSI_PREOPT_EXPECTEDSIZE" ] && \ - [ "$REVERSI_OPT_SIZE" -le "$REVERSI_OPT_EXPECTEDSIZE" ] && \ - [ "$REVERSI_PREOPT_GZ_SIZE" -le "$REVERSI_PREOPT_GZ_EXPECTEDSIZE" ] && \ - [ "$REVERSI_OPT_GZ_SIZE" -le "$REVERSI_OPT_GZ_EXPECTEDSIZE" ] diff --git a/cli/src/main/resources/scalajsc b/cli/src/main/resources/scalajsc deleted file mode 100755 index c9dbe3efd0..0000000000 --- a/cli/src/main/resources/scalajsc +++ /dev/null @@ -1,16 +0,0 @@ -#! /bin/sh - -SCALA_BIN_VER="@SCALA_BIN_VER@" -SCALAJS_VER="@SCALAJS_VER@" -SCALA_VER=$(scalac -version 2>&1 | grep -o '[0-9]\.[0-9]\+\.[0-9]\+') - -if [ "$(echo $SCALA_VER | cut -d '.' -f 1-2)" != "$SCALA_BIN_VER" ]; then - echo "This bundle of Scala.js CLI is for $SCALA_BIN_VER. Your scala version is $SCALA_VER!" >&2 - exit 1 -fi - -BASE="$(dirname $0)/.." -PLUGIN="$BASE/lib/scalajs-compiler_$SCALA_VER-$SCALAJS_VER.jar" -JSLIB="$BASE/lib/scalajs-library_$SCALA_BIN_VER-$SCALAJS_VER.jar" - -scalac -classpath "$JSLIB" "-Xplugin:$PLUGIN" "$@" diff --git a/cli/src/main/resources/scalajsc.bat b/cli/src/main/resources/scalajsc.bat deleted file mode 100644 index 767c5df9de..0000000000 --- a/cli/src/main/resources/scalajsc.bat +++ /dev/null @@ -1,14 +0,0 @@ -@ECHO OFF -set SCALA_BIN_VER=@SCALA_BIN_VER@ -set SCALAJS_VER=@SCALAJS_VER@ - -for /F "tokens=5" %%i in (' scala -version 2^>^&1 1^>nul ') do set SCALA_VER=%%i - -if NOT "%SCALA_VER:~0,4%" == "%SCALA_BIN_VER%" ( - echo "This bundle of Scala.js CLI is for %SCALA_BIN_VER%. Your scala version is %SCALA_VER%!" 1>&2 -) else ( - set PLUGIN=%~dp0\..\lib\scalajs-compiler_%SCALA_VER%-%SCALAJS_VER%.jar - set JSLIB=%~dp0\..\lib\scalajs-library_%SCALA_BIN_VER%-%SCALAJS_VER%.jar - - scalac -classpath "%JSLIB%" "-Xplugin:%PLUGIN%" %* -) diff --git a/cli/src/main/resources/scalajsld b/cli/src/main/resources/scalajsld deleted file mode 100755 index b194859ef7..0000000000 --- a/cli/src/main/resources/scalajsld +++ /dev/null @@ -1,10 +0,0 @@ -#! /bin/sh - -SCALA_BIN_VER="@SCALA_BIN_VER@" -SCALAJS_VER="@SCALAJS_VER@" - -BASE="$(dirname $0)/.." -CLILIB="$BASE/lib/scalajs-cli-assembly_$SCALA_BIN_VER-$SCALAJS_VER.jar" -JSLIB="$BASE/lib/scalajs-library_$SCALA_BIN_VER-$SCALAJS_VER.jar" - -scala -classpath "$CLILIB" org.scalajs.cli.Scalajsld --stdlib "$JSLIB" "$@" diff --git a/cli/src/main/resources/scalajsld.bat b/cli/src/main/resources/scalajsld.bat deleted file mode 100644 index 0308d559ea..0000000000 --- a/cli/src/main/resources/scalajsld.bat +++ /dev/null @@ -1,8 +0,0 @@ -@ECHO OFF -set SCALA_BIN_VER=@SCALA_BIN_VER@ -set SCALAJS_VER=@SCALAJS_VER@ - -set CLILIB="%~dp0\..\lib\scalajs-cli-assembly_%SCALA_BIN_VER%-%SCALAJS_VER%.jar" -set JSLIB="%~dp0\..\lib\scalajs-library_%SCALA_BIN_VER%-%SCALAJS_VER%.jar" - -scala -classpath %CLILIB% org.scalajs.cli.Scalajsld --stdlib %JSLIB% %* diff --git a/cli/src/main/resources/scalajsp b/cli/src/main/resources/scalajsp deleted file mode 100755 index f98f259355..0000000000 --- a/cli/src/main/resources/scalajsp +++ /dev/null @@ -1,9 +0,0 @@ -#! /bin/sh - -SCALA_BIN_VER="@SCALA_BIN_VER@" -SCALAJS_VER="@SCALAJS_VER@" - -BASE="$(dirname $0)/.." -CLILIB="$BASE/lib/scalajs-cli-assembly_$SCALA_BIN_VER-$SCALAJS_VER.jar" - -scala -classpath "$CLILIB" org.scalajs.cli.Scalajsp "$@" diff --git a/cli/src/main/resources/scalajsp.bat b/cli/src/main/resources/scalajsp.bat deleted file mode 100644 index 1fc4ad6752..0000000000 --- a/cli/src/main/resources/scalajsp.bat +++ /dev/null @@ -1,7 +0,0 @@ -@ECHO OFF -set SCALA_BIN_VER=@SCALA_BIN_VER@ -set SCALAJS_VER=@SCALAJS_VER@ - -set CLILIB="%~dp0\..\lib\scalajs-cli-assembly_%SCALA_BIN_VER%-%SCALAJS_VER%.jar" - -scala -classpath %CLILIB% org.scalajs.cli.Scalajsp %* diff --git a/cli/src/main/scala/org/scalajs/cli/Scalajsld.scala b/cli/src/main/scala/org/scalajs/cli/Scalajsld.scala deleted file mode 100644 index 8e049887ee..0000000000 --- a/cli/src/main/scala/org/scalajs/cli/Scalajsld.scala +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.cli - -import org.scalajs.core.ir.ScalaJSVersions - -import org.scalajs.core.tools.io._ -import org.scalajs.core.tools.logging._ - -import org.scalajs.core.tools.linker._ -import org.scalajs.core.tools.linker.standard._ - -import CheckedBehavior.Compliant - -import scala.collection.immutable.Seq - -import java.io.File -import java.net.URI - -object Scalajsld { - - private val AllOutputModes = List( - OutputMode.ECMAScript51Isolated, - OutputMode.ECMAScript6, - OutputMode.ECMAScript51Global) - - private case class Options( - cp: Seq[File] = Seq.empty, - moduleInitializers: Seq[ModuleInitializer] = Seq.empty, - output: File = null, - jsoutput: Boolean = false, - semantics: Semantics = Semantics.Defaults, - outputMode: OutputMode = OutputMode.ECMAScript51Isolated, - moduleKind: ModuleKind = ModuleKind.NoModule, - noOpt: Boolean = false, - fullOpt: Boolean = false, - prettyPrint: Boolean = false, - sourceMap: Boolean = false, - relativizeSourceMap: Option[URI] = None, - bypassLinkingErrors: Boolean = false, - checkIR: Boolean = false, - stdLib: Option[File] = None, - logLevel: Level = Level.Info) - - private implicit object MainMethodRead extends scopt.Read[ModuleInitializer] { - val arity = 1 - val reads = { (s: String) => - val lastDot = s.lastIndexOf('.') - if (lastDot < 0) - throw new IllegalArgumentException(s"$s is not a valid main method") - ModuleInitializer.mainMethod(s.substring(0, lastDot), - s.substring(lastDot + 1)) - } - } - - private implicit object OutputModeRead extends scopt.Read[OutputMode] { - val arity = 1 - val reads = { (s: String) => - AllOutputModes.find(_.toString() == s).getOrElse( - throw new IllegalArgumentException(s"$s is not a valid output mode")) - } - } - - private implicit object ModuleKindRead extends scopt.Read[ModuleKind] { - val arity = 1 - val reads = { (s: String) => - ModuleKind.All.find(_.toString() == s).getOrElse( - throw new IllegalArgumentException(s"$s is not a valid module kind")) - } - } - - def main(args: Array[String]): Unit = { - val parser = new scopt.OptionParser[Options]("scalajsld") { - head("scalajsld", ScalaJSVersions.current) - arg[File](" ...") - .unbounded() - .action { (x, c) => c.copy(cp = c.cp :+ x) } - .text("Entries of Scala.js classpath to link") - opt[ModuleInitializer]("mainMethod") - .valueName("") - .abbr("mm") - .unbounded() - .action { (x, c) => c.copy(moduleInitializers = c.moduleInitializers :+ x) } - .text("Execute the specified main method on startup") - opt[File]('o', "output") - .valueName("") - .required() - .action { (x, c) => c.copy(output = x) } - .text("Output file of linker (required)") - opt[File]("jsoutput") - .hidden() - .valueName("") - .abbr("jo") - .action { (_, c) => c.copy(jsoutput = true) } - .text("Deprecated: Does nothing but printing a warning") - opt[Unit]('f', "fastOpt") - .action { (_, c) => c.copy(noOpt = false, fullOpt = false) } - .text("Optimize code (this is the default)") - opt[Unit]('n', "noOpt") - .action { (_, c) => c.copy(noOpt = true, fullOpt = false) } - .text("Don't optimize code") - opt[Unit]('u', "fullOpt") - .action { (_, c) => c.copy(noOpt = false, fullOpt = true) } - .text("Fully optimize code (uses Google Closure Compiler)") - opt[Unit]('p', "prettyPrint") - .action { (_, c) => c.copy(prettyPrint = true) } - .text("Pretty print full opted code (meaningful with -u)") - opt[Unit]('s', "sourceMap") - .action { (_, c) => c.copy(sourceMap = true) } - .text("Produce a source map for the produced code") - opt[Unit]("compliantAsInstanceOfs") - .action { (_, c) => c.copy(semantics = - c.semantics.withAsInstanceOfs(Compliant)) - } - .text("Use compliant asInstanceOfs") - opt[OutputMode]('m', "outputMode") - .action { (mode, c) => c.copy(outputMode = mode) } - .text("Output mode " + AllOutputModes.mkString("(", ", ", ")")) - opt[ModuleKind]('k', "moduleKind") - .action { (kind, c) => c.copy(moduleKind = kind) } - .text("Module kind " + ModuleKind.All.mkString("(", ", ", ")")) - opt[Unit]('b', "bypassLinkingErrors") - .action { (_, c) => c.copy(bypassLinkingErrors = true) } - .text("Only warn if there are linking errors (deprecated)") - opt[Unit]('c', "checkIR") - .action { (_, c) => c.copy(checkIR = true) } - .text("Check IR before optimizing") - opt[File]('r', "relativizeSourceMap") - .valueName("") - .action { (x, c) => c.copy(relativizeSourceMap = Some(x.toURI)) } - .text("Relativize source map with respect to given path (meaningful with -s)") - opt[Unit]("noStdlib") - .action { (_, c) => c.copy(stdLib = None) } - .text("Don't automatically include Scala.js standard library") - opt[File]("stdlib") - .valueName("") - .hidden() - .action { (x, c) => c.copy(stdLib = Some(x)) } - .text("Location of Scala.js standard libarary. This is set by the " + - "runner script and automatically prepended to the classpath. " + - "Use -n to not include it.") - opt[Unit]('d', "debug") - .action { (_, c) => c.copy(logLevel = Level.Debug) } - .text("Debug mode: Show full log") - opt[Unit]('q', "quiet") - .action { (_, c) => c.copy(logLevel = Level.Warn) } - .text("Only show warnings & errors") - opt[Unit]("really-quiet") - .abbr("qq") - .action { (_, c) => c.copy(logLevel = Level.Error) } - .text("Only show errors") - version("version") - .abbr("v") - .text("Show scalajsld version") - help("help") - .abbr("h") - .text("prints this usage text") - - override def showUsageOnError = true - } - - for (options <- parser.parse(args, Options())) { - val classpath = options.stdLib.toList ++ options.cp - val irContainers = IRFileCache.IRContainer.fromClasspath(classpath) - val moduleInitializers = options.moduleInitializers - - // Warn if writing JS dependencies was requested. - if (options.jsoutput) { - Console.err.println( - "Support for the --jsoutput flag has been dropped. " + - "JS dependencies will not be written to disk. " + - "Comment on https://github.com/scala-js/scala-js/issues/2163 " + - "if you rely on this feature.") - } - - // Warn if bypassing linking errors was requested. - if (options.bypassLinkingErrors) { - Console.err.println( - "Support for bypassing linking errors with -b or " + - "--bypassLinkingErrors will be dropped in the next major version.") - } - - val semantics = - if (options.fullOpt) options.semantics.optimized - else options.semantics - - val config = StandardLinker.Config() - .withSemantics(semantics) - .withModuleKind(options.moduleKind) - .withESFeatures(options.outputMode) - .withBypassLinkingErrorsInternal(options.bypassLinkingErrors) - .withCheckIR(options.checkIR) - .withOptimizer(!options.noOpt) - .withParallel(true) - .withSourceMap(options.sourceMap) - .withRelativizeSourceMapBase(options.relativizeSourceMap) - .withClosureCompiler(options.fullOpt) - .withPrettyPrint(options.prettyPrint) - .withBatchMode(true) - - val linker = StandardLinker(config) - val logger = new ScalaConsoleLogger(options.logLevel) - val outFile = WritableFileVirtualJSFile(options.output) - val cache = (new IRFileCache).newCache - - linker.link(cache.cached(irContainers), moduleInitializers, outFile, - logger) - } - } -} diff --git a/cli/src/main/scala/org/scalajs/cli/Scalajsp.scala b/cli/src/main/scala/org/scalajs/cli/Scalajsp.scala deleted file mode 100644 index abeff4540d..0000000000 --- a/cli/src/main/scala/org/scalajs/cli/Scalajsp.scala +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.cli - -import org.scalajs.core.ir -import ir.ScalaJSVersions -import ir.Trees.{Tree, ClassDef} -import ir.Printers.{InfoPrinter, IRTreePrinter} - -import org.scalajs.core.tools.io._ -import scala.collection.immutable.Seq - -import java.io.{Console => _, _} -import java.util.zip.{ZipFile, ZipEntry} - -object Scalajsp { - - private case class Options( - infos: Boolean = false, - jar: Option[File] = None, - fileNames: Seq[String] = Seq.empty) - - def main(args: Array[String]): Unit = { - val parser = new scopt.OptionParser[Options]("scalajsp") { - head("scalajsp", ScalaJSVersions.current) - arg[String](" ...") - .unbounded() - .action { (x, c) => c.copy(fileNames = c.fileNames :+ x) } - .text("*.sjsir file to display content of") - opt[File]('j', "jar") - .valueName("") - .action { (x, c) => c.copy(jar = Some(x)) } - .text("Read *.sjsir file(s) from the given JAR.") - opt[Unit]('i', "infos") - .action { (_, c) => c.copy(infos = true) } - .text("Show DCE infos instead of trees") - opt[Unit]('s', "supported") - .action { (_,_) => printSupported(); exit(0) } - .text("Show supported Scala.js IR versions") - version("version") - .abbr("v") - .text("Show scalajsp version") - help("help") - .abbr("h") - .text("prints this usage text") - - override def showUsageOnError = true - } - - for { - options <- parser.parse(args, Options()) - fileName <- options.fileNames - } { - val vfile = options.jar map { jar => - readFromJar(jar, fileName) - } getOrElse { - readFromFile(fileName) - } - - displayFileContent(vfile, options) - } - } - - private def printSupported(): Unit = { - import ScalaJSVersions._ - println(s"Emitted Scala.js IR version is: $binaryEmitted") - println("Supported Scala.js IR versions are") - binarySupported.foreach(v => println(s"* $v")) - } - - private def displayFileContent(vfile: VirtualScalaJSIRFile, - opts: Options): Unit = { - if (opts.infos) - new InfoPrinter(stdout).print(vfile.info) - else - new IRTreePrinter(stdout).printTopLevelTree(vfile.tree) - - stdout.flush() - } - - private def fail(msg: String): Nothing = { - Console.err.println(msg) - exit(1) - } - - private def exit(code: Int): Nothing = { - System.exit(code) - throw new AssertionError("unreachable") - } - - private def readFromFile(fileName: String) = { - val file = new File(fileName) - - if (!file.exists) - fail(s"No such file: $fileName") - else if (!file.canRead) - fail(s"Unable to read file: $fileName") - else - FileVirtualScalaJSIRFile(file) - } - - private def readFromJar(jar: File, name: String) = { - val jarFile = - try { new ZipFile(jar) } - catch { case _: FileNotFoundException => fail(s"No such JAR: $jar") } - try { - val entry = jarFile.getEntry(name) - if (entry == null) - fail(s"No such file in jar: $name") - else { - val name = jarFile.getName + "#" + entry.getName - val content = - IO.readInputStreamToByteArray(jarFile.getInputStream(entry)) - new MemVirtualSerializedScalaJSIRFile(name).withContent(content) - } - } finally { - jarFile.close() - } - } - - private val stdout = - new BufferedWriter(new OutputStreamWriter(Console.out, "UTF-8")) - -} diff --git a/compiler/src/main/resources/scalac-plugin.xml b/compiler/src/main/resources/scalac-plugin.xml index b3f8bba348..6f133869fa 100644 --- a/compiler/src/main/resources/scalac-plugin.xml +++ b/compiler/src/main/resources/scalac-plugin.xml @@ -1,4 +1,4 @@ scalajs - org.scalajs.core.compiler.ScalaJSPlugin + org.scalajs.nscplugin.ScalaJSPlugin diff --git a/compiler/src/main/scala/org/scalajs/core/compiler/Compat210Component.scala b/compiler/src/main/scala/org/scalajs/core/compiler/Compat210Component.scala deleted file mode 100644 index 49fbb27aac..0000000000 --- a/compiler/src/main/scala/org/scalajs/core/compiler/Compat210Component.scala +++ /dev/null @@ -1,316 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler - -import scala.collection.mutable - -import scala.reflect.internal.Flags.{LOCAL, PRIVATE} -import scala.tools.nsc._ - -/** Hacks to have our source code compatible with 2.10 and 2.11. - * It exposes 2.11 API in a 2.10 compiler. - * - * @author Sébastien Doeraene - */ -trait Compat210Component { - import Compat210Component.{infiniteLoop, noImplClasses} - - val global: Global - - import global._ - - // unexpandedName replaces originalName - - implicit final class SymbolCompat(self: Symbol) { - def unexpandedName: Name = self.originalName - def originalName: Name = infiniteLoop() - - def isPrivateThis: Boolean = self.hasAllFlags(PRIVATE | LOCAL) - def isLocalToBlock: Boolean = self.isLocal - - def originalOwner: Symbol = - global.originalOwner.getOrElse(self, self.rawowner) - - def implClass: Symbol = NoSymbol - - def isTraitOrInterface: Boolean = self.isTrait || self.isInterface - } - - // Global compat - - @inline final def enteringPhase[T](ph: Phase)(op: => T): T = { - global.enteringPhase(ph)(op) - } - - @inline final def exitingPhase[T](ph: Phase)(op: => T): T = { - global.exitingPhase(ph)(op) - } - - @inline final def devWarning(msg: => String): Unit = - global.devWarning(msg) - - @inline final def forScaladoc: Boolean = - global.forScaladoc - - implicit final class GlobalCompat( - self: Compat210Component.this.global.type) { - - object originalOwner { - def getOrElse(sym: Symbol, orElse: => Symbol): Symbol = infiniteLoop() - } - - def enteringPhase[T](ph: Phase)(op: => T): T = self.beforePhase(ph)(op) - def beforePhase[T](ph: Phase)(op: => T): T = infiniteLoop() - - def exitingPhase[T](ph: Phase)(op: => T): T = self.afterPhase(ph)(op) - def afterPhase[T](ph: Phase)(op: => T): T = infiniteLoop() - - def delambdafy: DelambdafyCompat.type = DelambdafyCompat - - def devWarning(msg: => String): Unit = self.debugwarn(msg) - def debugwarn(msg: => String): Unit = infiniteLoop() - - def forScaladoc: Boolean = - self.isInstanceOf[ScaladocGlobalCompat.ScaladocGlobalCompat] - } - - object ScaladocGlobalCompat { - object Compat { - trait ScaladocGlobal - } - - import Compat._ - - object Inner { - import scala.tools.nsc.doc._ - - type ScaladocGlobalCompat = ScaladocGlobal - } - - type ScaladocGlobalCompat = Inner.ScaladocGlobalCompat - } - - object DelambdafyCompat { - object FreeVarTraverser { - def freeVarsOf(function: Function): mutable.LinkedHashSet[Symbol] = { - throw new AssertionError( - "FreeVarTraverser should not be called on 2.10") - } - } - } - - // Impl classes disappeared in 2.12 - - lazy val scalaUsesImplClasses: Boolean = - definitions.SeqClass.implClass != NoSymbol // a trait we know has an impl class - - def isImplClass(sym: Symbol): Boolean = - sym.isImplClass - - implicit final class StdTermNamesCompat(self: global.nme.type) { - def IMPL_CLASS_SUFFIX: String = noImplClasses() - - def isImplClassName(name: Name): Boolean = false - } - - implicit final class StdTypeNamesCompat(self: global.tpnme.type) { - def IMPL_CLASS_SUFFIX: String = noImplClasses() - - def interfaceName(implname: Name): TypeName = noImplClasses() - } - - // SAMFunction was introduced in 2.12 for LMF-capable SAM types - - object SAMFunctionAttachCompatDef { - /* Should extend PlainAttachment, but it does not exist in 2.10, and we - * do not actually need this relationship. - */ - case class SAMFunction(samTp: Type, sam: Symbol, synthCls: Symbol) - } - - object SAMFunctionAttachCompat { - import SAMFunctionAttachCompatDef._ - - object Inner { - import global._ - - type SAMFunctionAlias = SAMFunction - val SAMFunctionAlias = SAMFunction - } - } - - type SAMFunctionCompat = SAMFunctionAttachCompat.Inner.SAMFunctionAlias - lazy val SAMFunctionCompat = SAMFunctionAttachCompat.Inner.SAMFunctionAlias - - implicit final class SAMFunctionCompatOps(self: SAMFunctionCompat) { - // Introduced in 2.12.5 to synthesize bridges in LMF classes - def synthCls: Symbol = NoSymbol - } - - /* global.genBCode.bTypes.initializeCoreBTypes() - * - * This one has a very particular history: - * - in 2.10.x, no genBCode in global - * - in 2.11.{0-1}, there is genBCode but it has no bTypes member - * - In 2.11.{2-5}, there is genBCode.bTypes, but it has no - * initializeCoreBTypes (it was actually typo'ed as intializeCoreBTypes!) - * - In 2.11.6+, including 2.12, we finally have - * genBCode.bTypes.initializeCoreBTypes - * - As of 2.12, it is mandatory to call that method from GenJSCode.run() - */ - - object LowPrioGenBCodeCompat { - object genBCode { - object bTypes { - def initializeCoreBTypes(): Unit = () - } - } - } - - def initializeCoreBTypesCompat(): Unit = { - import LowPrioGenBCodeCompat._ - - { - import global._ - - import LowPrioGenBCodeCompat.genBCode._ - - { - import genBCode._ - - import LowPrioGenBCodeCompat.genBCode.bTypes._ - - { - import bTypes._ - - initializeCoreBTypes() - } - } - } - } - - // Compat to support: new overridingPairs.Cursor(sym).iterator - - implicit class OverridingPairsCursor2Iterable(cursor: overridingPairs.Cursor) { - def iterator: Iterator[SymbolPair] = new Iterator[SymbolPair] { - skipIgnoredEntries() - - def hasNext: Boolean = cursor.hasNext - - def next(): SymbolPair = { - val symbolPair = new SymbolPair(cursor.overriding, cursor.overridden) - cursor.next() - skipIgnoredEntries() - symbolPair - } - - private def skipIgnoredEntries(): Unit = { - while (cursor.hasNext && ignoreNextEntry) - cursor.next() - } - - /** In 2.10 the overridingPairs.Cursor returns some false positives - * on overriding members. The known false positives are always trying to - * override the `isInstanceOf` method. - */ - private def ignoreNextEntry: Boolean = - cursor.overriding.name == nme.isInstanceOf_ - } - - class SymbolPair(val low: Symbol, val high: Symbol) - - /** To make this compat code compile in 2.11 as the fields `overriding` and - * `overridden` are only present in 2.10. - */ - private implicit class Cursor210toCursor211(cursor: overridingPairs.Cursor) { - def overriding: Symbol = infiniteLoop() - def overridden: Symbol = infiniteLoop() - } - } - - // ErasedValueType has a different encoding - - implicit final class ErasedValueTypeCompat(self: global.ErasedValueType) { - def valueClazz: Symbol = self.original.typeSymbol - def erasedUnderlying: Type = - enteringPhase(currentRun.erasurePhase)( - erasure.erasedValueClassArg(self.original)) - def original: TypeRef = infiniteLoop() - } - - // Definitions - - @inline final def repeatedToSingle(t: Type): Type = - global.definitions.repeatedToSingle(t) - - final def isFunctionSymbol(sym: Symbol): Boolean = - global.definitions.isFunctionSymbol(sym) - - private implicit final class DefinitionsCompat( - self: Compat210Component.this.global.definitions.type) { - - def repeatedToSingle(t: Type): Type = t match { - case TypeRef(_, self.RepeatedParamClass, arg :: Nil) => arg - case _ => t - } - - def isFunctionSymbol(sym: Symbol): Boolean = - definitions.FunctionClass.seq.contains(definitions.unspecializedSymbol(sym)) - - } - - // run.runDefinitions bundles methods and state related to the run - // that were previously in definitions itself - - implicit final class RunCompat(self: Run) { - val runDefinitions: Compat210Component.this.global.definitions.type = - global.definitions - } - - // Mode.FUNmode replaces analyzer.FUNmode - - object Mode { - import Compat210Component.AnalyzerCompat - // No type ascription! Type is different in 2.10 / 2.11 - val FUNmode = analyzer.FUNmode - } -} - -object Compat210Component { - private object LowPriorityMode { - object Mode { - def FUNmode: Nothing = infiniteLoop() - } - } - - private implicit final class AnalyzerCompat(self: scala.tools.nsc.typechecker.Analyzer) { - def FUNmode = { // scalastyle:ignore - import Compat210Component.LowPriorityMode._ - { - import scala.reflect.internal._ - Mode.FUNmode - } - } - } - - private def infiniteLoop(): Nothing = - throw new AssertionError("Infinite loop in Compat") - - private def noImplClasses(): Nothing = - throw new AssertionError("No impl classes in this version") -} - -trait PluginComponent210Compat extends Compat210Component { - // Starting 2.11.x, we need to override the default description. - def description: String -} diff --git a/compiler/src/main/scala/org/scalajs/core/compiler/GenJSCode.scala b/compiler/src/main/scala/org/scalajs/core/compiler/GenJSCode.scala deleted file mode 100644 index 9da812c6a0..0000000000 --- a/compiler/src/main/scala/org/scalajs/core/compiler/GenJSCode.scala +++ /dev/null @@ -1,5898 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler - -import scala.language.implicitConversions - -import scala.annotation.switch - -import scala.collection.mutable -import scala.collection.mutable.ListBuffer - -import scala.tools.nsc._ - -import scala.annotation.tailrec - -import org.scalajs.core.ir -import ir.{Trees => js, Types => jstpe, ClassKind, Hashers} -import ir.Trees.OptimizerHints - -import org.scalajs.core.compiler.util.{ScopedVar, VarBox} -import ScopedVar.withScopedVars - -/** Generate JavaScript code and output it to disk - * - * @author Sébastien Doeraene - */ -abstract class GenJSCode[G <: Global with Singleton](val global: G) - extends plugins.PluginComponent with TypeKinds[G] with JSEncoding[G] - with GenJSExports[G] with GenJSFiles[G] with PluginComponent210Compat { - - /** Not for use in the constructor body: only initialized afterwards. */ - val jsAddons: JSGlobalAddons { - val global: GenJSCode.this.global.type - } - - /** Not for use in the constructor body: only initialized afterwards. */ - val scalaJSOpts: ScalaJSOptions - - import global._ - import jsAddons._ - import rootMirror._ - import definitions._ - import jsDefinitions._ - import jsInterop.{jsNameOf, compat068FullJSNameOf, jsNativeLoadSpecOf, JSName} - import JSTreeExtractors._ - - import treeInfo.{hasSynthCaseSymbol, StripCast} - - import platform.isMaybeBoxed - - val phaseName: String = "jscode" - override val description: String = "generate JavaScript code from ASTs" - - /** testing: this will be called when ASTs are generated */ - def generatedJSAST(clDefs: List[js.Tree]): Unit - - /** Implicit conversion from nsc Position to ir.Position. */ - implicit def pos2irPos(pos: Position): ir.Position = { - if (pos == NoPosition) ir.Position.NoPosition - else { - val source = pos2irPosCache.toIRSource(pos.source) - // nsc positions are 1-based but IR positions are 0-based - ir.Position(source, pos.line-1, pos.column-1) - } - } - - private[this] object pos2irPosCache { - import scala.reflect.internal.util._ - - private[this] var lastNscSource: SourceFile = null - private[this] var lastIRSource: ir.Position.SourceFile = null - - def toIRSource(nscSource: SourceFile): ir.Position.SourceFile = { - if (nscSource != lastNscSource) { - lastIRSource = convert(nscSource) - lastNscSource = nscSource - } - lastIRSource - } - - private[this] def convert(nscSource: SourceFile): ir.Position.SourceFile = { - nscSource.file.file match { - case null => - new java.net.URI( - "virtualfile", // Pseudo-Scheme - nscSource.file.path, // Scheme specific part - null // Fragment - ) - case file => - val srcURI = file.toURI - def matches(pat: java.net.URI) = pat.relativize(srcURI) != srcURI - - scalaJSOpts.sourceURIMaps.collectFirst { - case ScalaJSOptions.URIMap(from, to) if matches(from) => - val relURI = from.relativize(srcURI) - to.fold(relURI)(_.resolve(relURI)) - } getOrElse srcURI - } - } - - def clear(): Unit = { - lastNscSource = null - lastIRSource = null - } - } - - /** Materialize implicitly an ir.Position from an implicit nsc Position. */ - implicit def implicitPos2irPos(implicit pos: Position): ir.Position = pos - - override def newPhase(p: Phase): StdPhase = new JSCodePhase(p) - - private object jsnme { - val anyHash = newTermName("anyHash") - val arg_outer = newTermName("arg$outer") - val newString = newTermName("newString") - } - - class JSCodePhase(prev: Phase) extends StdPhase(prev) with JSExportsPhase { - - override def name: String = phaseName - override def description: String = GenJSCode.this.description - - // Scoped state ------------------------------------------------------------ - // Per class body - val currentClassSym = new ScopedVar[Symbol] - private val unexpectedMutatedFields = new ScopedVar[mutable.Set[Symbol]] - private val generatedSAMWrapperCount = new ScopedVar[VarBox[Int]] - - private def currentClassType = encodeClassType(currentClassSym) - - // Per method body - private val currentMethodSym = new ScopedVar[Symbol] - private val thisLocalVarIdent = new ScopedVar[Option[js.Ident]] - private val fakeTailJumpParamRepl = new ScopedVar[(Symbol, Symbol)] - private val enclosingLabelDefParams = new ScopedVar[Map[Symbol, List[Symbol]]] - private val isModuleInitialized = new ScopedVar[VarBox[Boolean]] - private val countsOfReturnsToMatchCase = new ScopedVar[mutable.Map[Symbol, Int]] - private val countsOfReturnsToMatchEnd = new ScopedVar[mutable.Map[Symbol, Int]] - private val undefinedDefaultParams = new ScopedVar[mutable.Set[Symbol]] - - // For some method bodies - private val mutableLocalVars = new ScopedVar[mutable.Set[Symbol]] - private val mutatedLocalVars = new ScopedVar[mutable.Set[Symbol]] - - // For anonymous methods - // These have a default, since we always read them. - private val tryingToGenMethodAsJSFunction = new ScopedVar[Boolean](false) - private val paramAccessorLocals = new ScopedVar(Map.empty[Symbol, js.ParamDef]) - - private class CancelGenMethodAsJSFunction(message: String) - extends scala.util.control.ControlThrowable { - override def getMessage(): String = message - } - - // Rewriting of anonymous function classes --------------------------------- - - /** Start nested generation of a class. - * - * Fully resets the scoped state (including local name scope). - * Allows to generate an anonymous class as needed. - */ - private def nestedGenerateClass[T](clsSym: Symbol)(body: => T): T = { - withScopedVars( - currentClassSym := clsSym, - unexpectedMutatedFields := mutable.Set.empty, - generatedSAMWrapperCount := new VarBox(0), - currentMethodSym := null, - thisLocalVarIdent := null, - fakeTailJumpParamRepl := null, - enclosingLabelDefParams := null, - isModuleInitialized := null, - countsOfReturnsToMatchCase := null, - countsOfReturnsToMatchEnd := null, - undefinedDefaultParams := null, - mutableLocalVars := null, - mutatedLocalVars := null, - tryingToGenMethodAsJSFunction := false, - paramAccessorLocals := Map.empty - )(withNewLocalNameScope(body)) - } - - // Global class generation state ------------------------------------------- - - private val lazilyGeneratedAnonClasses = mutable.Map.empty[Symbol, ClassDef] - private val generatedClasses = - ListBuffer.empty[(Symbol, Option[String], js.ClassDef)] - - private def consumeLazilyGeneratedAnonClass(sym: Symbol): ClassDef = { - /* If we are trying to generate an method as JSFunction, we cannot - * actually consume the symbol, since we might fail trying and retry. - * We will then see the same tree again and not find the symbol anymore. - * - * If we are sure this is the only generation, we remove the symbol to - * make sure we don't generate the same class twice. - */ - val optDef = { - if (tryingToGenMethodAsJSFunction) - lazilyGeneratedAnonClasses.get(sym) - else - lazilyGeneratedAnonClasses.remove(sym) - } - - optDef.getOrElse { - abort("Couldn't find tree for lazily generated anonymous class " + - s"${sym.fullName} at ${sym.pos}") - } - } - - // Top-level apply --------------------------------------------------------- - - override def run(): Unit = { - scalaPrimitives.init() - initializeCoreBTypesCompat() - jsPrimitives.init() - super.run() - } - - /** Generates the Scala.js IR for a compilation unit - * This method iterates over all the class and interface definitions - * found in the compilation unit and emits their IR (.sjsir). - * - * Some classes are never actually emitted: - * - Classes representing primitive types - * - The scala.Array class - * - Implementation classes for raw JS traits - * - * Some classes representing anonymous functions are not actually emitted. - * Instead, a temporary representation of their `apply` method is built - * and recorded, so that it can be inlined as a JavaScript anonymous - * function in the method that instantiates it. - * - * Other ClassDefs are emitted according to their nature: - * * Scala.js-defined JS class -> `genScalaJSDefinedJSClass()` - * * Other raw JS type (<: js.Any) -> `genRawJSClassData()` - * * Interface -> `genInterface()` - * * Implementation class -> `genImplClass()` - * * Normal class -> `genClass()` - */ - override def apply(cunit: CompilationUnit): Unit = { - try { - def collectClassDefs(tree: Tree): List[ClassDef] = { - tree match { - case EmptyTree => Nil - case PackageDef(_, stats) => stats flatMap collectClassDefs - case cd: ClassDef => cd :: Nil - } - } - val allClassDefs = collectClassDefs(cunit.body) - - /* There are three types of anonymous classes we want to generate - * only once we need them so we can inline them at construction site: - * - * - lambdas for js.FunctionN and js.ThisFunctionN (SAMs). (We may not - * generate actual Scala classes for these). - * - anonymous Scala.js defined JS classes. These classes may not have - * their own prototype. Therefore, their constructor *must* be - * inlined. - * - lambdas for scala.FunctionN. This is only an optimization and may - * fail. In the case of failure, we fall back to generating a - * fully-fledged Scala class. - * - * Since for all these, we don't know how they inter-depend, we just - * store them in a map at this point. - */ - val (lazyAnons, fullClassDefs0) = allClassDefs.partition { cd => - val sym = cd.symbol - isRawJSFunctionDef(sym) || sym.isAnonymousFunction || - isScalaJSDefinedAnonJSClass(sym) - } - - lazilyGeneratedAnonClasses ++= lazyAnons.map(cd => cd.symbol -> cd) - - /* Under Scala 2.11 with -Xexperimental, anonymous JS function classes - * can be referred to in private method signatures, which means they - * must exist at the IR level, as `AbstractJSType`s. - */ - val fullClassDefs = if (isScala211WithXexperimental) { - lazyAnons.filter(cd => isRawJSFunctionDef(cd.symbol)) ::: fullClassDefs0 - } else { - fullClassDefs0 - } - - /* Finally, we emit true code for the remaining class defs. */ - for (cd <- fullClassDefs) { - val sym = cd.symbol - implicit val pos = sym.pos - - /* Do not actually emit code for primitive types nor scala.Array. */ - val isPrimitive = - isPrimitiveValueClass(sym) || (sym == ArrayClass) - - if (!isPrimitive && !isRawJSImplClass(sym)) { - withScopedVars( - currentClassSym := sym, - unexpectedMutatedFields := mutable.Set.empty, - generatedSAMWrapperCount := new VarBox(0) - ) { - val tree = if (isRawJSType(sym.tpe)) { - if (!sym.isTraitOrInterface && isScalaJSDefinedJSClass(sym) && - !isRawJSFunctionDef(sym)) { - genScalaJSDefinedJSClass(cd) - } else { - genRawJSClassData(cd) - } - } else if (sym.isTraitOrInterface) { - genInterface(cd) - } else if (isImplClass(sym)) { - genImplClass(cd) - } else { - genClass(cd) - } - - generatedClasses += ((sym, None, tree)) - } - } - } - - val clDefs = generatedClasses.map(_._3).toList - generatedJSAST(clDefs) - - for ((sym, suffix, tree) <- generatedClasses) { - genIRFile(cunit, sym, suffix, tree) - } - } finally { - lazilyGeneratedAnonClasses.clear() - generatedClasses.clear() - pos2irPosCache.clear() - } - } - - // Generate a class -------------------------------------------------------- - - /** Gen the IR ClassDef for a class definition (maybe a module class). - */ - def genClass(cd: ClassDef): js.ClassDef = { - val ClassDef(mods, name, _, impl) = cd - val sym = cd.symbol - implicit val pos = sym.pos - - assert(!sym.isTraitOrInterface && !isImplClass(sym), - "genClass() must be called only for normal classes: "+sym) - assert(sym.superClass != NoSymbol, sym) - - if (hasDefaultCtorArgsAndRawJSModule(sym)) { - reporter.error(pos, - "Implementation restriction: constructors of " + - "Scala classes cannot have default parameters " + - "if their companion module is JS native.") - } - - val classIdent = encodeClassFullNameIdent(sym) - val isHijacked = isHijackedBoxedClass(sym) - - // Optimizer hints - - def isStdLibClassWithAdHocInlineAnnot(sym: Symbol): Boolean = { - val fullName = sym.fullName - (fullName.startsWith("scala.Tuple") && !fullName.endsWith("$")) || - (fullName.startsWith("scala.collection.mutable.ArrayOps$of")) - } - - val shouldMarkInline = ( - sym.hasAnnotation(InlineAnnotationClass) || - (sym.isAnonymousFunction && !sym.isSubClass(PartialFunctionClass)) || - isStdLibClassWithAdHocInlineAnnot(sym)) - - val optimizerHints = - OptimizerHints.empty. - withInline(shouldMarkInline). - withNoinline(sym.hasAnnotation(NoinlineAnnotationClass)) - - // Generate members (constructor + methods) - - val generatedMethods = new ListBuffer[js.MethodDef] - - def gen(tree: Tree): Unit = { - tree match { - case EmptyTree => () - case Template(_, _, body) => body foreach gen - - case ValDef(mods, name, tpt, rhs) => - () // fields are added via genClassFields() - - case dd: DefDef => - if (isNamedExporterDef(dd)) - generatedMethods ++= genNamedExporterDef(dd) - else - generatedMethods ++= genMethod(dd) - - case _ => abort("Illegal tree in gen of genClass(): " + tree) - } - } - - gen(impl) - - // Generate fields if necessary (and add to methods + ctors) - val generatedMembers = - if (!isHijacked) genClassFields(cd) ++ generatedMethods.toList - else generatedMethods.toList // No fields needed - - // Generate the exported members, constructors and accessors - val exports = { - // Generate the exported members - val memberExports = genMemberExports(sym) - - // Generate exported constructors or accessors - val exportedConstructorsOrAccessors = - if (isStaticModule(sym)) genModuleAccessorExports(sym) - else genConstructorExports(sym) - - val topLevelExports = genTopLevelExports(sym) - - memberExports ++ exportedConstructorsOrAccessors ++ topLevelExports - } - - // Static initializer - val optStaticInitializer = { - // Initialization of reflection data, if required - val reflectInit = { - val enableReflectiveInstantiation = { - (sym :: sym.ancestors).exists { ancestor => - ancestor.hasAnnotation(EnableReflectiveInstantiationAnnotation) - } - } - if (enableReflectiveInstantiation) - genRegisterReflectiveInstantiation(sym) - else - None - } - - // Initialization of the module because of field exports - val needsStaticModuleInit = - exports.exists(_.isInstanceOf[js.TopLevelFieldExportDef]) - val staticModuleInit = - if (!needsStaticModuleInit) None - else Some(genLoadModule(sym)) - - val staticInitializerStats = - reflectInit.toList ::: staticModuleInit.toList - if (staticInitializerStats.nonEmpty) - Some(genStaticInitializerWithStats(js.Block(staticInitializerStats))) - else - None - } - - // Hashed definitions of the class - val hashedDefs = - Hashers.hashDefs(generatedMembers ++ exports ++ optStaticInitializer) - - // The complete class definition - val kind = - if (isStaticModule(sym)) ClassKind.ModuleClass - else if (isHijacked) ClassKind.HijackedClass - else ClassKind.Class - - val classDefinition = js.ClassDef( - classIdent, - kind, - Some(encodeClassFullNameIdent(sym.superClass)), - genClassInterfaces(sym), - None, - hashedDefs)( - optimizerHints) - - classDefinition - } - - /** Gen the IR ClassDef for a Scala.js-defined JS class. */ - def genScalaJSDefinedJSClass(cd: ClassDef): js.ClassDef = { - val sym = cd.symbol - implicit val pos = sym.pos - - assert(isScalaJSDefinedJSClass(sym), - "genScalaJSDefinedJSClass() must be called only for " + - s"Scala.js-defined JS classes: $sym") - assert(sym.superClass != NoSymbol, sym) - - val classIdent = encodeClassFullNameIdent(sym) - - // Generate members (constructor + methods) - - val constructorTrees = new ListBuffer[DefDef] - val generatedMethods = new ListBuffer[js.MethodDef] - val dispatchMethodNames = new ListBuffer[JSName] - - def gen(tree: Tree): Unit = { - tree match { - case EmptyTree => () - case Template(_, _, body) => body foreach gen - - case ValDef(mods, name, tpt, rhs) => - () // fields are added via genClassFields() - - case dd: DefDef => - val sym = dd.symbol - val exposed = isExposed(sym) - - if (sym.isClassConstructor) { - constructorTrees += dd - } else if (exposed && sym.isAccessor && !sym.isLazy) { - /* Exposed accessors must not be emitted, since the field they - * access is enough. - */ - } else if (sym.hasAnnotation(JSOptionalAnnotation)) { - // Optional methods must not be emitted - } else { - generatedMethods ++= genMethod(dd) - - // Collect the names of the dispatchers we have to create - if (exposed && !sym.isDeferred) { - /* We add symbols that we have to expose here. This way we also - * get inherited stuff that is implemented in this class. - */ - dispatchMethodNames += jsNameOf(sym) - } - } - - case _ => abort("Illegal tree in gen of genClass(): " + tree) - } - } - - gen(cd.impl) - - // Static members (exported from the companion object) - val staticMembers = { - /* Phase travel is necessary for non-top-level classes, because flatten - * breaks their companionModule. This is tracked upstream at - * https://github.com/scala/scala-dev/issues/403 - */ - val companionModuleClass = - exitingPhase(currentRun.picklerPhase)(sym.linkedClassOfClass) - if (companionModuleClass == NoSymbol) { - Nil - } else { - val exports = withScopedVars(currentClassSym := companionModuleClass) { - genStaticExports(companionModuleClass) - } - if (exports.exists(_.isInstanceOf[js.FieldDef])) { - val staticInitializer = - genStaticInitializerWithStats(genLoadModule(companionModuleClass)) - exports :+ staticInitializer - } else { - exports - } - } - } - - // Generate class-level exporters - val classExports = - if (isStaticModule(sym)) genModuleAccessorExports(sym) - else genJSClassExports(sym) - - // Generate fields (and add to methods + ctors) - val generatedMembers = { - genClassFields(cd) ::: - genJSClassConstructor(sym, constructorTrees.toList) :: - genJSClassDispatchers(sym, dispatchMethodNames.result().distinct) ::: - generatedMethods.toList ::: - staticMembers ::: - classExports - } - - // Hashed definitions of the class - val hashedDefs = - Hashers.hashDefs(generatedMembers) - - // The complete class definition - val kind = - if (isStaticModule(sym)) ClassKind.JSModuleClass - else ClassKind.JSClass - - val classDefinition = js.ClassDef( - classIdent, - kind, - Some(encodeClassFullNameIdent(sym.superClass)), - genClassInterfaces(sym), - None, - hashedDefs)( - OptimizerHints.empty) - - classDefinition - } - - /** Generate an instance of an anonymous Scala.js defined class inline - * - * @param sym Class to generate the instance of - * @param args Arguments to the constructor - * @param pos Position of the original New tree - */ - def genAnonSJSDefinedNew(sym: Symbol, args: List[js.Tree], - pos: Position): js.Tree = { - assert(isScalaJSDefinedAnonJSClass(sym), - "Generating AnonSJSDefinedNew of non anonymous SJSDefined JS class") - - // Find the ClassDef for this anonymous class - val classDef = consumeLazilyGeneratedAnonClass(sym) - - // Generate a normal SJSDefinedJSClass - val origJsClass = - nestedGenerateClass(sym)(genScalaJSDefinedJSClass(classDef)) - - // Partition class members. - val staticMembers = ListBuffer.empty[js.Tree] - val classMembers = ListBuffer.empty[js.Tree] - var constructor: Option[js.MethodDef] = None - - origJsClass.defs.foreach { - case fdef: js.FieldDef => - classMembers += fdef - - case mdef: js.MethodDef => - mdef.name match { - case _: js.Ident => - assert(mdef.static, "Non-static method in SJS defined JS class") - staticMembers += mdef - - case js.StringLiteral("constructor") => - assert(!mdef.static, "Exported static method") - assert(constructor.isEmpty, "two ctors in class") - constructor = Some(mdef) - - case _ => - assert(!mdef.static, "Exported static method") - classMembers += mdef - } - - case property: js.PropertyDef => - classMembers += property - - case _: js.Skip => - // This can happen in cases of earlier errors. Don't crash. - - case tree => - abort("Unexpected tree: " + tree) - } - - // Make new class def with static members only - val newClassDef = { - implicit val pos = origJsClass.pos - val parent = js.Ident(ir.Definitions.ObjectClass) - js.ClassDef(origJsClass.name, ClassKind.AbstractJSType, - Some(parent), interfaces = Nil, jsNativeLoadSpec = None, - staticMembers.toList)(origJsClass.optimizerHints) - } - - generatedClasses += ((sym, None, newClassDef)) - - // Construct inline class definition - val js.MethodDef(_, _, ctorParams, _, Some(ctorBody)) = - constructor.getOrElse(throw new AssertionError("No ctor found")) - - val selfName = freshLocalIdent("this")(pos) - def selfRef(implicit pos: ir.Position) = - js.VarRef(selfName)(jstpe.AnyType) - - def lambda(params: List[js.ParamDef], body: js.Tree)( - implicit pos: ir.Position) = { - js.Closure(captureParams = Nil, params, body, captureValues = Nil) - } - - val memberDefinitions = classMembers.toList.map { - case fdef: js.FieldDef => - implicit val pos = fdef.pos - val select = fdef.name match { - case ident: js.Ident => js.JSDotSelect(selfRef, ident) - case lit: js.StringLiteral => js.JSBracketSelect(selfRef, lit) - case js.ComputedName(tree, _) => js.JSBracketSelect(selfRef, tree) - } - js.Assign(select, jstpe.zeroOf(fdef.ftpe)) - - case mdef: js.MethodDef => - implicit val pos = mdef.pos - val name = mdef.name.asInstanceOf[js.StringLiteral] - val impl = lambda(mdef.args, mdef.body.getOrElse( - throw new AssertionError("Got anon SJS class with abstract method"))) - js.Assign(js.JSBracketSelect(selfRef, name), impl) - - case pdef: js.PropertyDef => - implicit val pos = pdef.pos - val name = pdef.name.asInstanceOf[js.StringLiteral] - val jsObject = - js.JSBracketSelect(genLoadGlobal(), js.StringLiteral("Object")) - - def field(name: String, value: js.Tree) = - List(js.StringLiteral(name) -> value) - - val optGetter = pdef.getterBody map { body => - js.StringLiteral("get") -> lambda(params = Nil, body) - } - - val optSetter = pdef.setterArgAndBody map { case (arg, body) => - js.StringLiteral("set") -> lambda(params = arg :: Nil, body) - } - - val descriptor = js.JSObjectConstr( - optGetter.toList ++ - optSetter ++ - List(js.StringLiteral("configurable") -> js.BooleanLiteral(true)) - ) - - js.JSBracketMethodApply(jsObject, js.StringLiteral("defineProperty"), - List(selfRef, name, descriptor)) - - case tree => - abort("Unexpected tree: " + tree) - } - - // Transform the constructor body. - val inlinedCtorStats = new ir.Transformers.Transformer { - override def transform(tree: js.Tree, isStat: Boolean): js.Tree = tree match { - // The super constructor call. Transform this into a simple new call. - case js.JSSuperConstructorCall(args) => - implicit val pos = tree.pos - - val newTree = { - val ident = - origJsClass.superClass.getOrElse(abort("No superclass")) - if (args.isEmpty && ident.name == "sjs_js_Object") { - js.JSObjectConstr(Nil) - } else { - val superTpe = jstpe.ClassType(ident.name) - js.JSNew(js.LoadJSConstructor(superTpe), args) - } - } - - js.Block( - js.VarDef(selfName, jstpe.AnyType, mutable = false, newTree) :: - memberDefinitions)(NoPosition) - - case js.This() => selfRef(tree.pos) - - // Don't traverse closure boundaries - case closure: js.Closure => - val newCaptureValues = closure.captureValues.map(transformExpr) - closure.copy(captureValues = newCaptureValues)(closure.pos) - - case tree => - super.transform(tree, isStat) - } - }.transform(ctorBody, isStat = true) - - val invocation = { - implicit val invocationPosition = pos - - val closure = - js.Closure(Nil, ctorParams, js.Block(inlinedCtorStats, selfRef), Nil) - - js.JSFunctionApply(closure, args) - } - - invocation - } - - // Generate the class data of a raw JS class ------------------------------- - - /** Gen the IR ClassDef for a raw JS class or trait. - */ - def genRawJSClassData(cd: ClassDef): js.ClassDef = { - val sym = cd.symbol - implicit val pos = sym.pos - - val classIdent = encodeClassFullNameIdent(sym) - val kind = { - if (sym.isTraitOrInterface) ClassKind.AbstractJSType - else if (isRawJSFunctionDef(sym)) ClassKind.AbstractJSType - else if (sym.isModuleClass) ClassKind.NativeJSModuleClass - else ClassKind.NativeJSClass - } - val superClass = - if (sym.isTraitOrInterface) None - else Some(encodeClassFullNameIdent(sym.superClass)) - val jsNativeLoadSpec = - if (kind == ClassKind.AbstractJSType) None - else Some(jsNativeLoadSpecOf(sym)) - - js.ClassDef(classIdent, kind, superClass, genClassInterfaces(sym), - jsNativeLoadSpec, Nil)( - OptimizerHints.empty) - } - - // Generate an interface --------------------------------------------------- - - /** Gen the IR ClassDef for an interface definition. - */ - def genInterface(cd: ClassDef): js.ClassDef = { - val sym = cd.symbol - implicit val pos = sym.pos - - val classIdent = encodeClassFullNameIdent(sym) - - // fill in class info builder - def gen(tree: Tree): List[js.MethodDef] = { - tree match { - case EmptyTree => Nil - case Template(_, _, body) => body.flatMap(gen) - - case dd: DefDef => - if (isNamedExporterDef(dd)) - genNamedExporterDef(dd).toList - else - genMethod(dd).toList - - case _ => - abort("Illegal tree in gen of genInterface(): " + tree) - } - } - val generatedMethods = gen(cd.impl) - val interfaces = genClassInterfaces(sym) - - // Hashed definitions of the interface - val hashedDefs = - Hashers.hashDefs(generatedMethods) - - js.ClassDef(classIdent, ClassKind.Interface, None, interfaces, None, - hashedDefs)(OptimizerHints.empty) - } - - // Generate an implementation class of a trait ----------------------------- - - /** Gen the IR ClassDef for an implementation class (of a trait). - */ - def genImplClass(cd: ClassDef): js.ClassDef = { - val ClassDef(mods, name, _, impl) = cd - val sym = cd.symbol - implicit val pos = sym.pos - - def gen(tree: Tree): List[js.MethodDef] = { - tree match { - case EmptyTree => Nil - case Template(_, _, body) => body.flatMap(gen) - - case dd: DefDef => - assert(!dd.symbol.isDeferred, - s"Found an abstract method in an impl class at $pos: ${dd.symbol.fullName}") - val m = genMethod(dd) - m.toList - - case _ => abort("Illegal tree in gen of genImplClass(): " + tree) - } - } - val generatedMethods = gen(impl) - - val classIdent = encodeClassFullNameIdent(sym) - val objectClassIdent = encodeClassFullNameIdent(ObjectClass) - - // Hashed definitions of the impl class - val hashedDefs = - Hashers.hashDefs(generatedMethods) - - js.ClassDef(classIdent, ClassKind.Class, - Some(objectClassIdent), Nil, None, - hashedDefs)(OptimizerHints.empty) - } - - private def genClassInterfaces(sym: Symbol)( - implicit pos: Position): List[js.Ident] = { - for { - parent <- sym.info.parents - typeSym = parent.typeSymbol - _ = assert(typeSym != NoSymbol, "parent needs symbol") - if typeSym.isTraitOrInterface - } yield { - encodeClassFullNameIdent(typeSym) - } - } - - // Generate the fields of a class ------------------------------------------ - - /** Gen definitions for the fields of a class. - * The fields are initialized with the zero of their types. - */ - def genClassFields(cd: ClassDef): List[js.FieldDef] = { - val classSym = cd.symbol - assert(currentClassSym.get == classSym, - "genClassFields called with a ClassDef other than the current one") - - def isStaticBecauseOfTopLevelExport(f: Symbol): Boolean = - jsInterop.registeredExportsOf(f).head.destination == ExportDestination.TopLevel - - // Non-method term members are fields, except for module members. - (for { - f <- classSym.info.decls - if !f.isMethod && f.isTerm && !f.isModule - if !f.hasAnnotation(JSOptionalAnnotation) - static = jsInterop.isFieldStatic(f) - if !static || isStaticBecauseOfTopLevelExport(f) - } yield { - implicit val pos = f.pos - - val mutable = { - static || // static fields must always be mutable - suspectFieldMutable(f) || unexpectedMutatedFields.contains(f) - } - - val name = - if (isExposed(f)) genPropertyName(jsNameOf(f)) - else encodeFieldSym(f) - - val irTpe = { - if (isScalaJSDefinedJSClass(classSym)) genExposedFieldIRType(f) - else if (static) jstpe.AnyType - else toIRType(f.tpe) - } - - js.FieldDef(static, name, irTpe, mutable) - }).toList - } - - def genExposedFieldIRType(f: Symbol): jstpe.Type = { - val tpeEnteringPosterasure = - enteringPhase(currentRun.posterasurePhase)(f.tpe) - tpeEnteringPosterasure match { - case tpe: ErasedValueType => - /* Here, we must store the field as the boxed representation of - * the value class. The default value of that field, as - * initialized at the time the instance is created, will - * therefore be null. This will not match the behavior we would - * get in a Scala class. To match the behavior, we would need to - * initialized to an instance of the boxed representation, with - * an underlying value set to the zero of its type. However we - * cannot implement that, so we live with the discrepancy. - * Anyway, scalac also has problems with uninitialized value - * class values, if they come from a generic context. - */ - jstpe.ClassType(encodeClassFullName(tpe.valueClazz)) - - case _ if f.tpe.typeSymbol == CharClass => - /* Will be initialized to null, which will unbox to '\0' when - * read. - */ - jstpe.ClassType(ir.Definitions.BoxedCharacterClass) - - case _ => - /* Other types are not boxed, so we can initialize them to - * their true zero. - */ - toIRType(f.tpe) - } - } - - // Static initializers ----------------------------------------------------- - - private def genStaticInitializerWithStats(stats: js.Tree)( - implicit pos: Position): js.MethodDef = { - js.MethodDef( - static = true, - js.Ident(ir.Definitions.StaticInitializerName), - Nil, - jstpe.NoType, - Some(stats))( - OptimizerHints.empty, None) - } - - private def genRegisterReflectiveInstantiation(sym: Symbol)( - implicit pos: Position): Option[js.Tree] = { - if (isStaticModule(sym)) - genRegisterReflectiveInstantiationForModuleClass(sym) - else if (sym.isModuleClass) - None // #3228 - else if (sym.isLifted && !sym.originalOwner.isClass) - None // #3227 - else - genRegisterReflectiveInstantiationForNormalClass(sym) - } - - private def genRegisterReflectiveInstantiationForModuleClass(sym: Symbol)( - implicit pos: Position): Option[js.Tree] = { - val fqcnArg = js.StringLiteral(sym.fullName + "$") - val runtimeClassArg = js.ClassOf(toReferenceType(sym.info)) - val loadModuleFunArg = js.Closure(Nil, Nil, genLoadModule(sym), Nil) - - val stat = genApplyMethod( - genLoadModule(ReflectModule), - Reflect_registerLoadableModuleClass, - List(fqcnArg, runtimeClassArg, loadModuleFunArg)) - - Some(stat) - } - - private def genRegisterReflectiveInstantiationForNormalClass(sym: Symbol)( - implicit pos: Position): Option[js.Tree] = { - val ctors = - if (sym.isAbstractClass) Nil - else sym.info.member(nme.CONSTRUCTOR).alternatives.filter(_.isPublic) - - if (ctors.isEmpty) { - None - } else { - val constructorsInfos = for { - ctor <- ctors - } yield { - withNewLocalNameScope { - val (parameterTypes, formalParams, actualParams) = (for { - param <- ctor.tpe.params - } yield { - /* Note that we do *not* use `param.tpe` entering posterasure - * (neither to compute `paramType` nor to give to `fromAny`). - * Logic would tell us that we should do so, but we intentionally - * do not to preserve the behavior on the JVM regarding value - * classes. If a constructor takes a value class as parameter, as - * in: - * - * class ValueClass(val underlying: Int) extends AnyVal - * class Foo(val vc: ValueClass) - * - * then, from a reflection point of view, on the JVM, the - * constructor of `Foo` takes an `Int`, not a `ValueClas`. It - * must therefore be identified as the constructor whose - * parameter types is `List(classOf[Int])`, and when invoked - * reflectively, it must be given an `Int` (or `Integer`). - */ - val paramType = js.ClassOf(toReferenceType(param.tpe)) - val paramDef = js.ParamDef(encodeLocalSym(param), jstpe.AnyType, - mutable = false, rest = false) - val actualParam = fromAny(paramDef.ref, param.tpe) - (paramType, paramDef, actualParam) - }).unzip3 - - val paramTypesArray = js.JSArrayConstr(parameterTypes) - - val newInstanceFun = js.Closure(Nil, formalParams, { - genNew(sym, ctor, actualParams) - }, Nil) - - js.JSArrayConstr(List(paramTypesArray, newInstanceFun)) - } - } - - val fqcnArg = js.StringLiteral(sym.fullName) - val runtimeClassArg = js.ClassOf(toReferenceType(sym.info)) - val ctorsInfosArg = js.JSArrayConstr(constructorsInfos) - - val stat = genApplyMethod( - genLoadModule(ReflectModule), - Reflect_registerInstantiatableClass, - List(fqcnArg, runtimeClassArg, ctorsInfosArg)) - - Some(stat) - } - } - - // Constructor of a Scala.js-defined JS class ------------------------------ - - def genJSClassConstructor(classSym: Symbol, - constructorTrees: List[DefDef]): js.Tree = { - implicit val pos = classSym.pos - - if (hasDefaultCtorArgsAndRawJSModule(classSym)) { - reporter.error(pos, - "Implementation restriction: constructors of " + - "Scala.js-defined JS classes cannot have default parameters " + - "if their companion module is JS native.") - js.Skip() - } else { - withNewLocalNameScope { - val ctors: List[js.MethodDef] = constructorTrees.flatMap { tree => - genMethodWithCurrentLocalNameScope(tree) - } - - val dispatch = - genJSConstructorExport(constructorTrees.map(_.symbol)) - val js.MethodDef(_, dispatchName, dispatchArgs, dispatchResultType, - Some(dispatchResolution)) = dispatch - - val jsConstructorBuilder = mkJSConstructorBuilder(ctors) - - val overloadIdent = freshLocalIdent("overload") - - // Section containing the overload resolution and casts of parameters - val overloadSelection = mkOverloadSelection(jsConstructorBuilder, - overloadIdent, dispatchResolution) - - /* Section containing all the code executed before the call to `this` - * for every secondary constructor. - */ - val prePrimaryCtorBody = - jsConstructorBuilder.mkPrePrimaryCtorBody(overloadIdent) - - val primaryCtorBody = jsConstructorBuilder.primaryCtorBody - - /* Section containing all the code executed after the call to this for - * every secondary constructor. - */ - val postPrimaryCtorBody = - jsConstructorBuilder.mkPostPrimaryCtorBody(overloadIdent) - - val newBody = js.Block(overloadSelection ::: prePrimaryCtorBody :: - primaryCtorBody :: postPrimaryCtorBody :: Nil) - - js.MethodDef(static = false, dispatchName, dispatchArgs, jstpe.NoType, - Some(newBody))(dispatch.optimizerHints, None) - } - } - } - - private class ConstructorTree(val overrideNum: Int, val method: js.MethodDef, - val subConstructors: List[ConstructorTree]) { - - lazy val overrideNumBounds: (Int, Int) = - if (subConstructors.isEmpty) (overrideNum, overrideNum) - else (subConstructors.head.overrideNumBounds._1, overrideNum) - - def get(methodName: String): Option[ConstructorTree] = { - if (methodName == this.method.name.encodedName) { - Some(this) - } else { - subConstructors.iterator.map(_.get(methodName)).collectFirst { - case Some(node) => node - } - } - } - - def getParamRefs(implicit pos: Position): List[js.VarRef] = - method.args.map(_.ref) - - def getAllParamDefsAsVars(implicit pos: Position): List[js.VarDef] = { - val localDefs = method.args.map { pDef => - js.VarDef(pDef.name, pDef.ptpe, mutable = true, jstpe.zeroOf(pDef.ptpe)) - } - localDefs ++ subConstructors.flatMap(_.getAllParamDefsAsVars) - } - } - - private class JSConstructorBuilder(root: ConstructorTree) { - - def primaryCtorBody: js.Tree = root.method.body.getOrElse( - throw new AssertionError("Found abstract constructor")) - - def hasSubConstructors: Boolean = root.subConstructors.nonEmpty - - def getOverrideNum(methodName: String): Int = - root.get(methodName).fold(-1)(_.overrideNum) - - def getParamRefsFor(methodName: String)(implicit pos: Position): List[js.VarRef] = - root.get(methodName).fold(List.empty[js.VarRef])(_.getParamRefs) - - def getAllParamDefsAsVars(implicit pos: Position): List[js.VarDef] = - root.getAllParamDefsAsVars - - def mkPrePrimaryCtorBody(overrideNumIdent: js.Ident)( - implicit pos: Position): js.Tree = { - val overrideNumRef = js.VarRef(overrideNumIdent)(jstpe.IntType) - mkSubPreCalls(root, overrideNumRef) - } - - def mkPostPrimaryCtorBody(overrideNumIdent: js.Ident)( - implicit pos: Position): js.Tree = { - val overrideNumRef = js.VarRef(overrideNumIdent)(jstpe.IntType) - js.Block(mkSubPostCalls(root, overrideNumRef)) - } - - private def mkSubPreCalls(constructorTree: ConstructorTree, - overrideNumRef: js.VarRef)(implicit pos: Position): js.Tree = { - val overrideNumss = constructorTree.subConstructors.map(_.overrideNumBounds) - val paramRefs = constructorTree.getParamRefs - val bodies = constructorTree.subConstructors.map { constructorTree => - mkPrePrimaryCtorBodyOnSndCtr(constructorTree, overrideNumRef, paramRefs) - } - overrideNumss.zip(bodies).foldRight[js.Tree](js.Skip()) { - case ((numBounds, body), acc) => - val cond = mkOverrideNumsCond(overrideNumRef, numBounds) - js.If(cond, body, acc)(jstpe.BooleanType) - } - } - - private def mkPrePrimaryCtorBodyOnSndCtr(constructorTree: ConstructorTree, - overrideNumRef: js.VarRef, outputParams: List[js.VarRef])( - implicit pos: Position): js.Tree = { - val subCalls = - mkSubPreCalls(constructorTree, overrideNumRef) - - val preSuperCall = { - def checkForUndefinedParams(args: List[js.Tree]): List[js.Tree] = { - if (!args.exists(_.isInstanceOf[js.UndefinedParam])) { - args - } else { - /* If we find an undefined param here, we're in trouble, because - * the handling of a default param for the target constructor has - * already been done during overload resolution. If we store an - * `undefined` now, it will fall through without being properly - * processed. - * - * Since this seems very tricky to deal with, and a pretty rare - * use case (with a workaround), we emit an "implementation - * restriction" error. - */ - reporter.error(pos, - "Implementation restriction: in a JS class, a secondary " + - "constructor calling another constructor with default " + - "parameters must provide the values of all parameters.") - - /* Replace undefined params by undefined to prevent subsequent - * compiler crashes. - */ - args.map { - case arg: js.UndefinedParam => - js.Undefined()(arg.pos) - case arg => - arg - } - } - } - - constructorTree.method.body.get match { - case js.Block(stats) => - val beforeSuperCall = stats.takeWhile { - case js.ApplyStatic(_, mtd, _) => !ir.Definitions.isConstructorName(mtd.name) - case _ => true - } - val superCallParams = stats.collectFirst { - case js.ApplyStatic(_, mtd, js.This() :: args) - if ir.Definitions.isConstructorName(mtd.name) => - val checkedArgs = checkForUndefinedParams(args) - zipMap(outputParams, checkedArgs)(js.Assign(_, _)) - }.getOrElse(Nil) - - beforeSuperCall ::: superCallParams - - case js.ApplyStatic(_, mtd, js.This() :: args) - if ir.Definitions.isConstructorName(mtd.name) => - val checkedArgs = checkForUndefinedParams(args) - zipMap(outputParams, checkedArgs)(js.Assign(_, _)) - - case _ => Nil - } - } - - js.Block(subCalls :: preSuperCall) - } - - private def mkSubPostCalls(constructorTree: ConstructorTree, - overrideNumRef: js.VarRef)(implicit pos: Position): js.Tree = { - val overrideNumss = constructorTree.subConstructors.map(_.overrideNumBounds) - val bodies = constructorTree.subConstructors.map { ct => - mkPostPrimaryCtorBodyOnSndCtr(ct, overrideNumRef) - } - overrideNumss.zip(bodies).foldRight[js.Tree](js.Skip()) { - case ((numBounds, js.Skip()), acc) => acc - - case ((numBounds, body), acc) => - val cond = mkOverrideNumsCond(overrideNumRef, numBounds) - js.If(cond, body, acc)(jstpe.BooleanType) - } - } - - private def mkPostPrimaryCtorBodyOnSndCtr(constructorTree: ConstructorTree, - overrideNumRef: js.VarRef)(implicit pos: Position): js.Tree = { - val postSuperCall = { - constructorTree.method.body.get match { - case js.Block(stats) => - stats.dropWhile { - case js.ApplyStatic(_, mtd, _) => !ir.Definitions.isConstructorName(mtd.name) - case _ => true - }.tail - - case _ => Nil - } - } - js.Block(postSuperCall :+ mkSubPostCalls(constructorTree, overrideNumRef)) - } - - private def mkOverrideNumsCond(numRef: js.VarRef, - numBounds: (Int, Int))(implicit pos: Position) = numBounds match { - case (lo, hi) if lo == hi => - js.BinaryOp(js.BinaryOp.===, js.IntLiteral(lo), numRef) - - case (lo, hi) if lo == hi - 1 => - val lhs = js.BinaryOp(js.BinaryOp.===, numRef, js.IntLiteral(lo)) - val rhs = js.BinaryOp(js.BinaryOp.===, numRef, js.IntLiteral(hi)) - js.If(lhs, js.BooleanLiteral(true), rhs)(jstpe.BooleanType) - - case (lo, hi) => - val lhs = js.BinaryOp(js.BinaryOp.Num_<=, js.IntLiteral(lo), numRef) - val rhs = js.BinaryOp(js.BinaryOp.Num_<=, numRef, js.IntLiteral(hi)) - js.BinaryOp(js.BinaryOp.Boolean_&, lhs, rhs) - js.If(lhs, rhs, js.BooleanLiteral(false))(jstpe.BooleanType) - } - } - - private def zipMap[T, U, V](xs: List[T], ys: List[U])( - f: (T, U) => V): List[V] = { - for ((x, y) <- xs zip ys) yield f(x, y) - } - - /** mkOverloadSelection return a list of `stats` with that starts with: - * 1) The definition for the local variable that will hold the overload - * resolution number. - * 2) The definitions of all local variables that are used as parameters - * in all the constructors. - * 3) The overload resolution match/if statements. For each overload the - * overload number is assigned and the parameters are cast and assigned - * to their corresponding variables. - */ - private def mkOverloadSelection(jsConstructorBuilder: JSConstructorBuilder, - overloadIdent: js.Ident, dispatchResolution: js.Tree)( - implicit pos: Position): List[js.Tree] = { - - def deconstructApplyCtor(body: js.Tree): (List[js.Tree], String, List[js.Tree]) = { - val (prepStats, applyCtor) = body match { - case applyCtor: js.ApplyStatic => - (Nil, applyCtor) - case js.Block(prepStats :+ (applyCtor: js.ApplyStatic)) => - (prepStats, applyCtor) - } - val js.ApplyStatic(_, js.Ident(ctorName, _), js.This() :: ctorArgs) = - applyCtor - assert(ir.Definitions.isConstructorName(ctorName), - s"unexpected super constructor call to non-constructor $ctorName at ${applyCtor.pos}") - (prepStats, ctorName, ctorArgs) - } - - if (!jsConstructorBuilder.hasSubConstructors) { - val (prepStats, ctorName, ctorArgs) = - deconstructApplyCtor(dispatchResolution) - - val refs = jsConstructorBuilder.getParamRefsFor(ctorName) - assert(refs.size == ctorArgs.size, currentClassSym.fullName) - val assignCtorParams = zipMap(refs, ctorArgs) { (ref, ctorArg) => - js.VarDef(ref.ident, ref.tpe, mutable = false, ctorArg) - } - - prepStats ::: assignCtorParams - } else { - val overloadRef = js.VarRef(overloadIdent)(jstpe.IntType) - - /* transformDispatch takes the body of the method generated by - * `genJSConstructorExport` and transform it recursively. - */ - def transformDispatch(tree: js.Tree): js.Tree = tree match { - // Parameter count resolution - case js.Match(selector, cases, default) => - val newCases = cases.map { - case (literals, body) => (literals, transformDispatch(body)) - } - val newDefault = transformDispatch(default) - js.Match(selector, newCases, newDefault)(tree.tpe) - - // Parameter type resolution - case js.If(cond, thenp, elsep) => - js.If(cond, transformDispatch(thenp), - transformDispatch(elsep))(tree.tpe) - - // Throw(StringLiteral(No matching overload)) - case tree: js.Throw => - tree - - // Overload resolution done, apply the constructor - case _ => - val (prepStats, ctorName, ctorArgs) = deconstructApplyCtor(tree) - - val num = jsConstructorBuilder.getOverrideNum(ctorName) - val overloadAssign = js.Assign(overloadRef, js.IntLiteral(num)) - - val refs = jsConstructorBuilder.getParamRefsFor(ctorName) - assert(refs.size == ctorArgs.size, currentClassSym.fullName) - val assignCtorParams = zipMap(refs, ctorArgs)(js.Assign(_, _)) - - js.Block(overloadAssign :: prepStats ::: assignCtorParams) - } - - val newDispatchResolution = transformDispatch(dispatchResolution) - val allParamDefsAsVars = jsConstructorBuilder.getAllParamDefsAsVars - val overrideNumDef = - js.VarDef(overloadIdent, jstpe.IntType, mutable = true, js.IntLiteral(0)) - - overrideNumDef :: allParamDefsAsVars ::: newDispatchResolution :: Nil - } - } - - private def mkJSConstructorBuilder(ctors: List[js.MethodDef])( - implicit pos: Position): JSConstructorBuilder = { - def findCtorForwarderCall(tree: js.Tree): String = tree match { - case js.ApplyStatic(_, method, js.This() :: _) - if ir.Definitions.isConstructorName(method.name) => - method.name - - case js.Block(stats) => - stats.collectFirst { - case js.ApplyStatic(_, method, js.This() :: _) - if ir.Definitions.isConstructorName(method.name) => - method.name - }.get - } - - val (primaryCtor :: Nil, secondaryCtors) = ctors.partition { - _.body.get match { - case js.Block(stats) => - stats.exists(_.isInstanceOf[js.JSSuperConstructorCall]) - - case _: js.JSSuperConstructorCall => true - case _ => false - } - } - - val ctorToChildren = secondaryCtors.map { ctor => - findCtorForwarderCall(ctor.body.get) -> ctor - }.groupBy(_._1).map(kv => kv._1 -> kv._2.map(_._2)).withDefaultValue(Nil) - - var overrideNum = -1 - def mkConstructorTree(method: js.MethodDef): ConstructorTree = { - val methodName = method.name.encodedName - val subCtrTrees = ctorToChildren(methodName).map(mkConstructorTree) - overrideNum += 1 - new ConstructorTree(overrideNum, method, subCtrTrees) - } - - new JSConstructorBuilder(mkConstructorTree(primaryCtor)) - } - - // Generate a method ------------------------------------------------------- - - def genMethod(dd: DefDef): Option[js.MethodDef] = { - withNewLocalNameScope { - genMethodWithCurrentLocalNameScope(dd) - } - } - - /** Gen JS code for a method definition in a class or in an impl class. - * On the JS side, method names are mangled to encode the full signature - * of the Scala method, as described in `JSEncoding`, to support - * overloading. - * - * Some methods are not emitted at all: - * * Primitives, since they are never actually called (with exceptions) - * * Abstract methods - * * Constructors of hijacked classes - * * Methods with the {{{@JavaDefaultMethod}}} annotation mixed in classes. - * - * Constructors are emitted by generating their body as a statement. - * - * Interface methods with the {{{@JavaDefaultMethod}}} annotation produce - * default methods forwarding to the trait impl class method. - * - * Other (normal) methods are emitted with `genMethodDef()`. - */ - def genMethodWithCurrentLocalNameScope(dd: DefDef): Option[js.MethodDef] = { - implicit val pos = dd.pos - val DefDef(mods, name, _, vparamss, _, rhs) = dd - val sym = dd.symbol - - withScopedVars( - currentMethodSym := sym, - thisLocalVarIdent := None, - fakeTailJumpParamRepl := (NoSymbol, NoSymbol), - enclosingLabelDefParams := Map.empty, - isModuleInitialized := new VarBox(false), - countsOfReturnsToMatchCase := mutable.Map.empty, - countsOfReturnsToMatchEnd := mutable.Map.empty, - undefinedDefaultParams := mutable.Set.empty - ) { - assert(vparamss.isEmpty || vparamss.tail.isEmpty, - "Malformed parameter list: " + vparamss) - val params = if (vparamss.isEmpty) Nil else vparamss.head map (_.symbol) - - val isJSClassConstructor = - sym.isClassConstructor && isScalaJSDefinedJSClass(currentClassSym) - - val methodName: js.PropertyName = encodeMethodSym(sym) - - def jsParams = for (param <- params) yield { - implicit val pos = param.pos - js.ParamDef(encodeLocalSym(param), toIRType(param.tpe), - mutable = false, rest = false) - } - - if (scalaPrimitives.isPrimitive(sym) && - !jsPrimitives.shouldEmitPrimitiveBody(sym)) { - None - } else if (isAbstractMethod(dd)) { - val body = if (scalaUsesImplClasses && - sym.hasAnnotation(JavaDefaultMethodAnnotation)) { - /* For an interface method with @JavaDefaultMethod, make it a - * default method calling the impl class method. - */ - val implClassSym = sym.owner.implClass - val implMethodSym = implClassSym.info.member(sym.name).suchThat { s => - s.isMethod && - s.tpe.params.size == sym.tpe.params.size + 1 && - s.tpe.params.head.tpe =:= sym.owner.toTypeConstructor && - s.tpe.params.tail.zip(sym.tpe.params).forall { - case (sParam, symParam) => - sParam.tpe =:= symParam.tpe - } - } - Some(genTraitImplApply(implMethodSym, - js.This()(currentClassType) :: jsParams.map(_.ref))) - } else { - None - } - Some(js.MethodDef(static = false, methodName, - jsParams, toIRType(sym.tpe.resultType), body)( - OptimizerHints.empty, None)) - } else if (isJSNativeCtorDefaultParam(sym)) { - None - } else if (sym.isClassConstructor && isHijackedBoxedClass(sym.owner)) { - None - } else if (scalaUsesImplClasses && !isImplClass(sym.owner) && - sym.hasAnnotation(JavaDefaultMethodAnnotation)) { - // Do not emit trait impl forwarders with @JavaDefaultMethod - None - } else { - withScopedVars( - mutableLocalVars := mutable.Set.empty, - mutatedLocalVars := mutable.Set.empty - ) { - def isTraitImplForwarder = dd.rhs match { - case app: Apply => isImplClass(app.symbol.owner) - case _ => false - } - - val shouldMarkInline = { - sym.hasAnnotation(InlineAnnotationClass) || - sym.name.startsWith(nme.ANON_FUN_NAME) || - adHocInlineMethods.contains(sym.fullName) - } - - val shouldMarkNoinline = { - sym.hasAnnotation(NoinlineAnnotationClass) && - !isTraitImplForwarder && - !ignoreNoinlineAnnotation(sym) - } - - val optimizerHints = - OptimizerHints.empty. - withInline(shouldMarkInline). - withNoinline(shouldMarkNoinline) - - val methodDef = { - if (isJSClassConstructor) { - val body0 = genStat(rhs) - val body1 = - if (!sym.isPrimaryConstructor) body0 - else moveAllStatementsAfterSuperConstructorCall(body0) - js.MethodDef(static = false, methodName, - jsParams, jstpe.NoType, Some(body1))(optimizerHints, None) - } else if (sym.isClassConstructor) { - js.MethodDef(static = false, methodName, - jsParams, jstpe.NoType, - Some(genStat(rhs)))(optimizerHints, None) - } else { - val resultIRType = toIRType(sym.tpe.resultType) - genMethodDef(static = isImplClass(sym.owner), methodName, - params, resultIRType, rhs, optimizerHints) - } - } - - val methodDefWithoutUselessVars = { - val unmutatedMutableLocalVars = - (mutableLocalVars.diff(mutatedLocalVars)).toList - val mutatedImmutableLocalVals = - (mutatedLocalVars.diff(mutableLocalVars)).toList - if (unmutatedMutableLocalVars.isEmpty && - mutatedImmutableLocalVals.isEmpty) { - // OK, we're good (common case) - methodDef - } else { - val patches = ( - unmutatedMutableLocalVars.map(encodeLocalSym(_).name -> false) ::: - mutatedImmutableLocalVals.map(encodeLocalSym(_).name -> true) - ).toMap - patchMutableFlagOfLocals(methodDef, patches) - } - } - - Some(methodDefWithoutUselessVars) - } - } - } - } - - def isAbstractMethod(dd: DefDef): Boolean = { - /* When scalac uses impl classes, we cannot trust `rhs` to be - * `EmptyTree` for deferred methods (probably due to an internal bug - * of scalac), as can be seen in run/t6443.scala. - * However, when it does not use impl class anymore, we have to use - * `rhs == EmptyTree` as predicate, just like the JVM back-end does. - */ - if (scalaUsesImplClasses) - dd.symbol.isDeferred || dd.symbol.owner.isInterface - else - dd.rhs == EmptyTree - } - - private val adHocInlineMethods = Set( - "scala.collection.mutable.ArrayOps$ofRef.newBuilder$extension", - "scala.runtime.ScalaRunTime.arrayClass", - "scala.runtime.ScalaRunTime.arrayElementClass" - ) - - /** Patches the mutable flags of selected locals in a [[js.MethodDef]]. - * - * @param patches Map from local name to new value of the mutable flags. - * For locals not in the map, the flag is untouched. - */ - private def patchMutableFlagOfLocals(methodDef: js.MethodDef, - patches: Map[String, Boolean]): js.MethodDef = { - - def newMutable(name: String, oldMutable: Boolean): Boolean = - patches.getOrElse(name, oldMutable) - - val js.MethodDef(static, methodName, params, resultType, body) = methodDef - val newParams = for { - p @ js.ParamDef(name, ptpe, mutable, rest) <- params - } yield { - js.ParamDef(name, ptpe, newMutable(name.name, mutable), rest)(p.pos) - } - val transformer = new ir.Transformers.Transformer { - override def transform(tree: js.Tree, isStat: Boolean): js.Tree = tree match { - case js.VarDef(name, vtpe, mutable, rhs) => - assert(isStat, s"found a VarDef in expression position at ${tree.pos}") - super.transform(js.VarDef( - name, vtpe, newMutable(name.name, mutable), rhs)(tree.pos), isStat) - case js.Closure(captureParams, params, body, captureValues) => - js.Closure(captureParams, params, body, - captureValues.map(transformExpr))(tree.pos) - case _ => - super.transform(tree, isStat) - } - } - val newBody = body.map( - b => transformer.transform(b, isStat = resultType == jstpe.NoType)) - js.MethodDef(static, methodName, newParams, resultType, - newBody)(methodDef.optimizerHints, None)(methodDef.pos) - } - - /** Moves all statements after the super constructor call. - * - * This is used for the primary constructor of a Scala.js-defined JS - * class, because those cannot access `this` before the super constructor - * call. - * - * scalac inserts statements before the super constructor call for early - * initializers and param accessor initializers (including val's and var's - * declared in the params). We move those after the super constructor - * call, and are therefore executed later than for a Scala class. - */ - private def moveAllStatementsAfterSuperConstructorCall( - body: js.Tree): js.Tree = { - val bodyStats = body match { - case js.Block(stats) => stats - case _ => body :: Nil - } - - val (beforeSuper, superCall :: afterSuper) = - bodyStats.span(!_.isInstanceOf[js.JSSuperConstructorCall]) - - assert(!beforeSuper.exists(_.isInstanceOf[js.VarDef]), - "Trying to move a local VarDef after the super constructor call " + - "of a Scala.js-defined JS class at ${body.pos}") - - js.Block( - superCall :: - beforeSuper ::: - afterSuper)(body.pos) - } - - /** Generates the MethodDef of a (non-constructor) method - * - * Most normal methods are emitted straightforwardly. If the result - * type is Unit, then the body is emitted as a statement. Otherwise, it is - * emitted as an expression. - * - * The additional complexity of this method handles the transformation of - * a peculiarity of recursive tail calls: the local ValDef that replaces - * `this`. - */ - def genMethodDef(static: Boolean, methodName: js.PropertyName, - paramsSyms: List[Symbol], resultIRType: jstpe.Type, - tree: Tree, optimizerHints: OptimizerHints): js.MethodDef = { - implicit val pos = tree.pos - - val jsParams = for (param <- paramsSyms) yield { - implicit val pos = param.pos - js.ParamDef(encodeLocalSym(param), toIRType(param.tpe), - mutable = false, rest = false) - } - - val bodyIsStat = resultIRType == jstpe.NoType - - def genBody() = tree match { - case Block( - (thisDef @ ValDef(_, nme.THIS, _, initialThis)) :: otherStats, - rhs) => - // This method has tail jumps - - // To be called from within withScopedVars - def genInnerBody() = { - js.Block(otherStats.map(genStat) :+ ( - if (bodyIsStat) genStat(rhs) - else genExpr(rhs))) - } - - initialThis match { - case Ident(_) => - /* This case happens in trait implementation classes, until - * Scala 2.11. In the method, all usages of `this` have been - * replaced by the method's formal parameter `$this`. However, - * there is still a declaration of the pseudo local variable - * `_$this`, which is used in the param list of the label. We - * need to remember it now, so that when we build the JS version - * of the formal params for the label, we can redirect the - * assignment to `$this` instead of the otherwise unused - * `_$this`. - */ - withScopedVars( - fakeTailJumpParamRepl := (thisDef.symbol, initialThis.symbol) - ) { - genInnerBody() - } - - case _ => - val thisSym = thisDef.symbol - if (thisSym.isMutable) - mutableLocalVars += thisSym - - val thisLocalIdent = encodeLocalSym(thisSym) - val thisLocalType = currentClassType - - val genRhs = { - /* #3267 In default methods, scalac will type its _$this - * pseudo-variable as the *self-type* of the enclosing class, - * instead of the enclosing class type itself. However, it then - * considers *usages* of _$this as if its type were the - * enclosing class type. The latter makes sense, since it is - * compiled as `this` in the bytecode, which necessarily needs - * to be the enclosing class type. Only the declared type of - * _$this is wrong. - * - * In our case, since we generate an actual local variable for - * _$this, we must make sure to type it correctly, as the - * enclosing class type. However, this means the rhs of the - * ValDef does not match, which is why we have to adapt it - * here. - */ - forceAdapt(genExpr(initialThis), thisLocalType) - } - - val thisLocalVarDef = js.VarDef(thisLocalIdent, - thisLocalType, thisSym.isMutable, genRhs) - - val innerBody = { - withScopedVars( - thisLocalVarIdent := Some(thisLocalIdent) - ) { - genInnerBody() - } - } - - js.Block(thisLocalVarDef, innerBody) - } - - case _ => - if (bodyIsStat) genStat(tree) - else genExpr(tree) - } - - if (!isScalaJSDefinedJSClass(currentClassSym)) { - js.MethodDef(static, methodName, jsParams, resultIRType, - Some(genBody()))(optimizerHints, None) - } else { - assert(!static, tree.pos) - - val thisLocalIdent = freshLocalIdent("this") - withScopedVars( - thisLocalVarIdent := Some(thisLocalIdent) - ) { - val thisParamDef = js.ParamDef(thisLocalIdent, - jstpe.AnyType, mutable = false, rest = false) - - js.MethodDef(static = true, methodName, thisParamDef :: jsParams, - resultIRType, Some(genBody()))( - optimizerHints, None) - } - } - } - - /** Forces the given `tree` to a given type by adapting it. - * - * @param tree - * The tree to adapt. - * @param tpe - * The target type, which must be either `AnyType` or `ClassType(_)`. - */ - private def forceAdapt(tree: js.Tree, tpe: jstpe.Type): js.Tree = { - if (tree.tpe == tpe || tpe == jstpe.AnyType) { - tree - } else { - /* Remove the useless cast that scalac's erasure had to introduce to - * work around their own ill-typed _$this. Note that the optimizer will - * not be able to do that, since it won't be able to prove that the - * underlying expression is indeed an instance of `tpe`. - */ - tree match { - case js.AsInstanceOf(underlying, _) if underlying.tpe == tpe => - underlying - case _ => - js.AsInstanceOf(tree, tpe.asInstanceOf[jstpe.ClassType])(tree.pos) - } - } - } - - /** Gen JS code for a tree in statement position (in the IR). - */ - def genStat(tree: Tree): js.Tree = { - exprToStat(genStatOrExpr(tree, isStat = true)) - } - - /** Turn a JavaScript expression of type Unit into a statement */ - def exprToStat(tree: js.Tree): js.Tree = { - /* Any JavaScript expression is also a statement, but at least we get rid - * of some pure expressions that come from our own codegen. - */ - implicit val pos = tree.pos - tree match { - case js.Block(stats :+ expr) => js.Block(stats :+ exprToStat(expr)) - case _:js.Literal | js.This() => js.Skip() - case _ => tree - } - } - - /** Gen JS code for a tree in expression position (in the IR). - */ - def genExpr(tree: Tree): js.Tree = { - val result = genStatOrExpr(tree, isStat = false) - assert(result.tpe != jstpe.NoType, - s"genExpr($tree) returned a tree with type NoType at pos ${tree.pos}") - result - } - - /** Gen JS code for a tree in statement or expression position (in the IR). - * - * This is the main transformation method. Each node of the Scala AST - * is transformed into an equivalent portion of the JS AST. - */ - def genStatOrExpr(tree: Tree, isStat: Boolean): js.Tree = { - implicit val pos = tree.pos - - tree match { - /** LabelDefs (for while and do..while loops) */ - case lblDf: LabelDef => - genLabelDef(lblDf) - - /** Local val or var declaration */ - case ValDef(_, name, _, rhs) => - /* Must have been eliminated by the tail call transform performed - * by genMethodDef(). - * If you ever change/remove this assertion, you need to update - * genEnclosingLabelApply() regarding `nme.THIS`. - */ - assert(name != nme.THIS, - s"ValDef(_, nme.THIS, _, _) found at ${tree.pos}") - - val sym = tree.symbol - val rhsTree = - if (rhs == EmptyTree) genZeroOf(sym.tpe) - else genExpr(rhs) - - rhsTree match { - case js.UndefinedParam() => - // This is an intermediate assignment for default params on a - // js.Any. Add the symbol to the corresponding set to inform - // the Ident resolver how to replace it and don't emit the symbol - undefinedDefaultParams += sym - js.Skip() - case _ => - if (sym.isMutable) - mutableLocalVars += sym - js.VarDef(encodeLocalSym(sym), - toIRType(sym.tpe), sym.isMutable, rhsTree) - } - - case If(cond, thenp, elsep) => - js.If(genExpr(cond), genStatOrExpr(thenp, isStat), - genStatOrExpr(elsep, isStat))(toIRType(tree.tpe)) - - case Return(expr) => - js.Return(toIRType(expr.tpe) match { - case jstpe.NoType => js.Block(genStat(expr), js.Undefined()) - case _ => genExpr(expr) - }) - - case t: Try => - genTry(t, isStat) - - case Throw(expr) => - val ex = genExpr(expr) - js.Throw { - if (isMaybeJavaScriptException(expr.tpe)) { - genApplyMethod( - genLoadModule(RuntimePackageModule), - Runtime_unwrapJavaScriptException, - List(ex)) - } else { - ex - } - } - - /* !!! Copy-pasted from `CleanUp.scala` upstream and simplified with - * our `WrapArray` extractor. - * - * Replaces `Array(Predef.wrapArray(ArrayValue(...).$asInstanceOf[...]), )` - * with just `ArrayValue(...)` - * - * See scala/bug#6611; we must *only* do this for literal vararg arrays. - * - * This is normally done by `cleanup` but it comes later than this phase. - */ - case Apply(appMeth, Apply(wrapRefArrayMeth, StripCast(arg @ ArrayValue(_, _)) :: Nil) :: _ :: Nil) - if wrapRefArrayMeth.symbol == WrapArray.wrapRefArrayMethod && appMeth.symbol == ArrayModule_genericApply => - genArrayValue(arg) - case Apply(appMeth, elem0 :: WrapArray(rest @ ArrayValue(elemtpt, _)) :: Nil) - if appMeth.symbol == ArrayModule_apply(elemtpt.tpe) => - genArrayValue(rest, elem0 :: rest.elems) - case Apply(appMeth, elem :: (nil: RefTree) :: Nil) - if nil.symbol == NilModule && appMeth.symbol == ArrayModule_apply(elem.tpe.widen) && - treeInfo.isExprSafeToInline(nil) => - genArrayValue(tree, elem :: Nil) - - case app: Apply => - genApply(app, isStat) - - case app: ApplyDynamic => - genApplyDynamic(app) - - case This(qual) => - if (tree.symbol == currentClassSym.get) { - genThis() - } else { - assert(tree.symbol.isModuleClass, - "Trying to access the this of another class: " + - "tree.symbol = " + tree.symbol + - ", class symbol = " + currentClassSym.get + - " compilation unit:" + currentUnit) - genLoadModule(tree.symbol) - } - - case Select(qualifier, selector) => - val sym = tree.symbol - - def unboxFieldValue(boxed: js.Tree): js.Tree = { - fromAny(boxed, - enteringPhase(currentRun.posterasurePhase)(sym.tpe)) - } - - if (sym.isModule) { - assert(!sym.isPackageClass, "Cannot use package as value: " + tree) - genLoadModule(sym) - } else if (sym.isStaticMember) { - genStaticMember(sym) - } else if (paramAccessorLocals contains sym) { - paramAccessorLocals(sym).ref - } else if (isScalaJSDefinedJSClass(sym.owner)) { - val genQual = genExpr(qualifier) - val boxed = if (isExposed(sym)) - js.JSBracketSelect(genQual, genExpr(jsNameOf(sym))) - else - js.JSDotSelect(genQual, encodeFieldSym(sym)) - unboxFieldValue(boxed) - } else if (jsInterop.isFieldStatic(sym)) { - unboxFieldValue(genSelectStaticFieldAsBoxed(sym)) - } else { - js.Select(genExpr(qualifier), - encodeFieldSym(sym))(toIRType(sym.tpe)) - } - - case Ident(name) => - val sym = tree.symbol - if (!sym.hasPackageFlag) { - if (sym.isModule) { - assert(!sym.isPackageClass, "Cannot use package as value: " + tree) - genLoadModule(sym) - } else if (undefinedDefaultParams contains sym) { - // This is a default parameter whose assignment was moved to - // a local variable. Put a literal undefined param again - js.UndefinedParam()(toIRType(sym.tpe)) - } else { - js.VarRef(encodeLocalSym(sym))(toIRType(sym.tpe)) - } - } else { - abort("Cannot use package as value: " + tree) - } - - case Literal(value) => - value.tag match { - case UnitTag => - js.Skip() - case BooleanTag => - js.BooleanLiteral(value.booleanValue) - case ByteTag | ShortTag | CharTag | IntTag => - js.IntLiteral(value.intValue) - case LongTag => - js.LongLiteral(value.longValue) - case FloatTag => - js.FloatLiteral(value.floatValue) - case DoubleTag => - js.DoubleLiteral(value.doubleValue) - case StringTag => - js.StringLiteral(value.stringValue) - case NullTag => - js.Null() - case ClazzTag => - js.ClassOf(toReferenceType(value.typeValue)) - case EnumTag => - genStaticMember(value.symbolValue) - } - - case tree: Block => - genBlock(tree, isStat) - - case Typed(Super(_, _), _) => - genThis() - - case Typed(expr, _) => - genExpr(expr) - - case Assign(lhs, rhs) => - val sym = lhs.symbol - if (sym.isStaticMember) - abort(s"Assignment to static member ${sym.fullName} not supported") - val genRhs = genExpr(rhs) - lhs match { - case Select(qualifier, _) => - val ctorAssignment = ( - currentMethodSym.isClassConstructor && - currentMethodSym.owner == qualifier.symbol && - qualifier.isInstanceOf[This] - ) - if (!ctorAssignment && !suspectFieldMutable(sym)) - unexpectedMutatedFields += sym - - val genQual = genExpr(qualifier) - - def genBoxedRhs: js.Tree = { - val tpeEnteringPosterasure = - enteringPhase(currentRun.posterasurePhase)(rhs.tpe) - if ((tpeEnteringPosterasure eq null) && genRhs.isInstanceOf[js.Null]) { - devWarning( - "Working around https://github.com/scala-js/scala-js/issues/3422 " + - s"for ${sym.fullName} at ${sym.pos}") - // Fortunately, a literal `null` never needs to be boxed - genRhs - } else { - ensureBoxed(genRhs, tpeEnteringPosterasure) - } - } - - if (isScalaJSDefinedJSClass(sym.owner)) { - val genLhs = if (isExposed(sym)) - js.JSBracketSelect(genQual, genExpr(jsNameOf(sym))) - else - js.JSDotSelect(genQual, encodeFieldSym(sym)) - js.Assign(genLhs, genBoxedRhs) - } else if (jsInterop.isFieldStatic(sym)) { - js.Assign(genSelectStaticFieldAsBoxed(sym), genBoxedRhs) - } else { - js.Assign( - js.Select(genQual, encodeFieldSym(sym))(toIRType(sym.tpe)), - genRhs) - } - case _ => - mutatedLocalVars += sym - js.Assign( - js.VarRef(encodeLocalSym(sym))(toIRType(sym.tpe)), - genRhs) - } - - /** Array constructor */ - case av: ArrayValue => - genArrayValue(av) - - /** A Match reaching the backend is supposed to be optimized as a switch */ - case mtch: Match => - genMatch(mtch, isStat) - - /** Anonymous function (in 2.12, or with -Ydelambdafy:method in 2.11) */ - case fun: Function => - genAnonFunction(fun) - - case EmptyTree => - js.Skip() - - case _ => - abort("Unexpected tree in genExpr: " + - tree + "/" + tree.getClass + " at: " + tree.pos) - } - } // end of GenJSCode.genExpr() - - /** Gen JS this of the current class. - * Normally encoded straightforwardly as a JS this. - * But must be replaced by the tail-jump-this local variable if there - * is one. - */ - private def genThis()(implicit pos: Position): js.Tree = { - thisLocalVarIdent.fold[js.Tree] { - if (tryingToGenMethodAsJSFunction) { - throw new CancelGenMethodAsJSFunction( - "Trying to generate `this` inside the body") - } - js.This()(currentClassType) - } { thisLocalIdent => - // .copy() to get the correct position - js.VarRef(thisLocalIdent.copy())(currentClassType) - } - } - - private def genSelectStaticFieldAsBoxed(sym: Symbol)( - implicit pos: Position): js.Tree = { - val exportInfos = jsInterop.staticFieldInfoOf(sym) - (exportInfos.head.destination: @unchecked) match { - case ExportDestination.TopLevel => - val cls = jstpe.ClassType(encodeClassFullName(sym.owner)) - js.SelectStatic(cls, encodeFieldSym(sym))(jstpe.AnyType) - - case ExportDestination.Static => - val exportInfo = exportInfos.head - val companionClass = patchedLinkedClassOfClass(sym.owner) - js.JSBracketSelect( - genPrimitiveJSClass(companionClass), - js.StringLiteral(exportInfo.jsName)) - } - } - - /** Gen JS code for LabelDef - * The only LabelDefs that can reach here are the desugaring of - * while and do..while loops. All other LabelDefs (for tail calls or - * matches) are caught upstream and transformed in ad hoc ways. - * - * So here we recognize all the possible forms of trees that can result - * of while or do..while loops, and we reconstruct the loop for emission - * to JS. - */ - def genLabelDef(tree: LabelDef): js.Tree = { - implicit val pos = tree.pos - val sym = tree.symbol - - tree match { - // while (cond) { body } - case LabelDef(lname, Nil, - If(cond, - Block(bodyStats, Apply(target @ Ident(lname2), Nil)), - Literal(_))) if (target.symbol == sym) => - js.While(genExpr(cond), js.Block(bodyStats map genStat)) - - // while (cond) { body }; result - case LabelDef(lname, Nil, - Block(List( - If(cond, - Block(bodyStats, Apply(target @ Ident(lname2), Nil)), - Literal(_))), - result)) if (target.symbol == sym) => - js.Block( - js.While(genExpr(cond), js.Block(bodyStats map genStat)), - genExpr(result)) - - // while (true) { body } - case LabelDef(lname, Nil, - Block(bodyStats, - Apply(target @ Ident(lname2), Nil))) if (target.symbol == sym) => - js.While(js.BooleanLiteral(true), js.Block(bodyStats map genStat)) - - // while (false) { body } - case LabelDef(lname, Nil, Literal(Constant(()))) => - js.Skip() - - // do { body } while (cond) - case LabelDef(lname, Nil, - Block(bodyStats, - If(cond, - Apply(target @ Ident(lname2), Nil), - Literal(_)))) if (target.symbol == sym) => - js.DoWhile(js.Block(bodyStats map genStat), genExpr(cond)) - - // do { body } while (cond); result - case LabelDef(lname, Nil, - Block( - bodyStats :+ - If(cond, - Apply(target @ Ident(lname2), Nil), - Literal(_)), - result)) if (target.symbol == sym) => - js.Block( - js.DoWhile(js.Block(bodyStats map genStat), genExpr(cond)), - genExpr(result)) - - /* Arbitrary other label - we can jump to it from inside it. - * This is typically for the label-defs implementing tail-calls. - * It can also handle other weird LabelDefs generated by some compiler - * plugins (see for example #1148). - */ - case LabelDef(labelName, labelParams, rhs) => - val labelParamSyms = labelParams.map(_.symbol) map { - s => if (s == fakeTailJumpParamRepl._1) fakeTailJumpParamRepl._2 else s - } - - withScopedVars( - enclosingLabelDefParams := - enclosingLabelDefParams.get + (tree.symbol -> labelParamSyms) - ) { - val bodyType = toIRType(tree.tpe) - val labelIdent = encodeLabelSym(tree.symbol) - val blockLabelIdent = freshLocalIdent() - - js.Labeled(blockLabelIdent, bodyType, { - js.While(js.BooleanLiteral(true), { - if (bodyType == jstpe.NoType) - js.Block(genStat(rhs), js.Return(js.Undefined(), Some(blockLabelIdent))) - else - js.Return(genExpr(rhs), Some(blockLabelIdent)) - }, Some(labelIdent)) - }) - } - } - } - - /** Gen JS code for a try..catch or try..finally block - * - * try..finally blocks are compiled straightforwardly to try..finally - * blocks of JS. - * - * try..catch blocks are a bit more subtle, as JS does not have - * type-based selection of exceptions to catch. We thus encode explicitly - * the type tests, like in: - * - * try { ... } - * catch (e) { - * if (e.isInstanceOf[IOException]) { ... } - * else if (e.isInstanceOf[Exception]) { ... } - * else { - * throw e; // default, re-throw - * } - * } - */ - def genTry(tree: Try, isStat: Boolean): js.Tree = { - implicit val pos = tree.pos - val Try(block, catches, finalizer) = tree - - val blockAST = genStatOrExpr(block, isStat) - val resultType = toIRType(tree.tpe) - - val handled = - if (catches.isEmpty) blockAST - else genTryCatch(blockAST, catches, resultType, isStat) - - genStat(finalizer) match { - case js.Skip() => handled - case ast => js.TryFinally(handled, ast) - } - } - - private def genTryCatch(body: js.Tree, catches: List[CaseDef], - resultType: jstpe.Type, - isStat: Boolean)(implicit pos: Position): js.Tree = { - val exceptIdent = freshLocalIdent("e") - val origExceptVar = js.VarRef(exceptIdent)(jstpe.AnyType) - - val mightCatchJavaScriptException = catches.exists { caseDef => - caseDef.pat match { - case Typed(Ident(nme.WILDCARD), tpt) => - isMaybeJavaScriptException(tpt.tpe) - case Ident(nme.WILDCARD) => - true - case pat @ Bind(_, _) => - isMaybeJavaScriptException(pat.symbol.tpe) - } - } - - val (exceptValDef, exceptVar) = if (mightCatchJavaScriptException) { - val valDef = js.VarDef(freshLocalIdent("e"), - encodeClassType(ThrowableClass), mutable = false, { - genApplyMethod( - genLoadModule(RuntimePackageModule), - Runtime_wrapJavaScriptException, - List(origExceptVar)) - }) - (valDef, valDef.ref) - } else { - (js.Skip(), origExceptVar) - } - - val elseHandler: js.Tree = js.Throw(origExceptVar) - - val handler = catches.foldRight(elseHandler) { (caseDef, elsep) => - implicit val pos = caseDef.pos - val CaseDef(pat, _, body) = caseDef - - // Extract exception type and variable - val (tpe, boundVar) = (pat match { - case Typed(Ident(nme.WILDCARD), tpt) => - (tpt.tpe, None) - case Ident(nme.WILDCARD) => - (ThrowableClass.tpe, None) - case Bind(_, _) => - (pat.symbol.tpe, Some(encodeLocalSym(pat.symbol))) - }) - - // Generate the body that must be executed if the exception matches - val bodyWithBoundVar = (boundVar match { - case None => - genStatOrExpr(body, isStat) - case Some(bv) => - val castException = genAsInstanceOf(exceptVar, tpe) - js.Block( - js.VarDef(bv, toIRType(tpe), mutable = false, castException), - genStatOrExpr(body, isStat)) - }) - - // Generate the test - if (tpe == ThrowableClass.tpe) { - bodyWithBoundVar - } else { - val cond = genIsInstanceOf(exceptVar, tpe) - js.If(cond, bodyWithBoundVar, elsep)(resultType) - } - } - - js.TryCatch(body, exceptIdent, - js.Block(exceptValDef, handler))(resultType) - } - - /** Gen JS code for an Apply node (method call) - * - * There's a whole bunch of varieties of Apply nodes: regular method - * calls, super calls, constructor calls, isInstanceOf/asInstanceOf, - * primitives, JS calls, etc. They are further dispatched in here. - */ - def genApply(tree: Apply, isStat: Boolean): js.Tree = { - implicit val pos = tree.pos - val Apply(fun, args) = tree - val sym = fun.symbol - - def isRawJSDefaultParam: Boolean = { - if (isCtorDefaultParam(sym)) { - isRawJSCtorDefaultParam(sym) - } else { - sym.hasFlag(reflect.internal.Flags.DEFAULTPARAM) && - isRawJSType(sym.owner.tpe) && { - /* If this is a default parameter accessor on a - * ScalaJSDefinedJSClass, we need to know if the method for which we - * are the default parameter is exposed or not. - * We do this by removing the $default suffix from the method name, - * and looking up a member with that name in the owner. - * Note that this does not work for local methods. But local methods - * are never exposed. - * Further note that overloads are easy, because either all or none - * of them are exposed. - */ - def isAttachedMethodExposed = { - val methodName = nme.defaultGetterToMethod(sym.name) - val ownerMethod = sym.owner.info.decl(methodName) - ownerMethod.filter(isExposed).exists - } - - !isScalaJSDefinedJSClass(sym.owner) || isAttachedMethodExposed - } - } - } - - fun match { - case TypeApply(_, _) => - genApplyTypeApply(tree, isStat) - - case _ if isRawJSDefaultParam => - js.UndefinedParam()(toIRType(sym.tpe.resultType)) - - case Select(Super(_, _), _) => - genSuperCall(tree, isStat) - - case Select(New(_), nme.CONSTRUCTOR) => - genApplyNew(tree) - - case _ => - if (sym.isLabel) { - genLabelApply(tree) - } else if (scalaPrimitives.isPrimitive(sym)) { - genPrimitiveOp(tree, isStat) - } else if (currentRun.runDefinitions.isBox(sym)) { - // Box a primitive value (cannot be Unit) - val arg = args.head - makePrimitiveBox(genExpr(arg), sym.firstParam.tpe) - } else if (currentRun.runDefinitions.isUnbox(sym)) { - // Unbox a primitive value (cannot be Unit) - val arg = args.head - makePrimitiveUnbox(genExpr(arg), tree.tpe) - } else { - genNormalApply(tree, isStat) - } - } - } - - /** Gen an Apply with a TypeApply method. - * - * Until 2.12.0-M5, only `isInstanceOf` and `asInstanceOf` kept their type - * argument until the backend. Since 2.12.0-RC1, `AnyRef.synchronized` - * does so too. - */ - private def genApplyTypeApply(tree: Apply, isStat: Boolean): js.Tree = { - implicit val pos = tree.pos - val Apply(TypeApply(fun @ Select(obj, _), targs), args) = tree - val sym = fun.symbol - - sym match { - case Object_isInstanceOf => - genIsAsInstanceOf(obj, targs, cast = false) - case Object_asInstanceOf => - genIsAsInstanceOf(obj, targs, cast = true) - case Object_synchronized => - genSynchronized(obj, args.head, isStat) - case _ => - abort("Unexpected type application " + fun + - "[sym: " + sym.fullName + "]" + " in: " + tree) - } - } - - /** Gen `isInstanceOf` or `asInstanceOf`. */ - private def genIsAsInstanceOf(obj: Tree, targs: List[Tree], cast: Boolean)( - implicit pos: Position): js.Tree = { - genIsAsInstanceOf(genExpr(obj), obj.tpe, targs.head.tpe, cast) - } - - /** Gen `isInstanceOf` or `asInstanceOf`. */ - private def genIsAsInstanceOf(expr: js.Tree, from: Type, to: Type, - cast: Boolean)( - implicit pos: Position): js.Tree = { - val l = toTypeKind(from) - val r = toTypeKind(to) - - if (l.isValueType && r.isValueType) { - if (cast) - genConversion(l, r, expr) - else - js.BooleanLiteral(l == r) - } else if (l.isValueType) { - val result = if (cast) { - val ctor = ClassCastExceptionClass.info.member( - nme.CONSTRUCTOR).suchThat(_.tpe.params.isEmpty) - js.Throw(genNew(ClassCastExceptionClass, ctor, Nil)) - } else { - js.BooleanLiteral(false) - } - js.Block(expr, result) // eval and discard source - } else if (r.isValueType) { - assert(!cast, s"Unexpected asInstanceOf from ref type to value type") - genIsInstanceOf(expr, boxedClass(to.typeSymbol).tpe) - } else { - if (cast) - genAsInstanceOf(expr, to) - else - genIsInstanceOf(expr, to) - } - } - - /** Gen JS code for a super call, of the form Class.super[mix].fun(args). - * - * This does not include calls defined in mixin traits, as these are - * already desugared by the 'mixin' phase. Only calls to super classes - * remain. - * Since a class has exactly one direct superclass, and calling a method - * two classes above the current one is invalid, the `mix` item is - * irrelevant. - */ - private def genSuperCall(tree: Apply, isStat: Boolean): js.Tree = { - implicit val pos = tree.pos - val Apply(fun @ Select(sup @ Super(qual, _), _), args) = tree - val sym = fun.symbol - - if (isRawJSType(qual.tpe)) { - if (sym.isMixinConstructor) { - /* Do not emit a call to the $init$ method of JS traits. - * This exception is necessary because @JSOptional fields cause the - * creation of a $init$ method, which we must not call. - */ - js.Skip() - } else { - genJSSuperCall(tree, isStat) - } - } else { - /* #3013 `qual` can be `this.$outer()` in some cases since Scala 2.12, - * so we call `genExpr(qual)`, not just `genThis()`. - */ - val superCall = genApplyMethodStatically( - genExpr(qual), sym, genActualArgs(sym, args)) - - // Initialize the module instance just after the super constructor call. - if (isStaticModule(currentClassSym) && !isModuleInitialized.value && - currentMethodSym.isClassConstructor) { - isModuleInitialized.value = true - val thisType = jstpe.ClassType(encodeClassFullName(currentClassSym)) - val initModule = js.StoreModule(thisType, js.This()(thisType)) - js.Block(superCall, initModule) - } else { - superCall - } - } - } - - /** Gen JS code for a constructor call (new). - * Further refined into: - * * new String(...) - * * new of a hijacked boxed class - * * new of an anonymous function class that was recorded as JS function - * * new of a raw JS class - * * new Array - * * regular new - */ - private def genApplyNew(tree: Apply): js.Tree = { - implicit val pos = tree.pos - val Apply(fun @ Select(New(tpt), nme.CONSTRUCTOR), args) = tree - val ctor = fun.symbol - val tpe = tpt.tpe - val clsSym = tpe.typeSymbol - - assert(ctor.isClassConstructor, - "'new' call to non-constructor: " + ctor.name) - - if (isStringType(tpe)) { - genNewString(tree) - } else if (isHijackedBoxedClass(clsSym)) { - genNewHijackedBoxedClass(clsSym, ctor, args map genExpr) - } else if (isRawJSFunctionDef(clsSym)) { - val classDef = consumeLazilyGeneratedAnonClass(clsSym) - genRawJSFunction(classDef, args.map(genExpr)) - } else if (clsSym.isAnonymousFunction) { - val classDef = consumeLazilyGeneratedAnonClass(clsSym) - tryGenAnonFunctionClass(classDef, args.map(genExpr)).getOrElse { - // Cannot optimize anonymous function class. Generate full class. - generatedClasses += - ((clsSym, None, nestedGenerateClass(clsSym)(genClass(classDef)))) - genNew(clsSym, ctor, genActualArgs(ctor, args)) - } - } else if (isRawJSType(tpe)) { - genPrimitiveJSNew(tree) - } else { - toTypeKind(tpe) match { - case arr @ ARRAY(elem) => - genNewArray(arr.toIRType, args map genExpr) - case rt @ REFERENCE(cls) => - genNew(cls, ctor, genActualArgs(ctor, args)) - case generatedType => - abort(s"Non reference type cannot be instantiated: $generatedType") - } - } - } - - /** Gen jump to a label. - * Most label-applys are caught upstream (while and do..while loops, - * jumps to next case of a pattern match), but some are still handled here: - * * Jumps to enclosing label-defs, including tail-recursive calls - * * Jump to the end of a pattern match - */ - private def genLabelApply(tree: Apply): js.Tree = { - implicit val pos = tree.pos - val Apply(fun, args) = tree - val sym = fun.symbol - - if (enclosingLabelDefParams.contains(sym)) { - genEnclosingLabelApply(tree) - } else if (countsOfReturnsToMatchCase.contains(sym)) { - /* Jump the to a next-`case` label of a pattern match. - * - * Such labels are not enclosing. Instead, they are forward jumps to a - * following case LabelDef. For those labels, we generate a js.Return - * and keep track of how many such returns we generate, so that the - * enclosing `genTranslatedMatch` can optimize away the labeled blocks - * in some cases, notably when they are not used at all or used only - * once. - * - * Next-case labels have no argument. - */ - assert(args.isEmpty, tree) - countsOfReturnsToMatchCase(sym) += 1 - js.Return(js.Undefined(), Some(encodeLabelSym(sym))) - } else if (countsOfReturnsToMatchEnd.contains(sym)) { - /* Jump the to the match-end of a pattern match. - * This is similar to the jumps to next-case (see above), except that - * match-end labels hae exactly one argument, which is the result of the - * pattern match (of type BoxedUnit if the match is in statement position). - * We simply `return` the argument as the result of the labeled block - * surrounding the match. - */ - assert(args.size == 1, tree) - countsOfReturnsToMatchEnd(sym) += 1 - js.Return(genExpr(args.head), Some(encodeLabelSym(sym))) - } else { - /* No other label apply should ever happen. If it does, then we - * have missed a pattern of LabelDef/LabelApply and some new - * translation must be found for it. - */ - abort("Found unknown label apply at "+tree.pos+": "+tree) - } - } - - /** Gen a label-apply to an enclosing label def. - * - * This is typically used for tail-recursive calls. - * - * Basically this is compiled into - * continue labelDefIdent; - * but arguments need to be updated beforehand. - * - * Since the rhs for the new value of an argument can depend on the value - * of another argument (and since deciding if it is indeed the case is - * impossible in general), new values are computed in temporary variables - * first, then copied to the actual variables representing the argument. - * - * Trivial assignments (arg1 = arg1) are eliminated. - * - * If, after elimination of trivial assignments, only one assignment - * remains, then we do not use a temporary variable for this one. - */ - private def genEnclosingLabelApply(tree: Apply): js.Tree = { - implicit val pos = tree.pos - val Apply(fun, args) = tree - val sym = fun.symbol - - // Prepare quadruplets of (formalArg, irType, tempVar, actualArg) - // Do not include trivial assignments (when actualArg == formalArg) - val quadruplets = { - val formalArgs = enclosingLabelDefParams(sym) - val quadruplets = - List.newBuilder[(js.VarRef, jstpe.Type, js.Ident, js.Tree)] - - for ((formalArgSym, arg) <- formalArgs.zip(args)) { - val formalArg = encodeLocalSym(formalArgSym) - val actualArg = genExpr(arg) - - /* #3267 The formal argument representing the special `this` of a - * tailrec method can have the wrong type in the scalac symbol table. - * We need to patch it up, along with the actual argument, to be the - * enclosing class type. - * See the longer comment in genMethodDef() for more details. - * - * Note that only testing the `name` against `nme.THIS` is safe, - * given that `genStatOrExpr()` for `ValDef` asserts that no local - * variable named `nme.THIS` can happen, other than the ones - * generated for tailrec methods. - */ - val isTailJumpThisLocalVar = formalArgSym.name == nme.THIS - - val tpe = - if (isTailJumpThisLocalVar) currentClassType - else toIRType(formalArgSym.tpe) - - val fixedActualArg = - if (isTailJumpThisLocalVar) forceAdapt(actualArg, tpe) - else actualArg - - actualArg match { - case js.VarRef(`formalArg`) => - // This is trivial assignment, we don't need it - - case _ => - mutatedLocalVars += formalArgSym - quadruplets += ((js.VarRef(formalArg)(tpe), tpe, - freshLocalIdent("temp$" + formalArg.name), - fixedActualArg)) - } - } - - quadruplets.result() - } - - // The actual jump (continue labelDefIdent;) - val jump = js.Continue(Some(encodeLabelSym(sym))) - - quadruplets match { - case Nil => jump - - case (formalArg, argType, _, actualArg) :: Nil => - js.Block( - js.Assign(formalArg, actualArg), - jump) - - case _ => - val tempAssignments = - for ((_, argType, tempArg, actualArg) <- quadruplets) - yield js.VarDef(tempArg, argType, mutable = false, actualArg) - val trueAssignments = - for ((formalArg, argType, tempArg, _) <- quadruplets) - yield js.Assign(formalArg, js.VarRef(tempArg)(argType)) - js.Block(tempAssignments ++ trueAssignments :+ jump) - } - } - - /** Gen a "normal" apply (to a true method). - * - * But even these are further refined into: - * * Methods of java.lang.String, which are redirected to the - * RuntimeString trait implementation. - * * Calls to methods of raw JS types (Scala.js -> JS bridge) - * * Calls to methods in impl classes of traits. - * * Regular method call - */ - private def genNormalApply(tree: Apply, isStat: Boolean): js.Tree = { - implicit val pos = tree.pos - val Apply(fun @ Select(receiver, _), args) = tree - val sym = fun.symbol - - def isStringMethodFromObject: Boolean = sym.name match { - case nme.toString_ | nme.equals_ | nme.hashCode_ => true - case _ => false - } - - if (sym.owner == StringClass && !isStringMethodFromObject) { - genStringCall(tree) - } else if (isRawJSType(receiver.tpe) && sym.owner != ObjectClass) { - /* The !sym.isLazy test is intentionally bogus, to preserve backward - * binary compatibility at the cost of not correctly handling - * `override lazy val`s. - * - * It will cause the call site to directly access the internal accessor - * with a static call, rather than the JS getter using dynamic - * dispatch. This is necessary for bincompat, because Scala.js 0.6.24 - * and earlier did not generate a getter for the JS access, only a - * field (which does not trigger the initialization of the field when - * it hasn't been done yet). - */ - if (!isScalaJSDefinedJSClass(sym.owner) || (isExposed(sym) && !sym.isLazy)) - genPrimitiveJSCall(tree, isStat) - else - genApplyJSClassMethod(genExpr(receiver), sym, genActualArgs(sym, args)) - } else if (isImplClass(sym.owner)) { - genTraitImplApply(sym, args map genExpr) - } else if (sym.isClassConstructor) { - /* See #66: we have to emit a statically linked call to avoid calling a - * constructor with the same signature in a subclass. */ - genApplyMethodStatically(genExpr(receiver), sym, genActualArgs(sym, args)) - } else { - genApplyMethod(genExpr(receiver), sym, genActualArgs(sym, args)) - } - } - - def genApplyMethodStatically(receiver: js.Tree, method: Symbol, - arguments: List[js.Tree])(implicit pos: Position): js.Tree = { - val className = encodeClassFullName(method.owner) - val methodIdent = encodeMethodSym(method) - val resultType = - if (method.isClassConstructor) jstpe.NoType - else toIRType(method.tpe.resultType) - js.ApplyStatically(receiver, jstpe.ClassType(className), - methodIdent, arguments)(resultType) - } - - def genTraitImplApply(method: Symbol, arguments: List[js.Tree])( - implicit pos: Position): js.Tree = { - if (method.isMixinConstructor && isRawJSImplClass(method.owner)) { - /* Do not emit a call to the $init$ method of JS traits. - * This exception is necessary because @JSOptional fields cause the - * creation of a $init$ method, which we must not call. - */ - js.Skip() - } else { - genApplyStatic(method, arguments) - } - } - - def genApplyJSClassMethod(receiver: js.Tree, method: Symbol, - arguments: List[js.Tree])(implicit pos: Position): js.Tree = { - genApplyStatic(method, receiver :: arguments) - } - - def genApplyStatic(method: Symbol, arguments: List[js.Tree])( - implicit pos: Position): js.Tree = { - val cls = encodeClassFullName(method.owner) - val methodIdent = encodeMethodSym(method) - genApplyStatic(cls, methodIdent, arguments, - toIRType(method.tpe.resultType)) - } - - def genApplyStatic(cls: String, methodIdent: js.Ident, - arguments: List[js.Tree], resultType: jstpe.Type)( - implicit pos: Position): js.Tree = { - js.ApplyStatic(jstpe.ClassType(cls), methodIdent, - arguments)(resultType) - } - - /* This method corresponds to the method of the same name in - * BCodeBodyBuilder of the JVM back-end. It ends up calling the method - * BCodeIdiomatic.emitT2T, whose logic we replicate here. - */ - def genConversion(from: TypeKind, to: TypeKind, value: js.Tree)( - implicit pos: Position): js.Tree = { - import js.UnaryOp._ - - if (from == to || from == NOTHING) { - value - } else if (from == BOOL || to == BOOL) { - throw new AssertionError(s"Invalid genConversion from $from to $to") - } else { - def intValue = (from: @unchecked) match { - case INT(_) => value - case LONG => js.UnaryOp(LongToInt, value) - case FLOAT(_) => js.UnaryOp(DoubleToInt, value) - } - - def doubleValue = (from: @unchecked) match { - case FLOAT(_) | INT(_) => value - case LONG => js.UnaryOp(LongToDouble, value) - } - - (to: @unchecked) match { - case CharKind => - js.BinaryOp(js.BinaryOp.Int_&, intValue, js.IntLiteral(0xffff)) - case ByteKind => - js.BinaryOp(js.BinaryOp.Int_>>, - js.BinaryOp(js.BinaryOp.Int_<<, intValue, js.IntLiteral(24)), - js.IntLiteral(24)) - case ShortKind => - js.BinaryOp(js.BinaryOp.Int_>>, - js.BinaryOp(js.BinaryOp.Int_<<, intValue, js.IntLiteral(24)), - js.IntLiteral(24)) - case IntKind => - intValue - case LongKind => - from match { - case FLOAT(_) => - js.UnaryOp(DoubleToLong, doubleValue) - case _ => - js.UnaryOp(IntToLong, intValue) - } - case FloatKind => - js.UnaryOp(js.UnaryOp.DoubleToFloat, doubleValue) - case DoubleKind => - doubleValue - } - } - } - - /** Gen JS code for an isInstanceOf test (for reference types only) */ - def genIsInstanceOf(value: js.Tree, to: Type)( - implicit pos: Position): js.Tree = { - - val sym = to.typeSymbol - - if (sym == ObjectClass) { - js.BinaryOp(js.BinaryOp.!==, value, js.Null()) - } else if (isRawJSType(to)) { - if (sym.isTrait) { - reporter.error(pos, - s"isInstanceOf[${sym.fullName}] not supported because it is a raw JS trait") - js.BooleanLiteral(true) - } else { - js.Unbox(js.JSBinaryOp( - js.JSBinaryOp.instanceof, value, genPrimitiveJSClass(sym)), 'Z') - } - } else { - js.IsInstanceOf(value, toReferenceType(to)) - } - } - - /** Gen JS code for an asInstanceOf cast (for reference types only) */ - def genAsInstanceOf(value: js.Tree, to: Type)( - implicit pos: Position): js.Tree = { - - def default: js.Tree = - js.AsInstanceOf(value, toReferenceType(to)) - - val sym = to.typeSymbol - - if (sym == ObjectClass || isRawJSType(to)) { - /* asInstanceOf[Object] always succeeds, and - * asInstanceOf to a raw JS type is completely erased. - */ - value - } else if (FunctionClass.seq contains to.typeSymbol) { - /* Don't hide a JSFunctionToScala inside a useless cast, otherwise - * the optimization avoiding double-wrapping in genApply() will not - * be able to kick in. - */ - value match { - case JSFunctionToScala(fun, _) => value - case _ => default - } - } else { - default - } - } - - /** Gen JS code for a call to a Scala method. - * This also registers that the given method is called by the current - * method in the method info builder. - */ - def genApplyMethod(receiver: js.Tree, - methodSym: Symbol, arguments: List[js.Tree])( - implicit pos: Position): js.Tree = { - genApplyMethod(receiver, encodeMethodSym(methodSym), - arguments, toIRType(methodSym.tpe.resultType)) - } - - /** Gen JS code for a call to a Scala method. - * This also registers that the given method is called by the current - * method in the method info builder. - */ - def genApplyMethod(receiver: js.Tree, methodIdent: js.Ident, - arguments: List[js.Tree], resultType: jstpe.Type)( - implicit pos: Position): js.Tree = { - js.Apply(receiver, methodIdent, arguments)(resultType) - } - - /** Gen JS code for a call to a Scala class constructor. - * - * This also registers that the given class is instantiated by the current - * method, and that the given constructor is called, in the method info - * builder. - */ - def genNew(clazz: Symbol, ctor: Symbol, arguments: List[js.Tree])( - implicit pos: Position): js.Tree = { - assert(!isRawJSFunctionDef(clazz), - s"Trying to instantiate a raw JS function def $clazz") - val className = encodeClassFullName(clazz) - val ctorIdent = encodeMethodSym(ctor) - js.New(jstpe.ClassType(className), ctorIdent, arguments) - } - - /** Gen JS code for a call to a constructor of a hijacked boxed class. - * All of these have 2 constructors: one with the primitive - * value, which is erased, and one with a String, which is - * equivalent to BoxedClass.valueOf(arg). - */ - private def genNewHijackedBoxedClass(clazz: Symbol, ctor: Symbol, - arguments: List[js.Tree])(implicit pos: Position): js.Tree = { - assert(arguments.size == 1, - s"genNewHijackedBoxedClass of non-unary constructor $ctor") - if (isStringType(ctor.tpe.params.head.tpe)) { - // BoxedClass.valueOf(arg) - val companion = clazz.companionModule.moduleClass - val valueOf = getMemberMethod(companion, nme.valueOf) suchThat { s => - s.tpe.params.size == 1 && isStringType(s.tpe.params.head.tpe) - } - genApplyMethod(genLoadModule(companion), valueOf, arguments) - } else { - // erased - arguments.head - } - } - - /** Gen JS code for creating a new Array: new Array[T](length) - * For multidimensional arrays (dimensions > 1), the arguments can - * specify up to `dimensions` lengths for the first dimensions of the - * array. - */ - def genNewArray(arrayType: jstpe.ArrayType, arguments: List[js.Tree])( - implicit pos: Position): js.Tree = { - assert(arguments.length <= arrayType.dimensions, - "too many arguments for array constructor: found " + arguments.length + - " but array has only " + arrayType.dimensions + " dimension(s)") - - js.NewArray(arrayType, arguments) - } - - /** Gen JS code for an array literal. */ - def genArrayValue(tree: ArrayValue): js.Tree = { - val ArrayValue(tpt @ TypeTree(), elems) = tree - genArrayValue(tree, elems) - } - - /** Gen JS code for an array literal, in the context of `tree` (its `tpe` - * and `pos`) but with the elements `elems`. - */ - def genArrayValue(tree: Tree, elems: List[Tree]): js.Tree = { - implicit val pos = tree.pos - val arrType = toReferenceType(tree.tpe).asInstanceOf[jstpe.ArrayType] - js.ArrayValue(arrType, elems.map(genExpr)) - } - - /** Gen JS code for a Match, i.e., a switch-able pattern match. - * - * In most cases, this straightforwardly translates to a Match in the IR, - * which will eventually become a `switch` in JavaScript. - * - * However, sometimes there is a guard in here, despite the fact that - * matches cannot have guards (in the JVM nor in the IR). The JVM backend - * emits a jump to the default clause when a guard is not fulfilled. We - * cannot do that, since we do not have arbitrary jumps. We therefore use - * a funny encoding with two nested `Labeled` blocks. For example, - * {{{ - * x match { - * case 1 if y > 0 => a - * case 2 => b - * case _ => c - * } - * }}} - * arrives at the back-end as - * {{{ - * x match { - * case 1 => - * if (y > 0) - * a - * else - * default() - * case 2 => - * b - * case _ => - * default() { - * c - * } - * } - * }}} - * which we then translate into the following IR: - * {{{ - * matchResult[I]: { - * default[V]: { - * x match { - * case 1 => - * return(matchResult) if (y > 0) - * a - * else - * return(default) (void 0) - * case 2 => - * return(matchResult) b - * case _ => - * () - * } - * } - * c - * } - * }}} - */ - def genMatch(tree: Tree, isStat: Boolean): js.Tree = { - implicit val pos = tree.pos - val Match(selector, cases) = tree - - val expr = genExpr(selector) - val resultType = toIRType(tree.tpe) - - val defaultLabelSym = cases.collectFirst { - case CaseDef(Ident(nme.WILDCARD), EmptyTree, - body @ LabelDef(_, Nil, rhs)) if hasSynthCaseSymbol(body) => - body.symbol - }.getOrElse(NoSymbol) - - var clauses: List[(List[js.Literal], js.Tree)] = Nil - var optElseClause: Option[js.Tree] = None - var optElseClauseLabel: Option[js.Ident] = None - - def genJumpToElseClause(implicit pos: ir.Position): js.Tree = { - if (optElseClauseLabel.isEmpty) - optElseClauseLabel = Some(freshLocalIdent("default")) - js.Return(js.Undefined(), optElseClauseLabel) - } - - for (caze @ CaseDef(pat, guard, body) <- cases) { - assert(guard == EmptyTree, s"found a case guard at ${caze.pos}") - - def genBody(body: Tree): js.Tree = body match { - case app @ Apply(_, Nil) if app.symbol == defaultLabelSym => - genJumpToElseClause - case Block(List(app @ Apply(_, Nil)), _) if app.symbol == defaultLabelSym => - genJumpToElseClause - - case If(cond, thenp, elsep) => - js.If(genExpr(cond), genBody(thenp), genBody(elsep))( - resultType)(body.pos) - - /* For #1955. If we receive a tree with the shape - * if (cond) { - * thenp - * } else { - * elsep - * } - * scala.runtime.BoxedUnit.UNIT - * we rewrite it as - * if (cond) { - * thenp - * scala.runtime.BoxedUnit.UNIT - * } else { - * elsep - * scala.runtime.BoxedUnit.UNIT - * } - * so that it fits the shape of if/elses we can deal with. - */ - case Block(List(If(cond, thenp, elsep)), s: Select) - if s.symbol == definitions.BoxedUnit_UNIT => - val newThenp = Block(thenp, s).setType(s.tpe).setPos(thenp.pos) - val newElsep = Block(elsep, s).setType(s.tpe).setPos(elsep.pos) - js.If(genExpr(cond), genBody(newThenp), genBody(newElsep))( - resultType)(body.pos) - - case _ => - genStatOrExpr(body, isStat) - } - - def genLiteral(lit: Literal): js.Literal = - genExpr(lit).asInstanceOf[js.Literal] - - pat match { - case lit: Literal => - clauses = (List(genLiteral(lit)), genBody(body)) :: clauses - case Ident(nme.WILDCARD) => - optElseClause = Some(body match { - case LabelDef(_, Nil, rhs) if hasSynthCaseSymbol(body) => - genBody(rhs) - case _ => - genBody(body) - }) - case Alternative(alts) => - val genAlts = { - alts map { - case lit: Literal => genLiteral(lit) - case _ => - abort("Invalid case in alternative in switch-like pattern match: " + - tree + " at: " + tree.pos) - } - } - clauses = (genAlts, genBody(body)) :: clauses - case _ => - abort("Invalid case statement in switch-like pattern match: " + - tree + " at: " + (tree.pos)) - } - } - - val elseClause = optElseClause.getOrElse( - throw new AssertionError("No elseClause in pattern match")) - - optElseClauseLabel.fold[js.Tree] { - js.Match(expr, clauses.reverse, elseClause)(resultType) - } { elseClauseLabel => - val matchResultLabel = freshLocalIdent("matchResult") - val patchedClauses = for ((alts, body) <- clauses) yield { - implicit val pos = body.pos - val lab = Some(matchResultLabel) - val newBody = - if (isStat) js.Block(body, js.Return(js.Undefined(), lab)) - else js.Return(body, lab) - (alts, newBody) - } - js.Labeled(matchResultLabel, resultType, js.Block(List( - js.Labeled(elseClauseLabel, jstpe.NoType, { - js.Match(expr, patchedClauses.reverse, js.Skip())(jstpe.NoType) - }), - elseClause - ))) - } - } - - private def genBlock(tree: Block, isStat: Boolean): js.Tree = { - implicit val pos = tree.pos - val Block(stats, expr) = tree - - /** Predicate satisfied by LabelDefs produced by the pattern matcher */ - def isCaseLabelDef(tree: Tree) = - tree.isInstanceOf[LabelDef] && hasSynthCaseSymbol(tree) - - def translateMatch(expr: LabelDef) = { - /* Block that appeared as the result of a translated match - * Such blocks are recognized by having at least one element that is - * a so-called case-label-def. - * The method `genTranslatedMatch()` takes care of compiling the - * actual match. - * - * The assumption is once we encounter a case, the remainder of the - * block will consist of cases. - * The prologue may be empty, usually it is the valdef that stores - * the scrut. - */ - val (prologue, cases) = stats.span(s => !isCaseLabelDef(s)) - assert(cases.forall(isCaseLabelDef), - "Assumption on the form of translated matches broken: " + tree) - - val genPrologue = prologue map genStat - val translatedMatch = - genTranslatedMatch(cases.map(_.asInstanceOf[LabelDef]), expr) - - js.Block(genPrologue :+ translatedMatch) - } - - expr match { - case expr: LabelDef if isCaseLabelDef(expr) => - translateMatch(expr) - - // Sometimes the pattern matcher casts its final result - case Apply(TypeApply(Select(expr: LabelDef, nme.asInstanceOf_Ob), - List(targ)), Nil) - if isCaseLabelDef(expr) => - genIsAsInstanceOf(translateMatch(expr), expr.tpe, targ.tpe, - cast = true) - - // Peculiar shape generated by `return x match {...}` - #2928 - case Return(retExpr: LabelDef) if isCaseLabelDef(retExpr) => - val result = translateMatch(retExpr) - if (result.tpe == jstpe.NoType) { - // Could not actually reproduce this, but better be safe than sorry - js.Block(result, js.Return(js.Undefined())) - } else { - js.Return(result) - } - - case _ => - assert(!stats.exists(isCaseLabelDef), "Found stats with case label " + - s"def in non-match block at ${tree.pos}: $tree") - - /* Normal block */ - val statements = stats map genStat - val expression = genStatOrExpr(expr, isStat) - js.Block(statements :+ expression) - } - } - - /** Gen JS code for a translated match - * - * This implementation relies heavily on the patterns of trees emitted - * by the current pattern match phase (as of Scala 2.10). - * - * The trees output by the pattern matcher are assumed to follow these - * rules: - * * Each case LabelDef (in `cases`) must not take any argument. - * * The last one must be a catch-all (case _ =>) that never falls through. - * * Jumps to the `matchEnd` are allowed anywhere in the body of the - * corresponding case label-defs, but not outside. - * * Jumps to case label-defs are restricted to jumping to the very next - * case, and only in positions denoted by in: - * ::= - * If(_, , ) - * | Block(_, ) - * | - * | _ - * These restrictions, together with the fact that we are in statement - * position (thanks to the above transformation), mean that they can be - * simply replaced by `skip`. - * - * To implement jumps to `matchEnd`, which have one argument which is the - * result of the match, we enclose all the cases in one big labeled block. - * Jumps are then compiled as `return`s out of the block. - */ - def genTranslatedMatch(cases: List[LabelDef], - matchEnd: LabelDef)(implicit pos: Position): js.Tree = { - - val matchEndSym = matchEnd.symbol - countsOfReturnsToMatchEnd(matchEndSym) = 0 - - val nextCaseSyms = (cases.tail map (_.symbol)) :+ NoSymbol - - val translatedCases = for { - (LabelDef(_, Nil, rhs), nextCaseSym) <- cases zip nextCaseSyms - } yield { - if (nextCaseSym.exists) - countsOfReturnsToMatchCase(nextCaseSym) = 0 - - def genCaseBody(tree: Tree): js.Tree = { - implicit val pos = tree.pos - tree match { - case If(cond, thenp, elsep) => - js.If(genExpr(cond), genCaseBody(thenp), genCaseBody(elsep))( - jstpe.NoType) - - case Block(stats, expr) => - js.Block((stats map genStat) :+ genCaseBody(expr)) - - case Apply(_, Nil) if tree.symbol == nextCaseSym => - js.Skip() - - case _ => - genStat(tree) - } - } - - val translatedBody = genCaseBody(rhs) - - if (!nextCaseSym.exists) { - translatedBody - } else { - val returnCount = countsOfReturnsToMatchCase.remove(nextCaseSym).get - genOptimizedCaseLabeled(encodeLabelSym(nextCaseSym), translatedBody, - returnCount) - } - } - - val returnCount = countsOfReturnsToMatchEnd.remove(matchEndSym).get - - val LabelDef(_, List(matchEndParam), matchEndBody) = matchEnd - - val innerResultType = toIRType(matchEndParam.tpe) - val optimized = genOptimizedMatchEndLabeled(encodeLabelSym(matchEndSym), - innerResultType, translatedCases, returnCount) - - matchEndBody match { - case Ident(_) if matchEndParam.symbol == matchEndBody.symbol => - // matchEnd is identity. - optimized - - case Literal(Constant(())) => - // Unit return type. - optimized - - case _ => - // matchEnd does something. - val ident = encodeLocalSym(matchEndParam.symbol) - js.Block( - js.VarDef(ident, innerResultType, mutable = false, optimized), - genExpr(matchEndBody)) - } - } - - /** Gen JS code for a Labeled block from a pattern match'es case, while - * trying to optimize it away as a reversed If. - * - * If there was no `return` to the label at all, simply avoid generating - * the `Labeled` block alltogether. - * - * If there was more than one `return`, do not optimize anything, as - * nothing could be good enough for `genOptimizedMatchEndLabeled` to do - * anything useful down the line. - * - * If however there was a single `return`, we try and get rid of it by - * identifying the following shape: - * - * {{{ - * { - * ...stats1 - * if (test) - * return(nextCaseSym) - * ...stats2 - * } - * }}} - * - * which we then rewrite as - * - * {{{ - * { - * ...stats1 - * if (!test) { - * ...stats2 - * } - * } - * }}} - * - * The above rewrite is important for `genOptimizedMatchEndLabeled` below - * to be able to do its job, which in turn is important for the IR - * optimizer to perform a better analysis. - * - * This whole thing is only necessary in Scala 2.12.9+, with the new flat - * patmat ASTs. In previous versions, `returnCount` is always 0 because - * all jumps to case labels are already caught upstream by `genCaseBody()` - * inside `genTranslatedMatch()`. - */ - private def genOptimizedCaseLabeled(label: js.Ident, - translatedBody: js.Tree, returnCount: Int)( - implicit pos: Position): js.Tree = { - - def default: js.Tree = - js.Labeled(label, jstpe.NoType, translatedBody) - - if (returnCount == 0) { - translatedBody - } else if (returnCount > 1) { - default - } else { - translatedBody match { - case js.Block(stats) => - val (stats1, testAndStats2) = stats.span { - case js.If(_, js.Return(js.Undefined(), Some(`label`)), js.Skip()) => - false - case _ => - true - } - - testAndStats2 match { - case js.If(cond, _, _) :: stats2 => - val notCond = cond match { - case js.UnaryOp(js.UnaryOp.Boolean_!, notCond) => - notCond - case _ => - js.UnaryOp(js.UnaryOp.Boolean_!, cond) - } - js.Block(stats1 :+ js.If(notCond, js.Block(stats2), js.Skip())(jstpe.NoType)) - - case _ :: _ => - throw new AssertionError("unreachable code") - - case Nil => - default - } - - case _ => - default - } - } - } - - /** Gen JS code for a Labeled block from a pattern match'es match-end, - * while trying to optimize it away as an If chain. - * - * It is important to do so at compile-time because, when successful, the - * resulting IR can be much better optimized by the optimizer. - * - * The optimizer also does something similar, but *after* it has processed - * the body of the Labeled block, at which point it has already lost any - * information about stack-allocated values. - * - * !!! There is quite of bit of code duplication with - * OptimizerCore.tryOptimizePatternMatch. - */ - def genOptimizedMatchEndLabeled(label: js.Ident, tpe: jstpe.Type, - translatedCases: List[js.Tree], returnCount: Int)( - implicit pos: Position): js.Tree = { - def default: js.Tree = - js.Labeled(label, tpe, js.Block(translatedCases)) - - @tailrec - def createRevAlts(xs: List[js.Tree], - acc: List[(js.Tree, js.Tree)]): (List[(js.Tree, js.Tree)], js.Tree) = xs match { - case js.If(cond, body, js.Skip()) :: xr => - createRevAlts(xr, (cond, body) :: acc) - case remaining => - (acc, js.Block(remaining)(remaining.head.pos)) - } - val (revAlts, elsep) = createRevAlts(translatedCases, Nil) - - if (revAlts.size == returnCount - 1) { - def tryDropReturn(body: js.Tree): Option[js.Tree] = body match { - case jse.BlockOrAlone(prep, js.Return(result, Some(`label`))) => - Some(js.Block(prep :+ result)(body.pos)) - - case _ => - None - } - - @tailrec - def constructOptimized(revAlts: List[(js.Tree, js.Tree)], - elsep: js.Tree): js.Tree = { - revAlts match { - case (cond, body) :: revAltsRest => - // cannot use flatMap due to tailrec - tryDropReturn(body) match { - case Some(newBody) => - constructOptimized(revAltsRest, - js.If(cond, newBody, elsep)(tpe)(cond.pos)) - - case None => - default - } - case Nil => - elsep - } - } - - tryDropReturn(elsep).fold(default)(constructOptimized(revAlts, _)) - } else { - default - } - } - - /** Gen JS code for a primitive method call */ - private def genPrimitiveOp(tree: Apply, isStat: Boolean): js.Tree = { - import scalaPrimitives._ - - implicit val pos = tree.pos - - val sym = tree.symbol - val Apply(fun @ Select(receiver, _), args) = tree - - val code = scalaPrimitives.getPrimitive(sym, receiver.tpe) - - if (isArithmeticOp(code) || isLogicalOp(code) || isComparisonOp(code)) - genSimpleOp(tree, receiver :: args, code) - else if (code == scalaPrimitives.CONCAT) - genStringConcat(tree, receiver, args) - else if (code == HASH) - genScalaHash(tree, receiver) - else if (isArrayOp(code)) - genArrayOp(tree, code) - else if (code == SYNCHRONIZED) - genSynchronized(receiver, args.head, isStat) - else if (isCoercion(code)) - genCoercion(tree, receiver, code) - else if (jsPrimitives.isJavaScriptPrimitive(code)) - genJSPrimitive(tree, receiver, args, code) - else - abort("Unknown primitive operation: " + sym.fullName + "(" + - fun.symbol.simpleName + ") " + " at: " + (tree.pos)) - } - - /** Gen JS code for a simple operation (arithmetic, logical, or comparison) */ - private def genSimpleOp(tree: Apply, args: List[Tree], code: Int): js.Tree = { - import scalaPrimitives._ - - implicit val pos = tree.pos - - val isShift = isShiftOp(code) - - def isLongOp(ltpe: Type, rtpe: Type) = { - if (isShift) { - isLongType(ltpe) - } else { - (isLongType(ltpe) || isLongType(rtpe)) && - !(toTypeKind(ltpe).isInstanceOf[FLOAT] || - toTypeKind(rtpe).isInstanceOf[FLOAT] || - isStringType(ltpe) || isStringType(rtpe)) - } - } - - val sources = args map genExpr - - val resultType = toIRType(tree.tpe) - - sources match { - // Unary operation - case List(source) => - (code match { - case POS => - source - case NEG => - (resultType: @unchecked) match { - case jstpe.IntType => - js.BinaryOp(js.BinaryOp.Int_-, js.IntLiteral(0), source) - case jstpe.LongType => - js.BinaryOp(js.BinaryOp.Long_-, js.LongLiteral(0), source) - case jstpe.FloatType => - js.BinaryOp(js.BinaryOp.Float_*, js.FloatLiteral(-1.0f), source) - case jstpe.DoubleType => - js.BinaryOp(js.BinaryOp.Double_*, js.DoubleLiteral(-1.0), source) - } - case NOT => - (resultType: @unchecked) match { - case jstpe.IntType => - js.BinaryOp(js.BinaryOp.Int_^, js.IntLiteral(-1), source) - case jstpe.LongType => - js.BinaryOp(js.BinaryOp.Long_^, js.LongLiteral(-1), source) - } - case ZNOT => - js.UnaryOp(js.UnaryOp.Boolean_!, source) - case _ => - abort("Unknown unary operation code: " + code) - }) - - // Binary operation on Longs - case List(lsrc, rsrc) if isLongOp(args(0).tpe, args(1).tpe) => - def toLong(tree: js.Tree, tpe: Type) = - if (isLongType(tpe)) tree - else js.UnaryOp(js.UnaryOp.IntToLong, tree) - - def toInt(tree: js.Tree, tpe: Type) = - if (isLongType(tpe)) js.UnaryOp(js.UnaryOp.LongToInt, rsrc) - else tree - - val ltree = toLong(lsrc, args(0).tpe) - def rtree = toLong(rsrc, args(1).tpe) - def rtreeInt = toInt(rsrc, args(1).tpe) - - import js.BinaryOp._ - (code: @switch) match { - case ADD => js.BinaryOp(Long_+, ltree, rtree) - case SUB => js.BinaryOp(Long_-, ltree, rtree) - case MUL => js.BinaryOp(Long_*, ltree, rtree) - case DIV => js.BinaryOp(Long_/, ltree, rtree) - case MOD => js.BinaryOp(Long_%, ltree, rtree) - case OR => js.BinaryOp(Long_|, ltree, rtree) - case XOR => js.BinaryOp(Long_^, ltree, rtree) - case AND => js.BinaryOp(Long_&, ltree, rtree) - case LSL => js.BinaryOp(Long_<<, ltree, rtreeInt) - case LSR => js.BinaryOp(Long_>>>, ltree, rtreeInt) - case ASR => js.BinaryOp(Long_>>, ltree, rtreeInt) - case EQ => js.BinaryOp(Long_==, ltree, rtree) - case NE => js.BinaryOp(Long_!=, ltree, rtree) - case LT => js.BinaryOp(Long_<, ltree, rtree) - case LE => js.BinaryOp(Long_<=, ltree, rtree) - case GT => js.BinaryOp(Long_>, ltree, rtree) - case GE => js.BinaryOp(Long_>=, ltree, rtree) - case _ => - abort("Unknown binary operation code: " + code) - } - - // Binary operation - case List(lsrc_in, rsrc_in) => - val leftKind = toTypeKind(args(0).tpe) - val rightKind = toTypeKind(args(1).tpe) - - val opType = (leftKind, rightKind) match { - case (DoubleKind, _) | (_, DoubleKind) => jstpe.DoubleType - case (FloatKind, _) | (_, FloatKind) => jstpe.FloatType - case (INT(_), _) | (_, INT(_)) => jstpe.IntType - case (BooleanKind, BooleanKind) => jstpe.BooleanType - case _ => jstpe.AnyType - } - - def convertArg(tree: js.Tree, kind: TypeKind) = { - /* If we end up with a long, the op type must be float or double, - * so we can first eliminate the Long case by converting to Double. - * - * Unless it is a shift operation, in which case the op type would - * be int. - */ - val notLong = { - if (kind != LongKind) tree - else if (isShift) js.UnaryOp(js.UnaryOp.LongToInt, tree) - else js.UnaryOp(js.UnaryOp.LongToDouble, tree) - } - - if (opType != jstpe.FloatType) notLong - else if (kind == FloatKind) notLong - else js.UnaryOp(js.UnaryOp.DoubleToFloat, notLong) - } - - val lsrc = convertArg(lsrc_in, leftKind) - val rsrc = convertArg(rsrc_in, rightKind) - - def genEquality(eqeq: Boolean, not: Boolean) = { - opType match { - case jstpe.IntType | jstpe.DoubleType | jstpe.FloatType => - js.BinaryOp( - if (not) js.BinaryOp.Num_!= else js.BinaryOp.Num_==, - lsrc, rsrc) - case jstpe.BooleanType => - js.BinaryOp( - if (not) js.BinaryOp.Boolean_!= else js.BinaryOp.Boolean_==, - lsrc, rsrc) - case _ => - if (eqeq && - // don't call equals if we have a literal null at either side - !lsrc.isInstanceOf[js.Null] && - !rsrc.isInstanceOf[js.Null] && - // Arrays, Null, Nothing do not have an equals() method - leftKind.isInstanceOf[REFERENCE]) { - val body = genEqEqPrimitive(args(0).tpe, args(1).tpe, lsrc, rsrc) - if (not) js.UnaryOp(js.UnaryOp.Boolean_!, body) else body - } else { - js.BinaryOp( - if (not) js.BinaryOp.!== else js.BinaryOp.===, - lsrc, rsrc) - } - } - } - - (code: @switch) match { - case EQ => genEquality(eqeq = true, not = false) - case NE => genEquality(eqeq = true, not = true) - case ID => genEquality(eqeq = false, not = false) - case NI => genEquality(eqeq = false, not = true) - - case ZOR => js.If(lsrc, js.BooleanLiteral(true), rsrc)(jstpe.BooleanType) - case ZAND => js.If(lsrc, rsrc, js.BooleanLiteral(false))(jstpe.BooleanType) - - case _ => - import js.BinaryOp._ - val op = (resultType: @unchecked) match { - case jstpe.IntType => - (code: @switch) match { - case ADD => Int_+ - case SUB => Int_- - case MUL => Int_* - case DIV => Int_/ - case MOD => Int_% - case OR => Int_| - case AND => Int_& - case XOR => Int_^ - case LSL => Int_<< - case LSR => Int_>>> - case ASR => Int_>> - } - case jstpe.FloatType => - (code: @switch) match { - case ADD => Float_+ - case SUB => Float_- - case MUL => Float_* - case DIV => Float_/ - case MOD => Float_% - } - case jstpe.DoubleType => - (code: @switch) match { - case ADD => Double_+ - case SUB => Double_- - case MUL => Double_* - case DIV => Double_/ - case MOD => Double_% - } - case jstpe.BooleanType => - (code: @switch) match { - case LT => Num_< - case LE => Num_<= - case GT => Num_> - case GE => Num_>= - case OR => Boolean_| - case AND => Boolean_& - case XOR => Boolean_!= - } - } - js.BinaryOp(op, lsrc, rsrc) - } - - case _ => - abort("Too many arguments for primitive function: " + tree) - } - } - - /** See comment in `genEqEqPrimitive()` about `mustUseAnyComparator`. */ - private lazy val shouldPreserveEqEqBugWithJLFloatDouble = { - val v = scala.util.Properties.versionNumberString - - { - v.startsWith("2.10.") || - v.startsWith("2.11.") || - v == "2.12.0" || - v == "2.12.1" - } - } - - /** Gen JS code for a call to Any.== */ - def genEqEqPrimitive(ltpe: Type, rtpe: Type, lsrc: js.Tree, rsrc: js.Tree)( - implicit pos: Position): js.Tree = { - /* True if the equality comparison is between values that require the - * use of the rich equality comparator - * (scala.runtime.BoxesRunTime.equals). - * This is the case when either side of the comparison might have a - * run-time type subtype of java.lang.Number or java.lang.Character, - * **which includes when either is a raw JS type**. - * - * When it is statically known that both sides are equal and subtypes of - * Number or Character, not using the rich equality is possible (their - * own equals method will do ok), except for java.lang.Float and - * java.lang.Double: their `equals` have different behavior around `NaN` - * and `-0.0`, see Javadoc (scala-dev#329, #2799). - * - * The latter case is only avoided in 2.12.2+, to remain bug-compatible - * with the Scala/JVM compiler. - */ - val mustUseAnyComparator: Boolean = { - isRawJSType(ltpe) || isRawJSType(rtpe) || { - isMaybeBoxed(ltpe.typeSymbol) && isMaybeBoxed(rtpe.typeSymbol) && { - val areSameFinals = - ltpe.isFinalType && rtpe.isFinalType && (ltpe =:= rtpe) - !areSameFinals || { - val sym = ltpe.typeSymbol - (sym == BoxedFloatClass || sym == BoxedDoubleClass) && { - // Bug-compatibility for Scala < 2.12.2 - !shouldPreserveEqEqBugWithJLFloatDouble - } - } - } - } - } - - if (mustUseAnyComparator) { - val equalsMethod: Symbol = { - // scalastyle:off line.size.limit - val ptfm = platform.asInstanceOf[backend.JavaPlatform with ThisPlatform] // 2.10 compat - if (ltpe <:< BoxedNumberClass.tpe) { - if (rtpe <:< BoxedNumberClass.tpe) ptfm.externalEqualsNumNum - else if (rtpe <:< BoxedCharacterClass.tpe) ptfm.externalEqualsNumObject // will be externalEqualsNumChar in 2.12, SI-9030 - else ptfm.externalEqualsNumObject - } else ptfm.externalEquals - // scalastyle:on line.size.limit - } - val moduleClass = equalsMethod.owner - val instance = genLoadModule(moduleClass) - genApplyMethod(instance, equalsMethod, List(lsrc, rsrc)) - } else { - // if (lsrc eq null) rsrc eq null else lsrc.equals(rsrc) - if (isStringType(ltpe)) { - // String.equals(that) === (this eq that) - js.BinaryOp(js.BinaryOp.===, lsrc, rsrc) - } else { - /* This requires to evaluate both operands in local values first. - * The optimizer will eliminate them if possible. - */ - val ltemp = js.VarDef(freshLocalIdent(), lsrc.tpe, mutable = false, lsrc) - val rtemp = js.VarDef(freshLocalIdent(), rsrc.tpe, mutable = false, rsrc) - js.Block( - ltemp, - rtemp, - js.If(js.BinaryOp(js.BinaryOp.===, ltemp.ref, js.Null()), - js.BinaryOp(js.BinaryOp.===, rtemp.ref, js.Null()), - genApplyMethod(ltemp.ref, Object_equals, List(rtemp.ref)))( - jstpe.BooleanType)) - } - } - } - - /** Gen JS code for string concatenation. - */ - private def genStringConcat(tree: Apply, receiver: Tree, - args: List[Tree]): js.Tree = { - implicit val pos = tree.pos - - /* Primitive number types such as scala.Int have a - * def +(s: String): String - * method, which is why we have to box the lhs sometimes. - * Otherwise, both lhs and rhs are already reference types (Any of String) - * so boxing is not necessary (in particular, rhs is never a primitive). - */ - assert(!isPrimitiveValueType(receiver.tpe) || isStringType(args.head.tpe), - s"unexpected signature for string-concat call at $pos") - assert(!isPrimitiveValueType(args.head.tpe), - s"unexpected signature for string-concat call at $pos") - - val rhs = genExpr(args.head) - - val lhs = { - val lhs0 = genExpr(receiver) - // Box the receiver if it is a primitive value - if (!isPrimitiveValueType(receiver.tpe)) lhs0 - else makePrimitiveBox(lhs0, receiver.tpe) - } - - js.BinaryOp(js.BinaryOp.String_+, lhs, rhs) - } - - /** Gen JS code for a call to `Any.##`. - * - * This method unconditionally generates a call to `Statics.anyHash`. - * On the JVM, `anyHash` is only called as of 2.12.0-M5. Previous versions - * emitted a call to `ScalaRunTime.hash`. However, since our `anyHash` - * is always consistent with `ScalaRunTime.hash`, we always use it. - */ - private def genScalaHash(tree: Apply, receiver: Tree): js.Tree = { - implicit val pos = tree.pos - - val instance = genLoadModule(RuntimeStaticsModule) - val arguments = List(genExpr(receiver)) - val sym = getMember(RuntimeStaticsModule, jsnme.anyHash) - - genApplyMethod(instance, sym, arguments) - } - - /** Gen JS code for an array operation (get, set or length) */ - private def genArrayOp(tree: Tree, code: Int): js.Tree = { - import scalaPrimitives._ - - implicit val pos = tree.pos - - val Apply(Select(arrayObj, _), args) = tree - val arrayValue = genExpr(arrayObj) - val arguments = args map genExpr - - def genSelect() = { - val elemIRType = - toTypeKind(arrayObj.tpe).asInstanceOf[ARRAY].elem.toIRType - js.ArraySelect(arrayValue, arguments(0))(elemIRType) - } - - if (scalaPrimitives.isArrayGet(code)) { - // get an item of the array - assert(args.length == 1, - s"Array get requires 1 argument, found ${args.length} in $tree") - genSelect() - } else if (scalaPrimitives.isArraySet(code)) { - // set an item of the array - assert(args.length == 2, - s"Array set requires 2 arguments, found ${args.length} in $tree") - js.Assign(genSelect(), arguments(1)) - } else { - // length of the array - js.ArrayLength(arrayValue) - } - } - - /** Gen JS code for a call to AnyRef.synchronized */ - private def genSynchronized(receiver: Tree, arg: Tree, isStat: Boolean)( - implicit pos: Position): js.Tree = { - /* JavaScript is single-threaded, so we can drop the - * synchronization altogether. - */ - val newReceiver = genExpr(receiver) - val newArg = genStatOrExpr(arg, isStat) - newReceiver match { - case js.This() => - // common case for which there is no side-effect nor NPE - newArg - case _ => - val NPECtor = getMemberMethod(NullPointerExceptionClass, - nme.CONSTRUCTOR).suchThat(_.tpe.params.isEmpty) - js.Block( - js.If(js.BinaryOp(js.BinaryOp.===, newReceiver, js.Null()), - js.Throw(genNew(NullPointerExceptionClass, NPECtor, Nil)), - js.Skip())(jstpe.NoType), - newArg) - } - } - - /** Gen JS code for a coercion */ - private def genCoercion(tree: Apply, receiver: Tree, code: Int): js.Tree = { - import scalaPrimitives._ - - implicit val pos = tree.pos - - val source = genExpr(receiver) - - def source2int = (code: @switch) match { - case F2C | D2C | F2B | D2B | F2S | D2S | F2I | D2I => - js.UnaryOp(js.UnaryOp.DoubleToInt, source) - case L2C | L2B | L2S | L2I => - js.UnaryOp(js.UnaryOp.LongToInt, source) - case _ => - source - } - - (code: @switch) match { - // To Char, need to crop at unsigned 16-bit - case B2C | S2C | I2C | L2C | F2C | D2C => - js.BinaryOp(js.BinaryOp.Int_&, source2int, js.IntLiteral(0xffff)) - - // To Byte, need to crop at signed 8-bit - case C2B | S2B | I2B | L2B | F2B | D2B => - // note: & 0xff would not work because of negative values - js.BinaryOp(js.BinaryOp.Int_>>, - js.BinaryOp(js.BinaryOp.Int_<<, source2int, js.IntLiteral(24)), - js.IntLiteral(24)) - - // To Short, need to crop at signed 16-bit - case C2S | I2S | L2S | F2S | D2S => - // note: & 0xffff would not work because of negative values - js.BinaryOp(js.BinaryOp.Int_>>, - js.BinaryOp(js.BinaryOp.Int_<<, source2int, js.IntLiteral(16)), - js.IntLiteral(16)) - - // To Int, need to crop at signed 32-bit - case L2I | F2I | D2I => - source2int - - // Any int to Long - case C2L | B2L | S2L | I2L => - js.UnaryOp(js.UnaryOp.IntToLong, source) - - // Any double to Long - case F2L | D2L => - js.UnaryOp(js.UnaryOp.DoubleToLong, source) - - // Long to Double - case L2D => - js.UnaryOp(js.UnaryOp.LongToDouble, source) - - // Any int, or Double, to Float - case C2F | B2F | S2F | I2F | D2F => - js.UnaryOp(js.UnaryOp.DoubleToFloat, source) - - // Long to Float === Long to Double to Float - case L2F => - js.UnaryOp(js.UnaryOp.DoubleToFloat, - js.UnaryOp(js.UnaryOp.LongToDouble, source)) - - // Identities and IR upcasts - case C2C | B2B | S2S | I2I | L2L | F2F | D2D | - C2I | C2D | - B2S | B2I | B2D | - S2I | S2D | - I2D | - F2D => - source - } - } - - /** Gen JS code for an ApplyDynamic - * ApplyDynamic nodes appear as the result of calls to methods of a - * structural type. - * - * Most unfortunately, earlier phases of the compiler assume too much - * about the backend, namely, they believe arguments and the result must - * be boxed, and do the boxing themselves. This decision should be left - * to the backend, but it's not, so we have to undo these boxes. - * Note that this applies to parameter types only. The return type is boxed - * anyway since we do not know it's exact type. - * - * This then generates a call to the reflective call proxy for the given - * arguments. - */ - private def genApplyDynamic(tree: ApplyDynamic): js.Tree = { - implicit val pos = tree.pos - - val sym = tree.symbol - val name = sym.name - val params = sym.tpe.params - - /* Is this a primitive method introduced in AnyRef? - * The concerned methods are `eq`, `ne` and `synchronized`. - * - * If it is, it can be defined in a custom value class. Calling it - * reflectively works on the JVM in that case. However, it does not work - * if the reflective call should in fact resolve to the method in - * `AnyRef` (it causes a `NoSuchMethodError`). We maintain bug - * compatibility for these methods: they work if redefined in a custom - * AnyVal, and fail at run-time (with a `TypeError`) otherwise. - */ - val isAnyRefPrimitive = { - (name == nme.eq || name == nme.ne || name == nme.synchronized_) && - params.size == 1 && params.head.tpe.typeSymbol == ObjectClass - } - - /** check if the method we are invoking conforms to a method on - * scala.Array. If this is the case, we check that case specially at - * runtime to avoid having reflective call proxies on scala.Array. - * (Also, note that the element type of Array#update is not erased and - * therefore the method name mangling would turn out wrong) - * - * Note that we cannot check if the expected return type is correct, - * since this type information is already erased. - */ - def isArrayLikeOp = name match { - case nme.update => - params.size == 2 && params.head.tpe.typeSymbol == IntClass - case nme.apply => - params.size == 1 && params.head.tpe.typeSymbol == IntClass - case nme.length => - params.size == 0 - case nme.clone_ => - params.size == 0 - case _ => - false - } - - /** - * Tests whether one of our reflective "boxes" for primitive types - * implements the particular method. If this is the case - * (result != NoSymbol), we generate a runtime instance check if we are - * dealing with the appropriate primitive type. - */ - def matchingSymIn(clazz: Symbol) = clazz.tpe.member(name).suchThat { s => - val sParams = s.tpe.params - !s.isBridge && - params.size == sParams.size && - (params zip sParams).forall { case (s1,s2) => - s1.tpe =:= s2.tpe - } - } - - val ApplyDynamic(receiver, args) = tree - - val receiverType = toIRType(receiver.tpe) - val callTrgIdent = freshLocalIdent() - val callTrgVarDef = - js.VarDef(callTrgIdent, receiverType, mutable = false, genExpr(receiver)) - val callTrg = js.VarRef(callTrgIdent)(receiverType) - - val arguments = args zip sym.tpe.params map { case (arg, param) => - /* No need for enteringPosterasure, because value classes are not - * supported as parameters of methods in structural types. - * We could do it for safety and future-proofing anyway, except that - * I am weary of calling enteringPosterasure for a reflective method - * symbol. - * - * Note also that this will typically unbox a primitive value that - * has just been boxed, or will .asInstanceOf[T] an expression which - * is already of type T. But the optimizer will get rid of that, and - * reflective calls are not numerous, so we don't complicate the - * compiler to eliminate them early. - */ - fromAny(genExpr(arg), param.tpe) - } - - val proxyIdent = encodeMethodSym(sym, reflProxy = true) - var callStatement: js.Tree = - genApplyMethod(callTrg, proxyIdent, arguments, jstpe.AnyType) - - if (!isAnyRefPrimitive) { - if (isArrayLikeOp) { - def genRTCall(method: Symbol, args: js.Tree*) = - genApplyMethod(genLoadModule(ScalaRunTimeModule), - method, args.toList) - val isArrayTree = - genRTCall(ScalaRunTime_isArray, callTrg, js.IntLiteral(1)) - callStatement = js.If(isArrayTree, { - name match { - case nme.update => - js.Block( - genRTCall(currentRun.runDefinitions.arrayUpdateMethod, - callTrg, arguments(0), arguments(1)), - js.Undefined()) // Boxed Unit - case nme.apply => - genRTCall(currentRun.runDefinitions.arrayApplyMethod, callTrg, - arguments(0)) - case nme.length => - genRTCall(currentRun.runDefinitions.arrayLengthMethod, callTrg) - case nme.clone_ => - genApplyMethod(callTrg, Object_clone, arguments) - } - }, { - callStatement - })(jstpe.AnyType) - } - - for { - (rtClass, reflBoxClass) <- Seq( - (StringClass, StringClass), - (BoxedDoubleClass, NumberReflectiveCallClass), - (BoxedBooleanClass, BooleanReflectiveCallClass), - (BoxedLongClass, LongReflectiveCallClass) - ) - implMethodSym = matchingSymIn(reflBoxClass) - if implMethodSym != NoSymbol && implMethodSym.isPublic - } { - callStatement = js.If(genIsInstanceOf(callTrg, rtClass.tpe), { - if (implMethodSym.owner == ObjectClass) { - // If the method is defined on Object, we can call it normally. - genApplyMethod(callTrg, implMethodSym, arguments) - } else { - if (rtClass == StringClass) { - val (rtModuleClass, methodIdent) = - encodeRTStringMethodSym(implMethodSym) - val retTpe = implMethodSym.tpe.resultType - val castCallTrg = fromAny(callTrg, StringClass.toTypeConstructor) - val rawApply = genApplyMethod( - genLoadModule(rtModuleClass), - methodIdent, - castCallTrg :: arguments, - toIRType(retTpe)) - // Box the result of the implementing method if required - if (isPrimitiveValueType(retTpe)) - makePrimitiveBox(rawApply, retTpe) - else - rawApply - } else { - val reflBoxClassPatched = { - def isIntOrLongKind(kind: TypeKind) = kind match { - case _:INT | LONG => true - case _ => false - } - if (rtClass == BoxedDoubleClass && - toTypeKind(implMethodSym.tpe.resultType) == DoubleKind && - isIntOrLongKind(toTypeKind(sym.tpe.resultType))) { - // This must be an Int, and not a Double - IntegerReflectiveCallClass - } else { - reflBoxClass - } - } - val castCallTrg = - fromAny(callTrg, - reflBoxClassPatched.primaryConstructor.tpe.params.head.tpe) - val reflBox = genNew(reflBoxClassPatched, - reflBoxClassPatched.primaryConstructor, List(castCallTrg)) - genApplyMethod( - reflBox, - proxyIdent, - arguments, - jstpe.AnyType) - } - } - }, { // else - callStatement - })(jstpe.AnyType) - } - } - - js.Block(callTrgVarDef, callStatement) - } - - /** Ensures that the value of the given tree is boxed. - * @param expr Tree to be boxed if needed. - * @param tpeEnteringPosterasure The type of `expr` as it was entering - * the posterasure phase. - */ - def ensureBoxed(expr: js.Tree, tpeEnteringPosterasure: Type)( - implicit pos: Position): js.Tree = { - - tpeEnteringPosterasure match { - case tpe if isPrimitiveValueType(tpe) => - makePrimitiveBox(expr, tpe) - - case tpe: ErasedValueType => - val boxedClass = tpe.valueClazz - val ctor = boxedClass.primaryConstructor - genNew(boxedClass, ctor, List(expr)) - - case _ => - expr - } - } - - /** Extracts a value typed as Any to the given type after posterasure. - * @param expr Tree to be extracted. - * @param tpeEnteringPosterasure The type of `expr` as it was entering - * the posterasure phase. - */ - def fromAny(expr: js.Tree, tpeEnteringPosterasure: Type)( - implicit pos: Position): js.Tree = { - - tpeEnteringPosterasure match { - case tpe if isPrimitiveValueType(tpe) => - makePrimitiveUnbox(expr, tpe) - - case tpe: ErasedValueType => - val boxedClass = tpe.valueClazz - val unboxMethod = boxedClass.derivedValueClassUnbox - val content = genApplyMethod( - genAsInstanceOf(expr, tpe), unboxMethod, Nil) - if (unboxMethod.tpe.resultType <:< tpe.erasedUnderlying) - content - else - fromAny(content, tpe.erasedUnderlying) - - case tpe => - genAsInstanceOf(expr, tpe) - } - } - - /** Gen a boxing operation (tpe is the primitive type) */ - def makePrimitiveBox(expr: js.Tree, tpe: Type)( - implicit pos: Position): js.Tree = { - toTypeKind(tpe) match { - case VOID => // must be handled at least for JS interop - js.Block(expr, js.Undefined()) - case kind: ValueTypeKind => - if (kind == CharKind) { - genApplyMethod( - genLoadModule(BoxesRunTimeClass), - BoxesRunTime_boxToCharacter, - List(expr)) - } else { - expr // box is identity for all non-Char types - } - case _ => - abort(s"makePrimitiveBox requires a primitive type, found $tpe at $pos") - } - } - - /** Gen an unboxing operation (tpe is the primitive type) */ - def makePrimitiveUnbox(expr: js.Tree, tpe: Type)( - implicit pos: Position): js.Tree = { - toTypeKind(tpe) match { - case VOID => // must be handled at least for JS interop - expr - case kind: ValueTypeKind => - if (kind == CharKind) { - genApplyMethod( - genLoadModule(BoxesRunTimeClass), - BoxesRunTime_unboxToChar, - List(expr)) - } else { - js.Unbox(expr, kind.primitiveCharCode) - } - case _ => - abort(s"makePrimitiveUnbox requires a primitive type, found $tpe at $pos") - } - } - - private def lookupModuleClass(name: String) = { - val module = getModuleIfDefined(name) - if (module == NoSymbol) NoSymbol - else module.moduleClass - } - - lazy val ReflectArrayModuleClass = lookupModuleClass("java.lang.reflect.Array") - lazy val UtilArraysModuleClass = lookupModuleClass("java.util.Arrays") - - /** Gen JS code for a Scala.js-specific primitive method */ - private def genJSPrimitive(tree: Apply, receiver0: Tree, - args: List[Tree], code: Int): js.Tree = { - import jsPrimitives._ - - implicit val pos = tree.pos - - def receiver = genExpr(receiver0) - def genArgs = genPrimitiveJSArgs(tree.symbol, args) - - if (code == DYNNEW) { - // js.Dynamic.newInstance(clazz)(actualArgs:_*) - val (jsClass, actualArgs) = extractFirstArg(genArgs) - js.JSNew(jsClass, actualArgs) - } else if (code == DYNLIT) { - /* We have a call of the form: - * js.Dynamic.literal(name1 = arg1, name2 = arg2, ...) - * or - * js.Dynamic.literal(name1 -> arg1, name2 -> arg2, ...) - * or in general - * js.Dynamic.literal(tup1, tup2, ...) - * - * Translate to: - * var obj = {}; - * obj[name1] = arg1; - * obj[name2] = arg2; - * ... - * obj - * or, if possible, to: - * {name1: arg1, name2: arg2, ... } - */ - - def warnIfDuplicatedKey(keys: List[js.StringLiteral]): Unit = { - val keyNames = keys.map(_.value) - val keyCounts = - keyNames.distinct.map(key => key -> keyNames.count(_ == key)) - val duplicateKeyCounts = keyCounts.filter(1 < _._2) - if (duplicateKeyCounts.nonEmpty) { - reporter.warning(pos, - "Duplicate keys in object literal: " + - duplicateKeyCounts.map { - case (keyName, count) => s""""$keyName" defined $count times""" - }.mkString(", ") + - ". Only the last occurrence is assigned." - ) - } - } - - def keyToPropName(key: js.Tree, index: Int): js.PropertyName = key match { - case key: js.StringLiteral => key - case _ => js.ComputedName(key, "local" + index) - } - - // Extract first arg to future proof against varargs - extractFirstArg(genArgs) match { - // case js.Dynamic.literal("name1" -> ..., nameExpr2 -> ...) - case (js.StringLiteral("apply"), jse.Tuple2List(pairs)) => - warnIfDuplicatedKey(pairs.collect { - case (key: js.StringLiteral, _) => key - }) - js.JSObjectConstr(pairs.zipWithIndex.map { - case ((key, value), index) => (keyToPropName(key, index), value) - }) - - /* case js.Dynamic.literal(x: _*) - * Even though scalac does not support this notation, it is still - * possible to write its expansion by hand: - * js.Dynamic.literal.applyDynamic("apply")(x: _*) - */ - case (js.StringLiteral("apply"), tups) - if tups.exists(_.isInstanceOf[js.JSSpread]) => - // Delegate to a runtime method - val tupsArray = tups match { - case List(js.JSSpread(tupsArray)) => tupsArray - case _ => js.JSArrayConstr(tups) - } - genApplyMethod( - genLoadModule(RuntimePackageModule), - Runtime_jsTupleArray2jsObject, - List(tupsArray)) - - // case js.Dynamic.literal(x, y) - case (js.StringLiteral("apply"), tups) => - // Check for duplicated explicit keys - warnIfDuplicatedKey(jse.extractLiteralKeysFrom(tups)) - - // Evaluate all tuples first - val tuple2Type = encodeClassType(TupleClass(2)) - val evalTuples = tups.map { tup => - js.VarDef(freshLocalIdent("tup"), tuple2Type, mutable = false, - tup)(tup.pos) - } - - // Build the resulting object - val result = js.JSObjectConstr(evalTuples.zipWithIndex.map { - case (evalTuple, index) => - val tupRef = evalTuple.ref - val key = genApplyMethod(tupRef, js.Ident("$$und1__O"), Nil, - jstpe.AnyType) - val value = genApplyMethod(tupRef, js.Ident("$$und2__O"), Nil, - jstpe.AnyType) - keyToPropName(key, index) -> value - }) - - js.Block(evalTuples :+ result) - - // case where another method is called - case (js.StringLiteral(name), _) if name != "apply" => - reporter.error(pos, - s"js.Dynamic.literal does not have a method named $name") - js.Undefined() - case _ => - reporter.error(pos, - s"js.Dynamic.literal.${tree.symbol.name} may not be called directly") - js.Undefined() - } - } else if (code == ARR_CREATE) { - // js.Array.create(elements: _*) - js.JSArrayConstr(genArgs) - } else if (code == CONSTRUCTOROF) { - def fail() = { - reporter.error(pos, - "runtime.constructorOf() must be called with a constant " + - "classOf[T] representing a class extending js.Any " + - "(not a trait nor an object)") - js.Undefined() - } - args match { - case List(Literal(value)) if value.tag == ClazzTag => - val kind = toTypeKind(value.typeValue) - kind match { - case REFERENCE(classSym) if isRawJSType(classSym.tpe) && - !classSym.isTrait && !classSym.isModuleClass => - genPrimitiveJSClass(classSym) - case _ => - fail() - } - case _ => - fail() - } - } else (genArgs match { - case Nil => - code match { - case LINKING_INFO => js.JSLinkingInfo() - case DEBUGGER => js.Debugger() - case UNITVAL => js.Undefined() - case JS_NATIVE => - reporter.error(pos, "js.native may only be used as stub implementation in facade types") - js.Undefined() - } - - case List(arg) => - - /** Factorization of F2JS and F2JSTHIS. */ - def genFunctionToJSFunction(isThisFunction: Boolean): js.Tree = { - val arity = { - val funName = tree.fun.symbol.name.encoded - assert(funName.startsWith("fromFunction"), funName) - funName.stripPrefix("fromFunction").toInt - } - val inputClass = FunctionClass(arity) - val inputIRType = encodeClassType(inputClass) - val applyMeth = getMemberMethod(inputClass, nme.apply) suchThat { s => - val ps = s.paramss - ps.size == 1 && - ps.head.size == arity && - ps.head.forall(_.tpe.typeSymbol == ObjectClass) - } - val fCaptureParam = js.ParamDef(js.Ident("f"), inputIRType, - mutable = false, rest = false) - val jsArity = - if (isThisFunction) arity - 1 - else arity - val jsParams = (1 to jsArity).toList map { - x => js.ParamDef(js.Ident("arg"+x), jstpe.AnyType, - mutable = false, rest = false) - } - js.Closure( - List(fCaptureParam), - jsParams, - genApplyMethod( - fCaptureParam.ref, - applyMeth, - if (isThisFunction) - js.This()(jstpe.AnyType) :: jsParams.map(_.ref) - else - jsParams.map(_.ref)), - List(arg)) - } - - code match { - /** Convert a scala.FunctionN f to a js.FunctionN. */ - case F2JS => - arg match { - /* This case will happen every time we have a Scala lambda - * in js.FunctionN position. We remove the JS function to - * Scala function wrapper, instead of adding a Scala function - * to JS function wrapper. - */ - case JSFunctionToScala(fun, arity) => - fun - case _ => - genFunctionToJSFunction(isThisFunction = false) - } - - /** Convert a scala.FunctionN f to a js.ThisFunction{N-1}. */ - case F2JSTHIS => - genFunctionToJSFunction(isThisFunction = true) - - case DICT_DEL => - // js.Dictionary.delete(arg) - js.JSDelete(js.JSBracketSelect(receiver, arg)) - - case TYPEOF => - // js.typeOf(arg) - genAsInstanceOf(js.JSUnaryOp(js.JSUnaryOp.typeof, arg), - StringClass.tpe) - - case JS_IMPORT => - // js.import(arg) - js.JSImportCall(arg) - - case OBJPROPS => - // js.Object.properties(arg) - genApplyMethod( - genLoadModule(RuntimePackageModule), - Runtime_propertiesOf, - List(arg)) - } - - case List(arg1, arg2) => - code match { - case HASPROP => - // js.Object.hasProperty(arg1, arg2) - /* Here we have an issue with evaluation order of arg1 and arg2, - * since the obvious translation is `arg2 in arg1`, but then - * arg2 is evaluated before arg1. Since this is not a commonly - * used operator, we don't try to avoid unnecessary temp vars, and - * simply always evaluate arg1 in a temp before doing the `in`. - */ - val temp = freshLocalIdent() - js.Block( - js.VarDef(temp, jstpe.AnyType, mutable = false, arg1), - js.Unbox(js.JSBinaryOp(js.JSBinaryOp.in, arg2, - js.VarRef(temp)(jstpe.AnyType)), 'Z')) - - case DELETE => - // js.special.delete(arg1, arg2) - js.JSDelete(js.JSBracketSelect(arg1, arg2)) - } - }) - } - - /** Gen JS code for a primitive JS call (to a method of a subclass of js.Any) - * This is the typed Scala.js to JS bridge feature. Basically it boils - * down to calling the method without name mangling. But other aspects - * come into play: - * * Operator methods are translated to JS operators (not method calls) - * * apply is translated as a function call, i.e. o() instead of o.apply() - * * Scala varargs are turned into JS varargs (see genPrimitiveJSArgs()) - * * Getters and parameterless methods are translated as Selects - * * Setters are translated to Assigns of Selects - */ - private def genPrimitiveJSCall(tree: Apply, isStat: Boolean): js.Tree = { - implicit val pos = tree.pos - - val sym = tree.symbol - val Apply(fun @ Select(receiver0, _), args0) = tree - - val receiver = genExpr(receiver0) - val args = genPrimitiveJSArgs(sym, args0) - - genJSCallGeneric(sym, receiver, args, isStat) - } - - private def genJSSuperCall(tree: Apply, isStat: Boolean): js.Tree = { - implicit val pos = tree.pos - val Apply(fun @ Select(sup @ Super(qual, _), _), args) = tree - val sym = fun.symbol - - /* #3013 `qual` can be `this.$outer()` in some cases since Scala 2.12, - * so we call `genExpr(qual)`, not just `genThis()`. - */ - val genReceiver = genExpr(qual) - lazy val genScalaArgs = genActualArgs(sym, args) - lazy val genJSArgs = genPrimitiveJSArgs(sym, args) - - if (sym.owner == ObjectClass) { - // Normal call anyway - assert(!sym.isClassConstructor, - "Trying to call the super constructor of Object in a " + - s"Scala.js-defined JS class at $pos") - genApplyMethod(genReceiver, sym, genScalaArgs) - } else if (sym.isClassConstructor) { - assert(genReceiver.isInstanceOf[js.This], - "Trying to call a JS super constructor with a non-`this` " + - "receiver at " + pos) - js.JSSuperConstructorCall(genJSArgs) - } else if (isScalaJSDefinedJSClass(sym.owner) && !isExposed(sym)) { - // Reroute to the static method - genApplyJSClassMethod(genReceiver, sym, genScalaArgs) - } else { - genJSCallGeneric(sym, genReceiver, genJSArgs, isStat, - superIn = Some(currentClassSym)) - } - } - - private def genJSCallGeneric(sym: Symbol, receiver: js.Tree, - args: List[js.Tree], isStat: Boolean, superIn: Option[Symbol] = None)( - implicit pos: Position): js.Tree = { - def noSpread = !args.exists(_.isInstanceOf[js.JSSpread]) - val argc = args.size // meaningful only for methods that don't have varargs - - def requireNotSuper(): Unit = { - if (superIn.isDefined) { - reporter.error(pos, - "Illegal super call in Scala.js-defined JS class") - } - } - - def hasExplicitJSEncoding = - sym.hasAnnotation(JSNameAnnotation) || - sym.hasAnnotation(JSBracketAccessAnnotation) || - sym.hasAnnotation(JSBracketCallAnnotation) - - val boxedResult = sym.name match { - case JSUnaryOpMethodName(code) if argc == 0 => - requireNotSuper() - js.JSUnaryOp(code, receiver) - - case JSBinaryOpMethodName(code) if argc == 1 => - requireNotSuper() - js.JSBinaryOp(code, receiver, args.head) - - case nme.apply if sym.owner.isSubClass(JSThisFunctionClass) => - requireNotSuper() - js.JSBracketMethodApply(receiver, js.StringLiteral("call"), args) - - case nme.apply if !hasExplicitJSEncoding => - requireNotSuper() - js.JSFunctionApply(receiver, args) - - case _ => - def jsFunName: js.Tree = genExpr(jsNameOf(sym)) - - def genSuperReference(propName: js.Tree): js.Tree = { - superIn.fold[js.Tree] { - js.JSBracketSelect(receiver, propName) - } { superInSym => - js.JSSuperBracketSelect( - jstpe.ClassType(encodeClassFullName(superInSym)), - receiver, propName) - } - } - - def genSelectGet(propName: js.Tree): js.Tree = { - if (superIn.exists(isScalaJSDefinedAnonJSClass(_))) { - // #3055 - genApplyMethod( - genLoadModule(RuntimePackageModule), - Runtime_jsObjectSuperGet, - List(receiver, propName)) - } else { - genSuperReference(propName) - } - } - - def genSelectSet(propName: js.Tree, value: js.Tree): js.Tree = { - if (superIn.exists(isScalaJSDefinedAnonJSClass(_))) { - // #3055 - genApplyMethod( - genLoadModule(RuntimePackageModule), - Runtime_jsObjectSuperSet, - List(receiver, propName, value)) - } else { - js.Assign(genSuperReference(propName), value) - } - } - - def genCall(methodName: js.Tree, args: List[js.Tree]): js.Tree = { - superIn.fold[js.Tree] { - js.JSBracketMethodApply( - receiver, methodName, args) - } { superInSym => - if (isScalaJSDefinedAnonJSClass(superInSym)) { - // #3055 - val superClassType = - jstpe.ClassType(encodeClassFullName(superInSym.superClass)) - val superProto = js.JSBracketSelect( - js.LoadJSConstructor(superClassType), - js.StringLiteral("prototype")) - val superMethod = - js.JSBracketSelect(superProto, methodName) - js.JSBracketMethodApply( - superMethod, - js.StringLiteral("call"), - receiver :: args) - } else { - js.JSSuperBracketCall( - jstpe.ClassType(encodeClassFullName(superInSym)), - receiver, methodName, args) - } - } - } - - if (jsInterop.isJSGetter(sym)) { - assert(noSpread && argc == 0, - s"wrong number of arguments for call to JS getter $sym at $pos") - genSelectGet(jsFunName) - } else if (jsInterop.isJSSetter(sym)) { - assert(noSpread && argc == 1, - s"wrong number of arguments for call to JS setter $sym at $pos") - genSelectSet(jsFunName, args.head) - } else if (jsInterop.isJSBracketAccess(sym)) { - assert(noSpread && (argc == 1 || argc == 2), - s"@JSBracketAccess methods should have 1 or 2 non-varargs arguments") - args match { - case List(keyArg) => - genSelectGet(keyArg) - case List(keyArg, valueArg) => - genSelectSet(keyArg, valueArg) - } - } else if (jsInterop.isJSBracketCall(sym)) { - val (methodName, actualArgs) = extractFirstArg(args) - genCall(methodName, actualArgs) - } else { - genCall(jsFunName, args) - } - } - - boxedResult match { - case js.Assign(_, _) => - boxedResult - case _ if isStat => - boxedResult - case _ => - fromAny(boxedResult, - enteringPhase(currentRun.posterasurePhase)(sym.tpe.resultType)) - } - } - - private object JSUnaryOpMethodName { - private val map = Map( - nme.UNARY_+ -> js.JSUnaryOp.+, - nme.UNARY_- -> js.JSUnaryOp.-, - nme.UNARY_~ -> js.JSUnaryOp.~, - nme.UNARY_! -> js.JSUnaryOp.! - ) - - def unapply(name: TermName): Option[js.JSUnaryOp.Code] = - map.get(name) - } - - private object JSBinaryOpMethodName { - private val map = Map( - nme.ADD -> js.JSBinaryOp.+, - nme.SUB -> js.JSBinaryOp.-, - nme.MUL -> js.JSBinaryOp.*, - nme.DIV -> js.JSBinaryOp./, - nme.MOD -> js.JSBinaryOp.%, - - nme.LSL -> js.JSBinaryOp.<<, - nme.ASR -> js.JSBinaryOp.>>, - nme.LSR -> js.JSBinaryOp.>>>, - nme.OR -> js.JSBinaryOp.|, - nme.AND -> js.JSBinaryOp.&, - nme.XOR -> js.JSBinaryOp.^, - - nme.LT -> js.JSBinaryOp.<, - nme.LE -> js.JSBinaryOp.<=, - nme.GT -> js.JSBinaryOp.>, - nme.GE -> js.JSBinaryOp.>=, - - nme.ZAND -> js.JSBinaryOp.&&, - nme.ZOR -> js.JSBinaryOp.|| - ) - - def unapply(name: TermName): Option[js.JSBinaryOp.Code] = - map.get(name) - } - - /** Extract the first argument to a primitive JS call. - * This is nothing else than decomposing into head and tail, except that - * we assert that the first element is not a JSSpread. - */ - private def extractFirstArg(args: List[js.Tree]): (js.Tree, List[js.Tree]) = { - assert(args.nonEmpty, - "Trying to extract the first argument of an empty argument list") - val firstArg = args.head - assert(!firstArg.isInstanceOf[js.JSSpread], - "Trying to extract the first argument of an argument list starting " + - "with a Spread argument: " + firstArg) - (firstArg, args.tail) - } - - /** Gen JS code for new java.lang.String(...) - * Proxies calls to method newString on object - * scala.scalajs.runtime.RuntimeString with proper arguments - */ - private def genNewString(tree: Apply): js.Tree = { - implicit val pos = tree.pos - val Apply(fun @ Select(_, _), args0) = tree - - val ctor = fun.symbol - val args = args0 map genExpr - - // Filter members of target module for matching member - val compMembers = for { - mem <- RuntimeStringModule.tpe.members - if mem.name == jsnme.newString && ctor.tpe.matches(mem.tpe) - } yield mem - - if (compMembers.isEmpty) { - reporter.error(pos, - s"""Could not find implementation for constructor of java.lang.String - |with type ${ctor.tpe}. Constructors on java.lang.String - |are forwarded to the companion object of - |scala.scalajs.runtime.RuntimeString""".stripMargin) - js.Undefined() - } else { - assert(compMembers.size == 1, - s"""For constructor with type ${ctor.tpe} on java.lang.String, - |found multiple companion module members.""".stripMargin) - - // Emit call to companion object - genApplyMethod( - genLoadModule(RuntimeStringModule), compMembers.head, args) - } - } - - /** Gen JS code for calling a method on java.lang.String. - * - * Forwards call on java.lang.String to the module - * scala.scalajs.runtime.RuntimeString. - */ - private def genStringCall(tree: Apply): js.Tree = { - implicit val pos = tree.pos - - val sym = tree.symbol - - // Deconstruct tree and create receiver and argument JS expressions - val Apply(Select(receiver0, _), args0) = tree - val receiver = genExpr(receiver0) - val args = args0 map genExpr - - // Emit call to the RuntimeString module - val (rtModuleClass, methodIdent) = encodeRTStringMethodSym(sym) - genApplyMethod( - genLoadModule(rtModuleClass), - methodIdent, - receiver :: args, - toIRType(tree.tpe)) - } - - /** Gen JS code for a new of a raw JS class (subclass of js.Any) */ - private def genPrimitiveJSNew(tree: Apply): js.Tree = { - implicit val pos = tree.pos - - val Apply(fun @ Select(New(tpt), _), args0) = tree - val cls = tpt.tpe.typeSymbol - val ctor = fun.symbol - - val args = genPrimitiveJSArgs(ctor, args0) - - if (cls == JSObjectClass && args.isEmpty) - js.JSObjectConstr(Nil) - else if (cls == JSArrayClass && args.isEmpty) - js.JSArrayConstr(Nil) - else if (isScalaJSDefinedAnonJSClass(cls)) - genAnonSJSDefinedNew(cls, args, fun.pos) - else - js.JSNew(genPrimitiveJSClass(cls), args) - } - - /** Gen JS code representing a JS class (subclass of js.Any) */ - private def genPrimitiveJSClass(sym: Symbol)( - implicit pos: Position): js.Tree = { - assert(!isStaticModule(sym) && !sym.isTraitOrInterface, - s"genPrimitiveJSClass called with non-class $sym") - js.LoadJSConstructor(jstpe.ClassType(encodeClassFullName(sym))) - } - - /** Gen actual actual arguments to Scala method call. - * - * Returns a list of the transformed arguments. - * - * This tries to optimize repeated arguments (varargs) by turning them - * into JS arrays wrapped in the appropriate Seq, rather than Scala - * arrays. - */ - private def genActualArgs(sym: Symbol, args: List[Tree])( - implicit pos: Position): List[js.Tree] = { - val wereRepeated = exitingPhase(currentRun.typerPhase) { - /* Do NOT use `params` instead of `paramss.flatten` here! Exiting - * typer, `params` only contains the *first* parameter list. - * This was causing #2265 and #2741. - */ - sym.tpe.paramss.flatten.map(p => isScalaRepeatedParamType(p.tpe)) - } - - if (wereRepeated.size > args.size) { - // Should not happen, but let's not crash - args.map(genExpr) - } else { - /* Arguments that are in excess compared to the type signature after - * typer are lambda-lifted arguments. They cannot be repeated, hence - * the extension to `false`. - */ - for ((arg, wasRepeated) <- args.zipAll(wereRepeated, EmptyTree, false)) yield { - if (wasRepeated) { - tryGenRepeatedParamAsJSArray(arg, handleNil = false).fold { - genExpr(arg) - } { genArgs => - genJSArrayToVarArgs(js.JSArrayConstr(genArgs)) - } - } else { - genExpr(arg) - } - } - } - } - - /** Gen actual actual arguments to a primitive JS call. - * - * * Repeated arguments (varargs) are expanded - * * Default arguments are omitted or replaced by undefined - * * All arguments are boxed - * - * Repeated arguments that cannot be expanded at compile time (i.e., if a - * Seq is passed to a varargs parameter with the syntax `seq: _*`) will be - * wrapped in a [[js.JSSpread]] node to be expanded at runtime. - */ - private def genPrimitiveJSArgs(sym: Symbol, args: List[Tree])( - implicit pos: Position): List[js.Tree] = { - - /* lambdalift might have to introduce some parameters when transforming - * nested Scala.js-defined JS classes. Hence, the list of parameters - * exiting typer and entering posterasure might not be compatible with - * the list of actual arguments we receive now. - * - * We therefore need to establish of list of formal parameters based on - * the current signature of `sym`, but have to look back in time to see - * whether they were repeated and what was their type (for those that - * were already present at the time). - * - * Unfortunately, for some reason lambdalift creates new symbol *even - * for parameters originally in the signature* when doing so! That is - * why we use the *names* of the parameters as a link through time, - * rather than the symbols. - * - * This is pretty fragile, but fortunately we have a huge test suite to - * back us up should scalac alter its behavior. - */ - - val wereRepeated = exitingPhase(currentRun.typerPhase) { - for { - params <- sym.tpe.paramss - param <- params - } yield { - param.name -> isScalaRepeatedParamType(param.tpe) - } - }.toMap - - val paramTpes = enteringPhase(currentRun.posterasurePhase) { - for (param <- sym.tpe.params) - yield param.name -> param.tpe - }.toMap - - var reversedArgs: List[js.Tree] = Nil - - for ((arg, paramSym) <- args zip sym.tpe.params) { - val wasRepeated = wereRepeated.getOrElse(paramSym.name, false) - if (wasRepeated) { - reversedArgs = - genPrimitiveJSRepeatedParam(arg) reverse_::: reversedArgs - } else { - val unboxedArg = genExpr(arg) - val boxedArg = unboxedArg match { - case js.UndefinedParam() => - unboxedArg - case _ => - val tpe = paramTpes.getOrElse(paramSym.name, paramSym.tpe) - ensureBoxed(unboxedArg, tpe) - } - reversedArgs ::= boxedArg - } - } - - /* Remove all consecutive js.UndefinedParam's at the end of the argument - * list. No check is performed whether they may be there, since they will - * only be placed where default arguments can be anyway. - */ - reversedArgs = reversedArgs.dropWhile(_.isInstanceOf[js.UndefinedParam]) - - // Find remaining js.UndefinedParam and replace by js.Undefined. This can - // happen with named arguments or when multiple argument lists are present - reversedArgs = reversedArgs map { - case js.UndefinedParam() => js.Undefined() - case arg => arg - } - - reversedArgs.reverse - } - - /** Gen JS code for a repeated param of a primitive JS method - * In this case `arg` has type Seq[T] for some T, but the result should - * be an expanded list of the elements in the sequence. So this method - * takes care of the conversion. - * It is specialized for the shapes of tree generated by the desugaring - * of repeated params in Scala, so that these are actually expanded at - * compile-time. - * Otherwise, it returns a JSSpread with the Seq converted to a js.Array. - */ - private def genPrimitiveJSRepeatedParam(arg: Tree): List[js.Tree] = { - tryGenRepeatedParamAsJSArray(arg, handleNil = true) getOrElse { - /* Fall back to calling runtime.genTraversableOnce2jsArray - * to perform the conversion to js.Array, then wrap in a Spread - * operator. - */ - implicit val pos = arg.pos - val jsArrayArg = genApplyMethod( - genLoadModule(RuntimePackageModule), - Runtime_genTraversableOnce2jsArray, - List(genExpr(arg))) - List(js.JSSpread(jsArrayArg)) - } - } - - /** Try and expand a repeated param (xs: T*) at compile-time. - * This method recognizes the shapes of tree generated by the desugaring - * of repeated params in Scala, and expands them. - * If `arg` does not have the shape of a generated repeated param, this - * method returns `None`. - */ - private def tryGenRepeatedParamAsJSArray(arg: Tree, - handleNil: Boolean): Option[List[js.Tree]] = { - implicit val pos = arg.pos - - // Given a method `def foo(args: T*)` - arg match { - // foo(arg1, arg2, ..., argN) where N > 0 - case MaybeAsInstanceOf(WrapArray( - MaybeAsInstanceOf(ArrayValue(tpt, elems)))) => - /* Value classes in arrays are already boxed, so no need to use - * the type before erasure. - */ - val elemTpe = tpt.tpe - Some(elems.map(e => ensureBoxed(genExpr(e), elemTpe))) - - // foo() - case Select(_, _) if handleNil && arg.symbol == NilModule => - Some(Nil) - - // foo(argSeq:_*) - cannot be optimized - case _ => - None - } - } - - object MaybeAsInstanceOf { - def unapply(tree: Tree): Some[Tree] = tree match { - case Apply(TypeApply(asInstanceOf_? @ Select(base, _), _), _) - if asInstanceOf_?.symbol == Object_asInstanceOf => - Some(base) - case _ => - Some(tree) - } - } - - object WrapArray { - private val wrapArrayModule = - if (hasNewCollections) ScalaRunTimeModule - else PredefModule - - val wrapRefArrayMethod: Symbol = - getMemberMethod(wrapArrayModule, nme.wrapRefArray) - - private val isWrapArray: Set[Symbol] = { - Seq( - nme.wrapRefArray, - nme.wrapByteArray, - nme.wrapShortArray, - nme.wrapCharArray, - nme.wrapIntArray, - nme.wrapLongArray, - nme.wrapFloatArray, - nme.wrapDoubleArray, - nme.wrapBooleanArray, - nme.wrapUnitArray, - nme.genericWrapArray - ).map(getMemberMethod(wrapArrayModule, _)).toSet - } - - def unapply(tree: Apply): Option[Tree] = tree match { - case Apply(wrapArray_?, List(wrapped)) - if isWrapArray(wrapArray_?.symbol) => - Some(wrapped) - case _ => - None - } - } - - /** Wraps a `js.Array` to use as varargs. */ - def genJSArrayToVarArgs(arrayRef: js.Tree)( - implicit pos: Position): js.Tree = { - genApplyMethod(genLoadModule(RuntimePackageModule), - Runtime_toScalaVarArgs, List(arrayRef)) - } - - // Synthesizers for raw JS functions --------------------------------------- - - /** Try and generate JS code for an anonymous function class. - * - * Returns Some() if the class could be rewritten that way, None - * otherwise. - * - * We make the following assumptions on the form of such classes: - * - It is an anonymous function - * - Includes being anonymous, final, and having exactly one constructor - * - It is not a PartialFunction - * - It has no field other than param accessors - * - It has exactly one constructor - * - It has exactly one non-bridge method apply if it is not specialized, - * or a method apply$...$sp and a forwarder apply if it is specialized. - * - As a precaution: it is synthetic - * - * From a class looking like this: - * - * final class (outer, capture1, ..., captureM) extends AbstractionFunctionN[...] { - * def apply(param1, ..., paramN) = { - * - * } - * } - * new (o, c1, ..., cM) - * - * we generate a function: - * - * lambda[notype]( - * outer, capture1, ..., captureM, param1, ..., paramN) { - * - * } - * - * so that, at instantiation point, we can write: - * - * new AnonFunctionN(function) - * - * the latter tree is returned in case of success. - * - * Trickier things apply when the function is specialized. - */ - private def tryGenAnonFunctionClass(cd: ClassDef, - capturedArgs: List[js.Tree]): Option[js.Tree] = { - // scalastyle:off return - implicit val pos = cd.pos - val sym = cd.symbol - assert(sym.isAnonymousFunction, - s"tryGenAndRecordAnonFunctionClass called with non-anonymous function $cd") - - if (!sym.superClass.fullName.startsWith("scala.runtime.AbstractFunction")) { - /* This is an anonymous class for a non-LMF capable SAM in 2.12. - * We must not rewrite it, as it would then not inherit from the - * appropriate parent class and/or interface. - */ - None - } else { - nestedGenerateClass(sym) { - val (functionBase, arity) = - tryGenAnonFunctionClassGeneric(cd, capturedArgs)(_ => return None) - - Some(JSFunctionToScala(functionBase, arity)) - } - } - // scalastyle:on return - } - - /** Constructor and extractor object for a tree that converts a JavaScript - * function into a Scala function. - */ - private object JSFunctionToScala { - private val AnonFunPrefScala = - "scala.scalajs.runtime.AnonFunction" - private val AnonFunPrefJS = - "sjsr_AnonFunction" - - def apply(jsFunction: js.Tree, arity: Int)( - implicit pos: Position): js.Tree = { - val clsSym = getRequiredClass(AnonFunPrefScala + arity) - val ctor = clsSym.tpe.member(nme.CONSTRUCTOR) - genNew(clsSym, ctor, List(jsFunction)) - } - - def unapply(tree: js.New): Option[(js.Tree, Int)] = tree match { - case js.New(jstpe.ClassType(wrapperName), _, List(fun)) - if wrapperName.startsWith(AnonFunPrefJS) => - val arityStr = wrapperName.substring(AnonFunPrefJS.length) - try { - Some((fun, arityStr.toInt)) - } catch { - case e: NumberFormatException => None - } - - case _ => - None - } - } - - /** Gen JS code for a raw JS function class. - * - * This is called when emitting a ClassDef that represents an anonymous - * class extending `js.FunctionN`. These are generated by the SAM - * synthesizer when the target type is a `js.FunctionN`. Since JS - * functions are not classes, we deconstruct the ClassDef, then - * reconstruct it to be a genuine Closure. - * - * Compared to `tryGenAnonFunctionClass()`, this function must - * always succeed, because we really cannot afford keeping them as - * anonymous classes. The good news is that it can do so, because the - * body of SAM lambdas is hoisted in the enclosing class. Hence, the - * apply() method is just a forwarder to calling that hoisted method. - * - * From a class looking like this: - * - * final class (outer, capture1, ..., captureM) extends js.FunctionN[...] { - * def apply(param1, ..., paramN) = { - * outer.lambdaImpl(param1, ..., paramN, capture1, ..., captureM) - * } - * } - * new (o, c1, ..., cM) - * - * we generate a function: - * - * lambda[notype]( - * outer, capture1, ..., captureM, param1, ..., paramN) { - * outer.lambdaImpl(param1, ..., paramN, capture1, ..., captureM) - * } - */ - def genRawJSFunction(cd: ClassDef, captures: List[js.Tree]): js.Tree = { - val sym = cd.symbol - assert(isRawJSFunctionDef(sym), - s"genAndRecordRawJSFunctionClass called with non-JS function $cd") - - nestedGenerateClass(sym) { - val (function, _) = tryGenAnonFunctionClassGeneric(cd, captures)(msg => - abort(s"Could not generate raw function for JS function: $msg")) - - function - } - } - - /** Code common to tryGenAndRecordAnonFunctionClass and - * genAndRecordRawJSFunctionClass. - */ - private def tryGenAnonFunctionClassGeneric(cd: ClassDef, - initialCapturedArgs: List[js.Tree])( - fail: (=> String) => Nothing): (js.Tree, Int) = { - implicit val pos = cd.pos - val sym = cd.symbol - - // First checks - - if (sym.isSubClass(PartialFunctionClass)) - fail(s"Cannot rewrite PartialFunction $cd") - - // First step: find the apply method def, and collect param accessors - - var paramAccessors: List[Symbol] = Nil - var applyDef: DefDef = null - - def gen(tree: Tree): Unit = { - tree match { - case EmptyTree => () - case Template(_, _, body) => body foreach gen - case vd @ ValDef(mods, name, tpt, rhs) => - val fsym = vd.symbol - if (!fsym.isParamAccessor) - fail(s"Found field $fsym which is not a param accessor in anon function $cd") - - if (fsym.isPrivate) { - paramAccessors ::= fsym - } else { - // Uh oh ... an inner something will try to access my fields - fail(s"Found a non-private field $fsym in $cd") - } - case dd: DefDef => - val ddsym = dd.symbol - if (ddsym.isClassConstructor) { - if (!ddsym.isPrimaryConstructor) - fail(s"Non-primary constructor $ddsym in anon function $cd") - } else { - val name = dd.name.toString - if (name == "apply" || (ddsym.isSpecialized && name.startsWith("apply$"))) { - if ((applyDef eq null) || ddsym.isSpecialized) - applyDef = dd - } else { - // Found a method we cannot encode in the rewriting - fail(s"Found a non-apply method $ddsym in $cd") - } - } - case _ => - fail("Illegal tree in gen of genAndRecordAnonFunctionClass(): " + tree) - } - } - gen(cd.impl) - paramAccessors = paramAccessors.reverse // preserve definition order - - if (applyDef eq null) - fail(s"Did not find any apply method in anon function $cd") - - withNewLocalNameScope { - // Second step: build the list of useful constructor parameters - - val ctorParams = sym.primaryConstructor.tpe.params - - if (paramAccessors.size != ctorParams.size && - !(paramAccessors.size == ctorParams.size-1 && - ctorParams.head.unexpandedName == jsnme.arg_outer)) { - fail( - s"Have param accessors $paramAccessors but "+ - s"ctor params $ctorParams in anon function $cd") - } - - val hasUnusedOuterCtorParam = paramAccessors.size != ctorParams.size - val usedCtorParams = - if (hasUnusedOuterCtorParam) ctorParams.tail - else ctorParams - val ctorParamDefs = usedCtorParams map { p => - // in the apply method's context - js.ParamDef(encodeLocalSym(p)(p.pos), toIRType(p.tpe), - mutable = false, rest = false)(p.pos) - } - - // Third step: emit the body of the apply method def - - val applyMethod = withScopedVars( - paramAccessorLocals := (paramAccessors zip ctorParamDefs).toMap, - tryingToGenMethodAsJSFunction := true - ) { - try { - genMethodWithCurrentLocalNameScope(applyDef).getOrElse( - abort(s"Oops, $applyDef did not produce a method")) - } catch { - case e: CancelGenMethodAsJSFunction => - fail(e.getMessage) - } - } - - // Fourth step: patch the body to unbox parameters and box result - - val js.MethodDef(_, _, params, _, body) = applyMethod - val (patchedParams, patchedBody) = - patchFunBodyWithBoxes(applyDef.symbol, params, body.get) - - // Fifth step: build the js.Closure - - val isThisFunction = JSThisFunctionClasses.exists(sym isSubClass _) - assert(!isThisFunction || patchedParams.nonEmpty, - s"Empty param list in ThisFunction: $cd") - - val capturedArgs = - if (hasUnusedOuterCtorParam) initialCapturedArgs.tail - else initialCapturedArgs - assert(capturedArgs.size == ctorParamDefs.size, - s"$capturedArgs does not match $ctorParamDefs") - - val closure = { - if (isThisFunction) { - val thisParam :: actualParams = patchedParams - js.Closure( - ctorParamDefs, - actualParams, - js.Block( - js.VarDef(thisParam.name, thisParam.ptpe, mutable = false, - js.This()(thisParam.ptpe)(thisParam.pos))(thisParam.pos), - patchedBody), - capturedArgs) - } else { - js.Closure(ctorParamDefs, patchedParams, patchedBody, capturedArgs) - } - } - - val arity = params.size - - (closure, arity) - } - } - - /** Generate JS code for an anonymous function - * - * Anonymous functions survive until the backend in 2.11 under - * -Ydelambdafy:method (for Scala function types) and in 2.12 for any - * LambdaMetaFactory-capable type. - * - * When they do, their body is always of the form - * {{{ - * EnclosingClass.this.someMethod(args) - * }}} - * where the args are either formal parameters of the lambda, or local - * variables or the enclosing def. The latter must be captured. - * - * We identify the captures using the same method as the `delambdafy` - * phase. We have an additional hack for `this`. - * - * To translate them, we first construct a JS closure for the body: - * {{{ - * lambda( - * _this, capture1, ..., captureM, arg1, ..., argN) { - * _this.someMethod(arg1, ..., argN, capture1, ..., captureM) - * } - * }}} - * In the closure, input params are unboxed before use, and the result of - * `someMethod()` is boxed back. - * - * Then, we wrap that closure in a class satisfying the expected type. - * For Scala function types, we use the existing - * `scala.scalajs.runtime.AnonFunctionN` from the library. For other - * LMF-capable types, we generate a class on the fly, which looks like - * this: - * {{{ - * class AnonFun extends Object with FunctionalInterface { - * val f: any - * def (f: any) { - * super(); - * this.f = f - * } - * def theSAMMethod(params: Types...): Type = - * unbox((this.f)(boxParams...)) - * } - * }}} - */ - private def genAnonFunction(originalFunction: Function): js.Tree = { - implicit val pos = originalFunction.pos - val Function(paramTrees, Apply( - targetTree @ Select(receiver, _), allArgs0)) = originalFunction - - val captureSyms = - global.delambdafy.FreeVarTraverser.freeVarsOf(originalFunction) - val target = targetTree.symbol - val params = paramTrees.map(_.symbol) - - val allArgs = allArgs0 map genExpr - - val formalCaptures = captureSyms.toList map { sym => - // Use the anonymous function pos - js.ParamDef(encodeLocalSym(sym)(pos), toIRType(sym.tpe), - mutable = false, rest = false)(pos) - } - val actualCaptures = formalCaptures.map(_.ref) - - val formalArgs = params map { p => - // Use the param pos - js.ParamDef(encodeLocalSym(p)(p.pos), toIRType(p.tpe), - mutable = false, rest = false)(p.pos) - } - - val isInImplClass = isImplClass(target.owner) - - val (allFormalCaptures, body, allActualCaptures) = if (!isInImplClass) { - val thisActualCapture = genExpr(receiver) - val thisFormalCapture = js.ParamDef( - freshLocalIdent("this")(receiver.pos), - thisActualCapture.tpe, mutable = false, rest = false)(receiver.pos) - val thisCaptureArg = thisFormalCapture.ref - - val body = if (isRawJSType(receiver.tpe) && target.owner != ObjectClass) { - assert(isScalaJSDefinedJSClass(target.owner) && !isExposed(target), - s"A Function lambda is trying to call an exposed JS method ${target.fullName}") - genApplyJSClassMethod(thisCaptureArg, target, allArgs) - } else { - genApplyMethod(thisCaptureArg, target, allArgs) - } - - (thisFormalCapture :: formalCaptures, - body, thisActualCapture :: actualCaptures) - } else { - val body = genTraitImplApply(target, allArgs) - - (formalCaptures, body, actualCaptures) - } - - val (patchedFormalArgs, patchedBody) = { - patchFunBodyWithBoxes(target, formalArgs, body, - useParamsBeforeLambdaLift = true) - } - - val closure = js.Closure( - allFormalCaptures, - patchedFormalArgs, - patchedBody, - allActualCaptures) - - // Wrap the closure in the appropriate box for the SAM type - val funSym = originalFunction.tpe.typeSymbolDirect - if (isFunctionSymbol(funSym)) { - /* This is a scala.FunctionN. We use the existing AnonFunctionN - * wrapper. - */ - JSFunctionToScala(closure, params.size) - } else { - /* This is an arbitrary SAM type (can only happen in 2.12). - * We have to synthesize a class like LambdaMetaFactory would do on - * the JVM. - */ - val sam = originalFunction.attachments.get[SAMFunctionCompat].getOrElse { - abort(s"Cannot find the SAMFunction attachment on $originalFunction at $pos") - } - - val samWrapperClassName = synthesizeSAMWrapper(funSym, sam) - js.New(jstpe.ClassType(samWrapperClassName), js.Ident("init___O"), - List(closure)) - } - } - - private def synthesizeSAMWrapper(funSym: Symbol, samInfo: SAMFunctionCompat)( - implicit pos: Position): String = { - val intfName = encodeClassFullName(funSym) - - val suffix = { - generatedSAMWrapperCount.value += 1 - // LambdaMetaFactory names classes like this - "$$Lambda$" + generatedSAMWrapperCount.value - } - val generatedClassName = encodeClassFullName(currentClassSym) + suffix - - val classType = jstpe.ClassType(generatedClassName) - - // val f$1: Any - val fFieldIdent = js.Ident("f$1", Some("f")) - val fFieldDef = js.FieldDef(static = false, fFieldIdent, jstpe.AnyType, - mutable = false) - - // def this(f: Any) = { this.f$1 = f; super() } - val ctorDef = { - val fParamDef = js.ParamDef(js.Ident("f"), jstpe.AnyType, - mutable = false, rest = false) - js.MethodDef(static = false, js.Ident("init___O"), List(fParamDef), - jstpe.NoType, - Some(js.Block(List( - js.Assign( - js.Select(js.This()(classType), fFieldIdent)(jstpe.AnyType), - fParamDef.ref), - js.ApplyStatically(js.This()(classType), - jstpe.ClassType(ir.Definitions.ObjectClass), - js.Ident("init___"), - Nil)(jstpe.NoType)))))( - js.OptimizerHints.empty, None) - } - - // Compute the set of method symbols that we need to implement - val sams = { - val samsBuilder = List.newBuilder[Symbol] - val seenEncodedNames = mutable.Set.empty[String] - - /* scala/bug#10512: any methods which `samInfo.sam` overrides need - * bridges made for them. - * On Scala < 2.12.5, `synthCls` is polyfilled to `NoSymbol` and hence - * `samBridges` will always be empty. This causes our compiler to be - * bug-compatible on these versions. - */ - val synthCls = samInfo.synthCls - val samBridges = if (synthCls == NoSymbol) { - Nil - } else { - import scala.reflect.internal.Flags.BRIDGE - synthCls.info.findMembers(excludedFlags = 0L, requiredFlags = BRIDGE).toList - } - - for (sam <- samInfo.sam :: samBridges) { - /* Remove duplicates, e.g., if we override the same method declared - * in two super traits. - */ - if (seenEncodedNames.add(encodeMethodSym(sam).name)) - samsBuilder += sam - } - - samsBuilder.result() - } - - // def samMethod(...params): resultType = this.f$f(...params) - val samMethodDefs = for (sam <- sams) yield { - val jsParams = for (param <- sam.tpe.params) yield { - js.ParamDef(encodeLocalSym(param), toIRType(param.tpe), - mutable = false, rest = false) - } - val resultType = toIRType(sam.tpe.finalResultType) - - val actualParams = enteringPhase(currentRun.posterasurePhase) { - for ((formal, param) <- jsParams.zip(sam.tpe.params)) - yield (formal.ref, param.tpe) - }.map((ensureBoxed _).tupled) - - val call = js.JSFunctionApply( - js.Select(js.This()(classType), fFieldIdent)(jstpe.AnyType), - actualParams) - - val body = fromAny(call, enteringPhase(currentRun.posterasurePhase) { - sam.tpe.finalResultType - }) - - js.MethodDef(static = false, encodeMethodSym(sam), - jsParams, resultType, Some(body))( - js.OptimizerHints.empty, None) - } - - // The class definition - val classDef = js.ClassDef( - js.Ident(generatedClassName), - ClassKind.Class, - Some(js.Ident(ir.Definitions.ObjectClass)), - List(js.Ident(intfName)), - None, - fFieldDef :: ctorDef :: samMethodDefs)( - js.OptimizerHints.empty.withInline(true)) - - generatedClasses += ((currentClassSym.get, Some(suffix), classDef)) - - generatedClassName - } - - private def patchFunBodyWithBoxes(methodSym: Symbol, - params: List[js.ParamDef], body: js.Tree, - useParamsBeforeLambdaLift: Boolean = false)( - implicit pos: Position): (List[js.ParamDef], js.Tree) = { - val methodType = enteringPhase(currentRun.posterasurePhase)(methodSym.tpe) - - // See the comment in genPrimitiveJSArgs for a rationale about this - val paramTpes = enteringPhase(currentRun.posterasurePhase) { - for (param <- methodType.params) - yield param.name -> param.tpe - }.toMap - - /* Normally, we should work with the list of parameters as seen right - * now. But when generating an anonymous function from a Function node, - * the `methodSym` we use is the *target* of the inner call, not the - * enclosing method for which we're patching the params and body. This - * is a hack which we have to do because there is no such enclosing - * method in that case. When we use the target, the list of symbols for - * formal parameters that we want to see is that before lambdalift, not - * the one we see right now. - */ - val paramSyms = { - if (useParamsBeforeLambdaLift) - enteringPhase(currentRun.phaseNamed("lambdalift"))(methodSym.tpe.params) - else - methodSym.tpe.params - } - - val (patchedParams, paramsLocal) = (for { - (param, paramSym) <- params zip paramSyms - } yield { - val paramTpe = paramTpes.getOrElse(paramSym.name, paramSym.tpe) - val paramName = param.name - val js.Ident(name, origName) = paramName - val newOrigName = origName.getOrElse(name) - val newNameIdent = freshLocalIdent(name)(paramName.pos) - val patchedParam = js.ParamDef(newNameIdent, jstpe.AnyType, - mutable = false, rest = param.rest)(param.pos) - val paramLocal = js.VarDef(paramName, param.ptpe, mutable = false, - fromAny(patchedParam.ref, paramTpe)) - (patchedParam, paramLocal) - }).unzip - - assert(!methodSym.isClassConstructor, - s"Trying to patchFunBodyWithBoxes for constructor ${methodSym.fullName}") - - val patchedBody = js.Block( - paramsLocal :+ ensureBoxed(body, methodType.resultType)) - - (patchedParams, patchedBody) - } - - // Methods to deal with JSName --------------------------------------------- - - def genPropertyName(name: JSName)(implicit pos: Position): js.PropertyName = { - name match { - case JSName.Literal(name) => js.StringLiteral(name) - - case JSName.Computed(sym) => - js.ComputedName(genComputedJSName(sym), encodeComputedNameIdentity(sym)) - } - } - - def genExpr(name: JSName)(implicit pos: Position): js.Tree = name match { - case JSName.Literal(name) => js.StringLiteral(name) - case JSName.Computed(sym) => genComputedJSName(sym) - } - - private def genComputedJSName(sym: Symbol)(implicit pos: Position): js.Tree = { - /* By construction (i.e. restriction in PrepJSInterop), we know that sym - * must be a static method. - * Therefore, at this point, we can invoke it by loading its owner and - * calling it. - */ - val module = genLoadModule(sym.owner) - - if (isRawJSType(sym.owner.tpe)) { - if (!isScalaJSDefinedJSClass(sym.owner) || isExposed(sym)) - genJSCallGeneric(sym, module, args = Nil, isStat = false) - else - genApplyJSClassMethod(module, sym, arguments = Nil) - } else { - genApplyMethod(module, sym, arguments = Nil) - } - } - - // Utilities --------------------------------------------------------------- - - /** Generate a literal "zero" for the requested type */ - def genZeroOf(tpe: Type)(implicit pos: Position): js.Tree = toTypeKind(tpe) match { - case VOID => abort("Cannot call genZeroOf(VOID)") - case BOOL => js.BooleanLiteral(false) - case LONG => js.LongLiteral(0L) - case INT(_) => js.IntLiteral(0) - case FloatKind => js.FloatLiteral(0.0f) - case DoubleKind => js.DoubleLiteral(0.0) - case _ => js.Null() - } - - /** Generate loading of a module value - * Can be given either the module symbol, or its module class symbol. - */ - def genLoadModule(sym0: Symbol)(implicit pos: Position): js.Tree = { - require(sym0.isModuleOrModuleClass, - "genLoadModule called with non-module symbol: " + sym0) - val sym1 = if (sym0.isModule) sym0.moduleClass else sym0 - val sym = // redirect all static methods of String to RuntimeString - if (sym1 == StringModule) RuntimeStringModule.moduleClass - else sym1 - - if (isJSNativeClass(sym) && - !sym.hasAnnotation(HasJSNativeLoadSpecAnnotation)) { - /* Compatibility for native JS modules compiled with Scala.js 0.6.12 - * and earlier. Since they did not store their loading spec in the IR, - * the js.LoadJSModule() IR node cannot be used to load them. We must - * "desugar" it early in the compiler. - * - * Moreover, before 0.6.13, these objects would not have the - * annotation @JSGlobalScope. Instead, they would inherit from the - * magical trait js.GlobalScope. - */ - if (sym.isSubClass(JSGlobalScopeClass)) { - genLoadGlobal() - } else { - compat068FullJSNameOf(sym).split('.').foldLeft(genLoadGlobal()) { - (memo, chunk) => - js.JSBracketSelect(memo, js.StringLiteral(chunk)) - } - } - } else { - val moduleClassName = encodeClassFullName(sym) - - val cls = jstpe.ClassType(moduleClassName) - if (isRawJSType(sym.tpe)) js.LoadJSModule(cls) - else js.LoadModule(cls) - } - } - - /** Gen JS code to load the global scope. */ - private def genLoadGlobal()(implicit pos: ir.Position): js.Tree = { - js.JSBracketSelect( - js.JSBracketSelect(js.JSLinkingInfo(), js.StringLiteral("envInfo")), - js.StringLiteral("global")) - } - - /** Generate access to a static member */ - private def genStaticMember(sym: Symbol)(implicit pos: Position) = { - /* Actually, there is no static member in Scala.js. If we come here, that - * is because we found the symbol in a Java-emitted .class in the - * classpath. But the corresponding implementation in Scala.js will - * actually be a val in the companion module. - * We cannot use the .class files produced by our reimplementations of - * these classes (in which the symbol would be a Scala accessor) because - * that crashes the rest of scalac (at least for some choice symbols). - * Hence we cheat here. - */ - import scalaPrimitives._ - import jsPrimitives._ - if (isPrimitive(sym)) { - getPrimitive(sym) match { - case UNITVAL => js.Undefined() - } - } else { - val instance = genLoadModule(sym.owner) - val method = encodeStaticMemberSym(sym) - js.Apply(instance, method, Nil)(toIRType(sym.tpe)) - } - } - } - - private lazy val isScala211WithXexperimental = { - scala.util.Properties.versionNumberString.startsWith("2.11.") && - settings.Xexperimental.value - } - - private lazy val hasNewCollections = { - val v = scala.util.Properties.versionNumberString - !v.startsWith("2.10.") && - !v.startsWith("2.11.") && - !v.startsWith("2.12.") - } - - /** Tests whether the given type represents a raw JavaScript type, - * i.e., whether it extends scala.scalajs.js.Any. - */ - def isRawJSType(tpe: Type): Boolean = - tpe.typeSymbol.annotations.find(_.tpe =:= RawJSTypeAnnot.tpe).isDefined - - /** Tests whether the given class is a Scala.js-defined JS class. */ - def isScalaJSDefinedJSClass(sym: Symbol): Boolean = - !sym.isTrait && sym.hasAnnotation(ScalaJSDefinedAnnotation) - - def isScalaJSDefinedAnonJSClass(sym: Symbol): Boolean = - sym.hasAnnotation(SJSDefinedAnonymousClassAnnotation) - - /** Tests whether the given class is a JS native class. */ - private def isJSNativeClass(sym: Symbol): Boolean = - isRawJSType(sym.tpe) && !isScalaJSDefinedJSClass(sym) - - /** Tests whether the given class is the impl class of a raw JS trait. */ - private def isRawJSImplClass(sym: Symbol): Boolean = { - isImplClass(sym) && isRawJSType( - sym.owner.info.decl(sym.name.dropRight(nme.IMPL_CLASS_SUFFIX.length)).tpe) - } - - /** Tests whether the given member is exposed, i.e., whether it was - * originally a public or protected member of a Scala.js-defined JS class. - */ - private def isExposed(sym: Symbol): Boolean = { - !sym.isBridge && { - if (sym.isLazy) { - sym.isAccessor && { - sym.accessed.hasAnnotation(ExposedJSMemberAnnot) || - sym.hasAnnotation(ExposedJSMemberAnnot) // for 2.12.0, see #3439 - } - } else { - sym.hasAnnotation(ExposedJSMemberAnnot) - } - } - } - - /** Test whether `sym` is the symbol of a raw JS function definition */ - private def isRawJSFunctionDef(sym: Symbol): Boolean = - sym.isAnonymousClass && AllJSFunctionClasses.exists(sym isSubClass _) - - private def isRawJSCtorDefaultParam(sym: Symbol) = { - isCtorDefaultParam(sym) && - isRawJSType(patchedLinkedClassOfClass(sym.owner).tpe) - } - - private def isJSNativeCtorDefaultParam(sym: Symbol) = { - isCtorDefaultParam(sym) && - isJSNativeClass(patchedLinkedClassOfClass(sym.owner)) - } - - private def isCtorDefaultParam(sym: Symbol) = { - sym.hasFlag(reflect.internal.Flags.DEFAULTPARAM) && - sym.owner.isModuleClass && - nme.defaultGetterToMethod(sym.name) == nme.CONSTRUCTOR - } - - private def hasDefaultCtorArgsAndRawJSModule(classSym: Symbol): Boolean = { - /* Get the companion module class. - * For inner classes the sym.owner.companionModule can be broken, - * therefore companionModule is fetched at uncurryPhase. - */ - val companionClass = enteringPhase(currentRun.uncurryPhase) { - classSym.companionModule - }.moduleClass - - def hasDefaultParameters = { - val syms = classSym.info.members.filter(_.isClassConstructor) - enteringPhase(currentRun.uncurryPhase) { - syms.exists(_.paramss.iterator.flatten.exists(_.hasDefault)) - } - } - - isJSNativeClass(companionClass) && hasDefaultParameters - } - - private def patchedLinkedClassOfClass(sym: Symbol): Symbol = { - /* Work around a bug of scalac with linkedClassOfClass where package - * objects are involved (the companion class would somehow exist twice - * in the scope, making an assertion fail in Symbol.suchThat). - * Basically this inlines linkedClassOfClass up to companionClass, - * then replaces the `suchThat` by a `filter` and `head`. - */ - val flatOwnerInfo = { - // inline Symbol.flatOwnerInfo because it is protected - if (sym.needsFlatClasses) - sym.info - sym.owner.rawInfo - } - val result = flatOwnerInfo.decl(sym.name).filter(_ isCoDefinedWith sym) - if (!result.isOverloaded) result - else result.alternatives.head - } - - /** Whether a field is suspected to be mutable in the IR's terms - * - * A field is mutable in the IR, if it is assigned to elsewhere than in the - * constructor of its class. - * - * Mixed-in fields are always mutable, since they will be assigned to in - * a trait initializer (rather than a constructor). - * Further, in 2.10.x fields used to implement lazy vals are not marked - * mutable (but assigned to in the accessor). - */ - private def suspectFieldMutable(sym: Symbol) = { - import scala.reflect.internal.Flags - sym.hasFlag(Flags.MIXEDIN) || sym.isMutable || sym.isLazy - } - - private def isStringType(tpe: Type): Boolean = - tpe.typeSymbol == StringClass - - private def isLongType(tpe: Type): Boolean = - tpe.typeSymbol == LongClass - - private lazy val BoxedBooleanClass = boxedClass(BooleanClass) - private lazy val BoxedByteClass = boxedClass(ByteClass) - private lazy val BoxedShortClass = boxedClass(ShortClass) - private lazy val BoxedIntClass = boxedClass(IntClass) - private lazy val BoxedLongClass = boxedClass(LongClass) - private lazy val BoxedFloatClass = boxedClass(FloatClass) - private lazy val BoxedDoubleClass = boxedClass(DoubleClass) - - private lazy val NumberClass = requiredClass[java.lang.Number] - - private lazy val HijackedNumberClasses = - Seq(BoxedByteClass, BoxedShortClass, BoxedIntClass, BoxedLongClass, - BoxedFloatClass, BoxedDoubleClass) - private lazy val HijackedBoxedClasses = - Seq(BoxedUnitClass, BoxedBooleanClass) ++ HijackedNumberClasses - - protected lazy val isHijackedBoxedClass: Set[Symbol] = - HijackedBoxedClasses.toSet - - private lazy val InlineAnnotationClass = requiredClass[scala.inline] - private lazy val NoinlineAnnotationClass = requiredClass[scala.noinline] - - private lazy val ignoreNoinlineAnnotation: Set[Symbol] = { - val ccClass = getClassIfDefined("scala.util.continuations.ControlContext") - - Set( - getMemberIfDefined(ListClass, nme.map), - getMemberIfDefined(ListClass, nme.flatMap), - getMemberIfDefined(ListClass, newTermName("collect")), - getMemberIfDefined(ccClass, nme.map), - getMemberIfDefined(ccClass, nme.flatMap) - ) - NoSymbol - } - - private def isMaybeJavaScriptException(tpe: Type) = - JavaScriptExceptionClass isSubClass tpe.typeSymbol - - def isStaticModule(sym: Symbol): Boolean = - sym.isModuleClass && !isImplClass(sym) && !sym.isLifted -} diff --git a/compiler/src/main/scala/org/scalajs/core/compiler/GenJSExports.scala b/compiler/src/main/scala/org/scalajs/core/compiler/GenJSExports.scala deleted file mode 100644 index 67886b229e..0000000000 --- a/compiler/src/main/scala/org/scalajs/core/compiler/GenJSExports.scala +++ /dev/null @@ -1,1139 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler - -import scala.collection.mutable - -import scala.tools.nsc._ -import scala.math.PartialOrdering -import scala.reflect.internal.Flags - -import org.scalajs.core.ir -import ir.{Trees => js, Types => jstpe} -import ir.Trees.OptimizerHints - -import org.scalajs.core.compiler.util.ScopedVar -import ScopedVar.withScopedVars - -/** Generation of exports for JavaScript - * - * @author Sébastien Doeraene - */ -trait GenJSExports[G <: Global with Singleton] extends SubComponent { - self: GenJSCode[G] => - - import global._ - import jsAddons._ - import definitions._ - import jsDefinitions._ - import jsInterop.{jsNameOf, JSName} - - trait JSExportsPhase { this: JSCodePhase => - - /** Generates exported methods and properties for a class. - * - * @param classSym symbol of the class we export for - */ - def genMemberExports(classSym: Symbol): List[js.Tree] = { - val allExports = classSym.info.members.filter(jsInterop.isExport(_)) - - val newlyDecldExports = if (classSym.superClass == NoSymbol) { - allExports - } else { - allExports.filterNot { sym => - classSym.superClass.info.member(sym.name) - .filter(_.tpe =:= sym.tpe).exists - } - } - - val newlyDecldExportNames = - newlyDecldExports.map(_.name.toTermName).toList.distinct - - newlyDecldExportNames map { genMemberExport(classSym, _) } - } - - def genJSClassDispatchers(classSym: Symbol, - dispatchMethodsNames: List[JSName]): List[js.Tree] = { - dispatchMethodsNames - .map(genJSClassDispatcher(classSym, _)) - } - - def genConstructorExports(classSym: Symbol): List[js.ConstructorExportDef] = { - val constructors = classSym.tpe.member(nme.CONSTRUCTOR).alternatives - - // Generate exports from constructors and their annotations - val ctorExports = for { - ctor <- constructors - exp <- jsInterop.registeredExportsOf(ctor) - } yield (exp, ctor) - - if (ctorExports.isEmpty) { - Nil - } else { - val exports = for { - (jsName, specs) <- ctorExports.groupBy(_._1.jsName) // group by exported name - } yield { - val (namedExports, normalExports) = specs.partition(_._1.isNamed) - - val normalCtors = normalExports.map(s => ExportedSymbol(s._2)) - val namedCtors = for { - (exp, ctor) <- namedExports - } yield { - implicit val pos = exp.pos - new ExportedBody(List(JSAnyTpe), - argsRegistry => genNamedExporterBody(ctor, argsRegistry.genArgRef(0)), - nme.CONSTRUCTOR.toString, pos) - } - - val ctors = normalCtors ++ namedCtors - - implicit val pos = ctors.head.pos - - val js.MethodDef(_, _, args, _, body) = - withNewLocalNameScope(genExportMethod(ctors, JSName.Literal(jsName), - static = false)) - - js.ConstructorExportDef(jsName, args, body.get) - } - - exports.toList - } - } - - def genJSClassExports(classSym: Symbol): List[js.JSClassExportDef] = { - for { - exp <- jsInterop.registeredExportsOf(classSym) - } yield { - implicit val pos = exp.pos - assert(!exp.isNamed, "Class cannot be exported named") - - exp.destination match { - case ExportDestination.Normal | ExportDestination.TopLevel => - js.JSClassExportDef(exp.jsName) - case ExportDestination.Static => - throw new AssertionError( - "Found a class export static for " + classSym.fullName) - } - } - } - - def genModuleAccessorExports(classSym: Symbol): List[js.Tree] = { - for { - exp <- jsInterop.registeredExportsOf(classSym) - } yield { - implicit val pos = exp.pos - assert(!exp.isNamed, "Module cannot be exported named") - - exp.destination match { - case ExportDestination.Normal => - js.ModuleExportDef(exp.jsName) - case ExportDestination.TopLevel => - js.TopLevelModuleExportDef(exp.jsName) - case ExportDestination.Static => - throw new AssertionError( - "Found a module export static for " + classSym.fullName) - } - } - } - - def genTopLevelExports(classSym: Symbol): List[js.Tree] = - genTopLevelOrStaticExports(classSym, ExportDestination.TopLevel) - - def genStaticExports(classSym: Symbol): List[js.Tree] = - genTopLevelOrStaticExports(classSym, ExportDestination.Static) - - private def genTopLevelOrStaticExports(classSym: Symbol, - destination: ExportDestination): List[js.Tree] = { - require( - destination == ExportDestination.TopLevel || - destination == ExportDestination.Static, - destination) - - val exportsNamesAndPositions = { - genTopLevelOrStaticFieldExports(classSym, destination) ++ - genTopLevelOrStaticMethodExports(classSym, destination) - } - - for { - exportsWithSameName <- exportsNamesAndPositions.groupBy(_._2).values - duplicate <- exportsWithSameName.tail - } { - val strKind = - if (destination == ExportDestination.TopLevel) "top-level" - else "static" - reporter.error(duplicate._3, - s"Duplicate $strKind export with name '${duplicate._2}': " + - "a field may not share its exported name with another field or " + - "method") - } - - exportsNamesAndPositions.map(_._1) - } - - private def genTopLevelOrStaticFieldExports(classSym: Symbol, - destination: ExportDestination): List[(js.Tree, String, Position)] = { - (for { - fieldSym <- classSym.info.members - if !fieldSym.isMethod && fieldSym.isTerm && !fieldSym.isModule - export <- jsInterop.registeredExportsOf(fieldSym) - if export.destination == destination - } yield { - implicit val pos = fieldSym.pos - - val tree = if (destination == ExportDestination.Static) { - val mutable = true // static fields must always be mutable - val name = js.StringLiteral(export.jsName) - val irTpe = genExposedFieldIRType(fieldSym) - js.FieldDef(static = true, name, irTpe, mutable) - } else { - js.TopLevelFieldExportDef(export.jsName, encodeFieldSym(fieldSym)) - } - - (tree, export.jsName, pos) - }).toList - } - - private def genTopLevelOrStaticMethodExports(classSym: Symbol, - destination: ExportDestination): List[(js.Tree, String, Position)] = { - val allRelevantExports = for { - methodSym <- classSym.info.members - if methodSym.isMethod && !methodSym.isConstructor - export <- jsInterop.registeredExportsOf(methodSym) - if export.destination == destination - } yield { - (export, methodSym) - } - - for { - (jsName, tups) <- allRelevantExports.groupBy(_._1.jsName).toList - } yield { - implicit val pos = tups.head._1.pos - - val alts = tups.map(_._2).toList - val firstAlt = alts.head - val isProp = jsInterop.isJSProperty(firstAlt) - - // Check for conflict between method vs property - - for { - conflicting <- alts.tail - if jsInterop.isJSProperty(conflicting) != isProp - } { - val kindStr = if (isProp) "method" else "property" - reporter.error(conflicting.pos, - s"Exported $kindStr $jsName conflicts with ${firstAlt.nameString}") - } - - // Generate the export - - val exportedMember = genMemberExportOrDispatcher(classSym, - JSName.Literal(jsName), isProp, alts, static = true) - - val exportDef = - if (destination == ExportDestination.Static) exportedMember - else js.TopLevelMethodExportDef(exportedMember.asInstanceOf[js.MethodDef]) - - (exportDef, jsName, pos) - } - } - - /** Tests whether the given def a named exporter def that needs to be - * generated with `genNamedExporterDef`. - */ - def isNamedExporterDef(dd: DefDef): Boolean = { - jsInterop.isExport(dd.symbol) && - dd.symbol.annotations.exists(_.symbol == JSExportNamedAnnotation) - } - - /** Generate the exporter proxy for a named export */ - def genNamedExporterDef(dd: DefDef): Option[js.MethodDef] = { - implicit val pos = dd.pos - - if (isAbstractMethod(dd)) { - None - } else { - withNewLocalNameScope { - val sym = dd.symbol - - val Block(Apply(fun, _) :: Nil, _) = dd.rhs - val trgSym = fun.symbol - - val inArg = js.ParamDef(freshLocalIdent("namedParams"), jstpe.AnyType, - mutable = false, rest = false) - - val methodIdent = encodeMethodSym(sym) - - Some(js.MethodDef(static = false, methodIdent, - List(inArg), toIRType(sym.tpe.resultType), - Some(genNamedExporterBody(trgSym, inArg.ref)))( - OptimizerHints.empty, None)) - } - } - } - - private def genNamedExporterBody(trgSym: Symbol, inArg: js.Tree)( - implicit pos: Position) = { - - if (hasRepeatedParam(trgSym)) { - reporter.error(pos, - "You may not name-export a method with a *-parameter") - } - - val jsArgs = for { - (pSym, index) <- trgSym.info.params.zipWithIndex - } yield { - val rhs = js.JSBracketSelect(inArg, - js.StringLiteral(pSym.name.decoded)) - js.VarDef(freshLocalIdent("namedArg"), jstpe.AnyType, - mutable = false, rhs = rhs) - } - - val jsArgRefs = jsArgs.map(_.ref) - - // Generate JS code to prepare arguments (default getters and unboxes) - val jsArgPrep = genPrepareArgs(jsArgRefs, trgSym) - val jsResult = genResult(trgSym, jsArgPrep.map(_.ref), static = false) - - js.Block(jsArgs ++ jsArgPrep :+ jsResult) - } - - private def genMemberExport(classSym: Symbol, name: TermName): js.Tree = { - /* This used to be `.member(name)`, but it caused #3538, since we were - * sometimes selecting mixin forwarders, whose type history does not go - * far enough back in time to see varargs. We now explicitly exclude - * mixed-in members in addition to bridge methods (the latter are always - * excluded by `.member(name)`). - */ - val alts = classSym.info.memberBasedOnName(name, - excludedFlags = Flags.BRIDGE | Flags.MIXEDIN).alternatives - - assert(!alts.isEmpty, - s"Ended up with no alternatives for ${classSym.fullName}::$name. " + - s"Original set was ${alts} with types ${alts.map(_.tpe)}") - - val (jsName, isProp) = jsInterop.jsExportInfo(name) - - // Check if we have a conflicting export of the other kind - val conflicting = - classSym.info.member(jsInterop.scalaExportName(jsName, !isProp)) - - if (conflicting != NoSymbol) { - val kind = if (isProp) "property" else "method" - val alts = conflicting.alternatives - - reporter.error(alts.head.pos, - s"Exported $kind $jsName conflicts with ${alts.head.fullName}") - } - - genMemberExportOrDispatcher(classSym, JSName.Literal(jsName), isProp, - alts, static = false) - } - - private def genJSClassDispatcher(classSym: Symbol, name: JSName): js.Tree = { - val alts = classSym.info.members.toList.filter { sym => - sym.isMethod && - !sym.isBridge && - /* #3939: Object is not a "real" superclass of JS types. - * as such, its methods do not participate in overload resolution. - * An exception is toString, which is handled specially in - * genExportMethod. - */ - sym.owner != ObjectClass && - jsNameOf(sym) == name - } - - assert(!alts.isEmpty, - s"Ended up with no alternatives for ${classSym.fullName}::$name.") - - val (propSyms, methodSyms) = alts.partition(jsInterop.isJSProperty(_)) - val isProp = propSyms.nonEmpty - - if (isProp && methodSyms.nonEmpty) { - reporter.error(alts.head.pos, - s"Conflicting properties and methods for ${classSym.fullName}::$name.") - js.Skip()(ir.Position.NoPosition) - } else { - genMemberExportOrDispatcher(classSym, name, isProp, alts, - static = false) - } - } - - def genMemberExportOrDispatcher(classSym: Symbol, jsName: JSName, - isProp: Boolean, alts: List[Symbol], static: Boolean): js.Tree = { - withNewLocalNameScope { - if (isProp) - genExportProperty(alts, jsName, static) - else - genExportMethod(alts.map(ExportedSymbol), jsName, static) - } - } - - def genJSConstructorExport(alts: List[Symbol]): js.MethodDef = { - genExportMethod(alts.map(ExportedSymbol), JSName.Literal("constructor"), - static = false) - } - - private def genExportProperty(alts: List[Symbol], jsName: JSName, - static: Boolean): js.PropertyDef = { - assert(!alts.isEmpty, - s"genExportProperty with empty alternatives for $jsName") - - implicit val pos = alts.head.pos - - // Separate getters and setters. Somehow isJSGetter doesn't work here. Hence - // we just check the parameter list length. - val (getter, setters) = alts.partition(_.tpe.params.isEmpty) - - // We can have at most one getter - if (getter.size > 1) { - /* Member export of properties should be caught earlier, so if we get - * here with a non-static export, something went horribly wrong. - */ - assert(static, - s"Found more than one instance getter to export for name $jsName.") - for (duplicate <- getter.tail) { - reporter.error(duplicate.pos, - s"Duplicate static getter export with name '${jsName.displayName}'") - } - } - - val getterBody = getter.headOption.map( - genApplyForSym(new FormalArgsRegistry(0, false), _, static)) - - val setterArgAndBody = { - if (setters.isEmpty) { - None - } else { - val formalArgsRegistry = new FormalArgsRegistry(1, false) - val List(arg) = formalArgsRegistry.genFormalArgs() - val body = genExportSameArgc(jsName, formalArgsRegistry, - alts = setters.map(ExportedSymbol), - paramIndex = 0, static = static) - Some((arg, body)) - } - } - - js.PropertyDef(static, genPropertyName(jsName), getterBody, - setterArgAndBody) - } - - /** generates the exporter function (i.e. exporter for non-properties) for - * a given name */ - private def genExportMethod(alts0: List[Exported], jsName: JSName, - static: Boolean): js.MethodDef = { - assert(alts0.nonEmpty, - "need at least one alternative to generate exporter method") - - implicit val pos = alts0.head.pos - - val alts = { - // toString() is always exported. We might need to add it here - // to get correct overloading. - val needsToString = - jsName == JSName.Literal("toString") && alts0.forall(_.params.nonEmpty) - - if (needsToString) - ExportedSymbol(Object_toString) :: alts0 - else - alts0 - } - - // Factor out methods with variable argument lists. Note that they can - // only be at the end of the lists as enforced by PrepJSExports - val (varArgMeths, normalMeths) = alts.partition(_.hasRepeatedParam) - - // Highest non-repeated argument count - val maxArgc = ( - // We have argc - 1, since a repeated parameter list may also be empty - // (unlike a normal parameter) - varArgMeths.map(_.params.size - 1) ++ - normalMeths.map(_.params.size) - ).max - - // Calculates possible arg counts for normal method - def argCounts(ex: Exported) = ex match { - case ExportedSymbol(sym) => - val params = sym.tpe.params - // Find default param - val dParam = params.indexWhere { _.hasFlag(Flags.DEFAULTPARAM) } - if (dParam == -1) Seq(params.size) - else dParam to params.size - case ex: ExportedBody => - List(ex.params.size) - } - - // Generate tuples (argc, method) - val methodArgCounts = { - // Normal methods - for { - method <- normalMeths - argc <- argCounts(method) - } yield (argc, method) - } ++ { - // Repeated parameter methods - for { - method <- varArgMeths - argc <- method.params.size - 1 to maxArgc - } yield (argc, method) - } - - // Create a map: argCount -> methods (methods may appear multiple times) - val methodByArgCount = - methodArgCounts.groupBy(_._1).map(kv => kv._1 -> kv._2.map(_._2).toSet) - - // Create the formal args registry - val minArgc = methodByArgCount.keys.min - val hasVarArg = varArgMeths.nonEmpty - val needsRestParam = maxArgc != minArgc || hasVarArg - val formalArgsRegistry = new FormalArgsRegistry(minArgc, needsRestParam) - - // List of formal parameters - val formalArgs = formalArgsRegistry.genFormalArgs() - - // Create tuples: (methods, argCounts). This will be the cases we generate - val caseDefinitions = - methodByArgCount.groupBy(_._2).map(kv => kv._1 -> kv._2.keySet) - - // Verify stuff about caseDefinitions - assert({ - val argcs = caseDefinitions.values.flatten.toList - argcs == argcs.distinct && - argcs.forall(_ <= maxArgc) - }, "every argc should appear only once and be lower than max") - - // Generate a case block for each (methods, argCounts) tuple - val cases = for { - (methods, argcs) <- caseDefinitions - if methods.nonEmpty && argcs.nonEmpty - - // exclude default case we're generating anyways for varargs - if methods != varArgMeths.toSet - - // body of case to disambiguates methods with current count - caseBody = genExportSameArgc(jsName, formalArgsRegistry, - methods.toList, paramIndex = 0, static, Some(argcs.min)) - - // argc in reverse order - argcList = argcs.toList.sortBy(- _) - } yield (argcList.map(argc => js.IntLiteral(argc - minArgc)), caseBody) - - def defaultCase = { - if (!hasVarArg) { - genThrowTypeError() - } else { - genExportSameArgc(jsName, formalArgsRegistry, varArgMeths, - paramIndex = 0, static = static) - } - } - - val body = { - if (cases.isEmpty) - defaultCase - else if (cases.size == 1 && !hasVarArg) - cases.head._2 - else { - assert(needsRestParam, - "Trying to read rest param length but needsRestParam is false") - js.Match( - js.Unbox(js.JSBracketSelect( - formalArgsRegistry.genRestArgRef(), - js.StringLiteral("length")), - 'I'), - cases.toList, defaultCase)(jstpe.AnyType) - } - } - - js.MethodDef(static, genPropertyName(jsName), - formalArgs, jstpe.AnyType, Some(body))(OptimizerHints.empty, None) - } - - /** - * Resolve method calls to [[alts]] while assuming they have the same - * parameter count. - * @param minArgc The minimum number of arguments that must be given - * @param alts Alternative methods - * @param paramIndex Index where to start disambiguation - * @param maxArgc only use that many arguments - */ - private def genExportSameArgc(jsName: JSName, - formalArgsRegistry: FormalArgsRegistry, alts: List[Exported], - paramIndex: Int, static: Boolean, - maxArgc: Option[Int] = None): js.Tree = { - - implicit val pos = alts.head.pos - - if (alts.size == 1) { - alts.head.genBody(formalArgsRegistry, static) - } else if (maxArgc.exists(_ <= paramIndex) || - !alts.exists(_.params.size > paramIndex)) { - // We reach here in three cases: - // 1. The parameter list has been exhausted - // 2. The optional argument count restriction has triggered - // 3. We only have (more than once) repeated parameters left - // Therefore, we should fail - reportCannotDisambiguateError(jsName, alts) - js.Undefined() - } else { - val altsByTypeTest = groupByWithoutHashCode(alts) { - case ExportedSymbol(alt) => - typeTestForTpe(computeExportArgType(alt, paramIndex)) - - case ex: ExportedBody => - typeTestForTpe(ex.params(paramIndex)) - } - - if (altsByTypeTest.size == 1) { - // Testing this parameter is not doing any us good - genExportSameArgc(jsName, formalArgsRegistry, alts, paramIndex + 1, - static, maxArgc) - } else { - // Sort them so that, e.g., isInstanceOf[String] - // comes before isInstanceOf[Object] - val sortedAltsByTypeTest = topoSortDistinctsBy( - altsByTypeTest)(_._1)(RTTypeTest.Ordering) - - val defaultCase = genThrowTypeError() - - sortedAltsByTypeTest.foldRight[js.Tree](defaultCase) { (elem, elsep) => - val (typeTest, subAlts) = elem - implicit val pos = subAlts.head.pos - - val paramRef = formalArgsRegistry.genArgRef(paramIndex) - val genSubAlts = genExportSameArgc(jsName, formalArgsRegistry, - subAlts, paramIndex + 1, static, maxArgc) - - def hasDefaultParam = subAlts.exists { - case ExportedSymbol(p) => - val params = p.tpe.params - params.size > paramIndex && - params(paramIndex).hasFlag(Flags.DEFAULTPARAM) - case _: ExportedBody => false - } - - val optCond = typeTest match { - case HijackedTypeTest(boxedClassName, _) => - Some(js.IsInstanceOf(paramRef, jstpe.ClassType(boxedClassName))) - - case InstanceOfTypeTest(tpe) => - Some(genIsInstanceOf(paramRef, tpe)) - - case NoTypeTest => - None - } - - optCond.fold[js.Tree] { - genSubAlts // note: elsep is discarded, obviously - } { cond => - val condOrUndef = if (!hasDefaultParam) cond else { - js.If(cond, js.BooleanLiteral(true), - js.BinaryOp(js.BinaryOp.===, paramRef, js.Undefined()))( - jstpe.BooleanType) - } - js.If(condOrUndef, genSubAlts, elsep)(jstpe.AnyType) - } - } - } - } - } - - private def reportCannotDisambiguateError(jsName: JSName, - alts: List[Exported]): Unit = { - val currentClass = currentClassSym.get - - /* Find a position that is in the current class for decent error reporting. - * If there are more than one, always use the "highest" one (i.e., the - * one coming last in the source text) so that we reliably display the - * same error in all compilers. - */ - val validPositions = alts.collect { - case ExportedSymbol(sym) if sym.owner == currentClass => sym.pos - case alt: ExportedBody => alt.pos - } - val pos = - if (validPositions.isEmpty) currentClass.pos - else validPositions.maxBy(_.point) - - val kind = - if (isScalaJSDefinedJSClass(currentClass)) "method" - else "exported method" - - val displayName = jsName.displayName - val altsTypesInfo = alts.map(_.typeInfo).sorted.mkString("\n ") - - reporter.error(pos, - s"Cannot disambiguate overloads for $kind $displayName with types\n" + - s" $altsTypesInfo") - } - - private def computeExportArgType(alt: Symbol, paramIndex: Int): Type = { - // See the comment in genPrimitiveJSArgs for a rationale about this - enteringPhase(currentRun.uncurryPhase) { - - lazy val paramsUncurry = alt.paramss.flatten - lazy val paramsTypesUncurry = paramsUncurry.map(_.tpe) - lazy val isRepeatedUncurry = paramsUncurry.map(isRepeated) - - lazy val paramsPosterasure = enteringPhase(currentRun.posterasurePhase) { - alt.paramss.flatten - } - def paramTypePosterasure = enteringPhase(currentRun.posterasurePhase) { - paramsPosterasure.apply(paramIndex).tpe - } - - if (!alt.isClassConstructor) { - // get parameter type while resolving repeated params - if (paramsTypesUncurry.size <= paramIndex || isRepeatedUncurry(paramIndex)) { - assert(isRepeatedUncurry.last, - s"$alt does not have varargs nor enough params for $paramIndex") - repeatedToSingle(paramsTypesUncurry.last) - } else { - paramTypePosterasure - } - } else { - // Compute the number of captured parameters that are added to the front - val paramsNamesUncurry = paramsUncurry.map(_.name) - val numCapturesFront = enteringPhase(currentRun.posterasurePhase) { - if (paramsNamesUncurry.isEmpty) paramsPosterasure.size - else paramsPosterasure.map(_.name).indexOfSlice(paramsNamesUncurry) - } - // get parameter type while resolving repeated params - if (paramIndex < numCapturesFront) { - // Type of a parameter that represents a captured outer context - paramTypePosterasure - } else { - val paramIndexNoCaptures = paramIndex - numCapturesFront - if (paramsTypesUncurry.size <= paramIndexNoCaptures || - isRepeatedUncurry(paramIndexNoCaptures)) { - assert(isRepeatedUncurry.last, - s"$alt does not have varargs nor enough params for $paramIndexNoCaptures") - repeatedToSingle(paramsTypesUncurry.last) - } else { - paramsTypesUncurry(paramIndexNoCaptures) - } - } - } - } - } - - /** - * Generate a call to the method [[sym]] while using the formalArguments - * and potentially the argument array. Also inserts default parameters if - * required. - */ - private def genApplyForSym(formalArgsRegistry: FormalArgsRegistry, - sym: Symbol, static: Boolean): js.Tree = { - if (isScalaJSDefinedJSClass(currentClassSym) && - sym.owner != currentClassSym.get) { - assert(!static, s"nonsensical JS super call in static export of $sym") - genApplyForSymJSSuperCall(formalArgsRegistry, sym) - } else { - genApplyForSymNonJSSuperCall(formalArgsRegistry, sym, static) - } - } - - private def genApplyForSymJSSuperCall( - formalArgsRegistry: FormalArgsRegistry, sym: Symbol): js.Tree = { - implicit val pos = sym.pos - - val allArgs = formalArgsRegistry.genAllArgsRefsForForwarder() - - val cls = jstpe.ClassType(encodeClassFullName(currentClassSym)) - val receiver = js.This()(jstpe.AnyType) - val nameString = genExpr(jsNameOf(sym)) - - if (jsInterop.isJSGetter(sym)) { - assert(allArgs.isEmpty, - s"getter symbol $sym does not have a getter signature") - js.JSSuperBracketSelect(cls, receiver, nameString) - } else if (jsInterop.isJSSetter(sym)) { - assert(allArgs.size == 1 && !allArgs.head.isInstanceOf[js.JSSpread], - s"setter symbol $sym does not have a setter signature") - js.Assign(js.JSSuperBracketSelect(cls, receiver, nameString), - allArgs.head) - } else { - js.JSSuperBracketCall(cls, receiver, nameString, allArgs) - } - } - - private def genApplyForSymNonJSSuperCall( - formalArgsRegistry: FormalArgsRegistry, sym: Symbol, - static: Boolean): js.Tree = { - implicit val pos = sym.pos - - // the (single) type of the repeated parameter if any - val repeatedTpe = enteringPhase(currentRun.uncurryPhase) { - for { - param <- sym.paramss.flatten.lastOption - if isRepeated(param) - } yield repeatedToSingle(param.tpe) - } - - val normalArgc = sym.tpe.params.size - - (if (repeatedTpe.isDefined) 1 else 0) - - // optional repeated parameter list - val jsVarArgPrep = repeatedTpe map { tpe => - val rhs = genJSArrayToVarArgs(formalArgsRegistry.genVarargRef(normalArgc)) - js.VarDef(freshLocalIdent("prep"), rhs.tpe, mutable = false, rhs) - } - - // normal arguments - val jsArgRefs = - (0 until normalArgc).toList.map(formalArgsRegistry.genArgRef(_)) - - // Generate JS code to prepare arguments (default getters and unboxes) - val jsArgPrep = genPrepareArgs(jsArgRefs, sym) ++ jsVarArgPrep - val jsResult = genResult(sym, jsArgPrep.map(_.ref), static) - - js.Block(jsArgPrep :+ jsResult) - } - - /** Generate the necessary JavaScript code to prepare the arguments of an - * exported method (unboxing and default parameter handling) - */ - private def genPrepareArgs(jsArgs: List[js.Tree], sym: Symbol)( - implicit pos: Position): List[js.VarDef] = { - - val result = new mutable.ListBuffer[js.VarDef] - - val paramsPosterasure = - enteringPhase(currentRun.posterasurePhase)(sym.tpe).params - val paramsNow = sym.tpe.params - - /* The parameters that existed at posterasurePhase are taken from that - * phase. The parameters that where added after posterasurePhase are taken - * from the current parameter list. - */ - val params = paramsPosterasure ++ paramsNow.drop(paramsPosterasure.size) - - for { - (jsArg, (param, i)) <- jsArgs zip params.zipWithIndex - } yield { - // Unboxed argument (if it is defined) - val unboxedArg = fromAny(jsArg, - enteringPhase(currentRun.posterasurePhase)(param.tpe)) - - // If argument is undefined and there is a default getter, call it - val verifiedOrDefault = if (param.hasFlag(Flags.DEFAULTPARAM)) { - js.If(js.BinaryOp(js.BinaryOp.===, jsArg, js.Undefined()), { - val trgSym = { - if (sym.isClassConstructor) { - /* Get the companion module class. - * For inner classes the sym.owner.companionModule can be broken, - * therefore companionModule is fetched at uncurryPhase. - */ - val companionModule = enteringPhase(currentRun.namerPhase) { - sym.owner.companionModule - } - companionModule.moduleClass - } else { - sym.owner - } - } - val defaultGetter = trgSym.tpe.member( - nme.defaultGetterName(sym.name, i+1)) - - assert(defaultGetter.exists, - s"need default getter for method ${sym.fullName}") - assert(!defaultGetter.isOverloaded, - s"found overloaded default getter $defaultGetter") - - val trgTree = { - if (sym.isClassConstructor) genLoadModule(trgSym) - else js.This()(encodeClassType(trgSym)) - } - - // Pass previous arguments to defaultGetter - val defaultGetterArgs = - result.take(defaultGetter.tpe.params.size).toList.map(_.ref) - - if (isRawJSType(trgSym.toTypeConstructor)) { - if (isScalaJSDefinedJSClass(defaultGetter.owner)) { - genApplyJSClassMethod(trgTree, defaultGetter, defaultGetterArgs) - } else { - reporter.error(param.pos, "When overriding a native method " + - "with default arguments, the overriding method must " + - "explicitly repeat the default arguments.") - js.Undefined() - } - } else { - genApplyMethod(trgTree, defaultGetter, defaultGetterArgs) - } - }, { - // Otherwise, unbox the argument - unboxedArg - })(unboxedArg.tpe) - } else { - // Otherwise, it is always the unboxed argument - unboxedArg - } - - result += - js.VarDef(freshLocalIdent("prep"), verifiedOrDefault.tpe, - mutable = false, verifiedOrDefault) - } - - result.toList - } - - /** Generate the final forwarding call to the exported method. - * Attention: This method casts the arguments to the right type. The IR - * checker will not detect if you pass in a wrongly typed argument. - */ - private def genResult(sym: Symbol, args: List[js.Tree], - static: Boolean)(implicit pos: Position) = { - val thisType = - if (sym.owner == ObjectClass) jstpe.ClassType(ir.Definitions.ObjectClass) - else encodeClassType(sym.owner) - val receiver = - if (static) genLoadModule(sym.owner) - else js.This()(thisType) - val call = { - if (isScalaJSDefinedJSClass(currentClassSym)) { - assert(sym.owner == currentClassSym.get, sym.fullName) - genApplyJSClassMethod(receiver, sym, args) - } else { - if (sym.isClassConstructor) - genApplyMethodStatically(receiver, sym, args) - else - genApplyMethod(receiver, sym, args) - } - } - ensureBoxed(call, - enteringPhase(currentRun.posterasurePhase)(sym.tpe.resultType)) - } - - private sealed abstract class Exported { - def pos: Position - def params: List[Type] - def genBody(formalArgsRegistry: FormalArgsRegistry, static: Boolean): js.Tree - def typeInfo: String - def hasRepeatedParam: Boolean - } - - private case class ExportedSymbol(sym: Symbol) extends Exported { - def pos: Position = sym.pos - def params: List[Type] = sym.tpe.params.map(_.tpe) - - def genBody(formalArgsRegistry: FormalArgsRegistry, static: Boolean): js.Tree = - genApplyForSym(formalArgsRegistry, sym, static) - - def typeInfo: String = sym.tpe.toString - def hasRepeatedParam: Boolean = GenJSExports.this.hasRepeatedParam(sym) - } - - private class ExportedBody(val params: List[Type], - genBodyFun: FormalArgsRegistry => js.Tree, name: String, - val pos: Position) - extends Exported { - - def genBody(formalArgsRegistry: FormalArgsRegistry, static: Boolean): js.Tree = - genBodyFun(formalArgsRegistry) - - def typeInfo: String = params.mkString("(", ", ", ")") - val hasRepeatedParam: Boolean = false - } - } - - private sealed abstract class RTTypeTest - - private case class HijackedTypeTest( - boxedClassName: String, rank: Int) extends RTTypeTest - - // scalastyle:off equals.hash.code - private case class InstanceOfTypeTest(tpe: Type) extends RTTypeTest { - override def equals(that: Any): Boolean = { - that match { - case InstanceOfTypeTest(thatTpe) => tpe =:= thatTpe - case _ => false - } - } - } - // scalastyle:on equals.hash.code - - private case object NoTypeTest extends RTTypeTest - - private object RTTypeTest { - implicit object Ordering extends PartialOrdering[RTTypeTest] { - override def tryCompare(lhs: RTTypeTest, rhs: RTTypeTest): Option[Int] = { - if (lteq(lhs, rhs)) if (lteq(rhs, lhs)) Some(0) else Some(-1) - else if (lteq(rhs, lhs)) Some(1) else None - } - - override def lteq(lhs: RTTypeTest, rhs: RTTypeTest): Boolean = { - (lhs, rhs) match { - // NoTypeTest is always last - case (_, NoTypeTest) => true - case (NoTypeTest, _) => false - - case (HijackedTypeTest(_, rank1), HijackedTypeTest(_, rank2)) => - rank1 <= rank2 - - case (InstanceOfTypeTest(t1), InstanceOfTypeTest(t2)) => - t1 <:< t2 - - case (_: HijackedTypeTest, _: InstanceOfTypeTest) => true - case (_: InstanceOfTypeTest, _: HijackedTypeTest) => false - } - } - - override def equiv(lhs: RTTypeTest, rhs: RTTypeTest): Boolean = { - lhs == rhs - } - } - } - - // Very simple O(n²) topological sort for elements assumed to be distinct - private def topoSortDistinctsBy[A <: AnyRef, B](coll: List[A])(f: A => B)( - implicit ord: PartialOrdering[B]): List[A] = { - - @scala.annotation.tailrec - def loop(coll: List[A], acc: List[A]): List[A] = { - if (coll.isEmpty) acc - else if (coll.tail.isEmpty) coll.head :: acc - else { - val (lhs, rhs) = coll.span(x => !coll.forall( - y => (x eq y) || !ord.lteq(f(x), f(y)))) - assert(!rhs.isEmpty, s"cycle while ordering $coll") - loop(lhs ::: rhs.tail, rhs.head :: acc) - } - } - - loop(coll, Nil) - } - - private def typeTestForTpe(tpe: Type): RTTypeTest = { - tpe match { - case tpe: ErasedValueType => - InstanceOfTypeTest(tpe.valueClazz.typeConstructor) - - case _ => - import ir.{Definitions => Defs} - (toTypeKind(tpe): @unchecked) match { - case VoidKind => HijackedTypeTest(Defs.BoxedUnitClass, 0) - case BooleanKind => HijackedTypeTest(Defs.BoxedBooleanClass, 1) - case ByteKind => HijackedTypeTest(Defs.BoxedByteClass, 2) - case ShortKind => HijackedTypeTest(Defs.BoxedShortClass, 3) - case IntKind => HijackedTypeTest(Defs.BoxedIntegerClass, 4) - case FloatKind => HijackedTypeTest(Defs.BoxedFloatClass, 5) - case DoubleKind => HijackedTypeTest(Defs.BoxedDoubleClass, 6) - - case CharKind => InstanceOfTypeTest(boxedClass(CharClass).tpe) - case LongKind => InstanceOfTypeTest(boxedClass(LongClass).tpe) - - case REFERENCE(cls) => - cls match { - case BoxedUnitClass => HijackedTypeTest(Defs.BoxedUnitClass, 0) - case StringClass => HijackedTypeTest(Defs.StringClass, 7) - case ObjectClass => NoTypeTest - case _ => - if (isRawJSType(tpe)) NoTypeTest - else InstanceOfTypeTest(tpe) - } - - case ARRAY(_) => InstanceOfTypeTest(tpe) - } - } - } - - // Group-by that does not rely on hashCode(), only equals() - O(n²) - private def groupByWithoutHashCode[A, B]( - coll: List[A])(f: A => B): List[(B, List[A])] = { - - import scala.collection.mutable.ArrayBuffer - val m = new ArrayBuffer[(B, List[A])] - m.sizeHint(coll.length) - - for (elem <- coll) { - val key = f(elem) - val index = m.indexWhere(_._1 == key) - if (index < 0) m += ((key, List(elem))) - else m(index) = (key, elem :: m(index)._2) - } - - m.toList - } - - private def genThrowTypeError(msg: String = "No matching overload")( - implicit pos: Position): js.Tree = { - js.Throw(js.StringLiteral(msg)) - } - - private class FormalArgsRegistry(minArgc: Int, needsRestParam: Boolean) { - private val fixedParamNames: scala.collection.immutable.IndexedSeq[String] = - (0 until minArgc).toIndexedSeq.map(_ => freshLocalIdent("arg")(NoPosition).name) - - private val restParamName: String = - if (needsRestParam) freshLocalIdent("rest")(NoPosition).name - else "" - - def genFormalArgs()(implicit pos: Position): List[js.ParamDef] = { - val fixedParamDefs = fixedParamNames.toList.map { paramName => - js.ParamDef(js.Ident(paramName), jstpe.AnyType, - mutable = false, rest = false) - } - - if (needsRestParam) { - val restParamDef = js.ParamDef(js.Ident(restParamName), jstpe.AnyType, - mutable = false, rest = true) - fixedParamDefs :+ restParamDef - } else { - fixedParamDefs - } - } - - def genArgRef(index: Int)(implicit pos: Position): js.Tree = { - if (index < minArgc) - js.VarRef(js.Ident(fixedParamNames(index)))(jstpe.AnyType) - else - js.JSBracketSelect(genRestArgRef(), js.IntLiteral(index - minArgc)) - } - - def genVarargRef(fixedParamCount: Int)(implicit pos: Position): js.Tree = { - val restParam = genRestArgRef() - assert(fixedParamCount >= minArgc, - s"genVarargRef($fixedParamCount) with minArgc = $minArgc at $pos") - if (fixedParamCount == minArgc) { - restParam - } else { - js.JSBracketMethodApply(restParam, js.StringLiteral("slice"), List( - js.IntLiteral(fixedParamCount - minArgc))) - } - } - - def genRestArgRef()(implicit pos: Position): js.Tree = { - assert(needsRestParam, - s"trying to generate a reference to non-existent rest param at $pos") - js.VarRef(js.Ident(restParamName))(jstpe.AnyType) - } - - def genAllArgsRefsForForwarder()(implicit pos: Position): List[js.Tree] = { - val fixedArgRefs = fixedParamNames.toList.map { paramName => - js.VarRef(js.Ident(paramName))(jstpe.AnyType) - } - - if (needsRestParam) { - val restArgRef = js.VarRef(js.Ident(restParamName))(jstpe.AnyType) - fixedArgRefs :+ restArgRef - } else { - fixedArgRefs - } - } - } - - private def hasRepeatedParam(sym: Symbol) = - enteringPhase(currentRun.uncurryPhase) { - sym.paramss.flatten.lastOption.exists(isRepeated _) - } - -} diff --git a/compiler/src/main/scala/org/scalajs/core/compiler/GenJSFiles.scala b/compiler/src/main/scala/org/scalajs/core/compiler/GenJSFiles.scala deleted file mode 100644 index 39a7516d7c..0000000000 --- a/compiler/src/main/scala/org/scalajs/core/compiler/GenJSFiles.scala +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler - -import scala.tools.nsc._ -import scala.tools.nsc.io.AbstractFile -import scala.reflect.internal.pickling.PickleBuffer - -import java.io._ - -import org.scalajs.core.ir -import ir.Infos - -/** Send JS ASTs to files - * - * @author Sébastien Doeraene - */ -trait GenJSFiles[G <: Global with Singleton] extends SubComponent { - self: GenJSCode[G] => - - import global._ - import jsAddons._ - - def genIRFile(cunit: CompilationUnit, sym: Symbol, suffix: Option[String], - tree: ir.Trees.ClassDef): Unit = { - val outfile = getFileFor(cunit, sym, suffix.getOrElse("") + ".sjsir") - val output = outfile.bufferedOutput - try { - ir.InfoSerializers.serialize(output, Infos.generateClassInfo(tree)) - ir.Serializers.serialize(output, tree) - } catch { - case e: ir.InvalidIRException => - e.tree match { - case ir.Trees.UndefinedParam() => - reporter.error(sym.pos, "Found a dangling UndefinedParam at " + - s"${e.tree.pos}. This is likely due to a bad interaction " + - "between a macro or a compiler plugin and the Scala.js " + - "compiler plugin. If you hit this, please let us know.") - - case _ => - reporter.error(sym.pos, "The Scala.js compiler generated " + - "invalid IR for this class. Please report this as a bug. IR: " + - e.tree) - } - } finally { - output.close() - } - } - - private def getFileFor(cunit: CompilationUnit, sym: Symbol, - suffix: String) = { - val baseDir: AbstractFile = - settings.outputDirs.outputDirFor(cunit.source.file) - - val pathParts = sym.fullName.split("[./]") - val dir = pathParts.init.foldLeft(baseDir)(_.subdirectoryNamed(_)) - - var filename = pathParts.last - if (sym.isModuleClass && !isImplClass(sym)) - filename = filename + nme.MODULE_SUFFIX_STRING - - dir fileNamed (filename + suffix) - } -} diff --git a/compiler/src/main/scala/org/scalajs/core/compiler/JSDefinitions.scala b/compiler/src/main/scala/org/scalajs/core/compiler/JSDefinitions.scala deleted file mode 100644 index e3e6071222..0000000000 --- a/compiler/src/main/scala/org/scalajs/core/compiler/JSDefinitions.scala +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler - -import scala.tools.nsc._ - -/** Core definitions for Scala.js - * - * @author Sébastien Doeraene - */ -trait JSDefinitions { - val global: Global - - import global._ - - // scalastyle:off line.size.limit - - object jsDefinitions extends JSDefinitionsClass - - import definitions._ - import rootMirror._ - - class JSDefinitionsClass { - - lazy val ScalaJSJSPackageModule = getPackageObject("scala.scalajs.js") - lazy val JSPackage_typeOf = getMemberMethod(ScalaJSJSPackageModule, newTermName("typeOf")) - lazy val JSPackage_constructorOf = getMemberMethod(ScalaJSJSPackageModule, newTermName("constructorOf")) - lazy val JSPackage_native = getMemberMethod(ScalaJSJSPackageModule, newTermName("native")) - lazy val JSPackage_undefined = getMemberMethod(ScalaJSJSPackageModule, newTermName("undefined")) - - lazy val JSNativeAnnotation = getRequiredClass("scala.scalajs.js.native") - - lazy val JSAnyClass = getRequiredClass("scala.scalajs.js.Any") - lazy val JSDynamicClass = getRequiredClass("scala.scalajs.js.Dynamic") - lazy val JSDictionaryClass = getRequiredClass("scala.scalajs.js.Dictionary") - lazy val JSDictionary_delete = getMemberMethod(JSDictionaryClass, newTermName("delete")) - lazy val JSObjectClass = getRequiredClass("scala.scalajs.js.Object") - lazy val JSThisFunctionClass = getRequiredClass("scala.scalajs.js.ThisFunction") - - lazy val JSGlobalScopeClass = getRequiredClass("scala.scalajs.js.GlobalScope") - - lazy val UndefOrClass = getRequiredClass("scala.scalajs.js.UndefOr") - lazy val UnionClass = getRequiredClass("scala.scalajs.js.$bar") - - lazy val JSArrayClass = getRequiredClass("scala.scalajs.js.Array") - lazy val JSArray_apply = getMemberMethod(JSArrayClass, newTermName("apply")) - lazy val JSArray_update = getMemberMethod(JSArrayClass, newTermName("update")) - - lazy val JSFunctionClasses = (0 to 22) map (n => getRequiredClass("scala.scalajs.js.Function"+n)) - lazy val JSThisFunctionClasses = (0 to 21) map (n => getRequiredClass("scala.scalajs.js.ThisFunction"+n)) - lazy val AllJSFunctionClasses = JSFunctionClasses ++ JSThisFunctionClasses - - lazy val RuntimeExceptionClass = requiredClass[RuntimeException] - lazy val JavaScriptExceptionClass = getClassIfDefined("scala.scalajs.js.JavaScriptException") - - lazy val JSNameAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSName") - lazy val JSFullNameAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSFullName") - lazy val JSBracketAccessAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSBracketAccess") - lazy val JSBracketCallAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSBracketCall") - lazy val JSExportAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSExport") - lazy val JSExportDescendentObjectsAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSExportDescendentObjects") - lazy val JSExportDescendentClassesAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSExportDescendentClasses") - lazy val JSExportAllAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSExportAll") - lazy val JSExportNamedAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSExportNamed") - lazy val JSExportStaticAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSExportStatic") - lazy val JSExportTopLevelAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSExportTopLevel") - lazy val JSImportAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSImport") - lazy val JSGlobalAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSGlobal") - lazy val JSGlobalScopeAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSGlobalScope") - lazy val ScalaJSDefinedAnnotation = getRequiredClass("scala.scalajs.js.annotation.ScalaJSDefined") - lazy val SJSDefinedAnonymousClassAnnotation = getRequiredClass("scala.scalajs.js.annotation.SJSDefinedAnonymousClass") - lazy val HasJSNativeLoadSpecAnnotation = getRequiredClass("scala.scalajs.js.annotation.internal.HasJSNativeLoadSpec") - lazy val JSOptionalAnnotation = getRequiredClass("scala.scalajs.js.annotation.internal.JSOptional") - - lazy val JavaDefaultMethodAnnotation = getRequiredClass("scala.scalajs.js.annotation.JavaDefaultMethod") - - lazy val JSImportNamespaceObject = getRequiredModule("scala.scalajs.js.annotation.JSImport.Namespace") - - lazy val JSAnyTpe = JSAnyClass.toTypeConstructor - lazy val JSObjectTpe = JSObjectClass.toTypeConstructor - - lazy val JSGlobalScopeTpe = JSGlobalScopeClass.toTypeConstructor - - lazy val JSFunctionTpes = JSFunctionClasses.map(_.toTypeConstructor) - - lazy val JSAnyModule = JSAnyClass.companionModule - def JSAny_fromFunction(arity: Int): TermSymbol = getMemberMethod(JSAnyModule, newTermName("fromFunction"+arity)) - - lazy val JSDynamicModule = JSDynamicClass.companionModule - lazy val JSDynamic_newInstance = getMemberMethod(JSDynamicModule, newTermName("newInstance")) - lazy val JSDynamicLiteral = getMemberModule(JSDynamicModule, newTermName("literal")) - lazy val JSDynamicLiteral_applyDynamicNamed = getMemberMethod(JSDynamicLiteral, newTermName("applyDynamicNamed")) - lazy val JSDynamicLiteral_applyDynamic = getMemberMethod(JSDynamicLiteral, newTermName("applyDynamic")) - - lazy val JSObjectModule = JSObjectClass.companionModule - lazy val JSObject_hasProperty = getMemberMethod(JSObjectModule, newTermName("hasProperty")) - lazy val JSObject_properties = getMemberMethod(JSObjectModule, newTermName("properties")) - - lazy val JSArrayModule = JSArrayClass.companionModule - lazy val JSArray_create = getMemberMethod(JSArrayModule, newTermName("apply")) - - lazy val JSThisFunctionModule = JSThisFunctionClass.companionModule - def JSThisFunction_fromFunction(arity: Int): TermSymbol = getMemberMethod(JSThisFunctionModule, newTermName("fromFunction"+arity)) - - lazy val JSConstructorTagModule = getRequiredModule("scala.scalajs.js.ConstructorTag") - lazy val JSConstructorTag_materialize = getMemberMethod(JSConstructorTagModule, newTermName("materialize")) - - lazy val RawJSTypeAnnot = getRequiredClass("scala.scalajs.js.annotation.RawJSType") - lazy val ExposedJSMemberAnnot = getRequiredClass("scala.scalajs.js.annotation.ExposedJSMember") - - lazy val JSImportModule = getRequiredModule("scala.scalajs.js.import") - lazy val JSImportModuleClass = JSImportModule.moduleClass - lazy val JSImport_apply = getMemberMethod(JSImportModuleClass, nme.apply) - - lazy val SpecialPackageModule = getPackageObject("scala.scalajs.js.special") - lazy val Special_delete = getMemberMethod(SpecialPackageModule, newTermName("delete")) - lazy val Special_debugger = getMemberMethod(SpecialPackageModule, newTermName("debugger")) - - lazy val RuntimeStringModule = getRequiredModule("scala.scalajs.runtime.RuntimeString") - lazy val RuntimeStringModuleClass = RuntimeStringModule.moduleClass - - lazy val BooleanReflectiveCallClass = getRequiredClass("scala.scalajs.runtime.BooleanReflectiveCall") - lazy val NumberReflectiveCallClass = getRequiredClass("scala.scalajs.runtime.NumberReflectiveCall") - lazy val IntegerReflectiveCallClass = getRequiredClass("scala.scalajs.runtime.IntegerReflectiveCall") - lazy val LongReflectiveCallClass = getRequiredClass("scala.scalajs.runtime.LongReflectiveCall") - - lazy val RuntimePackageModule = getPackageObject("scala.scalajs.runtime") - lazy val Runtime_wrapJavaScriptException = getMemberMethod(RuntimePackageModule, newTermName("wrapJavaScriptException")) - lazy val Runtime_unwrapJavaScriptException = getMemberMethod(RuntimePackageModule, newTermName("unwrapJavaScriptException")) - lazy val Runtime_jsObjectSuperGet = getMemberMethod(RuntimePackageModule, newTermName("jsObjectSuperGet")) - lazy val Runtime_jsObjectSuperSet = getMemberMethod(RuntimePackageModule, newTermName("jsObjectSuperSet")) - lazy val Runtime_toScalaVarArgs = getMemberMethod(RuntimePackageModule, newTermName("toScalaVarArgs")) - lazy val Runtime_genTraversableOnce2jsArray = getMemberMethod(RuntimePackageModule, newTermName("genTraversableOnce2jsArray")) - lazy val Runtime_jsTupleArray2jsObject = getMemberMethod(RuntimePackageModule, newTermName("jsTupleArray2jsObject")) - lazy val Runtime_constructorOf = getMemberMethod(RuntimePackageModule, newTermName("constructorOf")) - lazy val Runtime_newConstructorTag = getMemberMethod(RuntimePackageModule, newTermName("newConstructorTag")) - lazy val Runtime_propertiesOf = getMemberMethod(RuntimePackageModule, newTermName("propertiesOf")) - lazy val Runtime_linkingInfo = getMemberMethod(RuntimePackageModule, newTermName("linkingInfo")) - - // This is a def, since similar symbols (arrayUpdateMethod, etc.) are in runDefinitions - // (rather than definitions) and we weren't sure if it is safe to make this a lazy val - def ScalaRunTime_isArray: Symbol = getMemberMethod(ScalaRunTimeModule, newTermName("isArray")).suchThat(_.tpe.params.size == 2) - - lazy val BoxesRunTime_boxToCharacter = getMemberMethod(BoxesRunTimeModule, newTermName("boxToCharacter")) - lazy val BoxesRunTime_unboxToChar = getMemberMethod(BoxesRunTimeModule, newTermName("unboxToChar")) - - lazy val ReflectModule = getRequiredModule("scala.scalajs.reflect.Reflect") - lazy val Reflect_registerLoadableModuleClass = getMemberMethod(ReflectModule, newTermName("registerLoadableModuleClass")) - lazy val Reflect_registerInstantiatableClass = getMemberMethod(ReflectModule, newTermName("registerInstantiatableClass")) - - lazy val EnableReflectiveInstantiationAnnotation = getRequiredClass("scala.scalajs.reflect.annotation.EnableReflectiveInstantiation") - - } - - // scalastyle:on line.size.limit -} diff --git a/compiler/src/main/scala/org/scalajs/core/compiler/JSEncoding.scala b/compiler/src/main/scala/org/scalajs/core/compiler/JSEncoding.scala deleted file mode 100644 index 7fd17f9efc..0000000000 --- a/compiler/src/main/scala/org/scalajs/core/compiler/JSEncoding.scala +++ /dev/null @@ -1,302 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler - -import scala.collection.mutable - -import scala.tools.nsc._ - -import org.scalajs.core.ir -import ir.{Trees => js, Types => jstpe} - -import org.scalajs.core.compiler.util.ScopedVar -import ScopedVar.withScopedVars - -/** Encoding of symbol names for JavaScript - * - * Some issues that this encoding solves: - * * Overloading: encode the full signature in the JS name - * * Same scope for fields and methods of a class - * * Global access to classes and modules (by their full name) - * - * @author Sébastien Doeraene - */ -trait JSEncoding[G <: Global with Singleton] extends SubComponent { - self: GenJSCode[G] => - - import global._ - import jsAddons._ - - /** Outer separator string (between parameter types) */ - final val OuterSep = "__" - - /** Inner separator character (replace dots in full names) */ - final val InnerSep = "_" - - /** Name given to the local Scala.js environment variable */ - final val ScalaJSEnvironmentName = "ScalaJS" - - /** Name given to all exported stuff of a class for DCE */ - final val dceExportName = "" - - // Fresh local name generator ---------------------------------------------- - - private val usedLocalNames = new ScopedVar[mutable.Set[String]] - private val localSymbolNames = new ScopedVar[mutable.Map[Symbol, String]] - private val isReserved = - Set("arguments", "eval", ScalaJSEnvironmentName) - - def withNewLocalNameScope[A](body: => A): A = - withScopedVars( - usedLocalNames := mutable.Set.empty, - localSymbolNames := mutable.Map.empty - )(body) - - private def freshName(base: String = "x"): String = { - var suffix = 1 - var longName = base - while (usedLocalNames(longName) || isReserved(longName)) { - suffix += 1 - longName = base+"$"+suffix - } - usedLocalNames += longName - mangleJSName(longName) - } - - def freshLocalIdent()(implicit pos: ir.Position): js.Ident = - js.Ident(freshName(), None) - - def freshLocalIdent(base: String)(implicit pos: ir.Position): js.Ident = - js.Ident(freshName(base), Some(base)) - - private def localSymbolName(sym: Symbol): String = - localSymbolNames.getOrElseUpdate(sym, freshName(sym.name.toString)) - - // Encoding methods ---------------------------------------------------------- - - def encodeLabelSym(sym: Symbol)(implicit pos: Position): js.Ident = { - require(sym.isLabel, "encodeLabelSym called with non-label symbol: " + sym) - js.Ident(localSymbolName(sym), Some(sym.unexpandedName.decoded)) - } - - /** See comment in `encodeFieldSym()`. */ - private lazy val shouldMangleOuterPointerName = { - val v = scala.util.Properties.versionNumberString - !(v.startsWith("2.10.") || v.startsWith("2.11.") || v == "2.12.0-RC1") - } - - def encodeFieldSym(sym: Symbol)(implicit pos: Position): js.Ident = { - require(sym.owner.isClass && sym.isTerm && !sym.isMethod && !sym.isModule, - "encodeFieldSym called with non-field symbol: " + sym) - - val name0 = encodeMemberNameInternal(sym) - val name = - if (name0.charAt(name0.length()-1) != ' ') name0 - else name0.substring(0, name0.length()-1) - - /* Java-defined fields are always accessed as if they were private. This - * is necessary because they are defined as private by our .scala source - * files, but they are considered `!isPrivate` at use site, since their - * symbols come from Java-emitted .class files. Fortunately, we can - * easily detect those as `isJavaDefined`. This includes fields of Ref - * types (IntRef, ObjectRef, etc.) which were special-cased at use-site - * in Scala.js < 0.6.15. - * Caveat: because of this, changing the length of the superclass chain of - * a Java-defined class is a binary incompatible change. - * - * Starting with 2.12.0-RC2, we also special case outer fields. This - * essentially fixes #2382, which is caused by a class having various $outer - * pointers in its hierarchy that points to different outer instances. - * Without this fix, they all collapse to the same field in the IR. We - * cannot fix this for all Scala versions at the moment, because that would - * break backwards binary compatibility. We *do* fix it for 2.12.0-RC2 - * onwards because that also fixes #2625, which surfaced in 2.12 and is - * therefore a regression. We can do this because the 2.12 ecosystem is - * not binary compatible anyway (because of Scala) so we can break it on - * our side at the same time. - * - * TODO We should probably consider emitting *all* fields with an ancestor - * count. We cannot do that in a binary compatible way, though. This is - * filed as #2629. - */ - val idSuffix: String = { - val usePerClassSuffix = { - sym.isPrivate || - sym.isJavaDefined || - (shouldMangleOuterPointerName && sym.isOuterField) - } - if (usePerClassSuffix) - sym.owner.ancestors.count(!_.isTraitOrInterface).toString - else - "f" - } - - val encodedName = name + "$" + idSuffix - js.Ident(mangleJSName(encodedName), Some(sym.unexpandedName.decoded)) - } - - def encodeMethodSym(sym: Symbol, reflProxy: Boolean = false) - (implicit pos: Position): js.Ident = { - val (encodedName, paramsString) = encodeMethodNameInternal(sym, reflProxy) - js.Ident(encodedName + paramsString, - Some(sym.unexpandedName.decoded + paramsString)) - } - - def encodeMethodName(sym: Symbol, reflProxy: Boolean = false): String = { - val (encodedName, paramsString) = encodeMethodNameInternal(sym, reflProxy) - encodedName + paramsString - } - - /** Encodes a method symbol of java.lang.String for use in RuntimeString. - * - * This basically means adding an initial parameter of type - * java.lang.String, which is the `this` parameter. - */ - def encodeRTStringMethodSym(sym: Symbol)( - implicit pos: Position): (Symbol, js.Ident) = { - require(sym.isMethod, "encodeMethodSym called with non-method symbol: " + sym) - require(!sym.isClassConstructor && !sym.isPrivate, sym) - - val (encodedName, paramsString) = - encodeMethodNameInternal(sym, inRTClass = true) - val methodIdent = js.Ident(encodedName + paramsString, - Some(sym.unexpandedName.decoded + paramsString)) - - (jsDefinitions.RuntimeStringModuleClass, methodIdent) - } - - private def encodeMethodNameInternal(sym: Symbol, - reflProxy: Boolean = false, - inRTClass: Boolean = false): (String, String) = { - require(sym.isMethod, "encodeMethodSym called with non-method symbol: " + sym) - - def name = encodeMemberNameInternal(sym) - - def privateSuffix(owner: Symbol): String = - if (owner.isTraitOrInterface && !isImplClass(owner)) encodeClassFullName(owner) - else owner.ancestors.count(!_.isTraitOrInterface).toString - - val encodedName = { - if (sym.isClassConstructor) - "init" + InnerSep - else if (sym.isPrivate) - mangleJSName(name) + OuterSep + "p" + privateSuffix(sym.owner) - else - mangleJSName(name) - } - - val paramsString = makeParamsString(sym, reflProxy, inRTClass) - - (encodedName, paramsString) - } - - def encodeStaticMemberSym(sym: Symbol)(implicit pos: Position): js.Ident = { - require(sym.isStaticMember, - "encodeStaticMemberSym called with non-static symbol: " + sym) - js.Ident( - mangleJSName(encodeMemberNameInternal(sym)) + - makeParamsString(List(internalName(sym.tpe))), - Some(sym.unexpandedName.decoded)) - } - - def encodeLocalSym(sym: Symbol)(implicit pos: Position): js.Ident = { - /* The isValueParameter case is necessary to work around an internal bug - * of scalac: for some @varargs methods, the owner of some parameters is - * the enclosing class rather the method, so !sym.owner.isClass fails. - * Go figure ... - * See #1440 - */ - require(sym.isValueParameter || - (!sym.owner.isClass && sym.isTerm && !sym.isMethod && !sym.isModule), - "encodeLocalSym called with non-local symbol: " + sym) - js.Ident(localSymbolName(sym), Some(sym.unexpandedName.decoded)) - } - - def encodeClassType(sym: Symbol): jstpe.Type = { - if (sym == definitions.ObjectClass) jstpe.AnyType - else if (isRawJSType(sym.toTypeConstructor)) jstpe.AnyType - else { - assert(sym != definitions.ArrayClass, - "encodeClassType() cannot be called with ArrayClass") - jstpe.ClassType(encodeClassFullName(sym)) - } - } - - def encodeClassFullNameIdent(sym: Symbol)(implicit pos: Position): js.Ident = { - js.Ident(encodeClassFullName(sym), Some(sym.fullName)) - } - - def encodeClassFullName(sym: Symbol): String = { - ir.Definitions.encodeClassName( - sym.fullName + (if (needsModuleClassSuffix(sym)) "$" else "")) - } - - def needsModuleClassSuffix(sym: Symbol): Boolean = - sym.isModuleClass && !isImplClass(sym) - - def encodeComputedNameIdentity(sym: Symbol): String = { - assert(sym.owner.isModuleClass, sym) - encodeClassFullName(sym.owner) + "__" + encodeMemberNameInternal(sym) - } - - private def encodeMemberNameInternal(sym: Symbol): String = - sym.name.toString.replace("_", "$und") - - // Encoding of method signatures - - private def makeParamsString(sym: Symbol, reflProxy: Boolean, - inRTClass: Boolean): String = { - val tpe = sym.tpe - - val paramTypeNames0 = tpe.params map (p => internalName(p.tpe)) - - val hasExplicitThisParameter = - inRTClass || isScalaJSDefinedJSClass(sym.owner) - val paramTypeNames = - if (!hasExplicitThisParameter) paramTypeNames0 - else internalName(sym.owner.toTypeConstructor) :: paramTypeNames0 - - val paramAndResultTypeNames = { - if (sym.isClassConstructor) - paramTypeNames - else if (reflProxy) - paramTypeNames :+ "" - else - paramTypeNames :+ internalName(tpe.resultType) - } - makeParamsString(paramAndResultTypeNames) - } - - private def makeParamsString(paramAndResultTypeNames: List[String]) = - paramAndResultTypeNames.mkString(OuterSep, OuterSep, "") - - /** Computes the internal name for a type. */ - private def internalName(tpe: Type): String = internalName(toTypeKind(tpe)) - - private def internalName(kind: TypeKind): String = kind match { - case VOID => "V" - case kind: ValueTypeKind => kind.primitiveCharCode.toString() - case NOTHING => ir.Definitions.RuntimeNothingClass - case NULL => ir.Definitions.RuntimeNullClass - case REFERENCE(cls) => encodeClassFullName(cls) - case ARRAY(elem) => "A"+internalName(elem) - } - - /** mangles names that are illegal in JavaScript by prepending a $ - * also mangles names that would collide with these mangled names - */ - private def mangleJSName(name: String) = - if (js.isKeyword(name) || name(0).isDigit || name(0) == '$') - "$" + name - else name -} diff --git a/compiler/src/main/scala/org/scalajs/core/compiler/JSGlobalAddons.scala b/compiler/src/main/scala/org/scalajs/core/compiler/JSGlobalAddons.scala deleted file mode 100644 index c07597f396..0000000000 --- a/compiler/src/main/scala/org/scalajs/core/compiler/JSGlobalAddons.scala +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler - -import scala.tools.nsc._ - -import scala.collection.mutable - -import org.scalajs.core.ir.Trees.JSNativeLoadSpec - -/** Additions to Global meaningful for the JavaScript backend - * - * @author Sébastien Doeraene - */ -trait JSGlobalAddons extends JSDefinitions - with Compat210Component { - val global: Global - - import global._ - import jsDefinitions._ - import definitions._ - - /** JavaScript primitives, used in jscode */ - object jsPrimitives extends JSPrimitives { - val global: JSGlobalAddons.this.global.type = JSGlobalAddons.this.global - val jsAddons: ThisJSGlobalAddons = - JSGlobalAddons.this.asInstanceOf[ThisJSGlobalAddons] - } - - sealed abstract class ExportDestination - - object ExportDestination { - /** Export in the "normal" way: as an instance member, or at the top-level - * for naturally top-level things (classes and modules). - */ - case object Normal extends ExportDestination - - /** Export at the top-level. */ - case object TopLevel extends ExportDestination - - /** Export as a static member of the companion class. */ - case object Static extends ExportDestination - } - - /** global javascript interop related helpers */ - object jsInterop { - import scala.reflect.NameTransformer - import scala.reflect.internal.Flags - - /** Symbols of constructors and modules that are to be exported */ - private val exportedSymbols = - mutable.Map.empty[Symbol, List[ExportInfo]] - - /** JS native load specs of the symbols in the current compilation run. */ - private val jsNativeLoadSpecs = - mutable.Map.empty[Symbol, JSNativeLoadSpec] - - private val exportPrefix = "$js$exported$" - private val methodExportPrefix = exportPrefix + "meth$" - private val propExportPrefix = exportPrefix + "prop$" - - trait ExportInfo { - val jsName: String - val pos: Position - val isNamed: Boolean - val destination: ExportDestination - } - - sealed abstract class JSName { - def displayName: String - } - - object JSName { - // Not final because it causes annoying compile warnings - case class Literal(name: String) extends JSName { - def displayName: String = name - } - - // Not final because it causes annoying compile warnings - case class Computed(sym: Symbol) extends JSName { - def displayName: String = sym.fullName - } - } - - def clearGlobalState(): Unit = { - exportedSymbols.clear() - jsNativeLoadSpecs.clear() - } - - def registerForExport(sym: Symbol, infos: List[ExportInfo]): Unit = { - assert(!exportedSymbols.contains(sym), - "Same symbol exported twice: " + sym) - exportedSymbols.put(sym, infos) - } - - def registeredExportsOf(sym: Symbol): List[ExportInfo] = { - exportedSymbols.getOrElse(sym, Nil) - } - - /** creates a name for an export specification */ - def scalaExportName(jsName: String, isProp: Boolean): TermName = { - val pref = if (isProp) propExportPrefix else methodExportPrefix - val encname = NameTransformer.encode(jsName) - newTermName(pref + encname) - } - - /** checks if the given symbol is a JSExport */ - def isExport(sym: Symbol): Boolean = - sym.name.startsWith(exportPrefix) && !sym.hasFlag(Flags.DEFAULTPARAM) - - /** retrieves the originally assigned jsName of this export and whether it - * is a property - */ - def jsExportInfo(name: Name): (String, Boolean) = { - def dropPrefix(prefix: String) ={ - if (name.startsWith(prefix)) { - // We can't decode right away due to $ separators - val enc = name.toString.substring(prefix.length) - Some(NameTransformer.decode(enc)) - } else None - } - - dropPrefix(methodExportPrefix).map((_,false)).orElse { - dropPrefix(propExportPrefix).map((_,true)) - }.getOrElse { - throw new IllegalArgumentException( - "non-exported name passed to jsExportInfo") - } - } - - def isJSProperty(sym: Symbol): Boolean = isJSGetter(sym) || isJSSetter(sym) - - @inline private def enteringUncurryIfAtPhaseAfter[A](op: => A): A = { - if (currentRun.uncurryPhase != NoPhase && - isAtPhaseAfter(currentRun.uncurryPhase)) { - enteringPhase(currentRun.uncurryPhase)(op) - } else { - op - } - } - - /** has this symbol to be translated into a JS getter (both directions)? */ - def isJSGetter(sym: Symbol): Boolean = { - /* We only get here when `sym.isMethod`, thus `sym.isModule` implies that - * `sym` is the module's accessor. In 2.12, module accessors are synthesized - * after uncurry, thus their first info is a MethodType at phase fields. - */ - sym.isModule || (sym.tpe.params.isEmpty && enteringUncurryIfAtPhaseAfter { - sym.tpe match { - case _: NullaryMethodType => true - case PolyType(_, _: NullaryMethodType) => true - case _ => false - } - }) - } - - /** has this symbol to be translated into a JS setter (both directions)? */ - def isJSSetter(sym: Symbol): Boolean = - nme.isSetterName(sym.name) && sym.isMethod && !sym.isConstructor - - /** Is this field symbol a static field at the IR level? */ - def isFieldStatic(sym: Symbol): Boolean = { - sym.owner.isModuleClass && // usually false, avoids a lookup in the map - registeredExportsOf(sym).nonEmpty - } - - /** The export info of a static field. - * - * Requires `isFieldStatic(sym)`. - * - * The result is non-empty. If it contains an `ExportInfo` with - * `isStatic = true`, then it is the only element in the list. Otherwise, - * all elements have `isTopLevel = true`. - */ - def staticFieldInfoOf(sym: Symbol): List[ExportInfo] = - registeredExportsOf(sym) - - /** has this symbol to be translated into a JS bracket access (JS to Scala) */ - def isJSBracketAccess(sym: Symbol): Boolean = - sym.hasAnnotation(JSBracketAccessAnnotation) - - /** has this symbol to be translated into a JS bracket call (JS to Scala) */ - def isJSBracketCall(sym: Symbol): Boolean = - sym.hasAnnotation(JSBracketCallAnnotation) - - /** Gets the unqualified JS name of a symbol. - * - * If it is not explicitly specified with an `@JSName` annotation, the - * JS name is inferred from the Scala name. - */ - def jsNameOf(sym: Symbol): JSName = { - sym.getAnnotation(JSNameAnnotation).fold[JSName] { - JSName.Literal(defaultJSNameOf(sym)) - } { annotation => - annotation.args.head match { - case Literal(Constant(name: String)) => JSName.Literal(name) - case tree => JSName.Computed(tree.symbol) - } - } - } - - def defaultJSNameOf(sym: Symbol): String = { - val base = sym.unexpandedName.decoded.stripSuffix("_=") - if (!sym.isMethod) base.stripSuffix(" ") - else base - } - - /** Gets the fully qualified JS name of a static module Symbol compiled - * with the 0.6.8 binary format or earlier. - */ - def compat068FullJSNameOf(sym: Symbol): String = { - assert(sym.isModuleClass, - s"compat068FullJSNameOf called for non-module-class symbol $sym") - sym.getAnnotation(JSFullNameAnnotation).flatMap(_.stringArg(0)) getOrElse { - /* In 0.6.8, computed names did not exist, so we are necessarily - * reading a Literal here. - */ - jsNameOf(sym).asInstanceOf[JSName.Literal].name - } - } - - /** Stores the JS native load spec of a symbol for the current compilation - * run. - */ - def storeJSNativeLoadSpec(sym: Symbol, spec: JSNativeLoadSpec): Unit = { - assert(sym.isClass, - s"storeJSNativeLoadSpec called for non-class symbol $sym") - - jsNativeLoadSpecs(sym) = spec - } - - /** Gets the JS native load spec of a symbol in the current compilation run. - */ - def jsNativeLoadSpecOf(sym: Symbol): JSNativeLoadSpec = { - assert(sym.isClass, - s"jsNativeLoadSpecOf called for non-class symbol $sym") - - jsNativeLoadSpecs(sym) - } - - } - -} diff --git a/compiler/src/main/scala/org/scalajs/core/compiler/JSPrimitives.scala b/compiler/src/main/scala/org/scalajs/core/compiler/JSPrimitives.scala deleted file mode 100644 index 3e30dcad80..0000000000 --- a/compiler/src/main/scala/org/scalajs/core/compiler/JSPrimitives.scala +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler - -import scala.tools.nsc._ - -import scala.collection.mutable - -/** Extension of ScalaPrimitives for primitives only relevant to the JS backend - * - * @author Sébastie Doeraene - */ -abstract class JSPrimitives { - val global: Global - - type ThisJSGlobalAddons = JSGlobalAddons { - val global: JSPrimitives.this.global.type - } - - val jsAddons: ThisJSGlobalAddons - - import global._ - import jsAddons._ - import definitions._ - import rootMirror._ - import jsDefinitions._ - import scalaPrimitives._ - - val F2JS = 305 // FunctionN to js.FunctionN - val F2JSTHIS = 306 // FunctionN to js.ThisFunction{N-1} - - val DYNNEW = 321 // Instantiate a new JavaScript object - - val DYNLIT = 334 // js.Dynamic.literal.applyDynamic{,Named} - - val DICT_DEL = 335 // js.Dictionary.delete - - val ARR_CREATE = 337 // js.Array.apply (array literal syntax) - - val TYPEOF = 344 // typeof x - val HASPROP = 346 // js.Object.hasProperty(o, p), equiv to `p in o` in JS - val OBJPROPS = 347 // js.Object.properties(o), equiv to `for (p in o)` in JS - val JS_NATIVE = 348 // js.native. Marker method. Fails if tried to be emitted. - - val UNITVAL = 349 // () value, which is undefined - - val JS_IMPORT = 350 // js.import.apply(specifier) - - val CONSTRUCTOROF = 352 // runtime.constructorOf(clazz) - val LINKING_INFO = 354 // $linkingInfo - - val DELETE = 355 // js.special.delete - val DEBUGGER = 356 // js.special.debugger - - /** Initialize the map of primitive methods (for GenJSCode) */ - def init(): Unit = initWithPrimitives(addPrimitive) - - /** Init the map of primitive methods for Scala.js (for PrepJSInterop) */ - def initPrepJSPrimitives(): Unit = { - scalaJSPrimitives.clear() - initWithPrimitives(scalaJSPrimitives.put) - } - - /** Only call from PrepJSInterop. In GenJSCode, use - * scalaPrimitives.isPrimitive instead - */ - def isJavaScriptPrimitive(sym: Symbol): Boolean = - scalaJSPrimitives.contains(sym) - - /** For a primitive, is it one for which we should emit its body anyway? */ - def shouldEmitPrimitiveBody(sym: Symbol): Boolean = { - /* No @switch because some Scala 2.11 versions erroneously report a - * warning for switch matches with less than 3 non-default cases. - */ - scalaPrimitives.getPrimitive(sym) match { - case F2JS | F2JSTHIS => true - case _ => false - } - } - - private val scalaJSPrimitives = mutable.Map.empty[Symbol, Int] - - private def initWithPrimitives(addPrimitive: (Symbol, Int) => Unit): Unit = { - for (i <- 0 to 22) - addPrimitive(JSAny_fromFunction(i), F2JS) - for (i <- 1 to 22) - addPrimitive(JSThisFunction_fromFunction(i), F2JSTHIS) - - addPrimitive(JSDynamic_newInstance, DYNNEW) - - addPrimitive(JSDynamicLiteral_applyDynamicNamed, DYNLIT) - addPrimitive(JSDynamicLiteral_applyDynamic, DYNLIT) - - addPrimitive(JSDictionary_delete, DICT_DEL) - - addPrimitive(JSArray_create, ARR_CREATE) - - addPrimitive(JSPackage_typeOf, TYPEOF) - addPrimitive(JSPackage_native, JS_NATIVE) - - addPrimitive(JSObject_hasProperty, HASPROP) - addPrimitive(JSObject_properties, OBJPROPS) - - addPrimitive(BoxedUnit_UNIT, UNITVAL) - - addPrimitive(JSImport_apply, JS_IMPORT) - - addPrimitive(Runtime_constructorOf, CONSTRUCTOROF) - addPrimitive(Runtime_linkingInfo, LINKING_INFO) - - addPrimitive(Special_delete, DELETE) - addPrimitive(Special_debugger, DEBUGGER) - } - - def isJavaScriptPrimitive(code: Int): Boolean = - code >= 300 && code < 360 -} diff --git a/compiler/src/main/scala/org/scalajs/core/compiler/JSTreeExtractors.scala b/compiler/src/main/scala/org/scalajs/core/compiler/JSTreeExtractors.scala deleted file mode 100644 index d0fbfff897..0000000000 --- a/compiler/src/main/scala/org/scalajs/core/compiler/JSTreeExtractors.scala +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler - -import scala.annotation.tailrec - -import org.scalajs.core.ir.Trees._ -import org.scalajs.core.ir.Types._ - -/** Useful extractors for JavaScript trees */ -object JSTreeExtractors { - - object jse { - - object BlockOrAlone { - def unapply(tree: Tree): Some[(List[Tree], Tree)] = Some(tree match { - case Block(trees) => (trees.init, trees.last) - case _ => (Nil, tree) - }) - } - - /** Extracts the literal strings in "key" position of a sequence of Tuple2. - * - * Non-Tuple2 constructors are silently ignored, as well as non-literal - * keys. - */ - def extractLiteralKeysFrom(exprs: List[Tree]): List[StringLiteral] = { - exprs.collect { - case Tuple2(key: StringLiteral, _) => key - } - } - - /** A list of Tuple2, for example used as a list of key/value pairs - * (like in a call to applyDynamicNamed). - * - * Examples (Scala): - * {{{ - * method(("name1", x), ("name2", y)) - * method("name1" -> x, "name2" -> y) - * method(nameExpr1 -> x, (nameExpr2, y)) - * }}} - */ - object Tuple2List { - def unapply(exprs: List[Tree]): Option[List[(Tree, Tree)]] = { - val tuples = exprs.collect { - case Tuple2(key, value) => (key, value) - } - if (tuples.size == exprs.size) - Some(tuples) - else - None - } - } - - /** - * A literal Tuple2 - * - * Example (Scala): (x, y) - * But also (Scala): x -> y - */ - object Tuple2 { - def unapply(tree: Tree): Option[(Tree, Tree)] = tree match { - // case (x, y) - case New(ClassType("T2"), Ident("init___O__O", _), - List(_1, _2)) => - Some((_1, _2)) - // case x -> y - case Apply( - LoadModule(ClassType("s_Predef$ArrowAssoc$")), - Ident("$$minus$greater$extension__O__O__T2", _), - List( - Apply( - LoadModule(ClassType("s_Predef$")), - Ident("any2ArrowAssoc__O__O" | "ArrowAssoc__O__O", _), - List(_1)), - _2)) => - Some((_1, _2)) - case _ => - None - } - } - } - -} diff --git a/compiler/src/main/scala/org/scalajs/core/compiler/PrepJSExports.scala b/compiler/src/main/scala/org/scalajs/core/compiler/PrepJSExports.scala deleted file mode 100644 index a147ea2759..0000000000 --- a/compiler/src/main/scala/org/scalajs/core/compiler/PrepJSExports.scala +++ /dev/null @@ -1,765 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler - -import scala.collection.mutable - -import scala.tools.nsc.Global - -/** - * Prepare export generation - * - * Helpers for transformation of @JSExport annotations - */ -trait PrepJSExports[G <: Global with Singleton] { this: PrepJSInterop[G] => - - import global._ - import jsAddons._ - import definitions._ - import jsDefinitions._ - - import scala.reflect.internal.Flags - - case class ExportInfo( - jsName: String, - pos: Position, - isNamed: Boolean, - destination: ExportDestination, - ignoreInvalid: Boolean - ) extends jsInterop.ExportInfo { - assert(!isNamed || destination == ExportDestination.Normal, - s"Named export $jsName at $pos must have the Normal destination") - } - - private final val SuppressExportDeprecationsMsg = { - "\n (you can suppress this warning in 0.6.x by passing the option " + - "`-P:scalajs:suppressExportDeprecations` to scalac)" - } - - /** Generate the exporter for the given DefDef - * or ValDef (abstract val in class, val in trait or lazy val; - * these don't get DefDefs until the fields phase) - * - * If this DefDef is a constructor, it is registered to be exported by - * GenJSCode instead and no trees are returned. - */ - def genExportMember(baseSym: Symbol): List[Tree] = { - val clsSym = baseSym.owner - - val exports = exportsOf(baseSym) - val ignoreInvalid = exports.forall(_.ignoreInvalid) - - // Helper function for errors - def err(msg: String) = { - if (!ignoreInvalid) - reporter.error(exports.head.pos, msg) - Nil - } - - def memType = if (baseSym.isConstructor) "constructor" else "method" - - if (exports.isEmpty) - Nil - else if (!hasLegalExportVisibility(baseSym)) - err(s"You may only export public and protected ${memType}s") - else if (baseSym.isMacro) - err("You may not export a macro") - else if (scalaPrimitives.isPrimitive(baseSym)) - err("You may not export a primitive") - else if (hasIllegalRepeatedParam(baseSym)) - err(s"In an exported $memType, a *-parameter must come last " + - "(through all parameter lists)") - else if (hasIllegalDefaultParam(baseSym)) - err(s"In an exported $memType, all parameters with defaults " + - "must be at the end") - else if (baseSym.isConstructor) { - // we can generate constructors entirely in the backend, since they - // do not need inheritance and such. But we want to check their sanity - // here by previous tests and the following ones. - - if (!hasLegalExportVisibility(clsSym)) - err("You may only export public and protected classes") - else if (clsSym.isAbstractClass) - err("You may not export an abstract class") - else if (clsSym.isLocalToBlock) - err("You may not export a local class") - else if (!clsSym.isStatic) - err(s"You may not export a nested class. $createFactoryInOuterClassHint") - else { - jsInterop.registerForExport(baseSym, exports) - Nil - } - } else { - assert(!baseSym.isBridge, - s"genExportMember called for bridge symbol $baseSym") - - // Reset interface flag: Any trait will contain non-empty methods - clsSym.resetFlag(Flags.INTERFACE) - - val (normalExports, topLevelAndStaticExports) = - exports.partition(_.destination == ExportDestination.Normal) - - /* We can handle top level exports and static exports entirely in the - * backend. So just register them here. - */ - jsInterop.registerForExport(baseSym, topLevelAndStaticExports) - - // Actually generate exporter methods - normalExports.flatMap { exp => - if (exp.isNamed) - genNamedExport(baseSym, exp.jsName, exp.pos) :: Nil - else - genExportDefs(baseSym, exp.jsName, exp.pos) - } - } - } - - /** Checks and registers module exports on the symbol */ - def registerModuleExports(sym: Symbol): Unit = { - assert(sym.isModuleClass, "Expected module class") - registerClassOrModuleExportsInternal(sym) - } - - /** Checks and registers class exports on the symbol. */ - def registerClassExports(sym: Symbol): Unit = { - assert(!sym.isModuleClass && sym.hasAnnotation(ScalaJSDefinedAnnotation), - "Expected a Scala.js-defined JS class") - registerClassOrModuleExportsInternal(sym) - } - - private def registerClassOrModuleExportsInternal(sym: Symbol): Unit = { - val isMod = sym.isModuleClass - - val exports = exportsOf(sym) - val ignoreInvalid = exports.forall(_.ignoreInvalid) - - if (exports.nonEmpty) { - def err(msg: String) = { - if (!ignoreInvalid) - reporter.error(exports.head.pos, msg) - } - - def hasAnyNonPrivateCtor: Boolean = - sym.info.member(nme.CONSTRUCTOR).filter(!isPrivateMaybeWithin(_)).exists - - if (!hasLegalExportVisibility(sym)) { - err("You may only export public and protected " + - (if (isMod) "objects" else "classes")) - } else if (sym.isLocalToBlock) { - err("You may not export a local " + - (if (isMod) "object" else "class")) - } else if (!sym.isStatic) { - err("You may not export a nested " + - (if (isMod) "object" else s"class. $createFactoryInOuterClassHint")) - } else if (sym.isAbstractClass) { - err("You may not export an abstract class") - } else if (!isMod && !hasAnyNonPrivateCtor) { - err("You may not export a class that has only private constructors") - } else { - val (named, normal) = exports.partition(_.isNamed) - - for { - exp <- named - if !exp.ignoreInvalid - } { - reporter.error(exp.pos, "You may not use @JSNamedExport on " + - (if (isMod) "an object" else "a Scala.js-defined JS class")) - } - - jsInterop.registerForExport(sym, normal) - } - } - } - - /** Deprecate `@JSExportDescendentClasses` and `@JSExportDescendentObjects`. - * - * We do this only on the annotated symbol (not in descendants), which is - * why this test is a bit separate from everything else. - * Ideally we would simply `@deprecate` the annotations, but that would not - * allow us to suppress the deprecations. - */ - def checkDeprecationOfJSExportDescendentClassesObjects(sym: Symbol): Unit = { - if (!scalaJSOpts.suppressExportDeprecations) { - for (annot <- sym.annotations) { - if (annot.symbol == JSExportDescendentClassesAnnotation) { - reporter.warning(annot.pos, - "@JSExportDescendentClasses is deprecated and will be removed " + - "in 1.0.0. For use cases where you want to simulate "+ - "\"reflective\" instantiation, use @EnableReflectiveInstantion " + - "and scala.scalajs.reflect.Reflect.lookupInstantiatableClass " + - "instead." + - SuppressExportDeprecationsMsg) - } else if (annot.symbol == JSExportDescendentObjectsAnnotation) { - reporter.warning(annot.pos, - "@JSExportDescendentObjects is deprecated and will be removed " + - "in 1.0.0. For use cases where you want to simulate " + - "\"reflective\" loading, use @EnableReflectiveInstantion and " + - "scala.scalajs.reflect.Reflect.lookupLoadableModuleClass " + - "instead." + - SuppressExportDeprecationsMsg) - } - } - } - } - - private def createFactoryInOuterClassHint = { - "Create an exported factory method in the outer class to work " + - "around this limitation." - } - - /** retrieves the names a sym should be exported to from its annotations - * - * Note that for accessor symbols, the annotations of the accessed symbol - * are used, rather than the annotations of the accessor itself. - */ - def exportsOf(sym: Symbol): List[ExportInfo] = { - val exports = directExportsOf(sym) ++ inheritedExportsOf(sym) - - /* Calculate the distinct exports for this symbol (eliminate double - * occurrences of (name, isNamed, isTopLevel, isStatic) tuples). - */ - val grouped = exports.groupBy( - exp => (exp.jsName, exp.isNamed, exp.destination)) - - for ((_, exps) <- grouped.toList) yield { - // Make sure that we are strict if necessary - exps.find(!_.ignoreInvalid).getOrElse(exps.head) - } - } - - private def directExportsOf(sym: Symbol): List[ExportInfo] = { - val trgSym = { - def isOwnerScalaClass = !sym.owner.isModuleClass && !isJSAny(sym.owner) - - /* For accessors, look on the val/var def, if there is one. - * TODO Get rid of this when we can break binary compatibility, as - * @JSExport and @JSExportNamed are now annotated with - * @field @getter @setter - */ - if (sym.isAccessor && sym.accessed != NoSymbol) sym.accessed - // For primary Scala class constructors, look on the class itself - else if (sym.isPrimaryConstructor && isOwnerScalaClass) sym.owner - else sym - } - - // Annotations that are directly on the member - val directAnnots = trgSym.annotations.filter( - annot => isDirectMemberAnnot(annot.symbol)) - - // Is this a member export (i.e. not a class or module export)? - val isMember = sym.isMethod && !sym.isConstructor - - // Annotations for this member on the whole unit - val unitAnnots = { - if (isMember && sym.isPublic && !sym.isSynthetic) - sym.owner.annotations.filter(_.symbol == JSExportAllAnnotation) - else - Nil - } - - val allExportInfos = for { - annot <- directAnnots ++ unitAnnots - } yield { - val isNamedExport = annot.symbol == JSExportNamedAnnotation - val isExportAll = annot.symbol == JSExportAllAnnotation - val isTopLevelExport = annot.symbol == JSExportTopLevelAnnotation - val isStaticExport = annot.symbol == JSExportStaticAnnotation - val hasExplicitName = annot.args.nonEmpty - - assert(!isTopLevelExport || hasExplicitName, - "Found a top-level export without an explicit name at " + annot.pos) - - def explicitName = annot.stringArg(0).getOrElse { - reporter.error(annot.pos, - s"The argument to ${annot.symbol.name} must be a literal string") - "dummy" - } - - val name = { - if (hasExplicitName) explicitName - else if (sym.isConstructor) decodedFullName(sym.owner) - else if (sym.isClass) decodedFullName(sym) - else sym.unexpandedName.decoded.stripSuffix("_=") - } - - val destination = { - if (isTopLevelExport) ExportDestination.TopLevel - else if (isStaticExport) ExportDestination.Static - else ExportDestination.Normal - } - - // Enforce proper setter signature - if (jsInterop.isJSSetter(sym)) - checkSetterSignature(sym, annot.pos, exported = true) - - // Enforce no __ in name - if (!isTopLevelExport && name.contains("__")) { - // Get position for error message - val pos = if (hasExplicitName) annot.args.head.pos else trgSym.pos - - reporter.error(pos, - "An exported name may not contain a double underscore (`__`)") - } - - /* Illegal function application exports, i.e., method named 'apply' - * without an explicit export name. - */ - if (isMember && !hasExplicitName && sym.name == nme.apply) { - destination match { - case ExportDestination.Normal => - def shouldBeTolerated = { - isExportAll && directAnnots.exists { annot => - annot.symbol == JSExportAnnotation && - annot.args.nonEmpty && - annot.stringArg(0) == Some("apply") - } - } - - // Don't allow apply without explicit name - if (!shouldBeTolerated) { - // Get position for error message - val pos = if (isExportAll) trgSym.pos else annot.pos - - reporter.warning(pos, "Member cannot be exported to function " + - "application. It is available under the name apply " + - "instead. Add @JSExport(\"apply\") to silence this " + - "warning. This will be enforced in 1.0.") - } - - case ExportDestination.TopLevel => - throw new AssertionError( - "Found a top-level export without an explicit name at " + - annot.pos) - - case ExportDestination.Static => - reporter.error(annot.pos, - "A member cannot be exported to function application as " + - "static. Use @JSExportStatic(\"apply\") to export it under " + - "the name 'apply'.") - } - } - - // Destination-specific restrictions - destination match { - case ExportDestination.Normal => - // Make sure we do not override the default export of toString - def isIllegalToString = { - isMember && !isNamedExport && - name == "toString" && sym.name != nme.toString_ && - sym.tpe.params.isEmpty && !jsInterop.isJSGetter(sym) - } - if (isIllegalToString) { - reporter.error(annot.pos, "You may not export a zero-argument " + - "method named other than 'toString' under the name 'toString'") - } - - if (isNamedExport && jsInterop.isJSProperty(sym)) { - reporter.error(annot.pos, - "You may not export a getter or a setter as a named export") - } - - // Don't allow nested class / module exports without explicit name. - def isStaticNested = { - /* For Scala.js defined JS classes, sym is the class itself. For - * normal classes, sym is the constructor that is to be exported. - */ - val clsSym = if (sym.isClass) sym else sym.owner - clsSym.isNestedClass && clsSym.isStatic && !clsSym.isLocalToBlock - } - if (!isMember && !hasExplicitName && isStaticNested) { - reporter.error(annot.pos, - "You must set an explicit name for exports of nested classes.") - } - - // Deprecate @JSExport on classes and objects - if (!isMember && !scalaJSOpts.suppressExportDeprecations) { - if (sym.isModuleClass) { - reporter.warning(annot.pos, - "@JSExport on objects is deprecated and will be removed " + - "in 1.0.0. Use @JSExportTopLevel instead. Note that it " + - "exports the object itself (rather than a 0-arg function " + - "returning the object), so the calling JavaScript code " + - "must be adapted." + - SuppressExportDeprecationsMsg) - } else { - reporter.warning(annot.pos, - "@JSExport on classes is deprecated and will be removed " + - "in 1.0.0. Use @JSExportTopLevel instead (which does " + - "exactly the same thing on classes)." + - SuppressExportDeprecationsMsg) - } - } - - case ExportDestination.TopLevel => - if (sym.isLazy) { - reporter.error(annot.pos, - "You may not export a lazy val to the top level") - } else if (!sym.isAccessor && jsInterop.isJSProperty(sym)) { - reporter.error(annot.pos, - "You may not export a getter or a setter to the top level") - } - - val symOwner = - if (sym.isConstructor) sym.owner.owner - else sym.owner - if (!symOwner.isStatic || !symOwner.isModuleClass) { - reporter.error(annot.pos, - "Only static objects may export their members to the top level") - } - - // Warn for namespaced top-level exports - if (name.contains('.') && !scalaJSOpts.suppressExportDeprecations) { - reporter.warning(annot.pos, - "Using a namespaced export (with a '.') in @JSExportTopLevel " + - "is deprecated." + - SuppressExportDeprecationsMsg) - } - - case ExportDestination.Static => - val symOwner = - if (sym.isClassConstructor) sym.owner.owner - else sym.owner - - def companionIsScalaJSDefinedJSClass: Boolean = { - val companion = symOwner.companionClass - companion != NoSymbol && - !companion.isTrait && - isJSAny(companion) && - isScalaJSDefinedAcrossRuns(companion) - } - - if (!symOwner.isStatic || !symOwner.isModuleClass || - !companionIsScalaJSDefinedJSClass) { - reporter.error(annot.pos, - "Only a static object whose companion class is a " + - "Scala.js-defined JS class may export its members as static.") - } - - if (isMember) { - if (sym.isLazy) { - reporter.error(annot.pos, - "You may not export a lazy val as static") - } - } else { - if (sym.isTrait) { - reporter.error(annot.pos, - "You may not export a trait as static.") - } else { - reporter.error(annot.pos, - "Implementation restriction: cannot export a class or " + - "object as static") - } - } - } - - ExportInfo(name, annot.pos, isNamedExport, destination, - ignoreInvalid = false) - } - - allExportInfos.filter(_.destination == ExportDestination.Normal) - .groupBy(_.jsName) - .filter { case (jsName, group) => - if (jsName == "apply" && group.size == 2) - // @JSExportAll and single @JSExport("apply") should not be warned. - !unitAnnots.exists(_.symbol == JSExportAllAnnotation) - else - group.size > 1 - } - .foreach(_ => reporter.warning(sym.pos, s"Found duplicate @JSExport")) - - /* Filter out static exports of accessors (as they are not actually - * exported, their fields are). The above is only used to uniformly perform - * checks. - */ - if (!sym.isAccessor || sym.accessed == NoSymbol) { - allExportInfos - } else { - /* For accessors, we need to apply some special logic to static exports. - * When tested on accessors, they actually apply on *fields*, not on the - * accessors. We use the same code paths hereabove to uniformly perform - * relevant checks, but at the end of the day, we have to throw away the - * ExportInfo. - * However, we must make sure that no field is exported *twice* as static, - * nor both as static and as top-level (it is possible to export a field - * several times as top-level, though). - */ - val (topLevelAndStaticExportInfos, actualExportInfos) = - allExportInfos.partition(_.destination != ExportDestination.Normal) - - if (sym.isGetter) { - topLevelAndStaticExportInfos.find { - _.destination == ExportDestination.Static - }.foreach { firstStatic => - for { - duplicate <- topLevelAndStaticExportInfos - if duplicate ne firstStatic - } { - if (duplicate.destination == ExportDestination.Static) { - reporter.error(duplicate.pos, - "Fields (val or var) cannot be exported as static more " + - "than once") - } else { - reporter.error(duplicate.pos, - "Fields (val or var) cannot be exported both as static " + - "and at the top-level") - } - } - } - - jsInterop.registerForExport(sym.accessed, topLevelAndStaticExportInfos) - } - - actualExportInfos - } - } - - private def inheritedExportsOf(sym: Symbol): List[ExportInfo] = { - // The symbol from which we (potentially) inherit exports. It also - // gives the exports their name - val trgSym = { - if (sym.isModuleClass || (sym.isClass && isJSAny(sym))) { - sym - } else if (sym.isConstructor && sym.isPublic && !isJSAny(sym.owner) && - sym.owner.isConcreteClass && !sym.owner.isModuleClass) { - sym.owner - } else { - NoSymbol - } - } - - if (trgSym == NoSymbol) { - Nil - } else { - val trgAnnot = - if (sym.isModuleClass) JSExportDescendentObjectsAnnotation - else JSExportDescendentClassesAnnotation - - val forcingSymInfos = for { - forcingSym <- trgSym.ancestors - annot <- forcingSym.annotations - if annot.symbol == trgAnnot - } yield { - val ignoreInvalid = annot.constantAtIndex(0).fold(false)(_.booleanValue) - (forcingSym, ignoreInvalid) - } - - // The dominating forcing symbol, is the first that does not ignore - // or the first otherwise - val forcingSymInfo = - forcingSymInfos.find(!_._2).orElse(forcingSymInfos.headOption) - - val name = decodedFullName(trgSym) - val nameValid = !name.contains("__") - - val optExport = for { - (forcingSym, ignoreInvalid) <- forcingSymInfo - if nameValid || !ignoreInvalid - } yield { - // Enfore no __ in name - if (!nameValid) { - // Get all annotation positions for error message - reporter.error(sym.pos, - s"${trgSym.name} may not have a double underscore (`__`) in " + - "its fully qualified name, since it is forced to be exported by " + - s"a @${trgAnnot.name} on $forcingSym") - } - - ExportInfo(name, sym.pos, isNamed = false, ExportDestination.Normal, - ignoreInvalid) - } - - optExport.toList - } - } - - /** Just like sym.fullName, but does not encode components */ - private def decodedFullName(sym: Symbol): String = { - if (sym.isRoot || sym.isRootPackage || sym == NoSymbol) sym.name.decoded - else if (sym.owner.isEffectiveRoot) sym.name.decoded - else decodedFullName(sym.effectiveOwner.enclClass) + '.' + sym.name.decoded - } - - /** generate an exporter for a DefDef including default parameter methods */ - private def genExportDefs(defSym: Symbol, jsName: String, pos: Position) = { - val clsSym = defSym.owner - val scalaName = - jsInterop.scalaExportName(jsName, jsInterop.isJSProperty(defSym)) - - // Create symbol for new method - val expSym = defSym.cloneSymbol - - // Set position of symbol - expSym.pos = pos - - // Alter type for new method (lift return type to Any) - // The return type is lifted, in order to avoid bridge - // construction and to detect methods whose signature only differs - // in the return type. - // Attention: This will cause boxes for primitive value types and value - // classes. However, since we have restricted the return types, we can - // always safely remove these boxes again in the back-end. - if (!defSym.isConstructor) - expSym.setInfo(retToAny(expSym.tpe)) - - // Change name for new method - expSym.name = scalaName - - // Update flags - expSym.setFlag(Flags.SYNTHETIC) - expSym.resetFlag( - Flags.DEFERRED | // We always have a body - Flags.ACCESSOR | // We are never a "direct" accessor - Flags.CASEACCESSOR | // And a fortiori not a case accessor - Flags.LAZY | // We are not a lazy val (even if we export one) - Flags.OVERRIDE // Synthetic methods need not bother with this - ) - - // Remove export annotations - expSym.removeAnnotation(JSExportAnnotation) - expSym.removeAnnotation(JSExportNamedAnnotation) - - // Add symbol to class - clsSym.info.decls.enter(expSym) - - // Construct exporter DefDef tree - val exporter = genProxyDefDef(clsSym, defSym, expSym, pos) - - // Construct exporters for default getters - val defaultGetters = for { - (param, i) <- expSym.paramss.flatten.zipWithIndex - if param.hasFlag(Flags.DEFAULTPARAM) - } yield genExportDefaultGetter(clsSym, defSym, expSym, i + 1, pos) - - exporter :: defaultGetters - } - - /** Generate a dummy DefDef tree for a named export. This tree is captured - * by GenJSCode again to generate the required JavaScript logic. - */ - private def genNamedExport(defSym: Symbol, jsName: String, pos: Position) = { - val clsSym = defSym.owner - val scalaName = jsInterop.scalaExportName(jsName, false) - - // Create symbol for the new exporter method - val expSym = clsSym.newMethodSymbol(scalaName, pos, - Flags.SYNTHETIC | Flags.FINAL) - - // Mark the symbol to be a named export - expSym.addAnnotation(JSExportNamedAnnotation) - - // Create a single parameter of type Any - val param = expSym.newValueParameter(newTermName("namedArgs"), pos) - param.setInfo(AnyTpe) - - // Set method type - expSym.setInfo(MethodType(param :: Nil, AnyClass.tpe)) - - // Register method to parent - clsSym.info.decls.enter(expSym) - - // Placeholder tree - def ph = Ident(Predef_???) - - // Create a call to the forwarded method with ??? as args - val sel = Select(This(clsSym), defSym) - val call = defSym.paramss.foldLeft[Tree](sel) { - (fun, params) => Apply(fun, List.fill(params.size)(ph)) - } - - // rhs is a block to prevent boxing of result - typer.typedDefDef(DefDef(expSym, Block(call, ph))) - } - - private def genExportDefaultGetter(clsSym: Symbol, trgMethod: Symbol, - exporter: Symbol, paramPos: Int, pos: Position) = { - - // Get default getter method we'll copy - val trgGetter = - clsSym.tpe.member(nme.defaultGetterName(trgMethod.name, paramPos)) - - assert(trgGetter.exists, - s"Cannot find default getter for param $paramPos of $trgMethod") - - // Although the following must be true in a correct program, we cannot - // assert, since a graceful failure message is only generated later - if (!trgGetter.isOverloaded) { - val expGetter = trgGetter.cloneSymbol - - expGetter.name = nme.defaultGetterName(exporter.name, paramPos) - expGetter.pos = pos - - clsSym.info.decls.enter(expGetter) - - genProxyDefDef(clsSym, trgGetter, expGetter, pos) - - } else EmptyTree - } - - /** generate a DefDef tree (from [[proxySym]]) that calls [[trgSym]] */ - private def genProxyDefDef(clsSym: Symbol, trgSym: Symbol, - proxySym: Symbol, pos: Position) = atPos(pos) { - - // Helper to ascribe repeated argument lists when calling - def spliceParam(sym: Symbol) = { - if (isRepeated(sym)) - Typed(Ident(sym), Ident(tpnme.WILDCARD_STAR)) - else - Ident(sym) - } - - // Construct proxied function call - val sel = Select(This(clsSym), trgSym) - val rhs = proxySym.paramss.foldLeft[Tree](sel) { - (fun,params) => Apply(fun, params map spliceParam) - } - - typer.typedDefDef(DefDef(proxySym, rhs)) - } - - /** changes the return type of the method type tpe to Any. returns new type */ - private def retToAny(tpe: Type): Type = tpe match { - case MethodType(params, result) => MethodType(params, retToAny(result)) - case NullaryMethodType(result) => NullaryMethodType(AnyClass.tpe) - case PolyType(tparams, result) => PolyType(tparams, retToAny(result)) - case _ => AnyClass.tpe - } - - /** Whether the given symbol has a visibility that allows exporting */ - private def hasLegalExportVisibility(sym: Symbol): Boolean = - sym.isPublic || sym.isProtected && !sym.isProtectedLocal - - /** checks whether this type has a repeated parameter elsewhere than at the end - * of all the params - */ - private def hasIllegalRepeatedParam(sym: Symbol): Boolean = { - val params = sym.paramss.flatten - params.nonEmpty && params.init.exists(isRepeated _) - } - - /** checks whether there are default parameters not at the end of - * the flattened parameter list - */ - private def hasIllegalDefaultParam(sym: Symbol): Boolean = { - val isDefParam = (_: Symbol).hasFlag(Flags.DEFAULTPARAM) - sym.paramss.flatten.reverse.dropWhile(isDefParam).exists(isDefParam) - } - - /** Whether a symbol is an annotation that goes directly on a member */ - private lazy val isDirectMemberAnnot = Set[Symbol]( - JSExportAnnotation, - JSExportNamedAnnotation, - JSExportTopLevelAnnotation, - JSExportStaticAnnotation - ) - -} diff --git a/compiler/src/main/scala/org/scalajs/core/compiler/PrepJSInterop.scala b/compiler/src/main/scala/org/scalajs/core/compiler/PrepJSInterop.scala deleted file mode 100644 index 217f5343dc..0000000000 --- a/compiler/src/main/scala/org/scalajs/core/compiler/PrepJSInterop.scala +++ /dev/null @@ -1,1669 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler - -import scala.tools.nsc -import nsc._ - -import scala.collection.immutable.ListMap -import scala.collection.mutable - -import org.scalajs.core.ir.Trees.JSNativeLoadSpec - -/** Prepares classes extending js.Any for JavaScript interop - * - * This phase does: - * - Sanity checks for js.Any hierarchy - * - Annotate subclasses of js.Any to be treated specially - * - Rewrite calls to scala.Enumeration.Value (include name string) - * - Create JSExport methods: Dummy methods that are propagated - * through the whole compiler chain to mark exports. This allows - * exports to have the same semantics than methods. - * - * @author Tobias Schlatter - */ -abstract class PrepJSInterop[G <: Global with Singleton](val global: G) - extends plugins.PluginComponent with PrepJSExports[G] - with transform.Transform with PluginComponent210Compat { - - import PrepJSInterop._ - - /** Not for use in the constructor body: only initialized afterwards. */ - val jsAddons: JSGlobalAddons { - val global: PrepJSInterop.this.global.type - } - - /** Not for use in the constructor body: only initialized afterwards. */ - val scalaJSOpts: ScalaJSOptions - - import global._ - import jsAddons._ - import definitions._ - import rootMirror._ - import jsDefinitions._ - import jsInterop.JSName - - val phaseName: String = "jsinterop" - override def description: String = "prepare ASTs for JavaScript interop" - - override def newPhase(p: nsc.Phase): StdPhase = new JSInteropPhase(p) - - class JSInteropPhase(prev: nsc.Phase) extends Phase(prev) { - override def name: String = phaseName - override def description: String = PrepJSInterop.this.description - override def run(): Unit = { - jsPrimitives.initPrepJSPrimitives() - jsInterop.clearGlobalState() - super.run() - } - } - - override protected def newTransformer(unit: CompilationUnit): Transformer = - new JSInteropTransformer(unit) - - private object jsnme { - val hasNext = newTermName("hasNext") - val next = newTermName("next") - val nextName = newTermName("nextName") - val x = newTermName("x") - val Value = newTermName("Value") - val Val = newTermName("Val") - } - - private object jstpnme { - val scala_ = newTypeName("scala") // not defined in 2.10's tpnme - } - - private final val SuppressMissingJSGlobalDeprecationsMsg = { - "\n (you can suppress this warning in 0.6.x by passing the option " + - "`-P:scalajs:suppressMissingJSGlobalDeprecations` to scalac)" - } - - class JSInteropTransformer(unit: CompilationUnit) extends Transformer { - - // Force evaluation of JSDynamicLiteral: Strangely, we are unable to find - // nested objects in the JSCode phase (probably after flatten). - // Therefore we force the symbol of js.Dynamic.literal here in order to - // have access to it in JSCode. - JSDynamicLiteral - - /** Kind of the directly enclosing (most nested) owner. */ - private var enclosingOwner: OwnerKind = OwnerKind.None - - /** Cumulative kinds of all enclosing owners. */ - private var allEnclosingOwners: OwnerKind = OwnerKind.None - - /** Nicer syntax for `allEnclosingOwners is kind`. */ - private def anyEnclosingOwner: OwnerKind = allEnclosingOwners - - /** Nicer syntax for `allEnclosingOwners isnt kind`. */ - private object noEnclosingOwner { - @inline def is(kind: OwnerKind): Boolean = - allEnclosingOwners isnt kind - } - - private def enterOwner[A](kind: OwnerKind)(body: => A): A = { - require(kind.isBaseKind, kind) - val oldEnclosingOwner = enclosingOwner - val oldAllEnclosingOwners = allEnclosingOwners - enclosingOwner = kind - allEnclosingOwners |= kind - try { - body - } finally { - enclosingOwner = oldEnclosingOwner - allEnclosingOwners = oldAllEnclosingOwners - } - } - - /** Tests whether this is a ScalaDoc run. - * - * There are some things we must not do in ScalaDoc runs because, because - * ScalaDoc runs don't do everything we need, for example constant-folding - * 'final val's. - * - * At the same time, it's no big deal to skip these things, because we - * won't reach the backend. - * - * We don't completely disable this phase under ScalaDoc mostly because - * we want to keep the addition of `RawJSType` annotations, so that they - * appear in the doc. - * - * Preparing exports, however, is a pure waste of time, which we cannot - * do properly anyway because of the aforementioned limitation. - */ - private def forScaladoc = PrepJSInterop.this.forScaladoc - - /** Whether to check that we have proper literals in some crucial places. */ - private def shouldCheckLiterals = !forScaladoc - - /** Whether to check and prepare exports. */ - private def shouldPrepareExports = !forScaladoc - - /** DefDefs in class templates that export methods to JavaScript */ - private val exporters = mutable.Map.empty[Symbol, mutable.ListBuffer[Tree]] - - override def transform(tree: Tree): Tree = { - checkInternalAnnotations(tree) - - val preTransformedTree = tree match { - // Nothing is allowed in native JS classes and traits - case idef: ImplDef if enclosingOwner is OwnerKind.JSNativeClass => - reporter.error(idef.pos, "Native JS traits and classes " + - "may not have inner traits, classes or objects") - super.transform(tree) - - // Handle js.Anys - case idef: ImplDef if isJSAny(idef) => - transformJSAny(idef) - - /* In native JS objects, only js.Any stuff is allowed. However, synthetic - * companion objects need to be allowed as they get generated, when a - * native class inside a native JS object has default arguments in its - * constructor (see #1891). - */ - case modDef: ModuleDef if (enclosingOwner is OwnerKind.JSNativeMod) && - modDef.symbol.isSynthetic => - super.transform(tree) - - // In native JS objects, only js.Any stuff is allowed - case idef: ImplDef if enclosingOwner is OwnerKind.JSNativeMod => - reporter.error(idef.pos, "Native JS objects cannot contain inner " + - "Scala traits, classes or objects (i.e., not extending js.Any)") - super.transform(tree) - - // Catch the definition of scala.Enumeration itself - case cldef: ClassDef if cldef.symbol == ScalaEnumClass => - enterOwner(OwnerKind.EnumImpl) { super.transform(cldef) } - - // Catch Scala Enumerations to transform calls to scala.Enumeration.Value - case idef: ImplDef if isScalaEnum(idef) => - val sym = idef.symbol - - checkJSAnySpecificAnnotsOnNonJSAny(idef) - - val kind = - if (idef.isInstanceOf[ModuleDef]) OwnerKind.EnumMod - else OwnerKind.EnumClass - enterOwner(kind) { super.transform(idef) } - - // Catch (Scala) ClassDefs to forbid js.Anys - case cldef: ClassDef => - val sym = cldef.symbol - - checkJSAnySpecificAnnotsOnNonJSAny(cldef) - - if (sym == UndefOrClass || sym == UnionClass) - sym.addAnnotation(RawJSTypeAnnot) - - if (shouldPrepareExports && sym.isTrait) { - // Check that interface/trait is not exported - for { - exp <- exportsOf(sym) - if !exp.ignoreInvalid - } reporter.error(exp.pos, "You may not export a trait") - } - - enterOwner(OwnerKind.NonEnumScalaClass) { super.transform(cldef) } - - // Module export sanity check (export generated in JSCode phase) - case modDef: ModuleDef => - val sym = modDef.symbol - - checkJSAnySpecificAnnotsOnNonJSAny(modDef) - - if (shouldPrepareExports) - registerModuleExports(sym.moduleClass) - - enterOwner(OwnerKind.NonEnumScalaMod) { super.transform(modDef) } - - case Template(parents, self, body) => - /* Do not transform `self`. We do not need to perform any checks on - * it (#3998). - */ - treeCopy.Template(tree, parents.map(transform(_)), self, body.map(transform(_))) - - // ValOrDefDef's that are local to a block must not be transformed - case vddef: ValOrDefDef if vddef.symbol.isLocalToBlock => - super.transform(tree) - - // Catch ValDef in js.Any - case vdef: ValDef if enclosingOwner is OwnerKind.RawJSType => - transformValOrDefDefInRawJSType(vdef) - - // Catch DefDef in js.Any - case ddef: DefDef if enclosingOwner is OwnerKind.RawJSType => - transformValOrDefDefInRawJSType(fixPublicBeforeTyper(ddef)) - - // Catch ValDefs in enumerations with simple calls to Value - case ValDef(mods, name, tpt, ScalaEnumValue.NoName(optPar)) - if anyEnclosingOwner is OwnerKind.Enum => - val nrhs = ScalaEnumValName(tree.symbol.owner, tree.symbol, optPar) - treeCopy.ValDef(tree, mods, name, transform(tpt), nrhs) - - // Exporter generation - case _: ValOrDefDef if tree.symbol.isMethod => - val sym = tree.symbol - if (shouldPrepareExports) { - // Generate exporters for this ddef if required - exporters.getOrElseUpdate(sym.owner, - mutable.ListBuffer.empty) ++= genExportMember(sym) - } - super.transform(tree) - - /* Anonymous function, need to check that it is not used as a SAM for a - * JS type, unless it is js.FunctionN or js.ThisFunctionN. - * See #2921. - */ - case tree: Function => - val tpeSym = tree.tpe.typeSymbol - if (isJSAny(tpeSym) && !AllJSFunctionClasses.contains(tpeSym)) { - reporter.error(tree.pos, - "Using an anonymous function as a SAM for the JavaScript " + - "type " + tpeSym.fullNameString + " is not allowed. " + - "Use an anonymous class instead.") - } - super.transform(tree) - - // Catch Select on Enumeration.Value we couldn't transform but need to - // we ignore the implementation of scala.Enumeration itself - case ScalaEnumValue.NoName(_) if noEnclosingOwner is OwnerKind.EnumImpl => - reporter.warning(tree.pos, - """Couldn't transform call to Enumeration.Value. - |The resulting program is unlikely to function properly as this - |operation requires reflection.""".stripMargin) - super.transform(tree) - - case ScalaEnumValue.NullName() if noEnclosingOwner is OwnerKind.EnumImpl => - reporter.warning(tree.pos, - """Passing null as name to Enumeration.Value - |requires reflection at runtime. The resulting - |program is unlikely to function properly.""".stripMargin) - super.transform(tree) - - case ScalaEnumVal.NoName(_) if noEnclosingOwner is OwnerKind.EnumImpl => - reporter.warning(tree.pos, - """Calls to the non-string constructors of Enumeration.Val - |require reflection at runtime. The resulting - |program is unlikely to function properly.""".stripMargin) - super.transform(tree) - - case ScalaEnumVal.NullName() if noEnclosingOwner is OwnerKind.EnumImpl => - reporter.warning(tree.pos, - """Passing null as name to a constructor of Enumeration.Val - |requires reflection at runtime. The resulting - |program is unlikely to function properly.""".stripMargin) - super.transform(tree) - - // Rewrite js.constructorOf[T] into runtime.constructorOf(classOf[T]) - case TypeApply(ctorOfTree, List(tpeArg)) - if ctorOfTree.symbol == JSPackage_constructorOf => - genConstructorOf(tree, tpeArg) - - /* Rewrite js.ConstructorTag.materialize[T] into - * runtime.newConstructorTag[T](runtime.constructorOf(classOf[T])) - */ - case TypeApply(ctorOfTree, List(tpeArg)) - if ctorOfTree.symbol == JSConstructorTag_materialize => - val ctorOf = genConstructorOf(tree, tpeArg) - typer.typed { - atPos(tree.pos) { - gen.mkMethodCall(Runtime_newConstructorTag, - List(tpeArg.tpe), List(ctorOf)) - } - } - - /* Catch calls to Predef.classOf[T]. These should NEVER reach this phase - * but unfortunately do. In normal cases, the typer phase replaces these - * calls by a literal constant of the given type. However, when we compile - * the scala library itself and Predef.scala is in the sources, this does - * not happen. - * - * The trees reach this phase under the form: - * - * scala.this.Predef.classOf[T] - * - * or, as of Scala 2.12.0, as: - * - * scala.Predef.classOf[T] - * - * or so it seems, at least. - * - * If we encounter such a tree, depending on the plugin options, we fail - * here or silently fix those calls. - */ - case TypeApply(classOfTree @ Select(predef, nme.classOf), List(tpeArg)) - if predef.symbol == PredefModule => - if (scalaJSOpts.fixClassOf) { - // Replace call by literal constant containing type - if (typer.checkClassType(tpeArg)) { - typer.typed { Literal(Constant(tpeArg.tpe.dealias.widen)) } - } else { - reporter.error(tpeArg.pos, s"Type ${tpeArg} is not a class type") - EmptyTree - } - } else { - reporter.error(classOfTree.pos, - """This classOf resulted in an unresolved classOf in the jscode - |phase. This is most likely a bug in the Scala compiler. ScalaJS - |is probably able to work around this bug. Enable the workaround - |by passing the fixClassOf option to the plugin.""".stripMargin) - EmptyTree - } - - // Fix for issue with calls to js.Dynamic.x() - // Rewrite (obj: js.Dynamic).x(...) to obj.applyDynamic("x")(...) - case Select(Select(trg, jsnme.x), nme.apply) if isJSDynamic(trg) => - val newTree = atPos(tree.pos) { - Apply( - Select(transform(trg), newTermName("applyDynamic")), - List(Literal(Constant("x"))) - ) - } - typer.typed(newTree, Mode.FUNmode, tree.tpe) - - - // Fix for issue with calls to js.Dynamic.x() - // Rewrite (obj: js.Dynamic).x to obj.selectDynamic("x") - case Select(trg, jsnme.x) if isJSDynamic(trg) => - val newTree = atPos(tree.pos) { - Apply( - Select(transform(trg), newTermName("selectDynamic")), - List(Literal(Constant("x"))) - ) - } - typer.typed(newTree, Mode.FUNmode, tree.tpe) - - case _ => super.transform(tree) - } - - if (tree.isInstanceOf[ImplDef]) - checkDeprecationOfJSExportDescendentClassesObjects(tree.symbol) - - postTransform(preTransformedTree) - } - - private def genConstructorOf(tree: Tree, tpeArg: Tree): Tree = { - val classValue = try { - typer.typedClassOf(tree, tpeArg) - } catch { - case typeError: TypeError => - reporter.error(typeError.pos, typeError.msg) - EmptyTree - } - - if (classValue != EmptyTree) { - val Literal(classConstant) = classValue - val tpe = classConstant.typeValue.dealiasWiden - val typeSym = tpe.typeSymbol - if (!typeSym.isTrait && !typeSym.isModuleClass) { - typer.typed { - atPos(tree.pos) { - Apply( - Select(Ident(RuntimePackageModule), newTermName("constructorOf")), - List(classValue)) - } - } - } else { - reporter.error(tpeArg.pos, - s"non-trait class type required but $tpe found") - EmptyTree - } - } else { - EmptyTree - } - } - - private def postTransform(tree: Tree) = tree match { - case _ if !shouldPrepareExports => - tree - - case Template(parents, self, body) => - val clsSym = tree.symbol.owner - - // Check that @JSExportStatic fields come first - if (clsSym.isModuleClass) { // quick check to avoid useless work - var foundStatOrNonStaticVal: Boolean = false - for (tree <- body) { - tree match { - case vd: ValDef if vd.symbol.hasAnnotation(JSExportStaticAnnotation) => - if (foundStatOrNonStaticVal) { - reporter.error(vd.pos, - "@JSExportStatic vals and vars must be defined before " + - "any other val/var, and before any constructor " + - "statement.") - } - case vd: ValDef if !vd.symbol.isLazy => - foundStatOrNonStaticVal = true - case _: MemberDef => - case _ => - foundStatOrNonStaticVal = true - } - } - } - - // Add exports to the template, if there are any - exporters.get(clsSym).fold { - tree // nothing to change - } { exports => - treeCopy.Template(tree, parents, self, body ::: exports.toList) - } - - case memDef: MemberDef => - val sym = memDef.symbol - if (sym.isLocalToBlock && !sym.owner.isCaseApplyOrUnapply) { - // We exclude case class apply (and unapply) to work around SI-8826 - for { - exp <- exportsOf(sym) - if !exp.ignoreInvalid - } { - reporter.error(exp.pos, "You may not export a local definition") - } - } - - // Expose objects (modules) members of Scala.js-defined JS classes - if (sym.isModule && (enclosingOwner is OwnerKind.JSNonNative)) { - if (shouldModuleBeExposed(sym)) - sym.addAnnotation(ExposedJSMemberAnnot) - } - - memDef - - case _ => tree - } - - /** - * Performs checks and rewrites specific to classes / objects extending - * js.Any - */ - private def transformJSAny(implDef: ImplDef) = { - val sym = implDef match { - case _: ModuleDef => implDef.symbol.moduleClass - case _ => implDef.symbol - } - - lazy val badParent = sym.info.parents find { t => - /* We have to allow scala.Dynamic to be able to define js.Dynamic - * and similar constructs. This causes the unsoundness filed as #1385. - */ - !(t <:< JSAnyClass.tpe || t =:= AnyRefClass.tpe || t =:= DynamicClass.tpe) - } - - def isNativeJSTraitType(tpe: Type): Boolean = { - val sym = tpe.typeSymbol - sym.isTrait && !isScalaJSDefinedAcrossRuns(sym) - } - - val isJSAnonFun = isJSLambda(sym) - - for (annot <- sym.getAnnotation(ScalaJSDefinedAnnotation)) { - reporter.warning(annot.pos, - "@ScalaJSDefined is deprecated: " + - "add `-P:scalajs:sjsDefinedByDefault` to your scalac options and " + - "simply remove `@ScalaJSDefined`") - } - - sym.addAnnotation(RawJSTypeAnnot) - if (sym.isAnonymousClass && !isJSAnonFun) { - sym.addAnnotation(ScalaJSDefinedAnnotation) - sym.addAnnotation(SJSDefinedAnonymousClassAnnotation) - } - - // Honor -P:scalajs:sjsDefinedByDefault - if (scalaJSOpts.sjsDefinedByDefault) { - if (!isJSAnonFun && !sym.hasAnnotation(JSNativeAnnotation) && - !sym.hasAnnotation(ScalaJSDefinedAnnotation)) { - sym.addAnnotation(ScalaJSDefinedAnnotation) - } - } - - /* Convert `extends js.GlobalScope` to `@JSGlobalScope`. - * No warning because `js.GlobalScope` already causes a deprecation - * warning. - * - * Note that due to an implementation detail of `addAnnotation()`, this - * will add `@JSGlobalScope` *before* all user-defined annotations. This - * is what we want here. The association `extends js.GlobalScope` + - * `@JSName` used not to be checked, in which case `js.GlobalScope` took - * precedence. The fact that `@JSGlobalScope` appears first in this case - * allows us to more easily preserve this behavior in - * `checkAndGetJSNativeLoadingSpecAnnotOf()`. - */ - if (sym.isSubClass(JSGlobalScopeClass) && sym != JSGlobalScopeClass) { - val annotInfo = { - AnnotationInfo(JSGlobalScopeAnnotation.tpe, Nil, Nil) - .setPos(implDef.pos) - } - sym.addAnnotation(annotInfo) - } - - val isJSNative = !sym.hasAnnotation(ScalaJSDefinedAnnotation) - - // Forbid @EnableReflectiveInstantiation on JS types - sym.getAnnotation(EnableReflectiveInstantiationAnnotation).foreach { - annot => - reporter.error(annot.pos, - "@EnableReflectiveInstantiation cannot be used on types " + - "extending js.Any.") - } - - if (sym.isPackageObjectClass) { - reporter.warning(implDef.pos, - "Package objects inheriting from js.Any are deprecated. " + - "Use a normal object instead.") - } else if (isJSNative && !isJSAnonFun && - !sym.hasAnnotation(JSNativeAnnotation)) { - reporter.warning(implDef.pos, - "Classes, traits and objects inheriting from js.Any should be " + - "annotated with @js.native, unless they have @ScalaJSDefined. " + - "The default will switch to Scala.js-defined in the next major " + - "version of Scala.js.") - } else if (!isJSNative && sym.hasAnnotation(JSNativeAnnotation)) { - reporter.error(implDef.pos, - "@ScalaJSDefined and @js.native cannot be used together") - } - - def strKind = - if (sym.isTrait) "trait" - else if (sym.isModuleClass) "object" - else "class" - - // Check that we do not have a case modifier - if (implDef.mods.hasFlag(Flag.CASE)) { - reporter.error(implDef.pos, "Classes and objects extending " + - "js.Any may not have a case modifier") - } - - // Check that we do not extend a trait that does not extends js.Any - if (!isJSAnonFun && badParent.isDefined) { - val badName = badParent.get.typeSymbol.fullName - reporter.error(implDef.pos, s"${sym.nameString} extends ${badName} " + - "which does not extend js.Any.") - } - - // Checks for Scala.js-defined JS stuff - if (!isJSNative) { - // Unless it is a trait, it cannot be in a native JS object - if (!sym.isTrait && (enclosingOwner is OwnerKind.JSNativeMod)) { - reporter.error(implDef.pos, - "Native JS objects cannot contain inner Scala.js-defined JS " + - "classes or objects") - } - - // Unless it is a trait, it cannot inherit directly from AnyRef - if (!sym.isTrait && sym.info.parents.exists(_ =:= AnyRefClass.tpe)) { - reporter.error(implDef.pos, - s"A Scala.js-defined JS $strKind cannot directly extend AnyRef. " + - "It must extend a JS class (native or not).") - } - - // Check that we do not inherit directly from a native JS trait - if (sym.info.parents.exists(isNativeJSTraitType)) { - reporter.error(implDef.pos, - s"A Scala.js-defined JS $strKind cannot directly extend a "+ - "native JS trait.") - } - - // Check that there is no JS-native-specific annotation - checkJSNativeSpecificAnnotsOnNonJSNative(implDef) - } - - if (shouldCheckLiterals) { - checkJSNameArgument(implDef) - checkJSGlobalLiteral(sym) - checkJSImportLiteral(sym) - } - - // Checks for native JS stuff, excluding JS anon functions - if (isJSNative && !isJSAnonFun) { - // Check if we may have a JS native here - if (sym.isLocalToBlock) { - reporter.error(implDef.pos, - "Local native JS classes and objects are not allowed") - } else if (anyEnclosingOwner is OwnerKind.AnyClass) { - reporter.error(implDef.pos, "Traits and classes " + - "may not have inner native JS traits, classes or objects") - } else if (enclosingOwner is OwnerKind.JSMod) { - reporter.error(implDef.pos, "Scala.js-defined JS objects " + - "may not have inner native JS classes or objects") - } else if (!sym.isTrait) { - /* Compute the loading spec now, before `flatten` destroys the name - * and (in 2.10) the original owner chain. We store it in a global - * map. - */ - val loadSpec = checkAndComputeJSNativeLoadSpecOf(implDef.pos, sym) - jsInterop.storeJSNativeLoadSpec(sym, loadSpec) - - // Mark module classes as having the new format - if (sym.isModuleClass) - sym.addAnnotation(HasJSNativeLoadSpecAnnotation) - } else { - assert(sym.isTrait, sym) // just tested in the previous `if` - for { - annot <- sym.annotations - annotSym = annot.symbol - if JSNativeLoadingSpecAnnots.contains(annotSym) - } { - if (annotSym == JSNameAnnotation) { - reporter.warning(annot.pos, - "Traits should not have an @JSName annotation, as it does " + - "not have any effect. This will be enforced in 1.0.") - } else { - reporter.error(annot.pos, - s"Traits may not have an @${annotSym.nameString} annotation.") - } - } - } - } - - if (shouldPrepareExports) { - if (sym.isTrait) { - // Check that interface/trait is not exported - for { - exp <- exportsOf(sym) - if !exp.ignoreInvalid - } { - reporter.error(exp.pos, "You may not export a trait") - } - } else if (isJSNative) { - // Check that a JS native type is not exported - for { - exp <- exportsOf(sym) - if !exp.ignoreInvalid - } { - reporter.error(exp.pos, - "You may not export a native JS class or object") - } - } else { - if (sym.isModuleClass) - registerModuleExports(sym) - else if (!sym.isTrait) - registerClassExports(sym) - } - } - - // Check for consistency of JS semantics across overriding - for (overridingPair <- new overridingPairs.Cursor(sym).iterator) { - val low = overridingPair.low - val high = overridingPair.high - - def errorPos = { - if (sym == low.owner) low.pos - else if (sym == high.owner) high.pos - else sym.pos - } - - def memberDefString(membSym: Symbol): String = - membSym.defStringSeenAs(sym.thisType.memberType(membSym)) - - // Check for overrides with different JS names - issue #1983 - if (jsInterop.jsNameOf(low) != jsInterop.jsNameOf(high)) { - val msg = { - def memberDefStringWithJSName(membSym: Symbol) = { - memberDefString(membSym) + - membSym.locationString + " with JSName '" + - jsInterop.jsNameOf(membSym).displayName + '\'' - } - "A member of a JS class is overriding another member with a different JS name.\n\n" + - memberDefStringWithJSName(low) + "\n" + - " is conflicting with\n" + - memberDefStringWithJSName(high) + "\n" - } - - reporter.warning(errorPos, msg) - } - - /* Cannot override a non-@JSOptional with an @JSOptional. Unfortunately - * at this point the symbols do not have @JSOptional yet, so we need - * to detect whether it would be applied. - */ - if (!isJSNative) { - def isJSOptional(sym: Symbol): Boolean = { - sym.owner.isTrait && !sym.isDeferred && !sym.isConstructor && - isScalaJSDefinedAcrossRuns(sym.owner) - } - - if (isJSOptional(low) && !(high.isDeferred || isJSOptional(high))) { - reporter.error(errorPos, - s"Cannot override concrete ${memberDefString(high)} from " + - s"${high.owner.fullName} in a Scala.js-defined JS trait.") - } - } - } - - val kind = { - if (!isJSNative) { - if (sym.isModuleClass) OwnerKind.JSMod - else OwnerKind.JSClass - } else { - if (sym.isModuleClass) OwnerKind.JSNativeMod - else OwnerKind.JSNativeClass - } - } - enterOwner(kind) { super.transform(implDef) } - } - - private def checkAndComputeJSNativeLoadSpecOf(pos: Position, - sym: Symbol): JSNativeLoadSpec = { - import JSNativeLoadSpec._ - - if (enclosingOwner is OwnerKind.JSNativeMod) { - for { - annot <- sym.annotations - annotSym = annot.symbol - if JSNativeLoadingSpecAnnots.contains(annotSym) - } { - if (annotSym != JSNameAnnotation) { - reporter.error(annot.pos, - "Classes and objects nested in a JS native object cannot " + - s"have an @${annotSym.nameString} annotation.") - } else if (annot.args.head.tpe.typeSymbol != StringClass) { - reporter.error(annot.pos, - "Implementation restriction: @JSName with a js.Symbol is not " + - "supported on nested native classes and objects") - } - } - - val jsName = jsInterop.jsNameOf(sym) match { - case JSName.Literal(jsName) => jsName - case JSName.Computed(_) => "" // compile error above - } - - val ownerLoadSpec = jsInterop.jsNativeLoadSpecOf(sym.owner) - ownerLoadSpec match { - case Global(path) => - Global(path :+ jsName) - case Import(module, path) => - Import(module, path :+ jsName) - case ImportWithGlobalFallback( - Import(module, modulePath), Global(globalPath)) => - ImportWithGlobalFallback( - Import(module, modulePath :+ jsName), - Global(globalPath :+ jsName)) - } - } else { - def parsePath(pathName: String): List[String] = - pathName.split('.').toList - - def needsExplicitJSName = { - (enclosingOwner is OwnerKind.ScalaMod) && - !sym.owner.isPackageObjectClass - } - - def globalFromName = { - val path = jsInterop.jsNameOf(sym) match { - case JSName.Literal(pathName) => - parsePath(pathName) - case JSName.Computed(_) => - // this happens in erroneous cases that report a compile error - List("") - } - JSNativeLoadSpec.Global(path) - } - - checkAndGetJSNativeLoadingSpecAnnotOf(sym) match { - case Some(annot) if annot.symbol == JSGlobalScopeAnnotation => - if (!sym.isModuleClass) { - reporter.error(annot.pos, - "Only native JS objects can have an " + - "@JSGlobalScope annotation (or extend js.GlobalScope).") - } - JSNativeLoadSpec.Global(Nil) - - case Some(annot) if annot.symbol == JSGlobalAnnotation => - val pathName = annot.stringArg(0).getOrElse { - if (needsExplicitJSName) { - reporter.error(annot.pos, - "Native JS classes and objects inside non-native objects " + - "must have an explicit name in @JSGlobal") - } - jsInterop.defaultJSNameOf(sym) - } - JSNativeLoadSpec.Global(parsePath(pathName)) - - case Some(annot) if annot.symbol == JSImportAnnotation => - val module = annot.stringArg(0).getOrElse { - "" // do not care because it does not compile anyway - } - val path = annot.stringArg(1).fold[List[String]](Nil)(parsePath) - val importSpec = Import(module, path) - annot.stringArg(2).fold[JSNativeLoadSpec] { - importSpec - } { globalPathName => - val globalSpec = Global(parsePath(globalPathName)) - ImportWithGlobalFallback(importSpec, globalSpec) - } - - case Some(annot) if annot.symbol == JSNameAnnotation => - if (!scalaJSOpts.suppressMissingJSGlobalDeprecations) { - reporter.warning(annot.pos, - "@JSName on top-level native JS classes and objects " + - "(or native JS classes and objects inside Scala objects) " + - "is deprecated, and should be replaced by @JSGlobal (with " + - "the same meaning). This will be enforced in 1.0." + - SuppressMissingJSGlobalDeprecationsMsg) - } - - globalFromName - - case None => - if (needsExplicitJSName) { - if (sym.isModuleClass) { - reporter.error(pos, - "Native JS objects inside non-native objects must " + - "have an @JSGlobal or @JSImport annotation") - } else { - // This should be an error, but we erroneously allowed that before - reporter.warning(pos, - "Native JS classes inside non-native objects should " + - "have an @JSGlobal or @JSImport annotation. " + - "This will be enforced in 1.0.") - } - } else { - if (!scalaJSOpts.suppressMissingJSGlobalDeprecations && - !sym.isPackageObjectClass) { - reporter.warning(pos, - "Top-level native JS classes and objects should have an " + - "@JSGlobal or @JSImport annotation. This will be " + - "enforced in 1.0.\n" + - " If migrating from 0.6.14 or earlier, the equivalent " + - "behavior is an @JSGlobal without parameter." + - SuppressMissingJSGlobalDeprecationsMsg) - } - } - - globalFromName - } - } - } - - /** Verify a ValOrDefDef inside a js.Any */ - private def transformValOrDefDefInRawJSType(tree: ValOrDefDef) = { - val sym = tree.symbol - - assert(!sym.isLocalToBlock, s"$tree at ${tree.pos}") - - if (shouldPrepareExports) { - // Exports are never valid on members of JS types - lazy val memType = if (sym.isConstructor) "constructor" else "method" - for { - exp <- exportsOf(sym) - if !exp.ignoreInvalid - } { - reporter.error(exp.pos, - s"You may not export a $memType of a subclass of js.Any") - } - - /* Add the @ExposedJSMember annotation to exposed symbols in - * Scala.js-defined classes. - */ - if (enclosingOwner is OwnerKind.JSNonNative) { - def shouldBeExposed: Boolean = { - !sym.isConstructor && - !sym.isValueParameter && - !sym.isParamWithDefault && - !sym.isSynthetic && - !isPrivateMaybeWithin(sym) - } - if (shouldBeExposed) { - sym.addAnnotation(ExposedJSMemberAnnot) - - /* The field being accessed must also be exposed, although it's - * private. - */ - if (sym.isAccessor) - sym.accessed.addAnnotation(ExposedJSMemberAnnot) - } - } - } - - /* If this is an accessor, copy a potential @JSName annotation from - * the field since otherwise it will get lost for traits (since they - * have no fields). - * - * Do this only if the accessor does not already have an @JSName itself - * (this happens almost all the time now that @JSName is annotated with - * @field @getter @setter). - */ - if (sym.isAccessor && !sym.hasAnnotation(JSNameAnnotation)) - sym.accessed.getAnnotation(JSNameAnnotation).foreach(sym.addAnnotation) - - sym.name match { - case nme.apply if !sym.hasAnnotation(JSNameAnnotation) => - if (jsInterop.isJSGetter(sym)) { - reporter.error(sym.pos, s"A member named apply represents function " + - "application in JavaScript. A parameterless member should be " + - "exported as a property. You must add @JSName(\"apply\")") - } else if (enclosingOwner is OwnerKind.JSNonNative) { - reporter.error(sym.pos, - "A Scala.js-defined JavaScript class cannot declare a method " + - "named `apply` without `@JSName`") - } - - case nme.equals_ if sym.tpe.matches(Any_equals.tpe) => - reporter.warning(sym.pos, "Overriding equals in a JS class does " + - "not change how it is compared. To silence this warning, change " + - "the name of the method and optionally add @JSName(\"equals\").") - - case nme.hashCode_ if sym.tpe.matches(Any_hashCode.tpe) => - reporter.warning(sym.pos, "Overriding hashCode in a JS class does " + - "not change its hash code. To silence this warning, change " + - "the name of the method and optionally add @JSName(\"hashCode\").") - - case _ => - } - - if (jsInterop.isJSSetter(sym)) - checkSetterSignature(sym, tree.pos, exported = false) - - if (jsInterop.isJSBracketAccess(sym)) { - if (enclosingOwner is OwnerKind.JSNonNative) { - reporter.error(tree.pos, - "@JSBracketAccess is not allowed in Scala.js-defined JS classes") - } else { - val paramCount = sym.paramss.map(_.size).sum - if (paramCount != 1 && paramCount != 2) { - reporter.error(tree.pos, - "@JSBracketAccess methods must have one or two parameters") - } else if (paramCount == 2 && - sym.tpe.finalResultType.typeSymbol != UnitClass) { - reporter.error(tree.pos, - "@JSBracketAccess methods with two parameters must return Unit") - } - - for (param <- sym.paramss.flatten) { - if (isScalaRepeatedParamType(param.tpe)) { - reporter.error(param.pos, - "@JSBracketAccess methods may not have repeated parameters") - } else if (param.isParamWithDefault) { - reporter.error(param.pos, - "@JSBracketAccess methods may not have default parameters") - } - } - } - } - - if (jsInterop.isJSBracketCall(sym)) { - if (enclosingOwner is OwnerKind.JSNonNative) { - reporter.error(tree.pos, - "@JSBracketCall is not allowed in Scala.js-defined JS classes") - } else { - // JS bracket calls must have at least one non-repeated parameter - sym.tpe.paramss match { - case (param :: _) :: _ if !isScalaRepeatedParamType(param.tpe) => - // ok - case _ => - reporter.error(tree.pos, "@JSBracketCall methods must have at " + - "least one non-repeated parameter") - } - } - } - - if (sym.hasAnnotation(NativeAttr)) { - // Native methods are not allowed - reporter.error(tree.pos, "Methods in a js.Any may not be @native") - } - - if (sym.hasAnnotation(JSGlobalAnnotation)) { - reporter.error(tree.pos, - "Methods and fields cannot be annotated with @JSGlobal.") - } else if (sym.hasAnnotation(JSImportAnnotation)) { - reporter.error(tree.pos, - "Methods and fields cannot be annotated with @JSImport.") - } - - if (shouldCheckLiterals) - checkJSNameArgument(tree) - - /* Check that there is at most one @JSName annotation. We used not to - * check this, so we can only warn. - */ - val allJSNameAnnots = sym.annotations.filter(_.symbol == JSNameAnnotation) - for (duplicate <- allJSNameAnnots.drop(1)) { // does not throw if empty - reporter.warning(duplicate.pos, - "A duplicate @JSName annotation is ignored. " + - "This will become an error in 1.0.0.") - } - - /* In native JS types, there should not be any private member, except - * private[this] constructors. - */ - if ((enclosingOwner is OwnerKind.JSNative) && isPrivateMaybeWithin(sym)) { - // Necessary for `private[this] val/var - def isFieldPrivateThis: Boolean = { - sym.isPrivateThis && - !sym.isParamAccessor && - !sym.owner.info.decls.exists(s => s.isGetter && s.accessed == sym) - } - - if (sym.isClassConstructor) { - if (!sym.isPrivateThis) { - reporter.warning(tree.pos, - "Declaring private constructors in native JS classes is " + - "deprecated, because they do not behave the same way as in " + - "Scala.js-defined JS classes. Use `private[this]` instead. " + - "This will become an error in 1.0.0.") - } - } else if (sym.isMethod || isFieldPrivateThis) { - reporter.warning(tree.pos, - "Declaring private members in native JS classes is " + - "deprecated, because they do not behave the same way as in " + - "Scala.js-defined JS classes. Use a public member in a " + - "private facade instead. " + - "This will become an error in 1.0.0.") - } - } - - if (enclosingOwner is OwnerKind.JSNonNative) { - // Private methods cannot be overloaded - if (sym.isMethod && isPrivateMaybeWithin(sym)) { - val alts = sym.owner.info.member(sym.name).filter(_.isMethod) - if (alts.isOverloaded) { - reporter.error(tree.pos, - "Private methods in Scala.js-defined JS classes cannot be " + - "overloaded. Use different names instead.") - } - } - - // private[Scope] methods must be final - if (sym.isMethod && (sym.hasAccessBoundary && !sym.isProtected) && - !sym.isFinal && !sym.isClassConstructor) { - reporter.error(tree.pos, - "Qualified private members in Scala.js-defined JS classes " + - "must be final") - } - - // Traits must be pure interfaces, except for js.undefined members - if (sym.owner.isTrait && sym.isTerm && !sym.isConstructor) { - if (sym.isMethod && isPrivateMaybeWithin(sym)) { - reporter.error(tree.pos, - "A Scala.js-defined JS trait cannot contain private members") - } else if (sym.isLazy) { - reporter.error(tree.pos, - "A Scala.js-defined JS trait cannot contain lazy vals") - } else if (!sym.isDeferred) { - /* Tell the back-end not emit this thing. In fact, this only - * matters for mixed-in members created from this member. - */ - sym.addAnnotation(JSOptionalAnnotation) - - // For non-accessor methods, check that they do not have parens - if (sym.isMethod && !sym.isAccessor) { - sym.tpe match { - case _: NullaryMethodType => - // ok - case PolyType(_, _: NullaryMethodType) => - // ok - case _ => - reporter.error(tree.rhs.pos, - "In Scala.js-defined JS traits, defs with parentheses " + - "must be abstract.") - } - } - - /* Check that the right-hand-side is `js.undefined`. - * - * On 2.12+, fields are created later than this phase, and getters - * still hold the right-hand-side that we need to check (we - * identify this case with `sym.accessed == NoSymbol`). - * On 2.11 and before, however, the getter has already been - * rewritten to read the field, so we must not check it. - * In either case, setters must not be checked. - */ - if (!sym.isAccessor || (sym.isGetter && sym.accessed == NoSymbol)) { - // Check that the tree's body is `js.undefined` - tree.rhs match { - case sel: Select if sel.symbol == JSPackage_undefined => - // ok - case _ => - reporter.error(tree.rhs.pos, - "Members of Scala.js-defined JS traits must either be " + - "abstract, or their right-hand-side must be " + - "`js.undefined`.") - } - } - } - } - } - - if (sym.isPrimaryConstructor || sym.isValueParameter || - sym.isParamWithDefault || sym.isAccessor || - sym.isParamAccessor || sym.isDeferred || sym.isSynthetic || - AllJSFunctionClasses.contains(sym.owner) || - (enclosingOwner is OwnerKind.JSNonNative)) { - /* Ignore (i.e. allow) primary ctor, parameters, default parameter - * getters, accessors, param accessors, abstract members, synthetic - * methods (to avoid double errors with case classes, e.g. generated - * copy method), js.Functions and js.ThisFunctions (they need abstract - * methods for SAM treatment), and any member of a Scala.js-defined - * JS class/trait. - */ - } else if (jsPrimitives.isJavaScriptPrimitive(sym)) { - // No check for primitives. We trust our own standard library. - } else if (sym.isConstructor) { - // Force secondary ctor to have only a call to the primary ctor inside - tree.rhs match { - case Block(List(Apply(trg, _)), Literal(Constant(()))) - if trg.symbol.isPrimaryConstructor && - trg.symbol.owner == sym.owner => - // everything is fine here - case _ => - reporter.error(tree.pos, "A secondary constructor of a class " + - "extending js.Any may only call the primary constructor") - } - } else { - // Check that the tree's body is either empty or calls js.native - tree.rhs match { - case sel: Select if sel.symbol == JSPackage_native => - case _ => - val pos = if (tree.rhs != EmptyTree) tree.rhs.pos else tree.pos - reporter.warning(pos, "Members of traits, classes and objects " + - "extending js.Any may only contain members that call js.native. " + - "This will be enforced in 1.0.") - } - - if (sym.tpe.resultType.typeSymbol == NothingClass && - tree.tpt.asInstanceOf[TypeTree].original == null) { - // Warn if resultType is Nothing and not ascribed - val name = sym.name.decoded.trim - reporter.warning(tree.pos, s"The type of $name got inferred " + - "as Nothing. To suppress this warning, explicitly ascribe " + - "the type.") - } - } - - super.transform(tree) - } - - private def checkJSAnySpecificAnnotsOnNonJSAny(implDef: ImplDef): Unit = { - val sym = implDef.symbol - - if (sym.hasAnnotation(ScalaJSDefinedAnnotation)) { - reporter.error(implDef.pos, - "@ScalaJSDefined is only allowed on classes extending js.Any") - } - - if (sym.hasAnnotation(JSNativeAnnotation)) { - reporter.error(implDef.pos, - "Classes, traits and objects not extending js.Any may not have an " + - "@js.native annotation") - } else { - checkJSNativeSpecificAnnotsOnNonJSNative(implDef) - } - } - - private def checkJSNativeSpecificAnnotsOnNonJSNative( - implDef: ImplDef): Unit = { - val sym = implDef.symbol - - val allowJSName = { - sym.isModuleOrModuleClass && - (enclosingOwner is OwnerKind.JSNonNative) && - shouldModuleBeExposed(sym) - } - - for (annot <- sym.annotations) { - if (annot.symbol == JSNameAnnotation && !allowJSName) { - reporter.warning(annot.pos, - "Non JS-native classes, traits and objects should not have an " + - "@JSName annotation, as it does not have any effect. " + - "This will be enforced in 1.0.") - } else if (annot.symbol == JSGlobalAnnotation) { - reporter.error(annot.pos, - "Non JS-native classes, traits and objects may not have an " + - "@JSGlobal annotation.") - } else if (annot.symbol == JSImportAnnotation) { - reporter.error(annot.pos, - "Non JS-native classes, traits and objects may not have an " + - "@JSImport annotation.") - } else if (annot.symbol == JSGlobalScopeAnnotation) { - reporter.error(annot.pos, - "Only native JS objects can have an @JSGlobalScope annotation " + - "(or extend js.GlobalScope).") - } - } - } - - /** Checks that argument to @JSName on [[member]] is a literal. - * Reports an error on each annotation where this is not the case. - */ - private def checkJSNameArgument(member: MemberDef): Unit = { - for (annot <- member.symbol.getAnnotation(JSNameAnnotation)) { - val argTree = annot.args.head - if (argTree.tpe.typeSymbol == StringClass) { - if (!argTree.isInstanceOf[Literal]) { - reporter.error(argTree.pos, - "A string argument to JSName must be a literal string") - } - } else { - // We have a js.Symbol - val sym = argTree.symbol - if (!sym.isStatic || !sym.isStable) { - reporter.error(argTree.pos, - "A js.Symbol argument to JSName must be a static, stable identifier") - } else if ((enclosingOwner is OwnerKind.JSNonNative) && - sym.owner == member.symbol.owner) { - reporter.warning(argTree.pos, - "This symbol is defined in the same object as the annotation's " + - "target. This will cause a stackoverflow at runtime") - } - } - - } - } - - } - - def isJSAny(sym: Symbol): Boolean = - sym.tpe.typeSymbol isSubClass JSAnyClass - - /** Checks that a setter has the right signature. - * - * Reports error messages otherwise. - */ - def checkSetterSignature(sym: Symbol, pos: Position, exported: Boolean): Unit = { - val typeStr = if (exported) "Exported" else "Raw JS" - - // Forbid setters with non-unit return type - if (sym.tpe.resultType.typeSymbol != UnitClass) { - reporter.error(pos, s"$typeStr setters must return Unit") - } - - // Forbid setters with more than one argument - sym.tpe.paramss match { - case List(List(arg)) => - // Arg list is OK. Do additional checks. - if (isScalaRepeatedParamType(arg.tpe)) - reporter.error(pos, s"$typeStr setters may not have repeated params") - - if (arg.hasFlag(reflect.internal.Flags.DEFAULTPARAM)) { - val msg = s"$typeStr setters may not have default params" - if (exported) - reporter.warning(pos, msg + ". This will be enforced in 1.0.") - else - reporter.error(pos, msg) - } - - case _ => - reporter.error(pos, s"$typeStr setters must have exactly one argument") - } - } - - private def isJSAny(implDef: ImplDef): Boolean = isJSAny(implDef.symbol) - - private def isJSLambda(sym: Symbol) = sym.isAnonymousClass && - AllJSFunctionClasses.exists(sym.tpe.typeSymbol isSubClass _) - - private def isScalaEnum(implDef: ImplDef) = - implDef.symbol.tpe.typeSymbol isSubClass ScalaEnumClass - - private def isJSDynamic(tree: Tree) = tree.tpe.typeSymbol == JSDynamicClass - - /** Tests whether the symbol has `private` in any form, either `private`, - * `private[this]` or `private[Enclosing]`. - */ - def isPrivateMaybeWithin(sym: Symbol): Boolean = - sym.isPrivate || (sym.hasAccessBoundary && !sym.isProtected) - - /** Checks that the optional argument to `@JSGlobal` on [[sym]] is a literal. - * - * Reports an error on each annotation where this is not the case. - */ - private def checkJSGlobalLiteral(sym: Symbol): Unit = { - for { - annot <- sym.getAnnotation(JSGlobalAnnotation) - if annot.args.nonEmpty - } { - assert(annot.args.size == 1, - s"@JSGlobal annotation $annot has more than 1 argument") - - val argIsValid = annot.stringArg(0).isDefined - if (!argIsValid) { - reporter.error(annot.args.head.pos, - "The argument to @JSGlobal must be a literal string.") - } - } - } - - /** Checks that arguments to `@JSImport` on [[sym]] are literals. - * - * The second argument can also be the singleton `JSImport.Namespace` - * object. - * - * Reports an error on each annotation where this is not the case. - */ - private def checkJSImportLiteral(sym: Symbol): Unit = { - for { - annot <- sym.getAnnotation(JSImportAnnotation) - } { - assert(annot.args.size == 2 || annot.args.size == 3, - s"@JSImport annotation $annot does not have exactly 2 or 3 arguments") - - val firstArgIsValid = annot.stringArg(0).isDefined - if (!firstArgIsValid) { - reporter.error(annot.args.head.pos, - "The first argument to @JSImport must be a literal string.") - } - - val secondArgIsValid = { - annot.stringArg(1).isDefined || - annot.args(1).symbol == JSImportNamespaceObject - } - if (!secondArgIsValid) { - reporter.error(annot.args(1).pos, - "The second argument to @JSImport must be literal string or the " + - "JSImport.Namespace object.") - } - - val thirdArgIsValid = annot.args.size < 3 || annot.stringArg(2).isDefined - if (!thirdArgIsValid) { - reporter.error(annot.args(2).pos, - "The third argument to @JSImport, when present, must be a " + - "literal string.") - } - } - } - - private abstract class ScalaEnumFctExtractors(methSym: Symbol) { - private def resolve(ptpes: Symbol*) = { - val res = methSym suchThat { - _.tpe.params.map(_.tpe.typeSymbol) == ptpes.toList - } - assert(res != NoSymbol, s"no overload of $methSym for param types $ptpes") - res - } - - private val noArg = resolve() - private val nameArg = resolve(StringClass) - private val intArg = resolve(IntClass) - private val fullMeth = resolve(IntClass, StringClass) - - /** - * Extractor object for calls to the targeted symbol that do not have an - * explicit name in the parameters - * - * Extracts: - * - `sel: Select` where sel.symbol is targeted symbol (no arg) - * - Apply(meth, List(param)) where meth.symbol is targeted symbol (i: Int) - */ - object NoName { - def unapply(t: Tree): Option[Option[Tree]] = t match { - case sel: Select if sel.symbol == noArg => - Some(None) - case Apply(meth, List(param)) if meth.symbol == intArg => - Some(Some(param)) - case _ => - None - } - } - - object NullName { - def unapply(tree: Tree): Boolean = tree match { - case Apply(meth, List(Literal(Constant(null)))) => - meth.symbol == nameArg - case Apply(meth, List(_, Literal(Constant(null)))) => - meth.symbol == fullMeth - case _ => false - } - } - - } - - private object ScalaEnumValue - extends ScalaEnumFctExtractors(getMemberMethod(ScalaEnumClass, jsnme.Value)) - - private object ScalaEnumVal - extends ScalaEnumFctExtractors(getMemberClass(ScalaEnumClass, jsnme.Val).tpe.member(nme.CONSTRUCTOR)) - - /** - * Construct a call to Enumeration.Value - * @param thisSym ClassSymbol of enclosing class - * @param nameOrig Symbol of ValDef where this call will be placed - * (determines the string passed to Value) - * @param intParam Optional tree with Int passed to Value - * @return Typed tree with appropriate call to Value - */ - private def ScalaEnumValName( - thisSym: Symbol, - nameOrig: Symbol, - intParam: Option[Tree]) = { - - val defaultName = nameOrig.asTerm.getterName.encoded - - - // Construct the following tree - // - // if (nextName != null && nextName.hasNext) - // nextName.next() - // else - // - // - val nextNameTree = Select(This(thisSym), jsnme.nextName) - val nullCompTree = - Apply(Select(nextNameTree, nme.NE), Literal(Constant(null)) :: Nil) - val hasNextTree = Select(nextNameTree, jsnme.hasNext) - val condTree = Apply(Select(nullCompTree, nme.ZAND), hasNextTree :: Nil) - val nameTree = If(condTree, - Apply(Select(nextNameTree, jsnme.next), Nil), - Literal(Constant(defaultName))) - val params = intParam.toList :+ nameTree - - typer.typed { - Apply(Select(This(thisSym), jsnme.Value), params) - } - } - - private def checkAndGetJSNativeLoadingSpecAnnotOf( - sym: Symbol): Option[Annotation] = { - val annots = sym.annotations.filter { annot => - JSNativeLoadingSpecAnnots.contains(annot.symbol) - } - - annots match { - case Nil => - None - - case result :: duplicates => - val actualResult = { - if (result.args.headOption.forall(_.tpe.typeSymbol == StringClass)) { - Some(result) - } else { - reporter.error(result.pos, - "@JSName with a js.Symbol can only be used on members of " + - "JavaScript types") - None - } - } - - for (annot <- duplicates) { - if (annot.symbol == JSNameAnnotation && - result.symbol == JSNameAnnotation) { - // This used not to be checked, so we can only warn - reporter.warning(annot.pos, - "A duplicate @JSName annotation is ignored, and should be " + - "removed. This will be enforced in 1.0.") - } else if (annot.symbol == JSNameAnnotation && - result.symbol == JSGlobalScopeAnnotation) { - /* This used not to be checked for `extends js.GlobalScope`, so we - * can only warn. See the comment where we deal with the legacy - * `extends js.GlobalScope` for the reason why we do not need to - * deal with the converse case (i.e., `@JSGlobalScope` always comes - * before `@JSName` in this case. - */ - reporter.warning(annot.pos, - "An @JSName annotation is ignored in the presence of " + - "@JSGlobalScope (or extends js.GlobalScope), and should be " + - "removed. This will be enforced in 1.0.") - } else { - reporter.error(annot.pos, - "Native JS classes and objects can only have one annotation " + - "among JSName, JSGlobal, JSImport and JSGlobalScope " + - "(extending js.GlobalScope is treated as having " + - "@JSGlobalScope).") - } - } - - actualResult - } - } - - private lazy val JSNativeLoadingSpecAnnots: Set[Symbol] = { - Set(JSNameAnnotation, JSGlobalAnnotation, JSImportAnnotation, - JSGlobalScopeAnnotation) - } - - private lazy val ScalaEnumClass = getRequiredClass("scala.Enumeration") - private lazy val WasPublicBeforeTyperClass = - getRequiredClass("scala.scalajs.js.annotation.WasPublicBeforeTyper") - - /** checks if the primary constructor of the ClassDef `cldef` does not - * take any arguments - */ - private def primCtorNoArg(cldef: ClassDef) = - getPrimCtor(cldef.symbol.tpe).forall(_.paramss == List(List())) - - /** return the MethodSymbol of the primary constructor of the given type - * if it exists - */ - private def getPrimCtor(tpe: Type) = - tpe.declaration(nme.CONSTRUCTOR).alternatives.collectFirst { - case ctor: MethodSymbol if ctor.isPrimaryConstructor => ctor - } - - private def shouldModuleBeExposed(sym: Symbol) = { - assert(sym.isModuleOrModuleClass, sym) - !sym.isLocalToBlock && !sym.isSynthetic && !isPrivateMaybeWithin(sym) - } - - protected def isScalaJSDefinedAcrossRuns(sym: Symbol): Boolean = { - val sjsDefinedByDefaultAppliesToSym = { - scalaJSOpts.sjsDefinedByDefault && - (sym.sourceFile ne null) // it is compiled from source, i.e., not loaded from .class - } - if (sjsDefinedByDefaultAppliesToSym) - !sym.hasAnnotation(JSNativeAnnotation) - else - sym.hasAnnotation(ScalaJSDefinedAnnotation) - } - - private def wasPublicBeforeTyper(sym: Symbol): Boolean = - sym.hasAnnotation(WasPublicBeforeTyperClass) - - private def fixPublicBeforeTyper(ddef: DefDef): DefDef = { - // This method assumes that isJSAny(ddef.symbol.owner) is true - val sym = ddef.symbol - val needsFix = { - sym.isPrivate && - (wasPublicBeforeTyper(sym) || - (sym.isAccessor && wasPublicBeforeTyper(sym.accessed))) - } - if (needsFix) { - sym.resetFlag(Flag.PRIVATE) - treeCopy.DefDef(ddef, ddef.mods &~ Flag.PRIVATE, ddef.name, ddef.tparams, - ddef.vparamss, ddef.tpt, ddef.rhs) - } else { - ddef - } - } - - private def checkInternalAnnotations(tree: Tree): Unit = { - /** Returns true iff it is a compiler annotations. This does not include - * annotations inserted before the typer (such as `@WasPublicBeforeTyper`). - */ - def isCompilerAnnotation(annotation: AnnotationInfo): Boolean = { - annotation.symbol == ExposedJSMemberAnnot || - annotation.symbol == JSFullNameAnnotation || - annotation.symbol == RawJSTypeAnnot || - annotation.symbol == SJSDefinedAnonymousClassAnnotation || - annotation.symbol == JSOptionalAnnotation - } - - if (tree.isInstanceOf[MemberDef]) { - for (annotation <- tree.symbol.annotations) { - if (isCompilerAnnotation(annotation)) { - reporter.error(annotation.pos, - s"$annotation is for compiler internal use only. " + - "Do not use it yourself.") - } - } - } - } -} - -object PrepJSInterop { - private final class OwnerKind(val baseKinds: Int) extends AnyVal { - import OwnerKind._ - - @inline def isBaseKind: Boolean = - Integer.lowestOneBit(baseKinds) == baseKinds && baseKinds != 0 // exactly 1 bit on - - @inline def |(that: OwnerKind): OwnerKind = - new OwnerKind(this.baseKinds | that.baseKinds) - - @inline def is(that: OwnerKind): Boolean = - (this.baseKinds & that.baseKinds) != 0 - - @inline def isnt(that: OwnerKind): Boolean = - !this.is(that) - } - - private object OwnerKind { - /** No owner, i.e., we are at the top-level. */ - val None = new OwnerKind(0x00) - - // Base kinds - those form a partition of all possible enclosing owners - - /** A Scala class/trait that does not extend Enumeration. */ - val NonEnumScalaClass = new OwnerKind(0x01) - /** A Scala object that does not extend Enumeration. */ - val NonEnumScalaMod = new OwnerKind(0x02) - /** A native JS class/trait, which extends js.Any. */ - val JSNativeClass = new OwnerKind(0x04) - /** A native JS object, which extends js.Any. */ - val JSNativeMod = new OwnerKind(0x08) - /** A Scala.js-defined JS class/trait. */ - val JSClass = new OwnerKind(0x10) - /** A Scala.js-defined JS oobject. */ - val JSMod = new OwnerKind(0x20) - /** A Scala class/trait that extends Enumeration. */ - val EnumClass = new OwnerKind(0x40) - /** A Scala object that extends Enumeration. */ - val EnumMod = new OwnerKind(0x80) - /** The Enumeration class itself. */ - val EnumImpl = new OwnerKind(0x100) - - // Compound kinds - - /** A Scala class/trait, possibly Enumeration-related. */ - val ScalaClass = NonEnumScalaClass | EnumClass | EnumImpl - /** A Scala object, possibly Enumeration-related. */ - val ScalaMod = NonEnumScalaMod | EnumMod - /** A Scala class, trait or object, i.e., anything not extending js.Any. */ - val ScalaThing = ScalaClass | ScalaMod - - /** A Scala class/trait/object extending Enumeration, but not Enumeration itself. */ - val Enum = EnumClass | EnumMod - - /** A native JS class/trait/object. */ - val JSNative = JSNativeClass | JSNativeMod - /** A non-native JS class/trait/object. */ - val JSNonNative = JSClass | JSMod - /** A raw JS type, i.e., something extending js.Any. */ - val RawJSType = JSNative | JSNonNative - - /** Anything defined in Scala.js, i.e., anything but a native JS declaration. */ - val ScalaJSDefined = ScalaThing | JSNonNative - /** Any kind of class/trait, i.e., a Scala or raw JS class/trait. */ - val AnyClass = ScalaClass | JSNativeClass | JSClass - } -} diff --git a/compiler/src/main/scala/org/scalajs/core/compiler/ScalaJSOptions.scala b/compiler/src/main/scala/org/scalajs/core/compiler/ScalaJSOptions.scala deleted file mode 100644 index 3412c4566d..0000000000 --- a/compiler/src/main/scala/org/scalajs/core/compiler/ScalaJSOptions.scala +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler - -import java.net.URI - -/** This trait allows to query all options to the ScalaJS plugin - * - * Also see the help text in ScalaJSPlugin for information about particular - * options. - */ -trait ScalaJSOptions { - import ScalaJSOptions.URIMap - - /** should calls to Predef.classOf[T] be fixed in the jsinterop phase. - * If false, bad calls to classOf will cause an error. */ - def fixClassOf: Boolean - - /** Should we suppress deprecations of exports coming from 0.6.15? */ - def suppressExportDeprecations: Boolean - - /** Should we suppress deprecations related to missing `@JSGlobal`? */ - def suppressMissingJSGlobalDeprecations: Boolean - - /** which source locations in source maps should be relativized (or where - * should they be mapped to)? */ - def sourceURIMaps: List[URIMap] - - /** Switch the default for JS types from `@js.native` to `@ScalaJSDefined`. - * This is intended as a transition option between 0.6.x and 1.x. - */ - def sjsDefinedByDefault: Boolean - -} - -object ScalaJSOptions { - case class URIMap(from: URI, to: Option[URI]) -} diff --git a/compiler/src/main/scala/org/scalajs/core/compiler/TypeKinds.scala b/compiler/src/main/scala/org/scalajs/core/compiler/TypeKinds.scala deleted file mode 100644 index 4904f6fd94..0000000000 --- a/compiler/src/main/scala/org/scalajs/core/compiler/TypeKinds.scala +++ /dev/null @@ -1,261 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler - -import scala.tools.nsc._ - -import org.scalajs.core.ir -import ir.{Definitions, Types} - -/** Glue representation of types as seen from the IR but still with a - * reference to the Symbols. - * - * @author Sébastien Doeraene - */ -trait TypeKinds[G <: Global with Singleton] extends SubComponent { - this: GenJSCode[G] => - - import global._ - import jsAddons._ - import definitions._ - - lazy val ObjectReference = REFERENCE(definitions.ObjectClass) - - lazy val VoidKind = VOID - lazy val BooleanKind = BOOL - lazy val CharKind = INT(CharClass) - lazy val ByteKind = INT(ByteClass) - lazy val ShortKind = INT(ShortClass) - lazy val IntKind = INT(IntClass) - lazy val LongKind = LONG - lazy val FloatKind = FLOAT(FloatClass) - lazy val DoubleKind = FLOAT(DoubleClass) - - /** TypeKinds for Scala primitive types. */ - lazy val primitiveTypeMap: Map[Symbol, TypeKind] = { - import definitions._ - Map( - UnitClass -> VoidKind, - BooleanClass -> BooleanKind, - CharClass -> CharKind, - ByteClass -> ByteKind, - ShortClass -> ShortKind, - IntClass -> IntKind, - LongClass -> LongKind, - FloatClass -> FloatKind, - DoubleClass -> DoubleKind - ) - } - - /** Glue representation of types as seen from the IR but still with a - * reference to the Symbols. - */ - sealed abstract class TypeKind { - def isReferenceType: Boolean = false - def isArrayType: Boolean = false - def isValueType: Boolean = false - - def toIRType: Types.Type - def toReferenceType: Types.ReferenceType - } - - sealed abstract class TypeKindButArray extends TypeKind { - protected def typeSymbol: Symbol - - override def toReferenceType: Types.ClassType = - Types.ClassType(encodeClassFullName(typeSymbol)) - } - - /** The void, for trees that can only appear in statement position. */ - case object VOID extends TypeKindButArray { - protected def typeSymbol: Symbol = UnitClass - def toIRType: Types.NoType.type = Types.NoType - } - - sealed abstract class ValueTypeKind extends TypeKindButArray { - override def isValueType: Boolean = true - - val primitiveCharCode: Char = typeSymbol match { - case BooleanClass => 'Z' - case CharClass => 'C' - case ByteClass => 'B' - case ShortClass => 'S' - case IntClass => 'I' - case LongClass => 'J' - case FloatClass => 'F' - case DoubleClass => 'D' - case x => abort("Unknown primitive type: " + x.fullName) - } - } - - /** Integer number (Byte, Short, Char or Int). */ - case class INT private[TypeKinds] (typeSymbol: Symbol) extends ValueTypeKind { - def toIRType: Types.IntType.type = Types.IntType - } - - /** Long */ - case object LONG extends ValueTypeKind { - protected def typeSymbol = definitions.LongClass - def toIRType: Types.LongType.type = Types.LongType - } - - /** Floating-point number (Float or Double). */ - case class FLOAT private[TypeKinds] (typeSymbol: Symbol) extends ValueTypeKind { - def toIRType: Types.Type = - if (typeSymbol == FloatClass) Types.FloatType - else Types.DoubleType - } - - /** Boolean */ - case object BOOL extends ValueTypeKind { - protected def typeSymbol = definitions.BooleanClass - def toIRType: Types.BooleanType.type = Types.BooleanType - } - - /** Nothing */ - case object NOTHING extends TypeKindButArray { - protected def typeSymbol: Symbol = definitions.NothingClass - def toIRType: Types.NothingType.type = Types.NothingType - override def toReferenceType: Types.ClassType = - Types.ClassType(Definitions.RuntimeNothingClass) - } - - /** Null */ - case object NULL extends TypeKindButArray { - protected def typeSymbol: Symbol = definitions.NullClass - def toIRType: Types.NullType.type = Types.NullType - override def toReferenceType: Types.ClassType = - Types.ClassType(Definitions.RuntimeNullClass) - } - - /** An object */ - case class REFERENCE private[TypeKinds] (typeSymbol: Symbol) extends TypeKindButArray { - override def toString(): String = "REFERENCE(" + typeSymbol.fullName + ")" - override def isReferenceType: Boolean = true - - def toIRType: Types.Type = encodeClassType(typeSymbol) - } - - /** An array */ - case class ARRAY private[TypeKinds] (elem: TypeKind) extends TypeKind { - override def toString(): String = "ARRAY[" + elem + "]" - override def isArrayType: Boolean = true - - def dimensions: Int = elem match { - case a: ARRAY => a.dimensions + 1 - case _ => 1 - } - - override def toIRType: Types.ArrayType = toReferenceType - - override def toReferenceType: Types.ArrayType = { - Types.ArrayType( - elementKind.toReferenceType.className, - dimensions) - } - - /** The ultimate element type of this array. */ - def elementKind: TypeKindButArray = elem match { - case a: ARRAY => a.elementKind - case k: TypeKindButArray => k - } - } - - ////////////////// Conversions ////////////////////////////// - - def toIRType(t: Type): Types.Type = - toTypeKind(t).toIRType - - def toReferenceType(t: Type): Types.ReferenceType = - toTypeKind(t).toReferenceType - - // The following code is a hard copy-and-paste from backend.icode.TypeKinds - - /** Return the TypeKind of the given type - * - * Call to .normalize fixes #3003 (follow type aliases). Otherwise, - * arrayOrClassType below would return ObjectReference. - */ - def toTypeKind(t: Type): TypeKind = t.normalize match { - case ThisType(ArrayClass) => ObjectReference - case ThisType(sym) => newReference(sym) - case SingleType(_, sym) => primitiveOrRefType(sym) - case ConstantType(_) => toTypeKind(t.underlying) - case TypeRef(_, sym, args) => primitiveOrClassType(sym, args) - case ClassInfoType(_, _, ArrayClass) => abort("ClassInfoType to ArrayClass!") - case ClassInfoType(_, _, sym) => primitiveOrRefType(sym) - - // !!! Iulian says types which make no sense after erasure should not reach here, - // which includes the ExistentialType, AnnotatedType, RefinedType. I don't know - // if the first two cases exist because they do or as a defensive measure, but - // at the time I added it, RefinedTypes were indeed reaching here. - // !!! Removed in JavaScript backend because I do not know what to do with lub - //case ExistentialType(_, t) => toTypeKind(t) - // Apparently, this case does occur (see pos/CustomGlobal.scala) - case t: AnnotatedType => toTypeKind(t.underlying) - //case RefinedType(parents, _) => parents map toTypeKind reduceLeft lub - - /* This case is not in scalac. We need it for the test - * run/valueclasses-classtag-existential. I have no idea how icode does - * not fail this test: we do everything the same as icode up to here. - */ - case tpe: ErasedValueType => newReference(tpe.valueClazz) - - // For sure WildcardTypes shouldn't reach here either, but when - // debugging such situations this may come in handy. - // case WildcardType => REFERENCE(ObjectClass) - case norm => abort( - "Unknown type: %s, %s [%s, %s] TypeRef? %s".format( - t, norm, t.getClass, norm.getClass, t.isInstanceOf[TypeRef] - ) - ) - } - - /** Return the type kind of a class, possibly an array type. - */ - private def arrayOrClassType(sym: Symbol, targs: List[Type]) = sym match { - case ArrayClass => ARRAY(toTypeKind(targs.head)) - case _ if sym.isClass => newReference(sym) - case _ => - assert(sym.isType, sym) // it must be compiling Array[a] - ObjectReference - } - - /** Interfaces have to be handled delicately to avoid introducing - * spurious errors, but if we treat them all as AnyRef we lose too - * much information. - */ - private def newReference(sym: Symbol): TypeKind = sym match { - case NothingClass => NOTHING - case NullClass => NULL - case _ => - // Can't call .toInterface (at this phase) or we trip an assertion. - // See PackratParser#grow for a method which fails with an apparent mismatch - // between "object PackratParsers$class" and "trait PackratParsers" - if (isImplClass(sym)) { - // pos/spec-List.scala is the sole failure if we don't check for NoSymbol - val traitSym = sym.owner.info.decl(tpnme.interfaceName(sym.name)) - if (traitSym != NoSymbol) - REFERENCE(traitSym) - else - REFERENCE(sym) - } else { - REFERENCE(sym) - } - } - - private def primitiveOrRefType(sym: Symbol) = - primitiveTypeMap.getOrElse(sym, newReference(sym)) - private def primitiveOrClassType(sym: Symbol, targs: List[Type]) = - primitiveTypeMap.getOrElse(sym, arrayOrClassType(sym, targs)) -} diff --git a/compiler/src/main/scala/org/scalajs/nscplugin/CompatComponent.scala b/compiler/src/main/scala/org/scalajs/nscplugin/CompatComponent.scala new file mode 100644 index 0000000000..ec59a07718 --- /dev/null +++ b/compiler/src/main/scala/org/scalajs/nscplugin/CompatComponent.scala @@ -0,0 +1,163 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin + +import scala.collection.mutable + +import scala.reflect.internal.Flags +import scala.tools.nsc._ + +/** Hacks to have our source code compatible with the compiler internals of all + * the versions of Scala that we support. + * + * In general, it tries to provide the newer APIs on top of older APIs. + * + * @author Sébastien Doeraene + */ +trait CompatComponent { + import CompatComponent.{infiniteLoop, noImplClasses} + + val global: Global + + import global._ + + implicit final class SymbolCompat(self: Symbol) { + def originalOwner: Symbol = + global.originalOwner.getOrElse(self, self.rawowner) + + def implClass: Symbol = NoSymbol + + def isTraitOrInterface: Boolean = self.isTrait || self.isInterface + + def isScala3Defined: Boolean = false + } + + implicit final class GlobalCompat( + self: CompatComponent.this.global.type) { + + object originalOwner { + def getOrElse(sym: Symbol, orElse: => Symbol): Symbol = infiniteLoop() + } + + // Added in Scala 2.13.2 for configurable warnings + object runReporting { + def warning(pos: Position, msg: String, cat: Any, site: Symbol): Unit = + reporter.warning(pos, msg) + } + } + + implicit final class TyperCompat(self: analyzer.Typer) { + // Added in Scala 2.13.5 to make it clearer what is allowed since 2.13.4 + def checkClassOrModuleType(tpt: Tree): Boolean = + self.checkClassType(tpt) + + def checkClassType(tpt: Tree): Boolean = + infiniteLoop() + } + + private implicit final class FlagsCompat(self: Flags.type) { + def IMPLCLASS: Long = infiniteLoop() + } + + lazy val scalaUsesImplClasses: Boolean = + definitions.SeqClass.implClass != NoSymbol // a trait we know has an impl class + + def isImplClass(sym: Symbol): Boolean = + scalaUsesImplClasses && sym.hasFlag(Flags.IMPLCLASS) + + lazy val isScala211: Boolean = scalaUsesImplClasses + + implicit final class StdTermNamesCompat(self: global.nme.type) { + def IMPL_CLASS_SUFFIX: String = noImplClasses() + + def isImplClassName(name: Name): Boolean = false + } + + implicit final class StdTypeNamesCompat(self: global.tpnme.type) { + def IMPL_CLASS_SUFFIX: String = noImplClasses() + + def interfaceName(implname: Name): TypeName = noImplClasses() + } + + /* SAMFunction was introduced in 2.12 for LMF-capable SAM types. + * DottyEnumSingleton was introduced in 2.13.6 to identify Scala 3 `enum` singleton cases. + */ + + object AttachmentsCompatDef { + case class SAMFunction(samTp: Type, sam: Symbol, synthCls: Symbol) + extends PlainAttachment + + object DottyEnumSingleton extends PlainAttachment + } + + object AttachmentsCompat { + import AttachmentsCompatDef._ + + object Inner { + import global._ + + type SAMFunctionAlias = SAMFunction + val SAMFunctionAlias = SAMFunction + + val DottyEnumSingletonAlias = DottyEnumSingleton + } + } + + type SAMFunctionCompat = AttachmentsCompat.Inner.SAMFunctionAlias + lazy val SAMFunctionCompat = AttachmentsCompat.Inner.SAMFunctionAlias + + lazy val DottyEnumSingletonCompat = AttachmentsCompat.Inner.DottyEnumSingletonAlias + + implicit final class SAMFunctionCompatOps(self: SAMFunctionCompat) { + // Introduced in 2.12.5 to synthesize bridges in LMF classes + def synthCls: Symbol = NoSymbol + } + + /* global.genBCode.bTypes.initializeCoreBTypes() + * Early 2.12.x versions require that this method be called from + * GenJSCode.run(), but it disappeared later in the 2.12.x series. + */ + + implicit class BTypesCompat(bTypes: genBCode.bTypes.type) { + def initializeCoreBTypes(): Unit = () + } + + // WarningCategory was added in Scala 2.13.2 for configurable warnings + + object WarningCategoryCompat { + object Reporting { + object WarningCategory { + val Deprecation: Any = null + val Other: Any = null + } + } + } + + // Of type Reporting.WarningCategory.type, but we cannot explicit write it + val WarningCategory = { + import WarningCategoryCompat._ + + { + import scala.tools.nsc._ + Reporting.WarningCategory + } + } +} + +object CompatComponent { + private def infiniteLoop(): Nothing = + throw new AssertionError("Infinite loop in Compat") + + private def noImplClasses(): Nothing = + throw new AssertionError("No impl classes in this version") +} diff --git a/compiler/src/main/scala/org/scalajs/nscplugin/ExplicitInnerJS.scala b/compiler/src/main/scala/org/scalajs/nscplugin/ExplicitInnerJS.scala new file mode 100644 index 0000000000..4e0e4855c8 --- /dev/null +++ b/compiler/src/main/scala/org/scalajs/nscplugin/ExplicitInnerJS.scala @@ -0,0 +1,321 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin + +import scala.reflect.internal.Flags + +import scala.tools.nsc +import nsc._ +import nsc.transform.{InfoTransform, TypingTransformers} + +import scala.collection.immutable.ListMap +import scala.collection.mutable + +/** Makes the references to inner JS class values explicit. + * + * Roughly, for every inner JS class of the form: + * {{{ + * class Outer { + * class Inner extends ParentJSClass + * } + * }}} + * this phase creates a field `Inner\$jsclass` in `Outer` to hold the JS class + * value for `Inner`. The rhs of that field is a call to a magic method, used + * to retain information that the back-end will need. + * {{{ + * class Outer { + * val Inner\$jsclass: AnyRef = + * createJSClass(classOf[Inner], js.constructorOf[ParentJSClass]) + * + * class Inner extends ParentJSClass + * } + * }}} + * + * These fields will be read by code generated in `ExplicitLocalJS`. + * + * A `\$jsclass` field is also generated for classes declared inside *static + * JS objects*. Indeed, even though those classes have a unique, globally + * accessible class value, that class value needs to be *exposed* as a field + * of the enclosing object. In those cases, the rhs of the field is a direct + * call to `runtime.constructorOf[classOf[Inner]]`. + * + * Finally, for *modules* declared inside static JS objects, we generate an + * explicit exposed getter as well. For non-static objects, scalac already + * generates a getter with the `@ExposedJSMember` annotation, so we do not + * need to do anything. But for static objects, it doesn't, so we have to do + * it ourselves here. + * + * To illustrate the two above paragraphs, for the following input: + * {{{ + * object Outer extends js.Object { + * class InnerClass extends ParentJSClass + * object InnerObject extends SomeOtherJSClass + * } + * }}} + * this phase will generate + * {{{ + * object Outer extends js.Object { + * ... + * + * @ExposedJSMember @JSName("InnerClass") + * val InnerClass\$jsclass: AnyRef = runtime.constructorOf(classOf[InnerClass]) + * + * @ExposedJSMember @JSName("InnerObject") + * def InnerObject\$jsobject: AnyRef = InnerObject + * } + * }}} + * + * Note that this field must also be added to outer classes and traits coming + * from separate compilation, therefore this phase is an `InfoTransform`. + * Since the `transformInfo` also applies to classes defined in the current + * compilation unit, the tree traversal must not create the field symbols a + * second time when synthesizing the `ValDef`. Instead, it must reuse the same + * symbols that `transformInfo` will create. + * + * It seems the easiest way to do that is to run the entire `transform` "in + * the future", with `exitingPhase(ExplicitInnerJS)`. This design is similar + * to how `explicitouter` works. + */ +abstract class ExplicitInnerJS[G <: Global with Singleton](val global: G) + extends plugins.PluginComponent with InfoTransform with TypingTransformers + with CompatComponent { + + val jsAddons: JSGlobalAddons { + val global: ExplicitInnerJS.this.global.type + } + + import global._ + import jsAddons._ + import jsInterop.jsclassAccessorFor + import definitions._ + import rootMirror._ + import jsDefinitions._ + + /* The missing 'e' is intentional so that the name of the phase is not longer + * than the longest standard phase (packageobjects/superaccessors). This + * avoids destroying the nice formatting of `-Xshow-phases`. + */ + val phaseName: String = "xplicitinnerjs" + + override def description: String = + "make references to inner JS classes explicit" + + /** This class does not change linearization. */ + override protected def changesBaseClasses: Boolean = false + + /** Whether vals in traits are represented by their getter. + * This is true in 2.12+, since the addition of the `fields` phase. + * @see https://github.com/scala/scala/pull/5141 + */ + private lazy val traitValsHoldTheirGetterSymbol = + !scala.util.Properties.versionNumberString.startsWith("2.11.") + + protected def newTransformer(unit: CompilationUnit): Transformer = + new ExplicitInnerJSTransformer(unit) + + /** Is the given symbol an owner for which this transformation applies? + * + * This applies if either or both of the following are true: + * - It is not a static owner, or + * - It is a non-native JS object. + * + * The latter is necessary for #4086. + */ + private def isApplicableOwner(sym: Symbol): Boolean = { + !sym.isStaticOwner || ( + sym.isModuleClass && + sym.hasAnnotation(JSTypeAnnot) && + !sym.hasAnnotation(JSNativeAnnotation) + ) + } + + /** Is the given symbol a JS class (that is not a trait nor an object)? */ + private def isJSClass(sym: Symbol): Boolean = { + sym.isClass && + !sym.hasFlag(Flags.TRAIT | Flags.MODULE) && + sym.hasAnnotation(JSTypeAnnot) + } + + /** Is the given symbol a Module that should be exposed? */ + private def isExposedModule(sym: Symbol): Boolean = + sym.isModule && sym.hasAnnotation(ExposedJSMemberAnnot) + + private def jsobjectGetterNameFor(moduleSym: Symbol): TermName = + moduleSym.name.append("$jsobject").toTermName + + /** Transforms the info of types to add the `Inner\$jsclass` fields. + * + * This method was inspired by `ExplicitOuter.transformInfo`. + */ + def transformInfo(sym: Symbol, tp: Type): Type = tp match { + case ClassInfoType(parents, decls, clazz) if !clazz.isJava && isApplicableOwner(clazz) => + val innerJSClasses = decls.filter(isJSClass) + + val innerObjectsForAdHocExposed = + if (!clazz.isStaticOwner) Nil // those receive a module accessor from scalac + else decls.filter(isExposedModule).toList + + if (innerJSClasses.isEmpty && innerObjectsForAdHocExposed.isEmpty) { + tp + } else { + def addAnnots(sym: Symbol, symForName: Symbol): Unit = { + symForName.getAnnotation(JSNameAnnotation).fold { + sym.addAnnotation(JSNameAnnotation, + Literal(Constant(jsInterop.defaultJSNameOf(symForName)))) + } { annot => + sym.addAnnotation(annot) + } + sym.addAnnotation(ExposedJSMemberAnnot) + } + + val clazzIsJSClass = clazz.hasAnnotation(JSTypeAnnot) + + val decls1 = decls.cloneScope + + for (innerJSClass <- innerJSClasses) { + def addAnnotsIfInJSClass(sym: Symbol): Unit = { + if (clazzIsJSClass) + addAnnots(sym, innerJSClass) + } + + val accessorName: TermName = + innerJSClass.name.append("$jsclass").toTermName + val accessorFlags = + Flags.SYNTHETIC | Flags.ARTIFACT | Flags.STABLE | Flags.ACCESSOR + val accessor = + clazz.newMethod(accessorName, innerJSClass.pos, accessorFlags) + accessor.setInfo(NullaryMethodType(AnyRefTpe)) + addAnnotsIfInJSClass(accessor) + decls1.enter(accessor) + + if (!clazz.isTrait || !traitValsHoldTheirGetterSymbol) { + val fieldName = accessorName.append(nme.LOCAL_SUFFIX_STRING) + val fieldFlags = + Flags.SYNTHETIC | Flags.ARTIFACT | Flags.PrivateLocal + val field = clazz + .newValue(fieldName, innerJSClass.pos, fieldFlags) + .setInfo(AnyRefTpe) + addAnnotsIfInJSClass(field) + decls1.enter(field) + } + } + + // #4086 Create exposed getters for exposed objects in static JS objects + for (innerObject <- innerObjectsForAdHocExposed) { + assert(clazzIsJSClass && clazz.isModuleClass && clazz.isStatic, + s"trying to ad-hoc expose objects in non-JS static object") + + val getterName = jsobjectGetterNameFor(innerObject) + val getterFlags = Flags.SYNTHETIC | Flags.ARTIFACT | Flags.STABLE + val getter = clazz.newMethod(getterName, innerObject.pos, getterFlags) + getter.setInfo(NullaryMethodType(AnyRefTpe)) + addAnnots(getter, innerObject) + decls1.enter(getter) + } + + ClassInfoType(parents, decls1, clazz) + } + + case PolyType(tparams, restp) => + val restp1 = transformInfo(sym, restp) + if (restp eq restp1) tp else PolyType(tparams, restp1) + + case _ => + tp + } + + class ExplicitInnerJSTransformer(unit: CompilationUnit) + extends TypingTransformer(unit) { + + /** Execute the whole transformation in the future, exiting this phase. */ + override def transformUnit(unit: CompilationUnit): Unit = { + global.exitingPhase(currentRun.phaseNamed(phaseName)) { + super.transformUnit(unit) + } + } + + /** The main transformation method. */ + override def transform(tree: Tree): Tree = { + tree match { + // Add the ValDefs for inner JS class values + case Template(parents, self, decls) if isApplicableOwner(currentOwner) => + val newDecls = mutable.ListBuffer.empty[Tree] + atOwner(tree, currentOwner) { + for (decl <- decls) { + val declSym = decl.symbol + if (declSym eq null) { + // not a member def, do nothing + } else if (isJSClass(declSym)) { + val jsclassAccessor = jsclassAccessorFor(declSym) + + val rhs = if (currentOwner.hasAnnotation(JSNativeAnnotation)) { + gen.mkAttributedRef(JSPackage_native) + } else { + val clazzValue = gen.mkClassOf(declSym.tpe_*) + if (currentOwner.isStaticOwner) { + // #4086 + gen.mkMethodCall(Runtime_constructorOf, List(clazzValue)) + } else { + val parentTpe = + extractSuperTpeFromImpl(decl.asInstanceOf[ClassDef].impl) + val superClassCtor = gen.mkNullaryCall( + JSPackage_constructorOf, List(parentTpe)) + gen.mkMethodCall(Runtime_createInnerJSClass, + List(clazzValue, superClassCtor)) + } + } + + if (!currentOwner.isTrait || !traitValsHoldTheirGetterSymbol) { + val jsclassField = jsclassAccessor.accessed + assert(jsclassField != NoSymbol, jsclassAccessor.fullName) + newDecls += localTyper.typedValDef(ValDef(jsclassField, rhs)) + newDecls += localTyper.typed { + val rhs = Select(This(currentClass), jsclassField) + DefDef(jsclassAccessor, rhs) + } + } else { + newDecls += localTyper.typedValDef(ValDef(jsclassAccessor, rhs)) + } + } else if (currentOwner.isStaticOwner) { + // #4086 + val maybeModuleSym = + if (declSym.isModuleClass) declSym.module // Necessary for Scala 2.11 + else declSym + if (isExposedModule(maybeModuleSym)) { + val getter = + currentOwner.info.member(jsobjectGetterNameFor(maybeModuleSym)) + newDecls += localTyper.typedDefDef { + DefDef(getter, gen.mkAttributedRef(maybeModuleSym)) + } + } + } + + newDecls += decl + } + } + + val newTemplate = + treeCopy.Template(tree, parents, self, newDecls.result()) + super.transform(newTemplate) + + case _ => + // Taken from ExplicitOuter + val x = super.transform(tree) + if (x.tpe eq null) x + else x.setType(transformInfo(currentOwner, x.tpe)) + } + } + + } + +} diff --git a/compiler/src/main/scala/org/scalajs/nscplugin/ExplicitLocalJS.scala b/compiler/src/main/scala/org/scalajs/nscplugin/ExplicitLocalJS.scala new file mode 100644 index 0000000000..194ec08d8a --- /dev/null +++ b/compiler/src/main/scala/org/scalajs/nscplugin/ExplicitLocalJS.scala @@ -0,0 +1,418 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin + +import scala.reflect.internal.Flags + +import scala.tools.nsc +import nsc._ +import nsc.transform.{Transform, TypingTransformers} + +import scala.collection.immutable.ListMap +import scala.collection.mutable + +/** Makes the references to local JS classes explicit and desugars calls to + * `js.constructorOf`. + * + * It also makes explicit all references to inner JS classes, using the + * pointers created by `ExplicitInnerJS`, and otherwise makes sure the + * back-end will receive all the information it needs to translate inner- and + * local JS classes and objects. + * + * Note that in this comment, by "class" we mean *only* `class`es. `trait`s + * and `object`s are not implied. + * + * Similarly to how `ExplicitInnerJS` creates explicit fields in the enclosing + * templates of inner JS classes to hold the JS class values, this phase + * creates local vals for local JS classes in the enclosing statement list. + * + * For every local JS class of the form: + * {{{ + * def outer() = { + * class Local extends ParentJSClass + * } + * }}} + * this phase creates a local `val Local\$jslass` in the body of `outer()` to + * hold the JS class value for `Local`. The rhs of that val is a call to a + * magic method, used to retain information that the back-end will need: + * + * - A reified reference to `class Local`, in the form of a `classOf` + * - An explicit reference to the super JS class value, i.e., the desugaring + * of `js.constructorOf[ParentJSClass]` + * - An array of fake `new` expressions for all overloaded constructors. + * + * The latter will be augmented by `lambdalift` with the appropriate actual + * parameters for the captures of `Local`, which will be needed by the + * back-end. In code, this looks like: + * {{{ + * def outer() = { + * class Local extends ParentJSClass + * val Local\$jsclass: AnyRef = createLocalJSClass( + * classOf[Local], + * js.constructorOf[ParentJSClass], + * Array[AnyRef](new Local(), ...)) + * } + * }}} + * + * Since we need to insert fake `new Inner()`s, this scheme does not work for + * abstract local classes. We therefore reject them as implementation + * restriction. + * + * If the body of `Local` references itself, then the `val Local\$jsclass` is + * instead declared as a `var` to work around the cyclic dependency: + * {{{ + * def outer() = { + * var Local\$jsclass: AnyRef = null + * class Local extends ParentJSClass { + * ... + * } + * Local\$jsclass = createLocalJSClass(...) + * } + * }}} + * + * In addition to the above, `ExplicitLocalJS` transforms all *call sites* of + * local JS classes *and* inner JS classes, so that they refer to the + * synthesized local vals and fields. + * + * The primary transformation is the desugaring of `js.constructorOf[C]`, + * which depends on the nature of `C`: + * + * - If `C` is a statically accessible class, desugar to + * `runtime.constructorOf(classOf[C])` so that the reified symbol survives + * erasure and reaches the back-end. + * - If `C` is an inner JS class, it must be of the form `path.D` for some + * pair (`path`, `D`), and we desugar it to `path.D\$jsclass`, using the + * field created by `ExplicitInnerJS` (it is an error if `C` is of the form + * `Enclosing#D`). + * - If `C` is a local JS class, desugar to `C\$jsclass`, using the local val + * created by this phase. + * + * The other transformations build on top of the desugaring of + * `js.constructorOf[C]`, and apply only to inner JS classes and local JS + * classes (not for statically accessible classes): + * + * - `x.isInstanceOf[C]` desugars into + * `js.special.instanceof(x, js.constructorOf[C])`. + * - `new C(...args)` desugars into + * `withContextualJSClassValue(js.constructorOf[C], new C(...args))`, so + * that the back-end receives a reified reference to the JS class value. + * - In the same spirit, for `D extends C`, `D.super.m(...args)` desugars into + * `withContextualJSClassValue(js.constructorOf[C], D.super.m(...args))`. + * + * Finally, for inner- and local JS *objects*, their (only) instantiation + * point of the form `new O.type()` is rewritten as + * `withContextualJSClassValue(js.constructorOf[ParentClassOfO], new O.type())`, + * so that the back-end receives a reified reference to the parent class of + * `O`. A similar treatment is applied on anonymous JS classes, which + * basically define something very similar to an `object`, although without + * its own JS class. + */ +abstract class ExplicitLocalJS[G <: Global with Singleton](val global: G) + extends plugins.PluginComponent with Transform with TypingTransformers + with CompatComponent { + + val jsAddons: JSGlobalAddons { + val global: ExplicitLocalJS.this.global.type + } + + import global._ + import jsAddons._ + import jsInterop.{jsclassAccessorFor, JSCallingConvention} + import definitions._ + import rootMirror._ + import jsDefinitions._ + + /* The missing 'e' is intentional so that the name of the phase is not longer + * than the longest standard phase (packageobjects/superaccessors). This + * avoids destroying the nice formatting of `-Xshow-phases`. + */ + val phaseName: String = "xplicitlocaljs" + + override def description: String = + "make references to local JS classes explicit" + + protected def newTransformer(unit: CompilationUnit): Transformer = + new ExplicitLocalJSTransformer(unit) + + /** Is the gen clazz an inner or local JS class? */ + private def isInnerOrLocalJSClass(sym: Symbol): Boolean = + isInnerJSClass(sym) || isLocalJSClass(sym) + + /** Is the given clazz an inner JS class? */ + private def isInnerJSClass(clazz: Symbol): Boolean = + isInnerJSClassOrObject(clazz) && !clazz.isModuleClass + + /** Is the given clazz a local JS class? */ + private def isLocalJSClass(clazz: Symbol): Boolean = { + isLocalJSClassOrObject(clazz) && + !clazz.isModuleClass && !clazz.isAnonymousClass + } + + /** Is the gen clazz an inner or local JS class or object? */ + private def isInnerOrLocalJSClassOrObject(sym: Symbol): Boolean = + isInnerJSClassOrObject(sym) || isLocalJSClassOrObject(sym) + + /** Is the given clazz an inner JS class or object? */ + private def isInnerJSClassOrObject(clazz: Symbol): Boolean = { + clazz.hasAnnotation(JSTypeAnnot) && + !clazz.isPackageClass && !clazz.outerClass.isStaticOwner && + !clazz.isLocalToBlock && !clazz.isTrait + } + + /** Is the given clazz a local JS class or object? */ + private def isLocalJSClassOrObject(clazz: Symbol): Boolean = { + def isJSLambda: Boolean = { + // See GenJSCode.isJSFunctionDef + clazz.isAnonymousClass && + clazz.superClass == JSFunctionClass && + clazz.info.decl(nme.apply).filter(JSCallingConvention.isCall(_)).exists + } + + clazz.isLocalToBlock && + !clazz.isTrait && clazz.hasAnnotation(JSTypeAnnot) && + !isJSLambda + } + + class ExplicitLocalJSTransformer(unit: CompilationUnit) + extends TypingTransformer(unit) { + + private val nestedObject2superClassTpe = mutable.Map.empty[Symbol, Type] + private val localClass2jsclassVal = mutable.Map.empty[Symbol, TermSymbol] + private val notYetSelfReferencingLocalClasses = mutable.Set.empty[Symbol] + + override def transformUnit(unit: CompilationUnit): Unit = { + try { + super.transformUnit(unit) + } finally { + nestedObject2superClassTpe.clear() + localClass2jsclassVal.clear() + notYetSelfReferencingLocalClasses.clear() + } + } + + /** The main transformation method. */ + override def transform(tree: Tree): Tree = { + val sym = tree.symbol + tree match { + /* Populate `nestedObject2superClassTpe` for inner objects at the start + * of a `Template`, so that they are visible even before their + * definition (in their enclosing scope). + */ + case Template(_, _, decls) => + for (decl <- decls) { + decl match { + case ClassDef(_, _, _, impl) + if decl.symbol.isModuleClass && isInnerJSClassOrObject(decl.symbol) => + nestedObject2superClassTpe(decl.symbol) = + extractSuperTpeFromImpl(impl) + case _ => + } + } + super.transform(tree) + + // Create local `val`s for local JS classes + case Block(stats, expr) => + val newStats = mutable.ListBuffer.empty[Tree] + for (stat <- stats) { + stat match { + case ClassDef(mods, name, tparams, impl) if isLocalJSClass(stat.symbol) => + val clazz = stat.symbol + val jsclassVal = currentOwner + .newValue(unit.freshTermName(name.toString() + "$jsname"), stat.pos) + .setInfo(AnyRefTpe) + localClass2jsclassVal(clazz) = jsclassVal + notYetSelfReferencingLocalClasses += clazz + val newClassDef = transform(stat) + val rhs = { + val clazzValue = gen.mkClassOf(clazz.tpe_*) + val superClassCtor = + genJSConstructorOf(tree, extractSuperTpeFromImpl(impl)) + val fakeNewInstances = { + val elems = for { + ctor <- clazz.info.decl(nme.CONSTRUCTOR).alternatives + } yield { + assert(ctor.tpe.paramss.nonEmpty, + s"Constructor ${ctor.fullName} has no param list") + val argss = ctor.tpe.paramss.map { params => + List.fill(params.size)(gen.mkAttributedRef(Predef_???)) + } + argss.tail.foldLeft( + global.NewFromConstructor(ctor, argss.head: _*))( + Apply(_, _)) + } + typer.typed(ArrayValue(TypeTree(AnyRefTpe), elems)) + } + gen.mkMethodCall(Runtime_createLocalJSClass, + List(clazzValue, superClassCtor, fakeNewInstances)) + } + if (notYetSelfReferencingLocalClasses.remove(clazz)) { + newStats += newClassDef + newStats += localTyper.typedValDef { + ValDef(jsclassVal, rhs) + } + } else { + /* We are using `jsclassVal` inside the definition of the + * class. We need to declare it as var before and initialize + * it after the class definition. + */ + jsclassVal.setFlag(Flags.MUTABLE) + newStats += localTyper.typedValDef { + ValDef(jsclassVal, Literal(gen.mkConstantZero(AnyRefTpe))) + } + newStats += newClassDef + newStats += localTyper.typed { + Assign(Ident(jsclassVal), rhs) + } + } + + case ClassDef(_, _, _, impl) + if isLocalJSClassOrObject(stat.symbol) => + nestedObject2superClassTpe(stat.symbol) = + extractSuperTpeFromImpl(impl) + newStats += transform(stat) + + case _ => + newStats += transform(stat) + } + } + val newExpr = transform(expr) + treeCopy.Block(tree, newStats.toList, newExpr) + + /* Wrap `new`s to inner and local JS classes and objects with + * `withContextualJSClassValue`, to preserve a reified reference to + * the necessary JS class value (the class itself for classes, or the + * super class for objects). + * Anonymous classes are considered as "objects" for this purpose. + */ + case Apply(sel @ Select(New(tpt), nme.CONSTRUCTOR), args) + if isInnerOrLocalJSClassOrObject(sel.symbol.owner) => + val newCall = super.transform(tree) + val newTpt = transform(tpt) + val classSym = sel.symbol.owner + if (!classSym.isModuleClass && !classSym.isAnonymousClass) { + val jsclassValue = genJSConstructorOf(newTpt, newTpt.tpe) + wrapWithContextualJSClassValue(jsclassValue) { + newCall + } + } else { + wrapWithContextualJSClassValue(nestedObject2superClassTpe(classSym)) { + newCall + } + } + + /* Wrap `super` calls to inner and local JS classes with + * `withContextualJSClassValue`, to preserve a reified reference to the + * necessary JS class value (that of the super class). + */ + case Apply(fun @ Select(sup: Super, _), _) + if !fun.symbol.isConstructor && + isInnerOrLocalJSClass(sup.symbol.superClass) => + wrapWithContextualJSClassValue(sup.symbol.superClass.tpe_*) { + super.transform(tree) + } + + // Same for a super call with type parameters + case Apply(TypeApply(fun @ Select(sup: Super, _), _), _) + if !fun.symbol.isConstructor && + isInnerOrLocalJSClass(sup.symbol.superClass) => + wrapWithContextualJSClassValue(sup.symbol.superClass.tpe_*) { + super.transform(tree) + } + + // Translate js.constructorOf[T] + case Apply(TypeApply(ctorOfTree, List(tpeArg)), Nil) + if ctorOfTree.symbol == JSPackage_constructorOf => + val newTpeArg = transform(tpeArg) + gen.mkAttributedCast(genJSConstructorOf(tree, newTpeArg.tpe), + JSDynamicClass.tpe) + + // Translate x.isInstanceOf[T] for inner and local JS classes + case Apply(TypeApply(fun @ Select(obj, _), List(tpeArg)), Nil) + if fun.symbol == Any_isInstanceOf && + isInnerOrLocalJSClass(tpeArg.tpe.typeSymbol) => + val newObj = transform(obj) + val newTpeArg = transform(tpeArg) + val jsCtorOf = genJSConstructorOf(tree, newTpeArg.tpe) + atPos(tree.pos) { + localTyper.typed { + gen.mkMethodCall(Special_instanceof, List(newObj, jsCtorOf)) + } + } + + case _ => + super.transform(tree) + } + } + + /** Generates the desugared version of `js.constructorOf[tpe]`. + */ + private def genJSConstructorOf(tree: Tree, tpe: Type): Tree = { + val clazz = tpe.typeSymbol + + // This should not have passed the checks in PrepJSInterop + assert(!clazz.isTrait && !clazz.isModuleClass, + s"non-trait class type required but $tpe found for " + + s"genJSConstructorOf at ${tree.pos}") + + localTyper.typed { + atPos(tree.pos) { + if (isInnerJSClass(clazz)) { + // Use the $jsclass field in the outer instance + val prefix = tpe.prefix match { + case NoPrefix => clazz.outerClass.thisType + case x => x + } + if (prefix.isStable) { + val qual = gen.mkAttributedQualifier(prefix) + gen.mkAttributedSelect(qual, jsclassAccessorFor(clazz)) + } else { + reporter.error(tree.pos, + s"stable reference to a JS class required but $tpe found") + gen.mkAttributedRef(Predef_???) + } + } else if (isLocalJSClass(clazz)) { + // Use the local `val` that stores the JS class value + val jsclassVal = localClass2jsclassVal(clazz) + notYetSelfReferencingLocalClasses.remove(clazz) + gen.mkAttributedIdent(jsclassVal) + } else { + // Defer translation to `LoadJSConstructor` to the back-end + val classValue = gen.mkClassOf(tpe) + gen.mkMethodCall(Runtime_constructorOf, List(classValue)) + } + } + } + } + + private def wrapWithContextualJSClassValue(jsClassType: Type)( + tree: Tree): Tree = { + wrapWithContextualJSClassValue(genJSConstructorOf(tree, jsClassType)) { + tree + } + } + + private def wrapWithContextualJSClassValue(jsClassValue: Tree)( + tree: Tree): Tree = { + atPos(tree.pos) { + localTyper.typed { + gen.mkMethodCall( + Runtime_withContextualJSClassValue, + List(tree.tpe), + List(jsClassValue, tree)) + } + } + } + + } + +} diff --git a/compiler/src/main/scala/org/scalajs/nscplugin/GenJSCode.scala b/compiler/src/main/scala/org/scalajs/nscplugin/GenJSCode.scala new file mode 100644 index 0000000000..cd367f7d63 --- /dev/null +++ b/compiler/src/main/scala/org/scalajs/nscplugin/GenJSCode.scala @@ -0,0 +1,7111 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin + +import scala.language.implicitConversions + +import scala.annotation.switch + +import scala.collection.mutable +import scala.collection.mutable.ListBuffer + +import scala.tools.nsc._ + +import scala.annotation.tailrec + +import scala.reflect.internal.Flags + +import org.scalajs.ir +import org.scalajs.ir.{Trees => js, Types => jstpe, ClassKind, Hashers, OriginalName} +import org.scalajs.ir.Names.{LocalName, FieldName, SimpleMethodName, MethodName, ClassName} +import org.scalajs.ir.OriginalName.NoOriginalName +import org.scalajs.ir.Trees.OptimizerHints + +import org.scalajs.nscplugin.util.{ScopedVar, VarBox} +import ScopedVar.withScopedVars + +/** Generate JavaScript code and output it to disk + * + * @author Sébastien Doeraene + */ +abstract class GenJSCode[G <: Global with Singleton](val global: G) + extends plugins.PluginComponent with TypeConversions[G] with JSEncoding[G] + with GenJSExports[G] with GenJSFiles[G] with CompatComponent { + + import GenJSCode._ + + /** Not for use in the constructor body: only initialized afterwards. */ + val jsAddons: JSGlobalAddons { + val global: GenJSCode.this.global.type + } + + /** Not for use in the constructor body: only initialized afterwards. */ + val scalaJSOpts: ScalaJSOptions + + import global._ + import jsAddons._ + import rootMirror._ + import definitions._ + import jsDefinitions._ + import jsInterop.{jsNameOf, jsNativeLoadSpecOfOption, JSName, JSCallingConvention} + + import treeInfo.{hasSynthCaseSymbol, StripCast} + + import platform.isMaybeBoxed + + val phaseName: String = "jscode" + override val description: String = "generate JavaScript code from ASTs" + + /** testing: this will be called when ASTs are generated */ + def generatedJSAST(clDefs: List[js.ClassDef]): Unit + + /** Implicit conversion from nsc Position to ir.Position. */ + implicit def pos2irPos(pos: Position): ir.Position = { + if (pos == NoPosition) ir.Position.NoPosition + else { + val source = pos2irPosCache.toIRSource(pos.source) + // nsc positions are 1-based but IR positions are 0-based + ir.Position(source, pos.line-1, pos.column-1) + } + } + + private[this] object pos2irPosCache { + import scala.reflect.internal.util._ + + private[this] var lastNscSource: SourceFile = null + private[this] var lastIRSource: ir.Position.SourceFile = null + + def toIRSource(nscSource: SourceFile): ir.Position.SourceFile = { + if (nscSource != lastNscSource) { + lastIRSource = convert(nscSource) + lastNscSource = nscSource + } + lastIRSource + } + + private[this] def convert(nscSource: SourceFile): ir.Position.SourceFile = { + nscSource.file.file match { + case null => + new java.net.URI( + "virtualfile", // Pseudo-Scheme + nscSource.file.path, // Scheme specific part + null // Fragment + ) + case file => + val srcURI = file.toURI + def matches(pat: java.net.URI) = pat.relativize(srcURI) != srcURI + + scalaJSOpts.sourceURIMaps.collectFirst { + case ScalaJSOptions.URIMap(from, to) if matches(from) => + val relURI = from.relativize(srcURI) + to.fold(relURI)(_.resolve(relURI)) + } getOrElse srcURI + } + } + + def clear(): Unit = { + lastNscSource = null + lastIRSource = null + } + } + + /** Materialize implicitly an ir.Position from an implicit nsc Position. */ + implicit def implicitPos2irPos(implicit pos: Position): ir.Position = pos + + override def newPhase(p: Phase): StdPhase = new JSCodePhase(p) + + object jsnme { + val anyHash = newTermName("anyHash") + val arg_outer = newTermName("arg$outer") + } + + private sealed abstract class EnclosingLabelDefInfo { + var generatedReturns: Int = 0 + } + + private final class EnclosingLabelDefInfoWithResultAsReturn() + extends EnclosingLabelDefInfo + + private final class EnclosingLabelDefInfoWithResultAsAssigns( + val paramSyms: List[Symbol]) + extends EnclosingLabelDefInfo + + class JSCodePhase(prev: Phase) extends StdPhase(prev) with JSExportsPhase { + + override def name: String = phaseName + override def description: String = GenJSCode.this.description + + // Scoped state ------------------------------------------------------------ + // Per class body + val currentClassSym = new ScopedVar[Symbol] + private val fieldsMutatedInCurrentClass = new ScopedVar[mutable.Set[Name]] + private val generatedSAMWrapperCount = new ScopedVar[VarBox[Int]] + + def currentThisType: jstpe.Type = { + encodeClassType(currentClassSym) match { + case tpe @ jstpe.ClassType(cls) => + jstpe.BoxedClassToPrimType.getOrElse(cls, tpe) + case tpe => + tpe + } + } + + // Per method body + private val currentMethodSym = new ScopedVar[Symbol] + private val thisLocalVarIdent = new ScopedVar[Option[js.LocalIdent]] + private val fakeTailJumpParamRepl = new ScopedVar[(Symbol, Symbol)] + private val enclosingLabelDefInfos = new ScopedVar[Map[Symbol, EnclosingLabelDefInfo]] + private val isModuleInitialized = new ScopedVar[VarBox[Boolean]] + private val undefinedDefaultParams = new ScopedVar[mutable.Set[Symbol]] + private val mutableLocalVars = new ScopedVar[mutable.Set[Symbol]] + private val mutatedLocalVars = new ScopedVar[mutable.Set[Symbol]] + + private def withPerMethodBodyState[A](methodSym: Symbol)(body: => A): A = { + withScopedVars( + currentMethodSym := methodSym, + thisLocalVarIdent := None, + fakeTailJumpParamRepl := (NoSymbol, NoSymbol), + enclosingLabelDefInfos := Map.empty, + isModuleInitialized := new VarBox(false), + undefinedDefaultParams := mutable.Set.empty, + mutableLocalVars := mutable.Set.empty, + mutatedLocalVars := mutable.Set.empty + ) { + body + } + } + + // For anonymous methods + // These have a default, since we always read them. + private val tryingToGenMethodAsJSFunction = new ScopedVar[Boolean](false) + private val paramAccessorLocals = new ScopedVar(Map.empty[Symbol, js.ParamDef]) + + /* Contextual JS class value for some operations of nested JS classes that + * need one. + */ + private val contextualJSClassValue = + new ScopedVar[Option[js.Tree]](None) + + private def acquireContextualJSClassValue[A](f: Option[js.Tree] => A): A = { + val jsClassValue = contextualJSClassValue.get + withScopedVars( + contextualJSClassValue := None + ) { + f(jsClassValue) + } + } + + private class CancelGenMethodAsJSFunction(message: String) + extends scala.util.control.ControlThrowable { + override def getMessage(): String = message + } + + // Rewriting of anonymous function classes --------------------------------- + + /** Start nested generation of a class. + * + * Fully resets the scoped state (including local name scope). + * Allows to generate an anonymous class as needed. + */ + private def nestedGenerateClass[T](clsSym: Symbol)(body: => T): T = { + withScopedVars( + currentClassSym := clsSym, + fieldsMutatedInCurrentClass := mutable.Set.empty, + generatedSAMWrapperCount := new VarBox(0), + currentMethodSym := null, + thisLocalVarIdent := null, + fakeTailJumpParamRepl := null, + enclosingLabelDefInfos := null, + isModuleInitialized := null, + undefinedDefaultParams := null, + mutableLocalVars := null, + mutatedLocalVars := null, + tryingToGenMethodAsJSFunction := false, + paramAccessorLocals := Map.empty + )(withNewLocalNameScope(body)) + } + + // Global class generation state ------------------------------------------- + + private val lazilyGeneratedAnonClasses = mutable.Map.empty[Symbol, ClassDef] + private val generatedClasses = ListBuffer.empty[js.ClassDef] + private val generatedStaticForwarderClasses = ListBuffer.empty[(Symbol, js.ClassDef)] + + private def consumeLazilyGeneratedAnonClass(sym: Symbol): ClassDef = { + /* If we are trying to generate an method as JSFunction, we cannot + * actually consume the symbol, since we might fail trying and retry. + * We will then see the same tree again and not find the symbol anymore. + * + * If we are sure this is the only generation, we remove the symbol to + * make sure we don't generate the same class twice. + */ + val optDef = { + if (tryingToGenMethodAsJSFunction) + lazilyGeneratedAnonClasses.get(sym) + else + lazilyGeneratedAnonClasses.remove(sym) + } + + optDef.getOrElse { + abort("Couldn't find tree for lazily generated anonymous class " + + s"${sym.fullName} at ${sym.pos}") + } + } + + // Top-level apply --------------------------------------------------------- + + override def run(): Unit = { + scalaPrimitives.init() + genBCode.bTypes.initializeCoreBTypes() + jsPrimitives.init() + super.run() + } + + /** Generates the Scala.js IR for a compilation unit + * This method iterates over all the class and interface definitions + * found in the compilation unit and emits their IR (.sjsir). + * + * Some classes are never actually emitted: + * - Classes representing primitive types + * - The scala.Array class + * - Implementation classes for JS traits + * + * Some classes representing anonymous functions are not actually emitted. + * Instead, a temporary representation of their `apply` method is built + * and recorded, so that it can be inlined as a JavaScript anonymous + * function in the method that instantiates it. + * + * Other ClassDefs are emitted according to their nature: + * * Non-native JS class -> `genNonNativeJSClass()` + * * Other JS type (<: js.Any) -> `genJSClassData()` + * * Interface -> `genInterface()` + * * Normal class -> `genClass()` + */ + override def apply(cunit: CompilationUnit): Unit = { + try { + def collectClassDefs(tree: Tree): List[ClassDef] = { + tree match { + case EmptyTree => Nil + case PackageDef(_, stats) => stats flatMap collectClassDefs + case cd: ClassDef => cd :: Nil + } + } + val allClassDefs = collectClassDefs(cunit.body) + + /* There are three types of anonymous classes we want to generate + * only once we need them so we can inline them at construction site: + * + * - anonymous class that are JS types, which includes: + * - lambdas for js.FunctionN and js.ThisFunctionN (SAMs). (We may + * not generate actual Scala classes for these). + * - anonymous (non-lambda) JS classes. These classes may not have + * their own prototype. Therefore, their constructor *must* be + * inlined. + * - lambdas for scala.FunctionN. This is only an optimization and may + * fail. In the case of failure, we fall back to generating a + * fully-fledged Scala class. + * + * Since for all these, we don't know how they inter-depend, we just + * store them in a map at this point. + */ + val (lazyAnons, fullClassDefs0) = allClassDefs.partition { cd => + val sym = cd.symbol + isAnonymousJSClass(sym) || isJSFunctionDef(sym) || sym.isAnonymousFunction + } + + lazilyGeneratedAnonClasses ++= lazyAnons.map(cd => cd.symbol -> cd) + + /* Under Scala 2.11 with -Xexperimental, anonymous JS function classes + * can be referred to in private method signatures, which means they + * must exist at the IR level, as `AbstractJSType`s. + */ + val fullClassDefs = if (isScala211WithXexperimental) { + lazyAnons.filter(cd => isJSFunctionDef(cd.symbol)) ::: fullClassDefs0 + } else { + fullClassDefs0 + } + + /* Finally, we emit true code for the remaining class defs. */ + for (cd <- fullClassDefs) { + val sym = cd.symbol + implicit val pos = sym.pos + + /* Do not actually emit code for primitive types nor scala.Array. */ + val isPrimitive = + isPrimitiveValueClass(sym) || (sym == ArrayClass) + + if (!isPrimitive && !isJSImplClass(sym)) { + withScopedVars( + currentClassSym := sym, + fieldsMutatedInCurrentClass := mutable.Set.empty, + generatedSAMWrapperCount := new VarBox(0) + ) { + try { + val tree = if (isJSType(sym)) { + if (!sym.isTraitOrInterface && isNonNativeJSClass(sym) && + !isJSFunctionDef(sym)) { + genNonNativeJSClass(cd) + } else { + genJSClassData(cd) + } + } else if (sym.isTraitOrInterface) { + genInterface(cd) + } else { + genClass(cd) + } + + generatedClasses += tree + } catch { + case e: ir.InvalidIRException => + e.tree match { + case ir.Trees.Transient(UndefinedParam) => + reporter.error(sym.pos, + "Found a dangling UndefinedParam at " + + s"${e.tree.pos}. This is likely due to a bad " + + "interaction between a macro or a compiler plugin " + + "and the Scala.js compiler plugin. If you hit " + + "this, please let us know.") + + case _ => + reporter.error(sym.pos, + "The Scala.js compiler generated invalid IR for " + + "this class. Please report this as a bug. IR: " + + e.tree) + } + } + } + } + } + + val clDefs = if (generatedStaticForwarderClasses.isEmpty) { + /* Fast path, applicable under -Xno-forwarders, as well as when all + * the `object`s of a compilation unit have a companion class. + */ + generatedClasses.toList + } else { + val regularClasses = generatedClasses.toList + + /* #4148 Add generated static forwarder classes, except those that + * would collide with regular classes on case insensitive file + * systems. + */ + + /* I could not find any reference anywhere about what locale is used + * by case insensitive file systems to compare case-insensitively. + * In doubt, force the English locale, which is probably going to do + * the right thing in virtually all cases (especially if users stick + * to ASCII class names), and it has the merit of being deterministic, + * as opposed to using the OS' default locale. + * The JVM backend performs a similar test to emit a warning for + * conflicting top-level classes. However, it uses `toLowerCase()` + * without argument, which is not deterministic. + */ + def caseInsensitiveNameOf(classDef: js.ClassDef): String = + classDef.name.name.nameString.toLowerCase(java.util.Locale.ENGLISH) + + val generatedCaseInsensitiveNames = + regularClasses.map(caseInsensitiveNameOf).toSet + val staticForwarderClasses = generatedStaticForwarderClasses.toList + .withFilter { case (site, classDef) => + if (!generatedCaseInsensitiveNames.contains(caseInsensitiveNameOf(classDef))) { + true + } else { + global.runReporting.warning( + site.pos, + s"Not generating the static forwarders of ${classDef.name.name.nameString} " + + "because its name differs only in case from the name of another class or " + + "trait in this compilation unit.", + WarningCategory.Other, + site) + false + } + } + .map(_._2) + + regularClasses ::: staticForwarderClasses + } + + generatedJSAST(clDefs) + + for (tree <- clDefs) { + genIRFile(cunit, tree) + } + } catch { + // Handle exceptions in exactly the same way as the JVM backend + case ex: InterruptedException => + throw ex + case ex: Throwable => + if (settings.debug.value) + ex.printStackTrace() + globalError(s"Error while emitting ${cunit.source}\n${ex.getMessage}") + } finally { + lazilyGeneratedAnonClasses.clear() + generatedStaticForwarderClasses.clear() + generatedClasses.clear() + pos2irPosCache.clear() + } + } + + // Generate a class -------------------------------------------------------- + + /** Gen the IR ClassDef for a class definition (maybe a module class). + */ + def genClass(cd: ClassDef): js.ClassDef = { + val ClassDef(mods, name, _, impl) = cd + val sym = cd.symbol + implicit val pos = sym.pos + + assert(!sym.isTraitOrInterface, + "genClass() must be called only for normal classes: "+sym) + assert(sym.superClass != NoSymbol, sym) + + if (hasDefaultCtorArgsAndJSModule(sym)) { + reporter.error(pos, + "Implementation restriction: constructors of " + + "Scala classes cannot have default parameters " + + "if their companion module is JS native.") + } + + val classIdent = encodeClassNameIdent(sym) + val originalName = originalNameOfClass(sym) + val isHijacked = isHijackedClass(sym) + + // Optimizer hints + + val isDynamicImportThunk = sym.isSubClass(DynamicImportThunkClass) + + def isStdLibClassWithAdHocInlineAnnot(sym: Symbol): Boolean = { + val fullName = sym.fullName + (fullName.startsWith("scala.Tuple") && !fullName.endsWith("$")) || + (fullName.startsWith("scala.collection.mutable.ArrayOps$of")) + } + + val shouldMarkInline = ( + isDynamicImportThunk || + sym.hasAnnotation(InlineAnnotationClass) || + (sym.isAnonymousFunction && !sym.isSubClass(PartialFunctionClass)) || + isStdLibClassWithAdHocInlineAnnot(sym)) + + val optimizerHints = + OptimizerHints.empty. + withInline(shouldMarkInline). + withNoinline(sym.hasAnnotation(NoinlineAnnotationClass)) + + // Generate members (constructor + methods) + + val generatedNonFieldMembers = new ListBuffer[js.MemberDef] + + def gen(tree: Tree): Unit = { + tree match { + case EmptyTree => () + case Template(_, _, body) => body foreach gen + + case ValDef(mods, name, tpt, rhs) => + () // fields are added via genClassFields() + + case dd: DefDef => + if (dd.symbol.hasAnnotation(JSNativeAnnotation)) + generatedNonFieldMembers += genJSNativeMemberDef(dd) + else + generatedNonFieldMembers ++= genMethod(dd) + + case _ => abort("Illegal tree in gen of genClass(): " + tree) + } + } + + gen(impl) + + // Generate fields if necessary (and add to methods + ctors) + val generatedMembers = + if (!isHijacked) genClassFields(cd) ++ generatedNonFieldMembers.toList + else generatedNonFieldMembers.toList // No fields needed + + // Generate member exports + val memberExports = genMemberExports(sym) + + // Generate the exported members, constructors and accessors + val topLevelExportDefs = genTopLevelExports(sym) + + // Static initializer + val optStaticInitializer = { + // Initialization of reflection data, if required + val reflectInit = { + val enableReflectiveInstantiation = { + (sym :: sym.ancestors).exists { ancestor => + ancestor.hasAnnotation(EnableReflectiveInstantiationAnnotation) + } + } + if (enableReflectiveInstantiation) + genRegisterReflectiveInstantiation(sym) + else + None + } + + // Initialization of the module because of field exports + val needsStaticModuleInit = + topLevelExportDefs.exists(_.isInstanceOf[js.TopLevelFieldExportDef]) + val staticModuleInit = + if (!needsStaticModuleInit) None + else Some(genLoadModule(sym)) + + val staticInitializerStats = + reflectInit.toList ::: staticModuleInit.toList + if (staticInitializerStats.nonEmpty) { + List(genStaticConstructorWithStats( + ir.Names.StaticInitializerName, + js.Block(staticInitializerStats))) + } else { + Nil + } + } + + val optDynamicImportForwarder = + if (isDynamicImportThunk) List(genDynamicImportForwarder(sym)) + else Nil + + val allMemberDefsExceptStaticForwarders = + generatedMembers ::: memberExports ::: optStaticInitializer ::: optDynamicImportForwarder + + // Add static forwarders + val allMemberDefs = if (!isCandidateForForwarders(sym)) { + allMemberDefsExceptStaticForwarders + } else { + if (sym.isModuleClass) { + /* If the module class has no linked class, we must create one to + * hold the static forwarders. Otherwise, this is going to be handled + * when generating the companion class. + */ + if (!sym.linkedClassOfClass.exists) { + val forwarders = genStaticForwardersFromModuleClass(Nil, sym) + if (forwarders.nonEmpty) { + val forwardersClassDef = js.ClassDef( + js.ClassIdent(ClassName(classIdent.name.nameString.stripSuffix("$"))), + originalName, + ClassKind.Class, + None, + Some(js.ClassIdent(ir.Names.ObjectClass)), + Nil, + None, + None, + forwarders, + Nil + )(js.OptimizerHints.empty) + generatedStaticForwarderClasses += sym -> forwardersClassDef + } + } + allMemberDefsExceptStaticForwarders + } else { + val forwarders = genStaticForwardersForClassOrInterface( + allMemberDefsExceptStaticForwarders, sym) + allMemberDefsExceptStaticForwarders ::: forwarders + } + } + + // Hashed definitions of the class + val hashedMemberDefs = Hashers.hashMemberDefs(allMemberDefs) + + // The complete class definition + val kind = + if (isStaticModule(sym)) ClassKind.ModuleClass + else if (isHijacked) ClassKind.HijackedClass + else ClassKind.Class + + val classDefinition = js.ClassDef( + classIdent, + originalName, + kind, + None, + Some(encodeClassNameIdent(sym.superClass)), + genClassInterfaces(sym, forJSClass = false), + None, + None, + hashedMemberDefs, + topLevelExportDefs)( + optimizerHints) + + classDefinition + } + + /** Gen the IR ClassDef for a non-native JS class. */ + def genNonNativeJSClass(cd: ClassDef): js.ClassDef = { + val sym = cd.symbol + implicit val pos = sym.pos + + assert(isNonNativeJSClass(sym), + "genNonNativeJSClass() must be called only for " + + s"non-native JS classes: $sym") + assert(sym.superClass != NoSymbol, sym) + + if (hasDefaultCtorArgsAndJSModule(sym)) { + reporter.error(pos, + "Implementation restriction: constructors of " + + "non-native JS classes cannot have default parameters " + + "if their companion module is JS native.") + } + + val classIdent = encodeClassNameIdent(sym) + + // Generate members (constructor + methods) + + val constructorTrees = new ListBuffer[DefDef] + val generatedMethods = new ListBuffer[js.MethodDef] + val dispatchMethodNames = new ListBuffer[JSName] + + def gen(tree: Tree): Unit = { + tree match { + case EmptyTree => () + case Template(_, _, body) => body foreach gen + + case ValDef(mods, name, tpt, rhs) => + () // fields are added via genClassFields() + + case dd: DefDef => + val sym = dd.symbol + val exposed = isExposed(sym) + + if (sym.isClassConstructor) { + constructorTrees += dd + } else if (exposed && sym.isAccessor && !sym.isLazy) { + /* Exposed accessors must not be emitted, since the field they + * access is enough. + */ + } else if (sym.hasAnnotation(JSOptionalAnnotation)) { + // Optional methods must not be emitted + } else { + generatedMethods ++= genMethod(dd) + + // Collect the names of the dispatchers we have to create + if (exposed && !sym.isDeferred) { + /* We add symbols that we have to expose here. This way we also + * get inherited stuff that is implemented in this class. + */ + dispatchMethodNames += jsNameOf(sym) + } + } + + case _ => abort("Illegal tree in gen of genClass(): " + tree) + } + } + + gen(cd.impl) + + // Static members (exported from the companion object) + val staticMembers = { + /* Phase travel is necessary for non-top-level classes, because flatten + * breaks their companionModule. This is tracked upstream at + * https://github.com/scala/scala-dev/issues/403 + */ + val companionModuleClass = + exitingPhase(currentRun.picklerPhase)(sym.linkedClassOfClass) + if (companionModuleClass == NoSymbol) { + Nil + } else { + val exports = withScopedVars(currentClassSym := companionModuleClass) { + genStaticExports(companionModuleClass) + } + if (exports.exists(_.isInstanceOf[js.JSFieldDef])) { + val classInitializer = genStaticConstructorWithStats( + ir.Names.ClassInitializerName, + genLoadModule(companionModuleClass)) + exports :+ classInitializer + } else { + exports + } + } + } + + val topLevelExports = genTopLevelExports(sym) + + val (generatedCtor, jsClassCaptures) = withNewLocalNameScope { + val isNested = isNestedJSClass(sym) + + if (isNested) + reserveLocalName(JSSuperClassParamName) + + val (captures, ctor) = + genJSClassCapturesAndConstructor(constructorTrees.toList) + + val jsClassCaptures = { + if (isNested) { + val superParam = js.ParamDef( + js.LocalIdent(JSSuperClassParamName), + NoOriginalName, jstpe.AnyType, mutable = false) + + Some(superParam :: captures) + } else { + assert(captures.isEmpty, + s"found non nested JS class with captures $captures at $pos") + None + } + } + + (ctor, jsClassCaptures) + } + + // Generate fields (and add to methods + ctors) + val generatedMembers = { + genClassFields(cd) ::: + generatedCtor :: + genJSClassDispatchers(sym, dispatchMethodNames.result().distinct) ::: + generatedMethods.toList ::: + staticMembers + } + + // Hashed definitions of the class + val hashedMemberDefs = + Hashers.hashMemberDefs(generatedMembers) + + // The complete class definition + val kind = + if (isStaticModule(sym)) ClassKind.JSModuleClass + else ClassKind.JSClass + + val classDefinition = js.ClassDef( + classIdent, + originalNameOfClass(sym), + kind, + jsClassCaptures, + Some(encodeClassNameIdent(sym.superClass)), + genClassInterfaces(sym, forJSClass = true), + jsSuperClass = jsClassCaptures.map(_.head.ref), + None, + hashedMemberDefs, + topLevelExports)( + OptimizerHints.empty) + + classDefinition + } + + /** Generate an instance of an anonymous (non-lambda) JS class inline + * + * @param sym Class to generate the instance of + * @param jsSuperClassValue JS class value of the super class + * @param args Arguments to the Scala constructor, which map to JS class captures + * @param pos Position of the original New tree + */ + def genAnonJSClassNew(sym: Symbol, jsSuperClassValue: js.Tree, + args: List[js.Tree])( + implicit pos: Position): js.Tree = { + assert(isAnonymousJSClass(sym), + "Generating AnonJSClassNew of non anonymous JS class") + + // Find the ClassDef for this anonymous class + val classDef = consumeLazilyGeneratedAnonClass(sym) + + // Generate a normal, non-native JS class + val origJsClass = + nestedGenerateClass(sym)(genNonNativeJSClass(classDef)) + + // Partition class members. + val privateFieldDefs = ListBuffer.empty[js.FieldDef] + val classDefMembers = ListBuffer.empty[js.MemberDef] + val instanceMembers = ListBuffer.empty[js.MemberDef] + var constructor: Option[js.JSConstructorDef] = None + + origJsClass.memberDefs.foreach { + case fdef: js.FieldDef => + privateFieldDefs += fdef + + case fdef: js.JSFieldDef => + instanceMembers += fdef + + case mdef: js.MethodDef => + assert(mdef.flags.namespace.isStatic, + "Non-static, unexported method in non-native JS class") + classDefMembers += mdef + + case cdef: js.JSConstructorDef => + assert(constructor.isEmpty, "two ctors in class") + constructor = Some(cdef) + + case mdef: js.JSMethodDef => + assert(!mdef.flags.namespace.isStatic, "Exported static method") + instanceMembers += mdef + + case property: js.JSPropertyDef => + instanceMembers += property + + case nativeMemberDef: js.JSNativeMemberDef => + abort("illegal native JS member in JS class at " + nativeMemberDef.pos) + } + + assert(origJsClass.topLevelExportDefs.isEmpty, + "Found top-level exports in anonymous JS class at " + pos) + + // Make new class def with static members + val newClassDef = { + implicit val pos = origJsClass.pos + val parent = js.ClassIdent(ir.Names.ObjectClass) + js.ClassDef(origJsClass.name, origJsClass.originalName, + ClassKind.AbstractJSType, None, Some(parent), interfaces = Nil, + jsSuperClass = None, jsNativeLoadSpec = None, + classDefMembers.toList, Nil)( + origJsClass.optimizerHints) + } + + generatedClasses += newClassDef + + // Construct inline class definition + + val jsClassCaptures = origJsClass.jsClassCaptures.getOrElse { + throw new AssertionError( + s"no class captures for anonymous JS class at $pos") + } + val js.JSConstructorDef(_, ctorParams, ctorRestParam, ctorBody) = constructor.getOrElse { + throw new AssertionError("No ctor found") + } + assert(ctorParams.isEmpty && ctorRestParam.isEmpty, + s"non-empty constructor params for anonymous JS class at $pos") + + /* The first class capture is always a reference to the super class. + * This is enforced by genJSClassCapturesAndConstructor. + */ + def jsSuperClassRef(implicit pos: ir.Position): js.VarRef = + jsClassCaptures.head.ref + + /* The `this` reference. + * FIXME This could clash with a local variable of the constructor or a JS + * class capture. How do we avoid this? + */ + val selfName = freshLocalIdent("this")(pos) + def selfRef(implicit pos: ir.Position) = + js.VarRef(selfName)(jstpe.AnyType) + + def memberLambda(params: List[js.ParamDef], restParam: Option[js.ParamDef], + body: js.Tree)(implicit pos: ir.Position) = { + js.Closure(arrow = false, captureParams = Nil, params, restParam, body, + captureValues = Nil) + } + + val memberDefinitions0 = instanceMembers.toList.map { + case fdef: js.FieldDef => + throw new AssertionError("unexpected FieldDef") + + case fdef: js.JSFieldDef => + implicit val pos = fdef.pos + js.Assign(js.JSSelect(selfRef, fdef.name), jstpe.zeroOf(fdef.ftpe)) + + case mdef: js.MethodDef => + throw new AssertionError("unexpected MethodDef") + + case cdef: js.JSConstructorDef => + throw new AssertionError("unexpected JSConstructorDef") + + case mdef: js.JSMethodDef => + implicit val pos = mdef.pos + val impl = memberLambda(mdef.args, mdef.restParam, mdef.body) + js.Assign(js.JSSelect(selfRef, mdef.name), impl) + + case pdef: js.JSPropertyDef => + implicit val pos = pdef.pos + val optGetter = pdef.getterBody.map { body => + js.StringLiteral("get") -> memberLambda(params = Nil, restParam = None, body) + } + val optSetter = pdef.setterArgAndBody.map { case (arg, body) => + js.StringLiteral("set") -> memberLambda(params = arg :: Nil, restParam = None, body) + } + val descriptor = js.JSObjectConstr( + optGetter.toList ::: + optSetter.toList ::: + List(js.StringLiteral("configurable") -> js.BooleanLiteral(true)) + ) + js.JSMethodApply(js.JSGlobalRef("Object"), + js.StringLiteral("defineProperty"), + List(selfRef, pdef.name, descriptor)) + + case nativeMemberDef: js.JSNativeMemberDef => + abort("illegal native JS member in JS class at " + nativeMemberDef.pos) + } + + val memberDefinitions = if (privateFieldDefs.isEmpty) { + memberDefinitions0 + } else { + /* Private fields, declared in FieldDefs, are stored in a separate + * object, itself stored as a non-enumerable field of the `selfRef`. + * The name of that field is retrieved at + * `scala.scalajs.runtime.privateFieldsSymbol()`, and is a Symbol if + * supported, or a randomly generated string that has the same enthropy + * as a UUID (i.e., 128 random bits). + * + * This encoding solves two issues: + * + * - Hide private fields in anonymous JS classes from `JSON.stringify` + * and other cursory inspections in JS (#2748). + * - Get around the fact that abstract JS types cannot declare + * FieldDefs (#3777). + */ + val fieldsObjValue = { + js.JSObjectConstr(privateFieldDefs.toList.map { fdef => + implicit val pos = fdef.pos + js.StringLiteral(fdef.name.name.nameString) -> jstpe.zeroOf(fdef.ftpe) + }) + } + val definePrivateFieldsObj = { + /* Object.defineProperty(selfRef, privateFieldsSymbol, { + * value: fieldsObjValue + * }); + * + * `writable`, `configurable` and `enumerable` are false by default. + */ + js.JSMethodApply( + js.JSGlobalRef("Object"), + js.StringLiteral("defineProperty"), + List( + selfRef, + genPrivateFieldsSymbol(), + js.JSObjectConstr(List( + js.StringLiteral("value") -> fieldsObjValue)) + ) + ) + } + definePrivateFieldsObj :: memberDefinitions0 + } + + // Transform the constructor body. + val inlinedCtorStats = { + val beforeSuper = ctorBody.beforeSuper + + val superCall = { + implicit val pos = ctorBody.superCall.pos + val js.JSSuperConstructorCall(args) = ctorBody.superCall + + val newTree = { + val ident = + origJsClass.superClass.getOrElse(abort("No superclass")) + if (args.isEmpty && ident.name == JSObjectClassName) + js.JSObjectConstr(Nil) + else + js.JSNew(jsSuperClassRef, args) + } + + val selfVarDef = js.VarDef(selfName, thisOriginalName, jstpe.AnyType, mutable = false, newTree) + selfVarDef :: memberDefinitions + } + + // After the super call, substitute `selfRef` for `This()` + val afterSuper = new ir.Transformers.Transformer { + override def transform(tree: js.Tree, isStat: Boolean): js.Tree = tree match { + case js.This() => + selfRef(tree.pos) + + // Don't traverse closure boundaries + case closure: js.Closure => + val newCaptureValues = closure.captureValues.map(transformExpr) + closure.copy(captureValues = newCaptureValues)(closure.pos) + + case tree => + super.transform(tree, isStat) + } + }.transformStats(ctorBody.afterSuper) + + beforeSuper ::: superCall ::: afterSuper + } + + val closure = js.Closure(arrow = true, jsClassCaptures, Nil, None, + js.Block(inlinedCtorStats, selfRef), jsSuperClassValue :: args) + js.JSFunctionApply(closure, Nil) + } + + // Generate the class data of a JS class ----------------------------------- + + /** Gen the IR ClassDef for a JS class or trait. + */ + def genJSClassData(cd: ClassDef): js.ClassDef = { + val sym = cd.symbol + implicit val pos = sym.pos + + val classIdent = encodeClassNameIdent(sym) + val kind = { + if (sym.isTraitOrInterface) ClassKind.AbstractJSType + else if (isJSFunctionDef(sym)) ClassKind.AbstractJSType + else if (sym.isModuleClass) ClassKind.NativeJSModuleClass + else ClassKind.NativeJSClass + } + val superClass = + if (sym.isTraitOrInterface) None + else Some(encodeClassNameIdent(sym.superClass)) + val jsNativeLoadSpec = jsNativeLoadSpecOfOption(sym) + + js.ClassDef(classIdent, originalNameOfClass(sym), kind, None, superClass, + genClassInterfaces(sym, forJSClass = true), None, jsNativeLoadSpec, + Nil, Nil)( + OptimizerHints.empty) + } + + // Generate an interface --------------------------------------------------- + + /** Gen the IR ClassDef for an interface definition. + */ + def genInterface(cd: ClassDef): js.ClassDef = { + val sym = cd.symbol + implicit val pos = sym.pos + + val classIdent = encodeClassNameIdent(sym) + + // fill in class info builder + def gen(tree: Tree): List[js.MethodDef] = { + tree match { + case EmptyTree => Nil + case Template(_, _, body) => body.flatMap(gen) + + case dd: DefDef => + genMethod(dd).toList + + case _ => + abort("Illegal tree in gen of genInterface(): " + tree) + } + } + val generatedMethods = gen(cd.impl) + val interfaces = genClassInterfaces(sym, forJSClass = false) + + val allMemberDefs = + if (!isCandidateForForwarders(sym)) generatedMethods + else generatedMethods ::: genStaticForwardersForClassOrInterface(generatedMethods, sym) + + // Hashed definitions of the interface + val hashedMemberDefs = + Hashers.hashMemberDefs(allMemberDefs) + + js.ClassDef(classIdent, originalNameOfClass(sym), ClassKind.Interface, + None, None, interfaces, None, None, hashedMemberDefs, Nil)( + OptimizerHints.empty) + } + + private lazy val jsTypeInterfacesBlacklist: Set[Symbol] = + Set(DynamicClass, SerializableClass) // #3118, #3252 + + private def genClassInterfaces(sym: Symbol, forJSClass: Boolean)( + implicit pos: Position): List[js.ClassIdent] = { + + val blacklist = + if (forJSClass) jsTypeInterfacesBlacklist + else Set.empty[Symbol] + + for { + parent <- sym.info.parents + typeSym = parent.typeSymbol + _ = assert(typeSym != NoSymbol, "parent needs symbol") + if typeSym.isTraitOrInterface && !blacklist.contains(typeSym) + } yield { + encodeClassNameIdent(typeSym) + } + } + + // Static forwarders ------------------------------------------------------- + + /* This mimics the logic in BCodeHelpers.addForwarders and the code that + * calls it, except that we never have collisions with existing methods in + * the companion class. This is because in the IR, only methods with the + * same `MethodName` (including signature) and that are also + * `PublicStatic` would collide. Since we never emit any `PublicStatic` + * method otherwise (except in 2.11 impl classes, which have no companion), + * there can be no collision. If that assumption is broken, an error + * message is emitted asking the user to report a bug. + * + * It is important that we always emit forwarders, because some Java APIs + * actually have a public static method and a public instance method with + * the same name. For example the class `Integer` has a + * `def hashCode(): Int` and a `static def hashCode(Int): Int`. The JVM + * back-end considers them as colliding because they have the same name, + * but we must not. + * + * By default, we only emit forwarders for top-level objects, like scalac. + * However, if requested via a compiler option, we enable them for all + * static objects. This is important so we can implement static methods + * of nested static classes of JDK APIs (see #3950). + */ + + /** Is the given Scala class, interface or module class a candidate for + * static forwarders? + */ + def isCandidateForForwarders(sym: Symbol): Boolean = { + !settings.noForwarders.value && sym.isStatic && !isImplClass(sym) && { + // Reject non-top-level objects unless opted in via the appropriate option + scalaJSOpts.genStaticForwardersForNonTopLevelObjects || + !sym.name.containsChar('$') // this is the same test that scalac performs + } + } + + /** Gen the static forwarders to the members of a class or interface for + * methods of its companion object. + * + * This is only done if there exists a companion object and it is not a JS + * type. + * + * Precondition: `isCandidateForForwarders(sym)` is true + */ + def genStaticForwardersForClassOrInterface( + existingMembers: List[js.MemberDef], sym: Symbol)( + implicit pos: Position): List[js.MemberDef] = { + /* Phase travel is necessary for non-top-level classes, because flatten + * breaks their companionModule. This is tracked upstream at + * https://github.com/scala/scala-dev/issues/403 + */ + val module = exitingPhase(currentRun.picklerPhase)(sym.companionModule) + if (module == NoSymbol) { + Nil + } else { + val moduleClass = module.moduleClass + if (!isJSType(moduleClass)) + genStaticForwardersFromModuleClass(existingMembers, moduleClass) + else + Nil + } + } + + private lazy val dontUseExitingUncurryForForwarders = + scala.util.Properties.versionNumberString.startsWith("2.11.") + + /** Gen the static forwarders for the methods of a module class. + * + * Precondition: `isCandidateForForwarders(moduleClass)` is true + */ + def genStaticForwardersFromModuleClass(existingMembers: List[js.MemberDef], + moduleClass: Symbol)( + implicit pos: Position): List[js.MemberDef] = { + + assert(moduleClass.isModuleClass, moduleClass) + + val hasAnyExistingPublicStaticMethod = existingMembers.exists { + case js.MethodDef(flags, _, _, _, _, _) => + flags.namespace == js.MemberNamespace.PublicStatic + case _ => + false + } + if (hasAnyExistingPublicStaticMethod) { + reporter.error(pos, + "Unexpected situation: found existing public static methods in " + + s"the class ${moduleClass.fullName} while trying to generate " + + "static forwarders for its companion object. " + + "Please report this as a bug in Scala.js.") + } + + def listMembersBasedOnFlags = { + // Copy-pasted from BCodeHelpers (it's somewhere else in 2.11.x) + val ExcludedForwarderFlags: Long = { + import scala.tools.nsc.symtab.Flags._ + SPECIALIZED | LIFTED | PROTECTED | STATIC | EXPANDEDNAME | PRIVATE | MACRO + } + + moduleClass.info.membersBasedOnFlags(ExcludedForwarderFlags, symtab.Flags.METHOD) + } + + /* See BCodeHelprs.addForwarders in 2.12+ for why we normally use + * exitingUncurry. In 2.11.x we do not use it, because Scala/JVM did not + * use it back then, and using it on that version causes mixed in methods + * not to be found (this notably breaks `extends App` as the `main` + * method that it defines is not found). + * + * This means that in 2.11.x we suffer from + * https://github.com/scala/bug/issues/10812, like upstream Scala/JVM, + * but it does not really affect Scala.js because the IR methods are not + * used for compilation, only for linking, and for linking it is fine to + * have additional, unexpected bridges. + */ + val members = + if (dontUseExitingUncurryForForwarders) listMembersBasedOnFlags + else exitingUncurry(listMembersBasedOnFlags) + + def isExcluded(m: Symbol): Boolean = { + def isOfJLObject: Boolean = { + val o = m.owner + (o eq ObjectClass) || (o eq AnyRefClass) || (o eq AnyClass) + } + + def isDefaultParamOfJSNativeDef: Boolean = { + DefaultParamInfo.isApplicable(m) && { + val info = new DefaultParamInfo(m) + !info.isForConstructor && info.attachedMethod.hasAnnotation(JSNativeAnnotation) + } + } + + m.isDeferred || m.isConstructor || m.hasAccessBoundary || + isOfJLObject || + m.hasAnnotation(JSNativeAnnotation) || isDefaultParamOfJSNativeDef // #4557 + } + + val forwarders = for { + m <- members + if !isExcluded(m) + } yield { + withNewLocalNameScope { + val flags = js.MemberFlags.empty.withNamespace(js.MemberNamespace.PublicStatic) + val methodIdent = encodeMethodSym(m) + val originalName = originalNameOfMethod(m) + val jsParams = m.tpe.params.map(genParamDef(_)) + val resultType = toIRType(m.tpe.resultType) + + js.MethodDef(flags, methodIdent, originalName, jsParams, resultType, Some { + genApplyMethod(genLoadModule(moduleClass), m, jsParams.map(_.ref)) + })(OptimizerHints.empty, None) + } + } + + forwarders.toList + } + + // Generate the fields of a class ------------------------------------------ + + /** Gen definitions for the fields of a class. + * The fields are initialized with the zero of their types. + */ + def genClassFields(cd: ClassDef): List[js.AnyFieldDef] = { + val classSym = cd.symbol + assert(currentClassSym.get == classSym, + "genClassFields called with a ClassDef other than the current one") + + val isJSClass = isNonNativeJSClass(classSym) + + // Non-method term members are fields, except for module members. + (for { + f <- classSym.info.decls + if !f.isMethod && f.isTerm && !f.isModule + if !f.hasAnnotation(JSOptionalAnnotation) && !f.hasAnnotation(JSNativeAnnotation) + if jsInterop.staticExportsOf(f).isEmpty + } yield { + implicit val pos = f.pos + + val static = jsInterop.topLevelExportsOf(f).nonEmpty + + val mutable = { + static || // static fields must always be mutable + f.isMutable || // mutable fields can be mutated from anywhere + fieldsMutatedInCurrentClass.contains(f.name) // the field is mutated in the current class + } + + val namespace = + if (static) js.MemberNamespace.PublicStatic + else js.MemberNamespace.Public + val flags = + js.MemberFlags.empty.withNamespace(namespace).withMutable(mutable) + + val irTpe0 = { + if (isJSClass) genExposedFieldIRType(f) + else if (static) jstpe.AnyType + else toIRType(f.tpe) + } + + // #4370 Fields cannot have type NothingType + val irTpe = + if (irTpe0 == jstpe.NothingType) encodeClassType(RuntimeNothingClass) + else irTpe0 + + if (isJSClass && isExposed(f)) + js.JSFieldDef(flags, genExpr(jsNameOf(f)), irTpe) + else + js.FieldDef(flags, encodeFieldSym(f), originalNameOfField(f), irTpe) + }).toList + } + + def genExposedFieldIRType(f: Symbol): jstpe.Type = { + val tpeEnteringPosterasure = + enteringPhase(currentRun.posterasurePhase)(f.tpe) + tpeEnteringPosterasure match { + case tpe: ErasedValueType => + /* Here, we must store the field as the boxed representation of + * the value class. The default value of that field, as + * initialized at the time the instance is created, will + * therefore be null. This will not match the behavior we would + * get in a Scala class. To match the behavior, we would need to + * initialized to an instance of the boxed representation, with + * an underlying value set to the zero of its type. However we + * cannot implement that, so we live with the discrepancy. + * Anyway, scalac also has problems with uninitialized value + * class values, if they come from a generic context. + */ + jstpe.ClassType(encodeClassName(tpe.valueClazz)) + + case _ => + /* Other types are not boxed, so we can initialize them to + * their true zero. + */ + toIRType(f.tpe) + } + } + + // Static initializers ----------------------------------------------------- + + private def genStaticConstructorWithStats(name: MethodName, stats: js.Tree)( + implicit pos: Position): js.MethodDef = { + js.MethodDef( + js.MemberFlags.empty.withNamespace(js.MemberNamespace.StaticConstructor), + js.MethodIdent(name), + NoOriginalName, + Nil, + jstpe.NoType, + Some(stats))( + OptimizerHints.empty, None) + } + + private def genRegisterReflectiveInstantiation(sym: Symbol)( + implicit pos: Position): Option[js.Tree] = { + if (isStaticModule(sym)) + genRegisterReflectiveInstantiationForModuleClass(sym) + else if (sym.isModuleClass) + None // #3228 + else if (sym.isLifted && !sym.originalOwner.isClass) + None // #3227 + else + genRegisterReflectiveInstantiationForNormalClass(sym) + } + + private def genRegisterReflectiveInstantiationForModuleClass(sym: Symbol)( + implicit pos: Position): Option[js.Tree] = { + val fqcnArg = js.StringLiteral(sym.fullName + "$") + val runtimeClassArg = js.ClassOf(toTypeRef(sym.info)) + val loadModuleFunArg = + js.Closure(arrow = true, Nil, Nil, None, genLoadModule(sym), Nil) + + val stat = genApplyMethod( + genLoadModule(ReflectModule), + Reflect_registerLoadableModuleClass, + List(fqcnArg, runtimeClassArg, loadModuleFunArg)) + + Some(stat) + } + + private def genRegisterReflectiveInstantiationForNormalClass(sym: Symbol)( + implicit pos: Position): Option[js.Tree] = { + val ctors = + if (sym.isAbstractClass) Nil + else sym.info.member(nme.CONSTRUCTOR).alternatives.filter(_.isPublic) + + if (ctors.isEmpty) { + None + } else { + val constructorsInfos = for { + ctor <- ctors + } yield { + withNewLocalNameScope { + val (parameterTypes, formalParams, actualParams) = (for { + param <- ctor.tpe.params + } yield { + /* Note that we do *not* use `param.tpe` entering posterasure + * (neither to compute `paramType` nor to give to `fromAny`). + * Logic would tell us that we should do so, but we intentionally + * do not to preserve the behavior on the JVM regarding value + * classes. If a constructor takes a value class as parameter, as + * in: + * + * class ValueClass(val underlying: Int) extends AnyVal + * class Foo(val vc: ValueClass) + * + * then, from a reflection point of view, on the JVM, the + * constructor of `Foo` takes an `Int`, not a `ValueClas`. It + * must therefore be identified as the constructor whose + * parameter types is `List(classOf[Int])`, and when invoked + * reflectively, it must be given an `Int` (or `Integer`). + */ + val paramType = js.ClassOf(toTypeRef(param.tpe)) + val paramDef = genParamDef(param, jstpe.AnyType) + val actualParam = fromAny(paramDef.ref, param.tpe) + (paramType, paramDef, actualParam) + }).unzip3 + + val paramTypesArray = js.JSArrayConstr(parameterTypes) + + val newInstanceFun = js.Closure(arrow = true, Nil, formalParams, None, { + genNew(sym, ctor, actualParams) + }, Nil) + + js.JSArrayConstr(List(paramTypesArray, newInstanceFun)) + } + } + + val fqcnArg = js.StringLiteral(sym.fullName) + val runtimeClassArg = js.ClassOf(toTypeRef(sym.info)) + val ctorsInfosArg = js.JSArrayConstr(constructorsInfos) + + val stat = genApplyMethod( + genLoadModule(ReflectModule), + Reflect_registerInstantiatableClass, + List(fqcnArg, runtimeClassArg, ctorsInfosArg)) + + Some(stat) + } + } + + // Constructor of a non-native JS class ------------------------------ + + def genJSClassCapturesAndConstructor(constructorTrees: List[DefDef])( + implicit pos: Position): (List[js.ParamDef], js.JSConstructorDef) = { + /* We need to merge all Scala constructors into a single one because + * JavaScript only allows a single one. + * + * We do this by applying: + * 1. Applying runtime type based dispatch, just like exports. + * 2. Splitting secondary ctors into parts before and after the `this` call. + * 3. Topo-sorting all constructor statements and including/excluding + * them based on the overload that was chosen. + */ + + val (primaryTree :: Nil, secondaryTrees) = + constructorTrees.partition(_.symbol.isPrimaryConstructor) + + val primaryCtor = genPrimaryJSClassCtor(primaryTree) + val secondaryCtors = secondaryTrees.map(genSecondaryJSClassCtor(_)) + + // VarDefs for the parameters of all constructors. + val paramVarDefs = for { + vparam <- constructorTrees.flatMap(_.vparamss.flatten) + } yield { + val sym = vparam.symbol + val tpe = toIRType(sym.tpe) + js.VarDef(encodeLocalSym(sym), originalNameOfLocal(sym), tpe, mutable = true, + jstpe.zeroOf(tpe))(vparam.pos) + } + + /* organize constructors in a called-by tree + * (the implicit root is the primary constructor) + */ + val ctorTree = { + val ctorToChildren = secondaryCtors + .groupBy(_.targetCtor) + .withDefaultValue(Nil) + + /* when constructing the call-by tree, we use pre-order traversal to + * assign overload numbers. + * this puts all descendants of a ctor in a range of overloads numbers. + * + * this property is useful, later, when we need to make statements + * conditional based on the chosen overload. + */ + var nextOverloadNum = 0 + def subTree[T <: JSCtor](ctor: T): ConstructorTree[T] = { + val overloadNum = nextOverloadNum + nextOverloadNum += 1 + val subtrees = ctorToChildren(ctor.sym).map(subTree(_)) + new ConstructorTree(overloadNum, ctor, subtrees) + } + + subTree(primaryCtor) + } + + /* prepare overload dispatch for all constructors. + * as a side-product, we retrieve the capture parameters. + */ + val (exports, jsClassCaptures) = { + val exports = List.newBuilder[Exported] + val jsClassCaptures = List.newBuilder[js.ParamDef] + + def add(tree: ConstructorTree[_ <: JSCtor]): Unit = { + val (e, c) = genJSClassCtorDispatch(tree.ctor.sym, + tree.ctor.paramsAndInfo, tree.overloadNum) + exports += e + jsClassCaptures ++= c + tree.subCtors.foreach(add(_)) + } + + add(ctorTree) + + (exports.result(), jsClassCaptures.result()) + } + + // The name 'constructor' is used for error reporting here + val (formalArgs, restParam, overloadDispatchBody) = + genOverloadDispatch(JSName.Literal("constructor"), exports, jstpe.IntType) + + val overloadVar = js.VarDef(freshLocalIdent("overload"), NoOriginalName, + jstpe.IntType, mutable = false, overloadDispatchBody) + + val constructorBody = wrapJSCtorBody( + paramVarDefs :+ overloadVar, + genJSClassCtorBody(overloadVar.ref, ctorTree), + js.Undefined() :: Nil + ) + + val constructorDef = js.JSConstructorDef( + js.MemberFlags.empty.withNamespace(js.MemberNamespace.Constructor), + formalArgs, restParam, constructorBody)(OptimizerHints.empty, None) + + (jsClassCaptures, constructorDef) + } + + private def genPrimaryJSClassCtor(dd: DefDef): PrimaryJSCtor = { + val DefDef(_, _, _, vparamss, _, Block(stats, _)) = dd + val sym = dd.symbol + assert(sym.isPrimaryConstructor, s"called with non-primary ctor: $sym") + + var jsSuperCall: Option[js.JSSuperConstructorCall] = None + val jsStats = List.newBuilder[js.Tree] + + /* Move all statements after the super constructor call since JS + * cannot access `this` before the super constructor call. + * + * scalac inserts statements before the super constructor call for early + * initializers and param accessor initializers (including val's and var's + * declared in the params). We move those after the super constructor + * call, and are therefore executed later than for a Scala class. + */ + withPerMethodBodyState(sym) { + flatStats(stats).foreach { + case tree @ Apply(fun @ Select(Super(This(_), _), _), args) + if fun.symbol.isClassConstructor => + assert(jsSuperCall.isEmpty, s"Found 2 JS Super calls at ${dd.pos}") + implicit val pos = tree.pos + jsSuperCall = Some(js.JSSuperConstructorCall(genPrimitiveJSArgs(fun.symbol, args))) + + case stat => + val jsStat = genStat(stat) + + assert(jsSuperCall.isDefined || !jsStat.isInstanceOf[js.VarDef], + "Trying to move a local VarDef after the super constructor call " + + s"of a non-native JS class at ${dd.pos}") + + jsStats += jsStat + } + } + + assert(jsSuperCall.isDefined, "Did not find Super call in primary JS " + + s"construtor at ${dd.pos}") + + new PrimaryJSCtor(sym, genParamsAndInfo(sym, vparamss), + js.JSConstructorBody(Nil, jsSuperCall.get, jsStats.result())(dd.pos)) + } + + private def genSecondaryJSClassCtor(dd: DefDef): SplitSecondaryJSCtor = { + val DefDef(_, _, _, vparamss, _, Block(stats, _)) = dd + val sym = dd.symbol + assert(!sym.isPrimaryConstructor, s"called with primary ctor $sym") + + val beforeThisCall = List.newBuilder[js.Tree] + var thisCall: Option[(Symbol, List[js.Tree])] = None + val afterThisCall = List.newBuilder[js.Tree] + + withPerMethodBodyState(sym) { + flatStats(stats).foreach { + case tree @ Apply(fun @ Select(This(_), _), args) + if fun.symbol.isClassConstructor => + assert(thisCall.isEmpty, + s"duplicate this() call in secondary JS constructor at ${dd.pos}") + + implicit val pos = tree.pos + val sym = fun.symbol + thisCall = Some((sym, genActualArgs(sym, args))) + + case stat => + val jsStat = genStat(stat) + if (thisCall.isEmpty) + beforeThisCall += jsStat + else + afterThisCall += jsStat + } + } + + val Some((targetCtor, ctorArgs)) = thisCall + + new SplitSecondaryJSCtor(sym, genParamsAndInfo(sym, vparamss), + beforeThisCall.result(), targetCtor, ctorArgs, afterThisCall.result()) + } + + private def genParamsAndInfo(ctorSym: Symbol, + vparamss: List[List[ValDef]]): List[(js.VarRef, JSParamInfo)] = { + implicit val pos = ctorSym.pos + + val paramSyms = if (vparamss.isEmpty) Nil else vparamss.head.map(_.symbol) + + for { + (paramSym, info) <- paramSyms.zip(jsParamInfos(ctorSym)) + } yield { + genVarRef(paramSym) -> info + } + } + + private def genJSClassCtorDispatch(ctorSym: Symbol, + allParamsAndInfos: List[(js.VarRef, JSParamInfo)], + overloadNum: Int): (Exported, List[js.ParamDef]) = { + implicit val pos = ctorSym.pos + + /* `allParams` are the parameters as seen from *inside* the constructor + * body. the symbols returned in jsParamInfos are the parameters as seen + * from *outside* (i.e. from a caller). + * + * we need to use the symbols from inside to generate the right + * identifiers (the ones generated by the trees in the constructor body). + */ + val (captureParamsAndInfos, normalParamsAndInfos) = + allParamsAndInfos.partition(_._2.capture) + + /* We use the *outer* param symbol to get different names than the *inner* + * symbols. This is necessary so that we can forward captures properly + * between constructor delegation calls. + */ + val jsClassCaptures = + captureParamsAndInfos.map(x => genParamDef(x._2.sym)) + + val normalInfos = normalParamsAndInfos.map(_._2).toIndexedSeq + + val jsExport = new Exported(ctorSym, normalInfos) { + def genBody(formalArgsRegistry: FormalArgsRegistry): js.Tree = { + val captureAssigns = for { + (param, info) <- captureParamsAndInfos + } yield { + js.Assign(param, genVarRef(info.sym)) + } + + val paramAssigns = for { + ((param, info), i) <- normalParamsAndInfos.zipWithIndex + } yield { + val rhs = genScalaArg(sym, i, formalArgsRegistry, info, static = true, + captures = captureParamsAndInfos.map(_._1))( + prevArgsCount => normalParamsAndInfos.take(prevArgsCount).map(_._1)) + + js.Assign(param, rhs) + } + + js.Block(captureAssigns ::: paramAssigns, js.IntLiteral(overloadNum)) + } + } + + (jsExport, jsClassCaptures) + } + + /** Generates a JS constructor body based on a constructor tree. */ + private def genJSClassCtorBody(overloadVar: js.VarRef, + ctorTree: ConstructorTree[PrimaryJSCtor])(implicit pos: Position): js.JSConstructorBody = { + + /* generates a statement that conditionally executes body iff the chosen + * overload is any of the descendants of `tree` (including itself). + * + * here we use the property from building the trees, that a set of + * descendants always has a range of overload numbers. + */ + def ifOverload(tree: ConstructorTree[_], body: js.Tree): js.Tree = body match { + case js.Skip() => js.Skip() + + case body => + val x = overloadVar + val cond = { + import tree.{lo, hi} + + if (lo == hi) { + js.BinaryOp(js.BinaryOp.Int_==, js.IntLiteral(lo), x) + } else { + val lhs = js.BinaryOp(js.BinaryOp.Int_<=, js.IntLiteral(lo), x) + val rhs = js.BinaryOp(js.BinaryOp.Int_<=, x, js.IntLiteral(hi)) + js.If(lhs, rhs, js.BooleanLiteral(false))(jstpe.BooleanType) + } + } + + js.If(cond, body, js.Skip())(jstpe.NoType) + } + + /* preStats / postStats use pre/post order traversal respectively to + * generate a topo-sorted sequence of statements. + */ + + def preStats(tree: ConstructorTree[SplitSecondaryJSCtor], + nextParamsAndInfo: List[(js.VarRef, JSParamInfo)]): js.Tree = { + val inner = tree.subCtors.map(preStats(_, tree.ctor.paramsAndInfo)) + + assert(tree.ctor.ctorArgs.size == nextParamsAndInfo.size, "param count mismatch") + val paramsInfosAndArgs = nextParamsAndInfo.zip(tree.ctor.ctorArgs) + + val (captureParamsInfosAndArgs, normalParamsInfosAndArgs) = + paramsInfosAndArgs.partition(_._1._2.capture) + + val captureAssigns = for { + ((param, _), arg) <- captureParamsInfosAndArgs + } yield { + js.Assign(param, arg) + } + + val normalAssigns = for { + (((param, info), arg), i) <- normalParamsInfosAndArgs.zipWithIndex + } yield { + val newArg = arg match { + case js.Transient(UndefinedParam) => + assert(info.hasDefault, + s"unexpected UndefinedParam for non default param: $param") + + /* Go full circle: We have ignored the default param getter for + * this, we'll create it again. + * + * This seems not optimal: We could simply not ignore the calls to + * default param getters in the first place. + * + * However, this proves to be difficult: Because of translations in + * earlier phases, calls to default param getters may be assigned + * to temporary variables first (see the undefinedDefaultParams + * ScopedVar). If this happens, it becomes increasingly difficult + * to distinguish a default param getter call for a constructor + * call of *this* instance (in which case we would want to keep + * the default param getter call) from one for a *different* + * instance (in which case we would want to discard the default + * param getter call) + * + * Because of this, it ends up being easier to just re-create the + * default param getter call if necessary. + */ + genCallDefaultGetter(tree.ctor.sym, i, tree.ctor.sym.pos, static = false, + captures = captureParamsInfosAndArgs.map(_._1._1))( + prevArgsCount => normalParamsInfosAndArgs.take(prevArgsCount).map(_._1._1)) + + case arg => arg + } + + js.Assign(param, newArg) + } + + ifOverload(tree, js.Block( + inner ++ tree.ctor.beforeCall ++ captureAssigns ++ normalAssigns)) + } + + def postStats(tree: ConstructorTree[SplitSecondaryJSCtor]): js.Tree = { + val inner = tree.subCtors.map(postStats(_)) + ifOverload(tree, js.Block(tree.ctor.afterCall ++ inner)) + } + + val primaryCtor = ctorTree.ctor + val secondaryCtorTrees = ctorTree.subCtors + + wrapJSCtorBody( + secondaryCtorTrees.map(preStats(_, primaryCtor.paramsAndInfo)), + primaryCtor.body, + secondaryCtorTrees.map(postStats(_)) + ) + } + + private def wrapJSCtorBody(before: List[js.Tree], body: js.JSConstructorBody, + after: List[js.Tree]): js.JSConstructorBody = { + js.JSConstructorBody(before ::: body.beforeSuper, body.superCall, + body.afterSuper ::: after)(body.pos) + } + + private sealed trait JSCtor { + val sym: Symbol + val paramsAndInfo: List[(js.VarRef, JSParamInfo)] + } + + private class PrimaryJSCtor(val sym: Symbol, + val paramsAndInfo: List[(js.VarRef, JSParamInfo)], + val body: js.JSConstructorBody) extends JSCtor + + private class SplitSecondaryJSCtor(val sym: Symbol, + val paramsAndInfo: List[(js.VarRef, JSParamInfo)], + val beforeCall: List[js.Tree], + val targetCtor: Symbol, val ctorArgs: List[js.Tree], + val afterCall: List[js.Tree]) extends JSCtor + + private class ConstructorTree[Ctor <: JSCtor]( + val overloadNum: Int, val ctor: Ctor, + val subCtors: List[ConstructorTree[SplitSecondaryJSCtor]]) { + val lo: Int = overloadNum + val hi: Int = subCtors.lastOption.fold(lo)(_.hi) + + assert(lo <= hi, "bad overload range") + } + + // Generate a method ------------------------------------------------------- + + /** Maybe gen JS code for a method definition. + * + * Some methods are not emitted at all: + * + * - Primitives, since they are never actually called (with exceptions) + * - Abstract methods in non-native JS classes + * - Default accessor of a native JS constructor + * - Constructors of hijacked classes + * - Methods with the {{{@JavaDefaultMethod}}} annotation mixed in classes. + */ + def genMethod(dd: DefDef): Option[js.MethodDef] = { + val sym = dd.symbol + val isAbstract = isAbstractMethod(dd) + + /* Is this method a default accessor that should be ignored? + * + * This is the case iff one of the following applies: + * - It is a constructor default accessor and the linked class is a + * native JS class. + * - It is a default accessor for a native JS def, but with the caveat + * that its rhs must be `js.native` because of #4553. + * + * Both of those conditions can only happen if the default accessor is in + * a module class, so we use that as a fast way out. (But omitting that + * condition would not change the result.) + * + * This is different than `isJSDefaultParam` in `genApply`: we do not + * ignore default accessors of *non-native* JS types. Neither for + * constructor default accessor nor regular default accessors. We also + * do not need to worry about non-constructor members of native JS types, + * since for those, the entire member list is ignored in `genJSClassData`. + */ + def isIgnorableDefaultParam: Boolean = { + DefaultParamInfo.isApplicable(sym) && sym.owner.isModuleClass && { + val info = new DefaultParamInfo(sym) + if (info.isForConstructor) { + /* This is a default accessor for a constructor parameter. Check + * whether the attached constructor is a native JS constructor, + * which is the case iff the linked class is a native JS type. + */ + isJSNativeClass(info.constructorOwner) + } else { + /* #4553 We need to ignore default accessors for JS native defs. + * However, because Scala.js <= 1.7.0 actually emitted code calling + * those accessors, we must keep default accessors that would + * compile. The only accessors we can actually get rid of are those + * that are `= js.native`. + */ + !isJSType(sym.owner) && + info.attachedMethod.hasAnnotation(JSNativeAnnotation) && { + dd.rhs match { + case MaybeAsInstanceOf(Apply(fun, _)) => + fun.symbol == JSPackage_native + case _ => + false + } + } + } + } + } + + if (scalaPrimitives.isPrimitive(sym)) { + None + } else if (isAbstract && isNonNativeJSClass(currentClassSym)) { + // #4409: Do not emit abstract methods in non-native JS classes + None + } else if (isIgnorableDefaultParam) { + None + } else if (sym.isClassConstructor && isHijackedClass(sym.owner)) { + None + } else if (scalaUsesImplClasses && !isImplClass(sym.owner) && + !isAbstract && sym.hasAnnotation(JavaDefaultMethodAnnotation)) { + // Do not emit trait impl forwarders with @JavaDefaultMethod + None + } else { + withNewLocalNameScope { + Some(genMethodWithCurrentLocalNameScope(dd)) + } + } + } + + /** Gen JS code for a method definition in a class or in an impl class. + * On the JS side, method names are mangled to encode the full signature + * of the Scala method, as described in `JSEncoding`, to support + * overloading. + * + * Constructors are emitted by generating their body as a statement. + * + * Interface methods with the {{{@JavaDefaultMethod}}} annotation produce + * default methods forwarding to the trait impl class method. + * + * Other (normal) methods are emitted with `genMethodDef()`. + */ + def genMethodWithCurrentLocalNameScope(dd: DefDef): js.MethodDef = { + implicit val pos = dd.pos + val sym = dd.symbol + + withPerMethodBodyState(sym) { + val methodName = encodeMethodSym(sym) + val originalName = originalNameOfMethod(sym) + + val jsParams = { + val vparamss = dd.vparamss + assert(vparamss.isEmpty || vparamss.tail.isEmpty, + "Malformed parameter list: " + vparamss) + val params = if (vparamss.isEmpty) Nil else vparamss.head.map(_.symbol) + params.map(genParamDef(_)) + } + + val jsMethodDef = if (isAbstractMethod(dd)) { + val body = if (scalaUsesImplClasses && + sym.hasAnnotation(JavaDefaultMethodAnnotation)) { + /* For an interface method with @JavaDefaultMethod, make it a + * default method calling the impl class method. + */ + val implClassSym = sym.owner.implClass + val implMethodSym = implClassSym.info.member(sym.name).suchThat { s => + s.isMethod && + s.tpe.params.size == sym.tpe.params.size + 1 && + s.tpe.params.head.tpe =:= sym.owner.toTypeConstructor && + s.tpe.params.tail.zip(sym.tpe.params).forall { + case (sParam, symParam) => + sParam.tpe =:= symParam.tpe + } + } + Some(genApplyStatic(implMethodSym, + js.This()(currentThisType) :: jsParams.map(_.ref))) + } else { + None + } + js.MethodDef(js.MemberFlags.empty, methodName, originalName, + jsParams, toIRType(sym.tpe.resultType), body)( + OptimizerHints.empty, None) + } else { + def isTraitImplForwarder = dd.rhs match { + case app: Apply => isImplClass(app.symbol.owner) + case _ => false + } + + val shouldMarkInline = { + sym.hasAnnotation(InlineAnnotationClass) || + sym.name.startsWith(nme.ANON_FUN_NAME) || + adHocInlineMethods.contains(sym.fullName) + } + + val shouldMarkNoinline = { + sym.hasAnnotation(NoinlineAnnotationClass) && + !isTraitImplForwarder && + !ignoreNoinlineAnnotation(sym) + } + + val optimizerHints = + OptimizerHints.empty. + withInline(shouldMarkInline). + withNoinline(shouldMarkNoinline) + + val methodDef = { + if (sym.isClassConstructor) { + val namespace = js.MemberNamespace.Constructor + js.MethodDef( + js.MemberFlags.empty.withNamespace(namespace), methodName, + originalName, jsParams, jstpe.NoType, Some(genStat(dd.rhs)))( + optimizerHints, None) + } else { + val resultIRType = toIRType(sym.tpe.resultType) + val namespace = { + if (sym.isStaticMember) { + if (sym.isPrivate) js.MemberNamespace.PrivateStatic + else js.MemberNamespace.PublicStatic + } else { + if (sym.isPrivate) js.MemberNamespace.Private + else js.MemberNamespace.Public + } + } + genMethodDef(namespace, methodName, originalName, jsParams, + resultIRType, dd.rhs, optimizerHints) + } + } + + val methodDefWithoutUselessVars = { + val unmutatedMutableLocalVars = + (mutableLocalVars.diff(mutatedLocalVars)).toList + val mutatedImmutableLocalVals = + (mutatedLocalVars.diff(mutableLocalVars)).toList + if (unmutatedMutableLocalVars.isEmpty && + mutatedImmutableLocalVals.isEmpty) { + // OK, we're good (common case) + methodDef + } else { + val patches = ( + unmutatedMutableLocalVars.map(encodeLocalSym(_).name -> false) ::: + mutatedImmutableLocalVals.map(encodeLocalSym(_).name -> true) + ).toMap + patchMutableFlagOfLocals(methodDef, patches) + } + } + + methodDefWithoutUselessVars + } + + /* #3953 Patch the param defs to have the type advertised by the method's type. + * This works around https://github.com/scala/bug/issues/11884, whose fix + * upstream is blocked because it is not binary compatible. The fix here + * only affects the inside of the js.MethodDef, so it is binary compat. + */ + val paramTypeRewrites = jsParams.zip(sym.tpe.paramTypes.map(toIRType(_))).collect { + case (js.ParamDef(name, _, tpe, _), sigType) if tpe != sigType => name.name -> sigType + } + if (paramTypeRewrites.isEmpty) { + // Overwhelmingly common case: all the types match, so there is nothing to do + jsMethodDef + } else { + devWarning( + "Working around https://github.com/scala/bug/issues/11884 " + + s"for ${sym.fullName} at ${sym.pos}") + patchTypeOfParamDefs(jsMethodDef, paramTypeRewrites.toMap) + } + } + } + + def isAbstractMethod(dd: DefDef): Boolean = { + /* When scalac uses impl classes, we cannot trust `rhs` to be + * `EmptyTree` for deferred methods (probably due to an internal bug + * of scalac), as can be seen in run/t6443.scala. + * However, when it does not use impl class anymore, we have to use + * `rhs == EmptyTree` as predicate, just like the JVM back-end does. + */ + if (scalaUsesImplClasses) + dd.symbol.isDeferred || dd.symbol.owner.isInterface + else + dd.rhs == EmptyTree + } + + private val adHocInlineMethods = Set( + "scala.collection.mutable.ArrayOps$ofRef.newBuilder$extension", + "scala.runtime.ScalaRunTime.arrayClass", + "scala.runtime.ScalaRunTime.arrayElementClass" + ) + + /** Patches the mutable flags of selected locals in a [[js.MethodDef]]. + * + * @param patches Map from local name to new value of the mutable flags. + * For locals not in the map, the flag is untouched. + */ + private def patchMutableFlagOfLocals(methodDef: js.MethodDef, + patches: Map[LocalName, Boolean]): js.MethodDef = { + + def newMutable(name: LocalName, oldMutable: Boolean): Boolean = + patches.getOrElse(name, oldMutable) + + val js.MethodDef(flags, methodName, originalName, params, resultType, body) = + methodDef + val newParams = for { + p @ js.ParamDef(name, originalName, ptpe, mutable) <- params + } yield { + js.ParamDef(name, originalName, ptpe, newMutable(name.name, mutable))(p.pos) + } + val transformer = new ir.Transformers.Transformer { + override def transform(tree: js.Tree, isStat: Boolean): js.Tree = tree match { + case js.VarDef(name, originalName, vtpe, mutable, rhs) => + assert(isStat, s"found a VarDef in expression position at ${tree.pos}") + super.transform(js.VarDef(name, originalName, vtpe, + newMutable(name.name, mutable), rhs)(tree.pos), isStat) + case js.Closure(arrow, captureParams, params, restParam, body, captureValues) => + js.Closure(arrow, captureParams, params, restParam, body, + captureValues.map(transformExpr))(tree.pos) + case _ => + super.transform(tree, isStat) + } + } + val newBody = body.map( + b => transformer.transform(b, isStat = resultType == jstpe.NoType)) + js.MethodDef(flags, methodName, originalName, newParams, resultType, + newBody)(methodDef.optimizerHints, None)(methodDef.pos) + } + + /** Patches the type of selected param defs in a [[js.MethodDef]]. + * + * @param patches + * Map from local name to new type. For param defs not in the map, the + * type is untouched. + */ + private def patchTypeOfParamDefs(methodDef: js.MethodDef, + patches: Map[LocalName, jstpe.Type]): js.MethodDef = { + + def newType(name: js.LocalIdent, oldType: jstpe.Type): jstpe.Type = + patches.getOrElse(name.name, oldType) + + val js.MethodDef(flags, methodName, originalName, params, resultType, body) = + methodDef + val newParams = for { + p @ js.ParamDef(name, originalName, ptpe, mutable) <- params + } yield { + js.ParamDef(name, originalName, newType(name, ptpe), mutable)(p.pos) + } + val transformer = new ir.Transformers.Transformer { + override def transform(tree: js.Tree, isStat: Boolean): js.Tree = tree match { + case tree @ js.VarRef(name) => + js.VarRef(name)(newType(name, tree.tpe))(tree.pos) + case js.Closure(arrow, captureParams, params, restParam, body, captureValues) => + js.Closure(arrow, captureParams, params, restParam, body, + captureValues.map(transformExpr))(tree.pos) + case _ => + super.transform(tree, isStat) + } + } + val newBody = body.map( + b => transformer.transform(b, isStat = resultType == jstpe.NoType)) + js.MethodDef(flags, methodName, originalName, newParams, resultType, + newBody)(methodDef.optimizerHints, None)(methodDef.pos) + } + + /** Generates the JSNativeMemberDef of a JS native method. */ + def genJSNativeMemberDef(tree: DefDef): js.JSNativeMemberDef = { + implicit val pos = tree.pos + + val sym = tree.symbol + val flags = js.MemberFlags.empty.withNamespace(js.MemberNamespace.PublicStatic) + val methodName = encodeMethodSym(sym) + val jsNativeLoadSpec = jsInterop.jsNativeLoadSpecOf(sym) + js.JSNativeMemberDef(flags, methodName, jsNativeLoadSpec) + } + + /** Generates the MethodDef of a (non-constructor) method + * + * Most normal methods are emitted straightforwardly. If the result + * type is Unit, then the body is emitted as a statement. Otherwise, it is + * emitted as an expression. + * + * The additional complexity of this method handles the transformation of + * a peculiarity of recursive tail calls: the local ValDef that replaces + * `this`. + */ + def genMethodDef(namespace: js.MemberNamespace, methodName: js.MethodIdent, + originalName: OriginalName, jsParams: List[js.ParamDef], + resultIRType: jstpe.Type, tree: Tree, + optimizerHints: OptimizerHints): js.MethodDef = { + implicit val pos = tree.pos + + val bodyIsStat = resultIRType == jstpe.NoType + + def genBodyWithinReturnableScope(): js.Tree = tree match { + case Block( + (thisDef @ ValDef(_, nme.THIS, _, initialThis)) :: otherStats, + rhs) => + // This method has tail jumps + + // To be called from within withScopedVars + def genInnerBody() = { + js.Block(otherStats.map(genStat) :+ ( + if (bodyIsStat) genStat(rhs) + else genExpr(rhs))) + } + + initialThis match { + case Ident(_) => + /* This case happens in trait implementation classes, until + * Scala 2.11. In the method, all usages of `this` have been + * replaced by the method's formal parameter `$this`. However, + * there is still a declaration of the pseudo local variable + * `_$this`, which is used in the param list of the label. We + * need to remember it now, so that when we build the JS version + * of the formal params for the label, we can redirect the + * assignment to `$this` instead of the otherwise unused + * `_$this`. + */ + withScopedVars( + fakeTailJumpParamRepl := (thisDef.symbol, initialThis.symbol) + ) { + genInnerBody() + } + + case _ => + val thisSym = thisDef.symbol + if (thisSym.isMutable) + mutableLocalVars += thisSym + + val thisLocalIdent = encodeLocalSym(thisSym) + val thisLocalType = currentThisType + + val genRhs = { + /* #3267 In default methods, scalac will type its _$this + * pseudo-variable as the *self-type* of the enclosing class, + * instead of the enclosing class type itself. However, it then + * considers *usages* of _$this as if its type were the + * enclosing class type. The latter makes sense, since it is + * compiled as `this` in the bytecode, which necessarily needs + * to be the enclosing class type. Only the declared type of + * _$this is wrong. + * + * In our case, since we generate an actual local variable for + * _$this, we must make sure to type it correctly, as the + * enclosing class type. However, this means the rhs of the + * ValDef does not match, which is why we have to adapt it + * here. + */ + forceAdapt(genExpr(initialThis), thisLocalType) + } + + val thisLocalVarDef = js.VarDef(thisLocalIdent, thisOriginalName, + thisLocalType, thisSym.isMutable, genRhs) + + val innerBody = { + withScopedVars( + thisLocalVarIdent := Some(thisLocalIdent) + ) { + genInnerBody() + } + } + + js.Block(thisLocalVarDef, innerBody) + } + + case _ => + if (bodyIsStat) genStat(tree) + else genExpr(tree) + } + + def genBody(): js.Tree = { + withNewReturnableScope(resultIRType) { + genBodyWithinReturnableScope() + } + } + + if (!isNonNativeJSClass(currentClassSym) || + isJSFunctionDef(currentClassSym)) { + val flags = js.MemberFlags.empty.withNamespace(namespace) + val body = { + if (currentClassSym.get == HackedStringClass) { + /* Hijack the bodies of String.length and String.charAt and replace + * them with String_length and String_charAt operations, respectively. + */ + methodName.name match { + case `lengthMethodName` => + js.UnaryOp(js.UnaryOp.String_length, genThis()) + case `charAtMethodName` => + js.BinaryOp(js.BinaryOp.String_charAt, genThis(), jsParams.head.ref) + case _ => + genBody() + } + } else if (isImplClass(currentClassSym)) { + val thisParam = jsParams.head + withScopedVars( + thisLocalVarIdent := Some(thisParam.name) + ) { + genBody() + } + } else { + genBody() + } + } + js.MethodDef(flags, methodName, originalName, jsParams, resultIRType, + Some(body))( + optimizerHints, None) + } else { + assert(!namespace.isStatic, tree.pos) + + val thisLocalIdent = freshLocalIdent("this") + withScopedVars( + thisLocalVarIdent := Some(thisLocalIdent) + ) { + val staticNamespace = + if (namespace.isPrivate) js.MemberNamespace.PrivateStatic + else js.MemberNamespace.PublicStatic + val flags = + js.MemberFlags.empty.withNamespace(staticNamespace) + val thisParamDef = js.ParamDef(thisLocalIdent, thisOriginalName, + jstpe.AnyType, mutable = false) + + js.MethodDef(flags, methodName, originalName, + thisParamDef :: jsParams, resultIRType, Some(genBody()))( + optimizerHints, None) + } + } + } + + /** Forces the given `tree` to a given type by adapting it. + * + * @param tree + * The tree to adapt. + * @param tpe + * The target type, which must be either `AnyType` or `ClassType(_)`. + */ + private def forceAdapt(tree: js.Tree, tpe: jstpe.Type): js.Tree = { + if (tree.tpe == tpe || tpe == jstpe.AnyType) { + tree + } else { + /* Remove the useless cast that scalac's erasure had to introduce to + * work around their own ill-typed _$this. Note that the optimizer will + * not be able to do that, since it won't be able to prove that the + * underlying expression is indeed an instance of `tpe`. + */ + tree match { + case js.AsInstanceOf(underlying, _) if underlying.tpe == tpe => + underlying + case _ => + js.AsInstanceOf(tree, tpe)(tree.pos) + } + } + } + + /** Gen JS code for a tree in statement position (in the IR). + */ + def genStat(tree: Tree): js.Tree = { + exprToStat(genStatOrExpr(tree, isStat = true)) + } + + /** Turn a JavaScript expression of type Unit into a statement */ + def exprToStat(tree: js.Tree): js.Tree = { + /* Any JavaScript expression is also a statement, but at least we get rid + * of some pure expressions that come from our own codegen. + */ + implicit val pos = tree.pos + tree match { + case js.Block(stats :+ expr) => + js.Block(stats :+ exprToStat(expr)) + case _:js.Literal | _:js.This | _:js.VarRef => + js.Skip() + case _ => + tree + } + } + + /** Gen JS code for a tree in expression position (in the IR). + */ + def genExpr(tree: Tree): js.Tree = { + val result = genStatOrExpr(tree, isStat = false) + assert(result.tpe != jstpe.NoType, + s"genExpr($tree) returned a tree with type NoType at pos ${tree.pos}") + result + } + + /** Gen JS code for a tree in expression position (in the IR) or the + * global scope. + */ + def genExprOrGlobalScope(tree: Tree): MaybeGlobalScope = { + implicit def pos: Position = tree.pos + + tree match { + case _: This => + val sym = tree.symbol + if (sym != currentClassSym.get && sym.isModule) + genLoadModuleOrGlobalScope(sym) + else + MaybeGlobalScope.NotGlobalScope(genExpr(tree)) + + case _:Ident | _:Select => + val sym = tree.symbol + if (sym.isModule) { + assert(!sym.isPackageClass, "Cannot use package as value: " + tree) + genLoadModuleOrGlobalScope(sym) + } else { + MaybeGlobalScope.NotGlobalScope(genExpr(tree)) + } + + case _ => + MaybeGlobalScope.NotGlobalScope(genExpr(tree)) + } + } + + /** Gen JS code for a tree in statement or expression position (in the IR). + * + * This is the main transformation method. Each node of the Scala AST + * is transformed into an equivalent portion of the JS AST. + */ + def genStatOrExpr(tree: Tree, isStat: Boolean): js.Tree = { + implicit val pos = tree.pos + + tree match { + /** LabelDefs (for while and do..while loops) */ + case lblDf: LabelDef => + genLabelDef(lblDf, isStat) + + /** Local val or var declaration */ + case ValDef(_, name, _, rhs) => + /* Must have been eliminated by the tail call transform performed + * by genMethodDef(). + * If you ever change/remove this assertion, you need to update + * genEnclosingLabelApply() regarding `nme.THIS`. + */ + assert(name != nme.THIS, + s"ValDef(_, nme.THIS, _, _) found at ${tree.pos}") + + val sym = tree.symbol + val rhsTree = + if (rhs == EmptyTree) jstpe.zeroOf(toIRType(sym.tpe)) + else genExpr(rhs) + + rhsTree match { + case js.Transient(UndefinedParam) => + // This is an intermediate assignment for default params on a + // js.Any. Add the symbol to the corresponding set to inform + // the Ident resolver how to replace it and don't emit the symbol + undefinedDefaultParams += sym + js.Skip() + case _ => + if (sym.isMutable) + mutableLocalVars += sym + js.VarDef(encodeLocalSym(sym), originalNameOfLocal(sym), + toIRType(sym.tpe), sym.isMutable, rhsTree) + } + + case If(cond, thenp, elsep) => + val tpe = + if (isStat) jstpe.NoType + else toIRType(tree.tpe) + + js.If(genExpr(cond), genStatOrExpr(thenp, isStat), + genStatOrExpr(elsep, isStat))(tpe) + + case Return(expr) => + js.Return(toIRType(expr.tpe) match { + case jstpe.NoType => js.Block(genStat(expr), js.Undefined()) + case _ => genExpr(expr) + }, getEnclosingReturnLabel()) + + case t: Try => + genTry(t, isStat) + + case Throw(expr) => + val ex = genExpr(expr) + ex match { + case js.New(cls, _, _) if cls != JavaScriptExceptionClassName => + // Common case where ex is neither null nor a js.JavaScriptException + js.Throw(ex) + case _ => + js.Throw(js.UnwrapFromThrowable(ex)) + } + + /* !!! Copy-pasted from `CleanUp.scala` upstream and simplified with + * our `WrapArray` extractor. + * + * Replaces `Array(Predef.wrapArray(ArrayValue(...).$asInstanceOf[...]), )` + * with just `ArrayValue(...)` + * + * See scala/bug#6611; we must *only* do this for literal vararg arrays. + * + * This is normally done by `cleanup` but it comes later than this phase. + */ + case Apply(appMeth, + Apply(wrapRefArrayMeth, StripCast(arg @ ArrayValue(elemtpt, elems)) :: Nil) :: classTagEvidence :: Nil) + if WrapArray.isClassTagBasedWrapArrayMethod(wrapRefArrayMeth.symbol) && + appMeth.symbol == ArrayModule_genericApply && + !elemtpt.tpe.typeSymbol.isBottomClass && + !elemtpt.tpe.typeSymbol.isPrimitiveValueClass /* can happen via specialization.*/ => + classTagEvidence.attachments.get[analyzer.MacroExpansionAttachment] match { + case Some(att) + if att.expandee.symbol.name == nme.materializeClassTag && tree.isInstanceOf[ApplyToImplicitArgs] => + genArrayValue(arg) + case _ => + val arrValue = genApplyMethod( + genExpr(classTagEvidence), + ClassTagClass.info.decl(nme.newArray), + js.IntLiteral(elems.size) :: Nil) + val arrVarDef = js.VarDef(freshLocalIdent("arr"), NoOriginalName, + arrValue.tpe, mutable = false, arrValue) + val stats = List.newBuilder[js.Tree] + foreachWithIndex(elems) { (elem, i) => + stats += genApplyMethod( + genLoadModule(ScalaRunTimeModule), + currentRun.runDefinitions.arrayUpdateMethod, + arrVarDef.ref :: js.IntLiteral(i) :: genExpr(elem) :: Nil) + } + js.Block(arrVarDef :: stats.result(), arrVarDef.ref) + } + case Apply(appMeth, elem0 :: WrapArray(rest @ ArrayValue(elemtpt, _)) :: Nil) + if appMeth.symbol == ArrayModule_apply(elemtpt.tpe) => + genArrayValue(rest, elem0 :: rest.elems) + case Apply(appMeth, elem :: (nil: RefTree) :: Nil) + if nil.symbol == NilModule && appMeth.symbol == ArrayModule_apply(elem.tpe.widen) && + treeInfo.isExprSafeToInline(nil) => + genArrayValue(tree, elem :: Nil) + + case app: Apply => + genApply(app, isStat) + + case app: ApplyDynamic => + genApplyDynamic(app) + + case This(qual) => + if (tree.symbol == currentClassSym.get) { + genThis() + } else { + assert(tree.symbol.isModuleClass, + "Trying to access the this of another class: " + + "tree.symbol = " + tree.symbol + + ", class symbol = " + currentClassSym.get + + " compilation unit:" + currentUnit) + genLoadModule(tree.symbol) + } + + case Select(qualifier, selector) => + val sym = tree.symbol + + def unboxFieldValue(boxed: js.Tree): js.Tree = { + fromAny(boxed, + enteringPhase(currentRun.posterasurePhase)(sym.tpe)) + } + + if (sym.isModule) { + assert(!sym.isPackageClass, "Cannot use package as value: " + tree) + genLoadModule(sym) + } else if (sym.isStaticMember) { + genStaticField(sym) + } else if (paramAccessorLocals contains sym) { + paramAccessorLocals(sym).ref + } else { + val (field, boxed) = genAssignableField(sym, qualifier) + if (boxed) unboxFieldValue(field) + else field + } + + case Ident(name) => + val sym = tree.symbol + if (!sym.hasPackageFlag) { + if (sym.isModule) { + assert(!sym.isPackageClass, "Cannot use package as value: " + tree) + genLoadModule(sym) + } else if (undefinedDefaultParams contains sym) { + // This is a default parameter whose assignment was moved to + // a local variable. Put a literal undefined param again + js.Transient(UndefinedParam) + } else { + genVarRef(sym) + } + } else { + abort("Cannot use package as value: " + tree) + } + + case Literal(value) => + value.tag match { + case UnitTag => + js.Skip() + case BooleanTag => + js.BooleanLiteral(value.booleanValue) + case ByteTag => + js.ByteLiteral(value.byteValue) + case ShortTag => + js.ShortLiteral(value.shortValue) + case CharTag => + js.CharLiteral(value.charValue) + case IntTag => + js.IntLiteral(value.intValue) + case LongTag => + js.LongLiteral(value.longValue) + case FloatTag => + js.FloatLiteral(value.floatValue) + case DoubleTag => + js.DoubleLiteral(value.doubleValue) + case StringTag => + js.StringLiteral(value.stringValue) + case NullTag => + js.Null() + case ClazzTag => + js.ClassOf(toTypeRef(value.typeValue)) + case EnumTag => + genStaticField(value.symbolValue) + } + + case tree: Block => + genBlock(tree, isStat) + + case Typed(Super(_, _), _) => + genThis() + + case Typed(expr, _) => + genExpr(expr) + + case Assign(lhs, rhs) => + val sym = lhs.symbol + if (sym.isStaticMember) + abort(s"Assignment to static member ${sym.fullName} not supported") + def genRhs = genExpr(rhs) + lhs match { + case Select(qualifier, _) => + /* Record assignments to fields of the current class. + * + * We only do that for fields of the current class sym. For other + * fields, even if we recorded it, we would forget them when + * `fieldsMutatedInCurrentClass` is reset when going out of the + * class. If we assign to an immutable field in a different + * class, it will be reported as an IR checking error. + * + * Assignments to `this.` fields in the constructor are valid + * even for immutable fields, and are therefore not recorded. + * + * #3918 We record the *names* of the fields instead of their + * symbols because, in rare cases, scalac has different fields in + * the trees than in the class' decls. Since we only record fields + * from the current class, names are non ambiguous. For the same + * reason, we record assignments to *all* fields, not only the + * immutable ones, because in 2.13 the symbol here can be mutable + * but not the one in the class' decls. + */ + if (sym.owner == currentClassSym.get) { + val ctorAssignment = ( + currentMethodSym.isClassConstructor && + currentMethodSym.owner == qualifier.symbol && + qualifier.isInstanceOf[This] + ) + if (!ctorAssignment) + fieldsMutatedInCurrentClass += sym.name + } + + def genBoxedRhs: js.Tree = { + val tpeEnteringPosterasure = + enteringPhase(currentRun.posterasurePhase)(rhs.tpe) + if ((tpeEnteringPosterasure eq null) && genRhs.isInstanceOf[js.Null]) { + devWarning( + "Working around https://github.com/scala-js/scala-js/issues/3422 " + + s"for ${sym.fullName} at ${sym.pos}") + // Fortunately, a literal `null` never needs to be boxed + genRhs + } else { + ensureBoxed(genRhs, tpeEnteringPosterasure) + } + } + + if (sym.hasAnnotation(JSNativeAnnotation)) { + /* This is an assignment to a @js.native field. Since we reject + * `@js.native var`s as compile errors, this can only happen in + * the constructor of the enclosing object. + * We simply ignore the assignment, since the field will not be + * emitted at all. + */ + js.Skip() + } else { + val (field, boxed) = genAssignableField(sym, qualifier) + + if (boxed) js.Assign(field, genBoxedRhs) + else js.Assign(field,genRhs) + } + + case _ => + mutatedLocalVars += sym + js.Assign( + js.VarRef(encodeLocalSym(sym))(toIRType(sym.tpe)), + genRhs) + } + + /** Array constructor */ + case av: ArrayValue => + genArrayValue(av) + + /** A Match reaching the backend is supposed to be optimized as a switch */ + case mtch: Match => + genMatch(mtch, isStat) + + /** Anonymous function (in 2.12, or with -Ydelambdafy:method in 2.11) */ + case fun: Function => + genAnonFunction(fun) + + case EmptyTree => + js.Skip() + + case _ => + abort("Unexpected tree in genExpr: " + + tree + "/" + tree.getClass + " at: " + tree.pos) + } + } // end of GenJSCode.genExpr() + + /** Gen JS this of the current class. + * Normally encoded straightforwardly as a JS this. + * But must be replaced by the tail-jump-this local variable if there + * is one. + */ + private def genThis()(implicit pos: Position): js.Tree = { + thisLocalVarIdent.fold[js.Tree] { + if (tryingToGenMethodAsJSFunction) { + throw new CancelGenMethodAsJSFunction( + "Trying to generate `this` inside the body") + } + js.This()(currentThisType) + } { thisLocalIdent => + // .copy() to get the correct position + val tpe = { + if (isImplClass(currentClassSym)) + encodeClassType(traitOfImplClass(currentClassSym)) + else + currentThisType + } + js.VarRef(thisLocalIdent.copy())(tpe) + } + } + + /** Gen JS code for LabelDef. + * + * If a LabelDef reaches this method, then the only valid jumps are from + * within it, which means it basically represents a loop. Other kinds of + * LabelDefs, notably those for matches, are caught upstream and + * transformed in ad hoc ways. + * + * The general transformation for + * {{{ + * labelName(...labelParams) { + * rhs + * }: T + * }}} + * is the following: + * {{{ + * block[T]: { + * while (true) { + * labelName[void]: { + * return@block transformedRhs + * } + * } + * } + * }}} + * where all jumps to the label inside the rhs of the form + * {{{ + * labelName(...args) + * }}} + * are transformed into + * {{{ + * ...labelParams = ...args; + * return@labelName (void 0) + * }}} + * + * This is always correct, so it can handle arbitrary labels and jumps + * such as those produced by loops, tail-recursive calls and even some + * compiler plugins (see for example #1148). However, the result is + * unnecessarily ugly for simple `while` and `do while` loops, so we have + * some post-processing to simplify those. + */ + def genLabelDef(tree: LabelDef, isStat: Boolean): js.Tree = { + implicit val pos = tree.pos + val sym = tree.symbol + + val labelParamSyms = tree.params.map(_.symbol).map { s => + if (s == fakeTailJumpParamRepl._1) fakeTailJumpParamRepl._2 else s + } + val info = new EnclosingLabelDefInfoWithResultAsAssigns(labelParamSyms) + + val labelIdent = encodeLabelSym(sym) + val labelName = labelIdent.name + + val transformedRhs = withScopedVars( + enclosingLabelDefInfos := enclosingLabelDefInfos.get + (sym -> info) + ) { + genStatOrExpr(tree.rhs, isStat) + } + + /** Matches a `js.Return` to the current `labelName`, and returns the + * `exprToStat()` of the returned expression. + * We only keep the `exprToStat()` because this label has a `void` type, + * so the expression is always discarded except for its side effects. + */ + object ReturnFromThisLabel { + def unapply(tree: js.Return): Option[js.Tree] = { + if (tree.label.name == labelName) Some(exprToStat(tree.expr)) + else None + } + } + + def genDefault(): js.Tree = { + if (transformedRhs.tpe == jstpe.NothingType) { + // In this case, we do not need the outer block label + js.While(js.BooleanLiteral(true), { + js.Labeled(labelIdent, jstpe.NoType, { + transformedRhs match { + // Eliminate a trailing return@lab + case js.Block(stats :+ ReturnFromThisLabel(exprAsStat)) => + js.Block(stats :+ exprAsStat) + case _ => + transformedRhs + } + }) + }) + } else { + // When all else has failed, we need the full machinery + val blockLabelIdent = freshLabelIdent("block") + val bodyType = + if (isStat) jstpe.NoType + else toIRType(tree.tpe) + js.Labeled(blockLabelIdent, bodyType, { + js.While(js.BooleanLiteral(true), { + js.Labeled(labelIdent, jstpe.NoType, { + if (isStat) + js.Block(transformedRhs, js.Return(js.Undefined(), blockLabelIdent)) + else + js.Return(transformedRhs, blockLabelIdent) + }) + }) + }) + } + } + + info.generatedReturns match { + case 0 => + /* There are no jumps to the loop label. Therefore we can remove + * the labeled block and and the loop altogether. + * This happens for `while (false)` and `do while (false)` loops. + */ + transformedRhs + + case 1 => + /* There is exactly one jump. Let us see if we can isolate where it + * is to try and remove unnecessary labeled blocks and keep only + * the loop. + */ + transformedRhs match { + /* { stats; return@lab expr } + * -> while (true) { stats; expr } + * This happens for `while (true)` and `do while (true)` loops. + */ + case BlockOrAlone(stats, ReturnFromThisLabel(exprAsStat)) => + js.While(js.BooleanLiteral(true), { + js.Block(stats, exprAsStat) + }) + + /* if (cond) { stats; return@lab expr } else elsep [; rest] + * -> while (cond) { stats; expr }; elsep; rest + * This happens for `while (cond)` loops with a non-constant `cond`. + * There is a `rest` if the while loop is on the rhs of a case in a + * patmat. + */ + case FirstInBlockOrAlone( + js.If(cond, BlockOrAlone(stats, ReturnFromThisLabel(exprAsStat)), elsep), + rest) => + js.Block( + js.While(cond, { + js.Block(stats, exprAsStat) + }) :: + elsep :: + rest + ) + + /* { stats; if (cond) { return@lab pureExpr } else { skip } } + * + * !! `cond` could refer to VarDefs declared in stats, and we have + * no way of telling (short of traversing `cond` again) so we + * generate a `while` loop anyway: + * + * -> while ({ stats; cond }) { skip } + * + * The `pureExpr` must be pure because we cannot add it after the + * `cond` above. It must be eliminated, which is only valid if it + * is pure. + * + * This happens for `do while (cond)` loops with a non-constant + * `cond`. + * + * There is no need for BlockOrAlone because the alone case would + * also be caught by the `case js.If` above. + */ + case js.Block(stats :+ js.If(cond, ReturnFromThisLabel(js.Skip()), js.Skip())) => + js.While(js.Block(stats, cond), js.Skip()) + + /* { stats; if (cond) { return@lab pureExpr } else { skip }; literal } + * + * Same as above, but there is an additional `literal` at the end. + * + * This happens for `do while (cond)` loops with a non-constant + * `cond` that are in the rhs of a case in a patmat. + */ + case js.Block(stats :+ js.If(cond, ReturnFromThisLabel(js.Skip()), js.Skip()) :+ (res: js.Literal)) => + js.Block(js.While(js.Block(stats, cond), js.Skip()), res) + + case _ => + genDefault() + } + + case moreThan1 => + genDefault() + } + } + + /** Gen JS code for a try..catch or try..finally block + * + * try..finally blocks are compiled straightforwardly to try..finally + * blocks of JS. + * + * try..catch blocks are a bit more subtle, as JS does not have + * type-based selection of exceptions to catch. We thus encode explicitly + * the type tests, like in: + * + * try { ... } + * catch (e) { + * if (e.isInstanceOf[IOException]) { ... } + * else if (e.isInstanceOf[Exception]) { ... } + * else { + * throw e; // default, re-throw + * } + * } + */ + def genTry(tree: Try, isStat: Boolean): js.Tree = { + implicit val pos = tree.pos + val Try(block, catches, finalizer) = tree + + val blockAST = genStatOrExpr(block, isStat) + + val resultType = + if (isStat) jstpe.NoType + else toIRType(tree.tpe) + + val handled = + if (catches.isEmpty) blockAST + else genTryCatch(blockAST, catches, resultType, isStat) + + genStat(finalizer) match { + case js.Skip() => handled + case ast => js.TryFinally(handled, ast) + } + } + + private def genTryCatch(body: js.Tree, catches: List[CaseDef], + resultType: jstpe.Type, isStat: Boolean)( + implicit pos: Position): js.Tree = { + + catches match { + case CaseDef(Ident(nme.WILDCARD), _, catchAllBody) :: Nil => + genTryCatchCatchIgnoreAll(body, catchAllBody, resultType, isStat) + + case CaseDef(Typed(Ident(nme.WILDCARD), tpt), _, catchAllBody) :: Nil + if tpt.tpe.typeSymbol == ThrowableClass => + genTryCatchCatchIgnoreAll(body, catchAllBody, resultType, isStat) + + case _ => + genTryCatchNotIgnoreAll(body, catches, resultType, isStat) + } + } + + private def genTryCatchCatchIgnoreAll(body: js.Tree, catchAllBody: Tree, + resultType: jstpe.Type, isStat: Boolean)( + implicit pos: Position): js.Tree = { + + js.TryCatch(body, freshLocalIdent("e"), NoOriginalName, + genStatOrExpr(catchAllBody, isStat))( + resultType) + } + + private def genTryCatchNotIgnoreAll(body: js.Tree, catches: List[CaseDef], + resultType: jstpe.Type, isStat: Boolean)( + implicit pos: Position): js.Tree = { + + val exceptIdent = freshLocalIdent("e") + val origExceptVar = js.VarRef(exceptIdent)(jstpe.AnyType) + + val mightCatchJavaScriptException = catches.exists { caseDef => + caseDef.pat match { + case Typed(Ident(nme.WILDCARD), tpt) => + isMaybeJavaScriptException(tpt.tpe) + case Ident(nme.WILDCARD) => + true + case pat @ Bind(_, _) => + isMaybeJavaScriptException(pat.symbol.tpe) + } + } + + val (exceptValDef, exceptVar) = if (mightCatchJavaScriptException) { + val valDef = js.VarDef(freshLocalIdent("e"), NoOriginalName, + encodeClassType(ThrowableClass), mutable = false, js.WrapAsThrowable(origExceptVar)) + (valDef, valDef.ref) + } else { + (js.Skip(), origExceptVar) + } + + val elseHandler: js.Tree = js.Throw(origExceptVar) + + val handler = catches.foldRight(elseHandler) { (caseDef, elsep) => + implicit val pos = caseDef.pos + val CaseDef(pat, _, body) = caseDef + + // Extract exception type and variable + val (tpe, boundVar) = (pat match { + case Typed(Ident(nme.WILDCARD), tpt) => + (tpt.tpe, None) + case Ident(nme.WILDCARD) => + (ThrowableClass.tpe, None) + case Bind(_, _) => + val ident = encodeLocalSym(pat.symbol) + val origName = originalNameOfLocal(pat.symbol) + (pat.symbol.tpe, Some((ident, origName))) + }) + + // Generate the body that must be executed if the exception matches + val bodyWithBoundVar = (boundVar match { + case None => + genStatOrExpr(body, isStat) + case Some((boundVarIdent, boundVarOriginalName)) => + val castException = genAsInstanceOf(exceptVar, tpe) + js.Block( + js.VarDef(boundVarIdent, boundVarOriginalName, toIRType(tpe), + mutable = false, castException), + genStatOrExpr(body, isStat)) + }) + + // Generate the test + if (tpe == ThrowableClass.tpe) { + bodyWithBoundVar + } else { + val cond = genIsInstanceOf(exceptVar, tpe) + js.If(cond, bodyWithBoundVar, elsep)(resultType) + } + } + + js.TryCatch(body, exceptIdent, NoOriginalName, + js.Block(exceptValDef, handler))(resultType) + } + + /** Gen JS code for an Apply node (method call) + * + * There's a whole bunch of varieties of Apply nodes: regular method + * calls, super calls, constructor calls, isInstanceOf/asInstanceOf, + * primitives, JS calls, etc. They are further dispatched in here. + */ + def genApply(tree: Apply, isStat: Boolean): js.Tree = { + implicit val pos = tree.pos + val Apply(fun, args) = tree + val sym = fun.symbol + + /* Is the method a JS default accessor, which should become an + * `UndefinedParam` rather than being compiled normally. + * + * This is true iff one of the following conditions apply: + * - It is a constructor default param for the constructor of a JS class. + * - It is a default param of an instance method of a native JS type. + * - It is a default param of an instance method of a non-native JS type + * and the attached method is exposed. + * - It is a default param for a native JS def. + * + * This is different than `isIgnorableDefaultParam` in `genMethod`: we + * include here the default accessors of *non-native* JS types (unless + * the corresponding methods are not exposed). We also need to handle + * non-constructor members of native JS types. + */ + def isJSDefaultParam: Boolean = { + DefaultParamInfo.isApplicable(sym) && { + val info = new DefaultParamInfo(sym) + if (info.isForConstructor) { + /* This is a default accessor for a constructor parameter. Check + * whether the attached constructor is a JS constructor, which is + * the case iff the linked class is a JS type. + */ + isJSType(info.constructorOwner) + } else { + if (isJSType(sym.owner)) { + /* The default accessor is in a JS type. It is a JS default + * param iff the enclosing class is native or the attached method + * is exposed. + */ + !isNonNativeJSClass(sym.owner) || isExposed(info.attachedMethod) + } else { + /* The default accessor is in a Scala type. It is a JS default + * param iff the attached method is a native JS def. This can + * only happen if the owner is a module class, which we test + * first as a fast way out. + */ + sym.owner.isModuleClass && info.attachedMethod.hasAnnotation(JSNativeAnnotation) + } + } + } + } + + fun match { + case TypeApply(_, _) => + genApplyTypeApply(tree, isStat) + + case _ if isJSDefaultParam => + js.Transient(UndefinedParam) + + case Select(Super(_, _), _) => + genSuperCall(tree, isStat) + + case Select(New(_), nme.CONSTRUCTOR) => + genApplyNew(tree) + + case _ => + if (sym.isLabel) { + genLabelApply(tree) + } else if (scalaPrimitives.isPrimitive(sym)) { + genPrimitiveOp(tree, isStat) + } else if (currentRun.runDefinitions.isBox(sym)) { + // Box a primitive value (cannot be Unit) + val arg = args.head + makePrimitiveBox(genExpr(arg), sym.firstParam.tpe) + } else if (currentRun.runDefinitions.isUnbox(sym)) { + // Unbox a primitive value (cannot be Unit) + val arg = args.head + makePrimitiveUnbox(genExpr(arg), tree.tpe) + } else { + genNormalApply(tree, isStat) + } + } + } + + /** Gen an Apply with a TypeApply method. + * + * Until 2.12.0-M5, only `isInstanceOf` and `asInstanceOf` kept their type + * argument until the backend. Since 2.12.0-RC1, `AnyRef.synchronized` + * does so too. + */ + private def genApplyTypeApply(tree: Apply, isStat: Boolean): js.Tree = { + implicit val pos = tree.pos + val Apply(TypeApply(fun @ Select(obj, _), targs), args) = tree + val sym = fun.symbol + + sym match { + case Object_isInstanceOf => + genIsAsInstanceOf(obj, targs, cast = false) + case Object_asInstanceOf => + genIsAsInstanceOf(obj, targs, cast = true) + case Object_synchronized => + genSynchronized(obj, args.head, isStat) + case _ => + abort("Unexpected type application " + fun + + "[sym: " + sym.fullName + "]" + " in: " + tree) + } + } + + /** Gen `isInstanceOf` or `asInstanceOf`. */ + private def genIsAsInstanceOf(obj: Tree, targs: List[Tree], cast: Boolean)( + implicit pos: Position): js.Tree = { + genIsAsInstanceOf(genExpr(obj), obj.tpe, targs.head.tpe, cast) + } + + /** Gen `isInstanceOf` or `asInstanceOf`. */ + private def genIsAsInstanceOf(expr: js.Tree, from: Type, to: Type, + cast: Boolean)( + implicit pos: Position): js.Tree = { + val l = toIRType(from) + val r = toIRType(to) + + def isValueType(tpe: jstpe.Type): Boolean = tpe match { + case jstpe.NoType | jstpe.BooleanType | jstpe.CharType | + jstpe.ByteType | jstpe.ShortType | jstpe.IntType | jstpe.LongType | + jstpe.FloatType | jstpe.DoubleType => + true + case _ => + false + } + + val lIsValueType = isValueType(l) + val rIsValueType = isValueType(r) + + if (lIsValueType && rIsValueType) { + if (cast) { + /* It is unclear whether this case can be reached for all type + * conversions, but scalac handles all cases, so we do too. + * Three known user code patterns that become code handled by this + * case are `byte.##`, `short.##` and `char.##`, which become, e.g., + * `char.toChar().$asInstanceOf[Int]`. + */ + genConversion(l, r, expr) + } else { + js.BooleanLiteral(l == r) + } + } else if (lIsValueType) { + val result = + if (cast) genThrowClassCastException() + else js.BooleanLiteral(false) + js.Block(expr, result) // eval and discard source + } else if (rIsValueType) { + assert(!cast, s"Unexpected asInstanceOf from ref type to value type") + genIsInstanceOf(expr, boxedClass(to.typeSymbol).tpe) + } else { + if (cast) + genAsInstanceOf(expr, to) + else + genIsInstanceOf(expr, to) + } + } + + private def genThrowClassCastException()(implicit pos: Position): js.Tree = { + val ctor = ClassCastExceptionClass.info.member( + nme.CONSTRUCTOR).suchThat(_.tpe.params.isEmpty) + js.Throw(genNew(ClassCastExceptionClass, ctor, Nil)) + } + + /** Gen JS code for a super call, of the form Class.super[mix].fun(args). + * + * This does not include calls defined in mixin traits, as these are + * already desugared by the 'mixin' phase. Only calls to super classes + * remain. + * Since a class has exactly one direct superclass, and calling a method + * two classes above the current one is invalid, the `mix` item is + * irrelevant. + */ + private def genSuperCall(tree: Apply, isStat: Boolean): js.Tree = { + implicit val pos = tree.pos + val Apply(fun @ Select(sup @ Super(qual, _), _), args) = tree + val sym = fun.symbol + + if (isJSType(qual.tpe)) { + if (sym.isMixinConstructor) { + /* Do not emit a call to the $init$ method of JS traits. + * This exception is necessary because @JSOptional fields cause the + * creation of a $init$ method, which we must not call. + */ + js.Skip() + } else { + genJSSuperCall(tree, isStat) + } + } else { + /* #3013 `qual` can be `this.$outer()` in some cases since Scala 2.12, + * so we call `genExpr(qual)`, not just `genThis()`. + */ + val superCall = genApplyMethodStatically( + genExpr(qual), sym, genActualArgs(sym, args)) + + // Initialize the module instance just after the super constructor call. + if (isStaticModule(currentClassSym) && !isModuleInitialized.value && + currentMethodSym.isClassConstructor) { + isModuleInitialized.value = true + val className = encodeClassName(currentClassSym) + val initModule = + js.StoreModule(className, js.This()(jstpe.ClassType(className))) + js.Block(superCall, initModule) + } else { + superCall + } + } + } + + /** Gen JS code for a constructor call (new). + * Further refined into: + * * new String(...) + * * new of a hijacked boxed class + * * new of an anonymous function class that was recorded as JS function + * * new of a JS class + * * new Array + * * regular new + */ + private def genApplyNew(tree: Apply): js.Tree = { + implicit val pos = tree.pos + val Apply(fun @ Select(New(tpt), nme.CONSTRUCTOR), args) = tree + val ctor = fun.symbol + val tpe = tpt.tpe + val clsSym = tpe.typeSymbol + + assert(ctor.isClassConstructor, + "'new' call to non-constructor: " + ctor.name) + + if (isHijackedClass(clsSym)) { + genNewHijackedClass(clsSym, ctor, args.map(genExpr)) + } else if (isJSFunctionDef(clsSym)) { + val classDef = consumeLazilyGeneratedAnonClass(clsSym) + genJSFunction(classDef, args.map(genExpr)) + } else if (clsSym.isAnonymousFunction) { + val classDef = consumeLazilyGeneratedAnonClass(clsSym) + tryGenAnonFunctionClass(classDef, args.map(genExpr)).getOrElse { + // Cannot optimize anonymous function class. Generate full class. + generatedClasses += nestedGenerateClass(clsSym)(genClass(classDef)) + genNew(clsSym, ctor, genActualArgs(ctor, args)) + } + } else if (isJSType(clsSym)) { + genPrimitiveJSNew(tree) + } else { + toTypeRef(tpe) match { + case jstpe.ClassRef(className) => + genNew(className, ctor, genActualArgs(ctor, args)) + case arr: jstpe.ArrayTypeRef => + genNewArray(arr, args.map(genExpr)) + case prim: jstpe.PrimRef => + abort(s"unexpected primitive type $prim in New at $pos") + } + } + } + + /** Gen jump to a label. + * + * Some label-applys are caught upstream (jumps to next case of a pattern + * match that are in tail-pos or their own case), but most are handled + * here, notably: + * + * - Jumps to the beginning label of loops, including tail-recursive calls + * - Jumps to the next case label that are not in tail position + * - Jumps to the end of a pattern match + */ + private def genLabelApply(tree: Apply): js.Tree = { + implicit val pos = tree.pos + val Apply(fun, args) = tree + val sym = fun.symbol + + val info = enclosingLabelDefInfos.getOrElse(sym, { + abort("Found unknown label apply at "+tree.pos+": "+tree) + }) + + val labelIdent = encodeLabelSym(sym) + info.generatedReturns += 1 + + def assertArgCountMatches(expected: Int): Unit = { + assert(args.size == expected, + s"argument count mismatch for label-apply at $pos: " + + s"expected $expected but got ${args.size}") + } + + info match { + case info: EnclosingLabelDefInfoWithResultAsAssigns => + val paramSyms = info.paramSyms + assertArgCountMatches(paramSyms.size) + + val jump = js.Return(js.Undefined(), labelIdent) + + if (args.isEmpty) { + // fast path, applicable notably to loops and case labels + jump + } else { + js.Block(genMultiAssign(paramSyms, args), jump) + } + + case _: EnclosingLabelDefInfoWithResultAsReturn => + assertArgCountMatches(1) + js.Return(genExpr(args.head), labelIdent) + } + } + + /** Gen multiple "parallel" assignments. + * + * This is used when assigning the new value of multiple parameters of a + * label-def, notably for the ones generated for tail-recursive methods. + * + * Since the rhs for the new value of an argument can depend on the value + * of another argument (and since deciding if it is indeed the case is + * impossible in general), new values are computed in temporary variables + * first, then copied to the actual variables representing the argument. + * + * Trivial assignments (arg1 = arg1) are eliminated. + * + * If, after elimination of trivial assignments, only one assignment + * remains, then we do not use a temporary variable for this one. + */ + private def genMultiAssign(targetSyms: List[Symbol], values: List[Tree])( + implicit pos: Position): List[js.Tree] = { + + // Prepare quadruplets of (formalArg, irType, tempVar, actualArg) + // Do not include trivial assignments (when actualArg == formalArg) + val quadruplets = { + val quadruplets = + List.newBuilder[(js.VarRef, jstpe.Type, js.LocalIdent, js.Tree)] + + for ((formalArgSym, arg) <- targetSyms.zip(values)) { + val formalArg = encodeLocalSym(formalArgSym) + val actualArg = genExpr(arg) + + /* #3267 The formal argument representing the special `this` of a + * tailrec method can have the wrong type in the scalac symbol table. + * We need to patch it up, along with the actual argument, to be the + * enclosing class type. + * See the longer comment in genMethodDef() for more details. + * + * Note that only testing the `name` against `nme.THIS` is safe, + * given that `genStatOrExpr()` for `ValDef` asserts that no local + * variable named `nme.THIS` can happen, other than the ones + * generated for tailrec methods. + */ + val isTailJumpThisLocalVar = formalArgSym.name == nme.THIS + + val tpe = + if (isTailJumpThisLocalVar) currentThisType + else toIRType(formalArgSym.tpe) + + val fixedActualArg = + if (isTailJumpThisLocalVar) forceAdapt(actualArg, tpe) + else actualArg + + actualArg match { + case js.VarRef(`formalArg`) => + // This is trivial assignment, we don't need it + + case _ => + mutatedLocalVars += formalArgSym + quadruplets += ((js.VarRef(formalArg)(tpe), tpe, + freshLocalIdent(formalArg.name.withPrefix("temp$")), + fixedActualArg)) + } + } + + quadruplets.result() + } + + quadruplets match { + case Nil => + Nil + + case (formalArg, _, _, actualArg) :: Nil => + js.Assign(formalArg, actualArg) :: Nil + + case _ => + val tempAssignments = + for ((_, argType, tempArg, actualArg) <- quadruplets) + yield js.VarDef(tempArg, NoOriginalName, argType, mutable = false, actualArg) + val trueAssignments = + for ((formalArg, argType, tempArg, _) <- quadruplets) + yield js.Assign(formalArg, js.VarRef(tempArg)(argType)) + tempAssignments ::: trueAssignments + } + } + + /** Gen a "normal" apply (to a true method). + * + * But even these are further refined into: + * + * - Calls to methods of JS types. + * - Calls to methods in impl classes of traits. + * - Direct calls to constructors (from secondary constructor to another one). + * - Regular method calls. + */ + private def genNormalApply(tree: Apply, isStat: Boolean): js.Tree = { + implicit val pos = tree.pos + val Apply(fun @ Select(receiver, _), args) = tree + val sym = fun.symbol + + if (isJSType(receiver.tpe) && sym.owner != ObjectClass) { + if (!isNonNativeJSClass(sym.owner) || isExposed(sym)) + genPrimitiveJSCall(tree, isStat) + else + genApplyJSClassMethod(genExpr(receiver), sym, genActualArgs(sym, args)) + } else if (sym.hasAnnotation(JSNativeAnnotation)) { + genJSNativeMemberCall(tree, isStat) + } else if (sym.isStaticMember) { + if (sym.isMixinConstructor && isJSImplClass(sym.owner)) { + /* Do not emit a call to the $init$ method of JS traits. + * This exception is necessary because optional JS fields cause the + * creation of a $init$ method, which we must not call. + */ + js.Skip() + } else { + genApplyStatic(sym, args.map(genExpr)) + } + } else { + genApplyMethodMaybeStatically(genExpr(receiver), sym, + genActualArgs(sym, args)) + } + } + + def genApplyMethodMaybeStatically(receiver: js.Tree, + method: Symbol, arguments: List[js.Tree])( + implicit pos: Position): js.Tree = { + if (method.isPrivate || method.isClassConstructor) + genApplyMethodStatically(receiver, method, arguments) + else + genApplyMethod(receiver, method, arguments) + } + + /** Gen JS code for a call to a Scala method. */ + def genApplyMethod(receiver: js.Tree, + method: Symbol, arguments: List[js.Tree])( + implicit pos: Position): js.Tree = { + assert(!method.isPrivate, + s"Cannot generate a dynamic call to private method $method at $pos") + js.Apply(js.ApplyFlags.empty, receiver, encodeMethodSym(method), arguments)( + toIRType(method.tpe.resultType)) + } + + def genApplyMethodStatically(receiver: js.Tree, method: Symbol, + arguments: List[js.Tree])(implicit pos: Position): js.Tree = { + val flags = js.ApplyFlags.empty + .withPrivate(method.isPrivate && !method.isClassConstructor) + .withConstructor(method.isClassConstructor) + val methodIdent = encodeMethodSym(method) + val resultType = + if (method.isClassConstructor) jstpe.NoType + else toIRType(method.tpe.resultType) + js.ApplyStatically(flags, receiver, encodeClassName(method.owner), + methodIdent, arguments)(resultType) + } + + def genApplyJSClassMethod(receiver: js.Tree, method: Symbol, + arguments: List[js.Tree])(implicit pos: Position): js.Tree = { + genApplyStatic(method, receiver :: arguments) + } + + def genApplyStatic(method: Symbol, arguments: List[js.Tree])( + implicit pos: Position): js.Tree = { + js.ApplyStatic(js.ApplyFlags.empty.withPrivate(method.isPrivate), + encodeClassName(method.owner), encodeMethodSym(method), arguments)( + toIRType(method.tpe.resultType)) + } + + private def adaptPrimitive(value: js.Tree, to: jstpe.Type)( + implicit pos: Position): js.Tree = { + genConversion(value.tpe, to, value) + } + + /* This method corresponds to the method of the same name in + * BCodeBodyBuilder of the JVM back-end. It ends up calling the method + * BCodeIdiomatic.emitT2T, whose logic we replicate here. + */ + private def genConversion(from: jstpe.Type, to: jstpe.Type, value: js.Tree)( + implicit pos: Position): js.Tree = { + import js.UnaryOp._ + + if (from == to || from == jstpe.NothingType) { + value + } else if (from == jstpe.BooleanType || to == jstpe.BooleanType) { + throw new AssertionError(s"Invalid genConversion from $from to $to") + } else { + def intValue = (from: @unchecked) match { + case jstpe.IntType => value + case jstpe.CharType => js.UnaryOp(CharToInt, value) + case jstpe.ByteType => js.UnaryOp(ByteToInt, value) + case jstpe.ShortType => js.UnaryOp(ShortToInt, value) + case jstpe.LongType => js.UnaryOp(LongToInt, value) + case jstpe.FloatType => js.UnaryOp(DoubleToInt, js.UnaryOp(FloatToDouble, value)) + case jstpe.DoubleType => js.UnaryOp(DoubleToInt, value) + } + + def doubleValue = from match { + case jstpe.DoubleType => value + case jstpe.FloatType => js.UnaryOp(FloatToDouble, value) + case jstpe.LongType => js.UnaryOp(LongToDouble, value) + case _ => js.UnaryOp(IntToDouble, intValue) + } + + (to: @unchecked) match { + case jstpe.CharType => + js.UnaryOp(IntToChar, intValue) + case jstpe.ByteType => + js.UnaryOp(IntToByte, intValue) + case jstpe.ShortType => + js.UnaryOp(IntToShort, intValue) + case jstpe.IntType => + intValue + case jstpe.LongType => + from match { + case jstpe.FloatType | jstpe.DoubleType => + js.UnaryOp(DoubleToLong, doubleValue) + case _ => + js.UnaryOp(IntToLong, intValue) + } + case jstpe.FloatType => + if (from == jstpe.LongType) + js.UnaryOp(js.UnaryOp.LongToFloat, value) + else + js.UnaryOp(js.UnaryOp.DoubleToFloat, doubleValue) + case jstpe.DoubleType => + doubleValue + } + } + } + + /** Gen JS code for an isInstanceOf test (for reference types only) */ + def genIsInstanceOf(value: js.Tree, to: Type)( + implicit pos: Position): js.Tree = { + + val sym = to.typeSymbol + + if (sym == ObjectClass) { + js.BinaryOp(js.BinaryOp.!==, value, js.Null()) + } else if (isJSType(sym)) { + if (sym.isTrait) { + reporter.error(pos, + s"isInstanceOf[${sym.fullName}] not supported because it is a JS trait") + js.BooleanLiteral(true) + } else { + js.AsInstanceOf( + js.JSBinaryOp(js.JSBinaryOp.instanceof, value, genPrimitiveJSClass(sym)), + jstpe.BooleanType) + } + } else { + // The Scala type system prevents x.isInstanceOf[Null] and ...[Nothing] + assert(sym != NullClass && sym != NothingClass, + s"Found a .isInstanceOf[$sym] at $pos") + js.IsInstanceOf(value, toIRType(to)) + } + } + + /** Gen JS code for an asInstanceOf cast (for reference types only) */ + def genAsInstanceOf(value: js.Tree, to: Type)( + implicit pos: Position): js.Tree = { + + def default: js.Tree = + js.AsInstanceOf(value, toIRType(to)) + + val sym = to.typeSymbol + + if (sym == ObjectClass || isJSType(sym)) { + /* asInstanceOf[Object] always succeeds, and + * asInstanceOf to a JS type is completely erased. + */ + value + } else if (sym == NullClass) { + js.If( + js.BinaryOp(js.BinaryOp.===, value, js.Null()), + js.Null(), + genThrowClassCastException())( + jstpe.NullType) + } else if (sym == NothingClass) { + js.Block(value, genThrowClassCastException()) + } else { + default + } + } + + /** Gen JS code for a call to a Scala class constructor. */ + def genNew(clazz: Symbol, ctor: Symbol, arguments: List[js.Tree])( + implicit pos: Position): js.Tree = { + assert(!isJSFunctionDef(clazz), + s"Trying to instantiate a JS function def $clazz") + genNew(encodeClassName(clazz), ctor, arguments) + } + + /** Gen JS code for a call to a Scala class constructor. */ + def genNew(className: ClassName, ctor: Symbol, arguments: List[js.Tree])( + implicit pos: Position): js.Tree = { + js.New(className, encodeMethodSym(ctor), arguments) + } + + /** Gen JS code for a call to a constructor of a hijacked class. + * Reroute them to the `new` method with the same signature in the + * companion object. + */ + private def genNewHijackedClass(clazz: Symbol, ctor: Symbol, + args: List[js.Tree])(implicit pos: Position): js.Tree = { + + val flags = js.ApplyFlags.empty + val className = encodeClassName(clazz) + + val initName = encodeMethodSym(ctor).name + val newName = MethodName(newSimpleMethodName, initName.paramTypeRefs, + jstpe.ClassRef(className)) + val newMethodIdent = js.MethodIdent(newName) + + js.ApplyStatic(flags, className, newMethodIdent, args)( + jstpe.ClassType(className)) + } + + /** Gen JS code for creating a new Array: new Array[T](length) + * For multidimensional arrays (dimensions > 1), the arguments can + * specify up to `dimensions` lengths for the first dimensions of the + * array. + */ + def genNewArray(arrayTypeRef: jstpe.ArrayTypeRef, arguments: List[js.Tree])( + implicit pos: Position): js.Tree = { + assert(arguments.length <= arrayTypeRef.dimensions, + "too many arguments for array constructor: found " + arguments.length + + " but array has only " + arrayTypeRef.dimensions + + " dimension(s)") + + js.NewArray(arrayTypeRef, arguments) + } + + /** Gen JS code for an array literal. */ + def genArrayValue(tree: ArrayValue): js.Tree = { + val ArrayValue(tpt @ TypeTree(), elems) = tree + genArrayValue(tree, elems) + } + + /** Gen JS code for an array literal, in the context of `tree` (its `tpe` + * and `pos`) but with the elements `elems`. + */ + def genArrayValue(tree: Tree, elems: List[Tree]): js.Tree = { + implicit val pos = tree.pos + val arrayTypeRef = toTypeRef(tree.tpe).asInstanceOf[jstpe.ArrayTypeRef] + js.ArrayValue(arrayTypeRef, elems.map(genExpr)) + } + + /** Gen JS code for a Match, i.e., a switch-able pattern match. + * + * In most cases, this straightforwardly translates to a Match in the IR, + * which will eventually become a `switch` in JavaScript. + * + * However, sometimes there is a guard in here, despite the fact that + * matches cannot have guards (in the JVM nor in the IR). The JVM backend + * emits a jump to the default clause when a guard is not fulfilled. We + * cannot do that, since we do not have arbitrary jumps. We therefore use + * a funny encoding with two nested `Labeled` blocks. For example, + * {{{ + * x match { + * case 1 if y > 0 => a + * case 2 => b + * case _ => c + * } + * }}} + * arrives at the back-end as + * {{{ + * x match { + * case 1 => + * if (y > 0) + * a + * else + * default() + * case 2 => + * b + * case _ => + * default() { + * c + * } + * } + * }}} + * which we then translate into the following IR: + * {{{ + * matchResult[I]: { + * default[V]: { + * x match { + * case 1 => + * return(matchResult) if (y > 0) + * a + * else + * return(default) (void 0) + * case 2 => + * return(matchResult) b + * case _ => + * () + * } + * } + * c + * } + * }}} + */ + def genMatch(tree: Tree, isStat: Boolean): js.Tree = { + implicit val pos = tree.pos + val Match(selector, cases) = tree + + /* Although GenBCode adapts the scrutinee and the cases to `int`, only + * true `int`s can reach the back-end, as asserted by the String-switch + * transformation in `cleanup`. Therefore, we do not adapt, preserving + * the `string`s and `null`s that come out of the pattern matching in + * Scala 2.13.2+. + */ + val genSelector = genExpr(selector) + + val resultType = + if (isStat) jstpe.NoType + else toIRType(tree.tpe) + + val defaultLabelSym = cases.collectFirst { + case CaseDef(Ident(nme.WILDCARD), EmptyTree, + body @ LabelDef(_, Nil, rhs)) if hasSynthCaseSymbol(body) => + body.symbol + }.getOrElse(NoSymbol) + + var clauses: List[(List[js.MatchableLiteral], js.Tree)] = Nil + var optElseClause: Option[js.Tree] = None + var optElseClauseLabel: Option[js.LabelIdent] = None + + def genJumpToElseClause(implicit pos: ir.Position): js.Tree = { + if (optElseClauseLabel.isEmpty) + optElseClauseLabel = Some(freshLabelIdent("default")) + js.Return(js.Undefined(), optElseClauseLabel.get) + } + + for (caze @ CaseDef(pat, guard, body) <- cases) { + assert(guard == EmptyTree, s"found a case guard at ${caze.pos}") + + def genBody(body: Tree): js.Tree = body match { + case app @ Apply(_, Nil) if app.symbol == defaultLabelSym => + genJumpToElseClause + case Block(List(app @ Apply(_, Nil)), _) if app.symbol == defaultLabelSym => + genJumpToElseClause + + case If(cond, thenp, elsep) => + js.If(genExpr(cond), genBody(thenp), genBody(elsep))( + resultType)(body.pos) + + /* For #1955. If we receive a tree with the shape + * if (cond) { + * thenp + * } else { + * elsep + * } + * scala.runtime.BoxedUnit.UNIT + * we rewrite it as + * if (cond) { + * thenp + * scala.runtime.BoxedUnit.UNIT + * } else { + * elsep + * scala.runtime.BoxedUnit.UNIT + * } + * so that it fits the shape of if/elses we can deal with. + */ + case Block(List(If(cond, thenp, elsep)), s: Select) + if s.symbol == definitions.BoxedUnit_UNIT => + val newThenp = Block(thenp, s).setType(s.tpe).setPos(thenp.pos) + val newElsep = Block(elsep, s).setType(s.tpe).setPos(elsep.pos) + js.If(genExpr(cond), genBody(newThenp), genBody(newElsep))( + resultType)(body.pos) + + case _ => + genStatOrExpr(body, isStat) + } + + def invalidCase(tree: Tree): Nothing = + abort(s"Invalid case in alternative in switch-like pattern match: $tree at: ${tree.pos}") + + def genMatchableLiteral(tree: Literal): js.MatchableLiteral = { + genExpr(tree) match { + case matchableLiteral: js.MatchableLiteral => matchableLiteral + case otherExpr => invalidCase(tree) + } + } + + pat match { + case lit: Literal => + clauses = (List(genMatchableLiteral(lit)), genBody(body)) :: clauses + case Ident(nme.WILDCARD) => + optElseClause = Some(body match { + case LabelDef(_, Nil, rhs) if hasSynthCaseSymbol(body) => + genBody(rhs) + case _ => + genBody(body) + }) + case Alternative(alts) => + val genAlts = { + alts map { + case lit: Literal => genMatchableLiteral(lit) + case _ => invalidCase(tree) + } + } + clauses = (genAlts, genBody(body)) :: clauses + case _ => + invalidCase(tree) + } + } + + val elseClause = optElseClause.getOrElse( + throw new AssertionError("No elseClause in pattern match")) + + /* Builds a `js.Match`, but simplifies it to a `js.If` if there is only + * one case with one alternative, and to a `js.Block` if there is no case + * at all. This happens in practice in the standard library. Having no + * case is a typical product of `match`es that are full of + * `case n if ... =>`, which are used instead of `if` chains for + * convenience and/or readability. + */ + def buildMatch(cases: List[(List[js.MatchableLiteral], js.Tree)], + default: js.Tree, tpe: jstpe.Type): js.Tree = { + + def isInt(tree: js.Tree): Boolean = tree.tpe == jstpe.IntType + + cases match { + case Nil => + /* Completely remove the Match. Preserve the side-effects of + * `genSelector`. + */ + js.Block(exprToStat(genSelector), default) + + case (uniqueAlt :: Nil, caseRhs) :: Nil => + /* Simplify the `match` as an `if`, so that the optimizer has less + * work to do, and we emit less code at the end of the day. + * Use `Int_==` instead of `===` if possible, since it is a common + * case. + */ + val op = + if (isInt(genSelector) && isInt(uniqueAlt)) js.BinaryOp.Int_== + else js.BinaryOp.=== + js.If(js.BinaryOp(op, genSelector, uniqueAlt), caseRhs, default)(tpe) + + case _ => + // We have more than one case: use a js.Match + js.Match(genSelector, cases, default)(tpe) + } + } + + optElseClauseLabel.fold[js.Tree] { + buildMatch(clauses.reverse, elseClause, resultType) + } { elseClauseLabel => + val matchResultLabel = freshLabelIdent("matchResult") + val patchedClauses = for ((alts, body) <- clauses) yield { + implicit val pos = body.pos + val newBody = + if (isStat) js.Block(body, js.Return(js.Undefined(), matchResultLabel)) + else js.Return(body, matchResultLabel) + (alts, newBody) + } + js.Labeled(matchResultLabel, resultType, js.Block(List( + js.Labeled(elseClauseLabel, jstpe.NoType, { + buildMatch(patchedClauses.reverse, js.Skip(), jstpe.NoType) + }), + elseClause + ))) + } + } + + /** Flatten nested Blocks that can be flattened without compromising the + * identification of pattern matches. + */ + private def flatStats(stats: List[Tree]): Iterator[Tree] = { + /* #4581 Never decompose a Block with LabelDef's, as they need to + * be processed by genBlockWithCaseLabelDefs. + */ + stats.iterator.flatMap { + case Block(stats, expr) if !stats.exists(isCaseLabelDef(_)) => + stats.iterator ++ Iterator.single(expr) + case tree => + Iterator.single(tree) + } + } + + /** Predicate satisfied by LabelDefs produced by the pattern matcher, + * except matchEnd's. + */ + private def isCaseLabelDef(tree: Tree): Boolean = { + tree.isInstanceOf[LabelDef] && hasSynthCaseSymbol(tree) && + !tree.symbol.name.startsWith("matchEnd") + } + + /** Predicate satisfied by matchEnd LabelDefs produced by the pattern + * matcher. + */ + private def isMatchEndLabelDef(tree: LabelDef): Boolean = + hasSynthCaseSymbol(tree) && tree.symbol.name.startsWith("matchEnd") + + private def genBlock(tree: Block, isStat: Boolean): js.Tree = { + implicit val pos = tree.pos + val Block(stats, expr) = tree + + val genStatsAndExpr = if (!stats.exists(isCaseLabelDef(_))) { + // #4684 Collapse { ; BoxedUnit } to + val genStatsAndExpr0 = stats.map(genStat(_)) :+ genStatOrExpr(expr, isStat) + genStatsAndExpr0 match { + case (undefParam @ js.Transient(UndefinedParam)) :: js.Undefined() :: Nil => + undefParam :: Nil + case _ => + genStatsAndExpr0 + } + } else { + genBlockWithCaseLabelDefs(stats :+ expr, isStat) + } + + /* A bit of dead code elimination: we drop all statements and + * expressions after the first statement of type `NothingType`. + * This helps other optimizations. + */ + val (nonNothing, rest) = genStatsAndExpr.span(_.tpe != jstpe.NothingType) + if (rest.isEmpty || rest.tail.isEmpty) + js.Block(genStatsAndExpr) + else + js.Block(nonNothing, rest.head) + } + + private def genBlockWithCaseLabelDefs(trees: List[Tree], isStat: Boolean)( + implicit pos: Position): List[js.Tree] = { + + val (prologue, casesAndRest) = trees.span(!isCaseLabelDef(_)) + + if (casesAndRest.isEmpty) { + if (prologue.isEmpty) Nil + else if (isStat) prologue.map(genStat(_)) + else prologue.init.map(genStat(_)) :+ genExpr(prologue.last) + } else { + val genPrologue = prologue.map(genStat(_)) + + val (cases0, rest) = casesAndRest.span(isCaseLabelDef(_)) + val cases = cases0.asInstanceOf[List[LabelDef]] + + val genCasesAndRest = rest match { + case (matchEnd: LabelDef) :: more if isMatchEndLabelDef(matchEnd) => + val translatedMatch = genTranslatedMatch(cases, matchEnd) + translatedMatch :: genBlockWithCaseLabelDefs(more, isStat) + + // Sometimes the pattern matcher casts its final result + case Apply(TypeApply(Select(matchEnd: LabelDef, nme.asInstanceOf_Ob), + List(targ)), Nil) :: more + if isMatchEndLabelDef(matchEnd) => + val translatedMatch = genTranslatedMatch(cases, matchEnd) + genIsAsInstanceOf(translatedMatch, matchEnd.tpe, targ.tpe, + cast = true) :: genBlockWithCaseLabelDefs(more, isStat) + + // Peculiar shape generated by `return x match {...}` - #2928 + case Return(matchEnd: LabelDef) :: more if isMatchEndLabelDef(matchEnd) => + val translatedMatch = genTranslatedMatch(cases, matchEnd) + val genMore = genBlockWithCaseLabelDefs(more, isStat) + val label = getEnclosingReturnLabel() + if (translatedMatch.tpe == jstpe.NoType) { + // Could not actually reproduce this, but better be safe than sorry + translatedMatch :: js.Return(js.Undefined(), label) :: genMore + } else { + js.Return(translatedMatch, label) :: genMore + } + + // Otherwise, there is no matchEnd, only consecutive cases + case Nil => + genTranslatedCases(cases, isStat) + case _ => + genTranslatedCases(cases, isStat = false) ::: genBlockWithCaseLabelDefs(rest, isStat) + } + + genPrologue ::: genCasesAndRest + } + } + + /** Gen JS code for a translated match. + * + * A translated match consists of consecutive `case` LabelDefs directly + * followed by a `matchEnd` LabelDef. + */ + private def genTranslatedMatch(cases: List[LabelDef], matchEnd: LabelDef)( + implicit pos: Position): js.Tree = { + genMatchEnd(matchEnd) { + genTranslatedCases(cases, isStat = true) + } + } + + /** Gen JS code for the cases of a patmat-transformed match. + * + * This implementation relies heavily on the patterns of trees emitted + * by the pattern match phase, including its variants across versions of + * scalac that we support. + * + * The trees output by the pattern matcher are assumed to follow these + * rules: + * + * - Each case LabelDef (in `cases`) must not take any argument. + * - Jumps to case label-defs are restricted to jumping to the very next + * case. + * + * There is an optimization to avoid generating jumps that are in tail + * position of a case, if they are in positions denoted by in: + * {{{ + * ::= + * If(_, , ) + * | Block(_, ) + * | + * | _ + * }}} + * Since all but the last case (which cannot have jumps) are in statement + * position, those jumps in tail position can be replaced by `skip`. + */ + private def genTranslatedCases(cases: List[LabelDef], isStat: Boolean)( + implicit pos: Position): List[js.Tree] = { + + assert(!cases.isEmpty, + s"genTranslatedCases called with no cases at $pos") + + val translatedCasesInit = for { + (caseLabelDef, nextCaseSym) <- cases.zip(cases.tail.map(_.symbol)) + } yield { + implicit val pos = caseLabelDef.pos + assert(caseLabelDef.params.isEmpty, + s"found case LabelDef with parameters at $pos") + + val info = new EnclosingLabelDefInfoWithResultAsAssigns(Nil) + + val translatedBody = withScopedVars( + enclosingLabelDefInfos := + enclosingLabelDefInfos.get + (nextCaseSym -> info) + ) { + /* Eager optimization of jumps in tail position, following the shapes + * produced by scala until 2.12.8. 2.12.9 introduced flat patmat + * translation, which does not trigger those optimizations. + * These shapes are also often produced by the async transformation. + */ + def genCaseBody(tree: Tree): js.Tree = { + implicit val pos = tree.pos + tree match { + case If(cond, thenp, elsep) => + js.If(genExpr(cond), genCaseBody(thenp), genCaseBody(elsep))( + jstpe.NoType) + + case Block(stats, Literal(Constant(()))) => + // Generated a lot by the async transform + if (stats.isEmpty) js.Skip() + else js.Block(stats.init.map(genStat(_)), genCaseBody(stats.last)) + + case Block(stats, expr) => + js.Block((stats map genStat) :+ genCaseBody(expr)) + + case Apply(_, Nil) if tree.symbol == nextCaseSym => + js.Skip() + + case _ => + genStat(tree) + } + } + + genCaseBody(caseLabelDef.rhs) + } + + genOptimizedCaseLabeled(encodeLabelSym(nextCaseSym), translatedBody, + info.generatedReturns) + } + + val translatedLastCase = genStatOrExpr(cases.last.rhs, isStat) + + translatedCasesInit :+ translatedLastCase + } + + /** Gen JS code for a match-end label def following match-cases. + * + * The preceding cases, which are allowed to jump to this match-end, must + * be generated in the `genTranslatedCases` callback. During the execution + * of this callback, the enclosing label infos contain appropriate info + * for this match-end. + * + * The translation of the match-end itself is straightforward, but is + * augmented with several optimizations to remove as many labeled blocks + * as possible. + * + * Most of the time, a match-end label has exactly one parameter. However, + * with the async transform, it can sometimes have no parameter instead. + * We handle those cases very differently. + */ + private def genMatchEnd(matchEnd: LabelDef)( + genTranslatedCases: => List[js.Tree])( + implicit pos: Position): js.Tree = { + + val sym = matchEnd.symbol + val labelIdent = encodeLabelSym(sym) + val matchEndBody = matchEnd.rhs + + def genMatchEndBody(): js.Tree = { + genStatOrExpr(matchEndBody, + isStat = toIRType(matchEndBody.tpe) == jstpe.NoType) + } + + matchEnd.params match { + // Optimizable common case produced by the regular pattern matcher + case List(matchEndParam) => + val info = new EnclosingLabelDefInfoWithResultAsReturn() + + val translatedCases = withScopedVars( + enclosingLabelDefInfos := enclosingLabelDefInfos.get + (sym -> info) + ) { + genTranslatedCases + } + + val innerResultType = toIRType(matchEndParam.tpe) + val optimized = genOptimizedMatchEndLabeled(encodeLabelSym(sym), + innerResultType, translatedCases, info.generatedReturns) + + matchEndBody match { + case Ident(_) if matchEndParam.symbol == matchEndBody.symbol => + // matchEnd is identity. + optimized + + case Literal(Constant(())) => + // Unit return type. + optimized + + case _ => + // matchEnd does something. + js.Block( + js.VarDef(encodeLocalSym(matchEndParam.symbol), + originalNameOfLocal(matchEndParam.symbol), + innerResultType, mutable = false, optimized), + genMatchEndBody()) + } + + /* Other cases, notably the matchEnd's produced by the async transform, + * which have no parameters. The case of more than one parameter is + * hypothetical, but it costs virtually nothing to handle it here. + */ + case params => + val paramSyms = params.map(_.symbol) + val varDefs = for (s <- paramSyms) yield { + implicit val pos = s.pos + val irType = toIRType(s.tpe) + js.VarDef(encodeLocalSym(s), originalNameOfLocal(s), irType, + mutable = true, jstpe.zeroOf(irType)) + } + val info = new EnclosingLabelDefInfoWithResultAsAssigns(paramSyms) + val translatedCases = withScopedVars( + enclosingLabelDefInfos := enclosingLabelDefInfos.get + (sym -> info) + ) { + genTranslatedCases + } + val optimized = genOptimizedMatchEndLabeled(labelIdent, jstpe.NoType, + translatedCases, info.generatedReturns) + js.Block(varDefs ::: optimized :: genMatchEndBody() :: Nil) + } + } + + /** Gen JS code for a Labeled block from a pattern match'es case, while + * trying to optimize it away as a reversed If. + * + * If there was no `return` to the label at all, simply avoid generating + * the `Labeled` block altogether. + * + * If there was more than one `return`, do not optimize anything, as + * nothing could be good enough for `genOptimizedMatchEndLabeled` to do + * anything useful down the line. + * + * If however there was a single `return`, we try and get rid of it by + * identifying the following shape: + * + * {{{ + * { + * ...stats1 + * if (test) + * return(nextCaseSym) + * ...stats2 + * } + * }}} + * + * which we then rewrite as + * + * {{{ + * { + * ...stats1 + * if (!test) { + * ...stats2 + * } + * } + * }}} + * + * The above rewrite is important for `genOptimizedMatchEndLabeled` below + * to be able to do its job, which in turn is important for the IR + * optimizer to perform a better analysis. + * + * This whole thing is only necessary in Scala 2.12.9+, with the new flat + * patmat ASTs. In previous versions, `returnCount` is always 0 because + * all jumps to case labels are already caught upstream by `genCaseBody()` + * inside `genTranslatedMatch()`. + */ + private def genOptimizedCaseLabeled(label: js.LabelIdent, + translatedBody: js.Tree, returnCount: Int)( + implicit pos: Position): js.Tree = { + + def default: js.Tree = + js.Labeled(label, jstpe.NoType, translatedBody) + + if (returnCount == 0) { + translatedBody + } else if (returnCount > 1) { + default + } else { + translatedBody match { + case js.Block(stats) => + val (stats1, testAndStats2) = stats.span { + case js.If(_, js.Return(js.Undefined(), `label`), js.Skip()) => + false + case _ => + true + } + + testAndStats2 match { + case js.If(cond, _, _) :: stats2 => + val notCond = cond match { + case js.UnaryOp(js.UnaryOp.Boolean_!, notCond) => + notCond + case _ => + js.UnaryOp(js.UnaryOp.Boolean_!, cond) + } + js.Block(stats1 :+ js.If(notCond, js.Block(stats2), js.Skip())(jstpe.NoType)) + + case _ :: _ => + throw new AssertionError("unreachable code") + + case Nil => + default + } + + case _ => + default + } + } + } + + /** Gen JS code for a Labeled block from a pattern match'es match-end, + * while trying to optimize it away as an If chain. + * + * It is important to do so at compile-time because, when successful, the + * resulting IR can be much better optimized by the optimizer. + * + * The optimizer also does something similar, but *after* it has processed + * the body of the Labeled block, at which point it has already lost any + * information about stack-allocated values. + * + * !!! There is quite of bit of code duplication with + * OptimizerCore.tryOptimizePatternMatch. + */ + def genOptimizedMatchEndLabeled(label: js.LabelIdent, tpe: jstpe.Type, + translatedCases: List[js.Tree], returnCount: Int)( + implicit pos: Position): js.Tree = { + def default: js.Tree = + js.Labeled(label, tpe, js.Block(translatedCases)) + + @tailrec + def createRevAlts(xs: List[js.Tree], + acc: List[(js.Tree, js.Tree)]): (List[(js.Tree, js.Tree)], js.Tree) = xs match { + case js.If(cond, body, js.Skip()) :: xr => + createRevAlts(xr, (cond, body) :: acc) + case remaining => + (acc, js.Block(remaining)(remaining.head.pos)) + } + val (revAlts, elsep) = createRevAlts(translatedCases, Nil) + + if (revAlts.size == returnCount - 1) { + def tryDropReturn(body: js.Tree): Option[js.Tree] = body match { + case js.Return(result, `label`) => + Some(result) + + case js.Block(prep :+ js.Return(result, `label`)) => + Some(js.Block(prep :+ result)(body.pos)) + + case _ => + None + } + + @tailrec + def constructOptimized(revAlts: List[(js.Tree, js.Tree)], + elsep: js.Tree): js.Tree = { + revAlts match { + case (cond, body) :: revAltsRest => + // cannot use flatMap due to tailrec + tryDropReturn(body) match { + case Some(newBody) => + constructOptimized(revAltsRest, + js.If(cond, newBody, elsep)(tpe)(cond.pos)) + + case None => + default + } + case Nil => + elsep + } + } + + tryDropReturn(elsep).fold(default)(constructOptimized(revAlts, _)) + } else { + default + } + } + + /** Gen JS code for a primitive method call */ + private def genPrimitiveOp(tree: Apply, isStat: Boolean): js.Tree = { + import scalaPrimitives._ + + implicit val pos = tree.pos + + val sym = tree.symbol + val Apply(fun @ Select(receiver, _), args) = tree + + val code = scalaPrimitives.getPrimitive(sym, receiver.tpe) + + if (isArithmeticOp(code) || isLogicalOp(code) || isComparisonOp(code)) + genSimpleOp(tree, receiver :: args, code) + else if (code == scalaPrimitives.CONCAT) + genStringConcat(tree, receiver, args) + else if (code == HASH) + genScalaHash(tree, receiver) + else if (isArrayOp(code)) + genArrayOp(tree, code) + else if (code == SYNCHRONIZED) + genSynchronized(receiver, args.head, isStat) + else if (isCoercion(code)) + genCoercion(tree, receiver, code) + else if (jsPrimitives.isJavaScriptPrimitive(code)) + genJSPrimitive(tree, args, code, isStat) + else + abort("Unknown primitive operation: " + sym.fullName + "(" + + fun.symbol.simpleName + ") " + " at: " + (tree.pos)) + } + + private def genPrimitiveOpForReflectiveCall(sym: Symbol, receiver: js.Tree, + args: List[js.Tree])( + implicit pos: Position): js.Tree = { + + import scalaPrimitives._ + + if (!isPrimitive(sym)) { + abort( + "Trying to reflectively call a method of a primitive type that " + + "is not itself a primitive method: " + sym.fullName + " at " + pos) + } + val code = getPrimitive(sym) + + if (isArithmeticOp(code) || isLogicalOp(code) || isComparisonOp(code)) { + genSimpleOp(sym.owner.tpe :: sym.tpe.paramTypes, sym.tpe.resultType, + receiver :: args, code) + } else if (code == CONCAT) { + js.BinaryOp(js.BinaryOp.String_+, receiver, args.head) + } else if (isCoercion(code)) { + adaptPrimitive(receiver, toIRType(sym.tpe.resultType)) + } else { + abort( + "Unknown primitive operation for reflective call: " + sym.fullName + + " at " + pos) + } + } + + /** Gen JS code for a simple operation (arithmetic, logical, or comparison) */ + private def genSimpleOp(tree: Apply, args: List[Tree], code: Int): js.Tree = { + implicit val pos = tree.pos + + genSimpleOp(args.map(_.tpe), tree.tpe, args.map(genExpr), code) + } + + /** Gen JS code for a simple operation (arithmetic, logical, or comparison) */ + private def genSimpleOp(argTpes: List[Type], resultTpe: Type, + sources: List[js.Tree], code: Int)( + implicit pos: Position): js.Tree = { + + import scalaPrimitives._ + + sources match { + // Unary operation + case List(src_in) => + val opType = toIRType(resultTpe) + val src = adaptPrimitive(src_in, opType) + + (code match { + case POS => + src + case NEG => + (opType: @unchecked) match { + case jstpe.IntType => + js.BinaryOp(js.BinaryOp.Int_-, js.IntLiteral(0), src) + case jstpe.LongType => + js.BinaryOp(js.BinaryOp.Long_-, js.LongLiteral(0), src) + case jstpe.FloatType => + js.BinaryOp(js.BinaryOp.Float_*, js.FloatLiteral(-1.0f), src) + case jstpe.DoubleType => + js.BinaryOp(js.BinaryOp.Double_*, js.DoubleLiteral(-1.0), src) + } + case NOT => + (opType: @unchecked) match { + case jstpe.IntType => + js.BinaryOp(js.BinaryOp.Int_^, js.IntLiteral(-1), src) + case jstpe.LongType => + js.BinaryOp(js.BinaryOp.Long_^, js.LongLiteral(-1), src) + } + case ZNOT => + js.UnaryOp(js.UnaryOp.Boolean_!, src) + case _ => + abort("Unknown unary operation code: " + code) + }) + + // Binary operation + case List(lsrc_in, rsrc_in) => + import js.BinaryOp._ + + val isShift = isShiftOp(code) + val leftIRType = toIRType(argTpes(0)) + val rightIRType = toIRType(argTpes(1)) + + val opType = { + if (isShift) { + if (leftIRType == jstpe.LongType) jstpe.LongType + else jstpe.IntType + } else { + (leftIRType, rightIRType) match { + case (jstpe.DoubleType, _) | (_, jstpe.DoubleType) => + jstpe.DoubleType + case (jstpe.FloatType, _) | (_, jstpe.FloatType) => + jstpe.FloatType + case (jstpe.LongType, _) | (_, jstpe.LongType) => + jstpe.LongType + case (jstpe.IntType | jstpe.CharType | jstpe.ByteType | jstpe.ShortType, _) | + (_, jstpe.IntType | jstpe.CharType | jstpe.ByteType | jstpe.ShortType) => + jstpe.IntType + case (jstpe.BooleanType, _) | (_, jstpe.BooleanType) => + jstpe.BooleanType + case _ => + jstpe.AnyType + } + } + } + + val lsrc = + if (opType == jstpe.AnyType) lsrc_in + else adaptPrimitive(lsrc_in, opType) + val rsrc = + if (opType == jstpe.AnyType) rsrc_in + else adaptPrimitive(rsrc_in, if (isShift) jstpe.IntType else opType) + + (opType: @unchecked) match { + case jstpe.IntType => + val op = (code: @switch) match { + case ADD => Int_+ + case SUB => Int_- + case MUL => Int_* + case DIV => Int_/ + case MOD => Int_% + case OR => Int_| + case AND => Int_& + case XOR => Int_^ + case LSL => Int_<< + case LSR => Int_>>> + case ASR => Int_>> + case EQ => Int_== + case NE => Int_!= + case LT => Int_< + case LE => Int_<= + case GT => Int_> + case GE => Int_>= + } + js.BinaryOp(op, lsrc, rsrc) + + case jstpe.LongType => + val op = (code: @switch) match { + case ADD => Long_+ + case SUB => Long_- + case MUL => Long_* + case DIV => Long_/ + case MOD => Long_% + case OR => Long_| + case XOR => Long_^ + case AND => Long_& + case LSL => Long_<< + case LSR => Long_>>> + case ASR => Long_>> + case EQ => Long_== + case NE => Long_!= + case LT => Long_< + case LE => Long_<= + case GT => Long_> + case GE => Long_>= + } + js.BinaryOp(op, lsrc, rsrc) + + case jstpe.FloatType => + def withFloats(op: Int): js.Tree = + js.BinaryOp(op, lsrc, rsrc) + + def toDouble(value: js.Tree): js.Tree = + js.UnaryOp(js.UnaryOp.FloatToDouble, value) + + def withDoubles(op: Int): js.Tree = + js.BinaryOp(op, toDouble(lsrc), toDouble(rsrc)) + + (code: @switch) match { + case ADD => withFloats(Float_+) + case SUB => withFloats(Float_-) + case MUL => withFloats(Float_*) + case DIV => withFloats(Float_/) + case MOD => withFloats(Float_%) + + case EQ => withDoubles(Double_==) + case NE => withDoubles(Double_!=) + case LT => withDoubles(Double_<) + case LE => withDoubles(Double_<=) + case GT => withDoubles(Double_>) + case GE => withDoubles(Double_>=) + } + + case jstpe.DoubleType => + val op = (code: @switch) match { + case ADD => Double_+ + case SUB => Double_- + case MUL => Double_* + case DIV => Double_/ + case MOD => Double_% + case EQ => Double_== + case NE => Double_!= + case LT => Double_< + case LE => Double_<= + case GT => Double_> + case GE => Double_>= + } + js.BinaryOp(op, lsrc, rsrc) + + case jstpe.BooleanType => + (code: @switch) match { + case OR => + js.BinaryOp(Boolean_|, lsrc, rsrc) + case AND => + js.BinaryOp(Boolean_&, lsrc, rsrc) + case EQ => + js.BinaryOp(Boolean_==, lsrc, rsrc) + case XOR | NE => + js.BinaryOp(Boolean_!=, lsrc, rsrc) + case ZOR => + js.If(lsrc, js.BooleanLiteral(true), rsrc)(jstpe.BooleanType) + case ZAND => + js.If(lsrc, rsrc, js.BooleanLiteral(false))(jstpe.BooleanType) + } + + case jstpe.AnyType => + def genAnyEquality(eqeq: Boolean, not: Boolean): js.Tree = { + // Arrays, Null, Nothing never have a custom equals() method + def canHaveCustomEquals(tpe: jstpe.Type): Boolean = tpe match { + case jstpe.AnyType | jstpe.ClassType(_) => true + case _ => false + } + if (eqeq && + // don't call equals if we have a literal null at either side + !lsrc.isInstanceOf[js.Null] && + !rsrc.isInstanceOf[js.Null] && + canHaveCustomEquals(leftIRType)) { + val body = genEqEqPrimitive(argTpes(0), argTpes(1), lsrc, rsrc) + if (not) js.UnaryOp(js.UnaryOp.Boolean_!, body) else body + } else { + js.BinaryOp( + if (not) js.BinaryOp.!== else js.BinaryOp.===, + lsrc, rsrc) + } + } + + (code: @switch) match { + case EQ => genAnyEquality(eqeq = true, not = false) + case NE => genAnyEquality(eqeq = true, not = true) + case ID => genAnyEquality(eqeq = false, not = false) + case NI => genAnyEquality(eqeq = false, not = true) + } + } + + case _ => + abort("Too many arguments for primitive function at " + pos) + } + } + + /** See comment in `genEqEqPrimitive()` about `mustUseAnyComparator`. */ + private lazy val shouldPreserveEqEqBugWithJLFloatDouble = { + val v = scala.util.Properties.versionNumberString + v.startsWith("2.11.") || v == "2.12.1" + } + + /** Gen JS code for a call to Any.== */ + def genEqEqPrimitive(ltpe: Type, rtpe: Type, lsrc: js.Tree, rsrc: js.Tree)( + implicit pos: Position): js.Tree = { + /* True if the equality comparison is between values that require the + * use of the rich equality comparator + * (scala.runtime.BoxesRunTime.equals). + * This is the case when either side of the comparison might have a + * run-time type subtype of java.lang.Number or java.lang.Character, + * **which includes when either is a JS type**. + * + * When it is statically known that both sides are equal and subtypes of + * Number or Character, not using the rich equality is possible (their + * own equals method will do ok), except for java.lang.Float and + * java.lang.Double: their `equals` have different behavior around `NaN` + * and `-0.0`, see Javadoc (scala-dev#329, #2799). + * + * The latter case is only avoided in 2.12.2+, to remain bug-compatible + * with the Scala/JVM compiler. + */ + val mustUseAnyComparator: Boolean = { + val lsym = ltpe.typeSymbol + val rsym = rtpe.typeSymbol + isJSType(lsym) || isJSType(rsym) || { + isMaybeBoxed(lsym) && isMaybeBoxed(rsym) && { + val areSameFinals = + ltpe.isFinalType && rtpe.isFinalType && lsym == rsym + !areSameFinals || { + (lsym == BoxedFloatClass || lsym == BoxedDoubleClass) && { + // Bug-compatibility for Scala < 2.12.2 + !shouldPreserveEqEqBugWithJLFloatDouble + } + } + } + } + } + + if (mustUseAnyComparator) { + val equalsMethod: Symbol = { + // scalastyle:off line.size.limit + if (ltpe <:< BoxedNumberClass.tpe) { + if (rtpe <:< BoxedNumberClass.tpe) platform.externalEqualsNumNum + else if (rtpe <:< BoxedCharacterClass.tpe) platform.externalEqualsNumObject // will be externalEqualsNumChar in 2.12, SI-9030 + else platform.externalEqualsNumObject + } else platform.externalEquals + // scalastyle:on line.size.limit + } + if (BoxesRunTimeClass.isJavaDefined) + genApplyStatic(equalsMethod, List(lsrc, rsrc)) + else // this happens when in the same compilation run as BoxesRunTime + genApplyMethod(genLoadModule(BoxesRunTimeClass), equalsMethod, List(lsrc, rsrc)) + } else { + // if (lsrc eq null) rsrc eq null else lsrc.equals(rsrc) + if (isStringType(ltpe)) { + // String.equals(that) === (this eq that) + js.BinaryOp(js.BinaryOp.===, lsrc, rsrc) + } else { + /* This requires to evaluate both operands in local values first. + * The optimizer will eliminate them if possible. + */ + val ltemp = js.VarDef(freshLocalIdent(), NoOriginalName, lsrc.tpe, + mutable = false, lsrc) + val rtemp = js.VarDef(freshLocalIdent(), NoOriginalName, rsrc.tpe, + mutable = false, rsrc) + js.Block( + ltemp, + rtemp, + js.If(js.BinaryOp(js.BinaryOp.===, ltemp.ref, js.Null()), + js.BinaryOp(js.BinaryOp.===, rtemp.ref, js.Null()), + genApplyMethod(ltemp.ref, Object_equals, List(rtemp.ref)))( + jstpe.BooleanType)) + } + } + } + + /** Gen JS code for string concatenation. + */ + private def genStringConcat(tree: Apply, receiver: Tree, + args: List[Tree]): js.Tree = { + implicit val pos = tree.pos + + /* Primitive number types such as scala.Int have a + * def +(s: String): String + * method, which is why we have to box the lhs sometimes. + * Otherwise, both lhs and rhs are already reference types (Any of String) + * so boxing is not necessary (in particular, rhs is never a primitive). + */ + assert(!isPrimitiveValueType(receiver.tpe) || isStringType(args.head.tpe), + s"unexpected signature for string-concat call at $pos") + assert(!isPrimitiveValueType(args.head.tpe), + s"unexpected signature for string-concat call at $pos") + + val rhs = genExpr(args.head) + + val lhs = { + val lhs0 = genExpr(receiver) + // Box the receiver if it is a primitive value + if (!isPrimitiveValueType(receiver.tpe)) lhs0 + else makePrimitiveBox(lhs0, receiver.tpe) + } + + js.BinaryOp(js.BinaryOp.String_+, lhs, rhs) + } + + /** Gen JS code for a call to `Any.##`. + * + * This method unconditionally generates a call to `Statics.anyHash`. + * On the JVM, `anyHash` is only called as of 2.12.0-M5. Previous versions + * emitted a call to `ScalaRunTime.hash`. However, since our `anyHash` + * is always consistent with `ScalaRunTime.hash`, we always use it. + */ + private def genScalaHash(tree: Apply, receiver: Tree): js.Tree = { + implicit val pos = tree.pos + + val instance = genLoadModule(RuntimeStaticsModule) + val arguments = List(genExpr(receiver)) + val sym = getMember(RuntimeStaticsModule, jsnme.anyHash) + + genApplyMethod(instance, sym, arguments) + } + + /** Gen JS code for an array operation (get, set or length) */ + private def genArrayOp(tree: Tree, code: Int): js.Tree = { + import scalaPrimitives._ + + implicit val pos = tree.pos + + val Apply(fun @ Select(arrayObj, _), args) = tree + val arrayValue = genExpr(arrayObj) + val arguments = args map genExpr + + def genSelect(elemType: Type) = + js.ArraySelect(arrayValue, arguments(0))(toIRType(elemType)) + + if (scalaPrimitives.isArrayGet(code)) { + // get an item of the array + assert(args.length == 1, + s"Array get requires 1 argument, found ${args.length} in $tree") + genSelect(fun.tpe.resultType) + } else if (scalaPrimitives.isArraySet(code)) { + // set an item of the array + assert(args.length == 2, + s"Array set requires 2 arguments, found ${args.length} in $tree") + js.Assign(genSelect(fun.tpe.paramTypes(1)), arguments(1)) + } else { + // length of the array + js.ArrayLength(arrayValue) + } + } + + /** Gen JS code for a call to AnyRef.synchronized */ + private def genSynchronized(receiver: Tree, arg: Tree, isStat: Boolean)( + implicit pos: Position): js.Tree = { + /* JavaScript is single-threaded, so we can drop the + * synchronization altogether. + */ + val newReceiver = genExpr(receiver) + val newArg = genStatOrExpr(arg, isStat) + newReceiver match { + case js.This() => + // common case for which there is no side-effect nor NPE + newArg + case _ => + val NPECtor = getMemberMethod(NullPointerExceptionClass, + nme.CONSTRUCTOR).suchThat(_.tpe.params.isEmpty) + js.Block( + js.If(js.BinaryOp(js.BinaryOp.===, newReceiver, js.Null()), + js.Throw(genNew(NullPointerExceptionClass, NPECtor, Nil)), + js.Skip())(jstpe.NoType), + newArg) + } + } + + /** Gen JS code for a coercion */ + private def genCoercion(tree: Apply, receiver: Tree, code: Int): js.Tree = { + implicit val pos = tree.pos + + val source = genExpr(receiver) + val resultType = toIRType(tree.tpe) + adaptPrimitive(source, resultType) + } + + /** Gen JS code for an ApplyDynamic + * ApplyDynamic nodes appear as the result of calls to methods of a + * structural type. + * + * Most unfortunately, earlier phases of the compiler assume too much + * about the backend, namely, they believe arguments and the result must + * be boxed, and do the boxing themselves. This decision should be left + * to the backend, but it's not, so we have to undo these boxes. + * Note that this applies to parameter types only. The return type is boxed + * anyway since we do not know it's exact type. + * + * This then generates a call to the reflective call proxy for the given + * arguments. + */ + private def genApplyDynamic(tree: ApplyDynamic): js.Tree = { + implicit val pos = tree.pos + + val sym = tree.symbol + val name = sym.name + val params = sym.tpe.params + + /* Is this a primitive method introduced in AnyRef? + * The concerned methods are `eq`, `ne` and `synchronized`. + * + * If it is, it can be defined in a custom value class. Calling it + * reflectively works on the JVM in that case. However, it does not work + * if the reflective call should in fact resolve to the method in + * `AnyRef` (it causes a `NoSuchMethodError`). We maintain bug + * compatibility for these methods: they work if redefined in a custom + * AnyVal, and fail at run-time (with a `TypeError`) otherwise. + */ + val isAnyRefPrimitive = { + (name == nme.eq || name == nme.ne || name == nme.synchronized_) && + params.size == 1 && params.head.tpe.typeSymbol == ObjectClass + } + + /** check if the method we are invoking conforms to a method on + * scala.Array. If this is the case, we check that case specially at + * runtime to avoid having reflective call proxies on scala.Array. + * (Also, note that the element type of Array#update is not erased and + * therefore the method name mangling would turn out wrong) + * + * Note that we cannot check if the expected return type is correct, + * since this type information is already erased. + */ + def isArrayLikeOp = name match { + case nme.update => + params.size == 2 && params.head.tpe.typeSymbol == IntClass + case nme.apply => + params.size == 1 && params.head.tpe.typeSymbol == IntClass + case nme.length => + params.size == 0 + case nme.clone_ => + params.size == 0 + case _ => + false + } + + /** + * Tests whether one of our reflective "boxes" for primitive types + * implements the particular method. If this is the case + * (result != NoSymbol), we generate a runtime instance check if we are + * dealing with the appropriate primitive type. + */ + def matchingSymIn(clazz: Symbol) = clazz.tpe.member(name).suchThat { s => + val sParams = s.tpe.params + !s.isBridge && + params.size == sParams.size && + (params zip sParams).forall { case (s1,s2) => + s1.tpe =:= s2.tpe + } + } + + val ApplyDynamic(receiver, args) = tree + + val receiverType = toIRType(receiver.tpe) + val callTrgIdent = freshLocalIdent() + val callTrgVarDef = js.VarDef(callTrgIdent, NoOriginalName, receiverType, + mutable = false, genExpr(receiver)) + val callTrg = js.VarRef(callTrgIdent)(receiverType) + + val arguments = args zip sym.tpe.params map { case (arg, param) => + /* No need for enteringPosterasure, because value classes are not + * supported as parameters of methods in structural types. + * We could do it for safety and future-proofing anyway, except that + * I am weary of calling enteringPosterasure for a reflective method + * symbol. + * + * Note also that this will typically unbox a primitive value that + * has just been boxed, or will .asInstanceOf[T] an expression which + * is already of type T. But the optimizer will get rid of that, and + * reflective calls are not numerous, so we don't complicate the + * compiler to eliminate them early. + */ + fromAny(genExpr(arg), param.tpe) + } + + var callStatement: js.Tree = js.Apply(js.ApplyFlags.empty, callTrg, + encodeMethodSym(sym, reflProxy = true), arguments)(jstpe.AnyType) + + if (!isAnyRefPrimitive) { + def boxIfNeeded(call: js.Tree, returnType: Type): js.Tree = { + if (isPrimitiveValueType(returnType)) + makePrimitiveBox(call, returnType) + else + call + } + + if (isArrayLikeOp) { + def genRTCall(method: Symbol, args: js.Tree*) = + genApplyMethod(genLoadModule(ScalaRunTimeModule), + method, args.toList) + val isArrayTree = + genRTCall(ScalaRunTime_isArray, callTrg, js.IntLiteral(1)) + callStatement = js.If(isArrayTree, { + name match { + case nme.update => + js.Block( + genRTCall(currentRun.runDefinitions.arrayUpdateMethod, + callTrg, arguments(0), arguments(1)), + js.Undefined()) // Boxed Unit + case nme.apply => + genRTCall(currentRun.runDefinitions.arrayApplyMethod, callTrg, + arguments(0)) + case nme.length => + genRTCall(currentRun.runDefinitions.arrayLengthMethod, callTrg) + case nme.clone_ => + genApplyMethod(callTrg, Object_clone, arguments) + } + }, { + callStatement + })(jstpe.AnyType) + } + + /* Add an explicit type test for a hijacked class with a call to a + * hijacked method, if applicable (i.e., if there is a matching method + * in the given hijacked class). This is necessary because hijacked + * classes of the IR do not support reflective proxy calls. + * + * Returns true if this treatment was applicable. + */ + def addCallToHijackedMethodIfApplicable(hijackedClass: Symbol): Boolean = { + val hijackedMethod = matchingSymIn(hijackedClass) + val isApplicable = + hijackedMethod != NoSymbol && hijackedMethod.isPublic + if (isApplicable) { + val hijackedClassTpe = hijackedClass.tpe + callStatement = js.If(genIsInstanceOf(callTrg, hijackedClassTpe), { + boxIfNeeded( + genApplyMethod(genAsInstanceOf(callTrg, hijackedClassTpe), + hijackedMethod, arguments), + hijackedMethod.tpe.resultType) + }, { // else + callStatement + })(jstpe.AnyType) + } + isApplicable + } + + // String is a hijacked class + addCallToHijackedMethodIfApplicable(StringClass) + + /* For primitive types, we need to handle two cases. The method could + * either be defined in the boxed class of the primitive type (which is + * hijacked), or it could be defined in the primitive class itself. + * If the hijacked class treatment is not applicable, we also try the + * primitive treatment, in which case we directly generate the + * primitive operation. + */ + + def addCallForPrimitive(primitiveClass: Symbol): Boolean = { + val boxedClass = definitions.boxedClass(primitiveClass) + if (addCallToHijackedMethodIfApplicable(boxedClass)) { + true + } else { + val methodInPrimClass = matchingSymIn(primitiveClass) + if (methodInPrimClass != NoSymbol && methodInPrimClass.isPublic) { + def isIntOrLong(tpe: jstpe.Type): Boolean = tpe match { + case jstpe.ByteType | jstpe.ShortType | jstpe.IntType | jstpe.LongType => + true + case _ => + false + } + val ignoreBecauseItMustBeAnInt = { + primitiveClass == DoubleClass && + toIRType(methodInPrimClass.tpe.resultType) == jstpe.DoubleType && + isIntOrLong(toIRType(sym.tpe.resultType)) + } + if (ignoreBecauseItMustBeAnInt) { + // Fall through to the Int case that will come next + false + } else { + val boxedTpe = boxedClass.tpe + callStatement = js.If(genIsInstanceOf(callTrg, boxedTpe), { + val castCallTrg = + makePrimitiveUnbox(callTrg, primitiveClass.tpe) + val call = genPrimitiveOpForReflectiveCall(methodInPrimClass, + castCallTrg, arguments) + boxIfNeeded(call, methodInPrimClass.tpe.resultType) + }, { // else + callStatement + })(jstpe.AnyType) + true + } + } else { + false + } + } + } + + addCallForPrimitive(BooleanClass) + addCallForPrimitive(LongClass) + addCallForPrimitive(CharClass) + + /* For primitive numeric types that box as JS numbers, find the first + * one that matches. It will be able to handle the subsequent cases. + */ + Seq(DoubleClass, IntClass, FloatClass, ShortClass, ByteClass).find( + addCallForPrimitive) + } + + js.Block(callTrgVarDef, callStatement) + } + + /** Ensures that the value of the given tree is boxed when used as a method result value. + * @param expr Tree to be boxed if needed. + * @param sym Method symbol this is the result of. + */ + def ensureResultBoxed(expr: js.Tree, methodSym: Symbol)( + implicit pos: Position): js.Tree = { + val tpeEnteringPosterasure = + enteringPhase(currentRun.posterasurePhase)(methodSym.tpe.resultType) + ensureBoxed(expr, tpeEnteringPosterasure) + } + + /** Ensures that the value of the given tree is boxed. + * @param expr Tree to be boxed if needed. + * @param tpeEnteringPosterasure The type of `expr` as it was entering + * the posterasure phase. + */ + def ensureBoxed(expr: js.Tree, tpeEnteringPosterasure: Type)( + implicit pos: Position): js.Tree = { + + tpeEnteringPosterasure match { + case tpe if isPrimitiveValueType(tpe) => + makePrimitiveBox(expr, tpe) + + case tpe: ErasedValueType => + val boxedClass = tpe.valueClazz + val ctor = boxedClass.primaryConstructor + genNew(boxedClass, ctor, List(expr)) + + case _ => + expr + } + } + + /** Extracts a value typed as Any to the given type after posterasure. + * @param expr Tree to be extracted. + * @param tpeEnteringPosterasure The type of `expr` as it was entering + * the posterasure phase. + */ + def fromAny(expr: js.Tree, tpeEnteringPosterasure: Type)( + implicit pos: Position): js.Tree = { + + tpeEnteringPosterasure match { + case tpe if isPrimitiveValueType(tpe) => + makePrimitiveUnbox(expr, tpe) + + case tpe: ErasedValueType => + val boxedClass = tpe.valueClazz + val unboxMethod = boxedClass.derivedValueClassUnbox + val content = genApplyMethod( + genAsInstanceOf(expr, tpe), unboxMethod, Nil) + if (unboxMethod.tpe.resultType <:< tpe.erasedUnderlying) + content + else + fromAny(content, tpe.erasedUnderlying) + + case tpe => + genAsInstanceOf(expr, tpe) + } + } + + /** Gen a boxing operation (tpe is the primitive type) */ + def makePrimitiveBox(expr: js.Tree, tpe: Type)( + implicit pos: Position): js.Tree = { + toIRType(tpe) match { + case jstpe.NoType => // for JS interop cases + js.Block(expr, js.Undefined()) + case jstpe.BooleanType | jstpe.CharType | jstpe.ByteType | + jstpe.ShortType | jstpe.IntType | jstpe.LongType | jstpe.FloatType | + jstpe.DoubleType => + expr // box is identity for all those primitive types + case _ => + abort(s"makePrimitiveBox requires a primitive type, found $tpe at $pos") + } + } + + /** Gen an unboxing operation (tpe is the primitive type) */ + def makePrimitiveUnbox(expr: js.Tree, tpe: Type)( + implicit pos: Position): js.Tree = { + toIRType(tpe) match { + case jstpe.NoType => expr // for JS interop cases + case irTpe => js.AsInstanceOf(expr, irTpe) + } + } + + /** Gen JS code for a Scala.js-specific primitive method */ + private def genJSPrimitive(tree: Apply, args: List[Tree], code: Int, + isStat: Boolean): js.Tree = { + import jsPrimitives._ + + implicit val pos = tree.pos + + def genArgs1: js.Tree = { + assert(args.size == 1, + s"Expected exactly 1 argument for JS primitive $code but got " + + s"${args.size} at $pos") + genExpr(args.head) + } + + def genArgs2: (js.Tree, js.Tree) = { + assert(args.size == 2, + s"Expected exactly 2 arguments for JS primitive $code but got " + + s"${args.size} at $pos") + (genExpr(args.head), genExpr(args.tail.head)) + } + + def genArgsVarLength: List[js.TreeOrJSSpread] = + genPrimitiveJSArgs(tree.symbol, args) + + def resolveReifiedJSClassSym(arg: Tree): Symbol = { + def fail(): Symbol = { + reporter.error(pos, + tree.symbol.nameString + " must be called with a constant " + + "classOf[T] representing a class extending js.Any " + + "(not a trait nor an object)") + NoSymbol + } + arg match { + case Literal(value) if value.tag == ClazzTag => + val classSym = value.typeValue.typeSymbol + if (isJSType(classSym) && !classSym.isTrait && !classSym.isModuleClass) + classSym + else + fail() + case _ => + fail() + } + } + + (code: @switch) match { + case DYNNEW => + // js.Dynamic.newInstance(clazz)(actualArgs: _*) + val (jsClass, actualArgs) = extractFirstArg(genArgsVarLength) + js.JSNew(jsClass, actualArgs) + + case ARR_CREATE => + // js.Array(elements: _*) + js.JSArrayConstr(genArgsVarLength) + + case CONSTRUCTOROF => + // runtime.constructorOf(clazz) + val classSym = resolveReifiedJSClassSym(args.head) + if (classSym == NoSymbol) + js.Undefined() // compile error emitted by resolveReifiedJSClassSym + else + genPrimitiveJSClass(classSym) + + case CREATE_INNER_JS_CLASS | CREATE_LOCAL_JS_CLASS => + // runtime.createInnerJSClass(clazz, superClass) + // runtime.createLocalJSClass(clazz, superClass, fakeNewInstances) + val classSym = resolveReifiedJSClassSym(args(0)) + val superClassValue = genExpr(args(1)) + if (classSym == NoSymbol) { + js.Undefined() // compile error emitted by resolveReifiedJSClassSym + } else { + val captureValues = { + if (code == CREATE_INNER_JS_CLASS) { + val outer = genThis() + List.fill(classSym.info.decls.count(_.isClassConstructor))(outer) + } else { + val ArrayValue(_, fakeNewInstances) = args(2) + fakeNewInstances.flatMap(genCaptureValuesFromFakeNewInstance(_)) + } + } + js.CreateJSClass(encodeClassName(classSym), + superClassValue :: captureValues) + } + + case WITH_CONTEXTUAL_JS_CLASS_VALUE => + // withContextualJSClassValue(jsclass, inner) + val jsClassValue = genExpr(args(0)) + withScopedVars( + contextualJSClassValue := Some(jsClassValue) + ) { + genStatOrExpr(args(1), isStat) + } + + case LINKING_INFO => + // runtime.linkingInfo + js.JSLinkingInfo() + + case IDENTITY_HASH_CODE => + // runtime.identityHashCode(arg) + val arg = genArgs1 + js.IdentityHashCode(arg) + + case DEBUGGER => + // js.special.debugger() + js.Debugger() + + case UNITVAL => + // BoxedUnit.UNIT, which is the boxed version of () + js.Undefined() + + case JS_NATIVE => + // js.native + reporter.error(pos, + "js.native may only be used as stub implementation in facade types") + js.Undefined() + + case TYPEOF => + // js.typeOf(arg) + val arg = genArgs1 + val typeofExpr = arg match { + case arg: js.JSGlobalRef => js.JSTypeOfGlobalRef(arg) + case _ => js.JSUnaryOp(js.JSUnaryOp.typeof, arg) + } + genAsInstanceOf(typeofExpr, StringClass.tpe) + + case JS_NEW_TARGET => + // js.new.target + val valid = currentMethodSym.isClassConstructor && isNonNativeJSClass(currentClassSym) + if (!valid) { + reporter.error(pos, + "Illegal use of js.`new`.target.\n" + + "It can only be used in the constructor of a JS class, " + + "as a statement or in the rhs of a val or var.\n" + + "It cannot be used inside a lambda or by-name parameter, nor in any other location.") + } + js.JSNewTarget() + + case JS_IMPORT => + // js.import(arg) + val arg = genArgs1 + js.JSImportCall(arg) + + case JS_IMPORT_META => + // js.import.meta + js.JSImportMeta() + + case DYNAMIC_IMPORT => + assert(args.size == 1, + s"Expected exactly 1 argument for JS primitive $code but got " + + s"${args.size} at $pos") + + args.head match { + case Block(stats, expr @ Apply(fun @ Select(New(tpt), _), args)) => + /* stats is always empty if no other compiler plugin is present. + * However, code instrumentation (notably scoverage) might add + * statements here. If this is the case, the thunk anonymous class + * has already been created when the other plugin runs (i.e. the + * plugin ran after jsinterop). + * + * Therefore, it is OK to leave the statements on our side of the + * dynamic loading boundary. + */ + + val clsSym = tpt.symbol + val ctor = fun.symbol + + assert(clsSym.isSubClass(DynamicImportThunkClass), + s"expected subclass of DynamicImportThunk, got: $clsSym at: ${expr.pos}") + assert(ctor.isPrimaryConstructor, + s"expected primary constructor, got: $ctor at: ${expr.pos}") + + js.Block( + stats.map(genStat(_)), + js.ApplyDynamicImport( + js.ApplyFlags.empty, + encodeClassName(clsSym), + encodeDynamicImportForwarderIdent(ctor.tpe.params), + genActualArgs(ctor, args)) + ) + + case tree => + abort("Unexpected argument tree in dynamicImport: " + + tree + "/" + tree.getClass + " at: " + tree.pos) + } + + case STRICT_EQ => + // js.special.strictEquals(arg1, arg2) + val (arg1, arg2) = genArgs2 + js.JSBinaryOp(js.JSBinaryOp.===, arg1, arg2) + + case IN => + // js.special.in(arg1, arg2) + val (arg1, arg2) = genArgs2 + js.AsInstanceOf(js.JSBinaryOp(js.JSBinaryOp.in, arg1, arg2), + jstpe.BooleanType) + + case INSTANCEOF => + // js.special.instanceof(arg1, arg2) + val (arg1, arg2) = genArgs2 + js.AsInstanceOf(js.JSBinaryOp(js.JSBinaryOp.instanceof, arg1, arg2), + jstpe.BooleanType) + + case DELETE => + // js.special.delete(arg1, arg2) + val (arg1, arg2) = genArgs2 + js.JSDelete(arg1, arg2) + + case FORIN => + /* js.special.forin(arg1, arg2) + * + * We must generate: + * + * val obj = arg1 + * val f = arg2 + * for (val key in obj) { + * f(key) + * } + * + * with temporary vals, because `arg2` must be evaluated only + * once, and after `arg1`. + */ + val (arg1, arg2) = genArgs2 + val objVarDef = js.VarDef(freshLocalIdent("obj"), NoOriginalName, + jstpe.AnyType, mutable = false, arg1) + val fVarDef = js.VarDef(freshLocalIdent("f"), NoOriginalName, + jstpe.AnyType, mutable = false, arg2) + val keyVarIdent = freshLocalIdent("key") + val keyVarRef = js.VarRef(keyVarIdent)(jstpe.AnyType) + js.Block( + objVarDef, + fVarDef, + js.ForIn(objVarDef.ref, keyVarIdent, NoOriginalName, { + js.JSFunctionApply(fVarDef.ref, List(keyVarRef)) + })) + + case JS_THROW => + // js.special.throw(arg) + js.Throw(genArgs1) + + case JS_TRY_CATCH => + /* js.special.tryCatch(arg1, arg2) + * + * We must generate: + * + * val body = arg1 + * val handler = arg2 + * try { + * body() + * } catch (e) { + * handler(e) + * } + * + * with temporary vals, because `arg2` must be evaluated before + * `body` executes. Moreover, exceptions thrown while evaluating + * the function values `arg1` and `arg2` must not be caught. + */ + val (arg1, arg2) = genArgs2 + val bodyVarDef = js.VarDef(freshLocalIdent("body"), NoOriginalName, + jstpe.AnyType, mutable = false, arg1) + val handlerVarDef = js.VarDef(freshLocalIdent("handler"), NoOriginalName, + jstpe.AnyType, mutable = false, arg2) + val exceptionVarIdent = freshLocalIdent("e") + val exceptionVarRef = js.VarRef(exceptionVarIdent)(jstpe.AnyType) + js.Block( + bodyVarDef, + handlerVarDef, + js.TryCatch( + js.JSFunctionApply(bodyVarDef.ref, Nil), + exceptionVarIdent, + NoOriginalName, + js.JSFunctionApply(handlerVarDef.ref, List(exceptionVarRef)) + )(jstpe.AnyType) + ) + + case WRAP_AS_THROWABLE => + // js.special.wrapAsThrowable(arg) + js.WrapAsThrowable(genArgs1) + + case UNWRAP_FROM_THROWABLE => + // js.special.unwrapFromThrowable(arg) + js.UnwrapFromThrowable(genArgs1) + } + } + + /** Gen JS code for a primitive JS call (to a method of a subclass of js.Any) + * This is the typed Scala.js to JS bridge feature. Basically it boils + * down to calling the method without name mangling. But other aspects + * come into play: + * * Operator methods are translated to JS operators (not method calls) + * * apply is translated as a function call, i.e. o() instead of o.apply() + * * Scala varargs are turned into JS varargs (see genPrimitiveJSArgs()) + * * Getters and parameterless methods are translated as Selects + * * Setters are translated to Assigns of Selects + */ + private def genPrimitiveJSCall(tree: Apply, isStat: Boolean): js.Tree = { + val sym = tree.symbol + val Apply(fun @ Select(receiver0, _), args0) = tree + + implicit val pos = tree.pos + + val receiver = genExprOrGlobalScope(receiver0) + val args = genPrimitiveJSArgs(sym, args0) + + genJSCallGeneric(sym, receiver, args, isStat) + } + + /** Gen JS code for a call to a native JS def or val. */ + private def genJSNativeMemberCall(tree: Apply, isStat: Boolean): js.Tree = { + val sym = tree.symbol + val Apply(_, args0) = tree + + implicit val pos = tree.pos + + val jsNativeMemberValue = + js.SelectJSNativeMember(encodeClassName(sym.owner), encodeMethodSym(sym)) + + val boxedResult = + if (jsInterop.isJSGetter(sym)) jsNativeMemberValue + else js.JSFunctionApply(jsNativeMemberValue, genPrimitiveJSArgs(sym, args0)) + + fromAny(boxedResult, enteringPhase(currentRun.posterasurePhase) { + sym.tpe.resultType + }) + } + + private def genJSSuperCall(tree: Apply, isStat: Boolean): js.Tree = { + acquireContextualJSClassValue { explicitJSSuperClassValue => + implicit val pos = tree.pos + val Apply(fun @ Select(sup @ Super(qual, _), _), args) = tree + val sym = fun.symbol + + /* #3013 `qual` can be `this.$outer()` in some cases since Scala 2.12, + * so we call `genExpr(qual)`, not just `genThis()`. + */ + val genReceiver = genExpr(qual) + lazy val genScalaArgs = genActualArgs(sym, args) + lazy val genJSArgs = genPrimitiveJSArgs(sym, args) + + if (sym.owner == ObjectClass) { + // Normal call anyway + assert(!sym.isClassConstructor, + "Trying to call the super constructor of Object in a " + + s"non-native JS class at $pos") + genApplyMethod(genReceiver, sym, genScalaArgs) + } else if (sym.isClassConstructor) { + throw new AssertionError("calling a JS super constructor should " + + s"have happened in genPrimaryJSClassCtor at $pos") + } else if (isNonNativeJSClass(sym.owner) && !isExposed(sym)) { + // Reroute to the static method + genApplyJSClassMethod(genReceiver, sym, genScalaArgs) + } else { + val jsSuperClassValue = explicitJSSuperClassValue.orElse { + Some(genPrimitiveJSClass(currentClassSym.superClass)) + } + genJSCallGeneric(sym, MaybeGlobalScope.NotGlobalScope(genReceiver), + genJSArgs, isStat, jsSuperClassValue) + } + } + } + + private def genJSCallGeneric(sym: Symbol, receiver: MaybeGlobalScope, + args: List[js.TreeOrJSSpread], isStat: Boolean, + jsSuperClassValue: Option[js.Tree] = None)( + implicit pos: Position): js.Tree = { + + def argsNoSpread: List[js.Tree] = { + assert(!args.exists(_.isInstanceOf[js.JSSpread]), + s"Unexpected spread at $pos") + args.asInstanceOf[List[js.Tree]] + } + + val argc = args.size // meaningful only for methods that don't have varargs + + def requireNotSuper(): Unit = { + if (jsSuperClassValue.isDefined) { + reporter.error(pos, + "Illegal super call in non-native JS class") + } + } + + def genSuperReference(propName: js.Tree): js.AssignLhs = { + jsSuperClassValue.fold[js.AssignLhs] { + genJSBracketSelectOrGlobalRef(receiver, propName) + } { superClassValue => + js.JSSuperSelect(superClassValue, + ruleOutGlobalScope(receiver), propName) + } + } + + def genSelectGet(propName: js.Tree): js.Tree = + genSuperReference(propName) + + def genSelectSet(propName: js.Tree, value: js.Tree): js.Tree = + js.Assign(genSuperReference(propName), value) + + def genCall(methodName: js.Tree, + args: List[js.TreeOrJSSpread]): js.Tree = { + jsSuperClassValue.fold[js.Tree] { + genJSBracketMethodApplyOrGlobalRefApply( + receiver, methodName, args) + } { superClassValue => + js.JSSuperMethodCall(superClassValue, + ruleOutGlobalScope(receiver), methodName, args) + } + } + + val boxedResult = JSCallingConvention.of(sym) match { + case JSCallingConvention.UnaryOp(code) => + requireNotSuper() + assert(argc == 0, s"bad argument count ($argc) for unary op at $pos") + js.JSUnaryOp(code, ruleOutGlobalScope(receiver)) + + case JSCallingConvention.BinaryOp(code) => + requireNotSuper() + assert(argc == 1, s"bad argument count ($argc) for binary op at $pos") + js.JSBinaryOp(code, ruleOutGlobalScope(receiver), argsNoSpread.head) + + case JSCallingConvention.Call => + requireNotSuper() + + if (sym.owner.isSubClass(JSThisFunctionClass)) { + genJSBracketMethodApplyOrGlobalRefApply(receiver, + js.StringLiteral("call"), args) + } else { + js.JSFunctionApply(ruleOutGlobalScope(receiver), args) + } + + case JSCallingConvention.Property(jsName) => + argsNoSpread match { + case Nil => genSelectGet(genExpr(jsName)) + case value :: Nil => genSelectSet(genExpr(jsName), value) + + case _ => + throw new AssertionError( + s"property methods should have 0 or 1 non-varargs arguments at $pos") + } + + case JSCallingConvention.BracketAccess => + argsNoSpread match { + case keyArg :: Nil => + genSelectGet(keyArg) + case keyArg :: valueArg :: Nil => + genSelectSet(keyArg, valueArg) + case _ => + throw new AssertionError( + s"@JSBracketAccess methods should have 1 or 2 non-varargs arguments at $pos") + } + + case JSCallingConvention.BracketCall => + val (methodName, actualArgs) = extractFirstArg(args) + genCall(methodName, actualArgs) + + case JSCallingConvention.Method(jsName) => + genCall(genExpr(jsName), args) + } + + boxedResult match { + case js.Assign(_, _) => + boxedResult + case _ if isStat => + boxedResult + case _ => + fromAny(boxedResult, + enteringPhase(currentRun.posterasurePhase)(sym.tpe.resultType)) + } + } + + /** Extract the first argument to a primitive JS call. + * This is nothing else than decomposing into head and tail, except that + * we assert that the first element is not a JSSpread. + */ + private def extractFirstArg( + args: List[js.TreeOrJSSpread]): (js.Tree, List[js.TreeOrJSSpread]) = { + assert(args.nonEmpty, + "Trying to extract the first argument of an empty argument list") + val firstArg = args.head match { + case firstArg: js.Tree => + firstArg + case firstArg: js.JSSpread => + throw new AssertionError( + "Trying to extract the first argument of an argument list starting " + + "with a Spread argument: " + firstArg) + } + (firstArg, args.tail) + } + + /** Gen JS code for a new of a JS class (subclass of js.Any) */ + private def genPrimitiveJSNew(tree: Apply): js.Tree = { + acquireContextualJSClassValue { jsClassValue => + implicit val pos = tree.pos + + val Apply(fun @ Select(New(tpt), _), args0) = tree + val cls = tpt.tpe.typeSymbol + val ctor = fun.symbol + + val nestedJSClass = isNestedJSClass(cls) + assert(jsClassValue.isDefined == nestedJSClass, + s"$cls at $pos: jsClassValue.isDefined = ${jsClassValue.isDefined} " + + s"but isInnerNonNativeJSClass = $nestedJSClass") + + def args = genPrimitiveJSArgs(ctor, args0) + + if (cls == JSObjectClass && args0.isEmpty) + js.JSObjectConstr(Nil) + else if (cls == JSArrayClass && args0.isEmpty) + js.JSArrayConstr(Nil) + else if (isAnonymousJSClass(cls)) + genAnonJSClassNew(cls, jsClassValue.get, args0.map(genExpr))(fun.pos) + else if (!nestedJSClass) + js.JSNew(genPrimitiveJSClass(cls), args) + else if (!cls.isModuleClass) + js.JSNew(jsClassValue.get, args) + else + genCreateInnerJSModule(cls, jsClassValue.get, args0.map(genExpr)) + } + } + + /** Gen JS code representing a JS class (subclass of js.Any) */ + private def genPrimitiveJSClass(sym: Symbol)( + implicit pos: Position): js.Tree = { + assert(!isStaticModule(sym) && !sym.isTraitOrInterface, + s"genPrimitiveJSClass called with non-class $sym") + js.LoadJSConstructor(encodeClassName(sym)) + } + + /** Gen JS code to create the JS class of an inner JS module class. */ + private def genCreateInnerJSModule(sym: Symbol, + jsSuperClassValue: js.Tree, args: List[js.Tree])( + implicit pos: Position): js.Tree = { + js.JSNew(js.CreateJSClass(encodeClassName(sym), + jsSuperClassValue :: args), Nil) + } + + /** Gen actual actual arguments to Scala method call. + * + * Returns a list of the transformed arguments. + * + * This tries to optimize repeated arguments (varargs) by turning them + * into JS arrays wrapped in the appropriate Seq, rather than Scala + * arrays. + */ + private def genActualArgs(sym: Symbol, args: List[Tree])( + implicit pos: Position): List[js.Tree] = { + val wereRepeated = exitingPhase(currentRun.typerPhase) { + /* Do NOT use `params` instead of `paramss.flatten` here! Exiting + * typer, `params` only contains the *first* parameter list. + * This was causing #2265 and #2741. + */ + sym.tpe.paramss.flatten.map(p => isScalaRepeatedParamType(p.tpe)) + } + + if (wereRepeated.size > args.size) { + // Should not happen, but let's not crash + args.map(genExpr) + } else { + /* Arguments that are in excess compared to the type signature after + * typer are lambda-lifted arguments. They cannot be repeated, hence + * the extension to `false`. + */ + for ((arg, wasRepeated) <- args.zipAll(wereRepeated, EmptyTree, false)) yield { + if (wasRepeated) { + tryGenRepeatedParamAsJSArray(arg, handleNil = false).fold { + genExpr(arg) + } { genArgs => + genJSArrayToVarArgs(js.JSArrayConstr(genArgs)) + } + } else { + genExpr(arg) + } + } + } + } + + /** Info about a Scala method param when called as JS method. + * + * @param sym Parameter symbol as seen now. + * @param tpe Parameter type (type of a single element if repeated) + * @param repeated Whether the parameter is repeated. + * @param capture Whether the parameter is a capture. + */ + final class JSParamInfo(val sym: Symbol, val tpe: Type, + val repeated: Boolean = false, val capture: Boolean = false) { + assert(!repeated || !capture, "capture cannot be repeated") + def hasDefault: Boolean = sym.hasFlag(Flags.DEFAULTPARAM) + } + + def jsParamInfos(sym: Symbol): List[JSParamInfo] = { + assert(sym.isMethod, s"trying to take JS param info of non-method: $sym") + + /* For constructors of nested JS classes (*), explicitouter and + * lambdalift have introduced some parameters for the outer parameter and + * captures. We must ignore those, as captures and outer pointers are + * taken care of by `explicitinerjs` for such classes. + * + * Unfortunately, for some reason lambdalift creates new symbol *even for + * parameters originally in the signature* when doing so! That is why we + * use the *names* of the parameters as a link through time, rather than + * the symbols, to identify which ones already existed at the time of + * explicitinerjs. + * + * This is pretty fragile, but fortunately we have a huge test suite to + * back us up should scalac alter its behavior. + * + * In addition, for actual parameters that we keep, we have to look back + * in time to see whether they were repeated and what was their type. + * + * (*) Note that we are not supposed to receive in genPrimitiveJSArgs a + * method symbol that would have such captures *and* would not be a + * class constructors. Indeed, such methods would have started their + * life as local defs, which are not exposed. + */ + + val uncurryParams = enteringPhase(currentRun.uncurryPhase) { + for { + paramUncurry <- sym.tpe.paramss.flatten + } yield { + val v = { + if (isRepeated(paramUncurry)) + Some(repeatedToSingle(paramUncurry.tpe)) + else + None + } + + paramUncurry.name -> v + } + }.toMap + + val paramTpes = enteringPhase(currentRun.posterasurePhase) { + for (param <- sym.tpe.params) + yield param.name -> param.tpe + }.toMap + + for { + paramSym <- sym.tpe.params + } yield { + uncurryParams.get(paramSym.name) match { + case None => + // This is a capture parameter introduced by explicitouter or lambdalift + new JSParamInfo(paramSym, paramSym.tpe, capture = true) + + case Some(Some(tpe)) => + new JSParamInfo(paramSym, tpe, repeated = true) + + case Some(None) => + val tpe = paramTpes.getOrElse(paramSym.name, paramSym.tpe) + new JSParamInfo(paramSym, tpe) + } + } + } + + /** Gen actual actual arguments to a primitive JS call. + * + * * Repeated arguments (varargs) are expanded + * * Default arguments are omitted or replaced by undefined + * * All arguments are boxed + * + * Repeated arguments that cannot be expanded at compile time (i.e., if a + * Seq is passed to a varargs parameter with the syntax `seq: _*`) will be + * wrapped in a [[js.JSSpread]] node to be expanded at runtime. + */ + private def genPrimitiveJSArgs(sym: Symbol, args: List[Tree])( + implicit pos: Position): List[js.TreeOrJSSpread] = { + + var reversedArgs: List[js.TreeOrJSSpread] = Nil + + for ((arg, info) <- args.zip(jsParamInfos(sym))) { + if (info.repeated) { + reversedArgs = + genPrimitiveJSRepeatedParam(arg) reverse_::: reversedArgs + } else if (info.capture) { + // Ignore captures + assert(sym.isClassConstructor, + s"Found an unknown param ${info.sym.name} in method " + + s"${sym.fullName}, which is not a class constructor, at $pos") + } else { + val unboxedArg = genExpr(arg) + val boxedArg = unboxedArg match { + case js.Transient(UndefinedParam) => + unboxedArg + case _ => + ensureBoxed(unboxedArg, info.tpe) + } + + reversedArgs ::= boxedArg + } + } + + /* Remove all consecutive UndefinedParam's at the end of the argument + * list. No check is performed whether they may be there, since they will + * only be placed where default arguments can be anyway. + */ + reversedArgs = reversedArgs.dropWhile { + case js.Transient(UndefinedParam) => true + case _ => false + } + + // Find remaining UndefinedParam's and replace by js.Undefined. This can + // happen with named arguments or when multiple argument lists are present + reversedArgs = reversedArgs map { + case js.Transient(UndefinedParam) => js.Undefined() + case arg => arg + } + + reversedArgs.reverse + } + + /** Gen JS code for a repeated param of a primitive JS method + * In this case `arg` has type Seq[T] for some T, but the result should + * be an expanded list of the elements in the sequence. So this method + * takes care of the conversion. + * It is specialized for the shapes of tree generated by the desugaring + * of repeated params in Scala, so that these are actually expanded at + * compile-time. + * Otherwise, it returns a JSSpread with the Seq converted to a js.Array. + */ + private def genPrimitiveJSRepeatedParam(arg: Tree): List[js.TreeOrJSSpread] = { + tryGenRepeatedParamAsJSArray(arg, handleNil = true) getOrElse { + /* Fall back to calling runtime.toJSVarArgs to perform the conversion + * to js.Array, then wrap in a Spread operator. + */ + implicit val pos = arg.pos + val jsArrayArg = genApplyMethod( + genLoadModule(RuntimePackageModule), + Runtime_toJSVarArgs, + List(genExpr(arg))) + List(js.JSSpread(jsArrayArg)) + } + } + + /** Try and expand a repeated param (xs: T*) at compile-time. + * This method recognizes the shapes of tree generated by the desugaring + * of repeated params in Scala, and expands them. + * If `arg` does not have the shape of a generated repeated param, this + * method returns `None`. + */ + private def tryGenRepeatedParamAsJSArray(arg: Tree, + handleNil: Boolean): Option[List[js.Tree]] = { + implicit val pos = arg.pos + + // Given a method `def foo(args: T*)` + arg match { + // foo(arg1, arg2, ..., argN) where N > 0 + case MaybeAsInstanceOf(WrapArray( + MaybeAsInstanceOf(ArrayValue(tpt, elems)))) => + /* Value classes in arrays are already boxed, so no need to use + * the type before erasure. + */ + val elemTpe = tpt.tpe + Some(elems.map(e => ensureBoxed(genExpr(e), elemTpe))) + + // foo() + case Select(_, _) if handleNil && arg.symbol == NilModule => + Some(Nil) + + // foo(argSeq:_*) - cannot be optimized + case _ => + None + } + } + + object MaybeAsInstanceOf { + def unapply(tree: Tree): Some[Tree] = tree match { + case Apply(TypeApply(asInstanceOf_? @ Select(base, _), _), _) + if asInstanceOf_?.symbol == Object_asInstanceOf => + Some(base) + case _ => + Some(tree) + } + } + + object WrapArray { + private val wrapArrayModule = + if (hasNewCollections) ScalaRunTimeModule + else PredefModule + + val wrapRefArrayMethod: Symbol = + getMemberMethod(wrapArrayModule, nme.wrapRefArray) + + val genericWrapArrayMethod: Symbol = + getMemberMethod(wrapArrayModule, nme.genericWrapArray) + + def isClassTagBasedWrapArrayMethod(sym: Symbol): Boolean = + sym == wrapRefArrayMethod || sym == genericWrapArrayMethod + + private val isWrapArray: Set[Symbol] = { + Seq( + nme.wrapRefArray, + nme.wrapByteArray, + nme.wrapShortArray, + nme.wrapCharArray, + nme.wrapIntArray, + nme.wrapLongArray, + nme.wrapFloatArray, + nme.wrapDoubleArray, + nme.wrapBooleanArray, + nme.wrapUnitArray, + nme.genericWrapArray + ).map(getMemberMethod(wrapArrayModule, _)).toSet + } + + def unapply(tree: Apply): Option[Tree] = tree match { + case Apply(wrapArray_?, List(wrapped)) + if isWrapArray(wrapArray_?.symbol) => + Some(wrapped) + case _ => + None + } + } + + /** Wraps a `js.Array` to use as varargs. */ + def genJSArrayToVarArgs(arrayRef: js.Tree)( + implicit pos: Position): js.Tree = { + genApplyMethod(genLoadModule(RuntimePackageModule), + Runtime_toScalaVarArgs, List(arrayRef)) + } + + /** Gen the actual capture values for a JS constructor based on its fake + * `new` invocation. + */ + private def genCaptureValuesFromFakeNewInstance( + tree: Tree): List[js.Tree] = { + + implicit val pos = tree.pos + + val Apply(fun @ Select(New(_), _), args) = tree + val sym = fun.symbol + + /* We use the same strategy as genPrimitiveJSArgs to detect which + * parameters were introduced by explicitouter or lambdalift (but + * reversed, of course). + */ + + val existedBeforeUncurry = enteringPhase(currentRun.uncurryPhase) { + for { + params <- sym.tpe.paramss + param <- params + } yield { + param.name + } + }.toSet + + for { + (arg, paramSym) <- args.zip(sym.tpe.params) + if !existedBeforeUncurry(paramSym.name) + } yield { + genExpr(arg) + } + } + + // Synthesizers for JS functions ------------------------------------------- + + /** Try and generate JS code for an anonymous function class. + * + * Returns Some() if the class could be rewritten that way, None + * otherwise. + * + * We make the following assumptions on the form of such classes: + * - It is an anonymous function + * - Includes being anonymous, final, and having exactly one constructor + * - It is not a PartialFunction + * - It has no field other than param accessors + * - It has exactly one constructor + * - It has exactly one non-bridge method apply if it is not specialized, + * or a method apply$...$sp and a forwarder apply if it is specialized. + * - As a precaution: it is synthetic + * + * From a class looking like this: + * + * final class (outer, capture1, ..., captureM) extends AbstractionFunctionN[...] { + * def apply(param1, ..., paramN) = { + * + * } + * } + * new (o, c1, ..., cM) + * + * we generate a function: + * + * lambda[notype]( + * outer, capture1, ..., captureM, param1, ..., paramN) { + * + * } + * + * so that, at instantiation point, we can write: + * + * new AnonFunctionN(function) + * + * the latter tree is returned in case of success. + * + * Trickier things apply when the function is specialized. + */ + private def tryGenAnonFunctionClass(cd: ClassDef, + capturedArgs: List[js.Tree]): Option[js.Tree] = { + // scalastyle:off return + implicit val pos = cd.pos + val sym = cd.symbol + assert(sym.isAnonymousFunction, + s"tryGenAndRecordAnonFunctionClass called with non-anonymous function $cd") + + if (!sym.superClass.fullName.startsWith("scala.runtime.AbstractFunction")) { + /* This is an anonymous class for a non-LMF capable SAM in 2.12. + * We must not rewrite it, as it would then not inherit from the + * appropriate parent class and/or interface. + */ + None + } else { + nestedGenerateClass(sym) { + val (functionBase, arity) = + tryGenAnonFunctionClassGeneric(cd, capturedArgs)(_ => return None) + + Some(genJSFunctionToScala(functionBase, arity)) + } + } + // scalastyle:on return + } + + /** Gen a conversion from a JavaScript function into a Scala function. */ + private def genJSFunctionToScala(jsFunction: js.Tree, arity: Int)( + implicit pos: Position): js.Tree = { + val clsSym = getRequiredClass("scala.scalajs.runtime.AnonFunction" + arity) + val ctor = clsSym.primaryConstructor + genNew(clsSym, ctor, List(jsFunction)) + } + + /** Gen JS code for a JS function class. + * + * This is called when emitting a ClassDef that represents an anonymous + * class extending `js.FunctionN`. These are generated by the SAM + * synthesizer when the target type is a `js.FunctionN`. Since JS + * functions are not classes, we deconstruct the ClassDef, then + * reconstruct it to be a genuine Closure. + * + * Compared to `tryGenAnonFunctionClass()`, this function must + * always succeed, because we really cannot afford keeping them as + * anonymous classes. The good news is that it can do so, because the + * body of SAM lambdas is hoisted in the enclosing class. Hence, the + * apply() method is just a forwarder to calling that hoisted method. + * + * From a class looking like this: + * + * final class (outer, capture1, ..., captureM) extends js.FunctionN[...] { + * def apply(param1, ..., paramN) = { + * outer.lambdaImpl(param1, ..., paramN, capture1, ..., captureM) + * } + * } + * new (o, c1, ..., cM) + * + * we generate a function: + * + * lambda[notype]( + * outer, capture1, ..., captureM, param1, ..., paramN) { + * outer.lambdaImpl(param1, ..., paramN, capture1, ..., captureM) + * } + */ + def genJSFunction(cd: ClassDef, captures: List[js.Tree]): js.Tree = { + val sym = cd.symbol + assert(isJSFunctionDef(sym), + s"genAndRecordJSFunctionClass called with non-JS function $cd") + + nestedGenerateClass(sym) { + val (function, _) = tryGenAnonFunctionClassGeneric(cd, captures)(msg => + abort(s"Could not generate function for JS function: $msg")) + + function + } + } + + /** Code common to tryGenAndRecordAnonFunctionClass and + * genAndRecordJSFunctionClass. + */ + private def tryGenAnonFunctionClassGeneric(cd: ClassDef, + initialCapturedArgs: List[js.Tree])( + fail: (=> String) => Nothing): (js.Tree, Int) = { + implicit val pos = cd.pos + val sym = cd.symbol + + // First checks + + if (sym.isSubClass(PartialFunctionClass)) + fail(s"Cannot rewrite PartialFunction $cd") + + // First step: find the apply method def, and collect param accessors + + var paramAccessors: List[Symbol] = Nil + var applyDef: DefDef = null + + def gen(tree: Tree): Unit = { + tree match { + case EmptyTree => () + case Template(_, _, body) => body foreach gen + case vd @ ValDef(mods, name, tpt, rhs) => + val fsym = vd.symbol + if (!fsym.isParamAccessor) + fail(s"Found field $fsym which is not a param accessor in anon function $cd") + + if (fsym.isPrivate) { + paramAccessors ::= fsym + } else { + // Uh oh ... an inner something will try to access my fields + fail(s"Found a non-private field $fsym in $cd") + } + case dd: DefDef => + val ddsym = dd.symbol + if (ddsym.isClassConstructor) { + if (!ddsym.isPrimaryConstructor) + fail(s"Non-primary constructor $ddsym in anon function $cd") + } else { + val name = dd.name.toString + if (name == "apply" || (ddsym.isSpecialized && name.startsWith("apply$"))) { + if ((applyDef eq null) || ddsym.isSpecialized) + applyDef = dd + } else if (ddsym.hasAnnotation(JSOptionalAnnotation)) { + // Ignore (this is useful for default parameters in custom JS function types) + } else { + // Found a method we cannot encode in the rewriting + fail(s"Found a non-apply method $ddsym in $cd") + } + } + case _ => + fail("Illegal tree in gen of genAndRecordAnonFunctionClass(): " + tree) + } + } + gen(cd.impl) + paramAccessors = paramAccessors.reverse // preserve definition order + + if (applyDef eq null) + fail(s"Did not find any apply method in anon function $cd") + + withNewLocalNameScope { + // Second step: build the list of useful constructor parameters + + val ctorParams = sym.primaryConstructor.tpe.params + + if (paramAccessors.size != ctorParams.size && + !(paramAccessors.size == ctorParams.size-1 && + ctorParams.head.unexpandedName == jsnme.arg_outer)) { + fail( + s"Have param accessors $paramAccessors but "+ + s"ctor params $ctorParams in anon function $cd") + } + + val hasUnusedOuterCtorParam = paramAccessors.size != ctorParams.size + val usedCtorParams = + if (hasUnusedOuterCtorParam) ctorParams.tail + else ctorParams + val ctorParamDefs = usedCtorParams.map(genParamDef(_)) + + // Third step: emit the body of the apply method def + + val applyMethod = withScopedVars( + paramAccessorLocals := (paramAccessors zip ctorParamDefs).toMap, + tryingToGenMethodAsJSFunction := true + ) { + try { + genMethodWithCurrentLocalNameScope(applyDef) + } catch { + case e: CancelGenMethodAsJSFunction => + fail(e.getMessage) + } + } + + // Fourth step: patch the body to unbox parameters and box result + + val hasRepeatedParam = { + sym.superClass == JSFunctionClass && // Scala functions are known not to have repeated params + enteringUncurry { + applyDef.symbol.paramss.flatten.lastOption.exists(isRepeated(_)) + } + } + + val js.MethodDef(_, _, _, params, _, body) = applyMethod + val (patchedParams, paramsLocals) = { + val nonRepeatedParams = + if (hasRepeatedParam) params.init + else params + patchFunParamsWithBoxes(applyDef.symbol, nonRepeatedParams, + useParamsBeforeLambdaLift = false) + } + + val (patchedRepeatedParam, repeatedParamLocal) = { + /* Instead of this circus, simply `unzip` would be nice. + * But that lowers the type to iterable. + */ + if (hasRepeatedParam) { + val (p, l) = genPatchedParam(params.last, genJSArrayToVarArgs(_)) + (Some(p), Some(l)) + } else { + (None, None) + } + } + + val patchedBody = + js.Block(paramsLocals ++ repeatedParamLocal :+ ensureResultBoxed(body.get, applyDef.symbol)) + + // Fifth step: build the js.Closure + + val isThisFunction = sym.isSubClass(JSThisFunctionClass) && { + val ok = patchedParams.nonEmpty + if (!ok) { + reporter.error(pos, + "The SAM or apply method for a js.ThisFunction must have a " + + "leading non-varargs parameter") + } + ok + } + + val capturedArgs = + if (hasUnusedOuterCtorParam) initialCapturedArgs.tail + else initialCapturedArgs + assert(capturedArgs.size == ctorParamDefs.size, + s"$capturedArgs does not match $ctorParamDefs") + + val closure = { + if (isThisFunction) { + val thisParam :: actualParams = patchedParams + js.Closure( + arrow = false, + ctorParamDefs, + actualParams, + patchedRepeatedParam, + js.Block( + js.VarDef(thisParam.name, thisParam.originalName, + thisParam.ptpe, mutable = false, + js.This()(thisParam.ptpe)(thisParam.pos))(thisParam.pos), + patchedBody), + capturedArgs) + } else { + js.Closure(arrow = true, ctorParamDefs, patchedParams, + patchedRepeatedParam, patchedBody, capturedArgs) + } + } + + val arity = params.size + + (closure, arity) + } + } + + /** Generate JS code for an anonymous function + * + * Anonymous functions survive until the backend in 2.11 under + * -Ydelambdafy:method (for Scala function types) and in 2.12 for any + * LambdaMetaFactory-capable type. + * + * When they do, their body is always of the form + * {{{ + * EnclosingClass.this.someMethod(args) + * }}} + * where the args are either formal parameters of the lambda, or local + * variables or the enclosing def. The latter must be captured. + * + * We identify the captures using the same method as the `delambdafy` + * phase. We have an additional hack for `this`. + * + * To translate them, we first construct a JS closure for the body: + * {{{ + * lambda( + * _this, capture1, ..., captureM, arg1, ..., argN) { + * _this.someMethod(arg1, ..., argN, capture1, ..., captureM) + * } + * }}} + * In the closure, input params are unboxed before use, and the result of + * `someMethod()` is boxed back. + * + * Then, we wrap that closure in a class satisfying the expected type. + * For Scala function types, we use the existing + * `scala.scalajs.runtime.AnonFunctionN` from the library. For other + * LMF-capable types, we generate a class on the fly, which looks like + * this: + * {{{ + * class AnonFun extends Object with FunctionalInterface { + * val f: any + * def (f: any) { + * super(); + * this.f = f + * } + * def theSAMMethod(params: Types...): Type = + * unbox((this.f)(boxParams...)) + * } + * }}} + */ + private def genAnonFunction(originalFunction: Function): js.Tree = { + implicit val pos = originalFunction.pos + val Function(paramTrees, Apply( + targetTree @ Select(receiver, _), allArgs0)) = originalFunction + + val captureSyms = + global.delambdafy.FreeVarTraverser.freeVarsOf(originalFunction) + val target = targetTree.symbol + val params = paramTrees.map(_.symbol) + + val allArgs = allArgs0 map genExpr + + val formalCaptures = captureSyms.toList.map(genParamDef(_, pos)) + val actualCaptures = formalCaptures.map(_.ref) + + val formalArgs = params.map(genParamDef(_)) + + val (allFormalCaptures, body, allActualCaptures) = if (!target.isStaticMember) { + val thisActualCapture = genExpr(receiver) + val thisFormalCapture = js.ParamDef( + freshLocalIdent("this")(receiver.pos), thisOriginalName, + thisActualCapture.tpe, mutable = false)(receiver.pos) + val thisCaptureArg = thisFormalCapture.ref + + val body = if (isJSType(receiver.tpe) && target.owner != ObjectClass) { + assert(isNonNativeJSClass(target.owner) && !isExposed(target), + s"A Function lambda is trying to call an exposed JS method ${target.fullName}") + genApplyJSClassMethod(thisCaptureArg, target, allArgs) + } else { + genApplyMethodMaybeStatically(thisCaptureArg, target, allArgs) + } + + (thisFormalCapture :: formalCaptures, + body, thisActualCapture :: actualCaptures) + } else { + val body = genApplyStatic(target, allArgs) + + (formalCaptures, body, actualCaptures) + } + + val (patchedFormalArgs, paramsLocals) = + patchFunParamsWithBoxes(target, formalArgs, useParamsBeforeLambdaLift = true) + + val patchedBody = + js.Block(paramsLocals :+ ensureResultBoxed(body, target)) + + val closure = js.Closure( + arrow = true, + allFormalCaptures, + patchedFormalArgs, + restParam = None, + patchedBody, + allActualCaptures) + + // Wrap the closure in the appropriate box for the SAM type + val funSym = originalFunction.tpe.typeSymbolDirect + if (isFunctionSymbol(funSym)) { + /* This is a scala.FunctionN. We use the existing AnonFunctionN + * wrapper. + */ + genJSFunctionToScala(closure, params.size) + } else { + /* This is an arbitrary SAM type (can only happen in 2.12). + * We have to synthesize a class like LambdaMetaFactory would do on + * the JVM. + */ + val sam = originalFunction.attachments.get[SAMFunctionCompat].getOrElse { + abort(s"Cannot find the SAMFunction attachment on $originalFunction at $pos") + } + + val samWrapperClassName = synthesizeSAMWrapper(funSym, sam) + js.New(samWrapperClassName, js.MethodIdent(ObjectArgConstructorName), + List(closure)) + } + } + + private def synthesizeSAMWrapper(funSym: Symbol, samInfo: SAMFunctionCompat)( + implicit pos: Position): ClassName = { + val intfName = encodeClassName(funSym) + + val suffix = { + generatedSAMWrapperCount.value += 1 + // LambdaMetaFactory names classes like this + "$$Lambda$" + generatedSAMWrapperCount.value + } + val className = encodeClassName(currentClassSym).withSuffix(suffix) + + val classType = jstpe.ClassType(className) + + // val f: Any + val fFieldIdent = js.FieldIdent(FieldName("f")) + val fFieldDef = js.FieldDef(js.MemberFlags.empty, fFieldIdent, + NoOriginalName, jstpe.AnyType) + + // def this(f: Any) = { this.f = f; super() } + val ctorDef = { + val fParamDef = js.ParamDef(js.LocalIdent(LocalName("f")), + NoOriginalName, jstpe.AnyType, mutable = false) + js.MethodDef( + js.MemberFlags.empty.withNamespace(js.MemberNamespace.Constructor), + js.MethodIdent(ObjectArgConstructorName), + NoOriginalName, + List(fParamDef), + jstpe.NoType, + Some(js.Block(List( + js.Assign( + js.Select(js.This()(classType), className, fFieldIdent)( + jstpe.AnyType), + fParamDef.ref), + js.ApplyStatically(js.ApplyFlags.empty.withConstructor(true), + js.This()(classType), + ir.Names.ObjectClass, + js.MethodIdent(ir.Names.NoArgConstructorName), + Nil)(jstpe.NoType)))))( + js.OptimizerHints.empty, None) + } + + // Compute the set of method symbols that we need to implement + val sams = { + val samsBuilder = List.newBuilder[Symbol] + val seenMethodNames = mutable.Set.empty[MethodName] + + /* scala/bug#10512: any methods which `samInfo.sam` overrides need + * bridges made for them. + * On Scala < 2.12.5, `synthCls` is polyfilled to `NoSymbol` and hence + * `samBridges` will always be empty. This causes our compiler to be + * bug-compatible on these versions. + */ + val synthCls = samInfo.synthCls + val samBridges = if (synthCls == NoSymbol) { + Nil + } else { + import scala.reflect.internal.Flags.BRIDGE + synthCls.info.findMembers(excludedFlags = 0L, requiredFlags = BRIDGE).toList + } + + for (sam <- samInfo.sam :: samBridges) { + /* Remove duplicates, e.g., if we override the same method declared + * in two super traits. + */ + if (seenMethodNames.add(encodeMethodSym(sam).name)) + samsBuilder += sam + } + + samsBuilder.result() + } + + // def samMethod(...params): resultType = this.f(...params) + val samMethodDefs = for (sam <- sams) yield { + val jsParams = sam.tpe.params.map(genParamDef(_, pos)) + val resultType = toIRType(sam.tpe.finalResultType) + + val actualParams = enteringPhase(currentRun.posterasurePhase) { + for ((formal, param) <- jsParams.zip(sam.tpe.params)) + yield (formal.ref, param.tpe) + }.map((ensureBoxed _).tupled) + + val call = js.JSFunctionApply( + js.Select(js.This()(classType), className, fFieldIdent)(jstpe.AnyType), + actualParams) + + val body = fromAny(call, enteringPhase(currentRun.posterasurePhase) { + sam.tpe.finalResultType + }) + + js.MethodDef(js.MemberFlags.empty, encodeMethodSym(sam), + originalNameOfMethod(sam), jsParams, resultType, + Some(body))( + js.OptimizerHints.empty, None) + } + + // The class definition + val classDef = js.ClassDef( + js.ClassIdent(className), + NoOriginalName, + ClassKind.Class, + None, + Some(js.ClassIdent(ir.Names.ObjectClass)), + List(js.ClassIdent(intfName)), + None, + None, + fFieldDef :: ctorDef :: samMethodDefs, + Nil)( + js.OptimizerHints.empty.withInline(true)) + + generatedClasses += classDef + + className + } + + private def patchFunParamsWithBoxes(methodSym: Symbol, + params: List[js.ParamDef], useParamsBeforeLambdaLift: Boolean)( + implicit pos: Position): (List[js.ParamDef], List[js.VarDef]) = { + // See the comment in genPrimitiveJSArgs for a rationale about this + val paramTpes = enteringPhase(currentRun.posterasurePhase) { + for (param <- methodSym.tpe.params) + yield param.name -> param.tpe + }.toMap + + /* Normally, we should work with the list of parameters as seen right + * now. But when generating an anonymous function from a Function node, + * the `methodSym` we use is the *target* of the inner call, not the + * enclosing method for which we're patching the params and body. This + * is a hack which we have to do because there is no such enclosing + * method in that case. When we use the target, the list of symbols for + * formal parameters that we want to see is that before lambdalift, not + * the one we see right now. + */ + val paramSyms = { + if (useParamsBeforeLambdaLift) + enteringPhase(currentRun.phaseNamed("lambdalift"))(methodSym.tpe.params) + else + methodSym.tpe.params + } + + (for { + (param, paramSym) <- params zip paramSyms + } yield { + val paramTpe = paramTpes.getOrElse(paramSym.name, paramSym.tpe) + genPatchedParam(param, fromAny(_, paramTpe)) + }).unzip + } + + private def genPatchedParam(param: js.ParamDef, rhs: js.VarRef => js.Tree)( + implicit pos: Position): (js.ParamDef, js.VarDef) = { + val paramNameIdent = param.name + val origName = param.originalName + val newNameIdent = freshLocalIdent(paramNameIdent.name)(paramNameIdent.pos) + val newOrigName = origName.orElse(paramNameIdent.name) + val patchedParam = js.ParamDef(newNameIdent, newOrigName, jstpe.AnyType, + mutable = false)(param.pos) + val paramLocal = js.VarDef(paramNameIdent, origName, param.ptpe, + mutable = false, rhs(patchedParam.ref)) + (patchedParam, paramLocal) + } + + /** Generates a static method instantiating and calling this + * DynamicImportThunk's `apply`: + * + * {{{ + * static def dynamicImport$;;Ljava.lang.Object(): any = { + * new .;:V().apply;Ljava.lang.Object() + * } + * }}} + */ + private def genDynamicImportForwarder(clsSym: Symbol)( + implicit pos: Position): js.MethodDef = { + withNewLocalNameScope { + val ctor = clsSym.primaryConstructor + val paramSyms = ctor.tpe.params + val paramDefs = paramSyms.map(genParamDef(_)) + + val body = { + val inst = genNew(clsSym, ctor, paramDefs.map(_.ref)) + genApplyMethod(inst, DynamicImportThunkClass_apply, Nil) + } + + js.MethodDef( + js.MemberFlags.empty.withNamespace(js.MemberNamespace.PublicStatic), + encodeDynamicImportForwarderIdent(paramSyms), + NoOriginalName, + paramDefs, + jstpe.AnyType, + Some(body))(OptimizerHints.empty, None) + } + } + + // Methods to deal with JSName --------------------------------------------- + + def genExpr(name: JSName)(implicit pos: Position): js.Tree = name match { + case JSName.Literal(name) => js.StringLiteral(name) + case JSName.Computed(sym) => genComputedJSName(sym) + } + + private def genComputedJSName(sym: Symbol)(implicit pos: Position): js.Tree = { + /* By construction (i.e. restriction in PrepJSInterop), we know that sym + * must be a static method. + * Therefore, at this point, we can invoke it by loading its owner and + * calling it. + */ + def moduleOrGlobalScope = genLoadModuleOrGlobalScope(sym.owner) + def module = genLoadModule(sym.owner) + + if (isJSType(sym.owner)) { + if (!isNonNativeJSClass(sym.owner) || isExposed(sym)) + genJSCallGeneric(sym, moduleOrGlobalScope, args = Nil, isStat = false) + else + genApplyJSClassMethod(module, sym, arguments = Nil) + } else { + genApplyMethod(module, sym, arguments = Nil) + } + } + + // Utilities --------------------------------------------------------------- + + def genVarRef(sym: Symbol)(implicit pos: Position): js.VarRef = + js.VarRef(encodeLocalSym(sym))(toIRType(sym.tpe)) + + def genParamDef(sym: Symbol): js.ParamDef = + genParamDef(sym, toIRType(sym.tpe)) + + private def genParamDef(sym: Symbol, ptpe: jstpe.Type): js.ParamDef = + genParamDef(sym, ptpe, sym.pos) + + private def genParamDef(sym: Symbol, pos: Position): js.ParamDef = + genParamDef(sym, toIRType(sym.tpe), pos) + + private def genParamDef(sym: Symbol, ptpe: jstpe.Type, + pos: Position): js.ParamDef = { + js.ParamDef(encodeLocalSym(sym)(pos), originalNameOfLocal(sym), ptpe, + mutable = false)(pos) + } + + /** Generates a call to `runtime.privateFieldsSymbol()` */ + private def genPrivateFieldsSymbol()(implicit pos: Position): js.Tree = { + genApplyMethod(genLoadModule(RuntimePackageModule), + Runtime_privateFieldsSymbol, Nil) + } + + /** Generate loading of a module value. + * + * Can be given either the module symbol or its module class symbol. + * + * If the module we load refers to the global scope (i.e., it is + * annotated with `@JSGlobalScope`), report a compile error specifying + * that a global scope object should only be used as the qualifier of a + * `.`-selection. + */ + def genLoadModule(sym0: Symbol)(implicit pos: Position): js.Tree = + ruleOutGlobalScope(genLoadModuleOrGlobalScope(sym0)) + + /** Generate loading of a module value or the global scope. + * + * Can be given either the module symbol of its module class symbol. + * + * Unlike `genLoadModule`, this method does not fail if the module we load + * refers to the global scope. + */ + def genLoadModuleOrGlobalScope(sym0: Symbol)( + implicit pos: Position): MaybeGlobalScope = { + + require(sym0.isModuleOrModuleClass, + "genLoadModule called with non-module symbol: " + sym0) + + if (sym0.isModule && sym0.isScala3Defined && sym0.hasAttachment[DottyEnumSingletonCompat.type]) { + /* #4739 This is a reference to a singleton `case` from a Scala 3 `enum`. + * It is not a module. Instead, it is a static field (accessed through + * a static getter) in the `enum` class. + * We use `originalOwner` and `rawname` because that's what the JVM back-end uses. + */ + val className = encodeClassName(sym0.originalOwner) + val getterSimpleName = sym0.rawname.toString() + val getterMethodName = MethodName(getterSimpleName, Nil, toTypeRef(sym0.tpe)) + val tree = js.ApplyStatic(js.ApplyFlags.empty, className, js.MethodIdent(getterMethodName), Nil)( + toIRType(sym0.tpe)) + MaybeGlobalScope.NotGlobalScope(tree) + } else { + val sym = if (sym0.isModule) sym0.moduleClass else sym0 + + // Does that module refer to the global scope? + if (sym.hasAnnotation(JSGlobalScopeAnnotation)) { + MaybeGlobalScope.GlobalScope(pos) + } else { + val className = encodeClassName(sym) + val tree = + if (isJSType(sym)) js.LoadJSModule(className) + else js.LoadModule(className) + MaybeGlobalScope.NotGlobalScope(tree) + } + } + } + + private final val GenericGlobalObjectInformationMsg = { + "\n " + + "See https://www.scala-js.org/doc/interoperability/global-scope.html " + + "for further information." + } + + /** Rule out the `GlobalScope` case of a `MaybeGlobalScope` and extract the + * value tree. + * + * If `tree` represents the global scope, report a compile error. + */ + private def ruleOutGlobalScope(tree: MaybeGlobalScope): js.Tree = { + tree match { + case MaybeGlobalScope.NotGlobalScope(t) => + t + case MaybeGlobalScope.GlobalScope(pos) => + reportErrorLoadGlobalScope()(pos) + } + } + + /** Report a compile error specifying that the global scope cannot be + * loaded as a value. + */ + private def reportErrorLoadGlobalScope()(implicit pos: Position): js.Tree = { + reporter.error(pos, + "Loading the global scope as a value (anywhere but as the " + + "left-hand-side of a `.`-selection) is not allowed." + + GenericGlobalObjectInformationMsg) + js.Undefined()(pos) + } + + /** Gen a JS bracket select or a `JSGlobalRef`. + * + * If the receiver is a normal value, i.e., not the global scope, then + * emit a `JSBracketSelect`. + * + * Otherwise, if the `item` is a constant string that is a valid + * JavaScript identifier, emit a `JSGlobalRef`. + * + * Otherwise, report a compile error. + */ + private def genJSBracketSelectOrGlobalRef(qual: MaybeGlobalScope, + item: js.Tree)(implicit pos: Position): js.AssignLhs = { + qual match { + case MaybeGlobalScope.NotGlobalScope(qualTree) => + js.JSSelect(qualTree, item) + + case MaybeGlobalScope.GlobalScope(_) => + genJSGlobalRef(item, "Selecting a field", "selection") + } + } + + /** Gen a JS bracket method apply or an apply of a `GlobalRef`. + * + * If the receiver is a normal value, i.e., not the global scope, then + * emit a `JSBracketMethodApply`. + * + * Otherwise, if the `method` is a constant string that is a valid + * JavaScript identifier, emit a `JSFunctionApply(JSGlobalRef(...), ...)`. + * + * Otherwise, report a compile error. + */ + private def genJSBracketMethodApplyOrGlobalRefApply( + receiver: MaybeGlobalScope, method: js.Tree, + args: List[js.TreeOrJSSpread])( + implicit pos: Position): js.Tree = { + receiver match { + case MaybeGlobalScope.NotGlobalScope(receiverTree) => + js.JSMethodApply(receiverTree, method, args) + + case MaybeGlobalScope.GlobalScope(_) => + val globalRef = genJSGlobalRef(method, "Calling a method", "call") + js.JSFunctionApply(globalRef, args) + } + } + + private def genJSGlobalRef(propName: js.Tree, + actionFull: String, actionSimpleNoun: String)( + implicit pos: Position): js.JSGlobalRef = { + propName match { + case js.StringLiteral(value) => + if (js.JSGlobalRef.isValidJSGlobalRefName(value)) { + if (value == "await") { + global.runReporting.warning(pos, + s"$actionFull of the global scope with the name '$value' is deprecated.\n" + + " It may produce invalid JavaScript code causing a SyntaxError in some environments." + + GenericGlobalObjectInformationMsg, + WarningCategory.Deprecation, + currentMethodSym.get) + } + js.JSGlobalRef(value) + } else if (js.JSGlobalRef.ReservedJSIdentifierNames.contains(value)) { + reporter.error(pos, + s"Invalid $actionSimpleNoun in the global scope of the reserved identifier name `$value`." + + GenericGlobalObjectInformationMsg) + js.JSGlobalRef("erroneous") + } else { + reporter.error(pos, + s"$actionFull of the global scope whose name is not a valid JavaScript identifier is not allowed." + + GenericGlobalObjectInformationMsg) + js.JSGlobalRef("erroneous") + } + + case _ => + reporter.error(pos, + s"$actionFull of the global scope with a dynamic name is not allowed." + + GenericGlobalObjectInformationMsg) + js.JSGlobalRef("erroneous") + } + } + + private def genAssignableField(sym: Symbol, qualifier: Tree)( + implicit pos: Position): (js.AssignLhs, Boolean) = { + def qual = genExpr(qualifier) + + if (isNonNativeJSClass(sym.owner)) { + val f = if (isExposed(sym)) { + js.JSSelect(qual, genExpr(jsNameOf(sym))) + } else if (isAnonymousJSClass(sym.owner)) { + js.JSSelect( + js.JSSelect(qual, genPrivateFieldsSymbol()), + encodeFieldSymAsStringLiteral(sym)) + } else { + js.JSPrivateSelect(qual, encodeClassName(sym.owner), + encodeFieldSym(sym)) + } + + (f, true) + } else if (jsInterop.topLevelExportsOf(sym).nonEmpty) { + val f = js.SelectStatic(encodeClassName(sym.owner), + encodeFieldSym(sym))(jstpe.AnyType) + (f, true) + } else if (jsInterop.staticExportsOf(sym).nonEmpty) { + val exportInfo = jsInterop.staticExportsOf(sym).head + val companionClass = patchedLinkedClassOfClass(sym.owner) + val f = js.JSSelect( + genPrimitiveJSClass(companionClass), + js.StringLiteral(exportInfo.jsName)) + + (f, true) + } else { + val className = encodeClassName(sym.owner) + val fieldIdent = encodeFieldSym(sym) + + /* #4370 Fields cannot have type NothingType, so we box them as + * scala.runtime.Nothing$ instead. They will be initialized with + * `null`, and any attempt to access them will throw a + * `ClassCastException` (generated in the unboxing code). + */ + toIRType(sym.tpe) match { + case jstpe.NothingType => + val f = js.Select(qual, className, fieldIdent)( + encodeClassType(RuntimeNothingClass)) + (f, true) + case ftpe => + val f = js.Select(qual, className, fieldIdent)(ftpe) + (f, false) + } + } + } + + /** Generate access to a static field. */ + private def genStaticField(sym: Symbol)(implicit pos: Position): js.Tree = { + /* Static fields are not accessed directly at the IR level, because there + * is no lazily-executed static initializer to make sure they are + * initialized. Instead, reading a static field must always go through a + * static getter with the same name as the field, 0 argument, and with + * the field's type as result type. The static getter is responsible for + * proper initialization, if required. + */ + import scalaPrimitives._ + import jsPrimitives._ + if (isPrimitive(sym)) { + getPrimitive(sym) match { + case UNITVAL => js.Undefined() + } + } else { + val className = encodeClassName(sym.owner) + val method = encodeStaticFieldGetterSym(sym) + js.ApplyStatic(js.ApplyFlags.empty, className, method, Nil)(toIRType(sym.tpe)) + } + } + } + + private lazy val isScala211WithXexperimental = { + scala.util.Properties.versionNumberString.startsWith("2.11.") && + settings.Xexperimental.value + } + + private lazy val hasNewCollections = { + val v = scala.util.Properties.versionNumberString + !v.startsWith("2.11.") && + !v.startsWith("2.12.") + } + + /** Tests whether the given type represents a JavaScript type, + * i.e., whether it extends scala.scalajs.js.Any. + */ + def isJSType(tpe: Type): Boolean = + isJSType(tpe.typeSymbol) + + /** Tests whether the given type symbol represents a JavaScript type, + * i.e., whether it extends scala.scalajs.js.Any. + */ + def isJSType(sym: Symbol): Boolean = + sym.hasAnnotation(JSTypeAnnot) + + /** Tests whether the given class is a non-native JS class. */ + def isNonNativeJSClass(sym: Symbol): Boolean = + !sym.isTrait && isJSType(sym) && !sym.hasAnnotation(JSNativeAnnotation) + + def isNestedJSClass(sym: Symbol): Boolean = + sym.isLifted && !isStaticModule(sym.originalOwner) && isJSType(sym) + + /** Tests whether the given class is a JS native class. */ + private def isJSNativeClass(sym: Symbol): Boolean = + sym.hasAnnotation(JSNativeAnnotation) + + /** Tests whether the given class is the impl class of a JS trait. */ + private def isJSImplClass(sym: Symbol): Boolean = + isImplClass(sym) && isJSType(traitOfImplClass(sym)) + + private def traitOfImplClass(sym: Symbol): Symbol = + sym.owner.info.decl(sym.name.dropRight(nme.IMPL_CLASS_SUFFIX.length)) + + /** Tests whether the given member is exposed, i.e., whether it was + * originally a public or protected member of a non-native JS class. + */ + private def isExposed(sym: Symbol): Boolean = { + !sym.isBridge && { + if (sym.isLazy) + sym.isAccessor && sym.accessed.hasAnnotation(ExposedJSMemberAnnot) + else + sym.hasAnnotation(ExposedJSMemberAnnot) + } + } + + /** Test whether `sym` is the symbol of a JS function definition */ + private def isJSFunctionDef(sym: Symbol): Boolean = { + /* A JS function may only reach the backend if it originally was a lambda. + * This is difficult to check in the backend, so we use the fact that a + * non-lambda, concrete, non-native JS type, cannot implement a method named + * `apply`. + * + * Therefore, a class is a JS lambda iff it is anonymous, its direct + * super class is `js.Function`, and it contains an implementation of an + * `apply` method. + * + * Note that being anonymous implies being concrete and non-native, so we + * do not have to test that. + */ + sym.isAnonymousClass && + sym.superClass == JSFunctionClass && + sym.info.decl(nme.apply).filter(JSCallingConvention.isCall(_)).exists + } + + private def hasDefaultCtorArgsAndJSModule(classSym: Symbol): Boolean = { + /* Get the companion module class. + * For inner classes the sym.owner.companionModule can be broken, + * therefore companionModule is fetched at uncurryPhase. + */ + val companionClass = enteringPhase(currentRun.uncurryPhase) { + classSym.companionModule + }.moduleClass + + def hasDefaultParameters = { + val syms = classSym.info.members.filter(_.isClassConstructor) + enteringPhase(currentRun.uncurryPhase) { + syms.exists(_.paramss.iterator.flatten.exists(_.hasDefault)) + } + } + + isJSNativeClass(companionClass) && hasDefaultParameters + } + + private def patchedLinkedClassOfClass(sym: Symbol): Symbol = { + /* Work around a bug of scalac with linkedClassOfClass where package + * objects are involved (the companion class would somehow exist twice + * in the scope, making an assertion fail in Symbol.suchThat). + * Basically this inlines linkedClassOfClass up to companionClass, + * then replaces the `suchThat` by a `filter` and `head`. + */ + val flatOwnerInfo = { + // inline Symbol.flatOwnerInfo because it is protected + if (sym.needsFlatClasses) + sym.info + sym.owner.rawInfo + } + val result = flatOwnerInfo.decl(sym.name).filter(_ isCoDefinedWith sym) + if (!result.isOverloaded) result + else result.alternatives.head + } + + private object DefaultParamInfo { + /** Is the symbol applicable to `DefaultParamInfo`? + * + * This is true iff it is a default accessor and it is not an value class + * `$extension` method. The latter condition is for #4583. + * + * Excluding all `$extension` methods is fine because `DefaultParamInfo` + * is used for JS default accessors, i.e., default accessors of + * `@js.native def`s or of `def`s in JS types. Those can never appear in + * an `AnyVal` class (as a class, it cannot contain `@js.native def`s, and + * as `AnyVal` it cannot also extend `js.Any`). + */ + def isApplicable(sym: Symbol): Boolean = + sym.hasFlag(Flags.DEFAULTPARAM) && !sym.name.endsWith("$extension") + } + + /** Info about a default param accessor. + * + * `DefaultParamInfo.isApplicable(sym)` must be true for this class to make + * sense. + */ + private class DefaultParamInfo(sym: Symbol) { + private val methodName = nme.defaultGetterToMethod(sym.name) + + def isForConstructor: Boolean = methodName == nme.CONSTRUCTOR + + /** When `isForConstructor` is true, returns the owner of the attached + * constructor. + */ + def constructorOwner: Symbol = patchedLinkedClassOfClass(sym.owner) + + /** When `isForConstructor` is false, returns the method attached to the + * specified default accessor. + */ + def attachedMethod: Symbol = { + // If there are overloads, we need to find the one that has default params. + val overloads = sym.owner.info.decl(methodName) + if (!overloads.isOverloaded) { + overloads + } else { + /* We should use `suchThat` here instead of `filter`+`head`. Normally, + * it can never happen that two overloads of a method both have default + * params. However, there is a loophole until Scala 2.12, with the + * `-Xsource:2.10` flag, which disables a check and allows that to + * happen in some circumstances. This is still tested as part of the + * partest test `pos/t8157-2.10.scala`. The use of `filter` instead of + * `suchThat` allows those situations not to crash, although that is + * mostly for (intense) backward compatibility purposes. + * + * This loophole can be use to construct a case of miscompilation where + * one of the overloads would be `@js.native` but the other not. We + * don't really care, though, as it needs some deep hackery to produce + * it. + */ + overloads + .filter(_.paramss.exists(_.exists(_.hasFlag(Flags.DEFAULTPARAM)))) + .alternatives + .head + } + } + } + + private def isStringType(tpe: Type): Boolean = + tpe.typeSymbol == StringClass + + protected lazy val isHijackedClass: Set[Symbol] = { + /* This list is a duplicate of ir.Definitions.HijackedClasses, but + * with global.Symbol's instead of IR encoded names as Strings. + * We also add java.lang.Void, which BoxedUnit "erases" to, and + * HackedStringClass if it is defined. + */ + val s = Set[Symbol]( + JavaLangVoidClass, BoxedUnitClass, BoxedBooleanClass, + BoxedCharacterClass, BoxedByteClass, BoxedShortClass, BoxedIntClass, + BoxedLongClass, BoxedFloatClass, BoxedDoubleClass, StringClass + ) + if (HackedStringClass == NoSymbol) s + else s + HackedStringClass + } + + private lazy val InlineAnnotationClass = requiredClass[scala.inline] + private lazy val NoinlineAnnotationClass = requiredClass[scala.noinline] + + private lazy val ignoreNoinlineAnnotation: Set[Symbol] = { + val ccClass = getClassIfDefined("scala.util.continuations.ControlContext") + + Set( + getMemberIfDefined(ListClass, nme.map), + getMemberIfDefined(ListClass, nme.flatMap), + getMemberIfDefined(ListClass, newTermName("collect")), + getMemberIfDefined(ccClass, nme.map), + getMemberIfDefined(ccClass, nme.flatMap) + ) - NoSymbol + } + + private def isMaybeJavaScriptException(tpe: Type) = + JavaScriptExceptionClass isSubClass tpe.typeSymbol + + def isStaticModule(sym: Symbol): Boolean = + sym.isModuleClass && !isImplClass(sym) && !sym.isLifted + + def isAnonymousJSClass(sym: Symbol): Boolean = { + /* sym.isAnonymousClass simply checks if + * `name containsName tpnme.ANON_CLASS_NAME` + * so after flatten (which we are) it identifies classes nested inside + * anonymous classes as anonymous (notably local classes, see #4278). + * + * Instead we recognize names generated for anonymous classes: + * tpnme.ANON_CLASS_NAME followed by $ where `n` is an integer. + */ + isJSType(sym) && { + val name = sym.name + val i = name.lastIndexOf('$') + + i > 0 && + name.endsWith(tpnme.ANON_CLASS_NAME, i) && + (i + 1 until name.length).forall(j => name.charAt(j).isDigit) + } + } + + sealed abstract class MaybeGlobalScope + + object MaybeGlobalScope { + case class NotGlobalScope(tree: js.Tree) extends MaybeGlobalScope + + case class GlobalScope(pos: Position) extends MaybeGlobalScope + } + + /** Marker object for undefined parameters in JavaScript semantic calls. + * + * To be used inside a `js.Transient` node. + */ + case object UndefinedParam extends js.Transient.Value { + val tpe: jstpe.Type = jstpe.UndefType + + def traverse(traverser: ir.Traversers.Traverser): Unit = () + + def transform(transformer: ir.Transformers.Transformer, isStat: Boolean)( + implicit pos: ir.Position): js.Tree = { + js.Transient(this) + } + + def printIR(out: ir.Printers.IRTreePrinter): Unit = + out.print("") + } +} + +private object GenJSCode { + private val JSObjectClassName = ClassName("scala.scalajs.js.Object") + private val JavaScriptExceptionClassName = ClassName("scala.scalajs.js.JavaScriptException") + + private val newSimpleMethodName = SimpleMethodName("new") + + private val ObjectArgConstructorName = + MethodName.constructor(List(jstpe.ClassRef(ir.Names.ObjectClass))) + + private val lengthMethodName = + MethodName("length", Nil, jstpe.IntRef) + private val charAtMethodName = + MethodName("charAt", List(jstpe.IntRef), jstpe.CharRef) + + private val thisOriginalName = OriginalName("this") + + private object BlockOrAlone { + def unapply(tree: js.Tree): Some[(List[js.Tree], js.Tree)] = tree match { + case js.Block(trees) => Some((trees.init, trees.last)) + case _ => Some((Nil, tree)) + } + } + + private object FirstInBlockOrAlone { + def unapply(tree: js.Tree): Some[(js.Tree, List[js.Tree])] = tree match { + case js.Block(trees) => Some((trees.head, trees.tail)) + case _ => Some((tree, Nil)) + } + } +} diff --git a/compiler/src/main/scala/org/scalajs/nscplugin/GenJSExports.scala b/compiler/src/main/scala/org/scalajs/nscplugin/GenJSExports.scala new file mode 100644 index 0000000000..4239c9c11a --- /dev/null +++ b/compiler/src/main/scala/org/scalajs/nscplugin/GenJSExports.scala @@ -0,0 +1,1017 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin + +import scala.collection.{immutable, mutable} + +import scala.tools.nsc._ +import scala.math.PartialOrdering +import scala.reflect.{ClassTag, classTag} +import scala.reflect.internal.Flags + +import org.scalajs.ir +import org.scalajs.ir.{Trees => js, Types => jstpe} +import org.scalajs.ir.Names.LocalName +import org.scalajs.ir.OriginalName.NoOriginalName +import org.scalajs.ir.Trees.OptimizerHints + +import org.scalajs.nscplugin.util.ScopedVar +import ScopedVar.withScopedVars + +/** Generation of exports for JavaScript + * + * @author Sébastien Doeraene + */ +trait GenJSExports[G <: Global with Singleton] extends SubComponent { + self: GenJSCode[G] => + + import global._ + import jsAddons._ + import definitions._ + import jsDefinitions._ + import jsInterop.{jsNameOf, JSName} + + trait JSExportsPhase { this: JSCodePhase => + + /** Generates exported methods and properties for a class. + * + * @param classSym symbol of the class we export for + */ + def genMemberExports(classSym: Symbol): List[js.MemberDef] = { + val allExports = classSym.info.members.filter(jsInterop.isExport(_)) + + val newlyDecldExports = if (classSym.superClass == NoSymbol) { + allExports + } else { + allExports.filterNot { sym => + classSym.superClass.info.member(sym.name) + .filter(_.tpe =:= sym.tpe).exists + } + } + + val newlyDecldExportNames = + newlyDecldExports.map(_.name.toTermName).toList.distinct + + newlyDecldExportNames map { genMemberExport(classSym, _) } + } + + def genJSClassDispatchers(classSym: Symbol, + dispatchMethodsNames: List[JSName]): List[js.MemberDef] = { + dispatchMethodsNames + .map(genJSClassDispatcher(classSym, _)) + } + + private sealed trait ExportKind + + private object ExportKind { + case object Module extends ExportKind + case object JSClass extends ExportKind + case object Constructor extends ExportKind + case object Method extends ExportKind + case object Property extends ExportKind + case object Field extends ExportKind + + def apply(sym: Symbol): ExportKind = { + if (isStaticModule(sym)) Module + else if (sym.isClass) JSClass + else if (sym.isConstructor) Constructor + else if (!sym.isMethod) Field + else if (jsInterop.isJSProperty(sym)) Property + else Method + } + } + + private def checkSameKind(tups: List[(jsInterop.ExportInfo, Symbol)]): Option[ExportKind] = { + assert(tups.nonEmpty, "must have at least one export") + + val firstSym = tups.head._2 + val overallKind = ExportKind(firstSym) + var bad = false + + for ((info, sym) <- tups.tail) { + val kind = ExportKind(sym) + + if (kind != overallKind) { + bad = true + reporter.error(info.pos, "export overload conflicts with export of " + + s"$firstSym: they are of different types ($kind / $overallKind)") + } + } + + if (bad) None + else Some(overallKind) + } + + private def checkSingleField(tups: List[(jsInterop.ExportInfo, Symbol)]): Symbol = { + assert(tups.nonEmpty, "must have at least one export") + + val firstSym = tups.head._2 + + for ((info, _) <- tups.tail) { + reporter.error(info.pos, "export overload conflicts with export of " + + s"$firstSym: a field may not share its exported name with another export") + } + + firstSym + } + + def genTopLevelExports(classSym: Symbol): List[js.TopLevelExportDef] = { + val exports = for { + sym <- List(classSym) ++ classSym.info.members + info <- jsInterop.topLevelExportsOf(sym) + } yield { + (info, sym) + } + + (for { + (info, tups) <- exports.groupBy(_._1) + kind <- checkSameKind(tups) + } yield { + import ExportKind._ + + implicit val pos = info.pos + + kind match { + case Module => + js.TopLevelModuleExportDef(info.moduleID, info.jsName) + + case JSClass => + assert(isNonNativeJSClass(classSym), "found export on non-JS class") + js.TopLevelJSClassExportDef(info.moduleID, info.jsName) + + case Constructor | Method => + val methodDef = withNewLocalNameScope { + genExportMethod(tups.map(_._2), JSName.Literal(info.jsName), static = true) + } + + js.TopLevelMethodExportDef(info.moduleID, methodDef) + + case Property => + throw new AssertionError("found top-level exported property") + + case Field => + val sym = checkSingleField(tups) + js.TopLevelFieldExportDef(info.moduleID, info.jsName, encodeFieldSym(sym)) + } + }).toList + } + + def genStaticExports(classSym: Symbol): List[js.MemberDef] = { + val exports = (for { + sym <- classSym.info.members + info <- jsInterop.staticExportsOf(sym) + } yield { + (info, sym) + }).toList + + (for { + (info, tups) <- exports.groupBy(_._1) + kind <- checkSameKind(tups) + } yield { + def alts = tups.map(_._2) + + implicit val pos = info.pos + + import ExportKind._ + + kind match { + case Method => + genMemberExportOrDispatcher( + JSName.Literal(info.jsName), isProp = false, alts, static = true) + + case Property => + genMemberExportOrDispatcher( + JSName.Literal(info.jsName), isProp = true, alts, static = true) + + case Field => + val sym = checkSingleField(tups) + + // static fields must always be mutable + val flags = js.MemberFlags.empty + .withNamespace(js.MemberNamespace.PublicStatic) + .withMutable(true) + val name = js.StringLiteral(info.jsName) + val irTpe = genExposedFieldIRType(sym) + js.JSFieldDef(flags, name, irTpe) + + case kind => + throw new AssertionError(s"unexpected static export kind: $kind") + } + }).toList + } + + private def genMemberExport(classSym: Symbol, name: TermName): js.MemberDef = { + /* This used to be `.member(name)`, but it caused #3538, since we were + * sometimes selecting mixin forwarders, whose type history does not go + * far enough back in time to see varargs. We now explicitly exclude + * mixed-in members in addition to bridge methods (the latter are always + * excluded by `.member(name)`). + */ + val alts = classSym.info.memberBasedOnName(name, + excludedFlags = Flags.BRIDGE | Flags.MIXEDIN).alternatives + + assert(!alts.isEmpty, + s"Ended up with no alternatives for ${classSym.fullName}::$name. " + + s"Original set was ${alts} with types ${alts.map(_.tpe)}") + + val (jsName, isProp) = jsInterop.jsExportInfo(name) + + // Check if we have a conflicting export of the other kind + val conflicting = + classSym.info.member(jsInterop.scalaExportName(jsName, !isProp)) + + if (conflicting != NoSymbol) { + val kind = if (isProp) "property" else "method" + val alts = conflicting.alternatives + + reporter.error(alts.head.pos, + s"Exported $kind $jsName conflicts with ${alts.head.fullName}") + } + + genMemberExportOrDispatcher(JSName.Literal(jsName), isProp, alts, static = false) + } + + private def genJSClassDispatcher(classSym: Symbol, name: JSName): js.MemberDef = { + val alts = classSym.info.members.toList.filter { sym => + sym.isMethod && + !sym.isBridge && + /* #3939: Object is not a "real" superclass of JS types. + * as such, its methods do not participate in overload resolution. + * An exception is toString, which is handled specially in + * genExportMethod. + */ + sym.owner != ObjectClass && + jsNameOf(sym) == name + } + + assert(!alts.isEmpty, + s"Ended up with no alternatives for ${classSym.fullName}::$name.") + + val (propSyms, methodSyms) = alts.partition(jsInterop.isJSProperty(_)) + val isProp = propSyms.nonEmpty + + if (isProp && methodSyms.nonEmpty) { + reporter.error(alts.head.pos, + s"Conflicting properties and methods for ${classSym.fullName}::$name.") + implicit val pos = alts.head.pos + js.JSPropertyDef(js.MemberFlags.empty, genExpr(name), None, None) + } else { + genMemberExportOrDispatcher(name, isProp, alts, static = false) + } + } + + def genMemberExportOrDispatcher(jsName: JSName, isProp: Boolean, + alts: List[Symbol], static: Boolean): js.MemberDef = { + withNewLocalNameScope { + if (isProp) + genExportProperty(alts, jsName, static) + else + genExportMethod(alts, jsName, static) + } + } + + private def genExportProperty(alts: List[Symbol], jsName: JSName, + static: Boolean): js.JSPropertyDef = { + assert(!alts.isEmpty, + s"genExportProperty with empty alternatives for $jsName") + + implicit val pos = alts.head.pos + + val namespace = + if (static) js.MemberNamespace.PublicStatic + else js.MemberNamespace.Public + val flags = js.MemberFlags.empty.withNamespace(namespace) + + // Separate getters and setters. Somehow isJSGetter doesn't work here. Hence + // we just check the parameter list length. + val (getter, setters) = alts.partition(_.tpe.params.isEmpty) + + // We can have at most one getter + if (getter.size > 1) + reportCannotDisambiguateError(jsName, alts) + + val getterBody = getter.headOption.map { getterSym => + genApplyForSym(new FormalArgsRegistry(0, false), getterSym, static) + } + + val setterArgAndBody = { + if (setters.isEmpty) { + None + } else { + val formalArgsRegistry = new FormalArgsRegistry(1, false) + val (List(arg), None) = formalArgsRegistry.genFormalArgs() + val body = genOverloadDispatchSameArgc(jsName, formalArgsRegistry, + alts = setters.map(new ExportedSymbol(_, static)), jstpe.AnyType, + paramIndex = 0) + Some((arg, body)) + } + } + + js.JSPropertyDef(flags, genExpr(jsName), getterBody, setterArgAndBody) + } + + /** generates the exporter function (i.e. exporter for non-properties) for + * a given name */ + private def genExportMethod(alts0: List[Symbol], jsName: JSName, + static: Boolean): js.JSMethodDef = { + assert(alts0.nonEmpty, + "need at least one alternative to generate exporter method") + + implicit val pos = alts0.head.pos + + val namespace = + if (static) js.MemberNamespace.PublicStatic + else js.MemberNamespace.Public + val flags = js.MemberFlags.empty.withNamespace(namespace) + + val alts = { + // toString() is always exported. We might need to add it here + // to get correct overloading. + val needsToString = + jsName == JSName.Literal("toString") && alts0.forall(_.tpe.params.nonEmpty) + + if (needsToString) + Object_toString :: alts0 + else + alts0 + } + + val overloads = alts.map(new ExportedSymbol(_, static)) + + val (formalArgs, restParam, body) = + genOverloadDispatch(jsName, overloads, jstpe.AnyType) + + js.JSMethodDef(flags, genExpr(jsName), formalArgs, restParam, body)( + OptimizerHints.empty, None) + } + + def genOverloadDispatch(jsName: JSName, alts: List[Exported], tpe: jstpe.Type)( + implicit pos: Position): (List[js.ParamDef], Option[js.ParamDef], js.Tree) = { + // Factor out methods with variable argument lists. Note that they can + // only be at the end of the lists as enforced by PrepJSExports + val (varArgMeths, normalMeths) = alts.partition(_.hasRepeatedParam) + + // Highest non-repeated argument count + val maxArgc = ( + // We have argc - 1, since a repeated parameter list may also be empty + // (unlike a normal parameter) + varArgMeths.map(_.params.size - 1) ++ + normalMeths.map(_.params.size) + ).max + + // Calculates possible arg counts for normal method + def argCounts(ex: Exported) = { + val params = ex.params + // Find default param + val dParam = params.indexWhere(_.hasDefault) + if (dParam == -1) Seq(params.size) + else dParam to params.size + } + + // Generate tuples (argc, method) + val methodArgCounts = { + // Normal methods + for { + method <- normalMeths + argc <- argCounts(method) + } yield (argc, method) + } ++ { + // Repeated parameter methods + for { + method <- varArgMeths + argc <- method.params.size - 1 to maxArgc + } yield (argc, method) + } + + // Create a map: argCount -> methods (methods may appear multiple times) + val methodByArgCount = + methodArgCounts.groupBy(_._1).map(kv => kv._1 -> kv._2.map(_._2).toSet) + + // Create the formal args registry + val minArgc = methodByArgCount.keys.min + val hasVarArg = varArgMeths.nonEmpty + val needsRestParam = maxArgc != minArgc || hasVarArg + val formalArgsRegistry = new FormalArgsRegistry(minArgc, needsRestParam) + + // List of formal parameters + val (formalArgs, restParam) = formalArgsRegistry.genFormalArgs() + + // Create tuples: (methods, argCounts). This will be the cases we generate + val caseDefinitions = + methodByArgCount.groupBy(_._2).map(kv => kv._1 -> kv._2.keySet) + + // Verify stuff about caseDefinitions + assert({ + val argcs = caseDefinitions.values.flatten.toList + argcs == argcs.distinct && + argcs.forall(_ <= maxArgc) + }, "every argc should appear only once and be lower than max") + + // Generate a case block for each (methods, argCounts) tuple + val cases = for { + (methods, argcs) <- caseDefinitions + if methods.nonEmpty && argcs.nonEmpty + + // exclude default case we're generating anyways for varargs + if methods != varArgMeths.toSet + + // body of case to disambiguates methods with current count + caseBody = genOverloadDispatchSameArgc(jsName, formalArgsRegistry, + methods.toList, tpe, paramIndex = 0, Some(argcs.min)) + + // argc in reverse order + argcList = argcs.toList.sortBy(- _) + } yield (argcList.map(argc => js.IntLiteral(argc - minArgc)), caseBody) + + def defaultCase = { + if (!hasVarArg) { + genThrowTypeError() + } else { + genOverloadDispatchSameArgc(jsName, formalArgsRegistry, varArgMeths, + tpe, paramIndex = 0) + } + } + + val body = { + if (cases.isEmpty) + defaultCase + else if (cases.size == 1 && !hasVarArg) + cases.head._2 + else { + assert(needsRestParam, + "Trying to read rest param length but needsRestParam is false") + val restArgRef = formalArgsRegistry.genRestArgRef() + js.Match( + js.AsInstanceOf(js.JSSelect(restArgRef, js.StringLiteral("length")), jstpe.IntType), + cases.toList, defaultCase)(tpe) + } + } + + (formalArgs, restParam, body) + } + + /** + * Resolve method calls to [[alts]] while assuming they have the same + * parameter count. + * @param minArgc The minimum number of arguments that must be given + * @param alts Alternative methods + * @param paramIndex Index where to start disambiguation + * @param maxArgc only use that many arguments + */ + private def genOverloadDispatchSameArgc(jsName: JSName, + formalArgsRegistry: FormalArgsRegistry, alts: List[Exported], + tpe: jstpe.Type, paramIndex: Int, maxArgc: Option[Int] = None): js.Tree = { + + implicit val pos = alts.head.sym.pos + + if (alts.size == 1) { + alts.head.genBody(formalArgsRegistry) + } else if (maxArgc.exists(_ <= paramIndex) || + !alts.exists(_.params.size > paramIndex)) { + // We reach here in three cases: + // 1. The parameter list has been exhausted + // 2. The optional argument count restriction has triggered + // 3. We only have (more than once) repeated parameters left + // Therefore, we should fail + reportCannotDisambiguateError(jsName, alts.map(_.sym)) + js.Undefined() + } else { + val altsByTypeTest = groupByWithoutHashCode(alts) { exported => + typeTestForTpe(exported.exportArgTypeAt(paramIndex)) + } + + if (altsByTypeTest.size == 1) { + // Testing this parameter is not doing any us good + genOverloadDispatchSameArgc(jsName, formalArgsRegistry, alts, tpe, + paramIndex + 1, maxArgc) + } else { + // Sort them so that, e.g., isInstanceOf[String] + // comes before isInstanceOf[Object] + val sortedAltsByTypeTest = topoSortDistinctsWith(altsByTypeTest) { (lhs, rhs) => + (lhs._1, rhs._1) match { + // NoTypeTest is always last + case (_, NoTypeTest) => true + case (NoTypeTest, _) => false + + case (PrimitiveTypeTest(_, rank1), PrimitiveTypeTest(_, rank2)) => + rank1 <= rank2 + + case (InstanceOfTypeTest(t1), InstanceOfTypeTest(t2)) => + t1 <:< t2 + + case (_: PrimitiveTypeTest, _: InstanceOfTypeTest) => true + case (_: InstanceOfTypeTest, _: PrimitiveTypeTest) => false + } + } + + val defaultCase = genThrowTypeError() + + sortedAltsByTypeTest.foldRight[js.Tree](defaultCase) { (elem, elsep) => + val (typeTest, subAlts) = elem + implicit val pos = subAlts.head.sym.pos + + val paramRef = formalArgsRegistry.genArgRef(paramIndex) + val genSubAlts = genOverloadDispatchSameArgc(jsName, formalArgsRegistry, + subAlts, tpe, paramIndex + 1, maxArgc) + + def hasDefaultParam = subAlts.exists { exported => + val params = exported.params + params.size > paramIndex && + params(paramIndex).hasDefault + } + + val optCond = typeTest match { + case PrimitiveTypeTest(tpe, _) => + Some(js.IsInstanceOf(paramRef, tpe)) + + case InstanceOfTypeTest(tpe) => + Some(genIsInstanceOf(paramRef, tpe)) + + case NoTypeTest => + None + } + + optCond.fold[js.Tree] { + genSubAlts // note: elsep is discarded, obviously + } { cond => + val condOrUndef = if (!hasDefaultParam) cond else { + js.If(cond, js.BooleanLiteral(true), + js.BinaryOp(js.BinaryOp.===, paramRef, js.Undefined()))( + jstpe.BooleanType) + } + js.If(condOrUndef, genSubAlts, elsep)(tpe) + } + } + } + } + } + + private def reportCannotDisambiguateError(jsName: JSName, + alts: List[Symbol]): Unit = { + val currentClass = currentClassSym.get + + /* Find a position that is in the current class for decent error reporting. + * If there are more than one, always use the "highest" one (i.e., the + * one coming last in the source text) so that we reliably display the + * same error in all compilers. + */ + val validPositions = alts.collect { + case alt if alt.owner == currentClass => alt.pos + } + val pos = + if (validPositions.isEmpty) currentClass.pos + else validPositions.maxBy(_.point) + + val kind = + if (jsInterop.isJSGetter(alts.head)) "getter" + else if (jsInterop.isJSSetter(alts.head)) "setter" + else "method" + + val fullKind = + if (isNonNativeJSClass(currentClass)) kind + else "exported " + kind + + val displayName = jsName.displayName + val altsTypesInfo = alts.map(_.tpe.toString).sorted.mkString("\n ") + + reporter.error(pos, + s"Cannot disambiguate overloads for $fullKind $displayName with types\n" + + s" $altsTypesInfo") + } + + /** + * Generate a call to the method [[sym]] while using the formalArguments + * and potentially the argument array. Also inserts default parameters if + * required. + */ + private def genApplyForSym(formalArgsRegistry: FormalArgsRegistry, + sym: Symbol, static: Boolean): js.Tree = { + if (isNonNativeJSClass(currentClassSym) && + sym.owner != currentClassSym.get) { + assert(!static, s"nonsensical JS super call in static export of $sym") + genApplyForSymJSSuperCall(formalArgsRegistry, sym) + } else { + genApplyForSymNonJSSuperCall(formalArgsRegistry, sym, static) + } + } + + private def genApplyForSymJSSuperCall( + formalArgsRegistry: FormalArgsRegistry, sym: Symbol): js.Tree = { + implicit val pos = sym.pos + + assert(!sym.isClassConstructor, + "Trying to genApplyForSymJSSuperCall for the constructor " + + sym.fullName) + + val allArgs = formalArgsRegistry.genAllArgsRefsForForwarder() + + val superClass = { + val superClassSym = currentClassSym.superClass + if (isNestedJSClass(superClassSym)) { + js.VarRef(js.LocalIdent(JSSuperClassParamName))(jstpe.AnyType) + } else { + js.LoadJSConstructor(encodeClassName(superClassSym)) + } + } + + val receiver = js.This()(currentThisType) + val nameString = genExpr(jsNameOf(sym)) + + if (jsInterop.isJSGetter(sym)) { + assert(allArgs.isEmpty, + s"getter symbol $sym does not have a getter signature") + js.JSSuperSelect(superClass, receiver, nameString) + } else if (jsInterop.isJSSetter(sym)) { + assert(allArgs.size == 1 && allArgs.head.isInstanceOf[js.Tree], + s"setter symbol $sym does not have a setter signature") + js.Assign(js.JSSuperSelect(superClass, receiver, nameString), + allArgs.head.asInstanceOf[js.Tree]) + } else { + js.JSSuperMethodCall(superClass, receiver, nameString, allArgs) + } + } + + private def genApplyForSymNonJSSuperCall( + formalArgsRegistry: FormalArgsRegistry, sym: Symbol, + static: Boolean): js.Tree = { + implicit val pos = sym.pos + + val varDefs = new mutable.ListBuffer[js.VarDef] + + for ((param, i) <- jsParamInfos(sym).zipWithIndex) { + val rhs = genScalaArg(sym, i, formalArgsRegistry, param, static, captures = Nil)( + prevArgsCount => varDefs.take(prevArgsCount).toList.map(_.ref)) + + varDefs += js.VarDef(freshLocalIdent("prep" + i), NoOriginalName, + rhs.tpe, mutable = false, rhs) + } + + val builtVarDefs = varDefs.result() + + val jsResult = genResult(sym, builtVarDefs.map(_.ref), static) + + js.Block(builtVarDefs :+ jsResult) + } + + /** Generates a Scala argument from dispatched JavaScript arguments + * (unboxing and default parameter handling). + */ + def genScalaArg(methodSym: Symbol, paramIndex: Int, + formalArgsRegistry: FormalArgsRegistry, param: JSParamInfo, + static: Boolean, captures: List[js.Tree])( + previousArgsValues: Int => List[js.Tree])( + implicit pos: Position): js.Tree = { + + if (param.repeated) { + genJSArrayToVarArgs(formalArgsRegistry.genVarargRef(paramIndex)) + } else { + val jsArg = formalArgsRegistry.genArgRef(paramIndex) + // Unboxed argument (if it is defined) + val unboxedArg = fromAny(jsArg, param.tpe) + + if (param.hasDefault) { + // If argument is undefined and there is a default getter, call it + val default = genCallDefaultGetter(methodSym, paramIndex, + param.sym.pos, static, captures)(previousArgsValues) + js.If(js.BinaryOp(js.BinaryOp.===, jsArg, js.Undefined()), + default, unboxedArg)(unboxedArg.tpe) + } else { + // Otherwise, it is always the unboxed argument + unboxedArg + } + } + } + + def genCallDefaultGetter(sym: Symbol, paramIndex: Int, + paramPos: Position, static: Boolean, captures: List[js.Tree])( + previousArgsValues: Int => List[js.Tree])( + implicit pos: Position): js.Tree = { + + val owner = sym.owner + val isNested = owner.isLifted && !isStaticModule(owner.originalOwner) + + val (trgSym, trgTree) = { + if (!sym.isClassConstructor && !static) { + /* Default getter is on the receiver. + * + * Since we only use this method for class internal exports + * dispatchers, we know the default getter is on `this`. This applies + * to both top-level and nested classes. + */ + (owner, js.This()(currentThisType)) + } else if (isNested) { + assert(captures.size == 1, + s"expected exactly one capture got $captures ($sym at $pos)") + + /* Find the module accessor. + * + * #4465: If owner is a nested class, the linked class is *not* a + * module value, but another class. In this case we need to call the + * module accessor on the enclosing class to retrieve this. + * + * #4526: If the companion module is private, linkedClassOfClass + * does not work (because the module name is prefixed with the full + * path). So we find the module accessor first and take its result + * type to be the companion module type. + */ + val outer = owner.originalOwner + + val modAccessor = { + val name = enteringPhase(currentRun.typerPhase) { + owner.unexpandedName.toTermName + } + + outer.info.members.find { sym => + sym.isModule && sym.unexpandedName == name + }.getOrElse { + throw new AssertionError( + s"couldn't find module accessor for ${owner.fullName} at $pos") + } + } + + val receiver = captures.head + + val trgSym = modAccessor.tpe.resultType.typeSymbol + + val trgTree = if (isJSType(outer)) { + genApplyJSClassMethod(receiver, modAccessor, Nil) + } else { + genApplyMethodMaybeStatically(receiver, modAccessor, Nil) + } + + (trgSym, trgTree) + } else if (sym.isClassConstructor) { + assert(captures.isEmpty, "expected empty captures") + + /* Get the companion module class. + * For classes nested inside modules the sym.owner.companionModule + * can be broken, therefore companionModule is fetched at + * uncurryPhase. + */ + val trgSym = enteringPhase(currentRun.uncurryPhase) { + owner.linkedClassOfClass + } + (trgSym, genLoadModule(trgSym)) + } else { + assert(static, "expected static") + assert(captures.isEmpty, "expected empty captures") + (owner, genLoadModule(owner)) + } + } + + val defaultGetter = trgSym.tpe.member( + nme.defaultGetterName(sym.name, paramIndex + 1)) + + assert(defaultGetter.exists, + s"need default getter for method ${sym.fullName}") + assert(!defaultGetter.isOverloaded, + s"found overloaded default getter $defaultGetter") + + // Pass previous arguments to defaultGetter + val defaultGetterArgs = previousArgsValues(defaultGetter.tpe.params.size) + + val callGetter = if (isJSType(trgSym)) { + if (isNonNativeJSClass(defaultGetter.owner)) { + if (defaultGetter.hasAnnotation(JSOptionalAnnotation)) + js.Undefined() + else + genApplyJSClassMethod(trgTree, defaultGetter, defaultGetterArgs) + } else if (defaultGetter.owner == trgSym) { + /* We get here if a non-native constructor has a native companion. + * This is reported on a per-class level. + */ + assert(sym.isClassConstructor, + s"got non-constructor method $sym with default method in JS native companion") + js.Undefined() + } else { + reporter.error(paramPos, "When overriding a native method " + + "with default arguments, the overriding method must " + + "explicitly repeat the default arguments.") + js.Undefined() + } + } else { + genApplyMethod(trgTree, defaultGetter, defaultGetterArgs) + } + + // #4684 If the getter returns void, we must "box" it by returning undefined + if (callGetter.tpe == jstpe.NoType) + js.Block(callGetter, js.Undefined()) + else + callGetter + } + + /** Generate the final forwarding call to the exported method. */ + private def genResult(sym: Symbol, args: List[js.Tree], + static: Boolean)(implicit pos: Position): js.Tree = { + def receiver = { + if (static) + genLoadModule(sym.owner) + else + js.This()(currentThisType) + } + + if (isNonNativeJSClass(currentClassSym)) { + assert(sym.owner == currentClassSym.get, sym.fullName) + ensureResultBoxed(genApplyJSClassMethod(receiver, sym, args), sym) + } else { + if (sym.isClassConstructor) + genNew(currentClassSym, sym, args) + else if (sym.isPrivate) + ensureResultBoxed(genApplyMethodStatically(receiver, sym, args), sym) + else + ensureResultBoxed(genApplyMethod(receiver, sym, args), sym) + } + } + + abstract class Exported(val sym: Symbol, + // Parameters participating in overload resolution. + val params: immutable.IndexedSeq[JSParamInfo]) { + + assert(!params.exists(_.capture), "illegal capture params in Exported") + + final def exportArgTypeAt(paramIndex: Int): Type = { + if (paramIndex < params.length) { + params(paramIndex).tpe + } else { + assert(hasRepeatedParam, + s"$sym does not have varargs nor enough params for $paramIndex") + params.last.tpe + } + } + + def genBody(formalArgsRegistry: FormalArgsRegistry): js.Tree + + lazy val hasRepeatedParam = params.lastOption.exists(_.repeated) + } + + private class ExportedSymbol(sym: Symbol, static: Boolean) + extends Exported(sym, jsParamInfos(sym).toIndexedSeq) { + def genBody(formalArgsRegistry: FormalArgsRegistry): js.Tree = + genApplyForSym(formalArgsRegistry, sym, static) + } + } + + private sealed abstract class RTTypeTest + + private case class PrimitiveTypeTest(tpe: jstpe.Type, rank: Int) + extends RTTypeTest + + // scalastyle:off equals.hash.code + private case class InstanceOfTypeTest(tpe: Type) extends RTTypeTest { + override def equals(that: Any): Boolean = { + that match { + case InstanceOfTypeTest(thatTpe) => tpe =:= thatTpe + case _ => false + } + } + } + // scalastyle:on equals.hash.code + + private case object NoTypeTest extends RTTypeTest + + // Very simple O(n²) topological sort for elements assumed to be distinct + private def topoSortDistinctsWith[A <: AnyRef](coll: List[A])( + lteq: (A, A) => Boolean): List[A] = { + @scala.annotation.tailrec + def loop(coll: List[A], acc: List[A]): List[A] = { + if (coll.isEmpty) acc + else if (coll.tail.isEmpty) coll.head :: acc + else { + val (lhs, rhs) = coll.span(x => !coll.forall( + y => (x eq y) || !lteq(x, y))) + assert(!rhs.isEmpty, s"cycle while ordering $coll") + loop(lhs ::: rhs.tail, rhs.head :: acc) + } + } + + loop(coll, Nil) + } + + private def typeTestForTpe(tpe: Type): RTTypeTest = { + tpe match { + case tpe: ErasedValueType => + InstanceOfTypeTest(tpe.valueClazz.typeConstructor) + + case _ => + import org.scalajs.ir.Names + + (toIRType(tpe): @unchecked) match { + case jstpe.AnyType => NoTypeTest + + case jstpe.NoType => PrimitiveTypeTest(jstpe.UndefType, 0) + case jstpe.BooleanType => PrimitiveTypeTest(jstpe.BooleanType, 1) + case jstpe.CharType => PrimitiveTypeTest(jstpe.CharType, 2) + case jstpe.ByteType => PrimitiveTypeTest(jstpe.ByteType, 3) + case jstpe.ShortType => PrimitiveTypeTest(jstpe.ShortType, 4) + case jstpe.IntType => PrimitiveTypeTest(jstpe.IntType, 5) + case jstpe.LongType => PrimitiveTypeTest(jstpe.LongType, 6) + case jstpe.FloatType => PrimitiveTypeTest(jstpe.FloatType, 7) + case jstpe.DoubleType => PrimitiveTypeTest(jstpe.DoubleType, 8) + + case jstpe.ClassType(Names.BoxedUnitClass) => PrimitiveTypeTest(jstpe.UndefType, 0) + case jstpe.ClassType(Names.BoxedStringClass) => PrimitiveTypeTest(jstpe.StringType, 9) + case jstpe.ClassType(_) => InstanceOfTypeTest(tpe) + + case jstpe.ArrayType(_) => InstanceOfTypeTest(tpe) + } + } + } + + // Group-by that does not rely on hashCode(), only equals() - O(n²) + private def groupByWithoutHashCode[A, B]( + coll: List[A])(f: A => B): List[(B, List[A])] = { + + import scala.collection.mutable.ArrayBuffer + val m = new ArrayBuffer[(B, List[A])] + m.sizeHint(coll.length) + + for (elem <- coll) { + val key = f(elem) + val index = m.indexWhere(_._1 == key) + if (index < 0) m += ((key, List(elem))) + else m(index) = (key, elem :: m(index)._2) + } + + m.toList + } + + private def genThrowTypeError(msg: String = "No matching overload")( + implicit pos: Position): js.Tree = { + js.Throw(js.StringLiteral(msg)) + } + + class FormalArgsRegistry(minArgc: Int, needsRestParam: Boolean) { + private val fixedParamNames: scala.collection.immutable.IndexedSeq[LocalName] = + (0 until minArgc).toIndexedSeq.map(_ => freshLocalIdent("arg")(NoPosition).name) + + private val restParamName: LocalName = + if (needsRestParam) freshLocalIdent("rest")(NoPosition).name + else null + + def genFormalArgs()(implicit pos: Position): (List[js.ParamDef], Option[js.ParamDef]) = { + val fixedParamDefs = fixedParamNames.toList.map { paramName => + js.ParamDef(js.LocalIdent(paramName), NoOriginalName, jstpe.AnyType, + mutable = false) + } + + val restParam = { + if (needsRestParam) { + Some(js.ParamDef(js.LocalIdent(restParamName), + NoOriginalName, jstpe.AnyType, mutable = false)) + } else { + None + } + } + + (fixedParamDefs, restParam) + } + + def genArgRef(index: Int)(implicit pos: Position): js.Tree = { + if (index < minArgc) + js.VarRef(js.LocalIdent(fixedParamNames(index)))(jstpe.AnyType) + else + js.JSSelect(genRestArgRef(), js.IntLiteral(index - minArgc)) + } + + def genVarargRef(fixedParamCount: Int)(implicit pos: Position): js.Tree = { + val restParam = genRestArgRef() + assert(fixedParamCount >= minArgc, + s"genVarargRef($fixedParamCount) with minArgc = $minArgc at $pos") + if (fixedParamCount == minArgc) { + restParam + } else { + js.JSMethodApply(restParam, js.StringLiteral("slice"), + List(js.IntLiteral(fixedParamCount - minArgc))) + } + } + + def genRestArgRef()(implicit pos: Position): js.Tree = { + assert(needsRestParam, + s"trying to generate a reference to non-existent rest param at $pos") + js.VarRef(js.LocalIdent(restParamName))(jstpe.AnyType) + } + + def genAllArgsRefsForForwarder()(implicit pos: Position): List[js.TreeOrJSSpread] = { + val fixedArgRefs = fixedParamNames.toList.map { paramName => + js.VarRef(js.LocalIdent(paramName))(jstpe.AnyType) + } + + if (needsRestParam) { + val restArgRef = js.VarRef(js.LocalIdent(restParamName))(jstpe.AnyType) + fixedArgRefs :+ js.JSSpread(restArgRef) + } else { + fixedArgRefs + } + } + } +} diff --git a/compiler/src/main/scala/org/scalajs/nscplugin/GenJSFiles.scala b/compiler/src/main/scala/org/scalajs/nscplugin/GenJSFiles.scala new file mode 100644 index 0000000000..10d2ac4f21 --- /dev/null +++ b/compiler/src/main/scala/org/scalajs/nscplugin/GenJSFiles.scala @@ -0,0 +1,50 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin + +import scala.tools.nsc._ +import scala.tools.nsc.io.AbstractFile +import scala.reflect.internal.pickling.PickleBuffer + +import java.io._ + +import org.scalajs.ir + +/** Send JS ASTs to files + * + * @author Sébastien Doeraene + */ +trait GenJSFiles[G <: Global with Singleton] extends SubComponent { + self: GenJSCode[G] => + + import global._ + import jsAddons._ + + def genIRFile(cunit: CompilationUnit, tree: ir.Trees.ClassDef): Unit = { + val outfile = getFileFor(cunit, tree.name.name, ".sjsir") + val output = outfile.bufferedOutput + try ir.Serializers.serialize(output, tree) + finally output.close() + } + + private def getFileFor(cunit: CompilationUnit, className: ir.Names.ClassName, + suffix: String): AbstractFile = { + val baseDir: AbstractFile = + settings.outputDirs.outputDirFor(cunit.source.file) + + val pathParts = className.nameString.split('.') + val dir = pathParts.init.foldLeft(baseDir)(_.subdirectoryNamed(_)) + val filename = pathParts.last + dir.fileNamed(filename + suffix) + } +} diff --git a/compiler/src/main/scala/org/scalajs/nscplugin/JSDefinitions.scala b/compiler/src/main/scala/org/scalajs/nscplugin/JSDefinitions.scala new file mode 100644 index 0000000000..389c76d5c6 --- /dev/null +++ b/compiler/src/main/scala/org/scalajs/nscplugin/JSDefinitions.scala @@ -0,0 +1,153 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin + +import scala.tools.nsc._ + +/** Core definitions for Scala.js + * + * @author Sébastien Doeraene + */ +trait JSDefinitions { + val global: Global + + import global._ + + // scalastyle:off line.size.limit + + object jsDefinitions extends JSDefinitionsClass + + import definitions._ + import rootMirror._ + + class JSDefinitionsClass { + + lazy val HackedStringClass = getClassIfDefined("java.lang._String") + lazy val HackedStringModClass = getModuleIfDefined("java.lang._String").moduleClass + + lazy val JavaLangVoidClass = getRequiredClass("java.lang.Void") + + lazy val BoxedUnitModClass = BoxedUnitModule.moduleClass + + lazy val ScalaJSJSPackageModule = getPackageObject("scala.scalajs.js") + lazy val JSPackage_typeOf = getMemberMethod(ScalaJSJSPackageModule, newTermName("typeOf")) + lazy val JSPackage_constructorOf = getMemberMethod(ScalaJSJSPackageModule, newTermName("constructorOf")) + lazy val JSPackage_native = getMemberMethod(ScalaJSJSPackageModule, newTermName("native")) + lazy val JSPackage_undefined = getMemberMethod(ScalaJSJSPackageModule, newTermName("undefined")) + lazy val JSPackage_dynamicImport = getMemberMethod(ScalaJSJSPackageModule, newTermName("dynamicImport")) + + lazy val JSNativeAnnotation = getRequiredClass("scala.scalajs.js.native") + + lazy val JSAnyClass = getRequiredClass("scala.scalajs.js.Any") + lazy val JSDynamicClass = getRequiredClass("scala.scalajs.js.Dynamic") + lazy val JSObjectClass = getRequiredClass("scala.scalajs.js.Object") + lazy val JSFunctionClass = getRequiredClass("scala.scalajs.js.Function") + lazy val JSThisFunctionClass = getRequiredClass("scala.scalajs.js.ThisFunction") + + lazy val UnionClass = getRequiredClass("scala.scalajs.js.$bar") + + lazy val JSArrayClass = getRequiredClass("scala.scalajs.js.Array") + + lazy val JavaScriptExceptionClass = getClassIfDefined("scala.scalajs.js.JavaScriptException") + + lazy val JSNameAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSName") + lazy val JSBracketAccessAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSBracketAccess") + lazy val JSBracketCallAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSBracketCall") + lazy val JSExportAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSExport") + lazy val JSExportAllAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSExportAll") + lazy val JSExportStaticAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSExportStatic") + lazy val JSExportTopLevelAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSExportTopLevel") + lazy val JSImportAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSImport") + lazy val JSGlobalAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSGlobal") + lazy val JSGlobalScopeAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSGlobalScope") + lazy val JSOperatorAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSOperator") + + lazy val JavaDefaultMethodAnnotation = getRequiredClass("scala.scalajs.js.annotation.JavaDefaultMethod") + + lazy val JSImportNamespaceObject = getRequiredModule("scala.scalajs.js.annotation.JSImport.Namespace") + + lazy val ExposedJSMemberAnnot = getRequiredClass("scala.scalajs.js.annotation.internal.ExposedJSMember") + lazy val JSOptionalAnnotation = getRequiredClass("scala.scalajs.js.annotation.internal.JSOptional") + lazy val JSTypeAnnot = getRequiredClass("scala.scalajs.js.annotation.internal.JSType") + lazy val WasPublicBeforeTyperClass = getRequiredClass("scala.scalajs.js.annotation.internal.WasPublicBeforeTyper") + + lazy val JSDynamicModule = JSDynamicClass.companionModule + lazy val JSDynamic_newInstance = getMemberMethod(JSDynamicModule, newTermName("newInstance")) + lazy val JSDynamicLiteral = getMemberModule(JSDynamicModule, newTermName("literal")) + lazy val JSDynamicLiteral_applyDynamicNamed = getMemberMethod(JSDynamicLiteral, newTermName("applyDynamicNamed")) + lazy val JSDynamicLiteral_applyDynamic = getMemberMethod(JSDynamicLiteral, newTermName("applyDynamic")) + + lazy val JSArrayModule = JSArrayClass.companionModule + lazy val JSArray_create = getMemberMethod(JSArrayModule, newTermName("apply")) + + lazy val JSConstructorTagModule = getRequiredModule("scala.scalajs.js.ConstructorTag") + lazy val JSConstructorTag_materialize = getMemberMethod(JSConstructorTagModule, newTermName("materialize")) + + lazy val JSNewModule = getRequiredModule("scala.scalajs.js.new") + lazy val JSNewModuleClass = JSNewModule.moduleClass + lazy val JSNew_target = getMemberMethod(JSNewModuleClass, newTermName("target")) + + lazy val JSImportModule = getRequiredModule("scala.scalajs.js.import") + lazy val JSImportModuleClass = JSImportModule.moduleClass + lazy val JSImport_apply = getMemberMethod(JSImportModuleClass, nme.apply) + lazy val JSImport_meta = getMemberMethod(JSImportModuleClass, newTermName("meta")) + + lazy val SpecialPackageModule = getPackageObject("scala.scalajs.js.special") + lazy val Special_strictEquals = getMemberMethod(SpecialPackageModule, newTermName("strictEquals")) + lazy val Special_in = getMemberMethod(SpecialPackageModule, newTermName("in")) + lazy val Special_instanceof = getMemberMethod(SpecialPackageModule, newTermName("instanceof")) + lazy val Special_delete = getMemberMethod(SpecialPackageModule, newTermName("delete")) + lazy val Special_forin = getMemberMethod(SpecialPackageModule, newTermName("forin")) + lazy val Special_throw = getMemberMethod(SpecialPackageModule, newTermName("throw")) + lazy val Special_tryCatch = getMemberMethod(SpecialPackageModule, newTermName("tryCatch")) + lazy val Special_wrapAsThrowable = getMemberMethod(SpecialPackageModule, newTermName("wrapAsThrowable")) + lazy val Special_unwrapFromThrowable = getMemberMethod(SpecialPackageModule, newTermName("unwrapFromThrowable")) + lazy val Special_debugger = getMemberMethod(SpecialPackageModule, newTermName("debugger")) + + lazy val RuntimePackageModule = getPackageObject("scala.scalajs.runtime") + lazy val Runtime_toScalaVarArgs = getMemberMethod(RuntimePackageModule, newTermName("toScalaVarArgs")) + lazy val Runtime_toJSVarArgs = getMemberMethod(RuntimePackageModule, newTermName("toJSVarArgs")) + lazy val Runtime_constructorOf = getMemberMethod(RuntimePackageModule, newTermName("constructorOf")) + lazy val Runtime_newConstructorTag = getMemberMethod(RuntimePackageModule, newTermName("newConstructorTag")) + lazy val Runtime_createInnerJSClass = getMemberMethod(RuntimePackageModule, newTermName("createInnerJSClass")) + lazy val Runtime_createLocalJSClass = getMemberMethod(RuntimePackageModule, newTermName("createLocalJSClass")) + lazy val Runtime_withContextualJSClassValue = getMemberMethod(RuntimePackageModule, newTermName("withContextualJSClassValue")) + lazy val Runtime_privateFieldsSymbol = getMemberMethod(RuntimePackageModule, newTermName("privateFieldsSymbol")) + lazy val Runtime_linkingInfo = getMemberMethod(RuntimePackageModule, newTermName("linkingInfo")) + lazy val Runtime_identityHashCode = getMemberMethod(RuntimePackageModule, newTermName("identityHashCode")) + lazy val Runtime_dynamicImport = getMemberMethod(RuntimePackageModule, newTermName("dynamicImport")) + + lazy val DynamicImportThunkClass = getRequiredClass("scala.scalajs.runtime.DynamicImportThunk") + lazy val DynamicImportThunkClass_apply = getMemberMethod(DynamicImportThunkClass, nme.apply) + + lazy val Tuple2_apply = getMemberMethod(TupleClass(2).companionModule, nme.apply) + + // This is a def, since similar symbols (arrayUpdateMethod, etc.) are in runDefinitions + // (rather than definitions) and we weren't sure if it is safe to make this a lazy val + def ScalaRunTime_isArray: Symbol = getMemberMethod(ScalaRunTimeModule, newTermName("isArray")).suchThat(_.tpe.params.size == 2) + + lazy val ReflectModule = getRequiredModule("scala.scalajs.reflect.Reflect") + lazy val Reflect_registerLoadableModuleClass = getMemberMethod(ReflectModule, newTermName("registerLoadableModuleClass")) + lazy val Reflect_registerInstantiatableClass = getMemberMethod(ReflectModule, newTermName("registerInstantiatableClass")) + + lazy val EnableReflectiveInstantiationAnnotation = getRequiredClass("scala.scalajs.reflect.annotation.EnableReflectiveInstantiation") + + lazy val ExecutionContextModule = getRequiredModule("scala.concurrent.ExecutionContext") + lazy val ExecutionContext_global = getMemberMethod(ExecutionContextModule, newTermName("global")) + + lazy val ExecutionContextImplicitsModule = getRequiredModule("scala.concurrent.ExecutionContext.Implicits") + lazy val ExecutionContextImplicits_global = getMemberMethod(ExecutionContextImplicitsModule, newTermName("global")) + } + + // scalastyle:on line.size.limit +} diff --git a/compiler/src/main/scala/org/scalajs/nscplugin/JSEncoding.scala b/compiler/src/main/scala/org/scalajs/nscplugin/JSEncoding.scala new file mode 100644 index 0000000000..2d7105cd91 --- /dev/null +++ b/compiler/src/main/scala/org/scalajs/nscplugin/JSEncoding.scala @@ -0,0 +1,326 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin + +import scala.collection.mutable + +import scala.tools.nsc._ + +import org.scalajs.ir +import org.scalajs.ir.{Trees => js, Types => jstpe} +import org.scalajs.ir.Names.{LocalName, LabelName, FieldName, SimpleMethodName, MethodName, ClassName} +import org.scalajs.ir.OriginalName +import org.scalajs.ir.OriginalName.NoOriginalName +import org.scalajs.ir.UTF8String + +import org.scalajs.nscplugin.util.{ScopedVar, VarBox} +import ScopedVar.withScopedVars + +/** Encoding of symbol names for the IR. */ +trait JSEncoding[G <: Global with Singleton] extends SubComponent { + self: GenJSCode[G] => + + import global._ + import jsAddons._ + + /** Name of the capture param storing the JS super class. + * + * This is used by the dispatchers of exposed JS methods and properties of + * nested JS classes when they need to perform a super call. Other super + * calls (in the actual bodies of the methods, not in the dispatchers) do + * not use this value, since they are implemented as static methods that do + * not have access to it. Instead, they get the JS super class value through + * the magic method inserted by `ExplicitLocalJS`, leveraging `lambdalift` + * to ensure that it is properly captured. + * + * Using this identifier is only allowed if it was reserved in the current + * local name scope using [[reserveLocalName]]. Otherwise, this name can + * clash with another local identifier. + */ + final val JSSuperClassParamName = LocalName("superClass$") + + private val xLocalName = LocalName("x") + + private val ScalaRuntimeNullClass = ClassName("scala.runtime.Null$") + private val ScalaRuntimeNothingClass = ClassName("scala.runtime.Nothing$") + + private val dynamicImportForwarderSimpleName = SimpleMethodName("dynamicImport$") + + // Fresh local name generator ---------------------------------------------- + + private val usedLocalNames = new ScopedVar[mutable.Set[LocalName]] + private val localSymbolNames = new ScopedVar[mutable.Map[Symbol, LocalName]] + private val usedLabelNames = new ScopedVar[mutable.Set[LabelName]] + private val labelSymbolNames = new ScopedVar[mutable.Map[Symbol, LabelName]] + private val returnLabelName = new ScopedVar[VarBox[Option[LabelName]]] + + def withNewLocalNameScope[A](body: => A): A = { + withScopedVars( + usedLocalNames := mutable.Set.empty, + localSymbolNames := mutable.Map.empty, + usedLabelNames := mutable.Set.empty, + labelSymbolNames := mutable.Map.empty, + returnLabelName := null + )(body) + } + + def reserveLocalName(name: LocalName): Unit = { + require(usedLocalNames.isEmpty, + s"Trying to reserve the name '$name' but names have already been " + + "allocated") + usedLocalNames += name + } + + def withNewReturnableScope(tpe: jstpe.Type)(body: => js.Tree)( + implicit pos: ir.Position): js.Tree = { + withScopedVars( + returnLabelName := new VarBox(None) + ) { + val inner = body + returnLabelName.get.value match { + case None => + inner + case Some(labelName) => + js.Labeled(js.LabelIdent(labelName), tpe, inner) + } + } + } + + private def freshNameGeneric[N <: ir.Names.Name](base: N, + usedNamesSet: mutable.Set[N])( + withSuffix: (N, String) => N): N = { + + var suffix = 1 + var result = base + while (usedNamesSet(result)) { + suffix += 1 + result = withSuffix(base, "$" + suffix) + } + usedNamesSet += result + result + } + + private def freshName(base: LocalName): LocalName = + freshNameGeneric(base, usedLocalNames)(_.withSuffix(_)) + + private def freshName(base: String): LocalName = + freshName(LocalName(base)) + + def freshLocalIdent()(implicit pos: ir.Position): js.LocalIdent = + js.LocalIdent(freshName(xLocalName)) + + def freshLocalIdent(base: LocalName)(implicit pos: ir.Position): js.LocalIdent = + js.LocalIdent(freshName(base)) + + def freshLocalIdent(base: String)(implicit pos: ir.Position): js.LocalIdent = + freshLocalIdent(LocalName(base)) + + private def localSymbolName(sym: Symbol): LocalName = { + localSymbolNames.getOrElseUpdate(sym, { + /* The emitter does not like local variables that start with a '$', + * because it needs to encode them not to clash with emitter-generated + * names. There are two common cases, caused by scalac-generated names: + * - the `$this` parameter of tailrec methods and "extension" methods of + * AnyVals, which scalac knows as `nme.SELF`, and + * - the `$outer` parameter of inner class constructors, which scalac + * knows as `nme.OUTER`. + * We choose different base names for those two cases instead, so that + * the avoidance mechanism of the emitter doesn't happen as a common + * case. It can still happen for user-defined variables, but in that case + * the emitter will deal with it. + */ + val base = sym.name match { + case nme.SELF => "this$" // instead of $this + case nme.OUTER => "outer" // instead of $outer + case name => name.toString() + } + freshName(base) + }) + } + + private def freshLabelName(base: LabelName): LabelName = + freshNameGeneric(base, usedLabelNames)(_.withSuffix(_)) + + private def freshLabelName(base: String): LabelName = + freshLabelName(LabelName(base)) + + def freshLabelIdent(base: String)(implicit pos: ir.Position): js.LabelIdent = + js.LabelIdent(freshLabelName(base)) + + private def labelSymbolName(sym: Symbol): LabelName = + labelSymbolNames.getOrElseUpdate(sym, freshLabelName(sym.name.toString)) + + def getEnclosingReturnLabel()(implicit pos: ir.Position): js.LabelIdent = { + val box = returnLabelName.get + if (box == null) + throw new IllegalStateException(s"No enclosing returnable scope at $pos") + if (box.value.isEmpty) + box.value = Some(freshLabelName("_return")) + js.LabelIdent(box.value.get) + } + + // Encoding methods ---------------------------------------------------------- + + def encodeLabelSym(sym: Symbol)(implicit pos: Position): js.LabelIdent = { + require(sym.isLabel, "encodeLabelSym called with non-label symbol: " + sym) + js.LabelIdent(labelSymbolName(sym)) + } + + def encodeFieldSym(sym: Symbol)(implicit pos: Position): js.FieldIdent = { + requireSymIsField(sym) + val name = sym.name.dropLocal + js.FieldIdent(FieldName(name.toString())) + } + + def encodeFieldSymAsStringLiteral(sym: Symbol)( + implicit pos: Position): js.StringLiteral = { + + requireSymIsField(sym) + js.StringLiteral(sym.name.dropLocal.toString()) + } + + private def requireSymIsField(sym: Symbol): Unit = { + require(sym.owner.isClass && sym.isTerm && !sym.isMethod && !sym.isModule, + "encodeFieldSym called with non-field symbol: " + sym) + } + + def encodeMethodSym(sym: Symbol, reflProxy: Boolean = false)( + implicit pos: Position): js.MethodIdent = { + + require(sym.isMethod, + "encodeMethodSym called with non-method symbol: " + sym) + + val tpe = sym.tpe + + val paramTypeRefs0 = tpe.params.map(p => paramOrResultTypeRef(p.tpe)) + + val hasExplicitThisParameter = isNonNativeJSClass(sym.owner) + val paramTypeRefs = + if (!hasExplicitThisParameter) paramTypeRefs0 + else paramOrResultTypeRef(sym.owner.toTypeConstructor) :: paramTypeRefs0 + + val name = sym.name + val simpleName = SimpleMethodName(name.toString()) + + val methodName = { + if (sym.isClassConstructor) + MethodName.constructor(paramTypeRefs) + else if (reflProxy) + MethodName.reflectiveProxy(simpleName, paramTypeRefs) + else + MethodName(simpleName, paramTypeRefs, paramOrResultTypeRef(tpe.resultType)) + } + + js.MethodIdent(methodName) + } + + def encodeStaticFieldGetterSym(sym: Symbol)( + implicit pos: Position): js.MethodIdent = { + + require(sym.isStaticMember, + "encodeStaticFieldGetterSym called with non-static symbol: " + sym) + + val name = sym.name + val resultTypeRef = paramOrResultTypeRef(sym.tpe) + val methodName = MethodName(name.toString(), Nil, resultTypeRef) + js.MethodIdent(methodName) + } + + def encodeDynamicImportForwarderIdent(params: List[Symbol])( + implicit pos: Position): js.MethodIdent = { + val paramTypeRefs = params.map(sym => paramOrResultTypeRef(sym.tpe)) + val resultTypeRef = jstpe.ClassRef(ir.Names.ObjectClass) + val methodName = + MethodName(dynamicImportForwarderSimpleName, paramTypeRefs, resultTypeRef) + + js.MethodIdent(methodName) + } + + /** Computes the internal name for a type. */ + private def paramOrResultTypeRef(tpe: Type): jstpe.TypeRef = { + toTypeRef(tpe) match { + case jstpe.ClassRef(ScalaRuntimeNothingClass) => jstpe.NothingRef + case jstpe.ClassRef(ScalaRuntimeNullClass) => jstpe.NullRef + case typeRef => typeRef + } + } + + def encodeLocalSym(sym: Symbol)(implicit pos: Position): js.LocalIdent = { + /* The isValueParameter case is necessary to work around an internal bug + * of scalac: for some @varargs methods, the owner of some parameters is + * the enclosing class rather the method, so !sym.owner.isClass fails. + * Go figure ... + * See #1440 + */ + require(sym.isValueParameter || + (!sym.owner.isClass && sym.isTerm && !sym.isMethod && !sym.isModule), + "encodeLocalSym called with non-local symbol: " + sym) + js.LocalIdent(localSymbolName(sym)) + } + + def encodeClassType(sym: Symbol): jstpe.Type = { + if (sym == definitions.ObjectClass) jstpe.AnyType + else if (isJSType(sym)) jstpe.AnyType + else { + assert(sym != definitions.ArrayClass, + "encodeClassType() cannot be called with ArrayClass") + jstpe.ClassType(encodeClassName(sym)) + } + } + + def encodeClassNameIdent(sym: Symbol)(implicit pos: Position): js.ClassIdent = + js.ClassIdent(encodeClassName(sym)) + + private val BoxedStringModuleClassName = ClassName("java.lang.String$") + + def encodeClassName(sym: Symbol): ClassName = { + assert(!sym.isPrimitiveValueClass, + s"Illegal encodeClassName(${sym.fullName}") + if (sym == jsDefinitions.HackedStringClass) { + ir.Names.BoxedStringClass + } else if (sym == jsDefinitions.HackedStringModClass) { + BoxedStringModuleClassName + } else if (sym == definitions.BoxedUnitClass || sym == jsDefinitions.BoxedUnitModClass) { + // Rewire scala.runtime.BoxedUnit to java.lang.Void, as the IR expects + // BoxedUnit$ is a JVM artifact + ir.Names.BoxedUnitClass + } else { + ClassName(sym.fullName + (if (needsModuleClassSuffix(sym)) "$" else "")) + } + } + + def needsModuleClassSuffix(sym: Symbol): Boolean = + sym.isModuleClass && !sym.isJavaDefined && !isImplClass(sym) + + def originalNameOfLocal(sym: Symbol): OriginalName = { + val irName = localSymbolName(sym) + val originalName = UTF8String(nme.unexpandedName(sym.name).decoded) + if (UTF8String.equals(originalName, irName.encoded)) NoOriginalName + else OriginalName(originalName) + } + + def originalNameOfField(sym: Symbol): OriginalName = + originalNameOf(sym.name.dropLocal) + + def originalNameOfMethod(sym: Symbol): OriginalName = + originalNameOf(sym.name) + + def originalNameOfClass(sym: Symbol): OriginalName = + originalNameOf(sym.fullNameAsName('.')) + + private def originalNameOf(name: Name): OriginalName = { + val originalName = nme.unexpandedName(name).decoded + if (originalName == name.toString) NoOriginalName + else OriginalName(originalName) + } +} diff --git a/compiler/src/main/scala/org/scalajs/nscplugin/JSGlobalAddons.scala b/compiler/src/main/scala/org/scalajs/nscplugin/JSGlobalAddons.scala new file mode 100644 index 0000000000..dea4d5529d --- /dev/null +++ b/compiler/src/main/scala/org/scalajs/nscplugin/JSGlobalAddons.scala @@ -0,0 +1,397 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin + +import scala.tools.nsc._ + +import scala.collection.mutable + +import org.scalajs.ir.Trees.JSNativeLoadSpec +import org.scalajs.ir.{Trees => js} + +/** Additions to Global meaningful for the JavaScript backend + * + * @author Sébastien Doeraene + */ +trait JSGlobalAddons extends JSDefinitions + with CompatComponent { + val global: Global + + import global._ + import jsDefinitions._ + import definitions._ + + /** JavaScript primitives, used in jscode */ + object jsPrimitives extends JSPrimitives { + val global: JSGlobalAddons.this.global.type = JSGlobalAddons.this.global + val jsAddons: ThisJSGlobalAddons = + JSGlobalAddons.this.asInstanceOf[ThisJSGlobalAddons] + } + + /** Extracts the super type of a `Template`, with type parameters reinvented + * so that the type is well-formed outside of the `Template`, i.e., at the + * same level where the corresponding `ImplDef` is defined. + */ + def extractSuperTpeFromImpl(impl: Template): Type = + reinventTypeParams(impl.parents.head.tpe) + + /** Reinvents all the type parameters of a `TypeRef`. + * + * This is done by existentially quantifying over all type parameters of + * the class type referenced by the `TypeRef`. + * + * As a simple example, given the definition + * {{{ + * class C[A, B <: AnyVal] + * }}} + * this transforms + * {{{ + * path.C[A, Int] + * }}} + * into + * {{{ + * path.C[_, _ <: AnyVal] + * }}} + * + * As a complex example, given the definition + * {{{ + * class D[A, B <: List[Seq[A]]] + * }}} + * this method transforms + * {{{ + * path.D[?0, ?1] forSome { type ?0; type ?1 <: List[Seq[?0]] } + * }}} + */ + private def reinventTypeParams(tp: Type): Type = { + tp match { + case TypeRef(pre, sym, _) if sym.isClass && sym.typeParams.nonEmpty => + val eparams = typeParamsToExistentials(sym) + existentialAbstraction(eparams, typeRef(pre, sym, eparams.map(_.tpe))) + case _ => + tp + } + } + + /** global javascript interop related helpers */ + object jsInterop { + import scala.reflect.NameTransformer + import scala.reflect.internal.Flags + + /** TopLevel exports, by owner. */ + private val topLevelExports = + mutable.Map.empty[Symbol, List[TopLevelExportInfo]] + + /** Static exports, by owner. */ + private val staticExports = + mutable.Map.empty[Symbol, List[StaticExportInfo]] + + /** JS native load specs of the symbols in the current compilation run. */ + private val jsNativeLoadSpecs = + mutable.Map.empty[Symbol, JSNativeLoadSpec] + + private val exportPrefix = "$js$exported$" + private val methodExportPrefix = exportPrefix + "meth$" + private val propExportPrefix = exportPrefix + "prop$" + + /** Info for a non-member export. */ + sealed trait ExportInfo { + val pos: Position + } + + /* Not final because it causes the following compile warning: + * "The outer reference in this type test cannot be checked at run time." + */ + case class TopLevelExportInfo(moduleID: String, jsName: String)( + val pos: Position) extends ExportInfo + case class StaticExportInfo(jsName: String)(val pos: Position) + extends ExportInfo + + sealed abstract class JSName { + def displayName: String + } + + object JSName { + // Not final because it causes annoying compile warnings + case class Literal(name: String) extends JSName { + def displayName: String = name + } + + // Not final because it causes annoying compile warnings + case class Computed(sym: Symbol) extends JSName { + def displayName: String = sym.fullName + } + } + + sealed abstract class JSCallingConvention { + def displayName: String + } + + object JSCallingConvention { + case object Call extends JSCallingConvention { + def displayName: String = "function application" + } + + case object BracketAccess extends JSCallingConvention { + def displayName: String = "bracket access" + } + + case object BracketCall extends JSCallingConvention { + def displayName: String = "bracket call" + } + + case class Method(name: JSName) extends JSCallingConvention { + def displayName: String = "method '" + name.displayName + "'" + } + + case class Property(name: JSName) extends JSCallingConvention { + def displayName: String = "property '" + name.displayName + "'" + } + + case class UnaryOp(code: js.JSUnaryOp.Code) extends JSCallingConvention { + def displayName: String = "unary operator" + } + + case class BinaryOp(code: js.JSBinaryOp.Code) extends JSCallingConvention { + def displayName: String = "binary operator" + } + + def of(sym: Symbol): JSCallingConvention = { + assert(sym.isTerm, s"got non-term symbol: $sym") + + if (isJSBracketAccess(sym)) { + BracketAccess + } else if (isJSBracketCall(sym)) { + BracketCall + } else { + def default = { + val jsName = jsNameOf(sym) + if (isJSProperty(sym)) Property(jsName) + else Method(jsName) + } + + if (!sym.hasAnnotation(JSNameAnnotation)) { + lazy val pc = sym.paramss.map(_.size).sum + + sym.name match { + case nme.apply => Call + + case JSUnaryOpMethodName(code, defaultsToOp) + if (defaultsToOp || sym.hasAnnotation(JSOperatorAnnotation)) && pc == 0 => + UnaryOp(code) + + case JSBinaryOpMethodName(code, defaultsToOp) + if (defaultsToOp || sym.hasAnnotation(JSOperatorAnnotation)) && pc == 1 => + BinaryOp(code) + + case _ => + default + } + } else { + default + } + } + } + + /** Tests whether the calling convention of the specified symbol is `Call`. + * + * This helper is provided because we use this test in a few places. + */ + def isCall(sym: Symbol): Boolean = + of(sym) == Call + } + + object JSUnaryOpMethodName { + private val map = Map[Name, (js.JSUnaryOp.Code, Boolean)]( + nme.UNARY_+ -> (js.JSUnaryOp.+, true), + nme.UNARY_- -> (js.JSUnaryOp.-, true), + nme.UNARY_~ -> (js.JSUnaryOp.~, true), + nme.UNARY_! -> (js.JSUnaryOp.!, true) + ) + + /* We use Name instead of TermName to work around + * https://github.com/scala/bug/issues/11534 + */ + def unapply(name: Name): Option[(js.JSUnaryOp.Code, Boolean)] = + map.get(name) + } + + object JSBinaryOpMethodName { + private val map = Map[Name, (js.JSBinaryOp.Code, Boolean)]( + nme.ADD -> (js.JSBinaryOp.+, true), + nme.SUB -> (js.JSBinaryOp.-, true), + nme.MUL -> (js.JSBinaryOp.*, true), + nme.DIV -> (js.JSBinaryOp./, true), + nme.MOD -> (js.JSBinaryOp.%, true), + + nme.LSL -> (js.JSBinaryOp.<<, true), + nme.ASR -> (js.JSBinaryOp.>>, true), + nme.LSR -> (js.JSBinaryOp.>>>, true), + nme.OR -> (js.JSBinaryOp.|, true), + nme.AND -> (js.JSBinaryOp.&, true), + nme.XOR -> (js.JSBinaryOp.^, true), + + nme.LT -> (js.JSBinaryOp.<, true), + nme.LE -> (js.JSBinaryOp.<=, true), + nme.GT -> (js.JSBinaryOp.>, true), + nme.GE -> (js.JSBinaryOp.>=, true), + + nme.ZAND -> (js.JSBinaryOp.&&, true), + nme.ZOR -> (js.JSBinaryOp.||, true), + + global.encode("**") -> (js.JSBinaryOp.**, false) + ) + + /* We use Name instead of TermName to work around + * https://github.com/scala/bug/issues/11534 + */ + def unapply(name: Name): Option[(js.JSBinaryOp.Code, Boolean)] = + map.get(name) + } + + def clearGlobalState(): Unit = { + topLevelExports.clear() + staticExports.clear() + jsNativeLoadSpecs.clear() + } + + def registerTopLevelExports(sym: Symbol, infos: List[TopLevelExportInfo]): Unit = { + assert(!topLevelExports.contains(sym), s"symbol exported twice: $sym") + topLevelExports.put(sym, infos) + } + + def registerStaticExports(sym: Symbol, infos: List[StaticExportInfo]): Unit = { + assert(!staticExports.contains(sym), s"symbol exported twice: $sym") + staticExports.put(sym, infos) + } + + def topLevelExportsOf(sym: Symbol): List[TopLevelExportInfo] = + topLevelExports.getOrElse(sym, Nil) + + def staticExportsOf(sym: Symbol): List[StaticExportInfo] = + staticExports.getOrElse(sym, Nil) + + /** creates a name for an export specification */ + def scalaExportName(jsName: String, isProp: Boolean): TermName = { + val pref = if (isProp) propExportPrefix else methodExportPrefix + val encname = NameTransformer.encode(jsName) + newTermName(pref + encname) + } + + /** checks if the given symbol is a JSExport */ + def isExport(sym: Symbol): Boolean = + sym.name.startsWith(exportPrefix) && !sym.hasFlag(Flags.DEFAULTPARAM) + + /** retrieves the originally assigned jsName of this export and whether it + * is a property + */ + def jsExportInfo(name: Name): (String, Boolean) = { + def dropPrefix(prefix: String) ={ + if (name.startsWith(prefix)) { + // We can't decode right away due to $ separators + val enc = name.toString.substring(prefix.length) + Some(NameTransformer.decode(enc)) + } else None + } + + dropPrefix(methodExportPrefix).map((_,false)).orElse { + dropPrefix(propExportPrefix).map((_,true)) + }.getOrElse { + throw new IllegalArgumentException( + "non-exported name passed to jsExportInfo") + } + } + + def jsclassAccessorFor(clazz: Symbol): Symbol = + clazz.owner.info.member(clazz.name.append("$jsclass").toTermName) + + def isJSProperty(sym: Symbol): Boolean = isJSGetter(sym) || isJSSetter(sym) + + @inline private def enteringUncurryIfAtPhaseAfter[A](op: => A): A = { + if (currentRun.uncurryPhase != NoPhase && + isAtPhaseAfter(currentRun.uncurryPhase)) { + enteringPhase(currentRun.uncurryPhase)(op) + } else { + op + } + } + + /** has this symbol to be translated into a JS getter (both directions)? */ + def isJSGetter(sym: Symbol): Boolean = { + /* `sym.isModule` implies that `sym` is the module's accessor. In 2.12, + * module accessors are synthesized + * after uncurry, thus their first info is a MethodType at phase fields. + */ + sym.isModule || (sym.tpe.params.isEmpty && enteringUncurryIfAtPhaseAfter { + sym.tpe match { + case _: NullaryMethodType => true + case PolyType(_, _: NullaryMethodType) => true + case _ => false + } + }) + } + + /** has this symbol to be translated into a JS setter (both directions)? */ + def isJSSetter(sym: Symbol): Boolean = + nme.isSetterName(sym.name) && sym.isMethod && !sym.isConstructor + + /** has this symbol to be translated into a JS bracket access (JS to Scala) */ + def isJSBracketAccess(sym: Symbol): Boolean = + sym.hasAnnotation(JSBracketAccessAnnotation) + + /** has this symbol to be translated into a JS bracket call (JS to Scala) */ + def isJSBracketCall(sym: Symbol): Boolean = + sym.hasAnnotation(JSBracketCallAnnotation) + + /** Gets the unqualified JS name of a symbol. + * + * If it is not explicitly specified with an `@JSName` annotation, the + * JS name is inferred from the Scala name. + */ + def jsNameOf(sym: Symbol): JSName = { + sym.getAnnotation(JSNameAnnotation).fold[JSName] { + JSName.Literal(defaultJSNameOf(sym)) + } { annotation => + annotation.constantAtIndex(0).collect { + case Constant(name: String) => JSName.Literal(name) + }.getOrElse { + JSName.Computed(annotation.args.head.symbol) + } + } + } + + def defaultJSNameOf(sym: Symbol): String = { + val base = sym.unexpandedName.decoded.stripSuffix("_=") + if (!sym.isMethod) base.stripSuffix(" ") + else base + } + + /** Stores the JS native load spec of a symbol for the current compilation + * run. + */ + def storeJSNativeLoadSpec(sym: Symbol, spec: JSNativeLoadSpec): Unit = + jsNativeLoadSpecs(sym) = spec + + /** Gets the JS native load spec of a symbol in the current compilation run. + */ + def jsNativeLoadSpecOf(sym: Symbol): JSNativeLoadSpec = + jsNativeLoadSpecs(sym) + + /** Gets the JS native load spec of a symbol in the current compilation run, + * if it has one. + */ + def jsNativeLoadSpecOfOption(sym: Symbol): Option[JSNativeLoadSpec] = + jsNativeLoadSpecs.get(sym) + + } + +} diff --git a/compiler/src/main/scala/org/scalajs/nscplugin/JSPrimitives.scala b/compiler/src/main/scala/org/scalajs/nscplugin/JSPrimitives.scala new file mode 100644 index 0000000000..df5ff293db --- /dev/null +++ b/compiler/src/main/scala/org/scalajs/nscplugin/JSPrimitives.scala @@ -0,0 +1,130 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin + +import scala.tools.nsc._ + +import scala.collection.mutable + +/** Extension of ScalaPrimitives for primitives only relevant to the JS backend + * + * @author Sébastie Doeraene + */ +abstract class JSPrimitives { + val global: Global + + type ThisJSGlobalAddons = JSGlobalAddons { + val global: JSPrimitives.this.global.type + } + + val jsAddons: ThisJSGlobalAddons + + import global._ + import jsAddons._ + import definitions._ + import jsDefinitions._ + import scalaPrimitives._ + + final val FirstJSPrimitiveCode = 300 + + final val DYNNEW = FirstJSPrimitiveCode + 1 // Instantiate a new JavaScript object + + final val ARR_CREATE = DYNNEW + 1 // js.Array.apply (array literal syntax) + + final val TYPEOF = ARR_CREATE + 1 // typeof x + final val JS_NATIVE = TYPEOF + 1 // js.native. Marker method. Fails if tried to be emitted. + + final val UNITVAL = JS_NATIVE + 1 // () value, which is undefined + + final val JS_NEW_TARGET = UNITVAL + 1 // js.new.target + + final val JS_IMPORT = JS_NEW_TARGET + 1 // js.import.apply(specifier) + final val JS_IMPORT_META = JS_IMPORT + 1 // js.import.meta + + final val CONSTRUCTOROF = JS_IMPORT_META + 1 // runtime.constructorOf(clazz) + final val CREATE_INNER_JS_CLASS = CONSTRUCTOROF + 1 // runtime.createInnerJSClass + final val CREATE_LOCAL_JS_CLASS = CREATE_INNER_JS_CLASS + 1 // runtime.createLocalJSClass + final val WITH_CONTEXTUAL_JS_CLASS_VALUE = CREATE_LOCAL_JS_CLASS + 1 // runtime.withContextualJSClassValue + final val LINKING_INFO = WITH_CONTEXTUAL_JS_CLASS_VALUE + 1 // runtime.linkingInfo + final val IDENTITY_HASH_CODE = LINKING_INFO + 1 // runtime.identityHashCode + final val DYNAMIC_IMPORT = IDENTITY_HASH_CODE + 1 // runtime.dynamicImport + + final val STRICT_EQ = DYNAMIC_IMPORT + 1 // js.special.strictEquals + final val IN = STRICT_EQ + 1 // js.special.in + final val INSTANCEOF = IN + 1 // js.special.instanceof + final val DELETE = INSTANCEOF + 1 // js.special.delete + final val FORIN = DELETE + 1 // js.special.forin + final val JS_THROW = FORIN + 1 // js.special.throw + final val JS_TRY_CATCH = JS_THROW + 1 // js.special.tryCatch + final val WRAP_AS_THROWABLE = JS_TRY_CATCH + 1 // js.special.wrapAsThrowable + final val UNWRAP_FROM_THROWABLE = WRAP_AS_THROWABLE + 1 // js.special.unwrapFromThrowable + final val DEBUGGER = UNWRAP_FROM_THROWABLE + 1 // js.special.debugger + + final val LastJSPrimitiveCode = DEBUGGER + + /** Initialize the map of primitive methods (for GenJSCode) */ + def init(): Unit = initWithPrimitives(addPrimitive) + + /** Init the map of primitive methods for Scala.js (for PrepJSInterop) */ + def initPrepJSPrimitives(): Unit = { + scalaJSPrimitives.clear() + initWithPrimitives(scalaJSPrimitives.put) + } + + /** Only call from PrepJSInterop. In GenJSCode, use + * scalaPrimitives.isPrimitive instead + */ + def isJavaScriptPrimitive(sym: Symbol): Boolean = + scalaJSPrimitives.contains(sym) + + private val scalaJSPrimitives = mutable.Map.empty[Symbol, Int] + + private def initWithPrimitives(addPrimitive: (Symbol, Int) => Unit): Unit = { + addPrimitive(JSDynamic_newInstance, DYNNEW) + + addPrimitive(JSArray_create, ARR_CREATE) + + addPrimitive(JSPackage_typeOf, TYPEOF) + addPrimitive(JSPackage_native, JS_NATIVE) + + addPrimitive(BoxedUnit_UNIT, UNITVAL) + + addPrimitive(JSNew_target, JS_NEW_TARGET) + + addPrimitive(JSImport_apply, JS_IMPORT) + addPrimitive(JSImport_meta, JS_IMPORT_META) + + addPrimitive(Runtime_constructorOf, CONSTRUCTOROF) + addPrimitive(Runtime_createInnerJSClass, CREATE_INNER_JS_CLASS) + addPrimitive(Runtime_createLocalJSClass, CREATE_LOCAL_JS_CLASS) + addPrimitive(Runtime_withContextualJSClassValue, + WITH_CONTEXTUAL_JS_CLASS_VALUE) + addPrimitive(Runtime_linkingInfo, LINKING_INFO) + addPrimitive(Runtime_identityHashCode, IDENTITY_HASH_CODE) + addPrimitive(Runtime_dynamicImport, DYNAMIC_IMPORT) + + addPrimitive(Special_strictEquals, STRICT_EQ) + addPrimitive(Special_in, IN) + addPrimitive(Special_instanceof, INSTANCEOF) + addPrimitive(Special_delete, DELETE) + addPrimitive(Special_forin, FORIN) + addPrimitive(Special_throw, JS_THROW) + addPrimitive(Special_tryCatch, JS_TRY_CATCH) + addPrimitive(Special_wrapAsThrowable, WRAP_AS_THROWABLE) + addPrimitive(Special_unwrapFromThrowable, UNWRAP_FROM_THROWABLE) + addPrimitive(Special_debugger, DEBUGGER) + } + + def isJavaScriptPrimitive(code: Int): Boolean = + code >= FirstJSPrimitiveCode && code <= LastJSPrimitiveCode +} diff --git a/compiler/src/main/scala/org/scalajs/core/compiler/PreTyperComponent.scala b/compiler/src/main/scala/org/scalajs/nscplugin/PreTyperComponent.scala similarity index 93% rename from compiler/src/main/scala/org/scalajs/core/compiler/PreTyperComponent.scala rename to compiler/src/main/scala/org/scalajs/nscplugin/PreTyperComponent.scala index 74ec0afcb2..2983735355 100644 --- a/compiler/src/main/scala/org/scalajs/core/compiler/PreTyperComponent.scala +++ b/compiler/src/main/scala/org/scalajs/nscplugin/PreTyperComponent.scala @@ -10,7 +10,7 @@ * additional information regarding copyright ownership. */ -package org.scalajs.core.compiler +package org.scalajs.nscplugin import scala.tools.nsc import nsc._ @@ -69,7 +69,7 @@ import nsc._ */ abstract class PreTyperComponent(val global: Global) extends plugins.PluginComponent - with transform.Transform with PluginComponent210Compat { + with transform.Transform with CompatComponent { import global._ @@ -131,12 +131,13 @@ abstract class PreTyperComponent(val global: Global) private val scalajs = newTermName("scalajs") private val js = newTermName("js") + private val internal_ = newTermName("internal") private val wasPublicBeforeTyper = newTypeName("WasPublicBeforeTyper") private def anonymousClassMethodWasPublicAnnotation: Tree = { - val runtimePackage = Select(Select(Select(Select(Ident(nme.ROOTPKG), - nme.scala_), scalajs), js), nme.annotation) - val cls = Select(runtimePackage, wasPublicBeforeTyper) + val cls = Select(Select(Select(Select(Select(Select(Ident(nme.ROOTPKG), + nme.scala_), scalajs), js), nme.annotation), internal_), + wasPublicBeforeTyper) Apply(Select(New(cls), nme.CONSTRUCTOR), Nil) } } diff --git a/compiler/src/main/scala/org/scalajs/nscplugin/PrepJSExports.scala b/compiler/src/main/scala/org/scalajs/nscplugin/PrepJSExports.scala new file mode 100644 index 0000000000..e2ac9a6a88 --- /dev/null +++ b/compiler/src/main/scala/org/scalajs/nscplugin/PrepJSExports.scala @@ -0,0 +1,623 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin + +import scala.collection.mutable + +import scala.tools.nsc.Global + +import org.scalajs.ir.Names.DefaultModuleID +import org.scalajs.ir.Trees.TopLevelExportDef.isValidTopLevelExportName + +/** + * Prepare export generation + * + * Helpers for transformation of @JSExport annotations + */ +trait PrepJSExports[G <: Global with Singleton] { this: PrepJSInterop[G] => + + import global._ + import jsAddons._ + import definitions._ + import jsDefinitions._ + + import scala.reflect.internal.Flags + + private sealed abstract class ExportDestination + + private object ExportDestination { + /** Export in the "normal" way: as an instance member, or at the top-level + * for naturally top-level things (classes and modules). + */ + case object Normal extends ExportDestination + + /** Export at the top-level. */ + case class TopLevel(moduleID: String) extends ExportDestination + + /** Export as a static member of the companion class. */ + case object Static extends ExportDestination + } + + /* Not final because it causes the following compile warning: + * "The outer reference in this type test cannot be checked at run time." + */ + private case class ExportInfo(jsName: String, + destination: ExportDestination)(val pos: Position) + + /** Generate the exporter for the given DefDef + * or ValDef (abstract val in class, val in trait or lazy val; + * these don't get DefDefs until the fields phase) + * + * If this DefDef is a constructor, it is registered to be exported by + * GenJSCode instead and no trees are returned. + */ + def genExportMember(baseSym: Symbol): List[Tree] = { + val clsSym = baseSym.owner + + val exports = exportsOf(baseSym) + + // Helper function for errors + def err(msg: String) = { + reporter.error(exports.head.pos, msg) + Nil + } + + def memType = if (baseSym.isConstructor) "constructor" else "method" + + if (exports.isEmpty) { + Nil + } else if (!hasLegalExportVisibility(baseSym)) { + err(s"You may only export public and protected ${memType}s") + } else if (baseSym.isMacro) { + err("You may not export a macro") + } else if (isJSAny(clsSym)) { + err(s"You may not export a $memType of a subclass of js.Any") + } else if (scalaPrimitives.isPrimitive(baseSym)) { + err("You may not export a primitive") + } else if (baseSym.isLocalToBlock) { + // We exclude case class apply (and unapply) to work around SI-8826 + if (clsSym.isCaseApplyOrUnapply) { + Nil + } else { + err("You may not export a local definition") + } + } else if (hasIllegalRepeatedParam(baseSym)) { + err(s"In an exported $memType, a *-parameter must come last " + + "(through all parameter lists)") + } else if (hasIllegalDefaultParam(baseSym)) { + err(s"In an exported $memType, all parameters with defaults " + + "must be at the end") + } else if (baseSym.isConstructor) { + // we can generate constructors entirely in the backend, since they + // do not need inheritance and such. But we want to check their sanity + // here by previous tests and the following ones. + if (checkClassOrModuleExports(clsSym, exports.head.pos)) + registerStaticAndTopLevelExports(baseSym, exports) + + Nil + } else { + assert(!baseSym.isBridge, + s"genExportMember called for bridge symbol $baseSym") + + // Reset interface flag: Any trait will contain non-empty methods + clsSym.resetFlag(Flags.INTERFACE) + + val (normalExports, topLevelAndStaticExports) = + exports.partition(_.destination == ExportDestination.Normal) + + /* We can handle top level exports and static exports entirely in the + * backend. So just register them here. + */ + registerStaticAndTopLevelExports(baseSym, topLevelAndStaticExports) + + // Actually generate exporter methods + normalExports.flatMap(exp => genExportDefs(baseSym, exp.jsName, exp.pos)) + } + } + + /** Check and (potentially) register a class or module for export. + * + * Note that Scala classes are never registered for export, their + * constructors are. + */ + def registerClassOrModuleExports(sym: Symbol): Unit = { + val exports = exportsOf(sym) + def isScalaClass = !sym.isModuleClass && !isJSAny(sym) + + if (exports.nonEmpty && checkClassOrModuleExports(sym, exports.head.pos) && + !isScalaClass) { + registerStaticAndTopLevelExports(sym, exports) + } + } + + private def registerStaticAndTopLevelExports(sym: Symbol, + exports: List[ExportInfo]): Unit = { + val topLevel = exports.collect { + case info @ ExportInfo(jsName, ExportDestination.TopLevel(moduleID)) => + jsInterop.TopLevelExportInfo(moduleID, jsName)(info.pos) + } + + if (topLevel.nonEmpty) + jsInterop.registerTopLevelExports(sym, topLevel) + + val static = exports.collect { + case info @ ExportInfo(jsName, ExportDestination.Static) => + jsInterop.StaticExportInfo(jsName)(info.pos) + } + + if (static.nonEmpty) + jsInterop.registerStaticExports(sym, static) + } + + /** Check a class or module for export. + * + * There are 2 ways that this method can be reached: + * - via `registerClassOrModuleExports` + * - via `genExportMember` (constructor of Scala class) + */ + private def checkClassOrModuleExports(sym: Symbol, errPos: Position): Boolean = { + val isMod = sym.isModuleClass + + def err(msg: String) = { + reporter.error(errPos, msg) + false + } + + def hasAnyNonPrivateCtor: Boolean = + sym.info.member(nme.CONSTRUCTOR).filter(!isPrivateMaybeWithin(_)).exists + + def isJSNative = sym.hasAnnotation(JSNativeAnnotation) + + if (sym.isTrait) { + err("You may not export a trait") + } else if (isJSNative) { + err("You may not export a native JS " + (if (isMod) "object" else "class")) + } else if (!hasLegalExportVisibility(sym)) { + err("You may only export public and protected " + + (if (isMod) "objects" else "classes")) + } else if (sym.isLocalToBlock) { + err("You may not export a local " + + (if (isMod) "object" else "class")) + } else if (!sym.isStatic) { + err("You may not export a nested " + + (if (isMod) "object" else s"class. $createFactoryInOuterClassHint")) + } else if (sym.isAbstractClass && !isJSAny(sym)) { + err("You may not export an abstract class") + } else if (!isMod && !hasAnyNonPrivateCtor) { + /* This test is only relevant for JS classes but doesn't hurt for Scala + * classes as we could not reach it if there were only private + * constructors. + */ + err("You may not export a class that has only private constructors") + } else { + true + } + } + + private def createFactoryInOuterClassHint = { + "Create an exported factory method in the outer class to work " + + "around this limitation." + } + + /** retrieves the names a sym should be exported to from its annotations + * + * Note that for accessor symbols, the annotations of the accessed symbol + * are used, rather than the annotations of the accessor itself. + */ + private def exportsOf(sym: Symbol): List[ExportInfo] = { + val trgSym = { + def isOwnerScalaClass = !sym.owner.isModuleClass && !isJSAny(sym.owner) + + // For primary Scala class constructors, look on the class itself + if (sym.isPrimaryConstructor && isOwnerScalaClass) sym.owner + else sym + } + + // Annotations that are directly on the member + val directAnnots = trgSym.annotations.filter( + annot => isDirectMemberAnnot(annot.symbol)) + + // Is this a member export (i.e. not a class or module export)? + val isMember = !sym.isClass && !sym.isConstructor + + // Annotations for this member on the whole unit + val unitAnnots = { + if (isMember && sym.isPublic && !sym.isSynthetic) + sym.owner.annotations.filter(_.symbol == JSExportAllAnnotation) + else + Nil + } + + val allExportInfos = for { + annot <- directAnnots ++ unitAnnots + } yield { + val isExportAll = annot.symbol == JSExportAllAnnotation + val isTopLevelExport = annot.symbol == JSExportTopLevelAnnotation + val isStaticExport = annot.symbol == JSExportStaticAnnotation + val hasExplicitName = annot.args.nonEmpty + + assert(!isTopLevelExport || hasExplicitName, + "Found a top-level export without an explicit name at " + annot.pos) + + val name = { + if (hasExplicitName) { + annot.stringArg(0).getOrElse { + reporter.error(annot.args(0).pos, + s"The argument to ${annot.symbol.name} must be a literal string") + "dummy" + } + } else if (sym.isConstructor) { + decodedFullName(sym.owner) + } else if (sym.isClass) { + decodedFullName(sym) + } else { + sym.unexpandedName.decoded.stripSuffix("_=") + } + } + + val destination = { + if (isTopLevelExport) { + val moduleID = if (annot.args.size == 1) { + DefaultModuleID + } else { + annot.stringArg(1).getOrElse { + reporter.error(annot.args(1).pos, + "moduleID must be a literal string") + DefaultModuleID + } + } + + ExportDestination.TopLevel(moduleID) + } else if (isStaticExport) { + ExportDestination.Static + } else { + ExportDestination.Normal + } + } + + // Enforce proper setter signature + if (jsInterop.isJSSetter(sym)) + checkSetterSignature(sym, annot.pos, exported = true) + + // Enforce no __ in name + if (!isTopLevelExport && name.contains("__")) { + // Get position for error message + val pos = if (hasExplicitName) annot.args.head.pos else trgSym.pos + + reporter.error(pos, + "An exported name may not contain a double underscore (`__`)") + } + + /* Illegal function application exports, i.e., method named 'apply' + * without an explicit export name. + */ + if (isMember && !hasExplicitName && sym.name == nme.apply) { + destination match { + case ExportDestination.Normal => + def shouldBeTolerated = { + isExportAll && directAnnots.exists { annot => + annot.symbol == JSExportAnnotation && + annot.args.nonEmpty && + annot.stringArg(0) == Some("apply") + } + } + + // Don't allow apply without explicit name + if (!shouldBeTolerated) { + // Get position for error message + val pos = if (isExportAll) trgSym.pos else annot.pos + + reporter.error(pos, "A member cannot be exported to function " + + "application. Add @JSExport(\"apply\") to export under the " + + "name apply.") + } + + case _: ExportDestination.TopLevel => + throw new AssertionError( + "Found a top-level export without an explicit name at " + + annot.pos) + + case ExportDestination.Static => + reporter.error(annot.pos, + "A member cannot be exported to function application as " + + "static. Use @JSExportStatic(\"apply\") to export it under " + + "the name 'apply'.") + } + } + + val symOwner = + if (sym.isConstructor) sym.owner.owner + else sym.owner + + // Destination-specific restrictions + destination match { + case ExportDestination.Normal => + // Make sure we do not override the default export of toString + def isIllegalToString = { + isMember && name == "toString" && sym.name != nme.toString_ && + sym.tpe.params.isEmpty && !jsInterop.isJSGetter(sym) + } + if (isIllegalToString) { + reporter.error(annot.pos, "You may not export a zero-argument " + + "method named other than 'toString' under the name 'toString'") + } + + // Disallow @JSExport on non-members. + if (!isMember && !sym.isTrait) { + reporter.error(annot.pos, + "@JSExport is forbidden on objects and classes. " + + "Use @JSExportTopLevel instead.") + } + + case _: ExportDestination.TopLevel => + if (sym.isLazy) { + reporter.error(annot.pos, + "You may not export a lazy val to the top level") + } else if (!sym.isAccessor && jsInterop.isJSProperty(sym)) { + reporter.error(annot.pos, + "You may not export a getter or a setter to the top level") + } + + /* Disallow non-static methods. + * Note: Non-static classes have more specific error messages in + * checkClassOrModuleExports + */ + if (sym.isMethod && (!symOwner.isStatic || !symOwner.isModuleClass)) { + reporter.error(annot.pos, + "Only static objects may export their members to the top level") + } + + // The top-level name must be a valid JS identifier + if (!isValidTopLevelExportName(name)) { + reporter.error(annot.pos, + "The top-level export name must be a valid JavaScript " + + "identifier name") + } + + case ExportDestination.Static => + def companionIsNonNativeJSClass: Boolean = { + val companion = symOwner.companionClass + companion != NoSymbol && + !companion.isTrait && + isJSAny(companion) && + !companion.hasAnnotation(JSNativeAnnotation) + } + + if (!symOwner.isStatic || !symOwner.isModuleClass || + !companionIsNonNativeJSClass) { + reporter.error(annot.pos, + "Only a static object whose companion class is a " + + "non-native JS class may export its members as static.") + } + + if (isMember) { + if (sym.isLazy) { + reporter.error(annot.pos, + "You may not export a lazy val as static") + } + } else { + if (sym.isTrait) { + reporter.error(annot.pos, + "You may not export a trait as static.") + } else { + reporter.error(annot.pos, + "Implementation restriction: cannot export a class or " + + "object as static") + } + } + } + + ExportInfo(name, destination)(annot.pos) + } + + allExportInfos.filter(_.destination == ExportDestination.Normal) + .groupBy(_.jsName) + .filter { case (jsName, group) => + if (jsName == "apply" && group.size == 2) + // @JSExportAll and single @JSExport("apply") should not be warned. + !unitAnnots.exists(_.symbol == JSExportAllAnnotation) + else + group.size > 1 + } + .foreach(_ => reporter.warning(sym.pos, s"Found duplicate @JSExport")) + + /* Filter out static exports of accessors (as they are not actually + * exported, their fields are). The above is only used to uniformly perform + * checks. + */ + val filteredExports = if (!sym.isAccessor || sym.accessed == NoSymbol) { + allExportInfos + } else { + /* For accessors, we need to apply some special logic to static exports. + * When tested on accessors, they actually apply on *fields*, not on the + * accessors. We use the same code paths hereabove to uniformly perform + * relevant checks, but at the end of the day, we have to throw away the + * ExportInfo. + * However, we must make sure that no field is exported *twice* as static, + * nor both as static and as top-level (it is possible to export a field + * several times as top-level, though). + */ + val (topLevelAndStaticExportInfos, actualExportInfos) = + allExportInfos.partition(_.destination != ExportDestination.Normal) + + if (sym.isGetter) { + topLevelAndStaticExportInfos.find { + _.destination == ExportDestination.Static + }.foreach { firstStatic => + for { + duplicate <- topLevelAndStaticExportInfos + if duplicate ne firstStatic + } { + if (duplicate.destination == ExportDestination.Static) { + reporter.error(duplicate.pos, + "Fields (val or var) cannot be exported as static more " + + "than once") + } else { + reporter.error(duplicate.pos, + "Fields (val or var) cannot be exported both as static " + + "and at the top-level") + } + } + } + + registerStaticAndTopLevelExports(sym.accessed, topLevelAndStaticExportInfos) + } + + actualExportInfos + } + + filteredExports.distinct + } + + /** Just like sym.fullName, but does not encode components */ + private def decodedFullName(sym: Symbol): String = { + if (sym.isRoot || sym.isRootPackage || sym == NoSymbol) sym.name.decoded + else if (sym.owner.isEffectiveRoot) sym.name.decoded + else decodedFullName(sym.effectiveOwner.enclClass) + '.' + sym.name.decoded + } + + /** generate an exporter for a DefDef including default parameter methods */ + private def genExportDefs(defSym: Symbol, jsName: String, pos: Position) = { + val clsSym = defSym.owner + val scalaName = + jsInterop.scalaExportName(jsName, jsInterop.isJSProperty(defSym)) + + // Create symbol for new method + val expSym = defSym.cloneSymbol + + // Set position of symbol + expSym.pos = pos + + // Alter type for new method (lift return type to Any) + // The return type is lifted, in order to avoid bridge + // construction and to detect methods whose signature only differs + // in the return type. + // Attention: This will cause boxes for primitive value types and value + // classes. However, since we have restricted the return types, we can + // always safely remove these boxes again in the back-end. + if (!defSym.isConstructor) + expSym.setInfo(retToAny(expSym.tpe)) + + // Change name for new method + expSym.name = scalaName + + // Update flags + expSym.setFlag(Flags.SYNTHETIC) + expSym.resetFlag( + Flags.DEFERRED | // We always have a body + Flags.ACCESSOR | // We are never a "direct" accessor + Flags.CASEACCESSOR | // And a fortiori not a case accessor + Flags.LAZY | // We are not a lazy val (even if we export one) + Flags.OVERRIDE // Synthetic methods need not bother with this + ) + + // Remove export annotations + expSym.removeAnnotation(JSExportAnnotation) + + // Add symbol to class + clsSym.info.decls.enter(expSym) + + // Construct exporter DefDef tree + val exporter = genProxyDefDef(clsSym, defSym, expSym, pos) + + // Construct exporters for default getters + val defaultGetters = for { + (param, i) <- expSym.paramss.flatten.zipWithIndex + if param.hasFlag(Flags.DEFAULTPARAM) + } yield genExportDefaultGetter(clsSym, defSym, expSym, i + 1, pos) + + exporter :: defaultGetters + } + + private def genExportDefaultGetter(clsSym: Symbol, trgMethod: Symbol, + exporter: Symbol, paramPos: Int, pos: Position) = { + + // Get default getter method we'll copy + val trgGetter = + clsSym.tpe.member(nme.defaultGetterName(trgMethod.name, paramPos)) + + assert(trgGetter.exists, + s"Cannot find default getter for param $paramPos of $trgMethod") + + // Although the following must be true in a correct program, we cannot + // assert, since a graceful failure message is only generated later + if (!trgGetter.isOverloaded) { + val expGetter = trgGetter.cloneSymbol + + expGetter.name = nme.defaultGetterName(exporter.name, paramPos) + expGetter.pos = pos + + clsSym.info.decls.enter(expGetter) + + genProxyDefDef(clsSym, trgGetter, expGetter, pos) + + } else EmptyTree + } + + /** generate a DefDef tree (from [[proxySym]]) that calls [[trgSym]] */ + private def genProxyDefDef(clsSym: Symbol, trgSym: Symbol, + proxySym: Symbol, pos: Position) = atPos(pos) { + + // Helper to ascribe repeated argument lists when calling + def spliceParam(sym: Symbol) = { + if (isRepeated(sym)) + Typed(Ident(sym), Ident(tpnme.WILDCARD_STAR)) + else + Ident(sym) + } + + // Construct proxied function call + val sel = Select(This(clsSym), trgSym) + val rhs = proxySym.paramss.foldLeft[Tree](sel) { + (fun,params) => Apply(fun, params map spliceParam) + } + + typer.typedDefDef(DefDef(proxySym, rhs)) + } + + /** changes the return type of the method type tpe to Any. returns new type */ + private def retToAny(tpe: Type): Type = tpe match { + case MethodType(params, result) => MethodType(params, retToAny(result)) + case NullaryMethodType(result) => NullaryMethodType(AnyClass.tpe) + case PolyType(tparams, result) => PolyType(tparams, retToAny(result)) + case _ => AnyClass.tpe + } + + /** Whether the given symbol has a visibility that allows exporting */ + private def hasLegalExportVisibility(sym: Symbol): Boolean = + sym.isPublic || sym.isProtected && !sym.isProtectedLocal + + /** checks whether this type has a repeated parameter elsewhere than at the end + * of all the params + */ + private def hasIllegalRepeatedParam(sym: Symbol): Boolean = { + val params = sym.paramss.flatten + params.nonEmpty && params.init.exists(isRepeated _) + } + + /** checks whether there are default parameters not at the end of + * the flattened parameter list + */ + private def hasIllegalDefaultParam(sym: Symbol): Boolean = { + val isDefParam = (_: Symbol).hasFlag(Flags.DEFAULTPARAM) + sym.paramss.flatten.reverse.dropWhile(isDefParam).exists(isDefParam) + } + + /** Whether a symbol is an annotation that goes directly on a member */ + private lazy val isDirectMemberAnnot = Set[Symbol]( + JSExportAnnotation, + JSExportTopLevelAnnotation, + JSExportStaticAnnotation + ) + +} diff --git a/compiler/src/main/scala/org/scalajs/nscplugin/PrepJSInterop.scala b/compiler/src/main/scala/org/scalajs/nscplugin/PrepJSInterop.scala new file mode 100644 index 0000000000..f9e6144641 --- /dev/null +++ b/compiler/src/main/scala/org/scalajs/nscplugin/PrepJSInterop.scala @@ -0,0 +1,1769 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin + +import scala.tools.nsc +import nsc._ + +import scala.collection.immutable.ListMap +import scala.collection.mutable + +import org.scalajs.ir.Trees.{JSGlobalRef, JSNativeLoadSpec} + +/** Prepares classes extending js.Any for JavaScript interop + * + * This phase does: + * - Sanity checks for js.Any hierarchy + * - Annotate subclasses of js.Any to be treated specially + * - Rewrite calls to scala.Enumeration.Value (include name string) + * - Create JSExport methods: Dummy methods that are propagated + * through the whole compiler chain to mark exports. This allows + * exports to have the same semantics than methods. + * + * @author Tobias Schlatter + */ +abstract class PrepJSInterop[G <: Global with Singleton](val global: G) + extends plugins.PluginComponent with PrepJSExports[G] + with transform.Transform with CompatComponent { + + import PrepJSInterop._ + + /** Not for use in the constructor body: only initialized afterwards. */ + val jsAddons: JSGlobalAddons { + val global: PrepJSInterop.this.global.type + } + + /** Not for use in the constructor body: only initialized afterwards. */ + val scalaJSOpts: ScalaJSOptions + + import global._ + import jsAddons._ + import definitions._ + import rootMirror._ + import jsDefinitions._ + import jsInterop.{JSCallingConvention, JSName} + + val phaseName: String = "jsinterop" + override def description: String = "prepare ASTs for JavaScript interop" + + override def newPhase(p: nsc.Phase): StdPhase = new JSInteropPhase(p) + + class JSInteropPhase(prev: nsc.Phase) extends Phase(prev) { + override def name: String = phaseName + override def description: String = PrepJSInterop.this.description + override def run(): Unit = { + jsPrimitives.initPrepJSPrimitives() + jsInterop.clearGlobalState() + super.run() + } + } + + override protected def newTransformer(unit: CompilationUnit): Transformer = + new JSInteropTransformer(unit) + + private object jsnme { + val hasNext = newTermName("hasNext") + val next = newTermName("next") + val nextName = newTermName("nextName") + val Value = newTermName("Value") + val Val = newTermName("Val") + + val ArrowAssoc = newTermName("ArrowAssoc") + } + + class JSInteropTransformer(unit: CompilationUnit) extends Transformer { + + /** Kind of the directly enclosing (most nested) owner. */ + private var enclosingOwner: OwnerKind = OwnerKind.None + + /** Cumulative kinds of all enclosing owners. */ + private var allEnclosingOwners: OwnerKind = OwnerKind.None + + /** Nicer syntax for `allEnclosingOwners is kind`. */ + private def anyEnclosingOwner: OwnerKind = allEnclosingOwners + + /** Nicer syntax for `allEnclosingOwners isnt kind`. */ + private object noEnclosingOwner { + @inline def is(kind: OwnerKind): Boolean = + allEnclosingOwners isnt kind + } + + private def enterOwner[A](kind: OwnerKind)(body: => A): A = { + require(kind.isBaseKind, kind) + val oldEnclosingOwner = enclosingOwner + val oldAllEnclosingOwners = allEnclosingOwners + enclosingOwner = kind + allEnclosingOwners |= kind + try { + body + } finally { + enclosingOwner = oldEnclosingOwner + allEnclosingOwners = oldAllEnclosingOwners + } + } + + /** Tests whether this is a ScalaDoc run. + * + * There are some things we must not do in ScalaDoc runs because, because + * ScalaDoc runs don't do everything we need, for example constant-folding + * 'final val's. + * + * At the same time, it's no big deal to skip these things, because we + * won't reach the backend. + * + * We don't completely disable this phase under ScalaDoc mostly because + * we want to keep the addition of `JSType` annotations, so that they + * appear in the doc. + * + * Preparing exports, however, is a pure waste of time, which we cannot + * do properly anyway because of the aforementioned limitation. + */ + private def forScaladoc = global.isInstanceOf[doc.ScaladocGlobal] + + /** Whether to check that we have proper literals in some crucial places. */ + private def shouldCheckLiterals = !forScaladoc + + /** Whether to check and prepare exports. */ + private def shouldPrepareExports = !forScaladoc + + /** DefDefs in class templates that export methods to JavaScript */ + private val exporters = mutable.Map.empty[Symbol, mutable.ListBuffer[Tree]] + + override def transform(tree: Tree): Tree = { + tree match { + case tree: MemberDef => transformMemberDef(tree) + case tree: Template => transformTemplateTree(tree) + case _ => transformStatOrExpr(tree) + } + } + + private def transformMemberDef(tree: MemberDef): Tree = { + val sym = moduleToModuleClass(tree.symbol) + + checkInternalAnnotations(sym) + + /* Checks related to @js.native: + * - if @js.native, verify that it is allowed in this context, and if + * yes, compute and store the JS native load spec + * - if not @js.native, verify that we do not use any other annotation + * reserved for @js.native members (namely, JS native load spec annots) + */ + val isJSNative = sym.hasAnnotation(JSNativeAnnotation) + if (isJSNative) + checkJSNativeDefinition(tree.pos, sym) + else + checkJSNativeSpecificAnnotsOnNonJSNative(tree) + + checkJSCallingConventionAnnots(sym) + + // @unchecked needed because MemberDef is not marked `sealed` + val transformedTree: Tree = (tree: @unchecked) match { + case tree: ImplDef => + if (shouldPrepareExports) + registerClassOrModuleExports(sym) + + if ((enclosingOwner is OwnerKind.JSNonNative) && sym.owner.isTrait && !sym.isTrait) { + reporter.error(tree.pos, + "Non-native JS traits cannot contain inner classes or objects") + } + + if (isJSAny(sym)) + transformJSImplDef(tree) + else + transformScalaImplDef(tree) + + case tree: ValOrDefDef => + /* Prepare exports for methods, local defs and local variables. + * Avoid *fields* (non-local non-method) because they all have a + * corresponding getter, which is the one that handles exports. + * (Note that local-to-block can never have exports, but the error + * messages for that are handled by genExportMember). + */ + if (shouldPrepareExports && (sym.isMethod || sym.isLocalToBlock)) { + exporters.getOrElseUpdate(sym.owner, mutable.ListBuffer.empty) ++= + genExportMember(sym) + } + + if (sym.isLocalToBlock) { + super.transform(tree) + } else if (isJSNative) { + transformJSNativeValOrDefDef(tree) + } else if (enclosingOwner is OwnerKind.JSType) { + val fixedTree = tree match { + case tree: DefDef => fixPublicBeforeTyper(tree) + case _ => tree + } + transformValOrDefDefInJSType(fixedTree) + } else { + transformScalaValOrDefDef(tree) + } + + case _:TypeDef | _:PackageDef => + super.transform(tree) + } + + /* Give tree.symbol, not sym, so that for modules it is the module + * symbol, not the module class symbol. + * + * #1899 This must be done *after* transforming the member def tree, + * because fixPublicBeforeTyper must have run. + */ + markExposedIfRequired(tree.symbol) + + transformedTree + } + + private def transformScalaImplDef(tree: ImplDef): Tree = { + val sym = moduleToModuleClass(tree.symbol) + val isModuleDef = tree.isInstanceOf[ModuleDef] + + // In native JS things, only js.Any stuff is allowed + if (enclosingOwner is OwnerKind.JSNative) { + /* We have to allow synthetic companion objects here, as they get + * generated when a nested native JS class has default arguments in + * its constructor (see #1891). + */ + if (!sym.isSynthetic) { + reporter.error(tree.pos, + "Native JS traits, classes and objects cannot contain inner " + + "Scala traits, classes or objects (i.e., not extending js.Any)") + } + } + + if (sym == UnionClass) + sym.addAnnotation(JSTypeAnnot) + + val kind = if (sym.isSubClass(ScalaEnumClass)) { + if (isModuleDef) OwnerKind.EnumMod + else if (sym == ScalaEnumClass) OwnerKind.EnumImpl + else OwnerKind.EnumClass + } else { + if (isModuleDef) OwnerKind.NonEnumScalaMod + else OwnerKind.NonEnumScalaClass + } + enterOwner(kind) { + super.transform(tree) + } + } + + private def transformScalaValOrDefDef(tree: ValOrDefDef): Tree = { + tree match { + // Catch ValDefs in enumerations with simple calls to Value + case ValDef(mods, name, tpt, ScalaEnumValue.NoName(optPar)) + if anyEnclosingOwner is OwnerKind.Enum => + val nrhs = ScalaEnumValName(tree.symbol.owner, tree.symbol, optPar) + treeCopy.ValDef(tree, mods, name, transform(tpt), nrhs) + + // Exporter generation + case _ => + super.transform(tree) + } + } + + private def transformTemplateTree(tree: Template): Template = { + val Template(parents, self, body) = tree + + /* Do not transform `self`. We do not need to perform any checks on + * it (#3998). + */ + val transformedParents = parents.map(transform(_)) + val nonTransformedSelf = self + val transformedBody = body.map(transform(_)) + + val clsSym = tree.symbol.owner + + // Check that @JSExportStatic fields come first + if (clsSym.isModuleClass) { // quick check to avoid useless work + var foundStatOrNonStaticVal: Boolean = false + for (tree <- transformedBody) { + tree match { + case vd: ValDef if vd.symbol.hasAnnotation(JSExportStaticAnnotation) => + if (foundStatOrNonStaticVal) { + reporter.error(vd.pos, + "@JSExportStatic vals and vars must be defined before " + + "any other val/var, and before any constructor " + + "statement.") + } + case vd: ValDef if !vd.symbol.isLazy => + foundStatOrNonStaticVal = true + case _: MemberDef => + case _ => + foundStatOrNonStaticVal = true + } + } + } + + // Add exports to the template, if there are any + val transformedBodyWithExports = exporters.get(clsSym).fold { + transformedBody + } { exports => + transformedBody ::: exports.toList + } + + treeCopy.Template(tree, transformedParents, nonTransformedSelf, + transformedBodyWithExports) + } + + private def transformStatOrExpr(tree: Tree): Tree = { + tree match { + /* Anonymous function, need to check that it is not used as a SAM for a + * JS type, unless it is a JS function type. + * See #2921. + */ + case tree: Function => + // tpeSym is the type of the target SAM type (not the to-be-generated anonymous class) + val tpeSym = tree.tpe.typeSymbol + if (isJSAny(tpeSym)) { + def reportError(reasonAndExplanation: String): Unit = { + reporter.error(tree.pos, + "Using an anonymous function as a SAM for the JavaScript " + + s"type ${tpeSym.fullNameString} is not allowed because " + + reasonAndExplanation) + } + if (!tpeSym.isTrait || tpeSym.superClass != JSFunctionClass) { + reportError( + "it is not a trait extending js.Function. " + + "Use an anonymous class instead.") + } else if (tpeSym.hasAnnotation(JSNativeAnnotation)) { + reportError( + "it is a native JS type. " + + "It is not possible to directly implement it.") + } else if (!JSCallingConvention.isCall(samOf(tree.tpe))) { + reportError( + "its single abstract method is not named `apply`. " + + "Use an anonymous class instead.") + } + } + super.transform(tree) + + // Catch Select on Enumeration.Value we couldn't transform but need to + // we ignore the implementation of scala.Enumeration itself + case ScalaEnumValue.NoName(_) if noEnclosingOwner is OwnerKind.EnumImpl => + reporter.warning(tree.pos, + """Couldn't transform call to Enumeration.Value. + |The resulting program is unlikely to function properly as this + |operation requires reflection.""".stripMargin) + super.transform(tree) + + case ScalaEnumValue.NullName() if noEnclosingOwner is OwnerKind.EnumImpl => + reporter.warning(tree.pos, + """Passing null as name to Enumeration.Value + |requires reflection at runtime. The resulting + |program is unlikely to function properly.""".stripMargin) + super.transform(tree) + + case ScalaEnumVal.NoName(_) if noEnclosingOwner is OwnerKind.EnumImpl => + reporter.warning(tree.pos, + """Calls to the non-string constructors of Enumeration.Val + |require reflection at runtime. The resulting + |program is unlikely to function properly.""".stripMargin) + super.transform(tree) + + case ScalaEnumVal.NullName() if noEnclosingOwner is OwnerKind.EnumImpl => + reporter.warning(tree.pos, + """Passing null as name to a constructor of Enumeration.Val + |requires reflection at runtime. The resulting + |program is unlikely to function properly.""".stripMargin) + super.transform(tree) + + case tree if tree.symbol == ExecutionContext_global || + tree.symbol == ExecutionContextImplicits_global => + if (scalaJSOpts.warnGlobalExecutionContext) { + global.runReporting.warning(tree.pos, + """The global execution context in Scala.js is based on JS Promises (microtasks). + |Using it may prevent macrotasks (I/O, timers, UI rendering) from running reliably. + | + |Unfortunately, there is no way with ECMAScript only to implement a performant + |macrotask execution context (and hence Scala.js core does not contain one). + | + |We recommend you use: https://github.com/scala-js/scala-js-macrotask-executor + |Please refer to the README.md of that project for more details regarding + |microtask vs. macrotask execution contexts. + | + |If you do not care about macrotask fairness, you can silence this warning by: + |- Adding @nowarn("cat=other") (Scala >= 2.13.x only) + |- Setting the -P:scalajs:nowarnGlobalExecutionContext compiler option (Scala < 3.x.y only) + |- Using scala.scalajs.concurrent.JSExecutionContext.queue + | (the implementation of ExecutionContext.global in Scala.js) directly. + | + |If you do not care about performance, you can use + |scala.scalajs.concurrent.QueueExecutionContext.timeouts(). + |It is based on setTimeout which makes it fair but slow (due to clamping). + """.stripMargin, + WarningCategory.Other, tree.symbol) + } + super.transform(tree) + + // Validate js.constructorOf[T] + case TypeApply(ctorOfTree, List(tpeArg)) + if ctorOfTree.symbol == JSPackage_constructorOf => + validateJSConstructorOf(tree, tpeArg) + super.transform(tree) + + /* Rewrite js.ConstructorTag.materialize[T] into + * runtime.newConstructorTag[T](js.constructorOf[T]) + */ + case TypeApply(ctorOfTree, List(tpeArg)) + if ctorOfTree.symbol == JSConstructorTag_materialize => + validateJSConstructorOf(tree, tpeArg) + typer.typed { + atPos(tree.pos) { + val ctorOf = gen.mkTypeApply( + gen.mkAttributedRef(JSPackage_constructorOf), List(tpeArg)) + gen.mkMethodCall(Runtime_newConstructorTag, + List(tpeArg.tpe), List(ctorOf)) + } + } + + /* Rewrite js.dynamicImport[T](body) into + * + * runtime.dynamicImport[T]( + * new DynamicImportThunk { def apply(): Any = body } + * ) + */ + case Apply(TypeApply(fun, List(tpeArg)), List(body)) + if fun.symbol == JSPackage_dynamicImport => + val pos = tree.pos + + assert(currentOwner.isTerm, s"unexpected owner: $currentOwner at $pos") + + val clsSym = currentOwner.newClass(tpnme.ANON_CLASS_NAME, pos) + clsSym.setInfo( // do not enter the symbol, owner is a term. + ClassInfoType(List(DynamicImportThunkClass.tpe), newScope, clsSym)) + + val ctorSym = clsSym.newClassConstructor(pos) + ctorSym.setInfoAndEnter(MethodType(Nil, clsSym.tpe)) + + val applySym = clsSym.newMethod(nme.apply) + applySym.setInfoAndEnter(MethodType(Nil, AnyTpe)) + + body.changeOwner(currentOwner -> applySym) + val newBody = atOwner(applySym)(transform(body)) + + typer.typed { + atPos(tree.pos) { + val superCtorCall = gen.mkMethodCall( + Super(clsSym, tpnme.EMPTY), + ObjectClass.primaryConstructor, Nil, Nil) + + // class $anon extends DynamicImportThunk + val clsDef = ClassDef(clsSym, List( + // def () = { super.(); () } + DefDef(ctorSym, + // `gen.mkUnitBlock(gen.mkSuperInitCall)` would be better but that fails on 2.11. + Block(superCtorCall, Literal(Constant(())))), + // def apply(): Any = body + DefDef(applySym, newBody))) + + /* runtime.DynamicImport[A]({ + * class $anon ... + * new $anon + * }) + */ + Apply(TypeApply(gen.mkAttributedRef(Runtime_dynamicImport), + List(tpeArg)), List(Block(clsDef, New(clsSym)))) + } + } + + /* Catch calls to Predef.classOf[T]. These should NEVER reach this phase + * but unfortunately do. In normal cases, the typer phase replaces these + * calls by a literal constant of the given type. However, when we compile + * the scala library itself and Predef.scala is in the sources, this does + * not happen. + * + * The trees reach this phase under the form: + * + * scala.this.Predef.classOf[T] + * + * or, as of Scala 2.12.0, as: + * + * scala.Predef.classOf[T] + * + * or so it seems, at least. + * + * If we encounter such a tree, depending on the plugin options, we fail + * here or silently fix those calls. + */ + case TypeApply(classOfTree @ Select(predef, nme.classOf), List(tpeArg)) + if predef.symbol == PredefModule => + if (scalaJSOpts.fixClassOf) { + // Replace call by literal constant containing type + if (typer.checkClassOrModuleType(tpeArg)) { + typer.typed { Literal(Constant(tpeArg.tpe.dealias.widen)) } + } else { + reporter.error(tpeArg.pos, s"Type ${tpeArg} is not a class type") + EmptyTree + } + } else { + reporter.error(classOfTree.pos, + """This classOf resulted in an unresolved classOf in the jscode + |phase. This is most likely a bug in the Scala compiler. ScalaJS + |is probably able to work around this bug. Enable the workaround + |by passing the fixClassOf option to the plugin.""".stripMargin) + EmptyTree + } + + // Compile-time errors and warnings for js.Dynamic.literal + case Apply(Apply(fun, nameArgs), args) + if fun.symbol == JSDynamicLiteral_applyDynamic || + fun.symbol == JSDynamicLiteral_applyDynamicNamed => + // Check that the first argument list is a constant string "apply" + nameArgs match { + case List(Literal(Constant(s: String))) => + if (s != "apply") { + reporter.error(tree.pos, + s"js.Dynamic.literal does not have a method named $s") + } + case _ => + reporter.error(tree.pos, + s"js.Dynamic.literal.${tree.symbol.name} may not be " + + "called directly") + } + + // Warn for known duplicate property names + val knownPropNames = mutable.Set.empty[String] + for (arg <- args) { + def processPropName(propNameTree: Tree): Unit = { + propNameTree match { + case Literal(Constant(propName: String)) => + if (!knownPropNames.add(propName)) { + reporter.warning(propNameTree.pos, + s"""Duplicate property "$propName" shadows a """ + + "previously defined one") + } + case _ => + // ignore + } + } + arg match { + case Apply(fun, List(propNameTree, _)) + if fun.symbol == Tuple2_apply => + processPropName(propNameTree) + case Apply(fun @ TypeApply(Select(receiver, nme.MINGT), _), _) + if currentRun.runDefinitions.isArrowAssoc(fun.symbol) => + receiver match { + case Apply(TypeApply(Select(predef, jsnme.ArrowAssoc), _), + List(propNameTree)) + if predef.symbol == PredefModule => + processPropName(propNameTree) + case _ => + // ignore + } + case _ => + // ignore + } + } + + super.transform(tree) + + case _ => super.transform(tree) + } + } + + private def validateJSConstructorOf(tree: Tree, tpeArg: Tree): Unit = { + val classValue = try { + typer.typedClassOf(tree, tpeArg) + } catch { + case typeError: TypeError => + reporter.error(typeError.pos, typeError.msg) + EmptyTree + } + + if (classValue != EmptyTree) { + val Literal(classConstant) = classValue + val tpe = classConstant.typeValue.dealiasWiden + val typeSym = tpe.typeSymbol + if (typeSym.isTrait || typeSym.isModuleClass) { + reporter.error(tpeArg.pos, + s"non-trait class type required but $tpe found") + } + } + } + + /** Performs checks and rewrites specific to classes / objects extending + * js.Any. + */ + private def transformJSImplDef(implDef: ImplDef): Tree = { + val sym = moduleToModuleClass(implDef.symbol) + + sym.addAnnotation(JSTypeAnnot) + + val isJSNative = sym.hasAnnotation(JSNativeAnnotation) + + val isJSFunctionSAMInScala211 = + isScala211 && sym.name == tpnme.ANON_FUN_NAME && sym.superClass == JSFunctionClass + + // Forbid @EnableReflectiveInstantiation on JS types + sym.getAnnotation(EnableReflectiveInstantiationAnnotation).foreach { + annot => + reporter.error(annot.pos, + "@EnableReflectiveInstantiation cannot be used on types " + + "extending js.Any.") + } + + // Forbid package objects that extends js.Any + if (sym.isPackageObjectClass) + reporter.error(implDef.pos, "Package objects may not extend js.Any.") + + // Check that we do not have a case modifier + if (implDef.mods.hasFlag(Flag.CASE)) { + reporter.error(implDef.pos, "Classes and objects extending " + + "js.Any may not have a case modifier") + } + + // Check the parents + for (parent <- sym.info.parents) { + parent.typeSymbol match { + case AnyRefClass | ObjectClass => + // AnyRef is valid, except for non-native JS traits + if (!isJSNative && !sym.isTrait) { + reporter.error(implDef.pos, + "Non-native JS classes and objects cannot directly extend " + + "AnyRef. They must extend a JS class (native or not).") + } + case parentSym if isJSAny(parentSym) => + // A non-native JS type cannot extend a native JS trait + // Otherwise, extending a JS type is valid + if (!isJSNative && parentSym.isTrait && + parentSym.hasAnnotation(JSNativeAnnotation)) { + reporter.error(implDef.pos, + "Non-native JS types cannot directly extend native JS " + + "traits.") + } + case DynamicClass => + /* We have to allow scala.Dynamic to be able to define js.Dynamic + * and similar constructs. + * This causes the unsoundness filed as #1385. + */ + () + case SerializableClass if isJSFunctionSAMInScala211 => + /* Ignore the scala.Serializable trait that Scala 2.11 adds on all + * SAM classes when on a JS function SAM. + */ + () + case parentSym => + /* This is a Scala class or trait other than AnyRef and Dynamic, + * which is never valid. + */ + reporter.error(implDef.pos, + s"${sym.nameString} extends ${parentSym.fullName} " + + "which does not extend js.Any.") + } + } + + // Require that the SAM of a JS function def be `apply` (2.11-only here) + if (isJSFunctionSAMInScala211) { + if (!sym.info.decl(nme.apply).filter(JSCallingConvention.isCall(_)).exists) { + val samType = sym.parentSymbols.find(_ != JSFunctionClass).getOrElse { + /* This shouldn't happen, but fall back on this symbol (which has a + * compiler-generated name) not to crash. + */ + sym + } + reporter.error(implDef.pos, + "Using an anonymous function as a SAM for the JavaScript type " + + s"${samType.fullNameString} is not allowed because its single " + + "abstract method is not named `apply`. " + + "Use an anonymous class instead.") + } + } + + // Checks for non-native JS stuff + if (!isJSNative) { + // It cannot be in a native JS class or trait + if (enclosingOwner is OwnerKind.JSNativeClass) { + reporter.error(implDef.pos, + "Native JS classes and traits cannot contain non-native JS " + + "classes, traits or objects") + } + + // Unless it is a trait, it cannot be in a native JS object + if (!sym.isTrait && (enclosingOwner is OwnerKind.JSNativeMod)) { + reporter.error(implDef.pos, + "Native JS objects cannot contain inner non-native JS " + + "classes or objects") + } + + // Local JS classes cannot be abstract (implementation restriction) + if (!sym.isTrait && sym.isAbstractClass && sym.isLocalToBlock) { + reporter.error(implDef.pos, + "Implementation restriction: local JS classes cannot be abstract") + } + } + + // Check for consistency of JS semantics across overriding + for (overridingPair <- new overridingPairs.Cursor(sym).iterator) { + val low = overridingPair.low + val high = overridingPair.high + + if (low.isType || high.isType) { + /* #4375 Do nothing if either is a type, and let refchecks take care + * of it. + * The case where one is a type and the other is not should never + * happen, because they would live in different namespaces and + * therefore not override each other. However, if that should still + * happen for some reason, rechecks should take care of it as well. + */ + } else { + def errorPos = { + if (sym == low.owner) low.pos + else if (sym == high.owner) high.pos + else sym.pos + } + + def memberDefString(membSym: Symbol): String = + membSym.defStringSeenAs(sym.thisType.memberType(membSym)) + + // Check for overrides with different JS names - issue #1983 + if (jsInterop.JSCallingConvention.of(low) != jsInterop.JSCallingConvention.of(high)) { + val msg = { + def memberDefStringWithCallingConvention(membSym: Symbol) = { + memberDefString(membSym) + + membSym.locationString + " called from JS as " + + JSCallingConvention.of(membSym).displayName + } + "A member of a JS class is overriding another member with a different JS calling convention.\n\n" + + memberDefStringWithCallingConvention(low) + "\n" + + " is conflicting with\n" + + memberDefStringWithCallingConvention(high) + "\n" + } + + reporter.error(errorPos, msg) + } + + /* Cannot override a non-@JSOptional with an @JSOptional. Unfortunately + * at this point the symbols do not have @JSOptional yet, so we need + * to detect whether it would be applied. + */ + if (!isJSNative) { + def isJSOptional(sym: Symbol): Boolean = { + sym.owner.isTrait && !sym.isDeferred && !sym.isConstructor && + !sym.owner.hasAnnotation(JSNativeAnnotation) + } + + if (isJSOptional(low) && !(high.isDeferred || isJSOptional(high))) { + reporter.error(errorPos, + s"Cannot override concrete ${memberDefString(high)} from " + + s"${high.owner.fullName} in a non-native JS trait.") + } + } + } + } + + val kind = { + if (!isJSNative) { + if (sym.isModuleClass) OwnerKind.JSMod + else OwnerKind.JSClass + } else { + if (sym.isModuleClass) OwnerKind.JSNativeMod + else OwnerKind.JSNativeClass + } + } + enterOwner(kind) { + super.transform(implDef) + } + } + + private def checkJSNativeDefinition(pos: Position, sym: Symbol): Unit = { + // Check if we may have a JS native here + if (sym.isLocalToBlock) { + reporter.error(pos, + "@js.native is not allowed on local definitions") + } else if (!sym.isClass && (anyEnclosingOwner is (OwnerKind.ScalaClass | OwnerKind.JSType))) { + reporter.error(pos, + "@js.native vals and defs can only appear in static Scala objects") + } else if (sym.isClass && !isJSAny(sym)) { + reporter.error(pos, + "Classes, traits and objects not extending js.Any may not have " + + "an @js.native annotation") + } else if (anyEnclosingOwner is OwnerKind.ScalaClass) { + reporter.error(pos, + "Scala traits and classes may not have native JS members") + } else if (enclosingOwner is OwnerKind.JSNonNative) { + reporter.error(pos, + "non-native JS classes, traits and objects may not have " + + "native JS members") + } else if (!sym.isTrait) { + /* Compute the loading spec now, before `flatten` destroys the name. + * We store it in a global map. + */ + val optLoadSpec = checkAndComputeJSNativeLoadSpecOf(pos, sym) + for (loadSpec <- optLoadSpec) + jsInterop.storeJSNativeLoadSpec(sym, loadSpec) + } else { + assert(sym.isTrait, sym) // just tested in the previous `if` + for (annot <- sym.annotations) { + val annotSym = annot.symbol + if (JSNativeLoadingSpecAnnots.contains(annotSym)) { + reporter.error(annot.pos, + s"Traits may not have an @${annotSym.nameString} annotation.") + } + } + } + } + + private def checkAndComputeJSNativeLoadSpecOf(pos: Position, + sym: Symbol): Option[JSNativeLoadSpec] = { + import JSNativeLoadSpec._ + + def makeGlobalRefNativeLoadSpec(globalRef: String, + path: List[String]): Global = { + val validatedGlobalRef = if (!JSGlobalRef.isValidJSGlobalRefName(globalRef)) { + reporter.error(pos, + "The name of a JS global variable must be a valid JS " + + s"identifier (got '$globalRef')") + "erroneous" + } else { + globalRef + } + Global(validatedGlobalRef, path) + } + + if (enclosingOwner is OwnerKind.JSNative) { + /* We cannot get here for @js.native vals and defs. That would mean we + * have an @js.native val/def inside a JavaScript type, which is not + * allowed and already caught in checkJSNativeDefinition(). + */ + assert(sym.isClass, + s"undetected @js.native val or def ${sym.fullName} inside JS type at $pos") + + for (annot <- sym.annotations) { + val annotSym = annot.symbol + + if (JSNativeLoadingSpecAnnots.contains(annotSym)) { + reporter.error(annot.pos, + "Nested JS classes and objects cannot " + + s"have an @${annotSym.nameString} annotation.") + } + } + + if (sym.owner.isStaticOwner) { + for (annot <- sym.annotations) { + if (annot.symbol == JSNameAnnotation && + annot.args.head.tpe.typeSymbol != StringClass) { + reporter.error(annot.pos, + "Implementation restriction: @JSName with a js.Symbol is " + + "not supported on nested native classes and objects") + } + } + + val jsName = jsInterop.jsNameOf(sym) match { + case JSName.Literal(jsName) => jsName + case JSName.Computed(_) => "" // compile error above + } + + val ownerLoadSpec = jsInterop.jsNativeLoadSpecOfOption(sym.owner) + val loadSpec = ownerLoadSpec match { + case None => + // The owner is a JSGlobalScope + makeGlobalRefNativeLoadSpec(jsName, Nil) + case Some(Global(globalRef, path)) => + Global(globalRef, path :+ jsName) + case Some(Import(module, path)) => + Import(module, path :+ jsName) + case Some(ImportWithGlobalFallback( + Import(module, modulePath), Global(globalRef, globalPath))) => + ImportWithGlobalFallback( + Import(module, modulePath :+ jsName), + Global(globalRef, globalPath :+ jsName)) + } + Some(loadSpec) + } else { + None + } + } else { + def parsePath(pathName: String): List[String] = + pathName.split('.').toList + + def parseGlobalPath(pathName: String): Global = { + val globalRef :: path = parsePath(pathName) + makeGlobalRefNativeLoadSpec(globalRef, path) + } + + checkAndGetJSNativeLoadingSpecAnnotOf(pos, sym) match { + case Some(annot) if annot.symbol == JSGlobalScopeAnnotation => + if (!sym.isModuleClass) { + reporter.error(annot.pos, + "@JSGlobalScope can only be used on native JS objects (with @js.native).") + } + None + + case Some(annot) if annot.symbol == JSGlobalAnnotation => + if (shouldCheckLiterals) + checkJSGlobalLiteral(annot) + val pathName = annot.stringArg(0).getOrElse { + val symTermName = sym.name.dropModule.toTermName.dropLocal + if (symTermName == nme.apply) { + reporter.error(annot.pos, + "Native JS definitions named 'apply' must have an explicit name in @JSGlobal") + } else if (symTermName.endsWith(nme.SETTER_SUFFIX)) { + reporter.error(annot.pos, + "Native JS definitions with a name ending in '_=' must have an explicit name in @JSGlobal") + } + jsInterop.defaultJSNameOf(sym) + } + Some(parseGlobalPath(pathName)) + + case Some(annot) if annot.symbol == JSImportAnnotation => + if (shouldCheckLiterals) + checkJSImportLiteral(annot) + val module = annot.stringArg(0).getOrElse { + "" // an error is reported by checkJSImportLiteral in this case + } + val path = annot.stringArg(1).fold { + if (annot.args.size < 2) { + val symTermName = sym.name.dropModule.toTermName.dropLocal + if (symTermName == nme.apply) { + reporter.error(annot.pos, + "Native JS definitions named 'apply' must have an explicit name in @JSImport") + } else if (symTermName.endsWith(nme.SETTER_SUFFIX)) { + reporter.error(annot.pos, + "Native JS definitions with a name ending in '_=' must have an explicit name in @JSImport") + } + parsePath(jsInterop.defaultJSNameOf(sym)) + } else { + Nil + } + } { pathName => + parsePath(pathName) + } + val importSpec = Import(module, path) + val loadSpec = annot.stringArg(2).fold[JSNativeLoadSpec] { + importSpec + } { globalPathName => + ImportWithGlobalFallback(importSpec, + parseGlobalPath(globalPathName)) + } + Some(loadSpec) + + case Some(annot) => + abort(s"checkAndGetJSNativeLoadingSpecAnnotOf returned unexpected annotation $annot") + + case None => + /* We already emitted an error. Invent something not to cause + * cascading errors. + */ + Some(JSNativeLoadSpec.Global("erroneous", Nil)) + } + } + } + + /** Verify a ValOrDefDef that is annotated with `@js.native`. */ + private def transformJSNativeValOrDefDef(tree: ValOrDefDef): ValOrDefDef = { + val sym = tree.symbol + + if (sym.isLazy || jsInterop.isJSSetter(sym)) { + reporter.error(tree.pos, + "@js.native is not allowed on vars, lazy vals and setter defs") + } + + if (!sym.isAccessor) + checkRHSCallsJSNative(tree, "@js.native members") + + if (sym.isMethod) { // i.e., it is not a field + for (overridden <- sym.allOverriddenSymbols.headOption) { + val verb = if (overridden.isDeferred) "implement" else "override" + reporter.error(tree.pos, + s"An @js.native member cannot $verb the inherited member " + + overridden.fullName) + } + } + + tree + } + + /** Verify a ValOrDefDef inside a js.Any */ + private def transformValOrDefDefInJSType(tree: ValOrDefDef): Tree = { + val sym = tree.symbol + + assert(!sym.isLocalToBlock, s"$tree at ${tree.pos}") + + sym.name match { + case nme.apply if !sym.hasAnnotation(JSNameAnnotation) && jsInterop.isJSGetter(sym) => + reporter.error(sym.pos, "A member named apply represents function " + + "application in JavaScript. A parameterless member should be " + + "exported as a property. You must add @JSName(\"apply\")") + + case jsInterop.JSUnaryOpMethodName(_, _) => + if (sym.hasAnnotation(JSOperatorAnnotation)) { + if (sym.paramss.map(_.size).sum != 0) { + reporter.error(tree.pos, + s"@JSOperator methods with the name '${sym.nameString}' may not have any parameters") + } + } else if (!sym.annotations.exists(annot => JSCallingConventionAnnots.contains(annot.symbol))) { + reporter.warning(tree.pos, + s"Method '${sym.nameString}' should have an explicit @JSName or @JSOperator annotation " + + "because its name is one of the JavaScript operators") + } + + case jsInterop.JSBinaryOpMethodName(_, _) => + if (sym.hasAnnotation(JSOperatorAnnotation)) { + if (sym.paramss.map(_.size).sum != 1) { + reporter.error(tree.pos, + s"@JSOperator methods with the name '${sym.nameString}' must have exactly one parameter") + } + } else if (!sym.annotations.exists(annot => JSCallingConventionAnnots.contains(annot.symbol))) { + reporter.warning(tree.pos, + s"Method '${sym.nameString}' should have an explicit @JSName or @JSOperator annotation " + + "because its name is one of the JavaScript operators") + } + + case _ if sym.hasAnnotation(JSOperatorAnnotation) => + reporter.error(tree.pos, + s"@JSOperator cannot be used on a method with the name '${sym.nameString}' " + + "because it is not one of the JavaScript operators") + + case nme.equals_ if sym.tpe.matches(Any_equals.tpe) => + reporter.warning(sym.pos, "Overriding equals in a JS class does " + + "not change how it is compared. To silence this warning, change " + + "the name of the method and optionally add @JSName(\"equals\").") + + case nme.hashCode_ if sym.tpe.matches(Any_hashCode.tpe) => + reporter.warning(sym.pos, "Overriding hashCode in a JS class does " + + "not change its hash code. To silence this warning, change " + + "the name of the method and optionally add @JSName(\"hashCode\").") + + case _ => + } + + if (jsInterop.isJSSetter(sym)) + checkSetterSignature(sym, tree.pos, exported = false) + + if (enclosingOwner is OwnerKind.JSNonNative) { + JSCallingConvention.of(sym) match { + case JSCallingConvention.Property(_) => // checked above + case JSCallingConvention.Method(_) => // no checks needed + + case JSCallingConvention.Call if !sym.isDeferred => + /* Concrete `def apply` methods are normally rejected because we + * cannot implement them in JavaScript. However, we do allow a + * synthetic `apply` method if it is in a SAM for a JS function + * type. + */ + val isJSFunctionSAM = { + /* Under 2.11, sym.owner.isAnonymousFunction does not properly + * recognize anonymous functions here (because they seem to not + * be marked as synthetic). + */ + sym.isSynthetic && + sym.owner.name == tpnme.ANON_FUN_NAME && + sym.owner.superClass == JSFunctionClass + } + if (!isJSFunctionSAM) { + reporter.error(sym.pos, + "A non-native JS class cannot declare a concrete method " + + "named `apply` without `@JSName`") + } + + case JSCallingConvention.Call => // if sym.isDeferred + /* Allow an abstract `def apply` only if the owner is a plausible + * JS function SAM trait. + */ + val owner = sym.owner + val isPlausibleJSFunctionType = { + owner.isTrait && + owner.superClass == JSFunctionClass && + samOf(owner.toTypeConstructor) == sym + } + if (!isPlausibleJSFunctionType) { + reporter.error(sym.pos, + "A non-native JS type can only declare an abstract " + + "method named `apply` without `@JSName` if it is the " + + "SAM of a trait that extends js.Function") + } + + case JSCallingConvention.BracketAccess => + reporter.error(tree.pos, + "@JSBracketAccess is not allowed in non-native JS classes") + + case JSCallingConvention.BracketCall => + reporter.error(tree.pos, + "@JSBracketCall is not allowed in non-native JS classes") + + case JSCallingConvention.UnaryOp(_) => + reporter.error(sym.pos, + "A non-native JS class cannot declare a method " + + "named like a unary operation without `@JSName`") + + case JSCallingConvention.BinaryOp(_) => + reporter.error(sym.pos, + "A non-native JS class cannot declare a method " + + "named like a binary operation without `@JSName`") + } + } else { + def checkNoDefaultOrRepeated(subject: String) = { + for (param <- sym.paramss.flatten) { + if (isScalaRepeatedParamType(param.tpe)) { + reporter.error(param.pos, s"$subject may not have repeated parameters") + } else if (param.isParamWithDefault) { + reporter.error(param.pos, s"$subject may not have default parameters") + } + } + } + + JSCallingConvention.of(sym) match { + case JSCallingConvention.Property(_) => // checked above + case JSCallingConvention.Method(_) => // no checks needed + case JSCallingConvention.Call => // no checks needed + case JSCallingConvention.UnaryOp(_) => // no checks needed + + case JSCallingConvention.BinaryOp(_) => + checkNoDefaultOrRepeated("methods representing binary operations") + + case JSCallingConvention.BracketAccess => + val paramCount = sym.paramss.map(_.size).sum + if (paramCount != 1 && paramCount != 2) { + reporter.error(tree.pos, + "@JSBracketAccess methods must have one or two parameters") + } else if (paramCount == 2 && + sym.tpe.finalResultType.typeSymbol != UnitClass) { + reporter.error(tree.pos, + "@JSBracketAccess methods with two parameters must return Unit") + } + + checkNoDefaultOrRepeated("@JSBracketAccess methods") + + case JSCallingConvention.BracketCall => + // JS bracket calls must have at least one non-repeated parameter + sym.tpe.paramss match { + case (param :: _) :: _ if !isScalaRepeatedParamType(param.tpe) => + // ok + case _ => + reporter.error(tree.pos, "@JSBracketCall methods must have at " + + "least one non-repeated parameter") + } + } + } + + if (sym.hasAnnotation(NativeAttr)) { + // Native methods are not allowed + reporter.error(tree.pos, "Methods in a js.Any may not be @native") + } + + /* In native JS types, there should not be any private member, except + * private[this] constructors. + */ + if ((enclosingOwner is OwnerKind.JSNative) && isPrivateMaybeWithin(sym)) { + // Necessary for `private[this] val/var + def isFieldPrivateThis: Boolean = { + sym.isPrivateThis && + !sym.isParamAccessor && + !sym.owner.info.decls.exists(s => s.isGetter && s.accessed == sym) + } + + if (sym.isClassConstructor) { + if (!sym.isPrivateThis) { + reporter.error(sym.pos, + "Native JS classes may not have private constructors. " + + "Use `private[this]` to declare an internal constructor.") + } + } else if (sym.isMethod || isFieldPrivateThis) { + reporter.error(tree.pos, + "Native JS classes may not have private members. " + + "Use a public member in a private facade instead.") + } + } + + if (enclosingOwner is OwnerKind.JSNonNative) { + // Private methods cannot be overloaded + if (sym.isMethod && isPrivateMaybeWithin(sym)) { + val alts = sym.owner.info.member(sym.name).filter(_.isMethod) + if (alts.isOverloaded) { + reporter.error(tree.pos, + "Private methods in non-native JS classes cannot be " + + "overloaded. Use different names instead.") + } + } + + // private[Scope] methods must be final + if (sym.isMethod && (sym.hasAccessBoundary && !sym.isProtected) && + !sym.isFinal && !sym.isClassConstructor) { + reporter.error(tree.pos, + "Qualified private members in non-native JS classes " + + "must be final") + } + + // Traits must be pure interfaces, except for js.undefined members + if (sym.owner.isTrait && sym.isTerm && !sym.isConstructor) { + if (sym.isMethod && isPrivateMaybeWithin(sym)) { + reporter.error(tree.pos, + "A non-native JS trait cannot contain private members") + } else if (sym.isLazy) { + reporter.error(tree.pos, + "A non-native JS trait cannot contain lazy vals") + } else if (!sym.isDeferred) { + /* Tell the back-end not emit this thing. In fact, this only + * matters for mixed-in members created from this member. + */ + sym.addAnnotation(JSOptionalAnnotation) + + // For non-accessor methods, check that they do not have parens + if (sym.isMethod && !sym.isAccessor) { + sym.tpe match { + case _: NullaryMethodType => + // ok + case PolyType(_, _: NullaryMethodType) => + // ok + case _ => + reporter.error(tree.rhs.pos, + "In non-native JS traits, defs with parentheses " + + "must be abstract.") + } + } + + /* Check that the right-hand-side is `js.undefined`. + * + * On 2.12+, fields are created later than this phase, and getters + * still hold the right-hand-side that we need to check (we + * identify this case with `sym.accessed == NoSymbol`). + * On 2.11 and before, however, the getter has already been + * rewritten to read the field, so we must not check it. + * In either case, setters must not be checked. + */ + if (!sym.isAccessor || (sym.isGetter && sym.accessed == NoSymbol)) { + // Check that the tree's body is `js.undefined` + tree.rhs match { + case sel: Select if sel.symbol == JSPackage_undefined => + // ok + case _ => + if (sym.hasFlag(reflect.internal.Flags.DEFAULTPARAM)) { + reporter.error(tree.rhs.pos, + "Members of non-native JS traits may not have default " + + "parameters unless their default is `js.undefined`.") + } else { + reporter.error(tree.rhs.pos, + "Members of non-native JS traits must either be " + + "abstract, or their right-hand-side must be " + + "`js.undefined`.") + } + } + } + } + } + } + + if (sym.isPrimaryConstructor || sym.isValueParameter || + sym.isParamWithDefault || sym.isAccessor || + sym.isParamAccessor || sym.isDeferred || sym.isSynthetic || + (enclosingOwner is OwnerKind.JSNonNative)) { + /* Ignore (i.e. allow) primary ctor, parameters, default parameter + * getters, accessors, param accessors, abstract members, synthetic + * methods (to avoid double errors with case classes, e.g. generated + * copy method), and any member of a non-native JS class/trait. + */ + } else if (jsPrimitives.isJavaScriptPrimitive(sym)) { + // No check for primitives. We trust our own standard library. + } else if (sym.isConstructor) { + // Force secondary ctor to have only a call to the primary ctor inside + tree.rhs match { + case Block(List(Apply(trg, _)), Literal(Constant(()))) + if trg.symbol.isPrimaryConstructor && + trg.symbol.owner == sym.owner => + // everything is fine here + case _ => + reporter.error(tree.pos, "A secondary constructor of a class " + + "extending js.Any may only call the primary constructor") + } + } else { + // Check that the tree's rhs is exactly `= js.native` + checkRHSCallsJSNative(tree, "Concrete members of JS native types") + } + + super.transform(tree) + } + + private def checkRHSCallsJSNative(tree: ValOrDefDef, + longKindStr: String): Unit = { + // Check that the rhs is exactly `= js.native` + tree.rhs match { + case sel: Select if sel.symbol == JSPackage_native => + // ok + case _ => + val pos = if (tree.rhs != EmptyTree) tree.rhs.pos else tree.pos + reporter.error(pos, s"$longKindStr may only call js.native.") + } + + // Warn if resultType is Nothing and not ascribed + val sym = tree.symbol + if (sym.tpe.resultType.typeSymbol == NothingClass && + tree.tpt.asInstanceOf[TypeTree].original == null) { + val name = sym.name.decoded.trim + reporter.warning(tree.pos, + s"The type of $name got inferred as Nothing. " + + "To suppress this warning, explicitly ascribe the type.") + } + } + + private def checkJSNativeSpecificAnnotsOnNonJSNative( + memberDef: MemberDef): Unit = { + val sym = memberDef.symbol + + for (annot <- sym.annotations) { + annot.symbol match { + case JSGlobalAnnotation => + reporter.error(annot.pos, + "@JSGlobal can only be used on native JS definitions (with @js.native).") + case JSImportAnnotation => + reporter.error(annot.pos, + "@JSImport can only be used on native JS definitions (with @js.native).") + case JSGlobalScopeAnnotation => + reporter.error(annot.pos, + "@JSGlobalScope can only be used on native JS objects (with @js.native).") + case _ => + // ok + } + } + } + + private def checkJSCallingConventionAnnots(sym: Symbol): Unit = { + val callingConvAnnots = sym.annotations.filter(annot => JSCallingConventionAnnots.contains(annot.symbol)) + + callingConvAnnots match { + case Nil => + () // OK + + case annot :: rest => + def annotName: String = annot.symbol.nameString + + if (sym.isLocalToBlock || (enclosingOwner isnt OwnerKind.JSType)) { + reporter.error(annot.pos, + s"@$annotName can only be used on members of JS types.") + } else if (sym.isTrait) { + reporter.error(annot.pos, + s"@$annotName cannot be used on traits.") + } else if ((sym.isMethod || sym.isClass) && isPrivateMaybeWithin(sym)) { + reporter.error(annot.pos, + s"@$annotName cannot be used on private members.") + } else { + annot.symbol match { + case JSNameAnnotation => + if (shouldCheckLiterals) + checkJSNameArgument(sym, annot) + case JSOperatorAnnotation | JSBracketAccessAnnotation | JSBracketCallAnnotation => + if (!sym.isMethod) { + reporter.error(annot.pos, + s"@$annotName can only be used on methods.") + } + case _ => + throw new AssertionError( + s"Found unexpected annotation ${annot.symbol} " + + s"in calling convention annots at ${annot.pos}") + } + } + + for (duplicateAnnot <- rest) { + reporter.error(duplicateAnnot.pos, + "A member can have at most one annotation among " + + "@JSName, @JSOperator, @JSBracketAccess and @JSBracketCall.") + } + } + } + + private lazy val JSCallingConventionAnnots: Set[Symbol] = + Set(JSNameAnnotation, JSOperatorAnnotation, JSBracketAccessAnnotation, JSBracketCallAnnotation) + + /** Checks that argument to @JSName on [[member]] is a literal. + * Reports an error on each annotation where this is not the case. + */ + private def checkJSNameArgument(memberSym: Symbol, annot: AnnotationInfo): Unit = { + val argTree = annot.args.head + if (argTree.tpe.typeSymbol == StringClass) { + if (annot.stringArg(0).isEmpty) { + reporter.error(argTree.pos, + "A string argument to JSName must be a literal string") + } + } else { + // We have a js.Symbol + val sym = argTree.symbol + if (!sym.isStatic || !sym.isStable) { + reporter.error(argTree.pos, + "A js.Symbol argument to JSName must be a static, stable identifier") + } else if ((enclosingOwner is OwnerKind.JSNonNative) && + sym.owner == memberSym.owner) { + reporter.warning(argTree.pos, + "This symbol is defined in the same object as the annotation's " + + "target. This will cause a stackoverflow at runtime") + } + } + } + + /** Mark the symbol as exposed if it is a non-private term member of a + * non-native JS class. + * + * @param sym + * The symbol, which must be the module symbol for a module, not its + * module class symbol. + */ + private def markExposedIfRequired(sym: Symbol): Unit = { + def shouldBeExposed: Boolean = { + // it is a member of a non-native JS class + (enclosingOwner is OwnerKind.JSNonNative) && !sym.isLocalToBlock && + // it is a term member + (sym.isModule || sym.isMethod) && + // it is not private + !isPrivateMaybeWithin(sym) && + // it is not a kind of term member that we never expose + !sym.isConstructor && !sym.isValueParameter && !sym.isParamWithDefault && + // it is not synthetic + !sym.isSynthetic + } + + if (shouldPrepareExports && shouldBeExposed) { + sym.addAnnotation(ExposedJSMemberAnnot) + /* For accessors, the field being accessed must also be exposed, + * although it is private. + * + * #4089 Don't do this if `sym.accessed == NoSymbol`. This happens in + * 2.12+, where fields are created later than this phase. + */ + if (sym.isAccessor && sym.accessed != NoSymbol) + sym.accessed.addAnnotation(ExposedJSMemberAnnot) + } + } + + } + + def isJSAny(sym: Symbol): Boolean = + sym.isSubClass(JSAnyClass) + + /** Checks that a setter has the right signature. + * + * Reports error messages otherwise. + */ + def checkSetterSignature(sym: Symbol, pos: Position, exported: Boolean): Unit = { + val typeStr = if (exported) "Exported" else "JS" + + // Forbid setters with non-unit return type + if (sym.tpe.resultType.typeSymbol != UnitClass) { + reporter.error(pos, s"$typeStr setters must return Unit") + } + + // Forbid setters with more than one argument + sym.tpe.paramss match { + case List(List(arg)) => + // Arg list is OK. Do additional checks. + if (isScalaRepeatedParamType(arg.tpe)) + reporter.error(pos, s"$typeStr setters may not have repeated params") + + if (arg.hasFlag(reflect.internal.Flags.DEFAULTPARAM)) + reporter.error(pos, s"$typeStr setters may not have default params") + + case _ => + reporter.error(pos, s"$typeStr setters must have exactly one argument") + } + } + + /** Tests whether the symbol has `private` in any form, either `private`, + * `private[this]` or `private[Enclosing]`. + */ + def isPrivateMaybeWithin(sym: Symbol): Boolean = + sym.isPrivate || (sym.hasAccessBoundary && !sym.isProtected) + + /** Checks that the optional argument to an `@JSGlobal` annotation is a + * literal. + * + * Reports an error on the annotation if it is not the case. + */ + private def checkJSGlobalLiteral(annot: AnnotationInfo): Unit = { + if (annot.args.nonEmpty) { + assert(annot.args.size == 1, + s"@JSGlobal annotation $annot has more than 1 argument") + + val argIsValid = annot.stringArg(0).isDefined + if (!argIsValid) { + reporter.error(annot.args.head.pos, + "The argument to @JSGlobal must be a literal string.") + } + } + } + + /** Checks that arguments to an `@JSImport` annotation are literals. + * + * The second argument can also be the singleton `JSImport.Namespace` + * object. + * + * Reports an error on the annotation if it is not the case. + */ + private def checkJSImportLiteral(annot: AnnotationInfo): Unit = { + val argCount = annot.args.size + assert(argCount >= 1 && argCount <= 3, + s"@JSImport annotation $annot does not have between 1 and 3 arguments") + + val firstArgIsValid = annot.stringArg(0).isDefined + if (!firstArgIsValid) { + reporter.error(annot.args.head.pos, + "The first argument to @JSImport must be a literal string.") + } + + val secondArgIsValid = { + argCount < 2 || + annot.stringArg(1).isDefined || + annot.args(1).symbol == JSImportNamespaceObject + } + if (!secondArgIsValid) { + reporter.error(annot.args(1).pos, + "The second argument to @JSImport must be literal string or the " + + "JSImport.Namespace object.") + } + + val thirdArgIsValid = argCount < 3 || annot.stringArg(2).isDefined + if (!thirdArgIsValid) { + reporter.error(annot.args(2).pos, + "The third argument to @JSImport, when present, must be a " + + "literal string.") + } + } + + private abstract class ScalaEnumFctExtractors(methSym: Symbol) { + private def resolve(ptpes: Symbol*) = { + val res = methSym suchThat { + _.tpe.params.map(_.tpe.typeSymbol) == ptpes.toList + } + assert(res != NoSymbol, s"no overload of $methSym for param types $ptpes") + res + } + + private val noArg = resolve() + private val nameArg = resolve(StringClass) + private val intArg = resolve(IntClass) + private val fullMeth = resolve(IntClass, StringClass) + + /** + * Extractor object for calls to the targeted symbol that do not have an + * explicit name in the parameters + * + * Extracts: + * - `sel: Select` where sel.symbol is targeted symbol (no arg) + * - Apply(meth, List(param)) where meth.symbol is targeted symbol (i: Int) + */ + object NoName { + def unapply(t: Tree): Option[Option[Tree]] = t match { + case sel: Select if sel.symbol == noArg => + Some(None) + case Apply(meth, List(param)) if meth.symbol == intArg => + Some(Some(param)) + case _ => + None + } + } + + object NullName { + def unapply(tree: Tree): Boolean = tree match { + case Apply(meth, List(Literal(Constant(null)))) => + meth.symbol == nameArg + case Apply(meth, List(_, Literal(Constant(null)))) => + meth.symbol == fullMeth + case _ => false + } + } + + } + + private object ScalaEnumValue + extends ScalaEnumFctExtractors(getMemberMethod(ScalaEnumClass, jsnme.Value)) + + private object ScalaEnumVal + extends ScalaEnumFctExtractors(getMemberClass(ScalaEnumClass, jsnme.Val).tpe.member(nme.CONSTRUCTOR)) + + /** + * Construct a call to Enumeration.Value + * @param thisSym ClassSymbol of enclosing class + * @param nameOrig Symbol of ValDef where this call will be placed + * (determines the string passed to Value) + * @param intParam Optional tree with Int passed to Value + * @return Typed tree with appropriate call to Value + */ + private def ScalaEnumValName( + thisSym: Symbol, + nameOrig: Symbol, + intParam: Option[Tree]) = { + + val defaultName = nameOrig.asTerm.getterName.encoded + + + // Construct the following tree + // + // if (nextName != null && nextName.hasNext) + // nextName.next() + // else + // + // + val nextNameTree = Select(This(thisSym), jsnme.nextName) + val nullCompTree = + Apply(Select(nextNameTree, nme.NE), Literal(Constant(null)) :: Nil) + val hasNextTree = Select(nextNameTree, jsnme.hasNext) + val condTree = Apply(Select(nullCompTree, nme.ZAND), hasNextTree :: Nil) + val nameTree = If(condTree, + Apply(Select(nextNameTree, jsnme.next), Nil), + Literal(Constant(defaultName))) + val params = intParam.toList :+ nameTree + + typer.typed { + Apply(Select(This(thisSym), jsnme.Value), params) + } + } + + private def checkAndGetJSNativeLoadingSpecAnnotOf( + pos: Position, sym: Symbol): Option[Annotation] = { + + for (annot <- sym.getAnnotation(JSNameAnnotation)) { + reporter.error(annot.pos, + "@JSName can only be used on members of JS types.") + } + + val annots = sym.annotations.filter { annot => + JSNativeLoadingSpecAnnots.contains(annot.symbol) + } + + val badAnnotCountMsg = if (sym.isModuleClass) { + "Native JS objects must have exactly one annotation among " + + "@JSGlobal, @JSImport and @JSGlobalScope." + } else { + "Native JS classes, vals and defs must have exactly one annotation " + + "among @JSGlobal and @JSImport." + } + + annots match { + case Nil => + reporter.error(pos, badAnnotCountMsg) + None + + case result :: duplicates => + for (annot <- duplicates) + reporter.error(annot.pos, badAnnotCountMsg) + + Some(result) + } + } + + /* Note that we consider @JSGlobalScope as a JS native loading spec because + * it's convenient for the purposes of PrepJSInterop. Actually @JSGlobalScope + * objects do not receive a JS loading spec in their IR. + */ + private lazy val JSNativeLoadingSpecAnnots: Set[Symbol] = { + Set(JSGlobalAnnotation, JSImportAnnotation, JSGlobalScopeAnnotation) + } + + private lazy val ScalaEnumClass = getRequiredClass("scala.Enumeration") + + private def wasPublicBeforeTyper(sym: Symbol): Boolean = + sym.hasAnnotation(WasPublicBeforeTyperClass) + + private def fixPublicBeforeTyper(ddef: DefDef): DefDef = { + // This method assumes that isJSAny(ddef.symbol.owner) is true + val sym = ddef.symbol + val needsFix = { + sym.isPrivate && + (wasPublicBeforeTyper(sym) || + (sym.isAccessor && wasPublicBeforeTyper(sym.accessed))) + } + if (needsFix) { + sym.resetFlag(Flag.PRIVATE) + treeCopy.DefDef(ddef, ddef.mods &~ Flag.PRIVATE, ddef.name, ddef.tparams, + ddef.vparamss, ddef.tpt, ddef.rhs) + } else { + ddef + } + } + + private def checkInternalAnnotations(sym: Symbol): Unit = { + /** Returns true iff it is a compiler annotations. This does not include + * annotations inserted before the typer (such as `@WasPublicBeforeTyper`). + */ + def isCompilerAnnotation(annotation: AnnotationInfo): Boolean = { + annotation.symbol == ExposedJSMemberAnnot || + annotation.symbol == JSTypeAnnot || + annotation.symbol == JSOptionalAnnotation + } + + for (annotation <- sym.annotations) { + if (isCompilerAnnotation(annotation)) { + reporter.error(annotation.pos, + s"$annotation is for compiler internal use only. " + + "Do not use it yourself.") + } + } + } + + private def moduleToModuleClass(sym: Symbol): Symbol = + if (sym.isModule) sym.moduleClass + else sym +} + +object PrepJSInterop { + private final class OwnerKind private (private val baseKinds: Int) + extends AnyVal { + + import OwnerKind._ + + @inline def isBaseKind: Boolean = + Integer.lowestOneBit(baseKinds) == baseKinds && baseKinds != 0 // exactly 1 bit on + + @inline def |(that: OwnerKind): OwnerKind = + new OwnerKind(this.baseKinds | that.baseKinds) + + @inline def is(that: OwnerKind): Boolean = + (this.baseKinds & that.baseKinds) != 0 + + @inline def isnt(that: OwnerKind): Boolean = + !this.is(that) + } + + private object OwnerKind { + /** No owner, i.e., we are at the top-level. */ + val None = new OwnerKind(0x00) + + // Base kinds - those form a partition of all possible enclosing owners + + /** A Scala class/trait that does not extend Enumeration. */ + val NonEnumScalaClass = new OwnerKind(0x01) + /** A Scala object that does not extend Enumeration. */ + val NonEnumScalaMod = new OwnerKind(0x02) + /** A native JS class/trait, which extends js.Any. */ + val JSNativeClass = new OwnerKind(0x04) + /** A native JS object, which extends js.Any. */ + val JSNativeMod = new OwnerKind(0x08) + /** A non-native JS class/trait. */ + val JSClass = new OwnerKind(0x10) + /** A non-native JS object. */ + val JSMod = new OwnerKind(0x20) + /** A Scala class/trait that extends Enumeration. */ + val EnumClass = new OwnerKind(0x40) + /** A Scala object that extends Enumeration. */ + val EnumMod = new OwnerKind(0x80) + /** The Enumeration class itself. */ + val EnumImpl = new OwnerKind(0x100) + + // Compound kinds + + /** A Scala class/trait, possibly Enumeration-related. */ + val ScalaClass = NonEnumScalaClass | EnumClass | EnumImpl + /** A Scala object, possibly Enumeration-related. */ + val ScalaMod = NonEnumScalaMod | EnumMod + /** A Scala class, trait or object, i.e., anything not extending js.Any. */ + val ScalaThing = ScalaClass | ScalaMod + + /** A Scala class/trait/object extending Enumeration, but not Enumeration itself. */ + val Enum = EnumClass | EnumMod + + /** A native JS class/trait/object. */ + val JSNative = JSNativeClass | JSNativeMod + /** A non-native JS class/trait/object. */ + val JSNonNative = JSClass | JSMod + /** A JS type, i.e., something extending js.Any. */ + val JSType = JSNative | JSNonNative + + /** Any kind of class/trait, i.e., a Scala or JS class/trait. */ + val AnyClass = ScalaClass | JSNativeClass | JSClass + } +} diff --git a/compiler/src/main/scala/org/scalajs/nscplugin/ScalaJSOptions.scala b/compiler/src/main/scala/org/scalajs/nscplugin/ScalaJSOptions.scala new file mode 100644 index 0000000000..50cc0bf1c8 --- /dev/null +++ b/compiler/src/main/scala/org/scalajs/nscplugin/ScalaJSOptions.scala @@ -0,0 +1,50 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin + +import java.net.URI + +/** This trait allows to query all options to the ScalaJS plugin + * + * Also see the help text in ScalaJSPlugin for information about particular + * options. + */ +trait ScalaJSOptions { + import ScalaJSOptions.URIMap + + /** should calls to Predef.classOf[T] be fixed in the jsinterop phase. + * If false, bad calls to classOf will cause an error. */ + def fixClassOf: Boolean + + /** Should static forwarders be emitted for non-top-level objects. + * + * Scala/JVM does not do that. Since Scala.js 1.2.0, we do not do it by + * default either, but this option can be used to opt in. This is necessary + * for implementations of JDK classes. + */ + def genStaticForwardersForNonTopLevelObjects: Boolean + + /** which source locations in source maps should be relativized (or where + * should they be mapped to)? */ + def sourceURIMaps: List[URIMap] + + /** Whether to warn if the global execution context is used. + * + * See the warning itself or #4129 for context. + */ + def warnGlobalExecutionContext: Boolean +} + +object ScalaJSOptions { + case class URIMap(from: URI, to: Option[URI]) +} diff --git a/compiler/src/main/scala/org/scalajs/core/compiler/ScalaJSPlugin.scala b/compiler/src/main/scala/org/scalajs/nscplugin/ScalaJSPlugin.scala similarity index 75% rename from compiler/src/main/scala/org/scalajs/core/compiler/ScalaJSPlugin.scala rename to compiler/src/main/scala/org/scalajs/nscplugin/ScalaJSPlugin.scala index 31ad30b714..5e7ca6faba 100644 --- a/compiler/src/main/scala/org/scalajs/core/compiler/ScalaJSPlugin.scala +++ b/compiler/src/main/scala/org/scalajs/nscplugin/ScalaJSPlugin.scala @@ -10,7 +10,7 @@ * additional information regarding copyright ownership. */ -package org.scalajs.core.compiler +package org.scalajs.nscplugin import scala.tools.nsc._ import scala.tools.nsc.plugins.{ @@ -20,30 +20,28 @@ import scala.collection.{ mutable, immutable } import java.net.{ URI, URISyntaxException } -import org.scalajs.core.ir.Trees +import org.scalajs.ir.Trees /** Main entry point for the Scala.js compiler plugin * * @author Sébastien Doeraene */ -class ScalaJSPlugin(val global: Global) - extends NscPlugin with Compat210Component { - +class ScalaJSPlugin(val global: Global) extends NscPlugin { import global._ val name = "scalajs" val description = "Compile to JavaScript" val components = { - if (forScaladoc) { + if (global.isInstanceOf[doc.ScaladocGlobal]) { List[NscPluginComponent](PrepInteropComponent) } else { List[NscPluginComponent](PreTyperComponentComponent, PrepInteropComponent, - GenCodeComponent) + ExplicitInnerJSComponent, ExplicitLocalJSComponent, GenCodeComponent) } } /** Called when the JS ASTs are generated. Override for testing */ - def generatedJSAST(clDefs: List[Trees.Tree]): Unit = {} + def generatedJSAST(clDefs: List[Trees.ClassDef]): Unit = {} /** A trick to avoid early initializers while still enforcing that `global` * is initialized early. @@ -57,18 +55,17 @@ class ScalaJSPlugin(val global: Global) object scalaJSOpts extends ScalaJSOptions { import ScalaJSOptions.URIMap var fixClassOf: Boolean = false - var suppressExportDeprecations: Boolean = false - var suppressMissingJSGlobalDeprecations: Boolean = false + var genStaticForwardersForNonTopLevelObjects: Boolean = false lazy val sourceURIMaps: List[URIMap] = { if (_sourceURIMaps.nonEmpty) _sourceURIMaps.reverse else relSourceMap.toList.map(URIMap(_, absSourceMap)) } + var warnGlobalExecutionContext: Boolean = true var _sourceURIMaps: List[URIMap] = Nil var relSourceMap: Option[URI] = None var absSourceMap: Option[URI] = None - var sjsDefinedByDefault: Boolean = false } /** Checks and registers module exports on the symbol. @@ -80,7 +77,7 @@ class ScalaJSPlugin(val global: Global) */ @deprecated("Might be removed at any time, use at your own risk.", "0.6.24") def registerModuleExports(sym: Symbol): Unit = - PrepInteropComponent.registerModuleExports(sym) + PrepInteropComponent.registerClassOrModuleExports(sym) object PreTyperComponentComponent extends PreTyperComponent(global) { val runsAfter = List("parser") @@ -94,24 +91,39 @@ class ScalaJSPlugin(val global: Global) override val runsBefore = List("pickle") } + object ExplicitInnerJSComponent extends ExplicitInnerJS[global.type](global) { + val jsAddons: ScalaJSPlugin.this.jsAddons.type = ScalaJSPlugin.this.jsAddons + override val runsAfter = List("refchecks") + override val runsBefore = List("uncurry") + } + + object ExplicitLocalJSComponent extends ExplicitLocalJS[global.type](global) { + val jsAddons: ScalaJSPlugin.this.jsAddons.type = ScalaJSPlugin.this.jsAddons + override val runsAfter = List("specialize") + override val runsBefore = List("explicitouter") + } + object GenCodeComponent extends GenJSCode[global.type](global) { val jsAddons: ScalaJSPlugin.this.jsAddons.type = ScalaJSPlugin.this.jsAddons val scalaJSOpts = ScalaJSPlugin.this.scalaJSOpts override val runsAfter = List("mixin") override val runsBefore = List("delambdafy", "cleanup", "terminal") - def generatedJSAST(clDefs: List[Trees.Tree]): Unit = + def generatedJSAST(clDefs: List[Trees.ClassDef]): Unit = ScalaJSPlugin.this.generatedJSAST(clDefs) } - override def processOptions(options: List[String], - error: String => Unit): Unit = { + override def init(options: List[String], error: String => Unit): Boolean = { import ScalaJSOptions.URIMap import scalaJSOpts._ for (option <- options) { if (option == "fixClassOf") { fixClassOf = true + } else if (option == "genStaticForwardersForNonTopLevelObjects") { + genStaticForwardersForNonTopLevelObjects = true + } else if (option == "nowarnGlobalExecutionContext") { + warnGlobalExecutionContext = false } else if (option.startsWith("mapSourceURI:")) { val uris = option.stripPrefix("mapSourceURI:").split("->") @@ -127,10 +139,6 @@ class ScalaJSPlugin(val global: Global) error(s"${e.getInput} is not a valid URI") } } - } else if (option == "suppressExportDeprecations") { - suppressExportDeprecations = true - } else if (option == "suppressMissingJSGlobalDeprecations") { - suppressMissingJSGlobalDeprecations = true // The following options are deprecated (how do we show this to the user?) } else if (option.startsWith("relSourceMap:")) { val uriStr = option.stripPrefix("relSourceMap:") @@ -144,8 +152,6 @@ class ScalaJSPlugin(val global: Global) catch { case e: URISyntaxException => error(s"$uriStr is not a valid URI") } - } else if (option == "sjsDefinedByDefault") { - sjsDefinedByDefault = true } else { error("Option not understood: " + option) } @@ -160,6 +166,8 @@ class ScalaJSPlugin(val global: Global) "Use another mapSourceURI option.") else if (absSourceMap.isDefined && relSourceMap.isEmpty) error("absSourceMap requires the use of relSourceMap") + + true // this plugin is always enabled } override val optionsHelp: Option[String] = Some(s""" @@ -167,13 +175,11 @@ class ScalaJSPlugin(val global: Global) | Change the location the source URIs in the emitted IR point to | - strips away the prefix FROM_URI (if it matches) | - optionally prefixes the TO_URI, where stripping has been performed - | - any number of occurences are allowed. Processing is done on a first match basis. - | -P:$name:suppressExportDeprecations - | Silence deprecations of top-level @JSExport, - | @JSExportDescendentClasses and @JSExportDescendentObjects. - | This can be used as a transition path in the 0.6.x cycle, - | to avoid too many deprecation warnings that are not trivial - | to address. + | - any number of occurrences are allowed. Processing is done on a first match basis. + | -P:$name:genStaticForwardersForNonTopLevelObjects + | Generate static forwarders for non-top-level objects. + | This option should be used by codebases that implement JDK classes. + | When used together with -Xno-forwarders, this option has no effect. | -P:$name:fixClassOf | Repair calls to Predef.classOf that reach Scala.js. | WARNING: This is a tremendous hack! Expect ugly errors if you use this option. diff --git a/compiler/src/main/scala/org/scalajs/nscplugin/TypeConversions.scala b/compiler/src/main/scala/org/scalajs/nscplugin/TypeConversions.scala new file mode 100644 index 0000000000..c063a2a02a --- /dev/null +++ b/compiler/src/main/scala/org/scalajs/nscplugin/TypeConversions.scala @@ -0,0 +1,155 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin + +import scala.tools.nsc._ + +import org.scalajs.ir.Types + +/** Conversions from scalac `Type`s to the IR `Type`s and `TypeRef`s. */ +trait TypeConversions[G <: Global with Singleton] extends SubComponent { + this: GenJSCode[G] => + + import global._ + import definitions._ + + private lazy val primitiveIRTypeMap: Map[Symbol, Types.Type] = { + Map( + UnitClass -> Types.NoType, + BooleanClass -> Types.BooleanType, + CharClass -> Types.CharType, + ByteClass -> Types.ByteType, + ShortClass -> Types.ShortType, + IntClass -> Types.IntType, + LongClass -> Types.LongType, + FloatClass -> Types.FloatType, + DoubleClass -> Types.DoubleType, + NothingClass -> Types.NothingType, + NullClass -> Types.NullType + ) + } + + private lazy val primitiveRefMap: Map[Symbol, Types.NonArrayTypeRef] = { + Map( + UnitClass -> Types.VoidRef, + BooleanClass -> Types.BooleanRef, + CharClass -> Types.CharRef, + ByteClass -> Types.ByteRef, + ShortClass -> Types.ShortRef, + IntClass -> Types.IntRef, + LongClass -> Types.LongRef, + FloatClass -> Types.FloatRef, + DoubleClass -> Types.DoubleRef, + NothingClass -> Types.ClassRef(encodeClassName(RuntimeNothingClass)), + NullClass -> Types.ClassRef(encodeClassName(RuntimeNullClass)) + ) + } + + def toIRType(t: Type): Types.Type = { + val (base, arrayDepth) = convert(t) + if (arrayDepth == 0) + primitiveIRTypeMap.getOrElse(base, encodeClassType(base)) + else + Types.ArrayType(makeArrayTypeRef(base, arrayDepth)) + } + + def toTypeRef(t: Type): Types.TypeRef = { + val (base, arrayDepth) = convert(t) + if (arrayDepth == 0) + makeNonArrayTypeRef(base) + else + makeArrayTypeRef(base, arrayDepth) + } + + private def makeNonArrayTypeRef(sym: Symbol): Types.NonArrayTypeRef = + primitiveRefMap.getOrElse(sym, Types.ClassRef(encodeClassName(sym))) + + private def makeArrayTypeRef(base: Symbol, depth: Int): Types.ArrayTypeRef = + Types.ArrayTypeRef(makeNonArrayTypeRef(base), depth) + + // The following code was modeled after backend.icode.TypeKinds.toTypeKind + + /** Converts the given `Type` to a Scala.js `Type` or `TypeRef`, according to + * the given `ConversionFinisher`. + * + * @param t + * The `Type` to convert + * @return + * The base symbol type, and the array depth. If the array depth is 0, it + * means that the base symbol itself is the result. + */ + /* The call to .normalize fixes #3003 (follow type aliases). Otherwise, + * convertMaybeArray below would return ObjectReference. + */ + private def convert(t: Type): (Symbol, Int) = t.normalize match { + case ThisType(ArrayClass) => (ObjectClass, 0) + case ThisType(sym) => (convertBase(sym), 0) + case SingleType(_, sym) => (convertBase(sym), 0) + case ConstantType(_) => convert(t.underlying) + case TypeRef(_, sym, args) => convertMaybeArray(sym, args) + case ClassInfoType(_, _, ArrayClass) => abort("ClassInfoType to ArrayClass!") + case ClassInfoType(_, _, sym) => (convertBase(sym), 0) + + // !!! Iulian says types which make no sense after erasure should not reach here, + // which includes the ExistentialType, AnnotatedType, RefinedType. I don't know + // if the first two cases exist because they do or as a defensive measure, but + // at the time I added it, RefinedTypes were indeed reaching here. + // !!! Removed in JavaScript backend because I do not know what to do with lub + //case ExistentialType(_, t) => toTypeKind(t) + // Apparently, this case does occur (see pos/CustomGlobal.scala) + case t: AnnotatedType => convert(t.underlying) + //case RefinedType(parents, _) => parents map toTypeKind reduceLeft lub + + /* This case is not in scalac. We need it for the test + * run/valueclasses-classtag-existential. I have no idea how icode does + * not fail this test: we do everything the same as icode up to here. + */ + case tpe: ErasedValueType => (convertBase(tpe.valueClazz), 0) + + // For sure WildcardTypes shouldn't reach here either, but when + // debugging such situations this may come in handy. + // case WildcardType => (ObjectClass, 0) + case norm => abort( + "Unknown type: %s, %s [%s, %s] TypeRef? %s".format( + t, norm, t.getClass, norm.getClass, t.isInstanceOf[TypeRef] + ) + ) + } + + /** Convert a type ref, possibly an array type. */ + private def convertMaybeArray(sym: Symbol, + targs: List[Type]): (Symbol, Int) = sym match { + case ArrayClass => + val convertedArg = convert(targs.head) + (convertedArg._1, convertedArg._2 + 1) + case _ if sym.isClass => + (convertBase(sym), 0) + case _ => + assert(sym.isType, sym) // it must be compiling Array[a] + (ObjectClass, 0) + } + + /** Convert a class ref, definitely not an array type. */ + private def convertBase(sym: Symbol): Symbol = { + if (isImplClass(sym)) { + // pos/spec-List.scala is the sole failure if we don't check for NoSymbol + val traitSym = sym.owner.info.decl(tpnme.interfaceName(sym.name)) + if (traitSym != NoSymbol) + traitSym + else + sym + } else { + sym + } + } +} diff --git a/compiler/src/main/scala/org/scalajs/core/compiler/util/ScopedVar.scala b/compiler/src/main/scala/org/scalajs/nscplugin/util/ScopedVar.scala similarity index 96% rename from compiler/src/main/scala/org/scalajs/core/compiler/util/ScopedVar.scala rename to compiler/src/main/scala/org/scalajs/nscplugin/util/ScopedVar.scala index 7778b8c351..c9781465af 100644 --- a/compiler/src/main/scala/org/scalajs/core/compiler/util/ScopedVar.scala +++ b/compiler/src/main/scala/org/scalajs/nscplugin/util/ScopedVar.scala @@ -10,7 +10,7 @@ * additional information regarding copyright ownership. */ -package org.scalajs.core.compiler.util +package org.scalajs.nscplugin.util import language.implicitConversions diff --git a/compiler/src/main/scala/org/scalajs/core/compiler/util/VarBox.scala b/compiler/src/main/scala/org/scalajs/nscplugin/util/VarBox.scala similarity index 89% rename from compiler/src/main/scala/org/scalajs/core/compiler/util/VarBox.scala rename to compiler/src/main/scala/org/scalajs/nscplugin/util/VarBox.scala index ccbcfb322d..e1d47515a0 100644 --- a/compiler/src/main/scala/org/scalajs/core/compiler/util/VarBox.scala +++ b/compiler/src/main/scala/org/scalajs/nscplugin/util/VarBox.scala @@ -10,7 +10,7 @@ * additional information regarding copyright ownership. */ -package org.scalajs.core.compiler.util +package org.scalajs.nscplugin.util import language.implicitConversions diff --git a/compiler/src/test/scala/org/scalajs/core/compiler/test/DiverseErrorsTest.scala b/compiler/src/test/scala/org/scalajs/core/compiler/test/DiverseErrorsTest.scala deleted file mode 100644 index 40fc42fea1..0000000000 --- a/compiler/src/test/scala/org/scalajs/core/compiler/test/DiverseErrorsTest.scala +++ /dev/null @@ -1,302 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler.test - -import org.scalajs.core.compiler.test.util._ -import org.junit.Test - -// scalastyle:off line.size.limit - -class DiverseErrorsTest extends DirectTest with TestHelpers { - - override def preamble: String = - """import scala.scalajs.js, js.annotation._ - """ - - @Test - def noIsInstanceOnJSRaw: Unit = { - - """ - @js.native - trait JSRaw extends js.Object - - class A { - val a: AnyRef = "asdf" - def x = a.isInstanceOf[JSRaw] - } - """ hasErrors - """ - |newSource1.scala:8: error: isInstanceOf[JSRaw] not supported because it is a raw JS trait - | def x = a.isInstanceOf[JSRaw] - | ^ - """ - - } - - @Test - def jsConstructorOfErrors: Unit = { - - """ - class ScalaClass - trait ScalaTrait - object ScalaObject - - object A { - val a = js.constructorOf[ScalaClass] - val b = js.constructorOf[ScalaTrait] - val c = js.constructorOf[ScalaObject.type] - } - """ hasErrors - """ - |newSource1.scala:8: error: type arguments [ScalaClass] do not conform to method constructorOf's type parameter bounds [T <: scala.scalajs.js.Any] - | val a = js.constructorOf[ScalaClass] - | ^ - |newSource1.scala:9: error: type arguments [ScalaTrait] do not conform to method constructorOf's type parameter bounds [T <: scala.scalajs.js.Any] - | val b = js.constructorOf[ScalaTrait] - | ^ - |newSource1.scala:10: error: type arguments [ScalaObject.type] do not conform to method constructorOf's type parameter bounds [T <: scala.scalajs.js.Any] - | val c = js.constructorOf[ScalaObject.type] - | ^ - """ - - """ - @js.native @JSGlobal class NativeJSClass extends js.Object - @js.native trait NativeJSTrait extends js.Object - @js.native @JSGlobal object NativeJSObject extends js.Object - - class JSClass extends js.Object - trait JSTrait extends js.Object - object JSObject extends js.Object - - object A { - val a = js.constructorOf[NativeJSTrait] - val b = js.constructorOf[NativeJSObject.type] - - val c = js.constructorOf[NativeJSClass with NativeJSTrait] - val d = js.constructorOf[NativeJSClass { def bar: Int }] - - val e = js.constructorOf[JSTrait] - val f = js.constructorOf[JSObject.type] - - val g = js.constructorOf[JSClass with JSTrait] - val h = js.constructorOf[JSClass { def bar: Int }] - - def foo[A <: js.Any] = js.constructorOf[A] - def bar[A <: js.Any: scala.reflect.ClassTag] = js.constructorOf[A] - } - """ hasErrors - """ - |newSource1.scala:12: error: non-trait class type required but NativeJSTrait found - | val a = js.constructorOf[NativeJSTrait] - | ^ - |newSource1.scala:13: error: class type required but NativeJSObject.type found - | val b = js.constructorOf[NativeJSObject.type] - | ^ - |newSource1.scala:15: error: class type required but NativeJSClass with NativeJSTrait found - | val c = js.constructorOf[NativeJSClass with NativeJSTrait] - | ^ - |newSource1.scala:16: error: class type required but NativeJSClass{def bar: Int} found - | val d = js.constructorOf[NativeJSClass { def bar: Int }] - | ^ - |newSource1.scala:18: error: non-trait class type required but JSTrait found - | val e = js.constructorOf[JSTrait] - | ^ - |newSource1.scala:19: error: class type required but JSObject.type found - | val f = js.constructorOf[JSObject.type] - | ^ - |newSource1.scala:21: error: class type required but JSClass with JSTrait found - | val g = js.constructorOf[JSClass with JSTrait] - | ^ - |newSource1.scala:22: error: class type required but JSClass{def bar: Int} found - | val h = js.constructorOf[JSClass { def bar: Int }] - | ^ - |newSource1.scala:24: error: class type required but A found - | def foo[A <: js.Any] = js.constructorOf[A] - | ^ - |newSource1.scala:25: error: class type required but A found - | def bar[A <: js.Any: scala.reflect.ClassTag] = js.constructorOf[A] - | ^ - """ - - } - - @Test - def jsConstructorTagErrors: Unit = { - - """ - class ScalaClass - trait ScalaTrait - object ScalaObject - - object A { - val a = js.constructorTag[ScalaClass] - val b = js.constructorTag[ScalaTrait] - val c = js.constructorTag[ScalaObject.type] - } - """ hasErrors - """ - |newSource1.scala:8: error: type arguments [ScalaClass] do not conform to method constructorTag's type parameter bounds [T <: scala.scalajs.js.Any] - | val a = js.constructorTag[ScalaClass] - | ^ - |newSource1.scala:9: error: type arguments [ScalaTrait] do not conform to method constructorTag's type parameter bounds [T <: scala.scalajs.js.Any] - | val b = js.constructorTag[ScalaTrait] - | ^ - |newSource1.scala:10: error: type arguments [ScalaObject.type] do not conform to method constructorTag's type parameter bounds [T <: scala.scalajs.js.Any] - | val c = js.constructorTag[ScalaObject.type] - | ^ - """ - - """ - @js.native @JSGlobal class NativeJSClass extends js.Object - @js.native trait NativeJSTrait extends js.Object - @js.native @JSGlobal object NativeJSObject extends js.Object - - class JSClass extends js.Object - trait JSTrait extends js.Object - object JSObject extends js.Object - - object A { - val a = js.constructorTag[NativeJSTrait] - val b = js.constructorTag[NativeJSObject.type] - - val c = js.constructorTag[NativeJSClass with NativeJSTrait] - val d = js.constructorTag[NativeJSClass { def bar: Int }] - - val e = js.constructorTag[JSTrait] - val f = js.constructorTag[JSObject.type] - - val g = js.constructorTag[JSClass with JSTrait] - val h = js.constructorTag[JSClass { def bar: Int }] - - def foo[A <: js.Any] = js.constructorTag[A] - def bar[A <: js.Any: scala.reflect.ClassTag] = js.constructorTag[A] - } - """ hasErrors - """ - |newSource1.scala:12: error: non-trait class type required but NativeJSTrait found - | val a = js.constructorTag[NativeJSTrait] - | ^ - |newSource1.scala:13: error: class type required but NativeJSObject.type found - | val b = js.constructorTag[NativeJSObject.type] - | ^ - |newSource1.scala:15: error: class type required but NativeJSClass with NativeJSTrait found - | val c = js.constructorTag[NativeJSClass with NativeJSTrait] - | ^ - |newSource1.scala:16: error: class type required but NativeJSClass{def bar: Int} found - | val d = js.constructorTag[NativeJSClass { def bar: Int }] - | ^ - |newSource1.scala:18: error: non-trait class type required but JSTrait found - | val e = js.constructorTag[JSTrait] - | ^ - |newSource1.scala:19: error: class type required but JSObject.type found - | val f = js.constructorTag[JSObject.type] - | ^ - |newSource1.scala:21: error: class type required but JSClass with JSTrait found - | val g = js.constructorTag[JSClass with JSTrait] - | ^ - |newSource1.scala:22: error: class type required but JSClass{def bar: Int} found - | val h = js.constructorTag[JSClass { def bar: Int }] - | ^ - |newSource1.scala:24: error: class type required but A found - | def foo[A <: js.Any] = js.constructorTag[A] - | ^ - |newSource1.scala:25: error: class type required but A found - | def bar[A <: js.Any: scala.reflect.ClassTag] = js.constructorTag[A] - | ^ - """ - - } - - @Test - def runtimeConstructorOfErrors: Unit = { - - """ - import scala.scalajs.runtime - - object ScalaObject - @js.native @JSGlobal object NativeJSObject extends js.Object - object JSObject extends js.Object - - object A { - val a = runtime.constructorOf(classOf[ScalaObject.type].asInstanceOf[Class[_ <: js.Any]]) - val b = runtime.constructorOf(classOf[NativeJSObject.type]) - val c = runtime.constructorOf(classOf[JSObject.type]) - } - """ hasErrors - """ - |newSource1.scala:10: error: class type required but ScalaObject.type found - | val a = runtime.constructorOf(classOf[ScalaObject.type].asInstanceOf[Class[_ <: js.Any]]) - | ^ - |newSource1.scala:11: error: class type required but NativeJSObject.type found - | val b = runtime.constructorOf(classOf[NativeJSObject.type]) - | ^ - |newSource1.scala:12: error: class type required but JSObject.type found - | val c = runtime.constructorOf(classOf[JSObject.type]) - | ^ - """ - - """ - import scala.scalajs.runtime - - class ScalaClass - trait ScalaTrait - - @js.native @JSGlobal class NativeJSClass extends js.Object - @js.native trait NativeJSTrait extends js.Object - @js.native @JSGlobal object NativeJSObject extends js.Object - - class JSClass extends js.Object - trait JSTrait extends js.Object - object JSObject extends js.Object - - object A { - val a = runtime.constructorOf(classOf[ScalaClass].asInstanceOf[Class[_ <: js.Any]]) - val b = runtime.constructorOf(classOf[ScalaTrait].asInstanceOf[Class[_ <: js.Any]]) - - val c = runtime.constructorOf(classOf[NativeJSTrait]) - val d = runtime.constructorOf(classOf[JSTrait]) - - def jsClassClass = classOf[JSClass] - val e = runtime.constructorOf(jsClassClass) - - val f = runtime.constructorOf(NativeJSObject.getClass) - val g = runtime.constructorOf(JSObject.getClass) - } - """ hasErrors - """ - |newSource1.scala:17: error: runtime.constructorOf() must be called with a constant classOf[T] representing a class extending js.Any (not a trait nor an object) - | val a = runtime.constructorOf(classOf[ScalaClass].asInstanceOf[Class[_ <: js.Any]]) - | ^ - |newSource1.scala:18: error: runtime.constructorOf() must be called with a constant classOf[T] representing a class extending js.Any (not a trait nor an object) - | val b = runtime.constructorOf(classOf[ScalaTrait].asInstanceOf[Class[_ <: js.Any]]) - | ^ - |newSource1.scala:20: error: runtime.constructorOf() must be called with a constant classOf[T] representing a class extending js.Any (not a trait nor an object) - | val c = runtime.constructorOf(classOf[NativeJSTrait]) - | ^ - |newSource1.scala:21: error: runtime.constructorOf() must be called with a constant classOf[T] representing a class extending js.Any (not a trait nor an object) - | val d = runtime.constructorOf(classOf[JSTrait]) - | ^ - |newSource1.scala:24: error: runtime.constructorOf() must be called with a constant classOf[T] representing a class extending js.Any (not a trait nor an object) - | val e = runtime.constructorOf(jsClassClass) - | ^ - |newSource1.scala:26: error: runtime.constructorOf() must be called with a constant classOf[T] representing a class extending js.Any (not a trait nor an object) - | val f = runtime.constructorOf(NativeJSObject.getClass) - | ^ - |newSource1.scala:27: error: runtime.constructorOf() must be called with a constant classOf[T] representing a class extending js.Any (not a trait nor an object) - | val g = runtime.constructorOf(JSObject.getClass) - | ^ - """ - - } - -} diff --git a/compiler/src/test/scala/org/scalajs/core/compiler/test/EnumerationInteropTest.scala b/compiler/src/test/scala/org/scalajs/core/compiler/test/EnumerationInteropTest.scala deleted file mode 100644 index a278e98d21..0000000000 --- a/compiler/src/test/scala/org/scalajs/core/compiler/test/EnumerationInteropTest.scala +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler.test - -import org.scalajs.core.compiler.test.util._ - -import org.junit.Test - -class EnumerationInteropTest extends DirectTest with TestHelpers { - - @Test - def warnIfUnableToTransformValue: Unit = { - - """ - class A extends Enumeration { - val a = { - println("oh, oh!") - Value - } - val b = { - println("oh, oh!") - Value(4) - } - } - """ hasWarns - """ - |newSource1.scala:5: warning: Couldn't transform call to Enumeration.Value. - |The resulting program is unlikely to function properly as this - |operation requires reflection. - | Value - | ^ - |newSource1.scala:9: warning: Couldn't transform call to Enumeration.Value. - |The resulting program is unlikely to function properly as this - |operation requires reflection. - | Value(4) - | ^ - """ - - } - - @Test - def warnIfNoNameVal: Unit = { - - """ - class A extends Enumeration { - val a = new Val - val b = new Val(10) - } - """ hasWarns - """ - |newSource1.scala:3: warning: Calls to the non-string constructors of Enumeration.Val - |require reflection at runtime. The resulting - |program is unlikely to function properly. - | val a = new Val - | ^ - |newSource1.scala:4: warning: Calls to the non-string constructors of Enumeration.Val - |require reflection at runtime. The resulting - |program is unlikely to function properly. - | val b = new Val(10) - | ^ - """ - - } - - @Test - def warnIfNullValue: Unit = { - - """ - class A extends Enumeration { - val a = Value(null) - val b = Value(10, null) - } - """ hasWarns - """ - |newSource1.scala:3: warning: Passing null as name to Enumeration.Value - |requires reflection at runtime. The resulting - |program is unlikely to function properly. - | val a = Value(null) - | ^ - |newSource1.scala:4: warning: Passing null as name to Enumeration.Value - |requires reflection at runtime. The resulting - |program is unlikely to function properly. - | val b = Value(10, null) - | ^ - """ - - } - - @Test - def warnIfNullNewVal: Unit = { - - """ - class A extends Enumeration { - val a = new Val(null) - val b = new Val(10, null) - } - """ hasWarns - """ - |newSource1.scala:3: warning: Passing null as name to a constructor of Enumeration.Val - |requires reflection at runtime. The resulting - |program is unlikely to function properly. - | val a = new Val(null) - | ^ - |newSource1.scala:4: warning: Passing null as name to a constructor of Enumeration.Val - |requires reflection at runtime. The resulting - |program is unlikely to function properly. - | val b = new Val(10, null) - | ^ - """ - - } - - @Test - def warnIfExtNoNameVal: Unit = { - - """ - class A extends Enumeration { - protected class Val1 extends Val - protected class Val2 extends Val(1) - } - """.warns() // no message checking: position differs in 2.10 and 2.11 - - } - - @Test - def warnIfExtNullNameVal: Unit = { - - """ - class A extends Enumeration { - protected class Val1 extends Val(null) - protected class Val2 extends Val(1,null) - } - """.warns() // no message checking: position differs in 2.10 and 2.11 - - } - -} diff --git a/compiler/src/test/scala/org/scalajs/core/compiler/test/JSDynamicLiteralTest.scala b/compiler/src/test/scala/org/scalajs/core/compiler/test/JSDynamicLiteralTest.scala deleted file mode 100644 index f1032d5635..0000000000 --- a/compiler/src/test/scala/org/scalajs/core/compiler/test/JSDynamicLiteralTest.scala +++ /dev/null @@ -1,247 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler.test - -import org.scalajs.core.compiler.test.util._ -import org.junit.Test - -// scalastyle:off line.size.limit - -class JSDynamicLiteralTest extends DirectTest with TestHelpers { - - override def preamble: String = - """import scala.scalajs.js.Dynamic.{ literal => lit } - """ - - @Test - def callApplyOnly: Unit = { - - // selectDynamic (with any name) - expr""" - lit.helloWorld - """.fails() // Scala error, no string checking due to versions - - // applyDynamicNamed with wrong method name - expr""" - lit.helloWorld(a = "a") - """ hasErrors - """ - |newSource1.scala:3: error: js.Dynamic.literal does not have a method named helloWorld - | lit.helloWorld(a = "a") - | ^ - """ - - // applyDynamic with wrong method name - expr""" - lit.helloWorld("a" -> "a") - """ hasErrors - """ - |newSource1.scala:3: error: js.Dynamic.literal does not have a method named helloWorld - | lit.helloWorld("a" -> "a") - | ^ - """ - - } - - @Test - def goodTypesOnly: Unit = { - - // Bad value type (applyDynamic) - """ - class A { - val x = new Object() - def foo = lit("a" -> x) - } - """.fails() - - // Bad key type (applyDynamic) - """ - class A { - val x = Seq() - def foo = lit(x -> "a") - } - """.fails() - - // Bad value type (applyDynamicNamed) - """ - class A { - val x = new Object() - def foo = lit(a = x) - } - """.fails() - - } - - @Test - def noNonLiteralMethodName: Unit = { - - // applyDynamicNamed - """ - class A { - val x = "string" - def foo = lit.applyDynamicNamed(x)() - } - """ hasErrors - """ - |newSource1.scala:5: error: js.Dynamic.literal.applyDynamicNamed may not be called directly - | def foo = lit.applyDynamicNamed(x)() - | ^ - """ - - // applyDynamic - """ - class A { - val x = "string" - def foo = lit.applyDynamic(x)() - } - """ hasErrors - """ - |newSource1.scala:5: error: js.Dynamic.literal.applyDynamic may not be called directly - | def foo = lit.applyDynamic(x)() - | ^ - """ - - } - - @Test - def keyDuplicationWarning: Unit = { - - // detects duplicate named keys - expr""" - lit(a = "1", b = "2", a = "3") - """ hasWarns - """ - |newSource1.scala:3: warning: Duplicate keys in object literal: "a" defined 2 times. Only the last occurrence is assigned. - | lit(a = "1", b = "2", a = "3") - | ^ - """ - - // detects duplicate named keys (check the arrow indentation) - expr""" - lit(aaa = "1", b = "2", aaa = "3") - """ hasWarns - """ - |newSource1.scala:3: warning: Duplicate keys in object literal: "aaa" defined 2 times. Only the last occurrence is assigned. - | lit(aaa = "1", b = "2", aaa = "3") - | ^ - """ - - // detects duplicate named keys (check the arrow indentation) - expr""" - lit(aaa = "1", - bb = "2", - bb = "3") - """ hasWarns - """ - |newSource1.scala:3: warning: Duplicate keys in object literal: "bb" defined 2 times. Only the last occurrence is assigned. - | lit(aaa = "1", - | ^ - """ - - // detects duplicate named keys (check the arrow indentation) - expr""" - lit(aaa = "1", - b = "2", - aaa = "3") - """ hasWarns - """ - |newSource1.scala:3: warning: Duplicate keys in object literal: "aaa" defined 2 times. Only the last occurrence is assigned. - | lit(aaa = "1", - | ^ - """ - - // detects triplicated named keys - expr""" - lit(a = "1", a = "2", a = "3") - """ hasWarns - """ - |newSource1.scala:3: warning: Duplicate keys in object literal: "a" defined 3 times. Only the last occurrence is assigned. - | lit(a = "1", a = "2", a = "3") - | ^ - """ - - // detects two different duplicates named keys - expr""" - lit(a = "1", b = "2", a = "3", b = "4", c = "5", c = "6", c = "7") - """ hasWarns - """ - |newSource1.scala:3: warning: Duplicate keys in object literal: "a" defined 2 times, "b" defined 2 times, "c" defined 3 times. Only the last occurrence is assigned. - | lit(a = "1", b = "2", a = "3", b = "4", c = "5", c = "6", c = "7") - | ^ - """ - - // detects duplicate keys when represented with arrows - expr""" - lit("a" -> "1", "b" -> "2", "a" -> "3") - """ hasWarns - """ - |newSource1.scala:3: warning: Duplicate keys in object literal: "a" defined 2 times. Only the last occurrence is assigned. - | lit("a" -> "1", "b" -> "2", "a" -> "3") - | ^ - """ - - // detects duplicate keys when represented with tuples - expr""" - lit(("a", "1"), ("b", "2"), ("a", "3")) - """ hasWarns - """ - |newSource1.scala:3: warning: Duplicate keys in object literal: "a" defined 2 times. Only the last occurrence is assigned. - | lit(("a", "1"), ("b", "2"), ("a", "3")) - | ^ - """ - - // detects duplicate keys when represented with mixed tuples and arrows - expr""" - lit("a" -> "1", ("b", "2"), ("a", "3")) - """ hasWarns - """ - |newSource1.scala:3: warning: Duplicate keys in object literal: "a" defined 2 times. Only the last occurrence is assigned. - | lit("a" -> "1", ("b", "2"), ("a", "3")) - | ^ - """ - - // should not warn if the key is not literal - expr""" - val a = "x" - lit("a" -> "1", a -> "2", a -> "3") - """ hasWarns - """ - """ - - // should not warn if the key/value pairs are not literal - """ - class A { - val tup = "x" -> lit() - def foo = lit(tup, tup) - } - """ hasWarns - """ - """ - - // should warn only for the literal keys when in - // the presence of non literal keys - """ - class A { - val b = "b" - val tup = b -> lit() - lit("a" -> "2", tup, ("a", "3"), b -> "5", tup, b -> "6") - } - """ hasWarns - """ - |newSource1.scala:6: warning: Duplicate keys in object literal: "a" defined 2 times. Only the last occurrence is assigned. - | lit("a" -> "2", tup, ("a", "3"), b -> "5", tup, b -> "6") - | ^ - """ - } - -} diff --git a/compiler/src/test/scala/org/scalajs/core/compiler/test/JSExportDeprecationsTest.scala b/compiler/src/test/scala/org/scalajs/core/compiler/test/JSExportDeprecationsTest.scala deleted file mode 100644 index 9c17e53fa7..0000000000 --- a/compiler/src/test/scala/org/scalajs/core/compiler/test/JSExportDeprecationsTest.scala +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler.test - -import org.scalajs.core.compiler.test.util._ -import org.junit.Test - -// scalastyle:off line.size.limit - -class JSExportDeprecationsTest extends DirectTest with TestHelpers { - - override def extraArgs: List[String] = - super.extraArgs :+ "-deprecation" - - override def preamble: String = - """import scala.scalajs.js, js.annotation._ - """ - - @Test - def warnJSExportClass: Unit = { - """ - @JSExport - class A - - @JSExport("Foo") - class B - """ hasWarns - """ - |newSource1.scala:3: warning: @JSExport on classes is deprecated and will be removed in 1.0.0. Use @JSExportTopLevel instead (which does exactly the same thing on classes). - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressExportDeprecations` to scalac) - | @JSExport - | ^ - |newSource1.scala:6: warning: @JSExport on classes is deprecated and will be removed in 1.0.0. Use @JSExportTopLevel instead (which does exactly the same thing on classes). - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressExportDeprecations` to scalac) - | @JSExport("Foo") - | ^ - """ - } - - @Test - def warnJSExportObject: Unit = { - """ - @JSExport - object A - - @JSExport("Foo") - object B - """ hasWarns - """ - |newSource1.scala:3: warning: @JSExport on objects is deprecated and will be removed in 1.0.0. Use @JSExportTopLevel instead. Note that it exports the object itself (rather than a 0-arg function returning the object), so the calling JavaScript code must be adapted. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressExportDeprecations` to scalac) - | @JSExport - | ^ - |newSource1.scala:6: warning: @JSExport on objects is deprecated and will be removed in 1.0.0. Use @JSExportTopLevel instead. Note that it exports the object itself (rather than a 0-arg function returning the object), so the calling JavaScript code must be adapted. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressExportDeprecations` to scalac) - | @JSExport("Foo") - | ^ - """ - } - - @Test - def warnJSExportDescendentClasses: Unit = { - for (kind <- Seq("class", "trait", "object")) { - s""" - @JSExportDescendentClasses - $kind A - - @JSExportDescendentClasses(ignoreInvalidDescendants = true) - $kind B - """ hasWarns - """ - |newSource1.scala:3: warning: @JSExportDescendentClasses is deprecated and will be removed in 1.0.0. For use cases where you want to simulate "reflective" instantiation, use @EnableReflectiveInstantion and scala.scalajs.reflect.Reflect.lookupInstantiatableClass instead. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressExportDeprecations` to scalac) - | @JSExportDescendentClasses - | ^ - |newSource1.scala:6: warning: @JSExportDescendentClasses is deprecated and will be removed in 1.0.0. For use cases where you want to simulate "reflective" instantiation, use @EnableReflectiveInstantion and scala.scalajs.reflect.Reflect.lookupInstantiatableClass instead. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressExportDeprecations` to scalac) - | @JSExportDescendentClasses(ignoreInvalidDescendants = true) - | ^ - """ - } - } - - @Test - def warnJSExportDescendentObjects: Unit = { - for (kind <- Seq("class", "trait", "object")) { - s""" - @JSExportDescendentObjects - $kind A - - @JSExportDescendentObjects(ignoreInvalidDescendants = true) - $kind B - """ hasWarns - """ - |newSource1.scala:3: warning: @JSExportDescendentObjects is deprecated and will be removed in 1.0.0. For use cases where you want to simulate "reflective" loading, use @EnableReflectiveInstantion and scala.scalajs.reflect.Reflect.lookupLoadableModuleClass instead. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressExportDeprecations` to scalac) - | @JSExportDescendentObjects - | ^ - |newSource1.scala:6: warning: @JSExportDescendentObjects is deprecated and will be removed in 1.0.0. For use cases where you want to simulate "reflective" loading, use @EnableReflectiveInstantion and scala.scalajs.reflect.Reflect.lookupLoadableModuleClass instead. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressExportDeprecations` to scalac) - | @JSExportDescendentObjects(ignoreInvalidDescendants = true) - | ^ - """ - } - } - - @Test - def warnJSExportTopLevelNamespaced: Unit = { - """ - @JSExportTopLevel("namespaced.export1") - object A - @JSExportTopLevel("namespaced.export2") - class B - object C { - @JSExportTopLevel("namespaced.export3") - val a: Int = 1 - @JSExportTopLevel("namespaced.export4") - var b: Int = 1 - @JSExportTopLevel("namespaced.export5") - def c(): Int = 1 - } - """ hasWarns - """ - |newSource1.scala:3: warning: Using a namespaced export (with a '.') in @JSExportTopLevel is deprecated. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressExportDeprecations` to scalac) - | @JSExportTopLevel("namespaced.export1") - | ^ - |newSource1.scala:5: warning: Using a namespaced export (with a '.') in @JSExportTopLevel is deprecated. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressExportDeprecations` to scalac) - | @JSExportTopLevel("namespaced.export2") - | ^ - |newSource1.scala:8: warning: Using a namespaced export (with a '.') in @JSExportTopLevel is deprecated. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressExportDeprecations` to scalac) - | @JSExportTopLevel("namespaced.export3") - | ^ - |newSource1.scala:10: warning: Using a namespaced export (with a '.') in @JSExportTopLevel is deprecated. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressExportDeprecations` to scalac) - | @JSExportTopLevel("namespaced.export4") - | ^ - |newSource1.scala:12: warning: Using a namespaced export (with a '.') in @JSExportTopLevel is deprecated. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressExportDeprecations` to scalac) - | @JSExportTopLevel("namespaced.export5") - | ^ - """ - } - -} diff --git a/compiler/src/test/scala/org/scalajs/core/compiler/test/JSExportTest.scala b/compiler/src/test/scala/org/scalajs/core/compiler/test/JSExportTest.scala deleted file mode 100644 index 2521e3c24f..0000000000 --- a/compiler/src/test/scala/org/scalajs/core/compiler/test/JSExportTest.scala +++ /dev/null @@ -1,2011 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler.test - -import org.scalajs.core.compiler.test.util._ -import org.scalajs.core.compiler.test.util.VersionDependentMessages.methodSig - -import org.junit.Assume._ -import org.junit.Test - -// scalastyle:off line.size.limit - -class JSExportTest extends DirectTest with TestHelpers { - - override def extraArgs: List[String] = - super.extraArgs ::: List("-deprecation", "-P:scalajs:suppressExportDeprecations") - - override def preamble: String = - """import scala.scalajs.js, js.annotation._ - """ - - @Test - def warnOnDuplicateExport: Unit = { - """ - class A { - @JSExport - @JSExport - def a = 1 - } - """ hasWarns - """ - |newSource1.scala:6: warning: Found duplicate @JSExport - | def a = 1 - | ^ - """ - - """ - class A { - @JSExport - @JSExport("a") - def a = 1 - } - """ hasWarns - """ - |newSource1.scala:6: warning: Found duplicate @JSExport - | def a = 1 - | ^ - """ - - """ - class A { - @JSExport("a") - @JSExport("a") - def a = 1 - } - """ hasWarns - """ - |newSource1.scala:6: warning: Found duplicate @JSExport - | def a = 1 - | ^ - """ - - // special case for @JSExportAll and 2 or more @JSExport("apply") - // since @JSExportAll and single @JSExport("apply") should not be warned (see other tests) - """ - @JSExportAll - class A { - @JSExport("apply") - @JSExport("apply") - def apply(): Int = 1 - } - """ hasWarns - """ - |newSource1.scala:7: warning: Found duplicate @JSExport - | def apply(): Int = 1 - | ^ - """ - - """ - @JSExportAll - class A { - @JSExport - def a = 1 - } - """ hasWarns - """ - |newSource1.scala:6: warning: Found duplicate @JSExport - | def a = 1 - | ^ - """ - } - @Test - def noWarnOnUniqueExplicitName: Unit = { - """ - class A { - @JSExport("a") - @JSExport("b") - def c = 1 - } - """.hasNoWarns - } - @Test - def noDoubleUnderscoreExport: Unit = { - // Normal exports - """ - class A { - @JSExport(name = "__") - def foo = 1 - - @JSExport - def bar__(x: Int) = x - } - - @JSExport - class B__ - - @JSExport - class C__ extends js.Object - """ hasErrors - """ - |newSource1.scala:4: error: An exported name may not contain a double underscore (`__`) - | @JSExport(name = "__") - | ^ - |newSource1.scala:8: error: An exported name may not contain a double underscore (`__`) - | def bar__(x: Int) = x - | ^ - |newSource1.scala:12: error: An exported name may not contain a double underscore (`__`) - | class B__ - | ^ - |newSource1.scala:15: error: An exported name may not contain a double underscore (`__`) - | class C__ extends js.Object - | ^ - """ - - // Inherited exports (objects) - """ - @JSExportDescendentObjects - trait A - - package fo__o { - object B extends A - } - """ hasErrors - """ - |newSource1.scala:7: error: B may not have a double underscore (`__`) in its fully qualified name, since it is forced to be exported by a @JSExportDescendentObjects on trait A - | object B extends A - | ^ - """ - - """ - @JSExportDescendentObjects - trait A extends js.Object - - package fo__o { - object B extends A - } - """ hasErrors - """ - |newSource1.scala:7: error: B may not have a double underscore (`__`) in its fully qualified name, since it is forced to be exported by a @JSExportDescendentObjects on trait A - | object B extends A - | ^ - """ - - // Inherited exports (classes) - """ - @JSExportDescendentClasses - trait A - - package fo__o { - class B(x: Int) extends A { - def this() = this(1) - private def this(s: String) = this(1) - } - } - """ hasErrors - """ - |newSource1.scala:7: error: B may not have a double underscore (`__`) in its fully qualified name, since it is forced to be exported by a @JSExportDescendentClasses on trait A - | class B(x: Int) extends A { - | ^ - |newSource1.scala:8: error: B may not have a double underscore (`__`) in its fully qualified name, since it is forced to be exported by a @JSExportDescendentClasses on trait A - | def this() = this(1) - | ^ - """ - - """ - @JSExportDescendentClasses - trait A extends js.Object - - package fo__o { - class B(x: Int) extends A - } - """ hasErrors - """ - |newSource1.scala:7: error: B may not have a double underscore (`__`) in its fully qualified name, since it is forced to be exported by a @JSExportDescendentClasses on trait A - | class B(x: Int) extends A - | ^ - """ - } - - @Test - def doubleUnderscoreOKInTopLevelExport: Unit = { - """ - @JSExportTopLevel("__A") - class A - - @JSExportTopLevel("__B") - object B - - object Container { - @JSExportTopLevel("__c") - def c(): Int = 4 - - @JSExportTopLevel("__d") - val d: Boolean = true - } - """.hasNoWarns - } - - @Test - def noConflictingExport: Unit = { - """ - class Confl { - @JSExport("value") - def hello = "foo" - - @JSExport("value") - def world = "bar" - } - """.fails() // No error test, Scala version dependent error messages - - """ - class Confl { - class Box[T](val x: T) - - @JSExport - def ub(x: Box[String]): String = x.x - @JSExport - def ub(x: Box[Int]): Int = x.x - } - """.fails() // No error test, Scala version dependent error messages - - """ - class Confl { - @JSExport - def rtType(x: scala.scalajs.js.prim.Number) = x - - @JSExport - def rtType(x: Double) = x - } - """.fails() // Error message depends on Scala version - - """ - class Confl { - @JSExport - def foo(x: Int)(ys: Int*) = x - - @JSExport - def foo(x: Int*) = x - } - """ hasErrors - s""" - |newSource1.scala:7: error: Cannot disambiguate overloads for exported method foo with types - | ${methodSig("(x: Int, ys: Seq)", "Object")} - | ${methodSig("(x: Seq)", "Object")} - | @JSExport - | ^ - """ - - """ - class Confl { - @JSExport - def foo(x: Int = 1) = x - @JSExport - def foo(x: String*) = x - } - """ hasErrors - s""" - |newSource1.scala:6: error: Cannot disambiguate overloads for exported method foo with types - | ${methodSig("(x: Int)", "Object")} - | ${methodSig("(x: Seq)", "Object")} - | @JSExport - | ^ - """ - - """ - class Confl { - @JSExport - def foo(x: scala.scalajs.js.prim.Number, y: String)(z: Int = 1) = x - @JSExport - def foo(x: Double, y: String)(z: String*) = x - } - """.fails() // Error message depends on Scala version - - """ - class A { - @JSExport - def a(x: scala.scalajs.js.Any) = 1 - - @JSExport - def a(x: Any) = 2 - } - """.fails() // Error message depends on Scala version - - } - - @Test - def noExportLocal: Unit = { - // Local class - """ - class A { - def method = { - @JSExport - class A - - @JSExport - class B extends js.Object - } - } - """ hasErrors - """ - |newSource1.scala:5: error: You may not export a local class - | @JSExport - | ^ - |newSource1.scala:8: error: You may not export a local class - | @JSExport - | ^ - """ - - // Local object - """ - class A { - def method = { - @JSExport - object A - - @JSExport - object B extends js.Object - } - } - """ hasErrors - """ - |newSource1.scala:5: error: You may not export a local object - | @JSExport - | ^ - |newSource1.scala:8: error: You may not export a local object - | @JSExport - | ^ - """ - - // Local method - """ - class A { - def method = { - @JSExport - def foo = 1 - } - } - """ hasErrors - """ - |newSource1.scala:5: error: You may not export a local definition - | @JSExport - | ^ - """ - - // Local val - """ - class A { - def method = { - @JSExport - val x = 1 - } - } - """ hasErrors - """ - |newSource1.scala:5: error: You may not export a local definition - | @JSExport - | ^ - """ - - // Local var - """ - class A { - def method = { - @JSExport - var x = 1 - } - } - """ hasErrors - """ - |newSource1.scala:5: error: You may not export a local definition - | @JSExport - | ^ - """ - - } - - @Test - def noMiddleVarArg: Unit = { - - """ - class A { - @JSExport - def method(xs: Int*)(ys: String) = 1 - } - """ hasErrors - """ - |newSource1.scala:4: error: In an exported method, a *-parameter must come last (through all parameter lists) - | @JSExport - | ^ - """ - - } - - @Test - def noMiddleDefaultParam: Unit = { - - """ - class A { - @JSExport - def method(x: Int = 1)(y: String) = 1 - } - """ hasErrors - """ - |newSource1.scala:4: error: In an exported method, all parameters with defaults must be at the end - | @JSExport - | ^ - """ - - } - - @Test - def noExportAbstractClass: Unit = { - - """ - @JSExport - abstract class A - - abstract class B(x: Int) { - @JSExport - def this() = this(5) - } - - @JSExport - abstract class C extends js.Object - """ hasErrors - """ - |newSource1.scala:3: error: You may not export an abstract class - | @JSExport - | ^ - |newSource1.scala:7: error: You may not export an abstract class - | @JSExport - | ^ - |newSource1.scala:11: error: You may not export an abstract class - | @JSExport - | ^ - """ - - } - - @Test - def noExportTrait: Unit = { - - """ - @JSExport - trait Test - - @JSExport - trait Test2 extends js.Object - - @JSExport - @js.native - trait Test3 extends js.Object - """ hasErrors - """ - |newSource1.scala:3: error: You may not export a trait - | @JSExport - | ^ - |newSource1.scala:6: error: You may not export a trait - | @JSExport - | ^ - |newSource1.scala:9: error: You may not export a trait - | @JSExport - | ^ - """ - - } - - @Test - def noExportNonPublicClassOrObject: Unit = { - - """ - @JSExport - private class A - - @JSExport - protected[this] class B - - @JSExport - private class C extends js.Object - - @JSExport - protected[this] class D extends js.Object - """ hasErrors - """ - |newSource1.scala:3: error: You may only export public and protected classes - | @JSExport - | ^ - |newSource1.scala:6: error: You may only export public and protected classes - | @JSExport - | ^ - |newSource1.scala:9: error: You may only export public and protected classes - | @JSExport - | ^ - |newSource1.scala:12: error: You may only export public and protected classes - | @JSExport - | ^ - """ - - """ - @JSExport - private object A - - @JSExport - protected[this] object B - - @JSExport - private object C extends js.Object - - @JSExport - protected[this] object D extends js.Object - """ hasErrors - """ - |newSource1.scala:3: error: You may only export public and protected objects - | @JSExport - | ^ - |newSource1.scala:6: error: You may only export public and protected objects - | @JSExport - | ^ - |newSource1.scala:9: error: You may only export public and protected objects - | @JSExport - | ^ - |newSource1.scala:12: error: You may only export public and protected objects - | @JSExport - | ^ - """ - - } - - @Test - def noExportNonPublicMember: Unit = { - - """ - class A { - @JSExport - private def foo = 1 - - @JSExport - protected[this] def bar = 2 - } - """ hasErrors - """ - |newSource1.scala:4: error: You may only export public and protected methods - | @JSExport - | ^ - |newSource1.scala:7: error: You may only export public and protected methods - | @JSExport - | ^ - """ - - } - - @Test - def noExportNestedClass: Unit = { - - """ - class A { - @JSExport - class Nested { - @JSExport - def this(x: Int) = this() - } - - @JSExport - class Nested2 extends js.Object - } - """ hasErrors - """ - |newSource1.scala:4: error: You may not export a nested class. Create an exported factory method in the outer class to work around this limitation. - | @JSExport - | ^ - |newSource1.scala:6: error: You may not export a nested class. Create an exported factory method in the outer class to work around this limitation. - | @JSExport - | ^ - |newSource1.scala:10: error: You may not export a nested class. Create an exported factory method in the outer class to work around this limitation. - | @JSExport - | ^ - """ - - } - - @Test - def noImplicitNameNestedExportClass: Unit = { - - """ - object A { - @JSExport - class Nested { - @JSExport - def this(x: Int) = this - } - - @JSExport - class Nested2 extends js.Object - } - """ hasErrors - """ - |newSource1.scala:4: error: You must set an explicit name for exports of nested classes. - | @JSExport - | ^ - |newSource1.scala:6: error: You must set an explicit name for exports of nested classes. - | @JSExport - | ^ - |newSource1.scala:10: error: You must set an explicit name for exports of nested classes. - | @JSExport - | ^ - """ - - } - - @Test - def noExportNestedObject: Unit = { - - """ - class A { - @JSExport - object Nested - - @JSExport - object Nested2 extends js.Object - } - """ hasErrors - """ - |newSource1.scala:4: error: You may not export a nested object - | @JSExport - | ^ - |newSource1.scala:7: error: You may not export a nested object - | @JSExport - | ^ - """ - - } - - @Test - def noImplicitNameNestedExportObject: Unit = { - - """ - object A { - @JSExport - object Nested - - @JSExport - object Nested2 extends js.Object - } - """ hasErrors - """ - |newSource1.scala:4: error: You must set an explicit name for exports of nested classes. - | @JSExport - | ^ - |newSource1.scala:7: error: You must set an explicit name for exports of nested classes. - | @JSExport - | ^ - """ - - } - - @Test - def noExportJSRaw: Unit = { - - """ - import scala.scalajs.js - - @JSExport - @js.native - @JSGlobal("Dummy") - object A extends js.Object - """ hasErrors - """ - |newSource1.scala:5: error: You may not export a native JS class or object - | @JSExport - | ^ - """ - - """ - import scala.scalajs.js - - @JSExport - @js.native - trait A extends js.Object - """ hasErrors - """ - |newSource1.scala:5: error: You may not export a trait - | @JSExport - | ^ - """ - - """ - import scala.scalajs.js - - @JSExport - @js.native - @JSGlobal("Dummy") - class A extends js.Object { - @JSExport - def this(x: Int) = this() - } - """ hasErrors - """ - |newSource1.scala:5: error: You may not export a native JS class or object - | @JSExport - | ^ - |newSource1.scala:9: error: You may not export a constructor of a subclass of js.Any - | @JSExport - | ^ - """ - - } - - @Test - def noExportJSRawMember: Unit = { - - """ - import scala.scalajs.js - - @js.native - @JSGlobal("Dummy") - class A extends js.Object { - @JSExport - def foo: Int = js.native - } - """ hasErrors - """ - |newSource1.scala:8: error: You may not export a method of a subclass of js.Any - | @JSExport - | ^ - """ - - """ - import scala.scalajs.js - - class A extends js.Object { - @JSExport - def foo: Int = js.native - } - """ hasErrors - """ - |newSource1.scala:6: error: You may not export a method of a subclass of js.Any - | @JSExport - | ^ - """ - - } - - @Test - def noBadSetterType: Unit = { - - // Bad param list - """ - class A { - @JSExport - def foo_=(x: Int, y: Int) = () - } - """ hasErrors - """ - |newSource1.scala:4: error: Exported setters must have exactly one argument - | @JSExport - | ^ - """ - - // Bad return type - """ - class A { - @JSExport - def foo_=(x: Int) = "string" - } - """ hasErrors - """ - |newSource1.scala:4: error: Exported setters must return Unit - | @JSExport - | ^ - """ - - // Varargs - """ - class A { - @JSExport - def foo_=(x: Int*) = () - } - """ hasErrors - """ - |newSource1.scala:4: error: Exported setters may not have repeated params - | @JSExport - | ^ - """ - - // Default arguments - """ - class A { - @JSExport - def foo_=(x: Int = 1) = () - } - """ hasWarns - """ - |newSource1.scala:4: warning: Exported setters may not have default params. This will be enforced in 1.0. - | @JSExport - | ^ - """ - - } - - @Test - def noBadToStringExport: Unit = { - - """ - class A { - @JSExport("toString") - def a(): Int = 5 - } - """ hasErrors - """ - |newSource1.scala:4: error: You may not export a zero-argument method named other than 'toString' under the name 'toString' - | @JSExport("toString") - | ^ - """ - - } - - @Test - def noBadNameExportAll: Unit = { - - """ - @JSExportAll - class A { - val __f = 1 - def a_= = 2 - } - """ hasErrors - """ - |newSource1.scala:5: error: An exported name may not contain a double underscore (`__`) - | val __f = 1 - | ^ - |newSource1.scala:3: error: Exported setters must return Unit - | @JSExportAll - | ^ - """ - - } - - @Test - def noConflictingMethodAndProperty: Unit = { - - // Basic case - """ - class A { - @JSExport("a") - def bar() = 2 - - @JSExport("a") - val foo = 1 - } - """ hasErrors - """ - |newSource1.scala:4: error: Exported property a conflicts with A.$js$exported$meth$a - | @JSExport("a") - | ^ - |newSource1.scala:7: error: Exported method a conflicts with A.$js$exported$prop$a - | @JSExport("a") - | ^ - """ - - // Inherited case - """ - class A { - @JSExport("a") - def bar() = 2 - } - - class B extends A { - @JSExport("a") - def foo_=(x: Int): Unit = () - - @JSExport("a") - val foo = 1 - } - """ hasErrors - """ - |newSource1.scala:4: error: Exported property a conflicts with A.$js$exported$meth$a - | @JSExport("a") - | ^ - """ - - } - - @Test - def namedExportIsDeprecated: Unit = { - - """ - class A { - @JSExportNamed - def foo(x: Int, y: Int) = 1 - } - """ hasWarns - s""" - |newSource1.scala:5: warning: class JSExportNamed in package annotation is deprecated${since("0.6.11")}: Use @JSExport with an explicit option bag instead. See the Scaladoc for more details. - | def foo(x: Int, y: Int) = 1 - | ^ - |newSource1.scala:4: warning: class JSExportNamed in package annotation is deprecated${since("0.6.11")}: Use @JSExport with an explicit option bag instead. See the Scaladoc for more details. - | @JSExportNamed - | ^ - """ - - } - - @Test - def noOverrideNamedExport: Unit = { - - val overrideFinalMsg = { - val version = scala.util.Properties.versionNumberString - if (version.startsWith("2.10.") || - version.startsWith("2.11.") || - version.startsWith("2.12.")) { - """overriding method $js$exported$meth$foo in class A of type (namedArgs: Any)Any; - | method $js$exported$meth$foo cannot override final member""".stripMargin - } else { - """cannot override final member: - |final def $js$exported$meth$foo(namedArgs: Any): Any (defined in class A)""".stripMargin - } - } - - """ - class A { - @JSExportNamed - def foo(x: Int, y: Int) = 1 - } - - class B extends A { - @JSExportNamed - override def foo(x: Int, y: Int) = 2 - } - """ hasErrors - s""" - |newSource1.scala:5: warning: class JSExportNamed in package annotation is deprecated${since("0.6.11")}: Use @JSExport with an explicit option bag instead. See the Scaladoc for more details. - | def foo(x: Int, y: Int) = 1 - | ^ - |newSource1.scala:4: warning: class JSExportNamed in package annotation is deprecated${since("0.6.11")}: Use @JSExport with an explicit option bag instead. See the Scaladoc for more details. - | @JSExportNamed - | ^ - |newSource1.scala:9: error: $overrideFinalMsg - | @JSExportNamed - | ^ - |newSource1.scala:10: warning: class JSExportNamed in package annotation is deprecated${since("0.6.11")}: Use @JSExport with an explicit option bag instead. See the Scaladoc for more details. - | override def foo(x: Int, y: Int) = 2 - | ^ - """ - - } - - @Test - def noConflictNamedExport: Unit = { - - // Normal method - """ - class A { - @JSExportNamed - def foo(x: Int, y: Int) = 1 - - @JSExport - def foo(x: scala.scalajs.js.Any) = 2 - } - """.fails() // No error test, Scala version dependent error messages - - // Ctors - """ - class A { - @JSExportNamed - def this(x: Int) = this() - - @JSExport - def this(x: scala.scalajs.js.Any) = this - - @JSExportNamed - def this(x: Long) = this() - } - """.fails() // No error test, Scala version dependent error messages - - } - - @Test - def noNamedExportObject: Unit = { - - """ - @JSExportNamed - object A - - @JSExportNamed - object B extends js.Object - """ hasErrors - """ - |newSource1.scala:3: error: You may not use @JSNamedExport on an object - | @JSExportNamed - | ^ - |newSource1.scala:6: error: You may not use @JSNamedExport on an object - | @JSExportNamed - | ^ - """ - - } - - @Test - def noNamedExportSJSDefinedClass: Unit = { - - """ - @JSExportNamed - class A extends js.Object - """ hasErrors - """ - |newSource1.scala:3: error: You may not use @JSNamedExport on a Scala.js-defined JS class - | @JSExportNamed - | ^ - """ - - } - - @Test - def noNamedExportVarArg: Unit = { - - """ - class A { - @JSExportNamed - def foo(a: Int*) = 1 - } - """ hasErrors - s""" - |newSource1.scala:5: warning: class JSExportNamed in package annotation is deprecated${since("0.6.11")}: Use @JSExport with an explicit option bag instead. See the Scaladoc for more details. - | def foo(a: Int*) = 1 - | ^ - |newSource1.scala:4: warning: class JSExportNamed in package annotation is deprecated${since("0.6.11")}: Use @JSExport with an explicit option bag instead. See the Scaladoc for more details. - | @JSExportNamed - | ^ - |newSource1.scala:4: error: You may not name-export a method with a *-parameter - | @JSExportNamed - | ^ - """ - - } - - @Test - def noNamedExportProperty: Unit = { - - // Getter - """ - class A { - @JSExportNamed - def a = 1 - } - """ hasErrors - """ - |newSource1.scala:4: error: You may not export a getter or a setter as a named export - | @JSExportNamed - | ^ - """ - - - // Setter - """ - class A { - @JSExportNamed - def a_=(x: Int) = () - } - """ hasErrors - """ - |newSource1.scala:4: error: You may not export a getter or a setter as a named export - | @JSExportNamed - | ^ - """ - - } - - @Test - def gracefulDoubleDefaultFail: Unit = { - // This used to blow up (i.e. not just fail), because PrepJSExports asked - // for the symbol of the default parameter getter of [[y]], and asserted its - // not overloaded. Since the Scala compiler only fails later on this, the - // assert got triggered and made the compiler crash - """ - class A { - @JSExport - def foo(x: String, y: String = "hello") = x - def foo(x: Int, y: String = "bar") = x - } - """.fails() - } - - @Test - def noNonLiteralExportNames: Unit = { - - """ - object A { - val a = "Hello" - final val b = "World" - } - - class B { - @JSExport(A.a) - def foo = 1 - @JSExport(A.b) - def bar = 1 - } - """ hasErrors - """ - |newSource1.scala:9: error: The argument to JSExport must be a literal string - | @JSExport(A.a) - | ^ - """ - - } - - @Test - def noInheritIgnoreInvalidDescendants: Unit = { - - """ - @JSExportDescendentClasses - trait A - - @JSExportDescendentClasses(ignoreInvalidDescendants = true) - trait B - - object A { - // Local class is not allowed - def foo = { new A with B } - } - """ hasErrors - """ - |newSource1.scala:11: error: You may not export a local class - | def foo = { new A with B } - | ^ - """ - } - - @Test - def noExportImplicitApply: Unit = { - - """ - class A { - @JSExport - def apply(): Int = 1 - } - """ hasWarns - """ - |newSource1.scala:4: warning: Member cannot be exported to function application. It is available under the name apply instead. Add @JSExport("apply") to silence this warning. This will be enforced in 1.0. - | @JSExport - | ^ - """ - - """ - @JSExportAll - class A { - def apply(): Int = 1 - } - """ hasWarns - """ - |newSource1.scala:5: warning: Member cannot be exported to function application. It is available under the name apply instead. Add @JSExport("apply") to silence this warning. This will be enforced in 1.0. - | def apply(): Int = 1 - | ^ - """ - - // For this case, deprecation warnings are not exactly the same in 2.10.x - """ - @JSExportAll - class A { - @JSExportNamed("apply") - @JSExport("foo") - def apply(): Int = 1 - } - """ containsWarns - """ - |newSource1.scala:7: warning: Member cannot be exported to function application. It is available under the name apply instead. Add @JSExport("apply") to silence this warning. This will be enforced in 1.0. - | def apply(): Int = 1 - | ^ - """ - - """ - @JSExportAll - class A { - @JSExport("apply") - def apply(): Int = 1 - } - """.hasNoWarns - - } - - @Test - def exportObjectAsToString: Unit = { - - """ - @JSExport("toString") - object ExportAsToString - """.succeeds - - } - - private def since(v: String): String = { - val version = scala.util.Properties.versionNumberString - if (version.startsWith("2.10.") || version.startsWith("2.11.")) "" - else s" (since $v)" - } - - @Test - def noExportTopLevelTrait: Unit = { - """ - @JSExportTopLevel("foo") - trait A - - @JSExportTopLevel("bar") - trait B extends js.Object - """ hasErrors - """ - |newSource1.scala:3: error: You may not export a trait - | @JSExportTopLevel("foo") - | ^ - |newSource1.scala:6: error: You may not export a trait - | @JSExportTopLevel("bar") - | ^ - """ - - """ - object Container { - @JSExportTopLevel("foo") - trait A - - @JSExportTopLevel("bar") - trait B extends js.Object - } - """ hasErrors - """ - |newSource1.scala:4: error: You may not export a trait - | @JSExportTopLevel("foo") - | ^ - |newSource1.scala:7: error: You may not export a trait - | @JSExportTopLevel("bar") - | ^ - """ - } - - @Test - def noExportTopLevelLazyVal: Unit = { - """ - object A { - @JSExportTopLevel("foo") - lazy val a: Int = 1 - } - """ hasErrors - """ - |newSource1.scala:4: error: You may not export a lazy val to the top level - | @JSExportTopLevel("foo") - | ^ - """ - } - - @Test - def noExportTopLevelGetter: Unit = { - """ - object A { - @JSExportTopLevel("foo") - def a: Int = 1 - } - """ hasErrors - """ - |newSource1.scala:4: error: You may not export a getter or a setter to the top level - | @JSExportTopLevel("foo") - | ^ - """ - } - - @Test - def noExportTopLevelSetter: Unit = { - """ - object A { - @JSExportTopLevel("foo") - def a_=(x: Int): Unit = () - } - """ hasErrors - """ - |newSource1.scala:4: error: You may not export a getter or a setter to the top level - | @JSExportTopLevel("foo") - | ^ - """ - } - - @Test - def noExportTopLevelFieldsWithSameName: Unit = { - """ - object A { - @JSExportTopLevel("foo") - val a: Int = 1 - - @JSExportTopLevel("foo") - var b: Int = 1 - } - """ hasErrors - """ - |newSource1.scala:5: error: Duplicate top-level export with name 'foo': a field may not share its exported name with another field or method - | val a: Int = 1 - | ^ - """ - } - - @Test - def noExportTopLevelFieldsAndMethodsWithSameName: Unit = { - """ - object A { - @JSExportTopLevel("foo") - val a: Int = 1 - - @JSExportTopLevel("foo") - def b(x: Int): Int = x + 1 - } - """ hasErrors - """ - |newSource1.scala:7: error: Duplicate top-level export with name 'foo': a field may not share its exported name with another field or method - | @JSExportTopLevel("foo") - | ^ - """ - - """ - object A { - @JSExportTopLevel("foo") - def a(x: Int): Int = x + 1 - - @JSExportTopLevel("foo") - val b: Int = 1 - } - """ hasErrors - """ - |newSource1.scala:4: error: Duplicate top-level export with name 'foo': a field may not share its exported name with another field or method - | @JSExportTopLevel("foo") - | ^ - """ - } - - @Test - def noExportTopLevelNonStatic: Unit = { - """ - class A { - @JSExportTopLevel("foo") - def a(): Unit = () - } - """ hasErrors - """ - |newSource1.scala:4: error: Only static objects may export their members to the top level - | @JSExportTopLevel("foo") - | ^ - """ - - """ - class A { - object B { - @JSExportTopLevel("foo") - def a(): Unit = () - } - } - """ hasErrors - """ - |newSource1.scala:5: error: Only static objects may export their members to the top level - | @JSExportTopLevel("foo") - | ^ - """ - - """ - class A { - @JSExportTopLevel("Foo") - object B - } - """ hasErrors - """ - |newSource1.scala:4: error: Only static objects may export their members to the top level - | @JSExportTopLevel("Foo") - | ^ - """ - - """ - class A { - @JSExportTopLevel("Foo") - object B extends js.Object - } - """ hasErrors - """ - |newSource1.scala:4: error: Only static objects may export their members to the top level - | @JSExportTopLevel("Foo") - | ^ - """ - - """ - class A { - @JSExportTopLevel("Foo") - class B extends js.Object - } - """ hasErrors - """ - |newSource1.scala:4: error: Only static objects may export their members to the top level - | @JSExportTopLevel("Foo") - | ^ - """ - - """ - class A { - @JSExportTopLevel("Foo") - class B - } - """ hasErrors - """ - |newSource1.scala:4: error: Only static objects may export their members to the top level - | @JSExportTopLevel("Foo") - | ^ - """ - } - - @Test - def noExportTopLevelJSModule: Unit = { - """ - object A extends js.Object { - @JSExportTopLevel("foo") - def a(): Unit = () - } - """ hasErrors - """ - |newSource1.scala:4: error: You may not export a method of a subclass of js.Any - | @JSExportTopLevel("foo") - | ^ - """ - } - - @Test - def noExportStaticModule: Unit = { - """ - class StaticContainer extends js.Object - - object StaticContainer { - @JSExportStatic - object A - } - """ hasErrors - """ - |newSource1.scala:6: error: Implementation restriction: cannot export a class or object as static - | @JSExportStatic - | ^ - """ - } - - @Test - def noExportStaticTrait: Unit = { - """ - class StaticContainer extends js.Object - - object StaticContainer { - @JSExportStatic - trait A - } - """ hasErrors - """ - |newSource1.scala:6: error: You may not export a trait as static. - | @JSExportStatic - | ^ - """ - } - - @Test - def noExportStaticClass: Unit = { - """ - class StaticContainer extends js.Object - - object StaticContainer { - @JSExportStatic - class A - } - """ hasErrors - """ - |newSource1.scala:6: error: Implementation restriction: cannot export a class or object as static - | @JSExportStatic - | ^ - """ - - """ - class StaticContainer extends js.Object - - object StaticContainer { - class A { - @JSExportStatic - def this(x: Int) = this() - } - } - """ hasErrors - """ - |newSource1.scala:7: error: Implementation restriction: cannot export a class or object as static - | @JSExportStatic - | ^ - """ - } - - @Test - def noExportStaticValTwice: Unit = { - """ - class StaticContainer extends js.Object - - object StaticContainer { - @JSExportStatic - @JSExportStatic("b") - val a: Int = 1 - } - """ hasErrors - """ - |newSource1.scala:7: error: Fields (val or var) cannot be exported as static more than once - | @JSExportStatic("b") - | ^ - """ - } - - @Test - def noExportStaticVarTwice: Unit = { - """ - class StaticContainer extends js.Object - - object StaticContainer { - @JSExportStatic - @JSExportStatic("b") - var a: Int = 1 - } - """ hasErrors - """ - |newSource1.scala:7: error: Fields (val or var) cannot be exported as static more than once - | @JSExportStatic("b") - | ^ - """ - } - - @Test - def noExportStaticLazyVal: Unit = { - // Affected by Scala bug SI-10075 - assumeTrue(scala.util.Properties.versionNumberString != "2.12.0") - - """ - class StaticContainer extends js.Object - - object StaticContainer { - @JSExportStatic - lazy val a: Int = 1 - } - """ hasErrors - """ - |newSource1.scala:6: error: You may not export a lazy val as static - | @JSExportStatic - | ^ - """ - } - - @Test - def noExportValAsStaticAndTopLevel: Unit = { - """ - class StaticContainer extends js.Object - - object StaticContainer { - @JSExportStatic - @JSExportTopLevel("foo") - val a: Int = 1 - } - """ hasErrors - """ - |newSource1.scala:7: error: Fields (val or var) cannot be exported both as static and at the top-level - | @JSExportTopLevel("foo") - | ^ - """ - } - - @Test - def noExportVarAsStaticAndTopLevel: Unit = { - """ - class StaticContainer extends js.Object - - object StaticContainer { - @JSExportStatic - @JSExportTopLevel("foo") - var a: Int = 1 - } - """ hasErrors - """ - |newSource1.scala:7: error: Fields (val or var) cannot be exported both as static and at the top-level - | @JSExportTopLevel("foo") - | ^ - """ - } - - @Test - def noExportSetterWithBadSetterType: Unit = { - """ - class StaticContainer extends js.Object - - object StaticContainer { - @JSExportStatic - def a_=(x: Int, y: Int): Unit = () - } - """ hasErrors - """ - |newSource1.scala:6: error: Exported setters must have exactly one argument - | @JSExportStatic - | ^ - """ - } - - @Test - def noExportStaticCollapsingMethods: Unit = { - """ - class StaticContainer extends js.Object - - object StaticContainer { - @JSExportStatic - def foo(x: Int): Int = x - - @JSExportStatic("foo") - def bar(x: Int): Int = x + 1 - } - """ hasErrors - s""" - |newSource1.scala:10: error: Cannot disambiguate overloads for exported method foo with types - | ${methodSig("(x: Int)", "Int")} - | ${methodSig("(x: Int)", "Int")} - | def bar(x: Int): Int = x + 1 - | ^ - """ - } - - @Test - def noExportStaticCollapsingGetters: Unit = { - """ - class StaticContainer extends js.Object - - object StaticContainer { - @JSExportStatic - def foo: Int = 1 - - @JSExportStatic("foo") - def bar: Int = 2 - } - """ hasErrors - """ - |newSource1.scala:7: error: Duplicate static getter export with name 'foo' - | def foo: Int = 1 - | ^ - """ - } - - @Test - def noExportStaticCollapsingSetters: Unit = { - """ - class StaticContainer extends js.Object - - object StaticContainer { - @JSExportStatic - def foo_=(v: Int): Unit = () - - @JSExportStatic("foo") - def bar_=(v: Int): Unit = () - } - """ hasErrors - s""" - |newSource1.scala:10: error: Cannot disambiguate overloads for exported method foo with types - | ${methodSig("(v: Int)", "Unit")} - | ${methodSig("(v: Int)", "Unit")} - | def bar_=(v: Int): Unit = () - | ^ - """ - } - - @Test - def noExportStaticFieldsWithSameName: Unit = { - """ - class StaticContainer extends js.Object - - object StaticContainer { - @JSExportStatic - val a: Int = 1 - - @JSExportStatic("a") - var b: Int = 1 - } - """ hasErrors - """ - |newSource1.scala:7: error: Duplicate static export with name 'a': a field may not share its exported name with another field or method - | val a: Int = 1 - | ^ - """ - } - - @Test - def noExportStaticFieldsAndMethodsWithSameName: Unit = { - """ - class StaticContainer extends js.Object - - object StaticContainer { - @JSExportStatic - val a: Int = 1 - - @JSExportStatic("a") - def b(x: Int): Int = x + 1 - } - """ hasErrors - """ - |newSource1.scala:9: error: Duplicate static export with name 'a': a field may not share its exported name with another field or method - | @JSExportStatic("a") - | ^ - """ - - """ - class StaticContainer extends js.Object - - object StaticContainer { - @JSExportStatic - def a(x: Int): Int = x + 1 - - @JSExportStatic("a") - val b: Int = 1 - } - """ hasErrors - """ - |newSource1.scala:6: error: Duplicate static export with name 'a': a field may not share its exported name with another field or method - | @JSExportStatic - | ^ - """ - } - - @Test - def noExportStaticFieldsAndPropertiesWithSameName: Unit = { - """ - class StaticContainer extends js.Object - - object StaticContainer { - @JSExportStatic - val a: Int = 1 - - @JSExportStatic("a") - def b: Int = 2 - } - """ hasErrors - """ - |newSource1.scala:9: error: Duplicate static export with name 'a': a field may not share its exported name with another field or method - | @JSExportStatic("a") - | ^ - """ - - """ - class StaticContainer extends js.Object - - object StaticContainer { - @JSExportStatic - def a: Int = 1 - - @JSExportStatic("a") - val b: Int = 2 - } - """ hasErrors - """ - |newSource1.scala:6: error: Duplicate static export with name 'a': a field may not share its exported name with another field or method - | @JSExportStatic - | ^ - """ - } - - @Test - def noExportStaticPropertiesAndMethodsWithSameName: Unit = { - """ - class StaticContainer extends js.Object - - object StaticContainer { - @JSExportStatic - def a: Int = 1 - - @JSExportStatic("a") - def b(x: Int): Int = x + 1 - } - """ hasErrors - """ - |newSource1.scala:7: error: Exported property a conflicts with b - | def a: Int = 1 - | ^ - """ - - """ - class StaticContainer extends js.Object - - object StaticContainer { - @JSExportStatic - def a(x: Int): Int = x + 1 - - @JSExportStatic("a") - def b: Int = 1 - } - """ hasErrors - """ - |newSource1.scala:7: error: Exported method a conflicts with b - | def a(x: Int): Int = x + 1 - | ^ - """ - } - - @Test - def noExportStaticNonStatic: Unit = { - """ - class A { - class StaticContainer extends js.Object - - object StaticContainer { - @JSExportStatic - def a(): Unit = () - } - } - """ hasErrors - """ - |newSource1.scala:7: error: Only a static object whose companion class is a Scala.js-defined JS class may export its members as static. - | @JSExportStatic - | ^ - """ - } - - @Test - def noExportStaticInJSModule: Unit = { - """ - class StaticContainer extends js.Object - - object StaticContainer extends js.Object { - @JSExportStatic - def a(): Unit = () - } - """ hasErrors - """ - |newSource1.scala:6: error: You may not export a method of a subclass of js.Any - | @JSExportStatic - | ^ - """ - - """ - class StaticContainer extends js.Object - - @js.native - @JSGlobal("Dummy") - object StaticContainer extends js.Object { - @JSExportStatic - def a(): Unit = js.native - } - """ hasErrors - """ - |newSource1.scala:8: error: You may not export a method of a subclass of js.Any - | @JSExportStatic - | ^ - """ - } - - @Test - def noExportStaticIfWrongCompanionType: Unit = { - """ - class StaticContainer - - object StaticContainer { - @JSExportStatic - def a(): Unit = () - } - """ hasErrors - """ - |newSource1.scala:6: error: Only a static object whose companion class is a Scala.js-defined JS class may export its members as static. - | @JSExportStatic - | ^ - """ - - """ - trait StaticContainer extends js.Object - - object StaticContainer { - @JSExportStatic - def a(): Unit = () - } - """ hasErrors - """ - |newSource1.scala:6: error: Only a static object whose companion class is a Scala.js-defined JS class may export its members as static. - | @JSExportStatic - | ^ - """ - - """ - @js.native - @JSGlobal("Dummy") - class StaticContainer extends js.Object - - object StaticContainer { - @JSExportStatic - def a(): Unit = () - } - """ hasErrors - """ - |newSource1.scala:8: error: Only a static object whose companion class is a Scala.js-defined JS class may export its members as static. - | @JSExportStatic - | ^ - """ - } - - @Test - def noExportStaticFieldAfterStatOrNonStaticField: Unit = { - for { - offendingDecl <- Seq( - "val a: Int = 1", - "var a: Int = 1", - """println("foo")""" - ) - } - s""" - class StaticContainer extends js.Object - - object StaticContainer { - $offendingDecl - - @JSExportStatic - val b: Int = 1 - - @JSExportStatic - var c: Int = 1 - - @JSExportStatic - def d: Int = 1 - - @JSExportStatic - def d_=(v: Int): Unit = () - - @JSExportStatic - def e(): Int = 1 - } - """ hasErrors - """ - |newSource1.scala:9: error: @JSExportStatic vals and vars must be defined before any other val/var, and before any constructor statement. - | val b: Int = 1 - | ^ - |newSource1.scala:12: error: @JSExportStatic vals and vars must be defined before any other val/var, and before any constructor statement. - | var c: Int = 1 - | ^ - """ - - for { - validDecl <- Seq( - "@JSExportStatic val a: Int = 1", - "@JSExportStatic var a: Int = 1", - "lazy val a: Int = 1", - "def a: Int = 1", - "def a_=(v: Int): Unit = ()", - "def a(): Int = 1", - "@JSExportStatic def a: Int = 1", - "@JSExportStatic def a_=(v: Int): Unit = ()", - "@JSExportStatic def a(): Int = 1", - "class A", - "object A", - "trait A", - "type A = Int" - ) - } - s""" - class StaticContainer extends js.Object - - object StaticContainer { - $validDecl - - @JSExportStatic - val b: Int = 1 - - @JSExportStatic - var c: Int = 1 - } - """.succeeds - } - - @Test - def noWarnJSExportTopLevelNamespacedWhenSuppressed: Unit = { - """ - @JSExportTopLevel("namespaced.export1") - object A - @JSExportTopLevel("namespaced.export2") - class B - object C { - @JSExportTopLevel("namespaced.export3") - val a: Int = 1 - @JSExportTopLevel("namespaced.export4") - var b: Int = 1 - @JSExportTopLevel("namespaced.export5") - def c(): Int = 1 - } - """.hasNoWarns - } -} diff --git a/compiler/src/test/scala/org/scalajs/core/compiler/test/JSInteropTest.scala b/compiler/src/test/scala/org/scalajs/core/compiler/test/JSInteropTest.scala deleted file mode 100644 index 1273249155..0000000000 --- a/compiler/src/test/scala/org/scalajs/core/compiler/test/JSInteropTest.scala +++ /dev/null @@ -1,3036 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler.test - -import org.scalajs.core.compiler.test.util._ - -import org.junit.Test -import org.junit.Ignore - -// scalastyle:off line.size.limit - -class JSInteropTest extends DirectTest with TestHelpers { - - override def preamble: String = - """ - import scala.scalajs.js - import scala.scalajs.js.annotation._ - """ - - private val JSNativeLoadSpecAnnots = Seq( - "JSName" -> "@JSName(\"foo\")", - "JSGlobal" -> "@JSGlobal", - "JSGlobal" -> "@JSGlobal(\"foo\")", - "JSImport" -> "@JSImport(\"foo\", \"bar\")", - "JSImport" -> "@JSImport(\"foo\", \"bar\", globalFallback = \"baz\")", - "JSGlobalScope" -> "@JSGlobalScope" - ) - - private def ifHasNewRefChecks(msg: String): String = { - val version = scala.util.Properties.versionNumberString - if (version.startsWith("2.10.") || - version.startsWith("2.11.") || - version.startsWith("2.12.")) { - "" - } else { - msg.stripMargin.trim() - } - } - - @Test - def warnJSPackageObjectDeprecated: Unit = { - - s""" - package object jspackage extends js.Object - """ containsWarns - s""" - |newSource1.scala:5: warning: Package objects inheriting from js.Any are deprecated. Use a normal object instead. - | package object jspackage extends js.Object - | ^ - """ - - } - - @Test - def noJSNativeAnnotWithSJSDefinedAnnot: Unit = { - - for { - obj <- Seq("class", "trait", "object") - } yield { - s""" - @ScalaJSDefined - @js.native - $obj A extends js.Object - """ hasErrors - s""" - |newSource1.scala:5: warning: @ScalaJSDefined is deprecated: add `-P:scalajs:sjsDefinedByDefault` to your scalac options and simply remove `@ScalaJSDefined` - | @ScalaJSDefined - | ^ - |newSource1.scala:7: error: @ScalaJSDefined and @js.native cannot be used together - | $obj A extends js.Object - | ${" " * obj.length} ^ - """ - } - - } - - @Test - def noJSNameAnnotOnNonJSNative: Unit = { - - for { - obj <- Seq("class", "trait", "object") - } yield { - s""" - @JSName("foo") - $obj A extends js.Object - - object Sym { - val sym = js.Symbol() - } - - @JSName(Sym.sym) - $obj B extends js.Object - """ hasWarns - s""" - |newSource1.scala:5: warning: Non JS-native classes, traits and objects should not have an @JSName annotation, as it does not have any effect. This will be enforced in 1.0. - | @JSName("foo") - | ^ - |newSource1.scala:12: warning: Non JS-native classes, traits and objects should not have an @JSName annotation, as it does not have any effect. This will be enforced in 1.0. - | @JSName(Sym.sym) - | ^ - """ - } - - for { - obj <- Seq("class", "trait", "object") - } yield { - s""" - @JSName("foo") - $obj A - - object Sym { - val sym = js.Symbol() - } - - @JSName(Sym.sym) - $obj B - """ hasWarns - s""" - |newSource1.scala:5: warning: Non JS-native classes, traits and objects should not have an @JSName annotation, as it does not have any effect. This will be enforced in 1.0. - | @JSName("foo") - | ^ - |newSource1.scala:12: warning: Non JS-native classes, traits and objects should not have an @JSName annotation, as it does not have any effect. This will be enforced in 1.0. - | @JSName(Sym.sym) - | ^ - """ - } - - } - - @Test - def okJSNameOnNestedObjects: Unit = { - - """ - class A extends js.Object { - @JSName("foo") - object toto - - @JSName("bar") - object tata extends js.Object - } - """.hasNoWarns - - """ - class A extends js.Object { - @JSName("foo") - private object toto - - @JSName("bar") - private object tata extends js.Object - } - """ hasWarns - """ - |newSource1.scala:6: warning: Non JS-native classes, traits and objects should not have an @JSName annotation, as it does not have any effect. This will be enforced in 1.0. - | @JSName("foo") - | ^ - |newSource1.scala:9: warning: Non JS-native classes, traits and objects should not have an @JSName annotation, as it does not have any effect. This will be enforced in 1.0. - | @JSName("bar") - | ^ - """ - - } - - @Test - def noJSGlobalAnnotOnNonJSNative: Unit = { - - for { - obj <- Seq("class", "trait", "object") - } yield { - s""" - @JSGlobal - $obj A extends js.Object - - @JSGlobal("Foo") - $obj B extends js.Object - """ hasErrors - s""" - |newSource1.scala:5: error: Non JS-native classes, traits and objects may not have an @JSGlobal annotation. - | @JSGlobal - | ^ - |newSource1.scala:8: error: Non JS-native classes, traits and objects may not have an @JSGlobal annotation. - | @JSGlobal("Foo") - | ^ - """ - } - - for { - obj <- Seq("class", "trait", "object") - } yield { - s""" - @JSGlobal - $obj A - - @JSGlobal("Foo") - $obj B - """ hasErrors - s""" - |newSource1.scala:5: error: Non JS-native classes, traits and objects may not have an @JSGlobal annotation. - | @JSGlobal - | ^ - |newSource1.scala:8: error: Non JS-native classes, traits and objects may not have an @JSGlobal annotation. - | @JSGlobal("Foo") - | ^ - """ - } - - } - - @Test - def noJSImportAnnotOnNonJSNative: Unit = { - - for { - obj <- Seq("class", "trait", "object") - } yield { - s""" - @JSImport("foo", JSImport.Namespace) - $obj A extends js.Object - """ hasErrors - s""" - |newSource1.scala:5: error: Non JS-native classes, traits and objects may not have an @JSImport annotation. - | @JSImport("foo", JSImport.Namespace) - | ^ - """ - } - - for { - obj <- Seq("class", "trait", "object") - } yield { - s""" - @JSImport("foo", JSImport.Namespace) - $obj A - """ hasErrors - s""" - |newSource1.scala:5: error: Non JS-native classes, traits and objects may not have an @JSImport annotation. - | @JSImport("foo", JSImport.Namespace) - | ^ - """ - } - - for { - obj <- Seq("class", "trait", "object") - } yield { - s""" - @JSImport("foo", JSImport.Namespace, globalFallback = "Foo") - $obj A extends js.Object - """ hasErrors - s""" - |newSource1.scala:5: error: Non JS-native classes, traits and objects may not have an @JSImport annotation. - | @JSImport("foo", JSImport.Namespace, globalFallback = "Foo") - | ^ - """ - } - - for { - obj <- Seq("class", "trait", "object") - } yield { - s""" - @JSImport("foo", JSImport.Namespace, globalFallback = "Foo") - $obj A - """ hasErrors - s""" - |newSource1.scala:5: error: Non JS-native classes, traits and objects may not have an @JSImport annotation. - | @JSImport("foo", JSImport.Namespace, globalFallback = "Foo") - | ^ - """ - } - - } - - @Test - def noJSNameAnnotOnTrait: Unit = { - - s""" - @js.native - @JSName("foo") - trait A extends js.Object - - object Sym { - val sym = js.Symbol() - } - - @js.native - @JSName(Sym.sym) - trait B extends js.Object - """ hasWarns - s""" - |newSource1.scala:6: warning: Traits should not have an @JSName annotation, as it does not have any effect. This will be enforced in 1.0. - | @JSName("foo") - | ^ - |newSource1.scala:14: warning: Traits should not have an @JSName annotation, as it does not have any effect. This will be enforced in 1.0. - | @JSName(Sym.sym) - | ^ - """ - - } - - @Test - def noJSGlobalAnnotOnTrait: Unit = { - - s""" - @js.native - @JSGlobal - trait A extends js.Object - """ hasErrors - s""" - |newSource1.scala:6: error: Traits may not have an @JSGlobal annotation. - | @JSGlobal - | ^ - """ - - s""" - @js.native - @JSGlobal("Foo") - trait A extends js.Object - """ hasErrors - s""" - |newSource1.scala:6: error: Traits may not have an @JSGlobal annotation. - | @JSGlobal("Foo") - | ^ - """ - - } - - @Test - def noJSImportAnnotOnTrait: Unit = { - - s""" - @js.native - @JSImport("foo", JSImport.Namespace) - trait A extends js.Object - """ hasErrors - s""" - |newSource1.scala:6: error: Traits may not have an @JSImport annotation. - | @JSImport("foo", JSImport.Namespace) - | ^ - """ - - s""" - @js.native - @JSImport("foo", JSImport.Namespace, globalFallback = "Foo") - trait A extends js.Object - """ hasErrors - s""" - |newSource1.scala:6: error: Traits may not have an @JSImport annotation. - | @JSImport("foo", JSImport.Namespace, globalFallback = "Foo") - | ^ - """ - - } - - @Test def noTwoJSNativeLoadSpecAnnots: Unit = { - for { - (firstAnnotName, firstAnnot) <- JSNativeLoadSpecAnnots - (secondAnnotName, secondAnnot) <- JSNativeLoadSpecAnnots - } { - val expectedMessageShort = { - if (firstAnnotName == "JSName" && secondAnnotName == firstAnnotName) - "warning: A duplicate @JSName annotation is ignored, and should be removed. This will be enforced in 1.0." - else if (firstAnnotName == "JSGlobalScope" && secondAnnotName == "JSName") - "warning: An @JSName annotation is ignored in the presence of @JSGlobalScope (or extends js.GlobalScope), and should be removed. This will be enforced in 1.0." - else - "error: Native JS classes and objects can only have one annotation among JSName, JSGlobal, JSImport and JSGlobalScope (extending js.GlobalScope is treated as having @JSGlobalScope)." - } - - val onlyWarn = expectedMessageShort.startsWith("warning: ") - - val expectedMessage = { - s""" - |newSource1.scala:7: $expectedMessageShort - |$secondAnnot - | ^ - """ - } - - val jsNameWarning = if (firstAnnotName == "JSName") { - s""" - |newSource1.scala:6: warning: @JSName on top-level native JS classes and objects (or native JS classes and objects inside Scala objects) is deprecated, and should be replaced by @JSGlobal (with the same meaning). This will be enforced in 1.0. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressMissingJSGlobalDeprecations` to scalac) - |$firstAnnot - | ^ - """.trim - } else { - "" - } - - val fullExpectedMessage = expectedMessage + jsNameWarning - - val kinds = { - if (firstAnnotName == "JSGlobalScope" || secondAnnotName == "JSGlobalScope") - Seq("object") - else - Seq("class", "object") - } - - for (kind <- kinds) { - val snippet = { - s""" - |@js.native - |$firstAnnot - |$secondAnnot - |$kind A extends js.Object - """.stripMargin - } - - if (onlyWarn) - snippet hasWarns fullExpectedMessage - else - snippet hasErrors fullExpectedMessage - } - } - } - - @Test - def noJSNativeAnnotWithoutJSAny: Unit = { - - """ - @js.native - class A - """ hasErrors - """ - |newSource1.scala:6: error: Classes, traits and objects not extending js.Any may not have an @js.native annotation - | class A - | ^ - """ - - """ - @js.native - trait A - """ hasErrors - """ - |newSource1.scala:6: error: Classes, traits and objects not extending js.Any may not have an @js.native annotation - | trait A - | ^ - """ - - """ - @js.native - object A - """ hasErrors - """ - |newSource1.scala:6: error: Classes, traits and objects not extending js.Any may not have an @js.native annotation - | object A - | ^ - """ - - """ - @js.native - class A extends Enumeration - """ hasErrors - """ - |newSource1.scala:6: error: Classes, traits and objects not extending js.Any may not have an @js.native annotation - | class A extends Enumeration - | ^ - """ - - """ - @js.native - object A extends Enumeration - """ hasErrors - """ - |newSource1.scala:6: error: Classes, traits and objects not extending js.Any may not have an @js.native annotation - | object A extends Enumeration - | ^ - """ - - } - - @Test - def noInnerClassTraitObject: Unit = { - - for { - outer <- Seq("class", "trait") - inner <- Seq("class", "trait", "object") - innerSJSDefined <- Seq(false, true) - } yield { - val jsGlobalAnnot = - if (outer == "trait") "" - else "@JSGlobal" - val innerLine = - if (innerSJSDefined) s"$inner A extends js.Object" - else s"@js.native $inner A" - s""" - @js.native $jsGlobalAnnot - $outer A extends js.Object { - $innerLine - } - """ hasErrors - s""" - |newSource1.scala:7: error: Native JS traits and classes may not have inner traits, classes or objects - | $innerLine - | ${" " * innerLine.indexOf('A')}^ - """ - } - - } - - @Test - def noScalaStuffInsideNativeJSObject: Unit = { - - for { - inner <- Seq("class", "trait", "object") - } yield { - s""" - @js.native - @JSGlobal - object A extends js.Object { - $inner A - } - """ hasErrors - s""" - |newSource1.scala:8: error: Native JS objects cannot contain inner Scala traits, classes or objects (i.e., not extending js.Any) - | $inner A - | ${" " * inner.length} ^ - """ - } - - } - - @Test - def noNonSyntheticCompanionInsideNativeJSObject: Unit = { - - // See #1891: The default parameter generates a synthetic companion object - // The synthetic companion should be allowed, but it may not be explicit - - """ - @js.native @JSGlobal object A extends js.Object { - @js.native class B(x: Int = ???) extends js.Object - object B - } - """ hasErrors - """ - |newSource1.scala:7: error: Native JS objects cannot contain inner Scala traits, classes or objects (i.e., not extending js.Any) - | object B - | ^ - """ - - """ - @js.native @JSGlobal object A extends js.Object { - @js.native class B(x: Int = ???) extends js.Object - } - """.succeeds - - } - - @Test - def noScalaJSDefinedClassObjectInsideNativeJSObject: Unit = { - - for { - inner <- Seq("class", "object") - } yield { - s""" - @js.native - @JSGlobal - object A extends js.Object { - $inner A extends js.Object - } - """ hasErrors - s""" - |newSource1.scala:8: error: Native JS objects cannot contain inner Scala.js-defined JS classes or objects - | $inner A extends js.Object - | ${" " * inner.length} ^ - """ - } - - } - - @Test - def noBadSetters: Unit = { - - """ - @js.native - @JSGlobal - class A extends js.Object { - def foo_=(x: Int): Int = js.native - def bar_=(x: Int, y: Int): Unit = js.native - def goo_=(x: Int*): Unit = js.native - def hoo_=(x: Int = 1): Unit = js.native - } - """ hasErrors - """ - |newSource1.scala:8: error: Raw JS setters must return Unit - | def foo_=(x: Int): Int = js.native - | ^ - |newSource1.scala:9: error: Raw JS setters must have exactly one argument - | def bar_=(x: Int, y: Int): Unit = js.native - | ^ - |newSource1.scala:10: error: Raw JS setters may not have repeated params - | def goo_=(x: Int*): Unit = js.native - | ^ - |newSource1.scala:11: error: Raw JS setters may not have default params - | def hoo_=(x: Int = 1): Unit = js.native - | ^ - """ - - } - - @Test - def noBadBracketAccess: Unit = { - - """ - @js.native - @JSGlobal - class A extends js.Object { - @js.annotation.JSBracketAccess - def foo(): Int = js.native - - @js.annotation.JSBracketAccess - def bar(x: Int, y: Int, z: Int): Int = js.native - } - """ hasErrors - """ - |newSource1.scala:9: error: @JSBracketAccess methods must have one or two parameters - | def foo(): Int = js.native - | ^ - |newSource1.scala:12: error: @JSBracketAccess methods must have one or two parameters - | def bar(x: Int, y: Int, z: Int): Int = js.native - | ^ - """ - - """ - @js.native - @JSGlobal - class A extends js.Object { - @js.annotation.JSBracketAccess - def foo(x: Int, y: Int): Int = js.native - } - """ hasErrors - """ - |newSource1.scala:9: error: @JSBracketAccess methods with two parameters must return Unit - | def foo(x: Int, y: Int): Int = js.native - | ^ - """ - - """ - @js.native - @JSGlobal - class A extends js.Object { - @js.annotation.JSBracketAccess - def bar(x: Int*): Int = js.native - } - """ hasErrors - """ - |newSource1.scala:9: error: @JSBracketAccess methods may not have repeated parameters - | def bar(x: Int*): Int = js.native - | ^ - """ - - """ - @js.native - @JSGlobal - class A extends js.Object { - @js.annotation.JSBracketAccess - def bar(x: Int = 1): Int = js.native - } - """ hasErrors - """ - |newSource1.scala:9: error: @JSBracketAccess methods may not have default parameters - | def bar(x: Int = 1): Int = js.native - | ^ - """ - - } - - @Test - def noBadBracketCall: Unit = { - - """ - @js.native - @JSGlobal - class A extends js.Object { - @js.annotation.JSBracketCall - def foo(): Int = js.native - } - """ hasErrors - """ - |newSource1.scala:9: error: @JSBracketCall methods must have at least one non-repeated parameter - | def foo(): Int = js.native - | ^ - """ - - } - - @Test - def onlyJSRawTraits: Unit = { - - """ - trait A - - @js.native - @JSGlobal - class B extends js.Object with A - """ hasErrors - """ - |newSource1.scala:9: error: B extends A which does not extend js.Any. - | class B extends js.Object with A - | ^ - """ - - """ - @js.native - @JSGlobal - class B extends js.Object with java.io.Serializable - """ hasErrors - """ - |newSource1.scala:7: error: B extends java.io.Serializable which does not extend js.Any. - | class B extends js.Object with java.io.Serializable - | ^ - """ - - } - - @Test - def noCaseClassObject: Unit = { - - """ - @js.native - @JSGlobal - case class A(x: Int) extends js.Object - """ hasErrors - """ - |newSource1.scala:7: error: Classes and objects extending js.Any may not have a case modifier - | case class A(x: Int) extends js.Object - | ^ - """ - - """ - @js.native - @JSGlobal - case object B extends js.Object - """ hasErrors - """ - |newSource1.scala:7: error: Classes and objects extending js.Any may not have a case modifier - | case object B extends js.Object - | ^ - """ - - """ - case class A(x: Int) extends js.Object - """ hasErrors - """ - |newSource1.scala:5: error: Classes and objects extending js.Any may not have a case modifier - | case class A(x: Int) extends js.Object - | ^ - """ - - """ - case object B extends js.Object - """ hasErrors - """ - |newSource1.scala:5: error: Classes and objects extending js.Any may not have a case modifier - | case object B extends js.Object - | ^ - """ - - } - - @Test - def notNested: Unit = { - - val outers = List("class", "trait") - val inners = List("trait", "class", "object") - - for { - outer <- outers - inner <- inners - outerSJSDefined <- Seq(false, true) - } yield { - val outerLine = - if (outerSJSDefined) s"$outer A extends js.Object" - else s"$outer A" - - val jsGlobalAnnot = - if (inner == "trait") "" - else "@JSGlobal" - - val errTrg = if (inner == "object") "objects" else "classes" - - s""" - $outerLine { - @js.native $jsGlobalAnnot - $inner Inner extends js.Object - } - """ hasErrors - s""" - |newSource1.scala:7: error: Traits and classes may not have inner native JS traits, classes or objects - | $inner Inner extends js.Object - | ${" " * inner.length}^ - """ - } - - } - - @Test - def noGlobalScopeClass: Unit = { - - """ - @js.native - class A extends js.GlobalScope - """ hasErrors - """ - |newSource1.scala:6: error: Only native JS objects can have an @JSGlobalScope annotation (or extend js.GlobalScope). - | class A extends js.GlobalScope - | ^ - """ - - """ - @js.native - trait A extends js.GlobalScope - """ hasErrors - """ - |newSource1.scala:6: error: Traits may not have an @JSGlobalScope annotation. - | trait A extends js.GlobalScope - | ^ - """ - - """ - class A extends js.Object with js.GlobalScope - """ hasErrors - """ - |newSource1.scala:5: error: A Scala.js-defined JS class cannot directly extend a native JS trait. - | class A extends js.Object with js.GlobalScope - | ^ - """ - - """ - trait A extends js.Object with js.GlobalScope - """ hasErrors - """ - |newSource1.scala:5: error: A Scala.js-defined JS trait cannot directly extend a native JS trait. - | trait A extends js.Object with js.GlobalScope - | ^ - """ - - """ - object A extends js.Object with js.GlobalScope - """ hasErrors - """ - |newSource1.scala:5: error: A Scala.js-defined JS object cannot directly extend a native JS trait. - | object A extends js.Object with js.GlobalScope - | ^ - """ - - } - - @Test - def noJSNameOnJSGlobalScope: Unit = { - // #2320 - """ - @js.native - @JSName("foo") - object Bar extends js.GlobalScope - """ containsWarns - """ - |newSource1.scala:6: warning: An @JSName annotation is ignored in the presence of @JSGlobalScope (or extends js.GlobalScope), and should be removed. This will be enforced in 1.0. - | @JSName("foo") - | ^ - """ - - } - - @Test - def noJSGlobalOnJSGlobalScope: Unit = { - - """ - @js.native - @JSGlobal - object Bar extends js.GlobalScope - """ hasErrors - """ - |newSource1.scala:6: error: Native JS classes and objects can only have one annotation among JSName, JSGlobal, JSImport and JSGlobalScope (extending js.GlobalScope is treated as having @JSGlobalScope). - | @JSGlobal - | ^ - """ - - } - - @Test - def noJSImportOnJSGlobalScope: Unit = { - - """ - @js.native - @JSImport("foo", JSImport.Namespace) - object Bar extends js.GlobalScope - """ hasErrors - """ - |newSource1.scala:6: error: Native JS classes and objects can only have one annotation among JSName, JSGlobal, JSImport and JSGlobalScope (extending js.GlobalScope is treated as having @JSGlobalScope). - | @JSImport("foo", JSImport.Namespace) - | ^ - """ - - """ - @js.native - @JSImport("foo", JSImport.Namespace, globalFallback = "Foo") - object Bar extends js.GlobalScope - """ hasErrors - """ - |newSource1.scala:6: error: Native JS classes and objects can only have one annotation among JSName, JSGlobal, JSImport and JSGlobalScope (extending js.GlobalScope is treated as having @JSGlobalScope). - | @JSImport("foo", JSImport.Namespace, globalFallback = "Foo") - | ^ - """ - - } - - @Test - def noLocalClass: Unit = { - - """ - object A { - def a = { - @js.native - @JSGlobal - class B extends js.Object - } - } - """ hasErrors - """ - |newSource1.scala:9: error: Local native JS classes and objects are not allowed - | class B extends js.Object - | ^ - """ - - } - - @Test - def noLocalObject: Unit = { - - """ - object A { - def a = { - @js.native - @JSGlobal - object B extends js.Object - } - } - """ hasErrors - """ - |newSource1.scala:9: error: Local native JS classes and objects are not allowed - | object B extends js.Object - | ^ - """ - - } - - @Test - def noNativeInJSAny: Unit = { - - """ - @js.native - @JSGlobal - class A extends js.Object { - @native - def value: Int = js.native - } - """ hasErrors - """ - |newSource1.scala:9: error: Methods in a js.Any may not be @native - | def value: Int = js.native - | ^ - """ - - } - - @Test - def warnJSAnyBody: Unit = { - - """ - @js.native - @JSGlobal - class A extends js.Object { - def value: Int = ??? - val x: Int = ??? - } - """ hasWarns - """ - |newSource1.scala:8: warning: Members of traits, classes and objects extending js.Any may only contain members that call js.native. This will be enforced in 1.0. - | def value: Int = ??? - | ^ - |newSource1.scala:9: warning: Members of traits, classes and objects extending js.Any may only contain members that call js.native. This will be enforced in 1.0. - | val x: Int = ??? - | ^ - """ - - } - - @Test - def noWarnJSAnyDeferred: Unit = { - - """ - @js.native - @JSGlobal - abstract class A extends js.Object { - def value: Int - val x: Int - } - """.hasNoWarns - - """ - @js.native - trait A extends js.Object { - def value: Int - val x: Int - } - """.hasNoWarns - - } - - @Test - def noCallSecondaryCtor: Unit = { - - """ - @js.native - @JSGlobal - class A(x: Int, y: Int) extends js.Object { - def this(x: Int) = this(x, 5) - def this() = this(7) - } - """ hasErrors - """ - |newSource1.scala:9: error: A secondary constructor of a class extending js.Any may only call the primary constructor - | def this() = this(7) - | ^ - """ - - } - - @Test - def warnPrivateMemberInNative: Unit = { - - """ - @js.native - @JSGlobal - class A extends js.Object { - private[this] val a: Int = js.native - private val b: Int = js.native - private[A] val c: Int = js.native - - private[this] var d: Int = js.native - private var e: Int = js.native - private[A] var f: Int = js.native - - private[this] def g(): Int = js.native - private def h(): Int = js.native - private[A] def i(): Int = js.native - } - """ hasWarns - """ - |newSource1.scala:8: warning: Declaring private members in native JS classes is deprecated, because they do not behave the same way as in Scala.js-defined JS classes. Use a public member in a private facade instead. This will become an error in 1.0.0. - | private[this] val a: Int = js.native - | ^ - |newSource1.scala:9: warning: Declaring private members in native JS classes is deprecated, because they do not behave the same way as in Scala.js-defined JS classes. Use a public member in a private facade instead. This will become an error in 1.0.0. - | private val b: Int = js.native - | ^ - |newSource1.scala:10: warning: Declaring private members in native JS classes is deprecated, because they do not behave the same way as in Scala.js-defined JS classes. Use a public member in a private facade instead. This will become an error in 1.0.0. - | private[A] val c: Int = js.native - | ^ - |newSource1.scala:12: warning: Declaring private members in native JS classes is deprecated, because they do not behave the same way as in Scala.js-defined JS classes. Use a public member in a private facade instead. This will become an error in 1.0.0. - | private[this] var d: Int = js.native - | ^ - |newSource1.scala:13: warning: Declaring private members in native JS classes is deprecated, because they do not behave the same way as in Scala.js-defined JS classes. Use a public member in a private facade instead. This will become an error in 1.0.0. - | private var e: Int = js.native - | ^ - |newSource1.scala:14: warning: Declaring private members in native JS classes is deprecated, because they do not behave the same way as in Scala.js-defined JS classes. Use a public member in a private facade instead. This will become an error in 1.0.0. - | private[A] var f: Int = js.native - | ^ - |newSource1.scala:16: warning: Declaring private members in native JS classes is deprecated, because they do not behave the same way as in Scala.js-defined JS classes. Use a public member in a private facade instead. This will become an error in 1.0.0. - | private[this] def g(): Int = js.native - | ^ - |newSource1.scala:17: warning: Declaring private members in native JS classes is deprecated, because they do not behave the same way as in Scala.js-defined JS classes. Use a public member in a private facade instead. This will become an error in 1.0.0. - | private def h(): Int = js.native - | ^ - |newSource1.scala:18: warning: Declaring private members in native JS classes is deprecated, because they do not behave the same way as in Scala.js-defined JS classes. Use a public member in a private facade instead. This will become an error in 1.0.0. - | private[A] def i(): Int = js.native - | ^ - """ - - } - - @Test - def warnPrivateConstructorInNative: Unit = { - - """ - @js.native - @JSGlobal - class A private () extends js.Object - """ containsWarns - """ - |newSource1.scala:7: warning: Declaring private constructors in native JS classes is deprecated, because they do not behave the same way as in Scala.js-defined JS classes. Use `private[this]` instead. This will become an error in 1.0.0. - | class A private () extends js.Object - """ - - """ - @js.native - @JSGlobal - class A private[A] () extends js.Object - """ containsWarns - """ - |newSource1.scala:7: warning: Declaring private constructors in native JS classes is deprecated, because they do not behave the same way as in Scala.js-defined JS classes. Use `private[this]` instead. This will become an error in 1.0.0. - | class A private[A] () extends js.Object - """ - - """ - @js.native - @JSGlobal - class A private[this] () extends js.Object - """.hasNoWarns - - } - - @Test - def noUseJsNative: Unit = { - - """ - class A { - def foo = js.native - } - """ hasErrors - """ - |newSource1.scala:6: error: js.native may only be used as stub implementation in facade types - | def foo = js.native - | ^ - """ - - } - - @Test - def warnNothingRaw: Unit = { - - """ - @js.native - @JSGlobal - class A extends js.Object { - def foo = js.native - val bar = js.native - } - """ hasWarns - """ - |newSource1.scala:8: warning: The type of foo got inferred as Nothing. To suppress this warning, explicitly ascribe the type. - | def foo = js.native - | ^ - |newSource1.scala:9: warning: The type of bar got inferred as Nothing. To suppress this warning, explicitly ascribe the type. - | val bar = js.native - | ^ - """ - - } - - @Test - def noNativeClassObjectWithoutExplicitNameInsideScalaObject: Unit = { - - """ - object A { - @js.native - class B extends js.Object - } - """ hasWarns - """ - |newSource1.scala:7: warning: Native JS classes inside non-native objects should have an @JSGlobal or @JSImport annotation. This will be enforced in 1.0. - | class B extends js.Object - | ^ - """ - - """ - object A { - @js.native - object B extends js.Object - } - """ hasErrors - """ - |newSource1.scala:7: error: Native JS objects inside non-native objects must have an @JSGlobal or @JSImport annotation - | object B extends js.Object - | ^ - """ - - """ - object A { - @js.native - @JSGlobal - class B extends js.Object - } - """ hasErrors - """ - |newSource1.scala:7: error: Native JS classes and objects inside non-native objects must have an explicit name in @JSGlobal - | @JSGlobal - | ^ - """ - - """ - object A { - @js.native - @JSGlobal - object B extends js.Object - } - """ hasErrors - """ - |newSource1.scala:7: error: Native JS classes and objects inside non-native objects must have an explicit name in @JSGlobal - | @JSGlobal - | ^ - """ - - // From issue #2401 - """ - package object A { - @js.native - object B extends js.Object - - @js.native - @JSGlobal - object C extends js.Object - } - """ hasWarns - """ - |newSource1.scala:7: warning: Top-level native JS classes and objects should have an @JSGlobal or @JSImport annotation. This will be enforced in 1.0. - | If migrating from 0.6.14 or earlier, the equivalent behavior is an @JSGlobal without parameter. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressMissingJSGlobalDeprecations` to scalac) - | object B extends js.Object - | ^ - """ - - """ - package object A { - @js.native - class B extends js.Object - - @js.native - @JSGlobal - class C extends js.Object - } - """ hasWarns - """ - |newSource1.scala:7: warning: Top-level native JS classes and objects should have an @JSGlobal or @JSImport annotation. This will be enforced in 1.0. - | If migrating from 0.6.14 or earlier, the equivalent behavior is an @JSGlobal without parameter. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressMissingJSGlobalDeprecations` to scalac) - | class B extends js.Object - | ^ - """ - - """ - object A { - @JSName("InnerB") - @js.native - class B extends js.Object - - @JSName("InnerC") - @js.native - object C extends js.Object - } - """ hasWarns - """ - |newSource1.scala:6: warning: @JSName on top-level native JS classes and objects (or native JS classes and objects inside Scala objects) is deprecated, and should be replaced by @JSGlobal (with the same meaning). This will be enforced in 1.0. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressMissingJSGlobalDeprecations` to scalac) - | @JSName("InnerB") - | ^ - |newSource1.scala:10: warning: @JSName on top-level native JS classes and objects (or native JS classes and objects inside Scala objects) is deprecated, and should be replaced by @JSGlobal (with the same meaning). This will be enforced in 1.0. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressMissingJSGlobalDeprecations` to scalac) - | @JSName("InnerC") - | ^ - """ - - """ - object A { - @JSGlobal("InnerB") - @js.native - class B extends js.Object - - @JSGlobal("InnerC") - @js.native - object C extends js.Object - } - """.hasNoWarns - - """ - object A { - @JSImport("InnerB", JSImport.Namespace) - @js.native - class B extends js.Object - - @JSImport("InnerC", JSImport.Namespace) - @js.native - object C extends js.Object - } - """.hasNoWarns - - """ - object A { - @JSImport("InnerB", JSImport.Namespace, globalFallback = "Foo") - @js.native - class B extends js.Object - - @JSImport("InnerC", JSImport.Namespace, globalFallback = "Foo") - @js.native - object C extends js.Object - } - """.hasNoWarns - - """ - object A { - @js.native - trait B extends js.Object - } - """.hasNoWarns - - """ - @js.native - @JSGlobal - object A extends js.Object { - @js.native - class B extends js.Object - - @js.native - trait C extends js.Object - - @js.native - object D extends js.Object - } - """.hasNoWarns - - } - - @Test - def nestedJSGlobalScopeWithoutExplicitName: Unit = { - // #2319 - """ - object Outer { - @js.native - object Foo extends js.GlobalScope - } - """.succeeds - - } - - @Test - def noNativeClassObjectInsideScalaJSDefinedObject: Unit = { - - for { - inner <- Seq("class", "object") - } { - s""" - object A extends js.Object { - @js.native - @JSGlobal - $inner B extends js.Object - } - """ hasErrors - s""" - |newSource1.scala:8: error: Scala.js-defined JS objects may not have inner native JS classes or objects - | $inner B extends js.Object - | ${" " * inner.length} ^ - """ - } - - } - - @Test - def noNonLiteralJSName: Unit = { - - """ - import js.annotation.JSName - - object A { - val a = "Hello" - final val b = "World" - } - - @js.native - @JSGlobal - class B extends js.Object { - @JSName(A.a) - def foo: Int = js.native - @JSName(A.b) - def bar: Int = js.native - } - """ hasErrors - """ - |newSource1.scala:15: error: A string argument to JSName must be a literal string - | @JSName(A.a) - | ^ - """ - - // #1664 - """ - import js.annotation.JSName - - object A { - val a = "Hello" - } - - @JSName(A.a) - @js.native - object B extends js.Object - - @JSName(A.a) - @js.native - class C extends js.Object - """ hasErrors - """ - |newSource1.scala:11: error: A string argument to JSName must be a literal string - | @JSName(A.a) - | ^ - |newSource1.scala:11: warning: @JSName on top-level native JS classes and objects (or native JS classes and objects inside Scala objects) is deprecated, and should be replaced by @JSGlobal (with the same meaning). This will be enforced in 1.0. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressMissingJSGlobalDeprecations` to scalac) - | @JSName(A.a) - | ^ - |newSource1.scala:15: error: A string argument to JSName must be a literal string - | @JSName(A.a) - | ^ - |newSource1.scala:15: warning: @JSName on top-level native JS classes and objects (or native JS classes and objects inside Scala objects) is deprecated, and should be replaced by @JSGlobal (with the same meaning). This will be enforced in 1.0. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressMissingJSGlobalDeprecations` to scalac) - | @JSName(A.a) - | ^ - """ - - } - - @Test - def noNonStaticStableJSNameSymbol: Unit = { - - """ - import js.annotation.JSName - - class A { - val a = js.Symbol("foo") - } - - @js.native - @JSGlobal - class B extends js.Object { - @JSName(js.Symbol()) - def foo: Int = js.native - @JSName(new A().a) - def bar: Int = js.native - } - - class C extends js.Object { - @JSName(js.Symbol()) - def foo: Int = js.native - @JSName(new A().a) - def bar: Int = js.native - } - """ hasErrors - """ - |newSource1.scala:14: error: A js.Symbol argument to JSName must be a static, stable identifier - | @JSName(js.Symbol()) - | ^ - |newSource1.scala:16: error: A js.Symbol argument to JSName must be a static, stable identifier - | @JSName(new A().a) - | ^ - |newSource1.scala:21: error: A js.Symbol argument to JSName must be a static, stable identifier - | @JSName(js.Symbol()) - | ^ - |newSource1.scala:23: error: A js.Symbol argument to JSName must be a static, stable identifier - | @JSName(new A().a) - | ^ - """ - - } - - @Test - def noSelfReferenceJSNameSymbol: Unit = { - - """ - object A extends js.Object { - val a = js.Symbol("foo") - - @JSName(a) - def foo: Int = 1 - } - """ hasWarns - """ - |newSource1.scala:8: warning: This symbol is defined in the same object as the annotation's target. This will cause a stackoverflow at runtime - | @JSName(a) - | ^ - """ - - // Native objects are OK, since we do not control definition order. - """ - @js.native - object A extends js.Object { - val a: js.Symbol = js.native - - @JSName(a) - def foo: Int = js.native - } - """.succeeds - - } - - @Test - def noJSGlobalOnMembersOfClassesAndTraits: Unit = { - - for (outer <- Seq("class", "trait")) { - s""" - @js.native ${if (outer == "trait") "" else "@JSGlobal"} - $outer Foo extends js.Object { - @JSGlobal("bar1") - val bar1: Int = js.native - @JSGlobal("bar2") - var bar2: Int = js.native - @JSGlobal("bar3") - def bar3: Int = js.native - - @js.native - @JSGlobal("Inner") - class Inner extends js.Object - - @js.native - @JSGlobal("Inner") - object Inner extends js.Object - - @js.native - @JSGlobal - class InnerImplied extends js.Object - - @js.native - @JSGlobal - object InnerImplied extends js.Object - } - """ hasErrors - """ - |newSource1.scala:8: error: Methods and fields cannot be annotated with @JSGlobal. - | val bar1: Int = js.native - | ^ - |newSource1.scala:10: error: Methods and fields cannot be annotated with @JSGlobal. - | var bar2: Int = js.native - | ^ - |newSource1.scala:12: error: Methods and fields cannot be annotated with @JSGlobal. - | def bar3: Int = js.native - | ^ - |newSource1.scala:16: error: Native JS traits and classes may not have inner traits, classes or objects - | class Inner extends js.Object - | ^ - |newSource1.scala:20: error: Native JS traits and classes may not have inner traits, classes or objects - | object Inner extends js.Object - | ^ - |newSource1.scala:24: error: Native JS traits and classes may not have inner traits, classes or objects - | class InnerImplied extends js.Object - | ^ - |newSource1.scala:28: error: Native JS traits and classes may not have inner traits, classes or objects - | object InnerImplied extends js.Object - | ^ - """ - } - - } - - @Test - def noJSGlobalOnMembersOfObjects: Unit = { - - s""" - @js.native @JSGlobal - object Foo extends js.Object { - @JSGlobal("bar1") - val bar1: Int = js.native - @JSGlobal("bar2") - var bar2: Int = js.native - @JSGlobal("bar3") - def bar3: Int = js.native - - @js.native - @JSGlobal("Inner") - class Inner extends js.Object - - @js.native - @JSGlobal("Inner") - object Inner extends js.Object - - @js.native - @JSGlobal - class InnerImplied extends js.Object - - @js.native - @JSGlobal - object InnerImplied extends js.Object - } - """ hasErrors - """ - |newSource1.scala:8: error: Methods and fields cannot be annotated with @JSGlobal. - | val bar1: Int = js.native - | ^ - |newSource1.scala:10: error: Methods and fields cannot be annotated with @JSGlobal. - | var bar2: Int = js.native - | ^ - |newSource1.scala:12: error: Methods and fields cannot be annotated with @JSGlobal. - | def bar3: Int = js.native - | ^ - |newSource1.scala:15: error: Classes and objects nested in a JS native object cannot have an @JSGlobal annotation. - | @JSGlobal("Inner") - | ^ - |newSource1.scala:19: error: Classes and objects nested in a JS native object cannot have an @JSGlobal annotation. - | @JSGlobal("Inner") - | ^ - |newSource1.scala:23: error: Classes and objects nested in a JS native object cannot have an @JSGlobal annotation. - | @JSGlobal - | ^ - |newSource1.scala:27: error: Classes and objects nested in a JS native object cannot have an @JSGlobal annotation. - | @JSGlobal - | ^ - """ - - } - - @Test - def noJSImportOnMembersOfClassesAndTraits: Unit = { - - for { - outer <- Seq("class", "trait") - fallbackStr <- Seq("", ", globalFallback = \"Foo\"") - } { - s""" - @js.native ${if (outer == "trait") "" else "@JSGlobal"} - $outer Foo extends js.Object { - @JSImport("bar1", JSImport.Namespace$fallbackStr) - val bar1: Int = js.native - @JSImport("bar2", JSImport.Namespace$fallbackStr) - var bar2: Int = js.native - @JSImport("bar3", JSImport.Namespace$fallbackStr) - def bar3: Int = js.native - - @js.native - @JSImport("Inner", JSImport.Namespace$fallbackStr) - class Inner extends js.Object - - @js.native - @JSImport("Inner", JSImport.Namespace$fallbackStr) - object Inner extends js.Object - } - """ hasErrors - """ - |newSource1.scala:8: error: Methods and fields cannot be annotated with @JSImport. - | val bar1: Int = js.native - | ^ - |newSource1.scala:10: error: Methods and fields cannot be annotated with @JSImport. - | var bar2: Int = js.native - | ^ - |newSource1.scala:12: error: Methods and fields cannot be annotated with @JSImport. - | def bar3: Int = js.native - | ^ - |newSource1.scala:16: error: Native JS traits and classes may not have inner traits, classes or objects - | class Inner extends js.Object - | ^ - |newSource1.scala:20: error: Native JS traits and classes may not have inner traits, classes or objects - | object Inner extends js.Object - | ^ - """ - } - - } - - @Test - def noJSImportOnMembersOfObjects: Unit = { - - for { - fallbackStr <- Seq("", ", globalFallback = \"Foo\"") - } { - s""" - @js.native @JSGlobal - object Foo extends js.Object { - @JSImport("bar1", JSImport.Namespace$fallbackStr) - val bar1: Int = js.native - @JSImport("bar2", JSImport.Namespace$fallbackStr) - var bar2: Int = js.native - @JSImport("bar3", JSImport.Namespace$fallbackStr) - def bar3: Int = js.native - - @js.native - @JSImport("Inner", JSImport.Namespace$fallbackStr) - class Inner extends js.Object - - @js.native - @JSImport("Inner", JSImport.Namespace$fallbackStr) - object Inner extends js.Object - } - """ hasErrors - s""" - |newSource1.scala:8: error: Methods and fields cannot be annotated with @JSImport. - | val bar1: Int = js.native - | ^ - |newSource1.scala:10: error: Methods and fields cannot be annotated with @JSImport. - | var bar2: Int = js.native - | ^ - |newSource1.scala:12: error: Methods and fields cannot be annotated with @JSImport. - | def bar3: Int = js.native - | ^ - |newSource1.scala:15: error: Classes and objects nested in a JS native object cannot have an @JSImport annotation. - | @JSImport("Inner", JSImport.Namespace$fallbackStr) - | ^ - |newSource1.scala:19: error: Classes and objects nested in a JS native object cannot have an @JSImport annotation. - | @JSImport("Inner", JSImport.Namespace$fallbackStr) - | ^ - """ - } - - } - - @Test - def noNonLiteralJSGlobal: Unit = { - - """ - object A { - val a = "Hello" - } - - @JSGlobal(A.a) - @js.native - object B extends js.Object - - @JSGlobal(A.a) - @js.native - class C extends js.Object - """ hasErrors - """ - |newSource1.scala:9: error: The argument to @JSGlobal must be a literal string. - | @JSGlobal(A.a) - | ^ - |newSource1.scala:13: error: The argument to @JSGlobal must be a literal string. - | @JSGlobal(A.a) - | ^ - """ - - } - - @Test - def noNonLiteralJSImport: Unit = { - - // Without global fallback - - """ - object A { - val a = "Hello" - } - - @JSImport(A.a, JSImport.Namespace) - @js.native - object B1 extends js.Object - - @JSImport(A.a, "B2") - @js.native - object B2 extends js.Object - - @JSImport("B3", A.a) - @js.native - object B3 extends js.Object - - @JSImport(A.a, JSImport.Namespace) - @js.native - object C1 extends js.Object - - @JSImport(A.a, "C2") - @js.native - object C2 extends js.Object - - @JSImport("C3", A.a) - @js.native - object C3 extends js.Object - - @JSImport(A.a, A.a) - @js.native - object D extends js.Object - """ hasErrors - """ - |newSource1.scala:9: error: The first argument to @JSImport must be a literal string. - | @JSImport(A.a, JSImport.Namespace) - | ^ - |newSource1.scala:13: error: The first argument to @JSImport must be a literal string. - | @JSImport(A.a, "B2") - | ^ - |newSource1.scala:17: error: The second argument to @JSImport must be literal string or the JSImport.Namespace object. - | @JSImport("B3", A.a) - | ^ - |newSource1.scala:21: error: The first argument to @JSImport must be a literal string. - | @JSImport(A.a, JSImport.Namespace) - | ^ - |newSource1.scala:25: error: The first argument to @JSImport must be a literal string. - | @JSImport(A.a, "C2") - | ^ - |newSource1.scala:29: error: The second argument to @JSImport must be literal string or the JSImport.Namespace object. - | @JSImport("C3", A.a) - | ^ - |newSource1.scala:33: error: The first argument to @JSImport must be a literal string. - | @JSImport(A.a, A.a) - | ^ - |newSource1.scala:33: error: The second argument to @JSImport must be literal string or the JSImport.Namespace object. - | @JSImport(A.a, A.a) - | ^ - """ - - // With constant (valid) global fallback - - """ - object A { - val a = "Hello" - } - - @JSImport(A.a, JSImport.Namespace, globalFallback = "GlobB1") - @js.native - object B1 extends js.Object - - @JSImport(A.a, "B2", globalFallback = "GlobB2") - @js.native - object B2 extends js.Object - - @JSImport("B3", A.a, globalFallback = "GlobB3") - @js.native - object B3 extends js.Object - - @JSImport(A.a, JSImport.Namespace, globalFallback = "GlobC1") - @js.native - object C1 extends js.Object - - @JSImport(A.a, "C2", globalFallback = "GlobC2") - @js.native - object C2 extends js.Object - - @JSImport("C3", A.a, globalFallback = "GlobC3") - @js.native - object C3 extends js.Object - - @JSImport(A.a, A.a, globalFallback = "GlobD") - @js.native - object D extends js.Object - """ hasErrors - """ - |newSource1.scala:9: error: The first argument to @JSImport must be a literal string. - | @JSImport(A.a, JSImport.Namespace, globalFallback = "GlobB1") - | ^ - |newSource1.scala:13: error: The first argument to @JSImport must be a literal string. - | @JSImport(A.a, "B2", globalFallback = "GlobB2") - | ^ - |newSource1.scala:17: error: The second argument to @JSImport must be literal string or the JSImport.Namespace object. - | @JSImport("B3", A.a, globalFallback = "GlobB3") - | ^ - |newSource1.scala:21: error: The first argument to @JSImport must be a literal string. - | @JSImport(A.a, JSImport.Namespace, globalFallback = "GlobC1") - | ^ - |newSource1.scala:25: error: The first argument to @JSImport must be a literal string. - | @JSImport(A.a, "C2", globalFallback = "GlobC2") - | ^ - |newSource1.scala:29: error: The second argument to @JSImport must be literal string or the JSImport.Namespace object. - | @JSImport("C3", A.a, globalFallback = "GlobC3") - | ^ - |newSource1.scala:33: error: The first argument to @JSImport must be a literal string. - | @JSImport(A.a, A.a, globalFallback = "GlobD") - | ^ - |newSource1.scala:33: error: The second argument to @JSImport must be literal string or the JSImport.Namespace object. - | @JSImport(A.a, A.a, globalFallback = "GlobD") - | ^ - """ - - // With variable (invalid) global fallback - - """ - object A { - val a = "Hello" - } - - @JSImport(A.a, JSImport.Namespace, globalFallback = A.a) - @js.native - object B1 extends js.Object - - @JSImport(A.a, "B2", globalFallback = A.a) - @js.native - object B2 extends js.Object - - @JSImport("B3", A.a, globalFallback = A.a) - @js.native - object B3 extends js.Object - - @JSImport(A.a, JSImport.Namespace, globalFallback = A.a) - @js.native - object C1 extends js.Object - - @JSImport(A.a, "C2", globalFallback = A.a) - @js.native - object C2 extends js.Object - - @JSImport("C3", A.a, globalFallback = A.a) - @js.native - object C3 extends js.Object - - @JSImport(A.a, A.a, globalFallback = A.a) - @js.native - object D extends js.Object - """ hasErrors - """ - |newSource1.scala:9: error: The first argument to @JSImport must be a literal string. - | @JSImport(A.a, JSImport.Namespace, globalFallback = A.a) - | ^ - |newSource1.scala:9: error: The third argument to @JSImport, when present, must be a literal string. - | @JSImport(A.a, JSImport.Namespace, globalFallback = A.a) - | ^ - |newSource1.scala:13: error: The first argument to @JSImport must be a literal string. - | @JSImport(A.a, "B2", globalFallback = A.a) - | ^ - |newSource1.scala:13: error: The third argument to @JSImport, when present, must be a literal string. - | @JSImport(A.a, "B2", globalFallback = A.a) - | ^ - |newSource1.scala:17: error: The second argument to @JSImport must be literal string or the JSImport.Namespace object. - | @JSImport("B3", A.a, globalFallback = A.a) - | ^ - |newSource1.scala:17: error: The third argument to @JSImport, when present, must be a literal string. - | @JSImport("B3", A.a, globalFallback = A.a) - | ^ - |newSource1.scala:21: error: The first argument to @JSImport must be a literal string. - | @JSImport(A.a, JSImport.Namespace, globalFallback = A.a) - | ^ - |newSource1.scala:21: error: The third argument to @JSImport, when present, must be a literal string. - | @JSImport(A.a, JSImport.Namespace, globalFallback = A.a) - | ^ - |newSource1.scala:25: error: The first argument to @JSImport must be a literal string. - | @JSImport(A.a, "C2", globalFallback = A.a) - | ^ - |newSource1.scala:25: error: The third argument to @JSImport, when present, must be a literal string. - | @JSImport(A.a, "C2", globalFallback = A.a) - | ^ - |newSource1.scala:29: error: The second argument to @JSImport must be literal string or the JSImport.Namespace object. - | @JSImport("C3", A.a, globalFallback = A.a) - | ^ - |newSource1.scala:29: error: The third argument to @JSImport, when present, must be a literal string. - | @JSImport("C3", A.a, globalFallback = A.a) - | ^ - |newSource1.scala:33: error: The first argument to @JSImport must be a literal string. - | @JSImport(A.a, A.a, globalFallback = A.a) - | ^ - |newSource1.scala:33: error: The second argument to @JSImport must be literal string or the JSImport.Namespace object. - | @JSImport(A.a, A.a, globalFallback = A.a) - | ^ - |newSource1.scala:33: error: The third argument to @JSImport, when present, must be a literal string. - | @JSImport(A.a, A.a, globalFallback = A.a) - | ^ - """ - - } - - @Test - def noApplyProperty: Unit = { - - // def apply - - """ - @js.native - trait A extends js.Object { - def apply: Int = js.native - } - """ hasErrors - """ - |newSource1.scala:7: error: A member named apply represents function application in JavaScript. A parameterless member should be exported as a property. You must add @JSName("apply") - | def apply: Int = js.native - | ^ - """ - - """ - import js.annotation.JSName - - @js.native - trait A extends js.Object { - @JSName("apply") - def apply: Int = js.native - } - """.succeeds - - // val apply - - """ - @js.native - trait A extends js.Object { - val apply: Int = js.native - } - """ hasErrors - """ - |newSource1.scala:7: error: A member named apply represents function application in JavaScript. A parameterless member should be exported as a property. You must add @JSName("apply") - | val apply: Int = js.native - | ^ - """ - - """ - import js.annotation.JSName - - @js.native - trait A extends js.Object { - @JSName("apply") - val apply: Int = js.native - } - """.succeeds - - // var apply - - """ - @js.native - trait A extends js.Object { - var apply: Int = js.native - } - """ hasErrors - """ - |newSource1.scala:7: error: A member named apply represents function application in JavaScript. A parameterless member should be exported as a property. You must add @JSName("apply") - | var apply: Int = js.native - | ^ - """ - - """ - import js.annotation.JSName - - @js.native - trait A extends js.Object { - @JSName("apply") - var apply: Int = js.native - } - """.succeeds - - } - - @Test - def noJSSymbolNameOnTopLevelClassesAndObjects: Unit = { - for { - kind <- Seq("class", "object") - } { - s""" - object Sym { - val sym = js.Symbol() - } - - @JSName(Sym.sym) - @js.native - $kind A extends js.Object - """ hasErrors - s""" - |newSource1.scala:9: error: @JSName with a js.Symbol can only be used on members of JavaScript types - | @JSName(Sym.sym) - | ^ - |newSource1.scala:11: warning: Top-level native JS classes and objects should have an @JSGlobal or @JSImport annotation. This will be enforced in 1.0. - | If migrating from 0.6.14 or earlier, the equivalent behavior is an @JSGlobal without parameter. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressMissingJSGlobalDeprecations` to scalac) - | $kind A extends js.Object - | ${" " * kind.length} ^ - """ - } - } - - @Test - def noJSSymbolNameOnNestedNativeClassesAndObjects: Unit = { - for { - kind <- Seq("class", "object") - } { - s""" - object Sym { - val sym = js.Symbol() - } - - @js.native - @JSGlobal - object Enclosing extends js.Object { - @JSName(Sym.sym) - @js.native - $kind A extends js.Object - } - """ hasErrors - """ - |newSource1.scala:12: error: Implementation restriction: @JSName with a js.Symbol is not supported on nested native classes and objects - | @JSName(Sym.sym) - | ^ - """ - } - } - - @Test - def warnOnDuplicateJSNameAnnotOnMember: Unit = { - for { - kind <- Seq("class", "object", "trait") - } { - """ - object A { - val a = js.Symbol() - } - - @js.native - @JSGlobal - class A extends js.Object { - @JSName(A.a) - @JSName("foo") - def a: Int = js.native - } - """ hasWarns - """ - |newSource1.scala:13: warning: A duplicate @JSName annotation is ignored. This will become an error in 1.0.0. - | @JSName("foo") - | ^ - """ - } - } - - @Test - def scalaJSDefinedJSNameOverrideWarnings: Unit = { - """ - abstract class A extends js.Object { - def bar(): Int - } - class B extends A { - override def bar() = 1 - } - """.hasNoWarns - - """ - trait A extends js.Object { - @JSName("foo") - def bar(): Int - } - class B extends A { - @JSName("foo") - override def bar() = 1 - } - """.hasNoWarns - - """ - abstract class A extends js.Object { - @JSName("foo") - def bar(): Int - } - class B extends A { - @JSName("foo") - override def bar() = 1 - } - """.hasNoWarns - - """ - abstract class A extends js.Object { - @JSName("foo") - def bar(): Int - } - class B extends A { - @JSName("baz") - override def bar() = 1 - } - """ hasWarns - """ - |newSource1.scala:11: warning: A member of a JS class is overriding another member with a different JS name. - | - |override def bar(): Int in class B with JSName 'baz' - | is conflicting with - |def bar(): Int in class A with JSName 'foo' - | - | override def bar() = 1 - | ^ - """ - - """ - abstract class A extends js.Object { - @JSName("foo") - def bar(): Int - } - class B extends A { - override def bar() = 1 - } - """ hasWarns - """ - |newSource1.scala:10: warning: A member of a JS class is overriding another member with a different JS name. - | - |override def bar(): Int in class B with JSName 'bar' - | is conflicting with - |def bar(): Int in class A with JSName 'foo' - | - | override def bar() = 1 - | ^ - """ - - """ - abstract class A extends js.Object { - @JSName("foo") - def bar(): Object - } - abstract class B extends A { - override def bar(): String - } - class C extends B { - override def bar() = "1" - } - """ hasWarns - """ - |newSource1.scala:10: warning: A member of a JS class is overriding another member with a different JS name. - | - |override def bar(): String in class B with JSName 'bar' - | is conflicting with - |def bar(): Object in class A with JSName 'foo' - | - | override def bar(): String - | ^ - |newSource1.scala:13: warning: A member of a JS class is overriding another member with a different JS name. - | - |override def bar(): String in class C with JSName 'bar' - | is conflicting with - |def bar(): Object in class A with JSName 'foo' - | - | override def bar() = "1" - | ^ - """ - - """ - abstract class A extends js.Object { - def bar(): Object - } - abstract class B extends A { - @JSName("foo") - override def bar(): String - } - class C extends B { - override def bar() = "1" - } - """ hasWarns - """ - |newSource1.scala:10: warning: A member of a JS class is overriding another member with a different JS name. - | - |override def bar(): String in class B with JSName 'foo' - | is conflicting with - |def bar(): Object in class A with JSName 'bar' - | - | override def bar(): String - | ^ - |newSource1.scala:13: warning: A member of a JS class is overriding another member with a different JS name. - | - |override def bar(): String in class C with JSName 'bar' - | is conflicting with - |override def bar(): String in class B with JSName 'foo' - | - | override def bar() = "1" - | ^ - """ - - """ - class A extends js.Object { - def foo: Int = 5 - } - trait B extends A { - @JSName("bar") - def foo: Int - } - class C extends B - """ hasWarns - s""" - |newSource1.scala:10: warning: A member of a JS class is overriding another member with a different JS name. - | - |def foo: Int in class A with JSName 'foo' - | is conflicting with - |def foo: Int in trait B with JSName 'bar' - | - | def foo: Int - | ^ - |${ifHasNewRefChecks(""" - |newSource1.scala:12: warning: A member of a JS class is overriding another member with a different JS name. - | - |def foo: Int in class A with JSName 'foo' - | is conflicting with - |def foo: Int in trait B with JSName 'bar' - | - | class C extends B - | ^ - """)} - """ - - """ - class A extends js.Object { - @JSName("bar") - def foo: Int = 5 - } - trait B extends A { - def foo: Int - } - class C extends B - """ hasWarns - s""" - |newSource1.scala:10: warning: A member of a JS class is overriding another member with a different JS name. - | - |def foo: Int in class A with JSName 'bar' - | is conflicting with - |def foo: Int in trait B with JSName 'foo' - | - | def foo: Int - | ^ - |${ifHasNewRefChecks(""" - |newSource1.scala:12: warning: A member of a JS class is overriding another member with a different JS name. - | - |def foo: Int in class A with JSName 'bar' - | is conflicting with - |def foo: Int in trait B with JSName 'foo' - | - | class C extends B - | ^ - """)} - """ - - """ - class A[T] extends js.Object { - @JSName("bar") - def foo(x: T): T = x - } - class B extends A[Int] { - override def foo(x: Int): Int = x - } - """ hasWarns - """ - |newSource1.scala:10: warning: A member of a JS class is overriding another member with a different JS name. - | - |override def foo(x: Int): Int in class B with JSName 'foo' - | is conflicting with - |def foo(x: Int): Int in class A with JSName 'bar' - | - | override def foo(x: Int): Int = x - | ^ - """ - - """ - trait A[T] extends js.Object { - @JSName("bar") - def foo(x: T): T - } - class B extends A[Int] { - override def foo(x: Int): Int = x - } - """ hasWarns - """ - |newSource1.scala:10: warning: A member of a JS class is overriding another member with a different JS name. - | - |override def foo(x: Int): Int in class B with JSName 'foo' - | is conflicting with - |def foo(x: Int): Int in trait A with JSName 'bar' - | - | override def foo(x: Int): Int = x - | ^ - """ - - """ - class A[T] extends js.Object { - @JSName("bar") - def foo(x: T): T = x - } - trait B extends A[Int] { - def foo(x: Int): Int - } - class C extends B { - override def foo(x: Int): Int = x - } - """ hasWarns - """ - |newSource1.scala:10: warning: A member of a JS class is overriding another member with a different JS name. - | - |def foo(x: Int): Int in class A with JSName 'bar' - | is conflicting with - |def foo(x: Int): Int in trait B with JSName 'foo' - | - | def foo(x: Int): Int - | ^ - |newSource1.scala:13: warning: A member of a JS class is overriding another member with a different JS name. - | - |override def foo(x: Int): Int in class C with JSName 'foo' - | is conflicting with - |def foo(x: Int): Int in class A with JSName 'bar' - | - | override def foo(x: Int): Int = x - | ^ - """ - - """ - class A[T] extends js.Object { - def foo(x: T): T = x - } - trait B extends A[Int] { - @JSName("bar") - def foo(x: Int): Int - } - class C extends B { - override def foo(x: Int): Int = x - } - """ hasWarns - """ - |newSource1.scala:10: warning: A member of a JS class is overriding another member with a different JS name. - | - |def foo(x: Int): Int in class A with JSName 'foo' - | is conflicting with - |def foo(x: Int): Int in trait B with JSName 'bar' - | - | def foo(x: Int): Int - | ^ - |newSource1.scala:13: warning: A member of a JS class is overriding another member with a different JS name. - | - |override def foo(x: Int): Int in class C with JSName 'foo' - | is conflicting with - |def foo(x: Int): Int in trait B with JSName 'bar' - | - | override def foo(x: Int): Int = x - | ^ - """ - - """ - trait A extends js.Object { - def foo: Int - } - trait B extends js.Object { - @JSName("bar") - def foo: Int - } - trait C extends A with B - """ hasWarns - """ - |newSource1.scala:12: warning: A member of a JS class is overriding another member with a different JS name. - | - |def foo: Int in trait B with JSName 'bar' - | is conflicting with - |def foo: Int in trait A with JSName 'foo' - | - | trait C extends A with B - | ^ - """ - - """ - trait A extends js.Object { - def foo: Int - } - trait B extends js.Object { - @JSName("bar") - def foo: Int - } - abstract class C extends A with B - """ hasWarns - """ - |newSource1.scala:12: warning: A member of a JS class is overriding another member with a different JS name. - | - |def foo: Int in trait B with JSName 'bar' - | is conflicting with - |def foo: Int in trait A with JSName 'foo' - | - | abstract class C extends A with B - | ^ - """ - } - - @Test - def scalaJSDefinedJSNameWithSymbolOverrideWarnings: Unit = { - """ - object Syms { - val sym1 = js.Symbol() - } - - trait A extends js.Object { - @JSName(Syms.sym1) - def bar(): Int - } - class B extends A { - @JSName(Syms.sym1) - override def bar() = 1 - } - """.hasNoWarns - - """ - object Syms { - val sym1 = js.Symbol() - } - - abstract class A extends js.Object { - @JSName(Syms.sym1) - def bar(): Int - } - class B extends A { - @JSName(Syms.sym1) - override def bar() = 1 - } - """.hasNoWarns - - """ - object Syms { - val sym1 = js.Symbol() - val sym2 = js.Symbol() - } - - abstract class A extends js.Object { - @JSName(Syms.sym1) - def bar(): Int - } - class B extends A { - @JSName(Syms.sym2) - override def bar() = 1 - } - """ hasWarns - """ - |newSource1.scala:16: warning: A member of a JS class is overriding another member with a different JS name. - | - |override def bar(): Int in class B with JSName 'Syms.sym2' - | is conflicting with - |def bar(): Int in class A with JSName 'Syms.sym1' - | - | override def bar() = 1 - | ^ - """ - - """ - object Syms { - val sym1 = js.Symbol() - } - - abstract class A extends js.Object { - @JSName(Syms.sym1) - def bar(): Int - } - class B extends A { - @JSName("baz") - override def bar() = 1 - } - """ hasWarns - """ - |newSource1.scala:15: warning: A member of a JS class is overriding another member with a different JS name. - | - |override def bar(): Int in class B with JSName 'baz' - | is conflicting with - |def bar(): Int in class A with JSName 'Syms.sym1' - | - | override def bar() = 1 - | ^ - """ - - """ - object Syms { - val sym1 = js.Symbol() - } - - abstract class A extends js.Object { - @JSName("foo") - def bar(): Int - } - class B extends A { - @JSName(Syms.sym1) - override def bar() = 1 - } - """ hasWarns - """ - |newSource1.scala:15: warning: A member of a JS class is overriding another member with a different JS name. - | - |override def bar(): Int in class B with JSName 'Syms.sym1' - | is conflicting with - |def bar(): Int in class A with JSName 'foo' - | - | override def bar() = 1 - | ^ - """ - - """ - object Syms { - val sym1 = js.Symbol() - } - - abstract class A extends js.Object { - @JSName(Syms.sym1) - def bar(): Int - } - class B extends A { - override def bar() = 1 - } - """ hasWarns - """ - |newSource1.scala:14: warning: A member of a JS class is overriding another member with a different JS name. - | - |override def bar(): Int in class B with JSName 'bar' - | is conflicting with - |def bar(): Int in class A with JSName 'Syms.sym1' - | - | override def bar() = 1 - | ^ - """ - - """ - object Syms { - val sym1 = js.Symbol() - } - - abstract class A extends js.Object { - @JSName(Syms.sym1) - def bar(): Object - } - abstract class B extends A { - override def bar(): String - } - class C extends B { - override def bar() = "1" - } - """ hasWarns - """ - |newSource1.scala:14: warning: A member of a JS class is overriding another member with a different JS name. - | - |override def bar(): String in class B with JSName 'bar' - | is conflicting with - |def bar(): Object in class A with JSName 'Syms.sym1' - | - | override def bar(): String - | ^ - |newSource1.scala:17: warning: A member of a JS class is overriding another member with a different JS name. - | - |override def bar(): String in class C with JSName 'bar' - | is conflicting with - |def bar(): Object in class A with JSName 'Syms.sym1' - | - | override def bar() = "1" - | ^ - """ - - """ - object Syms { - val sym1 = js.Symbol() - } - - abstract class A extends js.Object { - def bar(): Object - } - abstract class B extends A { - @JSName(Syms.sym1) - override def bar(): String - } - class C extends B { - override def bar() = "1" - } - """ hasWarns - """ - |newSource1.scala:14: warning: A member of a JS class is overriding another member with a different JS name. - | - |override def bar(): String in class B with JSName 'Syms.sym1' - | is conflicting with - |def bar(): Object in class A with JSName 'bar' - | - | override def bar(): String - | ^ - |newSource1.scala:17: warning: A member of a JS class is overriding another member with a different JS name. - | - |override def bar(): String in class C with JSName 'bar' - | is conflicting with - |override def bar(): String in class B with JSName 'Syms.sym1' - | - | override def bar() = "1" - | ^ - """ - - """ - object Syms { - val sym1 = js.Symbol() - } - - class A extends js.Object { - def foo: Int = 5 - } - trait B extends A { - @JSName(Syms.sym1) - def foo: Int - } - class C extends B - """ hasWarns - s""" - |newSource1.scala:14: warning: A member of a JS class is overriding another member with a different JS name. - | - |def foo: Int in class A with JSName 'foo' - | is conflicting with - |def foo: Int in trait B with JSName 'Syms.sym1' - | - | def foo: Int - | ^ - |${ifHasNewRefChecks(""" - |newSource1.scala:16: warning: A member of a JS class is overriding another member with a different JS name. - | - |def foo: Int in class A with JSName 'foo' - | is conflicting with - |def foo: Int in trait B with JSName 'Syms.sym1' - | - | class C extends B - | ^ - """)} - """ - - """ - object Syms { - val sym1 = js.Symbol() - } - - class A extends js.Object { - @JSName(Syms.sym1) - def foo: Int = 5 - } - trait B extends A { - def foo: Int - } - class C extends B - """ hasWarns - s""" - |newSource1.scala:14: warning: A member of a JS class is overriding another member with a different JS name. - | - |def foo: Int in class A with JSName 'Syms.sym1' - | is conflicting with - |def foo: Int in trait B with JSName 'foo' - | - | def foo: Int - | ^ - |${ifHasNewRefChecks(""" - |newSource1.scala:16: warning: A member of a JS class is overriding another member with a different JS name. - | - |def foo: Int in class A with JSName 'Syms.sym1' - | is conflicting with - |def foo: Int in trait B with JSName 'foo' - | - | class C extends B - | ^ - """)} - """ - - """ - object Syms { - val sym1 = js.Symbol() - } - - class A[T] extends js.Object { - @JSName(Syms.sym1) - def foo(x: T): T = x - } - class B extends A[Int] { - override def foo(x: Int): Int = x - } - """ hasWarns - """ - |newSource1.scala:14: warning: A member of a JS class is overriding another member with a different JS name. - | - |override def foo(x: Int): Int in class B with JSName 'foo' - | is conflicting with - |def foo(x: Int): Int in class A with JSName 'Syms.sym1' - | - | override def foo(x: Int): Int = x - | ^ - """ - - """ - object Syms { - val sym1 = js.Symbol() - } - - trait A[T] extends js.Object { - @JSName(Syms.sym1) - def foo(x: T): T - } - class B extends A[Int] { - override def foo(x: Int): Int = x - } - """ hasWarns - """ - |newSource1.scala:14: warning: A member of a JS class is overriding another member with a different JS name. - | - |override def foo(x: Int): Int in class B with JSName 'foo' - | is conflicting with - |def foo(x: Int): Int in trait A with JSName 'Syms.sym1' - | - | override def foo(x: Int): Int = x - | ^ - """ - - """ - object Syms { - val sym1 = js.Symbol() - } - - class A[T] extends js.Object { - @JSName(Syms.sym1) - def foo(x: T): T = x - } - trait B extends A[Int] { - def foo(x: Int): Int - } - class C extends B { - override def foo(x: Int): Int = x - } - """ hasWarns - """ - |newSource1.scala:14: warning: A member of a JS class is overriding another member with a different JS name. - | - |def foo(x: Int): Int in class A with JSName 'Syms.sym1' - | is conflicting with - |def foo(x: Int): Int in trait B with JSName 'foo' - | - | def foo(x: Int): Int - | ^ - |newSource1.scala:17: warning: A member of a JS class is overriding another member with a different JS name. - | - |override def foo(x: Int): Int in class C with JSName 'foo' - | is conflicting with - |def foo(x: Int): Int in class A with JSName 'Syms.sym1' - | - | override def foo(x: Int): Int = x - | ^ - """ - - """ - object Syms { - val sym1 = js.Symbol() - } - - class A[T] extends js.Object { - def foo(x: T): T = x - } - trait B extends A[Int] { - @JSName(Syms.sym1) - def foo(x: Int): Int - } - class C extends B { - override def foo(x: Int): Int = x - } - """ hasWarns - """ - |newSource1.scala:14: warning: A member of a JS class is overriding another member with a different JS name. - | - |def foo(x: Int): Int in class A with JSName 'foo' - | is conflicting with - |def foo(x: Int): Int in trait B with JSName 'Syms.sym1' - | - | def foo(x: Int): Int - | ^ - |newSource1.scala:17: warning: A member of a JS class is overriding another member with a different JS name. - | - |override def foo(x: Int): Int in class C with JSName 'foo' - | is conflicting with - |def foo(x: Int): Int in trait B with JSName 'Syms.sym1' - | - | override def foo(x: Int): Int = x - | ^ - """ - - """ - object Syms { - val sym1 = js.Symbol() - } - - trait A extends js.Object { - def foo: Int - } - trait B extends js.Object { - @JSName(Syms.sym1) - def foo: Int - } - trait C extends A with B - """ hasWarns - """ - |newSource1.scala:16: warning: A member of a JS class is overriding another member with a different JS name. - | - |def foo: Int in trait B with JSName 'Syms.sym1' - | is conflicting with - |def foo: Int in trait A with JSName 'foo' - | - | trait C extends A with B - | ^ - """ - - """ - object Syms { - val sym1 = js.Symbol() - } - - trait A extends js.Object { - def foo: Int - } - trait B extends js.Object { - @JSName(Syms.sym1) - def foo: Int - } - abstract class C extends A with B - """ hasWarns - """ - |newSource1.scala:16: warning: A member of a JS class is overriding another member with a different JS name. - | - |def foo: Int in trait B with JSName 'Syms.sym1' - | is conflicting with - |def foo: Int in trait A with JSName 'foo' - | - | abstract class C extends A with B - | ^ - """ - } - - @Test - def noDefaultConstructorArgsIfModuleIsJSNative: Unit = { - """ - class A(x: Int = 1) extends js.Object - - @js.native - @JSGlobal - object A extends js.Object - """ hasErrors - """ - |newSource1.scala:5: error: Implementation restriction: constructors of Scala.js-defined JS classes cannot have default parameters if their companion module is JS native. - | class A(x: Int = 1) extends js.Object - | ^ - """ - - """ - class A(x: Int = 1) - - @js.native - @JSGlobal - object A extends js.Object - """ hasErrors - """ - |newSource1.scala:5: error: Implementation restriction: constructors of Scala classes cannot have default parameters if their companion module is JS native. - | class A(x: Int = 1) - | ^ - """ - } - - @Test // #2547 - def noDefaultOverrideCrash: Unit = { - """ - @js.native - @JSGlobal - class NativeBase extends js.Object { - def add(option: js.Any = js.native): js.Any = js.native - } - class Derived extends NativeBase { - override def add(option: js.Any): js.Any = super.add(option) - } - """ hasErrors - """ - |newSource1.scala:11: error: When overriding a native method with default arguments, the overriding method must explicitly repeat the default arguments. - | override def add(option: js.Any): js.Any = super.add(option) - | ^ - """ - - """ - @js.native - trait NativeTrait extends js.Object { - def add(option: js.Any = js.native): js.Any = js.native - } - - @js.native - @JSGlobal - class NativeBase extends NativeTrait - - class Derived extends NativeBase { - override def add(option: js.Any): js.Any = super.add(option) - } - """ hasErrors - """ - |newSource1.scala:15: error: When overriding a native method with default arguments, the overriding method must explicitly repeat the default arguments. - | override def add(option: js.Any): js.Any = super.add(option) - | ^ - """ - } - - @Test // # 3969 - def overrideEqualsHashCode: Unit = { - for { - obj <- List("class", "object") - } { - s""" - $obj A extends js.Object { - override def hashCode(): Int = 1 - override def equals(obj: Any): Boolean = false - - // this one works as expected (so allowed) - override def toString(): String = "frobber" - - /* these are allowed, since they are protected in jl.Object. - * as a result, only the overrides can be called. So the fact that they - * do not truly override the methods in jl.Object is not observable. - */ - override def clone(): Object = null - override def finalize(): Unit = () - - // other methods in jl.Object are final. - } - """ hasWarns - """ - |newSource1.scala:6: warning: Overriding hashCode in a JS class does not change its hash code. To silence this warning, change the name of the method and optionally add @JSName("hashCode"). - | override def hashCode(): Int = 1 - | ^ - |newSource1.scala:7: warning: Overriding equals in a JS class does not change how it is compared. To silence this warning, change the name of the method and optionally add @JSName("equals"). - | override def equals(obj: Any): Boolean = false - | ^ - """ - } - - for { - obj <- List("class", "object") - } { - s""" - @js.native - @JSGlobal - $obj A extends js.Object { - override def hashCode(): Int = js.native - override def equals(obj: Any): Boolean = js.native - } - """ hasWarns - """ - |newSource1.scala:8: warning: Overriding hashCode in a JS class does not change its hash code. To silence this warning, change the name of the method and optionally add @JSName("hashCode"). - | override def hashCode(): Int = js.native - | ^ - |newSource1.scala:9: warning: Overriding equals in a JS class does not change how it is compared. To silence this warning, change the name of the method and optionally add @JSName("equals"). - | override def equals(obj: Any): Boolean = js.native - | ^ - """ - } - - """ - @js.native - trait A extends js.Any { - override def hashCode(): Int = js.native - override def equals(obj: Any): Boolean = js.native - } - """ hasWarns - """ - |newSource1.scala:7: warning: Overriding hashCode in a JS class does not change its hash code. To silence this warning, change the name of the method and optionally add @JSName("hashCode"). - | override def hashCode(): Int = js.native - | ^ - |newSource1.scala:8: warning: Overriding equals in a JS class does not change how it is compared. To silence this warning, change the name of the method and optionally add @JSName("equals"). - | override def equals(obj: Any): Boolean = js.native - | ^ - """ - - """ - trait A extends js.Any { - override def hashCode(): Int - override def equals(obj: Any): Boolean - } - """ hasWarns - """ - |newSource1.scala:6: warning: Overriding hashCode in a JS class does not change its hash code. To silence this warning, change the name of the method and optionally add @JSName("hashCode"). - | override def hashCode(): Int - | ^ - |newSource1.scala:7: warning: Overriding equals in a JS class does not change how it is compared. To silence this warning, change the name of the method and optionally add @JSName("equals"). - | override def equals(obj: Any): Boolean - | ^ - """ - } - -} diff --git a/compiler/src/test/scala/org/scalajs/core/compiler/test/JSNativeByDefaultTest.scala b/compiler/src/test/scala/org/scalajs/core/compiler/test/JSNativeByDefaultTest.scala deleted file mode 100644 index e2379ffb66..0000000000 --- a/compiler/src/test/scala/org/scalajs/core/compiler/test/JSNativeByDefaultTest.scala +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler.test - -import org.scalajs.core.compiler.test.util._ - -import org.junit.Test -import org.junit.Ignore - -// scalastyle:off line.size.limit - -class JSNativeByDefaultTest extends DirectTest with TestHelpers { - - /* We add the compiler's output path itself to the classpath, for tests - * involving separate compilation. - */ - override def classpath: List[String] = - super.classpath ++ List(testOutputPath) - - override def extraArgs: List[String] = - super.extraArgs.filter(_ != "-P:scalajs:sjsDefinedByDefault") - - override def preamble: String = - """ - import scala.scalajs.js - import scala.scalajs.js.annotation._ - """ - - @Test - def warnNoJSNativeAnnotation: Unit = { - - """ - class A extends js.Object - """ containsWarns - """ - |newSource1.scala:5: warning: Classes, traits and objects inheriting from js.Any should be annotated with @js.native, unless they have @ScalaJSDefined. The default will switch to Scala.js-defined in the next major version of Scala.js. - | class A extends js.Object - | ^ - """ - - """ - object A extends js.Object - """ containsWarns - """ - |newSource1.scala:5: warning: Classes, traits and objects inheriting from js.Any should be annotated with @js.native, unless they have @ScalaJSDefined. The default will switch to Scala.js-defined in the next major version of Scala.js. - | object A extends js.Object - | ^ - """ - - """ - trait A extends js.Object - """ hasWarns - """ - |newSource1.scala:5: warning: Classes, traits and objects inheriting from js.Any should be annotated with @js.native, unless they have @ScalaJSDefined. The default will switch to Scala.js-defined in the next major version of Scala.js. - | trait A extends js.Object - | ^ - """ - - } - - @Test - def treatedAsJSNative: Unit = { - - """ - @JSGlobal - class A extends js.Object { - def foo(): Int = 42 - } - """ hasWarns - """ - |newSource1.scala:6: warning: Classes, traits and objects inheriting from js.Any should be annotated with @js.native, unless they have @ScalaJSDefined. The default will switch to Scala.js-defined in the next major version of Scala.js. - | class A extends js.Object { - | ^ - |newSource1.scala:7: warning: Members of traits, classes and objects extending js.Any may only contain members that call js.native. This will be enforced in 1.0. - | def foo(): Int = 42 - | ^ - """ - - """ - @JSGlobal - object A extends js.Object { - def foo(): Int = 42 - } - """ hasWarns - """ - |newSource1.scala:6: warning: Classes, traits and objects inheriting from js.Any should be annotated with @js.native, unless they have @ScalaJSDefined. The default will switch to Scala.js-defined in the next major version of Scala.js. - | object A extends js.Object { - | ^ - |newSource1.scala:7: warning: Members of traits, classes and objects extending js.Any may only contain members that call js.native. This will be enforced in 1.0. - | def foo(): Int = 42 - | ^ - """ - - """ - trait A extends js.Object { - def foo(): Int = 42 - } - """ hasWarns - """ - |newSource1.scala:5: warning: Classes, traits and objects inheriting from js.Any should be annotated with @js.native, unless they have @ScalaJSDefined. The default will switch to Scala.js-defined in the next major version of Scala.js. - | trait A extends js.Object { - | ^ - |newSource1.scala:6: warning: Members of traits, classes and objects extending js.Any may only contain members that call js.native. This will be enforced in 1.0. - | def foo(): Int = 42 - | ^ - """ - - } - - @Test - def noExtendNativeTrait: Unit = { - """ - trait NativeTrait extends js.Object - - @ScalaJSDefined - class A extends NativeTrait - - @ScalaJSDefined - trait B extends NativeTrait - - @ScalaJSDefined - object C extends NativeTrait - - object Container { - val x = new NativeTrait {} - } - """ hasErrors - """ - |newSource1.scala:5: warning: Classes, traits and objects inheriting from js.Any should be annotated with @js.native, unless they have @ScalaJSDefined. The default will switch to Scala.js-defined in the next major version of Scala.js. - | trait NativeTrait extends js.Object - | ^ - |newSource1.scala:7: warning: @ScalaJSDefined is deprecated: add `-P:scalajs:sjsDefinedByDefault` to your scalac options and simply remove `@ScalaJSDefined` - | @ScalaJSDefined - | ^ - |newSource1.scala:8: error: A Scala.js-defined JS class cannot directly extend a native JS trait. - | class A extends NativeTrait - | ^ - |newSource1.scala:10: warning: @ScalaJSDefined is deprecated: add `-P:scalajs:sjsDefinedByDefault` to your scalac options and simply remove `@ScalaJSDefined` - | @ScalaJSDefined - | ^ - |newSource1.scala:11: error: A Scala.js-defined JS trait cannot directly extend a native JS trait. - | trait B extends NativeTrait - | ^ - |newSource1.scala:13: warning: @ScalaJSDefined is deprecated: add `-P:scalajs:sjsDefinedByDefault` to your scalac options and simply remove `@ScalaJSDefined` - | @ScalaJSDefined - | ^ - |newSource1.scala:14: error: A Scala.js-defined JS object cannot directly extend a native JS trait. - | object C extends NativeTrait - | ^ - |newSource1.scala:17: error: A Scala.js-defined JS class cannot directly extend a native JS trait. - | val x = new NativeTrait {} - | ^ - """ - } - - @Test - def noExtendNativeTraitSeparateCompilation: Unit = { - """ - trait NativeTrait extends js.Object - """.succeeds() - - """ - @ScalaJSDefined - class A extends NativeTrait - - @ScalaJSDefined - trait B extends NativeTrait - - @ScalaJSDefined - object C extends NativeTrait - - object Container { - val x = new NativeTrait {} - } - """ hasErrors - """ - |newSource1.scala:5: warning: @ScalaJSDefined is deprecated: add `-P:scalajs:sjsDefinedByDefault` to your scalac options and simply remove `@ScalaJSDefined` - | @ScalaJSDefined - | ^ - |newSource1.scala:6: error: A Scala.js-defined JS class cannot directly extend a native JS trait. - | class A extends NativeTrait - | ^ - |newSource1.scala:8: warning: @ScalaJSDefined is deprecated: add `-P:scalajs:sjsDefinedByDefault` to your scalac options and simply remove `@ScalaJSDefined` - | @ScalaJSDefined - | ^ - |newSource1.scala:9: error: A Scala.js-defined JS trait cannot directly extend a native JS trait. - | trait B extends NativeTrait - | ^ - |newSource1.scala:11: warning: @ScalaJSDefined is deprecated: add `-P:scalajs:sjsDefinedByDefault` to your scalac options and simply remove `@ScalaJSDefined` - | @ScalaJSDefined - | ^ - |newSource1.scala:12: error: A Scala.js-defined JS object cannot directly extend a native JS trait. - | object C extends NativeTrait - | ^ - |newSource1.scala:15: error: A Scala.js-defined JS class cannot directly extend a native JS trait. - | val x = new NativeTrait {} - | ^ - """ - } - -} diff --git a/compiler/src/test/scala/org/scalajs/core/compiler/test/JSOptionalTest.scala b/compiler/src/test/scala/org/scalajs/core/compiler/test/JSOptionalTest.scala deleted file mode 100644 index fd784eb9bc..0000000000 --- a/compiler/src/test/scala/org/scalajs/core/compiler/test/JSOptionalTest.scala +++ /dev/null @@ -1,276 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler.test - -import org.scalajs.core.compiler.test.util._ - -import org.junit.Test -import org.junit.Ignore - -// scalastyle:off line.size.limit - -class JSOptionalTest extends DirectTest with TestHelpers { - - /* We add the compiler's output path itself to the classpath, for tests - * involving separate compilation. - */ - override def classpath: List[String] = - super.classpath ++ List(testOutputPath) - - override def preamble: String = { - """ - import scala.scalajs.js - import scala.scalajs.js.annotation._ - """ - } - - @Test - def optionalRequiresUndefinedRHS: Unit = { - s""" - trait A extends js.Object { - val a1: js.UndefOr[Int] = 5 - val a2: Int = 5 - - def b1: js.UndefOr[Int] = 5 - def b2: Int = 5 - - var c1: js.UndefOr[Int] = 5 - var c2: Int = 5 - } - """ hasErrors - s""" - |newSource1.scala:6: error: Members of Scala.js-defined JS traits must either be abstract, or their right-hand-side must be `js.undefined`. - | val a1: js.UndefOr[Int] = 5 - | ^ - |newSource1.scala:7: error: Members of Scala.js-defined JS traits must either be abstract, or their right-hand-side must be `js.undefined`. - | val a2: Int = 5 - | ^ - |newSource1.scala:9: error: Members of Scala.js-defined JS traits must either be abstract, or their right-hand-side must be `js.undefined`. - | def b1: js.UndefOr[Int] = 5 - | ^ - |newSource1.scala:10: error: Members of Scala.js-defined JS traits must either be abstract, or their right-hand-side must be `js.undefined`. - | def b2: Int = 5 - | ^ - |newSource1.scala:12: error: Members of Scala.js-defined JS traits must either be abstract, or their right-hand-side must be `js.undefined`. - | var c1: js.UndefOr[Int] = 5 - | ^ - |newSource1.scala:13: error: Members of Scala.js-defined JS traits must either be abstract, or their right-hand-side must be `js.undefined`. - | var c2: Int = 5 - | ^ - """ - } - - @Test - def noOptionalLazyVal: Unit = { - s""" - trait A extends js.Object { - lazy val a1: js.UndefOr[Int] = js.undefined - } - """ hasErrors - s""" - |newSource1.scala:6: error: A Scala.js-defined JS trait cannot contain lazy vals - | lazy val a1: js.UndefOr[Int] = js.undefined - | ^ - """ - } - - @Test - def noOverrideConcreteNonOptionalWithOptional: Unit = { - """ - abstract class A extends js.Object { - val a1: js.UndefOr[Int] = 5 - val a2: js.UndefOr[Int] - - def b1: js.UndefOr[Int] = 5 - def b2: js.UndefOr[Int] - } - - trait B extends A { - override val a1: js.UndefOr[Int] = js.undefined - override val a2: js.UndefOr[Int] = js.undefined - - override def b1: js.UndefOr[Int] = js.undefined - override def b2: js.UndefOr[Int] = js.undefined - } - """ hasErrors - """ - |newSource1.scala:14: error: Cannot override concrete val a1: scala.scalajs.js.UndefOr[Int] from A in a Scala.js-defined JS trait. - | override val a1: js.UndefOr[Int] = js.undefined - | ^ - |newSource1.scala:17: error: Cannot override concrete def b1: scala.scalajs.js.UndefOr[Int] from A in a Scala.js-defined JS trait. - | override def b1: js.UndefOr[Int] = js.undefined - | ^ - """ - - """ - @js.native - @JSGlobal - class A extends js.Object { - val a: js.UndefOr[Int] = js.native - def b: js.UndefOr[Int] = js.native - } - - trait B extends A { - override val a: js.UndefOr[Int] = js.undefined - override def b: js.UndefOr[Int] = js.undefined - } - """ hasErrors - """ - |newSource1.scala:13: error: Cannot override concrete val a: scala.scalajs.js.UndefOr[Int] from A in a Scala.js-defined JS trait. - | override val a: js.UndefOr[Int] = js.undefined - | ^ - |newSource1.scala:14: error: Cannot override concrete def b: scala.scalajs.js.UndefOr[Int] from A in a Scala.js-defined JS trait. - | override def b: js.UndefOr[Int] = js.undefined - | ^ - """ - - """ - @js.native - trait A extends js.Object { - val a: js.UndefOr[Int] = js.native - def b: js.UndefOr[Int] = js.native - } - - @js.native - @JSGlobal - class B extends A - - trait C extends B { - override val a: js.UndefOr[Int] = js.undefined - override def b: js.UndefOr[Int] = js.undefined - } - """ hasErrors - """ - |newSource1.scala:16: error: Cannot override concrete val a: scala.scalajs.js.UndefOr[Int] from A in a Scala.js-defined JS trait. - | override val a: js.UndefOr[Int] = js.undefined - | ^ - |newSource1.scala:17: error: Cannot override concrete def b: scala.scalajs.js.UndefOr[Int] from A in a Scala.js-defined JS trait. - | override def b: js.UndefOr[Int] = js.undefined - | ^ - """ - } - - @Test - def noOverrideConcreteNonOptionalWithOptionalSeparateCompilation1: Unit = { - """ - abstract class A extends js.Object { - val a1: js.UndefOr[Int] = 5 - val a2: js.UndefOr[Int] - - def b1: js.UndefOr[Int] = 5 - def b2: js.UndefOr[Int] - } - """.succeeds() - - """ - trait B extends A { - override val a1: js.UndefOr[Int] = js.undefined - override val a2: js.UndefOr[Int] = js.undefined - - override def b1: js.UndefOr[Int] = js.undefined - override def b2: js.UndefOr[Int] = js.undefined - } - """ hasErrors - """ - |newSource1.scala:6: error: Cannot override concrete val a1: scala.scalajs.js.UndefOr[Int] from A in a Scala.js-defined JS trait. - | override val a1: js.UndefOr[Int] = js.undefined - | ^ - |newSource1.scala:9: error: Cannot override concrete def b1: scala.scalajs.js.UndefOr[Int] from A in a Scala.js-defined JS trait. - | override def b1: js.UndefOr[Int] = js.undefined - | ^ - """ - } - - @Test - def noOverrideConcreteNonOptionalWithOptionalSeparateCompilation2: Unit = { - """ - @js.native - @JSGlobal - class A extends js.Object { - val a: js.UndefOr[Int] = js.native - def b: js.UndefOr[Int] = js.native - } - """.succeeds() - - """ - trait B extends A { - override val a: js.UndefOr[Int] = js.undefined - override def b: js.UndefOr[Int] = js.undefined - } - """ hasErrors - """ - |newSource1.scala:6: error: Cannot override concrete val a: scala.scalajs.js.UndefOr[Int] from A in a Scala.js-defined JS trait. - | override val a: js.UndefOr[Int] = js.undefined - | ^ - |newSource1.scala:7: error: Cannot override concrete def b: scala.scalajs.js.UndefOr[Int] from A in a Scala.js-defined JS trait. - | override def b: js.UndefOr[Int] = js.undefined - | ^ - """ - } - - @Test - def noOverrideConcreteNonOptionalWithOptionalSeparateCompilation3: Unit = { - """ - @js.native - trait A extends js.Object { - val a: js.UndefOr[Int] = js.native - def b: js.UndefOr[Int] = js.native - } - - @js.native - @JSGlobal - class B extends A - """.succeeds() - - """ - trait C extends B { - override val a: js.UndefOr[Int] = js.undefined - override def b: js.UndefOr[Int] = js.undefined - } - """ hasErrors - """ - |newSource1.scala:6: error: Cannot override concrete val a: scala.scalajs.js.UndefOr[Int] from A in a Scala.js-defined JS trait. - | override val a: js.UndefOr[Int] = js.undefined - | ^ - |newSource1.scala:7: error: Cannot override concrete def b: scala.scalajs.js.UndefOr[Int] from A in a Scala.js-defined JS trait. - | override def b: js.UndefOr[Int] = js.undefined - | ^ - """ - } - - @Test - def noOptionalDefWithParens: Unit = { - s""" - trait A extends js.Object { - def a(): js.UndefOr[Int] = js.undefined - def b(x: Int): js.UndefOr[Int] = js.undefined - def c_=(v: Int): js.UndefOr[Int] = js.undefined - } - """ hasErrors - s""" - |newSource1.scala:6: error: In Scala.js-defined JS traits, defs with parentheses must be abstract. - | def a(): js.UndefOr[Int] = js.undefined - | ^ - |newSource1.scala:7: error: In Scala.js-defined JS traits, defs with parentheses must be abstract. - | def b(x: Int): js.UndefOr[Int] = js.undefined - | ^ - |newSource1.scala:8: error: Raw JS setters must return Unit - | def c_=(v: Int): js.UndefOr[Int] = js.undefined - | ^ - |newSource1.scala:8: error: In Scala.js-defined JS traits, defs with parentheses must be abstract. - | def c_=(v: Int): js.UndefOr[Int] = js.undefined - | ^ - """ - } - -} diff --git a/compiler/src/test/scala/org/scalajs/core/compiler/test/JSSAMTest.scala b/compiler/src/test/scala/org/scalajs/core/compiler/test/JSSAMTest.scala deleted file mode 100644 index 7144dac0da..0000000000 --- a/compiler/src/test/scala/org/scalajs/core/compiler/test/JSSAMTest.scala +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler.test - -import org.scalajs.core.compiler.test.util._ - -import org.junit.Assume._ -import org.junit.Test - -// scalastyle:off line.size.limit - -class JSSAMTest extends DirectTest with TestHelpers { - - override def preamble: String = - """ - import scala.scalajs.js - import scala.scalajs.js.annotation._ - """ - - @Test - def noSAMAsJSTypeGeneric: Unit = { - - """ - @js.native - trait Foo extends js.Object { - def foo(x: Int): Int - } - - trait Bar extends js.Object { - def bar(x: Int): Int - } - - class A { - val foo: Foo = x => x + 1 - val Bar: Bar = x => x + 1 - } - """.fails() - - } - - @Test - def noSAMAsJSType212: Unit = { - - val version = scala.util.Properties.versionNumberString - assumeTrue(!version.startsWith("2.10.") && !version.startsWith("2.11.")) - - """ - @js.native - trait Foo extends js.Object { - def foo(x: Int): Int - } - - trait Bar extends js.Object { - def bar(x: Int): Int - } - - class A { - val foo: Foo = x => x + 1 - val Bar: Bar = x => x + 1 - } - """ hasErrors - """ - |newSource1.scala:15: error: Using an anonymous function as a SAM for the JavaScript type Foo is not allowed. Use an anonymous class instead. - | val foo: Foo = x => x + 1 - | ^ - |newSource1.scala:16: error: Using an anonymous function as a SAM for the JavaScript type Bar is not allowed. Use an anonymous class instead. - | val Bar: Bar = x => x + 1 - | ^ - """ - - } - -} diff --git a/compiler/src/test/scala/org/scalajs/core/compiler/test/MatchASTTest.scala b/compiler/src/test/scala/org/scalajs/core/compiler/test/MatchASTTest.scala deleted file mode 100644 index cec2e6d6e8..0000000000 --- a/compiler/src/test/scala/org/scalajs/core/compiler/test/MatchASTTest.scala +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler.test - -import util._ - -import org.junit.Test -import org.junit.Assert._ - -import org.scalajs.core.ir.{Trees => js} - -class MatchASTTest extends JSASTTest { - - @Test - def stripIdentityMatchEndNonUnitResult: Unit = { - """ - object A { - def foo = "a" match { - case "a" => true - case "b" => false - } - } - """.hasExactly(1, "local variable") { - case js.VarDef(_, _, _, _) => - } - } - - @Test - def stripIdentityMatchEndUnitResult: Unit = { - """ - object A { - def foo = "a" match { - case "a" => - case "b" => - } - } - """.hasExactly(1, "local variable") { - case js.VarDef(_, _, _, _) => - } - } - -} diff --git a/compiler/src/test/scala/org/scalajs/core/compiler/test/MissingJSGlobalDeprecationsSuppressedTest.scala b/compiler/src/test/scala/org/scalajs/core/compiler/test/MissingJSGlobalDeprecationsSuppressedTest.scala deleted file mode 100644 index 984760c375..0000000000 --- a/compiler/src/test/scala/org/scalajs/core/compiler/test/MissingJSGlobalDeprecationsSuppressedTest.scala +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler.test - -import org.scalajs.core.compiler.test.util._ -import org.junit.Test - -// scalastyle:off line.size.limit - -/* This is a copy of MissingJSGlobalDeprecationsTest, but with all the - * relevant deprecations suppressed. This tests the suppression mechanism. - */ -class MissingJSGlobalDeprecationsSuppressedTest - extends DirectTest with TestHelpers { - - override def extraArgs: List[String] = - super.extraArgs :+ "-P:scalajs:suppressMissingJSGlobalDeprecations" - - override def preamble: String = - """import scala.scalajs.js, js.annotation._ - """ - - @Test - def noWarnNoAnnotClass: Unit = { - """ - @js.native - class A extends js.Object - - @js.native - abstract class B extends js.Object - """.hasNoWarns - } - - @Test - def noWarnNoAnnotObject: Unit = { - """ - @js.native - object A extends js.Object - """.hasNoWarns - } - - @Test - def noWarnJSNameClass: Unit = { - """ - @js.native - @JSName("Foo") - class A extends js.Object - - @js.native - @JSName("Foo") - abstract class B extends js.Object - """.hasNoWarns - } - - @Test - def noWarnJSNameObject: Unit = { - """ - @js.native - @JSName("Foo") - object A extends js.Object - """.hasNoWarns - } - - @Test - def noWarnJSNameNestedClass: Unit = { - """ - object Enclosing { - @js.native - @JSName("Foo") - class A extends js.Object - - @js.native - @JSName("Foo") - abstract class B extends js.Object - } - """.hasNoWarns - } - - @Test - def noWarnJSNameNestObject: Unit = { - """ - object Enclosing { - @js.native - @JSName("Foo") - object A extends js.Object - } - """.hasNoWarns - } - -} diff --git a/compiler/src/test/scala/org/scalajs/core/compiler/test/MissingJSGlobalDeprecationsTest.scala b/compiler/src/test/scala/org/scalajs/core/compiler/test/MissingJSGlobalDeprecationsTest.scala deleted file mode 100644 index ab43c8b8c5..0000000000 --- a/compiler/src/test/scala/org/scalajs/core/compiler/test/MissingJSGlobalDeprecationsTest.scala +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler.test - -import org.scalajs.core.compiler.test.util._ -import org.junit.Test - -// scalastyle:off line.size.limit - -class MissingJSGlobalDeprecationsTest extends DirectTest with TestHelpers { - - override def preamble: String = - """import scala.scalajs.js, js.annotation._ - """ - - @Test - def warnNoAnnotClass: Unit = { - """ - @js.native - class A extends js.Object - - @js.native - abstract class B extends js.Object - """ hasWarns - """ - |newSource1.scala:4: warning: Top-level native JS classes and objects should have an @JSGlobal or @JSImport annotation. This will be enforced in 1.0. - | If migrating from 0.6.14 or earlier, the equivalent behavior is an @JSGlobal without parameter. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressMissingJSGlobalDeprecations` to scalac) - | class A extends js.Object - | ^ - |newSource1.scala:7: warning: Top-level native JS classes and objects should have an @JSGlobal or @JSImport annotation. This will be enforced in 1.0. - | If migrating from 0.6.14 or earlier, the equivalent behavior is an @JSGlobal without parameter. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressMissingJSGlobalDeprecations` to scalac) - | abstract class B extends js.Object - | ^ - """ - } - - @Test - def warnNoAnnotObject: Unit = { - """ - @js.native - object A extends js.Object - """ hasWarns - """ - |newSource1.scala:4: warning: Top-level native JS classes and objects should have an @JSGlobal or @JSImport annotation. This will be enforced in 1.0. - | If migrating from 0.6.14 or earlier, the equivalent behavior is an @JSGlobal without parameter. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressMissingJSGlobalDeprecations` to scalac) - | object A extends js.Object - | ^ - """ - } - - @Test - def warnJSNameClass: Unit = { - """ - @js.native - @JSName("Foo") - class A extends js.Object - - @js.native - @JSName("Foo") - abstract class B extends js.Object - """ hasWarns - """ - |newSource1.scala:4: warning: @JSName on top-level native JS classes and objects (or native JS classes and objects inside Scala objects) is deprecated, and should be replaced by @JSGlobal (with the same meaning). This will be enforced in 1.0. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressMissingJSGlobalDeprecations` to scalac) - | @JSName("Foo") - | ^ - |newSource1.scala:8: warning: @JSName on top-level native JS classes and objects (or native JS classes and objects inside Scala objects) is deprecated, and should be replaced by @JSGlobal (with the same meaning). This will be enforced in 1.0. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressMissingJSGlobalDeprecations` to scalac) - | @JSName("Foo") - | ^ - """ - } - - @Test - def warnJSNameObject: Unit = { - """ - @js.native - @JSName("Foo") - object A extends js.Object - """ hasWarns - """ - |newSource1.scala:4: warning: @JSName on top-level native JS classes and objects (or native JS classes and objects inside Scala objects) is deprecated, and should be replaced by @JSGlobal (with the same meaning). This will be enforced in 1.0. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressMissingJSGlobalDeprecations` to scalac) - | @JSName("Foo") - | ^ - """ - } - - @Test - def warnJSNameNestedClass: Unit = { - """ - object Enclosing { - @js.native - @JSName("Foo") - class A extends js.Object - - @js.native - @JSName("Foo") - abstract class B extends js.Object - } - """ hasWarns - """ - |newSource1.scala:5: warning: @JSName on top-level native JS classes and objects (or native JS classes and objects inside Scala objects) is deprecated, and should be replaced by @JSGlobal (with the same meaning). This will be enforced in 1.0. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressMissingJSGlobalDeprecations` to scalac) - | @JSName("Foo") - | ^ - |newSource1.scala:9: warning: @JSName on top-level native JS classes and objects (or native JS classes and objects inside Scala objects) is deprecated, and should be replaced by @JSGlobal (with the same meaning). This will be enforced in 1.0. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressMissingJSGlobalDeprecations` to scalac) - | @JSName("Foo") - | ^ - """ - } - - @Test - def warnJSNameNestObject: Unit = { - """ - object Enclosing { - @js.native - @JSName("Foo") - object A extends js.Object - } - """ hasWarns - """ - |newSource1.scala:5: warning: @JSName on top-level native JS classes and objects (or native JS classes and objects inside Scala objects) is deprecated, and should be replaced by @JSGlobal (with the same meaning). This will be enforced in 1.0. - | (you can suppress this warning in 0.6.x by passing the option `-P:scalajs:suppressMissingJSGlobalDeprecations` to scalac) - | @JSName("Foo") - | ^ - """ - } - -} diff --git a/compiler/src/test/scala/org/scalajs/core/compiler/test/OptimizationTest.scala b/compiler/src/test/scala/org/scalajs/core/compiler/test/OptimizationTest.scala deleted file mode 100644 index 275e2a524f..0000000000 --- a/compiler/src/test/scala/org/scalajs/core/compiler/test/OptimizationTest.scala +++ /dev/null @@ -1,389 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler.test - -import util._ - -import org.junit.Test - -import org.scalajs.core.ir.{Trees => js, Types => jstpe} - -class OptimizationTest extends JSASTTest { - import OptimizationTest._ - - @Test - def unwrapScalaFunWrapper: Unit = { - // Make sure we do not wrap and unwrap right away - """ - import scala.scalajs.js - - class A { - val jsFun: js.Function = (x: Int) => x * 2 - } - """. - hasNot("runtime.AnonFunction ctor") { - case js.New(jstpe.ClassType("sjsr_AnonFunction1"), _, _) => - } - - // Make sure our wrapper matcher has the right name - """ - import scala.scalajs.js - - class A { - val scalaFun = (x: Int) => x * 2 - val jsFun: js.Function = scalaFun - } - """. - has("runtime.AnonFunction ctor") { - case js.New(jstpe.ClassType("sjsr_AnonFunction1"), _, _) => - } - } - - @Test - def testArrayApplyOptimization: Unit = { - /* Make sure Array(...) is optimized away completely for several kinds - * of data types, with both the generic overload and the ones specialized - * for primitives. - */ - """ - class A { - val a = Array(5, 7, 9, -3) - val b = Array("hello", "world") - val c = Array('a', 'b') - val d = Array(Nil) - val e = Array(5.toByte, 7.toByte, 9.toByte, -3.toByte) - - // Also with exactly 1 element of a primitive type (#3938) - val f = Array('a') - val g = Array(5.toByte) - } - """. - hasNot("any LoadModule of the scala.Array companion") { - case js.LoadModule(jstpe.ClassType("s_Array$")) => - } - - /* Using [] with primitives produces suboptimal trees, which cannot be - * optimized. We should improve this in the future, if possible. This is - * particularly annoying for Byte and Short, as it means that we need to - * write `.toByte` for every single element if we want the optimization to - * kick in. - * - * Scala/JVM has the same limitation. - */ - """ - class A { - val a = Array[Int](5, 7, 9, -3) - val b = Array[Byte](5, 7, 9, -3) - val c = Array[Int](5) - val d = Array[Byte](5) - } - """. - hasExactly(4, "calls to Array.apply methods") { - case js.Apply(js.LoadModule(jstpe.ClassType("s_Array$")), js.Ident(methodName, _), _) - if methodName.startsWith("apply__") => - } - } - - @Test - def testJSArrayApplyOptimization: Unit = { - /* Make sure js.Array(...) is optimized away completely for several kinds - * of data types. - */ - """ - import scala.scalajs.js - - class VC(val x: Int) extends AnyVal - - class A { - val a = js.Array(5, 7, 9, -3) - val b = js.Array("hello", "world") - val c = js.Array('a', 'b') - val d = js.Array(Nil) - val e = js.Array(new VC(151189)) - } - """. - hasNot("any of the wrapArray methods") { - case WrapArrayCall() => - } - } - - @Test - def testVarArgsOptimization: Unit = { - /* Make sure varargs are optimized to use js.WrappedArray instead of - * scm.WrappedArray, for various data types. - */ - """ - import scala.scalajs.js - - class VC(val x: Int) extends AnyVal - - class A { - val a = List(5, 7, 9, -3) - val b = List("hello", "world") - val c = List('a', 'b') - val d = List(Nil) - val e = List(new VC(151189)) - } - """. - hasNot("any of the wrapArray methods") { - case WrapArrayCall() => - } - - /* #2265 and #2741: - * Make sure varargs are optimized to use js.WrappedArray instead of - * scm.WrappedArray, for different species of target method (single arg - * list, multiple arg list, in value class). - */ - """ - import scala.scalajs.js - - class VC(val x: Int) extends AnyVal { - def singleInVC(ys: Int*): Int = x + ys.size - } - - class A { - def test(): Int = { - val a = single(5, 7, 9, -3) - val b = multiple(5)(7, 9, -3) - val c = new VC(5).singleInVC(7, 9, -3) - a + b + c - } - - def single(x: Int, ys: Int*): Int = x + ys.size - def multiple(x: Int)(ys: Int*): Int = x + ys.size - } - """. - hasNot("any of the wrapArray methods") { - case WrapArrayCall() => - } - - /* Make sure our wrapper matcher has the right name. - * With the new collections, only actual varargs will produce a call to the - * methods we optimize, and we would always be able to optimize them in - * that case. So we need to explicitly call the method that the codegen - * would use. - */ - val sanityCheckCode = if (hasOldCollections) { - """ - class A { - val a: Seq[Int] = new Array[Int](5) - } - """ - } else { - """ - class A { - runtime.ScalaRunTime.wrapIntArray(new Array[Int](5)) - } - """ - } - sanityCheckCode.has("one of the wrapArray methods") { - case WrapArrayCall() => - } - } - - @Test - def testNewJSObjectAndJSArray: Unit = { - // Verify the optimized emitted code for 'new js.Object' and 'new js.Array' - """ - import scala.scalajs.js - - class A { - val o = new js.Object - val a = new js.Array - } - """. - hasNot("any reference to the global scope") { - case js.JSLinkingInfo() => - } - } - - @Test - def noLabeledBlockForPatmatWithToplevelCaseClassesOnlyAndNoGuards: Unit = { - """ - sealed abstract class Foo - final case class Foobar(x: Int) extends Foo - final case class Foobaz(y: String) extends Foo - - class Test { - def testWithListsStat(xs: List[Int]): Unit = { - xs match { - case head :: tail => println(head + " " + tail) - case Nil => println("nil") - } - } - - def testWithListsExpr(xs: List[Int]): Int = { - xs match { - case head :: tail => head + tail.size - case Nil => 0 - } - } - - def testWithFooStat(foo: Foo): Unit = { - foo match { - case Foobar(x) => println("foobar: " + x) - case Foobaz(y) => println(y) - } - } - - def testWithFooExpr(foo: Foo): String = { - foo match { - case Foobar(x) => "foobar: " + x - case Foobaz(y) => "foobaz: " + y - } - } - } - """.hasNot("Labeled block") { - case js.Labeled(_, _, _) => - } - } - - @Test - def switchWithoutGuards: Unit = { - """ - class Test { - def switchWithGuardsStat(x: Int, y: Int): Unit = { - x match { - case 1 => println("one") - case 2 => println("two") - case z if y > 100 => println("big " + z) - case _ => println("None of those") - } - } - } - """.hasNot("Labeled block") { - case js.Labeled(_, _, _) => - }.has("Match node") { - case js.Match(_, _, _) => - } - } - - @Test - def switchWithGuards: Unit = { - // Statement position - """ - class Test { - def switchWithGuardsStat(x: Int, y: Int): Unit = { - x match { - case 1 => println("one") - case 2 if y < 10 => println("two special") - case 2 => println("two") - case 3 if y < 10 => println("three special") - case 3 if y > 100 => println("three big special") - case z if y > 100 => println("big " + z) - case _ => println("None of those") - } - } - } - """.hasExactly(1, "default case (\"None of those\")") { - case js.StringLiteral("None of those") => - }.has("Match node") { - case js.Match(_, _, _) => - } - - // Expression position - """ - class Test { - def switchWithGuardsExpr(x: Int, y: Int): Unit = { - val message = x match { - case 1 => "one" - case 2 if y < 10 => "two special" - case 2 => "two" - case 3 if y < 10 => "three special" - case 3 if y > 100 => "three big special" - case z if y > 100 => "big " + z - case _ => "None of those" - } - println(message) - } - } - """.hasExactly(1, "default case (\"None of those\")") { - case js.StringLiteral("None of those") => - }.has("Match node") { - case js.Match(_, _, _) => - } - } - - @Test - def newSJSDefinedTraitProducesObjectConstr: Unit = { - """ - import scala.scalajs.js - import scala.scalajs.js.annotation._ - - trait Point extends js.Object { - val x: Double - val y: Double - } - - class Test { - def newSJSDefinedTraitProducesObjectConstr(): Any = { - new Point { - val x = 5.0 - val y = 6.5 - } - } - } - """.hasNot("`new Object`") { - case js.JSNew(_, _) => - }.has("object literal") { - case js.JSObjectConstr(Nil) => - } - - """ - import scala.scalajs.js - import scala.scalajs.js.annotation._ - - trait Point extends js.Object { - var x: js.UndefOr[Double] = js.undefined - var y: js.UndefOr[Double] = js.undefined - } - - class Test { - def newSJSDefinedTraitProducesObjectConstr(): Any = { - new Point { - x = 5.0 - y = 6.5 - } - } - } - """.hasNot("`new Object`") { - case js.JSNew(_, _) => - }.has("object literal") { - case js.JSObjectConstr(Nil) => - } - } - -} - -object OptimizationTest { - - private val hasOldCollections = { - val version = scala.util.Properties.versionNumberString - - version.startsWith("2.10.") || - version.startsWith("2.11.") || - version.startsWith("2.12.") - } - - private object WrapArrayCall { - private val Suffix = - if (hasOldCollections) "__scm_WrappedArray" - else "__sci_ArraySeq" - - def unapply(tree: js.Apply): Boolean = { - val methodName = tree.method.name - methodName.startsWith("wrap") && methodName.endsWith(Suffix) - } - } - -} diff --git a/compiler/src/test/scala/org/scalajs/core/compiler/test/RegressionTest.scala b/compiler/src/test/scala/org/scalajs/core/compiler/test/RegressionTest.scala deleted file mode 100644 index 8e3c88418b..0000000000 --- a/compiler/src/test/scala/org/scalajs/core/compiler/test/RegressionTest.scala +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler.test - -import org.scalajs.core.compiler.test.util._ -import org.junit.Test -import org.junit.Assume._ - -// scalastyle:off line.size.limit - -class RegressionTest extends DirectTest with TestHelpers { - - @Test - def noCrashWhenCallingDefaultMethodsOfCharSequence_issue3211: Unit = { - val javaVersion = System.getProperty("java.specification.version") - assumeTrue(javaVersion.startsWith("1.8") || !javaVersion.startsWith("1.")) - - """ - object LexerUtil { - def reflectiveLongest(data: String): Unit = { - println(data.chars()) - } - } - """.succeeds() - - """ - import scala.language.reflectiveCalls - - object LexerUtil { - def reflectiveLongest(data: Any { def chars: String }): Unit = { - println(data.chars) - } - } - """.succeeds() - } - -} diff --git a/compiler/src/test/scala/org/scalajs/core/compiler/test/ScalaJSDefinedTest.scala b/compiler/src/test/scala/org/scalajs/core/compiler/test/ScalaJSDefinedTest.scala deleted file mode 100644 index 8c9265cf30..0000000000 --- a/compiler/src/test/scala/org/scalajs/core/compiler/test/ScalaJSDefinedTest.scala +++ /dev/null @@ -1,695 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler.test - -import org.scalajs.core.compiler.test.util._ -import org.scalajs.core.compiler.test.util.VersionDependentMessages.methodSig - -import org.junit.Test -import org.junit.Ignore - -// scalastyle:off line.size.limit - -class ScalaJSDefinedTest extends DirectTest with TestHelpers { - - override def extraArgs: List[String] = - super.extraArgs :+ "-P:scalajs:suppressExportDeprecations" - - override def preamble: String = - """ - import scala.scalajs.js - import scala.scalajs.js.annotation._ - """ - - @Test - def noSJSDefinedOnScalaEntity: Unit = { - val objs = List("class", "trait", "object") - - for { - obj <- objs - } { - s""" - @ScalaJSDefined - $obj A - """ hasErrors - s""" - |newSource1.scala:6: error: @ScalaJSDefined is only allowed on classes extending js.Any - | $obj A - | ${" " * obj.length}^ - """ - } - } - - @Test - def noExtendAnyRef: Unit = { - """ - class A extends js.Any - """ hasErrors - """ - |newSource1.scala:5: error: A Scala.js-defined JS class cannot directly extend AnyRef. It must extend a JS class (native or not). - | class A extends js.Any - | ^ - """ - - """ - object A extends js.Any - """ hasErrors - """ - |newSource1.scala:5: error: A Scala.js-defined JS object cannot directly extend AnyRef. It must extend a JS class (native or not). - | object A extends js.Any - | ^ - """ - } - - @Test - def noExtendNativeTrait: Unit = { - """ - @js.native - trait NativeTrait extends js.Object - - class A extends NativeTrait - - trait B extends NativeTrait - - object C extends NativeTrait - - object Container { - val x = new NativeTrait {} - } - """ hasErrors - """ - |newSource1.scala:8: error: A Scala.js-defined JS class cannot directly extend a native JS trait. - | class A extends NativeTrait - | ^ - |newSource1.scala:10: error: A Scala.js-defined JS trait cannot directly extend a native JS trait. - | trait B extends NativeTrait - | ^ - |newSource1.scala:12: error: A Scala.js-defined JS object cannot directly extend a native JS trait. - | object C extends NativeTrait - | ^ - |newSource1.scala:15: error: A Scala.js-defined JS class cannot directly extend a native JS trait. - | val x = new NativeTrait {} - | ^ - """ - } - - @Test - def noApplyMethod: Unit = { - """ - class A extends js.Object { - def apply(arg: Int): Int = arg - } - """ hasErrors - """ - |newSource1.scala:6: error: A Scala.js-defined JavaScript class cannot declare a method named `apply` without `@JSName` - | def apply(arg: Int): Int = arg - | ^ - """ - } - - @Test - def noBracketAccess: Unit = { - """ - class A extends js.Object { - @JSBracketAccess - def foo(index: Int, arg: Int): Int = arg - } - """ hasErrors - """ - |newSource1.scala:7: error: @JSBracketAccess is not allowed in Scala.js-defined JS classes - | def foo(index: Int, arg: Int): Int = arg - | ^ - """ - } - - @Test - def noBracketCall: Unit = { - """ - class A extends js.Object { - @JSBracketCall - def foo(m: String, arg: Int): Int = arg - } - """ hasErrors - """ - |newSource1.scala:7: error: @JSBracketCall is not allowed in Scala.js-defined JS classes - | def foo(m: String, arg: Int): Int = arg - | ^ - """ - } - - @Test - def noCollapseOverloadsOnJSName: Unit = { - """ - class A extends js.Object { - @JSName("bar") - def foo(): Int = 42 - - def bar(): Int = 24 - } - """ hasErrors - s""" - |newSource1.scala:9: error: Cannot disambiguate overloads for method bar with types - | ${methodSig("()", "Int")} - | ${methodSig("()", "Int")} - | def bar(): Int = 24 - | ^ - """ - - """ - class A extends js.Object { - def bar(): Int = 24 - - @JSName("bar") - def foo(): Int = 42 - } - """ hasErrors - s""" - |newSource1.scala:9: error: Cannot disambiguate overloads for method bar with types - | ${methodSig("()", "Int")} - | ${methodSig("()", "Int")} - | def foo(): Int = 42 - | ^ - """ - - """ - class A extends js.Object { - @JSName("bar") - def foo(): Int = 42 - } - - class B extends A { - def bar(): Int = 24 - } - """ hasErrors - s""" - |newSource1.scala:11: error: Cannot disambiguate overloads for method bar with types - | ${methodSig("()", "Int")} - | ${methodSig("()", "Int")} - | def bar(): Int = 24 - | ^ - """ - - """ - @js.native - @JSGlobal - class A extends js.Object { - @JSName("bar") - def foo(): Int = js.native - } - - class B extends A { - def bar(): Int = 24 - } - """ hasErrors - s""" - |newSource1.scala:13: error: Cannot disambiguate overloads for method bar with types - | ${methodSig("()", "Int")} - | ${methodSig("()", "Int")} - | def bar(): Int = 24 - | ^ - """ - - """ - @js.native - @JSGlobal - class Foo extends js.Object { - def foo(x: Int): Int = js.native - - @JSName("foo") - def bar(x: Int): Int = js.native - } - - class Bar extends Foo { - def foo(): Int = 42 - } - """ hasErrors - s""" - |newSource1.scala:14: error: Cannot disambiguate overloads for method foo with types - | ${methodSig("(x: Int)", "Int")} - | ${methodSig("(x: Int)", "Int")} - | class Bar extends Foo { - | ^ - """ - } - - @Test - def noOverloadedPrivate: Unit = { - """ - class A extends js.Object { - private def foo(i: Int): Int = i - private def foo(s: String): String = s - } - """ hasErrors - """ - |newSource1.scala:6: error: Private methods in Scala.js-defined JS classes cannot be overloaded. Use different names instead. - | private def foo(i: Int): Int = i - | ^ - |newSource1.scala:7: error: Private methods in Scala.js-defined JS classes cannot be overloaded. Use different names instead. - | private def foo(s: String): String = s - | ^ - """ - - """ - object A extends js.Object { - private def foo(i: Int): Int = i - private def foo(s: String): String = s - } - """ hasErrors - """ - |newSource1.scala:6: error: Private methods in Scala.js-defined JS classes cannot be overloaded. Use different names instead. - | private def foo(i: Int): Int = i - | ^ - |newSource1.scala:7: error: Private methods in Scala.js-defined JS classes cannot be overloaded. Use different names instead. - | private def foo(s: String): String = s - | ^ - """ - - """ - object Enclosing { - class A extends js.Object { - private[Enclosing] def foo(i: Int): Int = i - private def foo(s: String): String = s - } - } - """ hasErrors - """ - |newSource1.scala:7: error: Private methods in Scala.js-defined JS classes cannot be overloaded. Use different names instead. - | private[Enclosing] def foo(i: Int): Int = i - | ^ - |newSource1.scala:8: error: Private methods in Scala.js-defined JS classes cannot be overloaded. Use different names instead. - | private def foo(s: String): String = s - | ^ - """ - - """ - class A extends js.Object { - private def foo(i: Int): Int = i - def foo(s: String): String = s - } - """ hasErrors - """ - |newSource1.scala:6: error: Private methods in Scala.js-defined JS classes cannot be overloaded. Use different names instead. - | private def foo(i: Int): Int = i - | ^ - """ - - """ - object Enclosing { - class A extends js.Object { - private[Enclosing] def foo(i: Int): Int = i - def foo(s: String): String = s - } - } - """ hasErrors - """ - |newSource1.scala:7: error: Private methods in Scala.js-defined JS classes cannot be overloaded. Use different names instead. - | private[Enclosing] def foo(i: Int): Int = i - | ^ - """ - } - - @Test - def noVirtualQualifiedPrivate: Unit = { - """ - object Enclosing { - class A extends js.Object { - private[Enclosing] def foo(i: Int): Int = i - private[Enclosing] val x: Int = 3 - private[Enclosing] var y: Int = 5 - } - - class B extends A { - override private[Enclosing] final def foo(i: Int): Int = i + 1 - } - } - """ hasErrors - """ - |newSource1.scala:7: error: Qualified private members in Scala.js-defined JS classes must be final - | private[Enclosing] def foo(i: Int): Int = i - | ^ - |newSource1.scala:8: error: Qualified private members in Scala.js-defined JS classes must be final - | private[Enclosing] val x: Int = 3 - | ^ - |newSource1.scala:9: error: Qualified private members in Scala.js-defined JS classes must be final - | private[Enclosing] var y: Int = 5 - | ^ - """ - - """ - object Enclosing { - object A extends js.Object { - private[Enclosing] def foo(i: Int): Int = i - private[Enclosing] val x: Int = 3 - private[Enclosing] var y: Int = 5 - } - } - """ hasErrors - """ - |newSource1.scala:7: error: Qualified private members in Scala.js-defined JS classes must be final - | private[Enclosing] def foo(i: Int): Int = i - | ^ - |newSource1.scala:8: error: Qualified private members in Scala.js-defined JS classes must be final - | private[Enclosing] val x: Int = 3 - | ^ - |newSource1.scala:9: error: Qualified private members in Scala.js-defined JS classes must be final - | private[Enclosing] var y: Int = 5 - | ^ - """ - - """ - object Enclosing { - abstract class A extends js.Object { - private[Enclosing] def foo(i: Int): Int - private[Enclosing] val x: Int - private[Enclosing] var y: Int - } - - class B extends A { - override private[Enclosing] final def foo(i: Int): Int = i + 1 - } - } - """ hasErrors - """ - |newSource1.scala:7: error: Qualified private members in Scala.js-defined JS classes must be final - | private[Enclosing] def foo(i: Int): Int - | ^ - |newSource1.scala:8: error: Qualified private members in Scala.js-defined JS classes must be final - | private[Enclosing] val x: Int - | ^ - |newSource1.scala:9: error: Qualified private members in Scala.js-defined JS classes must be final - | private[Enclosing] var y: Int - | ^ - """ - - """ - object Enclosing { - trait A extends js.Object { - private[Enclosing] def foo(i: Int): Int - private[Enclosing] val x: Int - private[Enclosing] var y: Int - } - } - """ hasErrors - """ - |newSource1.scala:7: error: Qualified private members in Scala.js-defined JS classes must be final - | private[Enclosing] def foo(i: Int): Int - | ^ - |newSource1.scala:8: error: Qualified private members in Scala.js-defined JS classes must be final - | private[Enclosing] val x: Int - | ^ - |newSource1.scala:9: error: Qualified private members in Scala.js-defined JS classes must be final - | private[Enclosing] var y: Int - | ^ - """ - - """ - object Enclosing { - class A private () extends js.Object - - class B private[this] () extends js.Object - - class C private[Enclosing] () extends js.Object - } - """.succeeds - - """ - object Enclosing { - class A extends js.Object { - final private[Enclosing] def foo(i: Int): Int = i - } - } - """.succeeds - - """ - object Enclosing { - class A extends js.Object { - private def foo(i: Int): Int = i - private[this] def bar(i: Int): Int = i + 1 - } - } - """.succeeds - - """ - object Enclosing { - object A extends js.Object { - final private[Enclosing] def foo(i: Int): Int = i - } - } - """.succeeds - - """ - object Enclosing { - object A extends js.Object { - private def foo(i: Int): Int = i - private[this] def bar(i: Int): Int = i + 1 - } - } - """.succeeds - - """ - object Enclosing { - abstract class A extends js.Object { - final private[Enclosing] def foo(i: Int): Int - } - } - """ hasErrors - """ - |newSource1.scala:7: error: abstract member may not have final modifier - | final private[Enclosing] def foo(i: Int): Int - | ^ - """ - - """ - object Enclosing { - trait A extends js.Object { - final private[Enclosing] def foo(i: Int): Int - } - } - """ hasErrors - """ - |newSource1.scala:7: error: abstract member may not have final modifier - | final private[Enclosing] def foo(i: Int): Int - | ^ - """ - } - - @Test - def noUseJsNative: Unit = { - """ - class A extends js.Object { - def foo = js.native - } - """ hasErrors - """ - |newSource1.scala:6: error: js.native may only be used as stub implementation in facade types - | def foo = js.native - | ^ - """ - - """ - object A extends js.Object { - def foo = js.native - } - """ hasErrors - """ - |newSource1.scala:6: error: js.native may only be used as stub implementation in facade types - | def foo = js.native - | ^ - """ - - """ - class A { - val x = new js.Object { - def a: Int = js.native - } - } - """ hasErrors - """ - |newSource1.scala:7: error: js.native may only be used as stub implementation in facade types - | def a: Int = js.native - | ^ - """ - } - - @Test - def noNonLiteralJSName: Unit = { - """ - object A { - val a = "Hello" - final val b = "World" - } - - class B extends js.Object { - @JSName(A.a) - def foo: Int = 5 - @JSName(A.b) - def bar: Int = 5 - } - """ hasErrors - """ - |newSource1.scala:11: error: A string argument to JSName must be a literal string - | @JSName(A.a) - | ^ - """ - - """ - object A { - val a = "Hello" - final val b = "World" - } - - object B extends js.Object { - @JSName(A.a) - def foo: Int = 5 - @JSName(A.b) - def bar: Int = 5 - } - """ hasErrors - """ - |newSource1.scala:11: error: A string argument to JSName must be a literal string - | @JSName(A.a) - | ^ - """ - } - - @Test - def noApplyProperty: Unit = { - // def apply - - """ - class A extends js.Object { - def apply: Int = 42 - } - """ hasErrors - """ - |newSource1.scala:6: error: A member named apply represents function application in JavaScript. A parameterless member should be exported as a property. You must add @JSName("apply") - | def apply: Int = 42 - | ^ - """ - - """ - class A extends js.Object { - @JSName("apply") - def apply: Int = 42 - } - """.succeeds - - // val apply - - """ - class A extends js.Object { - val apply: Int = 42 - } - """ hasErrors - """ - |newSource1.scala:6: error: A member named apply represents function application in JavaScript. A parameterless member should be exported as a property. You must add @JSName("apply") - | val apply: Int = 42 - | ^ - """ - - """ - class A extends js.Object { - @JSName("apply") - val apply: Int = 42 - } - """.succeeds - - // var apply - - """ - class A extends js.Object { - var apply: Int = 42 - } - """ hasErrors - """ - |newSource1.scala:6: error: A member named apply represents function application in JavaScript. A parameterless member should be exported as a property. You must add @JSName("apply") - | var apply: Int = 42 - | ^ - """ - - """ - class A extends js.Object { - @JSName("apply") - var apply: Int = 42 - } - """.succeeds - } - - @Test - def noExportClassWithOnlyPrivateCtors: Unit = { - """ - @JSExport - class A private () extends js.Object - """ hasErrors - """ - |newSource1.scala:5: error: You may not export a class that has only private constructors - | @JSExport - | ^ - """ - - """ - @JSExport - class A private[this] () extends js.Object - """ hasErrors - """ - |newSource1.scala:5: error: You may not export a class that has only private constructors - | @JSExport - | ^ - """ - - """ - @JSExport - class A private[A] () extends js.Object - - object A - """ hasErrors - """ - |newSource1.scala:5: error: You may not export a class that has only private constructors - | @JSExport - | ^ - """ - } - - @Test - def noConcreteMemberInTrait: Unit = { - """ - trait A extends js.Object { - def foo(x: Int): Int = x + 1 - def bar[A](x: A): A = x - } - """ hasErrors - """ - |newSource1.scala:6: error: In Scala.js-defined JS traits, defs with parentheses must be abstract. - | def foo(x: Int): Int = x + 1 - | ^ - |newSource1.scala:7: error: In Scala.js-defined JS traits, defs with parentheses must be abstract. - | def bar[A](x: A): A = x - | ^ - """ - } - - @Test - def noCallOtherConstructorsWithLeftOutDefaultParams: Unit = { - """ - class A(x: Int, y: String = "default") extends js.Object { - def this() = this(12) - } - """ hasErrors - """ - |newSource1.scala:5: error: Implementation restriction: in a JS class, a secondary constructor calling another constructor with default parameters must provide the values of all parameters. - | class A(x: Int, y: String = "default") extends js.Object { - | ^ - """ - } - -} diff --git a/compiler/src/test/scala/org/scalajs/core/compiler/test/util/JSASTTest.scala b/compiler/src/test/scala/org/scalajs/core/compiler/test/util/JSASTTest.scala deleted file mode 100644 index 422bb58ca9..0000000000 --- a/compiler/src/test/scala/org/scalajs/core/compiler/test/util/JSASTTest.scala +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler.test.util - -import language.implicitConversions - -import scala.tools.nsc._ -import scala.reflect.internal.util.SourceFile - -import scala.util.control.ControlThrowable - -import org.junit.Assert._ - -import org.scalajs.core.compiler.{ScalaJSPlugin, JSTreeExtractors} -import JSTreeExtractors.jse -import org.scalajs.core.ir -import ir.{Trees => js} - -abstract class JSASTTest extends DirectTest { - - private var lastAST: JSAST = _ - - class JSAST(val clDefs: List[js.Tree]) { - type Pat = PartialFunction[js.Tree, Unit] - - class PFTraverser(pf: Pat) extends ir.Traversers.Traverser { - private case object Found extends ControlThrowable - - private[this] var finding = false - - def find: Boolean = { - finding = true - try { - clDefs.map(traverse) - false - } catch { - case Found => true - } - } - - def traverse(): Unit = { - finding = false - clDefs.map(traverse) - } - - override def traverse(tree: js.Tree): Unit = { - if (finding && pf.isDefinedAt(tree)) - throw Found - - if (!finding) - pf.lift(tree) - - super.traverse(tree) - } - } - - def has(trgName: String)(pf: Pat): this.type = { - val tr = new PFTraverser(pf) - assertTrue(s"AST should have $trgName", tr.find) - this - } - - def hasNot(trgName: String)(pf: Pat): this.type = { - val tr = new PFTraverser(pf) - assertFalse(s"AST should not have $trgName", tr.find) - this - } - - def hasExactly(count: Int, trgName: String)(pf: Pat): this.type = { - var actualCount = 0 - val tr = new PFTraverser(pf.andThen(_ => actualCount += 1)) - tr.traverse() - assertEquals(s"AST has the wrong number of $trgName", count, actualCount) - this - } - - def traverse(pf: Pat): this.type = { - val tr = new PFTraverser(pf) - tr.traverse() - this - } - - def show: this.type = { - clDefs foreach println _ - this - } - - } - - implicit def string2ast(str: String): JSAST = stringAST(str) - - override def newScalaJSPlugin(global: Global): ScalaJSPlugin = { - new ScalaJSPlugin(global) { - override def generatedJSAST(cld: List[js.Tree]): Unit = { - lastAST = new JSAST(cld) - } - } - } - - def stringAST(code: String): JSAST = stringAST(defaultGlobal)(code) - def stringAST(global: Global)(code: String): JSAST = { - if (!compileString(global)(code)) - throw new IllegalArgumentException("snippet did not compile") - lastAST - } - - def sourceAST(source: SourceFile): JSAST = sourceAST(defaultGlobal)(source) - def sourceAST(global: Global)(source: SourceFile): JSAST = { - if (!compileSources(global)(source)) - throw new IllegalArgumentException("snippet did not compile") - lastAST - } - -} diff --git a/compiler/src/test/scala/org/scalajs/core/compiler/test/util/VersionDependentMessages.scala b/compiler/src/test/scala/org/scalajs/core/compiler/test/util/VersionDependentMessages.scala deleted file mode 100644 index 48b4463cfc..0000000000 --- a/compiler/src/test/scala/org/scalajs/core/compiler/test/util/VersionDependentMessages.scala +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.compiler.test.util - -object VersionDependentMessages { - private val scalaVersion = scala.util.Properties.versionNumberString - - private val usesColonInMethodSig = { - !scalaVersion.startsWith("2.10.") && - !scalaVersion.startsWith("2.11.") && - !scalaVersion.startsWith("2.12.") && - scalaVersion != "2.13.0" && - scalaVersion != "2.13.1" - } - - def methodSig(params: String, resultType: String): String = - if (usesColonInMethodSig) params + ": " + resultType - else params + resultType -} diff --git a/compiler/src/test/scala/org/scalajs/nscplugin/test/BinaryCompatTest.scala b/compiler/src/test/scala/org/scalajs/nscplugin/test/BinaryCompatTest.scala new file mode 100644 index 0000000000..9b8e8f4e33 --- /dev/null +++ b/compiler/src/test/scala/org/scalajs/nscplugin/test/BinaryCompatTest.scala @@ -0,0 +1,65 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin.test + +import org.scalajs.nscplugin.test.util._ + +import org.scalajs.ir.Names._ +import org.scalajs.ir.Trees._ +import org.scalajs.ir.Types._ + +import org.junit.Test + +// scalastyle:off line.size.limit + +class BinaryCompatTest extends JSASTTest { + + @Test + def emitDefaultAccessorsOfJSNativeDefs(): Unit = { + val XDefaultAccessorName = MethodName("foo$default$1", Nil, IntRef) + + /* Check that, even with the fix to #4553, we still emit default accessors + * for JS native defs, unless they are `= js.native`. + */ + """ + import scala.scalajs.js, js.annotation._ + + object Container { + @js.native + @JSGlobal("foo") + def foo(x: Int = 5): Int = js.native + + def bar(x: Int): Int = x + } + """.hasExactly(1, "default accessor for x in foo") { + case MethodDef(flags, MethodIdent(XDefaultAccessorName), _, _, _, _) => + } + + // Check that it is not emitted for `= js.native`. + """ + import scala.scalajs.js, js.annotation._ + + object Container { + @js.native + @JSGlobal("foo") + def foo(x: Int = js.native): Int = js.native + + def bar(x: Int): Int = x + } + """.hasNot("default accessor for x in foo") { + case MethodDef(flags, MethodIdent(XDefaultAccessorName), _, _, _, _) => + } + + } + +} diff --git a/compiler/src/test/scala/org/scalajs/nscplugin/test/DiverseErrorsTest.scala b/compiler/src/test/scala/org/scalajs/nscplugin/test/DiverseErrorsTest.scala new file mode 100644 index 0000000000..ef625a67c0 --- /dev/null +++ b/compiler/src/test/scala/org/scalajs/nscplugin/test/DiverseErrorsTest.scala @@ -0,0 +1,379 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin.test + +import org.scalajs.nscplugin.test.util._ +import org.junit.Test +import org.junit.Assume._ + +// scalastyle:off line.size.limit + +class DiverseErrorsTest extends DirectTest with TestHelpers { + + override def preamble: String = + """import scala.scalajs.js, js.annotation._ + """ + + private def version = scala.util.Properties.versionNumberString + + private val allowsSingletonClassOf = ( + !version.startsWith("2.11.") && + !version.startsWith("2.12.") && + version != "2.13.0" && + version != "2.13.1" && + version != "2.13.2" && + version != "2.13.3" + ) + + @Test + def noIsInstanceOnJS(): Unit = { + + """ + @js.native + trait JSTrait extends js.Object + + class A { + val a: AnyRef = "asdf" + def x = a.isInstanceOf[JSTrait] + } + """ hasErrors + """ + |newSource1.scala:8: error: isInstanceOf[JSTrait] not supported because it is a JS trait + | def x = a.isInstanceOf[JSTrait] + | ^ + """ + + } + + @Test + def jsConstructorOfErrors(): Unit = { + + """ + class ScalaClass + trait ScalaTrait + object ScalaObject + + object A { + val a = js.constructorOf[ScalaClass] + val b = js.constructorOf[ScalaTrait] + val c = js.constructorOf[ScalaObject.type] + } + """ hasErrors + """ + |newSource1.scala:8: error: type arguments [ScalaClass] do not conform to method constructorOf's type parameter bounds [T <: scala.scalajs.js.Any] + | val a = js.constructorOf[ScalaClass] + | ^ + |newSource1.scala:9: error: type arguments [ScalaTrait] do not conform to method constructorOf's type parameter bounds [T <: scala.scalajs.js.Any] + | val b = js.constructorOf[ScalaTrait] + | ^ + |newSource1.scala:10: error: type arguments [ScalaObject.type] do not conform to method constructorOf's type parameter bounds [T <: scala.scalajs.js.Any] + | val c = js.constructorOf[ScalaObject.type] + | ^ + """ + + val singletonPrefix = + if (allowsSingletonClassOf) "non-trait " + else "" + + """ + @js.native @JSGlobal class NativeJSClass extends js.Object + @js.native trait NativeJSTrait extends js.Object + @js.native @JSGlobal object NativeJSObject extends js.Object + + class JSClass extends js.Object + trait JSTrait extends js.Object + object JSObject extends js.Object + + object A { + val a = js.constructorOf[NativeJSTrait] + val b = js.constructorOf[NativeJSObject.type] + + val c = js.constructorOf[NativeJSClass with NativeJSTrait] + val d = js.constructorOf[NativeJSClass { def bar: Int }] + + val e = js.constructorOf[JSTrait] + val f = js.constructorOf[JSObject.type] + + val g = js.constructorOf[JSClass with JSTrait] + val h = js.constructorOf[JSClass { def bar: Int }] + + def foo[A <: js.Any] = js.constructorOf[A] + def bar[A <: js.Any: scala.reflect.ClassTag] = js.constructorOf[A] + } + """ hasErrors + s""" + |newSource1.scala:12: error: non-trait class type required but NativeJSTrait found + | val a = js.constructorOf[NativeJSTrait] + | ^ + |newSource1.scala:13: error: ${singletonPrefix}class type required but NativeJSObject.type found + | val b = js.constructorOf[NativeJSObject.type] + | ^ + |newSource1.scala:15: error: class type required but NativeJSClass with NativeJSTrait found + | val c = js.constructorOf[NativeJSClass with NativeJSTrait] + | ^ + |newSource1.scala:16: error: class type required but NativeJSClass{def bar: Int} found + | val d = js.constructorOf[NativeJSClass { def bar: Int }] + | ^ + |newSource1.scala:18: error: non-trait class type required but JSTrait found + | val e = js.constructorOf[JSTrait] + | ^ + |newSource1.scala:19: error: ${singletonPrefix}class type required but JSObject.type found + | val f = js.constructorOf[JSObject.type] + | ^ + |newSource1.scala:21: error: class type required but JSClass with JSTrait found + | val g = js.constructorOf[JSClass with JSTrait] + | ^ + |newSource1.scala:22: error: class type required but JSClass{def bar: Int} found + | val h = js.constructorOf[JSClass { def bar: Int }] + | ^ + |newSource1.scala:24: error: class type required but A found + | def foo[A <: js.Any] = js.constructorOf[A] + | ^ + |newSource1.scala:25: error: class type required but A found + | def bar[A <: js.Any: scala.reflect.ClassTag] = js.constructorOf[A] + | ^ + """ + + } + + @Test + def jsConstructorTagErrors(): Unit = { + + """ + class ScalaClass + trait ScalaTrait + object ScalaObject + + object A { + val a = js.constructorTag[ScalaClass] + val b = js.constructorTag[ScalaTrait] + val c = js.constructorTag[ScalaObject.type] + } + """ hasErrors + """ + |newSource1.scala:8: error: type arguments [ScalaClass] do not conform to method constructorTag's type parameter bounds [T <: scala.scalajs.js.Any] + | val a = js.constructorTag[ScalaClass] + | ^ + |newSource1.scala:9: error: type arguments [ScalaTrait] do not conform to method constructorTag's type parameter bounds [T <: scala.scalajs.js.Any] + | val b = js.constructorTag[ScalaTrait] + | ^ + |newSource1.scala:10: error: type arguments [ScalaObject.type] do not conform to method constructorTag's type parameter bounds [T <: scala.scalajs.js.Any] + | val c = js.constructorTag[ScalaObject.type] + | ^ + """ + + val singletonPrefix = + if (allowsSingletonClassOf) "non-trait " + else "" + + """ + @js.native @JSGlobal class NativeJSClass extends js.Object + @js.native trait NativeJSTrait extends js.Object + @js.native @JSGlobal object NativeJSObject extends js.Object + + class JSClass extends js.Object + trait JSTrait extends js.Object + object JSObject extends js.Object + + object A { + val a = js.constructorTag[NativeJSTrait] + val b = js.constructorTag[NativeJSObject.type] + + val c = js.constructorTag[NativeJSClass with NativeJSTrait] + val d = js.constructorTag[NativeJSClass { def bar: Int }] + + val e = js.constructorTag[JSTrait] + val f = js.constructorTag[JSObject.type] + + val g = js.constructorTag[JSClass with JSTrait] + val h = js.constructorTag[JSClass { def bar: Int }] + + def foo[A <: js.Any] = js.constructorTag[A] + def bar[A <: js.Any: scala.reflect.ClassTag] = js.constructorTag[A] + } + """ hasErrors + s""" + |newSource1.scala:12: error: non-trait class type required but NativeJSTrait found + | val a = js.constructorTag[NativeJSTrait] + | ^ + |newSource1.scala:13: error: ${singletonPrefix}class type required but NativeJSObject.type found + | val b = js.constructorTag[NativeJSObject.type] + | ^ + |newSource1.scala:15: error: class type required but NativeJSClass with NativeJSTrait found + | val c = js.constructorTag[NativeJSClass with NativeJSTrait] + | ^ + |newSource1.scala:16: error: class type required but NativeJSClass{def bar: Int} found + | val d = js.constructorTag[NativeJSClass { def bar: Int }] + | ^ + |newSource1.scala:18: error: non-trait class type required but JSTrait found + | val e = js.constructorTag[JSTrait] + | ^ + |newSource1.scala:19: error: ${singletonPrefix}class type required but JSObject.type found + | val f = js.constructorTag[JSObject.type] + | ^ + |newSource1.scala:21: error: class type required but JSClass with JSTrait found + | val g = js.constructorTag[JSClass with JSTrait] + | ^ + |newSource1.scala:22: error: class type required but JSClass{def bar: Int} found + | val h = js.constructorTag[JSClass { def bar: Int }] + | ^ + |newSource1.scala:24: error: class type required but A found + | def foo[A <: js.Any] = js.constructorTag[A] + | ^ + |newSource1.scala:25: error: class type required but A found + | def bar[A <: js.Any: scala.reflect.ClassTag] = js.constructorTag[A] + | ^ + """ + + } + + @Test + def runtimeConstructorOfErrorsDisallowedSingletonTypes(): Unit = { + assumeTrue(!allowsSingletonClassOf) + + """ + import scala.scalajs.runtime + + object ScalaObject + @js.native @JSGlobal object NativeJSObject extends js.Object + object JSObject extends js.Object + + object A { + val a = runtime.constructorOf(classOf[ScalaObject.type].asInstanceOf[Class[_ <: js.Any]]) + val b = runtime.constructorOf(classOf[NativeJSObject.type]) + val c = runtime.constructorOf(classOf[JSObject.type]) + } + """ hasErrors + """ + |newSource1.scala:10: error: class type required but ScalaObject.type found + | val a = runtime.constructorOf(classOf[ScalaObject.type].asInstanceOf[Class[_ <: js.Any]]) + | ^ + |newSource1.scala:11: error: class type required but NativeJSObject.type found + | val b = runtime.constructorOf(classOf[NativeJSObject.type]) + | ^ + |newSource1.scala:12: error: class type required but JSObject.type found + | val c = runtime.constructorOf(classOf[JSObject.type]) + | ^ + """ + + } + + @Test + def runtimeConstructorOfErrorsAllowedSingletonTypes(): Unit = { + assumeTrue(allowsSingletonClassOf) + + """ + import scala.scalajs.runtime + + object ScalaObject + @js.native @JSGlobal object NativeJSObject extends js.Object + object JSObject extends js.Object + + object A { + val a = runtime.constructorOf(classOf[ScalaObject.type].asInstanceOf[Class[_ <: js.Any]]) + val b = runtime.constructorOf(classOf[NativeJSObject.type]) + val c = runtime.constructorOf(classOf[JSObject.type]) + } + """ hasErrors + """ + |newSource1.scala:10: error: constructorOf must be called with a constant classOf[T] representing a class extending js.Any (not a trait nor an object) + | val a = runtime.constructorOf(classOf[ScalaObject.type].asInstanceOf[Class[_ <: js.Any]]) + | ^ + |newSource1.scala:11: error: constructorOf must be called with a constant classOf[T] representing a class extending js.Any (not a trait nor an object) + | val b = runtime.constructorOf(classOf[NativeJSObject.type]) + | ^ + |newSource1.scala:12: error: constructorOf must be called with a constant classOf[T] representing a class extending js.Any (not a trait nor an object) + | val c = runtime.constructorOf(classOf[JSObject.type]) + | ^ + """ + + } + + @Test + def runtimeConstructorOfErrors(): Unit = { + + """ + import scala.scalajs.runtime + + class ScalaClass + trait ScalaTrait + + @js.native @JSGlobal class NativeJSClass extends js.Object + @js.native trait NativeJSTrait extends js.Object + @js.native @JSGlobal object NativeJSObject extends js.Object + + class JSClass extends js.Object + trait JSTrait extends js.Object + object JSObject extends js.Object + + object A { + val a = runtime.constructorOf(classOf[ScalaClass].asInstanceOf[Class[_ <: js.Any]]) + val b = runtime.constructorOf(classOf[ScalaTrait].asInstanceOf[Class[_ <: js.Any]]) + + val c = runtime.constructorOf(classOf[NativeJSTrait]) + val d = runtime.constructorOf(classOf[JSTrait]) + + def jsClassClass = classOf[JSClass] + val e = runtime.constructorOf(jsClassClass) + + val f = runtime.constructorOf(NativeJSObject.getClass) + val g = runtime.constructorOf(JSObject.getClass) + } + """ hasErrors + """ + |newSource1.scala:17: error: constructorOf must be called with a constant classOf[T] representing a class extending js.Any (not a trait nor an object) + | val a = runtime.constructorOf(classOf[ScalaClass].asInstanceOf[Class[_ <: js.Any]]) + | ^ + |newSource1.scala:18: error: constructorOf must be called with a constant classOf[T] representing a class extending js.Any (not a trait nor an object) + | val b = runtime.constructorOf(classOf[ScalaTrait].asInstanceOf[Class[_ <: js.Any]]) + | ^ + |newSource1.scala:20: error: constructorOf must be called with a constant classOf[T] representing a class extending js.Any (not a trait nor an object) + | val c = runtime.constructorOf(classOf[NativeJSTrait]) + | ^ + |newSource1.scala:21: error: constructorOf must be called with a constant classOf[T] representing a class extending js.Any (not a trait nor an object) + | val d = runtime.constructorOf(classOf[JSTrait]) + | ^ + |newSource1.scala:24: error: constructorOf must be called with a constant classOf[T] representing a class extending js.Any (not a trait nor an object) + | val e = runtime.constructorOf(jsClassClass) + | ^ + |newSource1.scala:26: error: constructorOf must be called with a constant classOf[T] representing a class extending js.Any (not a trait nor an object) + | val f = runtime.constructorOf(NativeJSObject.getClass) + | ^ + |newSource1.scala:27: error: constructorOf must be called with a constant classOf[T] representing a class extending js.Any (not a trait nor an object) + | val g = runtime.constructorOf(JSObject.getClass) + | ^ + """ + + } + + @Test + def veryLongStringLiteral(): Unit = { + // Create a string whose length is greater than 65,635 bytes + val len = 70000 + val charArray = new Array[Char](len) + java.util.Arrays.fill(charArray, 'A') + val veryLongString = new String(charArray) + + s""" + object Foo { + val bar: String = "$veryLongString" + } + """ containsErrors + """ + |error: Error while emitting newSource1.scala + |encoded string + """ + // optionally followed by the string, then by " too long: 70000 bytes" + } + +} diff --git a/compiler/src/test/scala/org/scalajs/nscplugin/test/EnumerationInteropTest.scala b/compiler/src/test/scala/org/scalajs/nscplugin/test/EnumerationInteropTest.scala new file mode 100644 index 0000000000..f930632797 --- /dev/null +++ b/compiler/src/test/scala/org/scalajs/nscplugin/test/EnumerationInteropTest.scala @@ -0,0 +1,171 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin.test + +import org.scalajs.nscplugin.test.util._ + +import org.junit.Test + +class EnumerationInteropTest extends DirectTest with TestHelpers { + + @Test + def warnIfUnableToTransformValue(): Unit = { + + """ + class A extends Enumeration { + val a = { + println("oh, oh!") + Value + } + val b = { + println("oh, oh!") + Value(4) + } + } + """ hasWarns + """ + |newSource1.scala:5: warning: Couldn't transform call to Enumeration.Value. + |The resulting program is unlikely to function properly as this + |operation requires reflection. + | Value + | ^ + |newSource1.scala:9: warning: Couldn't transform call to Enumeration.Value. + |The resulting program is unlikely to function properly as this + |operation requires reflection. + | Value(4) + | ^ + """ + + } + + @Test + def warnIfNoNameVal(): Unit = { + + """ + class A extends Enumeration { + val a = new Val + val b = new Val(10) + } + """ hasWarns + """ + |newSource1.scala:3: warning: Calls to the non-string constructors of Enumeration.Val + |require reflection at runtime. The resulting + |program is unlikely to function properly. + | val a = new Val + | ^ + |newSource1.scala:4: warning: Calls to the non-string constructors of Enumeration.Val + |require reflection at runtime. The resulting + |program is unlikely to function properly. + | val b = new Val(10) + | ^ + """ + + } + + @Test + def warnIfNullValue(): Unit = { + + """ + class A extends Enumeration { + val a = Value(null) + val b = Value(10, null) + } + """ hasWarns + """ + |newSource1.scala:3: warning: Passing null as name to Enumeration.Value + |requires reflection at runtime. The resulting + |program is unlikely to function properly. + | val a = Value(null) + | ^ + |newSource1.scala:4: warning: Passing null as name to Enumeration.Value + |requires reflection at runtime. The resulting + |program is unlikely to function properly. + | val b = Value(10, null) + | ^ + """ + + } + + @Test + def warnIfNullNewVal(): Unit = { + + """ + class A extends Enumeration { + val a = new Val(null) + val b = new Val(10, null) + } + """ hasWarns + """ + |newSource1.scala:3: warning: Passing null as name to a constructor of Enumeration.Val + |requires reflection at runtime. The resulting + |program is unlikely to function properly. + | val a = new Val(null) + | ^ + |newSource1.scala:4: warning: Passing null as name to a constructor of Enumeration.Val + |requires reflection at runtime. The resulting + |program is unlikely to function properly. + | val b = new Val(10, null) + | ^ + """ + + } + + @Test + def warnIfExtNoNameVal(): Unit = { + + """ + class A extends Enumeration { + protected class Val1 extends Val + protected class Val2 extends Val(1) + } + """ hasWarns + """ + |newSource1.scala:3: warning: Calls to the non-string constructors of Enumeration.Val + |require reflection at runtime. The resulting + |program is unlikely to function properly. + | protected class Val1 extends Val + | ^ + |newSource1.scala:4: warning: Calls to the non-string constructors of Enumeration.Val + |require reflection at runtime. The resulting + |program is unlikely to function properly. + | protected class Val2 extends Val(1) + | ^ + """ + + } + + @Test + def warnIfExtNullNameVal(): Unit = { + + """ + class A extends Enumeration { + protected class Val1 extends Val(null) + protected class Val2 extends Val(1,null) + } + """ hasWarns + """ + |newSource1.scala:3: warning: Passing null as name to a constructor of Enumeration.Val + |requires reflection at runtime. The resulting + |program is unlikely to function properly. + | protected class Val1 extends Val(null) + | ^ + |newSource1.scala:4: warning: Passing null as name to a constructor of Enumeration.Val + |requires reflection at runtime. The resulting + |program is unlikely to function properly. + | protected class Val2 extends Val(1,null) + | ^ + """ + + } + +} diff --git a/compiler/src/test/scala/org/scalajs/nscplugin/test/GlobalExecutionContextNoWarnTest.scala b/compiler/src/test/scala/org/scalajs/nscplugin/test/GlobalExecutionContextNoWarnTest.scala new file mode 100644 index 0000000000..94decfd65a --- /dev/null +++ b/compiler/src/test/scala/org/scalajs/nscplugin/test/GlobalExecutionContextNoWarnTest.scala @@ -0,0 +1,47 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin.test + +import org.scalajs.nscplugin.test.util._ +import org.scalajs.nscplugin.test.util.VersionDependentUtils.scalaSupportsNoWarn + +import org.junit.Assume._ +import org.junit.Test + +class GlobalExecutionContextNoWarnTest extends DirectTest with TestHelpers { + + override def extraArgs: List[String] = + super.extraArgs ::: List("-P:scalajs:nowarnGlobalExecutionContext") + + @Test + def noWarnOnUsage: Unit = { + """ + import scala.concurrent.ExecutionContext.global + + object Enclosing { + global + } + """.hasNoWarns() + } + + @Test + def noWarnOnImplicitUsage: Unit = { + """ + import scala.concurrent.ExecutionContext.Implicits.global + + object Enclosing { + scala.concurrent.Future { } + } + """.hasNoWarns() + } +} diff --git a/compiler/src/test/scala/org/scalajs/nscplugin/test/GlobalExecutionContextWarnTest.scala b/compiler/src/test/scala/org/scalajs/nscplugin/test/GlobalExecutionContextWarnTest.scala new file mode 100644 index 0000000000..1fd1333eb1 --- /dev/null +++ b/compiler/src/test/scala/org/scalajs/nscplugin/test/GlobalExecutionContextWarnTest.scala @@ -0,0 +1,122 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin.test + +import org.scalajs.nscplugin.test.util._ +import org.scalajs.nscplugin.test.util.VersionDependentUtils.scalaSupportsNoWarn + +import org.junit.Assume._ +import org.junit.Test + +class GlobalExecutionContextWarnTest extends DirectTest with TestHelpers { + + @Test + def warnOnUsage: Unit = { + """ + import scala.concurrent.ExecutionContext.global + + object Enclosing { + global + } + """ hasWarns + """ + |newSource1.scala:5: warning: The global execution context in Scala.js is based on JS Promises (microtasks). + |Using it may prevent macrotasks (I/O, timers, UI rendering) from running reliably. + | + |Unfortunately, there is no way with ECMAScript only to implement a performant + |macrotask execution context (and hence Scala.js core does not contain one). + | + |We recommend you use: https://github.com/scala-js/scala-js-macrotask-executor + |Please refer to the README.md of that project for more details regarding + |microtask vs. macrotask execution contexts. + | + |If you do not care about macrotask fairness, you can silence this warning by: + |- Adding @nowarn("cat=other") (Scala >= 2.13.x only) + |- Setting the -P:scalajs:nowarnGlobalExecutionContext compiler option (Scala < 3.x.y only) + |- Using scala.scalajs.concurrent.JSExecutionContext.queue + | (the implementation of ExecutionContext.global in Scala.js) directly. + | + |If you do not care about performance, you can use + |scala.scalajs.concurrent.QueueExecutionContext.timeouts(). + |It is based on setTimeout which makes it fair but slow (due to clamping). + | + | global + | ^ + """ + } + + @Test + def warnOnImplicitUsage: Unit = { + """ + import scala.concurrent.ExecutionContext.Implicits.global + + object Enclosing { + scala.concurrent.Future { } + } + """ hasWarns + """ + |newSource1.scala:5: warning: The global execution context in Scala.js is based on JS Promises (microtasks). + |Using it may prevent macrotasks (I/O, timers, UI rendering) from running reliably. + | + |Unfortunately, there is no way with ECMAScript only to implement a performant + |macrotask execution context (and hence Scala.js core does not contain one). + | + |We recommend you use: https://github.com/scala-js/scala-js-macrotask-executor + |Please refer to the README.md of that project for more details regarding + |microtask vs. macrotask execution contexts. + | + |If you do not care about macrotask fairness, you can silence this warning by: + |- Adding @nowarn("cat=other") (Scala >= 2.13.x only) + |- Setting the -P:scalajs:nowarnGlobalExecutionContext compiler option (Scala < 3.x.y only) + |- Using scala.scalajs.concurrent.JSExecutionContext.queue + | (the implementation of ExecutionContext.global in Scala.js) directly. + | + |If you do not care about performance, you can use + |scala.scalajs.concurrent.QueueExecutionContext.timeouts(). + |It is based on setTimeout which makes it fair but slow (due to clamping). + | + | scala.concurrent.Future { } + | ^ + """ + } + + @Test + def noWarnIfSelectivelyDisabled: Unit = { + assumeTrue(scalaSupportsNoWarn) + + """ + import scala.annotation.nowarn + import scala.concurrent.ExecutionContext.global + + object Enclosing { + global: @nowarn("cat=other") + } + """.hasNoWarns() + } + + @Test + def noWarnQueue: Unit = { + /* Test that JSExecutionContext.queue does not warn for good measure. + * We explicitly say it doesn't so we want to notice if it does. + */ + + """ + import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue + + object Enclosing { + scala.concurrent.Future { } + } + """.hasNoWarns() + } + +} diff --git a/compiler/src/test/scala/org/scalajs/core/compiler/test/InternalAnnotationsTest.scala b/compiler/src/test/scala/org/scalajs/nscplugin/test/InternalAnnotationsTest.scala similarity index 82% rename from compiler/src/test/scala/org/scalajs/core/compiler/test/InternalAnnotationsTest.scala rename to compiler/src/test/scala/org/scalajs/nscplugin/test/InternalAnnotationsTest.scala index 22cff79e5d..7e553d378f 100644 --- a/compiler/src/test/scala/org/scalajs/core/compiler/test/InternalAnnotationsTest.scala +++ b/compiler/src/test/scala/org/scalajs/nscplugin/test/InternalAnnotationsTest.scala @@ -10,9 +10,9 @@ * additional information regarding copyright ownership. */ -package org.scalajs.core.compiler.test +package org.scalajs.nscplugin.test -import org.scalajs.core.compiler.test.util._ +import org.scalajs.nscplugin.test.util._ import org.junit._ @@ -24,32 +24,22 @@ class InternalAnnotationsTest extends DirectTest with TestHelpers { "import scala.scalajs.js, js.annotation._, js.annotation.internal._" @Test - def exposedJSMember: Unit = { + def exposedJSMember(): Unit = { test("ExposedJSMember") } @Test - def jsFullName: Unit = { - test("JSFullName(\"abc\")") + def jsType(): Unit = { + test("JSType") } @Test - def rawJSType: Unit = { - test("RawJSType") - } - - @Test - def sjsDefinedAnonymousClass: Unit = { - test("SJSDefinedAnonymousClass") - } - - @Test - def jsOptional: Unit = { - test("JSOptional", "scala.scalajs.js.annotation.internal.JSOptional") + def jsOptional(): Unit = { + test("JSOptional") } private def test(annotation: String): Unit = - test(annotation, s"scala.scalajs.js.annotation.$annotation") + test(annotation, s"scala.scalajs.js.annotation.internal.$annotation") private def test(annotation: String, annotFullName: String): Unit = { s""" diff --git a/compiler/src/test/scala/org/scalajs/nscplugin/test/JSDynamicLiteralTest.scala b/compiler/src/test/scala/org/scalajs/nscplugin/test/JSDynamicLiteralTest.scala new file mode 100644 index 0000000000..df493ce0ff --- /dev/null +++ b/compiler/src/test/scala/org/scalajs/nscplugin/test/JSDynamicLiteralTest.scala @@ -0,0 +1,284 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin.test + +import org.scalajs.nscplugin.test.util._ +import org.junit.Test + +// scalastyle:off line.size.limit + +class JSDynamicLiteralTest extends DirectTest with TestHelpers { + + override def preamble: String = + """import scala.scalajs.js.Dynamic.{ literal => lit } + """ + + @Test + def callApplyOnly(): Unit = { + + // selectDynamic (with any name) + expr""" + lit.helloWorld + """ hasErrors + """ + |newSource1.scala:3: error: value selectDynamic is not a member of object scalajs.js.Dynamic.literal + |error after rewriting to scala.scalajs.js.Dynamic.literal.("helloWorld") + |possible cause: maybe a wrong Dynamic method signature? + | lit.helloWorld + | ^ + """ + + // applyDynamicNamed with wrong method name + expr""" + lit.helloWorld(a = "a") + """ hasErrors + """ + |newSource1.scala:3: error: js.Dynamic.literal does not have a method named helloWorld + | lit.helloWorld(a = "a") + | ^ + """ + + // applyDynamic with wrong method name + expr""" + lit.helloWorld("a" -> "a") + """ hasErrors + """ + |newSource1.scala:3: error: js.Dynamic.literal does not have a method named helloWorld + | lit.helloWorld("a" -> "a") + | ^ + """ + + } + + @Test + def goodTypesOnly(): Unit = { + + // Bad value type (applyDynamic) + """ + class A { + val x = new Object() + def foo = lit("a" -> x) + } + """ hasErrors + """ + |newSource1.scala:5: error: type mismatch; + | found : Object + | required: scala.scalajs.js.Any + | def foo = lit("a" -> x) + | ^ + """ + + // Bad key type (applyDynamic) + """ + class A { + val x = Seq() + def foo = lit(x -> "a") + } + """ hasErrors + """ + |newSource1.scala:5: error: type mismatch; + | found : (Seq[Nothing], String) + | required: (String, scala.scalajs.js.Any) + | def foo = lit(x -> "a") + | ^ + """ + + // Bad value type (applyDynamicNamed) + """ + class A { + val x = new Object() + def foo = lit(a = x) + } + """ hasErrors + """ + |newSource1.scala:5: error: type mismatch; + | found : Object + | required: scala.scalajs.js.Any + |error after rewriting to scala.scalajs.js.Dynamic.literal.applyDynamicNamed("apply")(scala.Tuple2("a", x)) + |possible cause: maybe a wrong Dynamic method signature? + | def foo = lit(a = x) + | ^ + """ + + } + + @Test + def noNonLiteralMethodName(): Unit = { + + // applyDynamicNamed + """ + class A { + val x = "string" + def foo = lit.applyDynamicNamed(x)() + } + """ hasErrors + """ + |newSource1.scala:5: error: js.Dynamic.literal.applyDynamicNamed may not be called directly + | def foo = lit.applyDynamicNamed(x)() + | ^ + """ + + // applyDynamic + """ + class A { + val x = "string" + def foo = lit.applyDynamic(x)() + } + """ hasErrors + """ + |newSource1.scala:5: error: js.Dynamic.literal.applyDynamic may not be called directly + | def foo = lit.applyDynamic(x)() + | ^ + """ + + } + + @Test + def keyDuplicationWarning(): Unit = { + // detects duplicate named keys + expr""" + lit(a = "1", b = "2", a = "3") + """ hasWarns + """ + |newSource1.scala:3: warning: Duplicate property "a" shadows a previously defined one + | lit(a = "1", b = "2", a = "3") + | ^ + """ + + // detects duplicate named keys + expr""" + lit(aaa = "1", b = "2", aaa = "3") + """ hasWarns + """ + |newSource1.scala:3: warning: Duplicate property "aaa" shadows a previously defined one + | lit(aaa = "1", b = "2", aaa = "3") + | ^ + """ + + // detects duplicate named keys + expr""" + lit(aaa = "1", + bb = "2", + bb = "3") + """ hasWarns + """ + |newSource1.scala:5: warning: Duplicate property "bb" shadows a previously defined one + | bb = "3") + | ^ + """ + + // detects duplicate named keys + expr""" + lit(aaa = "1", + b = "2", + aaa = "3") + """ hasWarns + """ + |newSource1.scala:5: warning: Duplicate property "aaa" shadows a previously defined one + | aaa = "3") + | ^ + """ + + // detects triplicated named keys + expr""" + lit(a = "1", a = "2", a = "3") + """ hasWarns + """ + |newSource1.scala:3: warning: Duplicate property "a" shadows a previously defined one + | lit(a = "1", a = "2", a = "3") + | ^ + |newSource1.scala:3: warning: Duplicate property "a" shadows a previously defined one + | lit(a = "1", a = "2", a = "3") + | ^ + """ + + // detects two different duplicates named keys + expr""" + lit(a = "1", b = "2", a = "3", b = "4", c = "5", c = "6", c = "7") + """ hasWarns + """ + |newSource1.scala:3: warning: Duplicate property "a" shadows a previously defined one + | lit(a = "1", b = "2", a = "3", b = "4", c = "5", c = "6", c = "7") + | ^ + |newSource1.scala:3: warning: Duplicate property "b" shadows a previously defined one + | lit(a = "1", b = "2", a = "3", b = "4", c = "5", c = "6", c = "7") + | ^ + |newSource1.scala:3: warning: Duplicate property "c" shadows a previously defined one + | lit(a = "1", b = "2", a = "3", b = "4", c = "5", c = "6", c = "7") + | ^ + |newSource1.scala:3: warning: Duplicate property "c" shadows a previously defined one + | lit(a = "1", b = "2", a = "3", b = "4", c = "5", c = "6", c = "7") + | ^ + """ + + // detects duplicate keys when represented with arrows + expr""" + lit("a" -> "1", "b" -> "2", "a" -> "3") + """ hasWarns + """ + |newSource1.scala:3: warning: Duplicate property "a" shadows a previously defined one + | lit("a" -> "1", "b" -> "2", "a" -> "3") + | ^ + """ + + // detects duplicate keys when represented with tuples + expr""" + lit(("a", "1"), ("b", "2"), ("a", "3")) + """ hasWarns + """ + |newSource1.scala:3: warning: Duplicate property "a" shadows a previously defined one + | lit(("a", "1"), ("b", "2"), ("a", "3")) + | ^ + """ + + // detects duplicate keys when represented with mixed tuples and arrows + expr""" + lit("a" -> "1", ("b", "2"), ("a", "3")) + """ hasWarns + """ + |newSource1.scala:3: warning: Duplicate property "a" shadows a previously defined one + | lit("a" -> "1", ("b", "2"), ("a", "3")) + | ^ + """ + + // should not warn if the key is not literal + expr""" + val a = "x" + lit("a" -> "1", a -> "2", a -> "3") + """.hasNoWarns() + + // should not warn if the key/value pairs are not literal + """ + class A { + val tup = "x" -> lit() + def foo = lit(tup, tup) + } + """.hasNoWarns() + + // should warn only for the literal keys when in + // the presence of non literal keys + """ + class A { + val b = "b" + val tup = b -> lit() + lit("a" -> "2", tup, ("a", "3"), b -> "5", tup, b -> "6") + } + """ hasWarns + """ + |newSource1.scala:6: warning: Duplicate property "a" shadows a previously defined one + | lit("a" -> "2", tup, ("a", "3"), b -> "5", tup, b -> "6") + | ^ + """ + } + +} diff --git a/compiler/src/test/scala/org/scalajs/core/compiler/test/JSExportASTTest.scala b/compiler/src/test/scala/org/scalajs/nscplugin/test/JSExportASTTest.scala similarity index 78% rename from compiler/src/test/scala/org/scalajs/core/compiler/test/JSExportASTTest.scala rename to compiler/src/test/scala/org/scalajs/nscplugin/test/JSExportASTTest.scala index 5b356970e2..01fe141a4a 100644 --- a/compiler/src/test/scala/org/scalajs/core/compiler/test/JSExportASTTest.scala +++ b/compiler/src/test/scala/org/scalajs/nscplugin/test/JSExportASTTest.scala @@ -10,19 +10,19 @@ * additional information regarding copyright ownership. */ -package org.scalajs.core.compiler.test +package org.scalajs.nscplugin.test import util._ import org.junit.Test import org.junit.Assert._ -import org.scalajs.core.ir.{Trees => js} +import org.scalajs.ir.{Trees => js} class JSExportASTTest extends JSASTTest { @Test - def inheritExportMethods: Unit = { + def inheritExportMethods(): Unit = { """ import scala.scalajs.js.annotation.JSExport @@ -36,7 +36,7 @@ class JSExportASTTest extends JSASTTest { override def foo = 2 } """.hasExactly(1, "definitions of property `foo`") { - case js.PropertyDef(_, js.StringLiteral("foo"), _, _) => + case js.JSPropertyDef(_, js.StringLiteral("foo"), _, _) => } } diff --git a/compiler/src/test/scala/org/scalajs/nscplugin/test/JSExportTest.scala b/compiler/src/test/scala/org/scalajs/nscplugin/test/JSExportTest.scala new file mode 100644 index 0000000000..790edb15b6 --- /dev/null +++ b/compiler/src/test/scala/org/scalajs/nscplugin/test/JSExportTest.scala @@ -0,0 +1,1926 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin.test + +import org.scalajs.nscplugin.test.util._ +import org.scalajs.nscplugin.test.util.VersionDependentUtils.methodSig + +import org.junit.Assume._ +import org.junit.Test + +// scalastyle:off line.size.limit + +class JSExportTest extends DirectTest with TestHelpers { + + override def extraArgs: List[String] = + super.extraArgs ::: List("-deprecation") + + override def preamble: String = + """import scala.scalajs.js, js.annotation._ + """ + + @Test + def warnOnDuplicateExport(): Unit = { + """ + class A { + @JSExport + @JSExport + def a = 1 + } + """ hasWarns + """ + |newSource1.scala:6: warning: Found duplicate @JSExport + | def a = 1 + | ^ + """ + + """ + class A { + @JSExport + @JSExport("a") + def a = 1 + } + """ hasWarns + """ + |newSource1.scala:6: warning: Found duplicate @JSExport + | def a = 1 + | ^ + """ + + """ + class A { + @JSExport("a") + @JSExport("a") + def a = 1 + } + """ hasWarns + """ + |newSource1.scala:6: warning: Found duplicate @JSExport + | def a = 1 + | ^ + """ + + // special case for @JSExportAll and 2 or more @JSExport("apply") + // since @JSExportAll and single @JSExport("apply") should not be warned (see other tests) + """ + @JSExportAll + class A { + @JSExport("apply") + @JSExport("apply") + def apply(): Int = 1 + } + """ hasWarns + """ + |newSource1.scala:7: warning: Found duplicate @JSExport + | def apply(): Int = 1 + | ^ + """ + + """ + @JSExportAll + class A { + @JSExport + def a = 1 + } + """ hasWarns + """ + |newSource1.scala:6: warning: Found duplicate @JSExport + | def a = 1 + | ^ + """ + } + + @Test + def noWarnOnUniqueExplicitName(): Unit = { + """ + class A { + @JSExport("a") + @JSExport("b") + def c = 1 + } + """.hasNoWarns() + } + + @Test + def noJSExportClass(): Unit = { + """ + @JSExport + class A + + @JSExport("Foo") + class B + """ hasErrors + """ + |newSource1.scala:3: error: @JSExport is forbidden on objects and classes. Use @JSExportTopLevel instead. + | @JSExport + | ^ + |newSource1.scala:6: error: @JSExport is forbidden on objects and classes. Use @JSExportTopLevel instead. + | @JSExport("Foo") + | ^ + """ + } + + @Test + def noJSExportObject(): Unit = { + """ + @JSExport + object A + + @JSExport("Foo") + object B + """ hasErrors + """ + |newSource1.scala:3: error: @JSExport is forbidden on objects and classes. Use @JSExportTopLevel instead. + | @JSExport + | ^ + |newSource1.scala:6: error: @JSExport is forbidden on objects and classes. Use @JSExportTopLevel instead. + | @JSExport("Foo") + | ^ + """ + } + + @Test + def noDoubleUnderscoreExport(): Unit = { + """ + class A { + @JSExport(name = "__") + def foo = 1 + + @JSExport + def bar__(x: Int) = x + } + """ hasErrors + """ + |newSource1.scala:4: error: An exported name may not contain a double underscore (`__`) + | @JSExport(name = "__") + | ^ + |newSource1.scala:8: error: An exported name may not contain a double underscore (`__`) + | def bar__(x: Int) = x + | ^ + """ + } + + @Test + def doubleUnderscoreOKInTopLevelExport(): Unit = { + """ + @JSExportTopLevel("__A") + class A + + @JSExportTopLevel("__B") + object B + + object Container { + @JSExportTopLevel("__c") + def c(): Int = 4 + + @JSExportTopLevel("__d") + val d: Boolean = true + } + """.hasNoWarns() + } + + @Test + def noConflictingExport(): Unit = { + """ + class Confl { + @JSExport("value") + def hello = "foo" + + @JSExport("value") + def world = "bar" + } + """ hasErrors + """ + |newSource1.scala:7: error: double definition: + |def $js$exported$prop$value: Any at line 4 and + |def $js$exported$prop$value: Any at line 7 + |have same type + | @JSExport("value") + | ^ + """ + + """ + class Confl { + class Box[T](val x: T) + + @JSExport + def ub(x: Box[String]): String = x.x + @JSExport + def ub(x: Box[Int]): Int = x.x + } + """ hasErrors + s""" + |newSource1.scala:8: error: double definition: + |def ${"$js$exported$meth$ub"}(x: Confl.this.Box[String]): Any at line 6 and + |def ${"$js$exported$meth$ub"}(x: Confl.this.Box[Int]): Any at line 8 + |have same type after erasure: ${methodSig("(x: Confl#Box)", "Object")} + | @JSExport + | ^ + """ + + """ + class Confl { + @JSExport + def rtType(x: js.Any) = x + + @JSExport + def rtType(x: js.Dynamic) = x + } + """ hasErrors + s""" + |newSource1.scala:7: error: Cannot disambiguate overloads for exported method rtType with types + | ${methodSig("(x: scala.scalajs.js.Any)", "Object")} + | ${methodSig("(x: scala.scalajs.js.Dynamic)", "Object")} + | @JSExport + | ^ + """ + + """ + class Confl { + @JSExport + def foo(x: Int)(ys: Int*) = x + + @JSExport + def foo(x: Int*) = x + } + """ hasErrors + s""" + |newSource1.scala:7: error: Cannot disambiguate overloads for exported method foo with types + | ${methodSig("(x: Int, ys: Seq)", "Object")} + | ${methodSig("(x: Seq)", "Object")} + | @JSExport + | ^ + """ + + """ + class Confl { + @JSExport + def foo(x: Int = 1) = x + @JSExport + def foo(x: String*) = x + } + """ hasErrors + s""" + |newSource1.scala:6: error: Cannot disambiguate overloads for exported method foo with types + | ${methodSig("(x: Int)", "Object")} + | ${methodSig("(x: Seq)", "Object")} + | @JSExport + | ^ + """ + + """ + class Confl { + @JSExport + def foo(x: Double, y: String)(z: Int = 1) = x + @JSExport + def foo(x: Double, y: String)(z: String*) = x + } + """ hasErrors + s""" + |newSource1.scala:6: error: Cannot disambiguate overloads for exported method foo with types + | ${methodSig("(x: Double, y: String, z: Int)", "Object")} + | ${methodSig("(x: Double, y: String, z: Seq)", "Object")} + | @JSExport + | ^ + """ + + """ + class A { + @JSExport + def a(x: scala.scalajs.js.Any) = 1 + + @JSExport + def a(x: Any) = 2 + } + """ hasErrors + s""" + |newSource1.scala:7: error: Cannot disambiguate overloads for exported method a with types + | ${methodSig("(x: Object)", "Object")} + | ${methodSig("(x: scala.scalajs.js.Any)", "Object")} + | @JSExport + | ^ + """ + + } + + @Test + def noExportLocal(): Unit = { + // Local class + """ + class A { + def method = { + @JSExport + class A + + @JSExport + class B extends js.Object + } + } + """ hasErrors + """ + |newSource1.scala:5: error: @JSExport is forbidden on objects and classes. Use @JSExportTopLevel instead. + | @JSExport + | ^ + |newSource1.scala:8: error: @JSExport is forbidden on objects and classes. Use @JSExportTopLevel instead. + | @JSExport + | ^ + """ + + // Local object + """ + class A { + def method = { + @JSExport + object A + + @JSExport + object B extends js.Object + } + } + """ hasErrors + """ + |newSource1.scala:5: error: @JSExport is forbidden on objects and classes. Use @JSExportTopLevel instead. + | @JSExport + | ^ + |newSource1.scala:8: error: @JSExport is forbidden on objects and classes. Use @JSExportTopLevel instead. + | @JSExport + | ^ + """ + + // Local method + """ + class A { + def method = { + @JSExport + def foo = 1 + } + } + """ hasErrors + """ + |newSource1.scala:5: error: You may not export a local definition + | @JSExport + | ^ + """ + + // Local val + """ + class A { + def method = { + @JSExport + val x = 1 + } + } + """ hasErrors + """ + |newSource1.scala:5: error: You may not export a local definition + | @JSExport + | ^ + """ + + // Local var + """ + class A { + def method = { + @JSExport + var x = 1 + } + } + """ hasErrors + """ + |newSource1.scala:5: error: You may not export a local definition + | @JSExport + | ^ + """ + + } + + @Test + def noMiddleVarArg(): Unit = { + + """ + class A { + @JSExport + def method(xs: Int*)(ys: String) = 1 + } + """ hasErrors + """ + |newSource1.scala:4: error: In an exported method, a *-parameter must come last (through all parameter lists) + | @JSExport + | ^ + """ + + } + + @Test + def noMiddleDefaultParam(): Unit = { + + """ + class A { + @JSExport + def method(x: Int = 1)(y: String) = 1 + } + """ hasErrors + """ + |newSource1.scala:4: error: In an exported method, all parameters with defaults must be at the end + | @JSExport + | ^ + """ + + } + + @Test + def noExportAbstractClass(): Unit = { + + """ + @JSExportTopLevel("A") + abstract class A + + abstract class B(x: Int) { + @JSExportTopLevel("B") + def this() = this(5) + } + """ hasErrors + """ + |newSource1.scala:3: error: You may not export an abstract class + | @JSExportTopLevel("A") + | ^ + |newSource1.scala:7: error: You may not export an abstract class + | @JSExportTopLevel("B") + | ^ + """ + + } + + @Test + def noJSExportOnTrait(): Unit = { + + """ + @JSExport + trait Test + + @JSExport + trait Test2 extends js.Object + + @JSExport + @js.native + trait Test3 extends js.Object + """ hasErrors + """ + |newSource1.scala:3: error: You may not export a trait + | @JSExport + | ^ + |newSource1.scala:6: error: You may not export a trait + | @JSExport + | ^ + |newSource1.scala:9: error: You may not export a trait + | @JSExport + | ^ + """ + + } + + @Test + def noExportNonPublicClassOrObject(): Unit = { + + """ + @JSExportTopLevel("A") + private class A + + @JSExportTopLevel("B") + protected[this] class B + + @JSExportTopLevel("C") + private class C extends js.Object + + @JSExportTopLevel("D") + protected[this] class D extends js.Object + """ hasErrors + """ + |newSource1.scala:3: error: You may only export public and protected classes + | @JSExportTopLevel("A") + | ^ + |newSource1.scala:6: error: You may only export public and protected classes + | @JSExportTopLevel("B") + | ^ + |newSource1.scala:9: error: You may only export public and protected classes + | @JSExportTopLevel("C") + | ^ + |newSource1.scala:12: error: You may only export public and protected classes + | @JSExportTopLevel("D") + | ^ + """ + + """ + @JSExportTopLevel("A") + private object A + + @JSExportTopLevel("B") + protected[this] object B + + @JSExportTopLevel("C") + private object C extends js.Object + + @JSExportTopLevel("D") + protected[this] object D extends js.Object + """ hasErrors + """ + |newSource1.scala:3: error: You may only export public and protected objects + | @JSExportTopLevel("A") + | ^ + |newSource1.scala:6: error: You may only export public and protected objects + | @JSExportTopLevel("B") + | ^ + |newSource1.scala:9: error: You may only export public and protected objects + | @JSExportTopLevel("C") + | ^ + |newSource1.scala:12: error: You may only export public and protected objects + | @JSExportTopLevel("D") + | ^ + """ + + } + + @Test + def noExportNonPublicMember(): Unit = { + + """ + class A { + @JSExport + private def foo = 1 + + @JSExport + protected[this] def bar = 2 + } + """ hasErrors + """ + |newSource1.scala:4: error: You may only export public and protected methods + | @JSExport + | ^ + |newSource1.scala:7: error: You may only export public and protected methods + | @JSExport + | ^ + """ + + } + + @Test + def noExportNestedClass(): Unit = { + + """ + class A { + @JSExport + class Nested { + @JSExport + def this(x: Int) = this() + } + + @JSExport + class Nested2 extends js.Object + } + """ hasErrors + """ + |newSource1.scala:4: error: @JSExport is forbidden on objects and classes. Use @JSExportTopLevel instead. + | @JSExport + | ^ + |newSource1.scala:6: error: @JSExport is forbidden on objects and classes. Use @JSExportTopLevel instead. + | @JSExport + | ^ + |newSource1.scala:10: error: @JSExport is forbidden on objects and classes. Use @JSExportTopLevel instead. + | @JSExport + | ^ + """ + + } + + @Test + def noNestedExportClass: Unit = { + + """ + object A { + @JSExport + class Nested { + @JSExport + def this(x: Int) = this + } + + @JSExport + class Nested2 extends js.Object + } + """ hasErrors + """ + + |newSource1.scala:4: error: @JSExport is forbidden on objects and classes. Use @JSExportTopLevel instead. + | @JSExport + | ^ + |newSource1.scala:6: error: @JSExport is forbidden on objects and classes. Use @JSExportTopLevel instead. + | @JSExport + | ^ + |newSource1.scala:10: error: @JSExport is forbidden on objects and classes. Use @JSExportTopLevel instead. + | @JSExport + | ^ + """ + + } + + @Test + def noNestedExportObject(): Unit = { + + """ + object A { + @JSExport + object Nested + + @JSExport + object Nested2 extends js.Object + } + """ hasErrors + """ + |newSource1.scala:4: error: @JSExport is forbidden on objects and classes. Use @JSExportTopLevel instead. + | @JSExport + | ^ + |newSource1.scala:7: error: @JSExport is forbidden on objects and classes. Use @JSExportTopLevel instead. + | @JSExport + | ^ + """ + + } + + @Test + def noExportTopLevelNestedObject(): Unit = { + + """ + class A { + @JSExportTopLevel("Nested") + object Nested + + @JSExportTopLevel("Nested2") + object Nested2 extends js.Object + } + """ hasErrors + """ + |newSource1.scala:4: error: You may not export a nested object + | @JSExportTopLevel("Nested") + | ^ + |newSource1.scala:7: error: You may not export a nested object + | @JSExportTopLevel("Nested2") + | ^ + """ + + } + + @Test + def noExportJSNative(): Unit = { + + """ + import scala.scalajs.js + + @JSExportTopLevel("A") + @js.native + @JSGlobal("Dummy") + object A extends js.Object + """ hasErrors + """ + |newSource1.scala:5: error: You may not export a native JS object + | @JSExportTopLevel("A") + | ^ + """ + + """ + import scala.scalajs.js + + @JSExportTopLevel("A") + @js.native + trait A extends js.Object + """ hasErrors + """ + |newSource1.scala:5: error: You may not export a trait + | @JSExportTopLevel("A") + | ^ + """ + + """ + import scala.scalajs.js + + @JSExportTopLevel("A") + @js.native + @JSGlobal("Dummy") + class A extends js.Object { + @JSExportTopLevel("A") + def this(x: Int) = this() + } + """ hasErrors + """ + |newSource1.scala:5: error: You may not export a native JS class + | @JSExportTopLevel("A") + | ^ + |newSource1.scala:9: error: You may not export a constructor of a subclass of js.Any + | @JSExportTopLevel("A") + | ^ + """ + + } + + @Test + def noExportJSMember(): Unit = { + + """ + import scala.scalajs.js + + @js.native + @JSGlobal("Dummy") + class A extends js.Object { + @JSExport + def foo: Int = js.native + } + """ hasErrors + """ + |newSource1.scala:8: error: You may not export a method of a subclass of js.Any + | @JSExport + | ^ + """ + + """ + import scala.scalajs.js + + class A extends js.Object { + @JSExport + def foo: Int = js.native + } + """ hasErrors + """ + |newSource1.scala:6: error: You may not export a method of a subclass of js.Any + | @JSExport + | ^ + """ + + } + + @Test + def noBadSetterType(): Unit = { + + // Bad param list + """ + class A { + @JSExport + def foo_=(x: Int, y: Int) = () + } + """ hasErrors + """ + |newSource1.scala:4: error: Exported setters must have exactly one argument + | @JSExport + | ^ + """ + + // Bad return type + """ + class A { + @JSExport + def foo_=(x: Int) = "string" + } + """ hasErrors + """ + |newSource1.scala:4: error: Exported setters must return Unit + | @JSExport + | ^ + """ + + // Varargs + """ + class A { + @JSExport + def foo_=(x: Int*) = () + } + """ hasErrors + """ + |newSource1.scala:4: error: Exported setters may not have repeated params + | @JSExport + | ^ + """ + + // Default arguments + """ + class A { + @JSExport + def foo_=(x: Int = 1) = () + } + """ hasErrors + """ + |newSource1.scala:4: error: Exported setters may not have default params + | @JSExport + | ^ + """ + + } + + @Test + def noBadToStringExport(): Unit = { + + """ + class A { + @JSExport("toString") + def a(): Int = 5 + } + """ hasErrors + """ + |newSource1.scala:4: error: You may not export a zero-argument method named other than 'toString' under the name 'toString' + | @JSExport("toString") + | ^ + """ + + } + + @Test + def noBadNameExportAll(): Unit = { + + """ + @JSExportAll + class A { + val __f = 1 + def a_= = 2 + } + """ hasErrors + """ + |newSource1.scala:5: error: An exported name may not contain a double underscore (`__`) + | val __f = 1 + | ^ + |newSource1.scala:3: error: Exported setters must return Unit + | @JSExportAll + | ^ + """ + + } + + @Test + def noConflictingMethodAndProperty(): Unit = { + + // Basic case + """ + class A { + @JSExport("a") + def bar() = 2 + + @JSExport("a") + val foo = 1 + } + """ hasErrors + """ + |newSource1.scala:4: error: Exported property a conflicts with A.$js$exported$meth$a + | @JSExport("a") + | ^ + |newSource1.scala:7: error: Exported method a conflicts with A.$js$exported$prop$a + | @JSExport("a") + | ^ + """ + + // Inherited case + """ + class A { + @JSExport("a") + def bar() = 2 + } + + class B extends A { + @JSExport("a") + def foo_=(x: Int): Unit = () + + @JSExport("a") + val foo = 1 + } + """ hasErrors + """ + |newSource1.scala:4: error: Exported property a conflicts with A.$js$exported$meth$a + | @JSExport("a") + | ^ + """ + + } + + @Test + def gracefulDoubleDefaultFail(): Unit = { + // This used to blow up (i.e. not just fail), because PrepJSExports asked + // for the symbol of the default parameter getter of [[y]], and asserted its + // not overloaded. Since the Scala compiler only fails later on this, the + // assert got triggered and made the compiler crash + """ + class A { + @JSExport + def foo(x: String, y: String = "hello") = x + def foo(x: Int, y: String = "bar") = x + } + """ hasErrors + """ + |newSource1.scala:3: error: in class A, multiple overloaded alternatives of method foo define default arguments. + | class A { + | ^ + """ + } + + @Test + def noNonLiteralExportNames(): Unit = { + + """ + object A { + val a = "Hello" + final val b = "World" + } + + class B { + @JSExport(A.a) + def foo = 1 + @JSExport(A.b) + def bar = 1 + } + """ hasErrors + """ + |newSource1.scala:9: error: The argument to JSExport must be a literal string + | @JSExport(A.a) + | ^ + """ + + } + + @Test + def noNonLiteralModuleID(): Unit = { + + """ + object A { + val a = "Hello" + final val b = "World" + } + + object B { + @JSExportTopLevel("foo", A.a) + def foo() = 1 + @JSExportTopLevel("foo", A.b) + def bar() = 1 + } + """ hasErrors + """ + |newSource1.scala:9: error: moduleID must be a literal string + | @JSExportTopLevel("foo", A.a) + | ^ + """ + + } + + @Test + def noExportImplicitApply(): Unit = { + + """ + class A { + @JSExport + def apply(): Int = 1 + } + """ hasErrors + """ + |newSource1.scala:4: error: A member cannot be exported to function application. Add @JSExport("apply") to export under the name apply. + | @JSExport + | ^ + """ + + """ + @JSExportAll + class A { + def apply(): Int = 1 + } + """ hasErrors + """ + |newSource1.scala:5: error: A member cannot be exported to function application. Add @JSExport("apply") to export under the name apply. + | def apply(): Int = 1 + | ^ + """ + + """ + @JSExportAll + class A { + @JSExport("foo") + def apply(): Int = 1 + } + """ hasErrors + """ + |newSource1.scala:6: error: A member cannot be exported to function application. Add @JSExport("apply") to export under the name apply. + | def apply(): Int = 1 + | ^ + """ + + """ + @JSExportAll + class A { + @JSExport("apply") + def apply(): Int = 1 + } + """.hasNoWarns() + + } + + @Test + def exportObjectAsToString(): Unit = { + + """ + @JSExportTopLevel("toString") + object ExportAsToString + """.succeeds() + + } + + @Test + def noExportTopLevelTrait(): Unit = { + """ + @JSExportTopLevel("foo") + trait A + + @JSExportTopLevel("bar") + trait B extends js.Object + """ hasErrors + """ + |newSource1.scala:3: error: You may not export a trait + | @JSExportTopLevel("foo") + | ^ + |newSource1.scala:6: error: You may not export a trait + | @JSExportTopLevel("bar") + | ^ + """ + + """ + object Container { + @JSExportTopLevel("foo") + trait A + + @JSExportTopLevel("bar") + trait B extends js.Object + } + """ hasErrors + """ + |newSource1.scala:4: error: You may not export a trait + | @JSExportTopLevel("foo") + | ^ + |newSource1.scala:7: error: You may not export a trait + | @JSExportTopLevel("bar") + | ^ + """ + } + + @Test + def noExportTopLevelLazyVal(): Unit = { + """ + object A { + @JSExportTopLevel("foo") + lazy val a: Int = 1 + } + """ hasErrors + """ + |newSource1.scala:4: error: You may not export a lazy val to the top level + | @JSExportTopLevel("foo") + | ^ + """ + } + + @Test + def noExportTopLevelInvalidJSIdentifier(): Unit = { + """ + @JSExportTopLevel("not-a-valid-JS-identifier-1") + object A + + @JSExportTopLevel("not-a-valid-JS-identifier-2") + class B + + object C { + @JSExportTopLevel("not-a-valid-JS-identifier-3") + val a: Int = 1 + + @JSExportTopLevel("not-a-valid-JS-identifier-4") + var b: Int = 1 + + @JSExportTopLevel("not-a-valid-JS-identifier-5") + def c(): Int = 1 + } + + @JSExportTopLevel("") + object D + """ hasErrors + """ + |newSource1.scala:3: error: The top-level export name must be a valid JavaScript identifier name + | @JSExportTopLevel("not-a-valid-JS-identifier-1") + | ^ + |newSource1.scala:6: error: The top-level export name must be a valid JavaScript identifier name + | @JSExportTopLevel("not-a-valid-JS-identifier-2") + | ^ + |newSource1.scala:10: error: The top-level export name must be a valid JavaScript identifier name + | @JSExportTopLevel("not-a-valid-JS-identifier-3") + | ^ + |newSource1.scala:13: error: The top-level export name must be a valid JavaScript identifier name + | @JSExportTopLevel("not-a-valid-JS-identifier-4") + | ^ + |newSource1.scala:16: error: The top-level export name must be a valid JavaScript identifier name + | @JSExportTopLevel("not-a-valid-JS-identifier-5") + | ^ + |newSource1.scala:20: error: The top-level export name must be a valid JavaScript identifier name + | @JSExportTopLevel("") + | ^ + """ + } + + @Test + def noExportTopLevelNamespaced(): Unit = { + """ + @JSExportTopLevel("namespaced.export1") + object A + @JSExportTopLevel("namespaced.export2") + class B + object C { + @JSExportTopLevel("namespaced.export3") + val a: Int = 1 + @JSExportTopLevel("namespaced.export4") + var b: Int = 1 + @JSExportTopLevel("namespaced.export5") + def c(): Int = 1 + } + """ hasErrors + """ + |newSource1.scala:3: error: The top-level export name must be a valid JavaScript identifier name + | @JSExportTopLevel("namespaced.export1") + | ^ + |newSource1.scala:5: error: The top-level export name must be a valid JavaScript identifier name + | @JSExportTopLevel("namespaced.export2") + | ^ + |newSource1.scala:8: error: The top-level export name must be a valid JavaScript identifier name + | @JSExportTopLevel("namespaced.export3") + | ^ + |newSource1.scala:10: error: The top-level export name must be a valid JavaScript identifier name + | @JSExportTopLevel("namespaced.export4") + | ^ + |newSource1.scala:12: error: The top-level export name must be a valid JavaScript identifier name + | @JSExportTopLevel("namespaced.export5") + | ^ + """ + } + + @Test + def noExportTopLevelGetter(): Unit = { + """ + object A { + @JSExportTopLevel("foo") + def a: Int = 1 + } + """ hasErrors + """ + |newSource1.scala:4: error: You may not export a getter or a setter to the top level + | @JSExportTopLevel("foo") + | ^ + """ + } + + @Test + def noExportTopLevelSetter(): Unit = { + """ + object A { + @JSExportTopLevel("foo") + def a_=(x: Int): Unit = () + } + """ hasErrors + """ + |newSource1.scala:4: error: You may not export a getter or a setter to the top level + | @JSExportTopLevel("foo") + | ^ + """ + } + + @Test + def noExportTopLevelFieldsWithSameName(): Unit = { + """ + object A { + @JSExportTopLevel("foo") + val a: Int = 1 + + @JSExportTopLevel("foo") + var b: Int = 1 + } + """ hasErrors + """ + |newSource1.scala:4: error: export overload conflicts with export of variable b: a field may not share its exported name with another export + | @JSExportTopLevel("foo") + | ^ + """ + } + + @Test + def noExportTopLevelFieldsAndMethodsWithSameName(): Unit = { + """ + object A { + @JSExportTopLevel("foo") + val a: Int = 1 + + @JSExportTopLevel("foo") + def b(x: Int): Int = x + 1 + } + """ hasErrors + """ + |newSource1.scala:4: error: export overload conflicts with export of method b: they are of different types (Field / Method) + | @JSExportTopLevel("foo") + | ^ + """ + + """ + object A { + @JSExportTopLevel("foo") + def a(x: Int): Int = x + 1 + + @JSExportTopLevel("foo") + val b: Int = 1 + } + """ hasErrors + """ + |newSource1.scala:4: error: export overload conflicts with export of value b: they are of different types (Method / Field) + | @JSExportTopLevel("foo") + | ^ + """ + } + + @Test + def noExportTopLevelNonStatic(): Unit = { + """ + class A { + @JSExportTopLevel("foo") + def a(): Unit = () + } + """ hasErrors + """ + |newSource1.scala:4: error: Only static objects may export their members to the top level + | @JSExportTopLevel("foo") + | ^ + """ + + """ + class A { + object B { + @JSExportTopLevel("foo") + def a(): Unit = () + } + } + """ hasErrors + """ + |newSource1.scala:5: error: Only static objects may export their members to the top level + | @JSExportTopLevel("foo") + | ^ + """ + + """ + class A { + @JSExportTopLevel("Foo") + object B + } + """ hasErrors + """ + |newSource1.scala:4: error: You may not export a nested object + | @JSExportTopLevel("Foo") + | ^ + """ + + """ + class A { + @JSExportTopLevel("Foo") + object B extends js.Object + } + """ hasErrors + """ + |newSource1.scala:4: error: You may not export a nested object + | @JSExportTopLevel("Foo") + | ^ + """ + + """ + class A { + @JSExportTopLevel("Foo") + class B extends js.Object + } + """ hasErrors + """ + |newSource1.scala:4: error: You may not export a nested class. Create an exported factory method in the outer class to work around this limitation. + | @JSExportTopLevel("Foo") + | ^ + """ + + """ + class A { + @JSExportTopLevel("Foo") + class B + } + """ hasErrors + """ + |newSource1.scala:4: error: You may not export a nested class. Create an exported factory method in the outer class to work around this limitation. + | @JSExportTopLevel("Foo") + | ^ + """ + } + + @Test + def noExportTopLevelLocal(): Unit = { + // Local class + """ + class A { + def method = { + @JSExportTopLevel("A") + class A + + @JSExportTopLevel("B") + class B extends js.Object + } + } + """ hasErrors + """ + |newSource1.scala:5: error: You may not export a local class + | @JSExportTopLevel("A") + | ^ + |newSource1.scala:8: error: You may not export a local class + | @JSExportTopLevel("B") + | ^ + """ + + // Local object + """ + class A { + def method = { + @JSExportTopLevel("A") + object A + + @JSExportTopLevel("B") + object B extends js.Object + } + } + """ hasErrors + """ + |newSource1.scala:5: error: You may not export a local object + | @JSExportTopLevel("A") + | ^ + |newSource1.scala:8: error: You may not export a local object + | @JSExportTopLevel("B") + | ^ + """ + } + + @Test + def noExportTopLevelJSModule(): Unit = { + """ + object A extends js.Object { + @JSExportTopLevel("foo") + def a(): Unit = () + } + """ hasErrors + """ + |newSource1.scala:4: error: You may not export a method of a subclass of js.Any + | @JSExportTopLevel("foo") + | ^ + """ + } + + @Test + def noExportStaticModule(): Unit = { + """ + class StaticContainer extends js.Object + + object StaticContainer { + @JSExportStatic + object A + } + """ hasErrors + """ + |newSource1.scala:6: error: Implementation restriction: cannot export a class or object as static + | @JSExportStatic + | ^ + """ + } + + @Test + def noExportStaticTrait(): Unit = { + """ + class StaticContainer extends js.Object + + object StaticContainer { + @JSExportStatic + trait A + } + """ hasErrors + """ + |newSource1.scala:6: error: You may not export a trait as static. + | @JSExportStatic + | ^ + """ + } + + @Test + def noExportStaticClass(): Unit = { + """ + class StaticContainer extends js.Object + + object StaticContainer { + @JSExportStatic + class A + } + """ hasErrors + """ + |newSource1.scala:6: error: Implementation restriction: cannot export a class or object as static + | @JSExportStatic + | ^ + """ + + """ + class StaticContainer extends js.Object + + object StaticContainer { + class A { + @JSExportStatic + def this(x: Int) = this() + } + } + """ hasErrors + """ + |newSource1.scala:7: error: Implementation restriction: cannot export a class or object as static + | @JSExportStatic + | ^ + """ + } + + @Test + def noExportStaticValTwice(): Unit = { + """ + class StaticContainer extends js.Object + + object StaticContainer { + @JSExportStatic + @JSExportStatic("b") + val a: Int = 1 + } + """ hasErrors + """ + |newSource1.scala:7: error: Fields (val or var) cannot be exported as static more than once + | @JSExportStatic("b") + | ^ + """ + } + + @Test + def noExportStaticVarTwice(): Unit = { + """ + class StaticContainer extends js.Object + + object StaticContainer { + @JSExportStatic + @JSExportStatic("b") + var a: Int = 1 + } + """ hasErrors + """ + |newSource1.scala:7: error: Fields (val or var) cannot be exported as static more than once + | @JSExportStatic("b") + | ^ + """ + } + + @Test + def noExportStaticLazyVal(): Unit = { + """ + class StaticContainer extends js.Object + + object StaticContainer { + @JSExportStatic + lazy val a: Int = 1 + } + """ hasErrors + """ + |newSource1.scala:6: error: You may not export a lazy val as static + | @JSExportStatic + | ^ + """ + } + + @Test + def noExportValAsStaticAndTopLevel(): Unit = { + """ + class StaticContainer extends js.Object + + object StaticContainer { + @JSExportStatic + @JSExportTopLevel("foo") + val a: Int = 1 + } + """ hasErrors + """ + |newSource1.scala:7: error: Fields (val or var) cannot be exported both as static and at the top-level + | @JSExportTopLevel("foo") + | ^ + """ + } + + @Test + def noExportVarAsStaticAndTopLevel(): Unit = { + """ + class StaticContainer extends js.Object + + object StaticContainer { + @JSExportStatic + @JSExportTopLevel("foo") + var a: Int = 1 + } + """ hasErrors + """ + |newSource1.scala:7: error: Fields (val or var) cannot be exported both as static and at the top-level + | @JSExportTopLevel("foo") + | ^ + """ + } + + @Test + def noExportSetterWithBadSetterType(): Unit = { + """ + class StaticContainer extends js.Object + + object StaticContainer { + @JSExportStatic + def a_=(x: Int, y: Int): Unit = () + } + """ hasErrors + """ + |newSource1.scala:6: error: Exported setters must have exactly one argument + | @JSExportStatic + | ^ + """ + } + + @Test + def noExportStaticCollapsingMethods(): Unit = { + """ + class StaticContainer extends js.Object + + object StaticContainer { + @JSExportStatic + def foo(x: Int): Int = x + + @JSExportStatic("foo") + def bar(x: Int): Int = x + 1 + } + """ hasErrors + s""" + |newSource1.scala:10: error: Cannot disambiguate overloads for exported method foo with types + | ${methodSig("(x: Int)", "Int")} + | ${methodSig("(x: Int)", "Int")} + | def bar(x: Int): Int = x + 1 + | ^ + """ + } + + @Test + def noExportStaticCollapsingGetters(): Unit = { + """ + class StaticContainer extends js.Object + + object StaticContainer { + @JSExportStatic + def foo: Int = 1 + + @JSExportStatic("foo") + def bar: Int = 2 + } + """ hasErrors + s""" + |newSource1.scala:10: error: Cannot disambiguate overloads for exported getter foo with types + | ${methodSig("()", "Int")} + | ${methodSig("()", "Int")} + | def bar: Int = 2 + | ^ + """ + } + + @Test + def noExportStaticCollapsingSetters(): Unit = { + """ + class StaticContainer extends js.Object + + object StaticContainer { + @JSExportStatic + def foo_=(v: Int): Unit = () + + @JSExportStatic("foo") + def bar_=(v: Int): Unit = () + } + """ hasErrors + s""" + |newSource1.scala:10: error: Cannot disambiguate overloads for exported setter foo with types + | ${methodSig("(v: Int)", "Unit")} + | ${methodSig("(v: Int)", "Unit")} + | def bar_=(v: Int): Unit = () + | ^ + """ + } + + @Test + def noExportStaticFieldsWithSameName(): Unit = { + """ + class StaticContainer extends js.Object + + object StaticContainer { + @JSExportStatic + val a: Int = 1 + + @JSExportStatic("a") + var b: Int = 1 + } + """ hasErrors + """ + |newSource1.scala:6: error: export overload conflicts with export of variable b: a field may not share its exported name with another export + | @JSExportStatic + | ^ + """ + } + + @Test + def noExportStaticFieldsAndMethodsWithSameName(): Unit = { + """ + class StaticContainer extends js.Object + + object StaticContainer { + @JSExportStatic + val a: Int = 1 + + @JSExportStatic("a") + def b(x: Int): Int = x + 1 + } + """ hasErrors + """ + |newSource1.scala:6: error: export overload conflicts with export of method b: they are of different types (Field / Method) + | @JSExportStatic + | ^ + """ + + """ + class StaticContainer extends js.Object + + object StaticContainer { + @JSExportStatic + def a(x: Int): Int = x + 1 + + @JSExportStatic("a") + val b: Int = 1 + } + """ hasErrors + """ + |newSource1.scala:6: error: export overload conflicts with export of value b: they are of different types (Method / Field) + | @JSExportStatic + | ^ + """ + } + + @Test + def noExportStaticFieldsAndPropertiesWithSameName(): Unit = { + """ + class StaticContainer extends js.Object + + object StaticContainer { + @JSExportStatic + val a: Int = 1 + + @JSExportStatic("a") + def b: Int = 2 + } + """ hasErrors + """ + |newSource1.scala:6: error: export overload conflicts with export of method b: they are of different types (Field / Property) + | @JSExportStatic + | ^ + """ + + """ + class StaticContainer extends js.Object + + object StaticContainer { + @JSExportStatic + def a: Int = 1 + + @JSExportStatic("a") + val b: Int = 2 + } + """ hasErrors + """ + |newSource1.scala:6: error: export overload conflicts with export of value b: they are of different types (Property / Field) + | @JSExportStatic + | ^ + """ + } + + @Test + def noExportStaticPropertiesAndMethodsWithSameName(): Unit = { + """ + class StaticContainer extends js.Object + + object StaticContainer { + @JSExportStatic + def a: Int = 1 + + @JSExportStatic("a") + def b(x: Int): Int = x + 1 + } + """ hasErrors + """ + |newSource1.scala:6: error: export overload conflicts with export of method b: they are of different types (Property / Method) + | @JSExportStatic + | ^ + """ + + """ + class StaticContainer extends js.Object + + object StaticContainer { + @JSExportStatic + def a(x: Int): Int = x + 1 + + @JSExportStatic("a") + def b: Int = 1 + } + """ hasErrors + """ + |newSource1.scala:6: error: export overload conflicts with export of method b: they are of different types (Method / Property) + | @JSExportStatic + | ^ + """ + } + + @Test + def noExportStaticNonStatic(): Unit = { + """ + class A { + class StaticContainer extends js.Object + + object StaticContainer { + @JSExportStatic + def a(): Unit = () + } + } + """ hasErrors + """ + |newSource1.scala:7: error: Only a static object whose companion class is a non-native JS class may export its members as static. + | @JSExportStatic + | ^ + """ + } + + @Test + def noExportStaticInJSModule(): Unit = { + """ + class StaticContainer extends js.Object + + object StaticContainer extends js.Object { + @JSExportStatic + def a(): Unit = () + } + """ hasErrors + """ + |newSource1.scala:6: error: You may not export a method of a subclass of js.Any + | @JSExportStatic + | ^ + """ + + """ + class StaticContainer extends js.Object + + @js.native + @JSGlobal("Dummy") + object StaticContainer extends js.Object { + @JSExportStatic + def a(): Unit = js.native + } + """ hasErrors + """ + |newSource1.scala:8: error: You may not export a method of a subclass of js.Any + | @JSExportStatic + | ^ + """ + } + + @Test + def noExportStaticIfWrongCompanionType(): Unit = { + """ + class StaticContainer + + object StaticContainer { + @JSExportStatic + def a(): Unit = () + } + """ hasErrors + """ + |newSource1.scala:6: error: Only a static object whose companion class is a non-native JS class may export its members as static. + | @JSExportStatic + | ^ + """ + + """ + trait StaticContainer extends js.Object + + object StaticContainer { + @JSExportStatic + def a(): Unit = () + } + """ hasErrors + """ + |newSource1.scala:6: error: Only a static object whose companion class is a non-native JS class may export its members as static. + | @JSExportStatic + | ^ + """ + + """ + @js.native + @JSGlobal("Dummy") + class StaticContainer extends js.Object + + object StaticContainer { + @JSExportStatic + def a(): Unit = () + } + """ hasErrors + """ + |newSource1.scala:8: error: Only a static object whose companion class is a non-native JS class may export its members as static. + | @JSExportStatic + | ^ + """ + } + + @Test + def noExportStaticFieldAfterStatOrNonStaticField(): Unit = { + for { + offendingDecl <- Seq( + "val a: Int = 1", + "var a: Int = 1", + """println("foo")""" + ) + } + s""" + class StaticContainer extends js.Object + + object StaticContainer { + $offendingDecl + + @JSExportStatic + val b: Int = 1 + + @JSExportStatic + var c: Int = 1 + + @JSExportStatic + def d: Int = 1 + + @JSExportStatic + def d_=(v: Int): Unit = () + + @JSExportStatic + def e(): Int = 1 + } + """ hasErrors + """ + |newSource1.scala:9: error: @JSExportStatic vals and vars must be defined before any other val/var, and before any constructor statement. + | val b: Int = 1 + | ^ + |newSource1.scala:12: error: @JSExportStatic vals and vars must be defined before any other val/var, and before any constructor statement. + | var c: Int = 1 + | ^ + """ + + for { + validDecl <- Seq( + "@JSExportStatic val a: Int = 1", + "@JSExportStatic var a: Int = 1", + "lazy val a: Int = 1", + "def a: Int = 1", + "def a_=(v: Int): Unit = ()", + "def a(): Int = 1", + "@JSExportStatic def a: Int = 1", + "@JSExportStatic def a_=(v: Int): Unit = ()", + "@JSExportStatic def a(): Int = 1", + "class A", + "object A", + "trait A", + "type A = Int" + ) + } + s""" + class StaticContainer extends js.Object + + object StaticContainer { + $validDecl + + @JSExportStatic + val b: Int = 1 + + @JSExportStatic + var c: Int = 1 + } + """.succeeds() + } +} diff --git a/compiler/src/test/scala/org/scalajs/nscplugin/test/JSGlobalScopeTest.scala b/compiler/src/test/scala/org/scalajs/nscplugin/test/JSGlobalScopeTest.scala new file mode 100644 index 0000000000..a00d6a2909 --- /dev/null +++ b/compiler/src/test/scala/org/scalajs/nscplugin/test/JSGlobalScopeTest.scala @@ -0,0 +1,500 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin.test + +import org.scalajs.nscplugin.test.util._ +import org.scalajs.nscplugin.test.util.VersionDependentUtils.scalaSupportsNoWarn + +import org.junit.Test +import org.junit.Ignore +import org.junit.Assume._ + +// scalastyle:off line.size.limit + +class JSGlobalScopeTest extends DirectTest with TestHelpers { + + override def extraArgs: List[String] = + super.extraArgs :+ "-deprecation" + + override def preamble: String = { + """ + import scala.scalajs.js + import scala.scalajs.js.annotation._ + + object Symbols { + val sym: js.Symbol = js.Symbol() + } + + @js.native + @JSGlobalScope + object SomeGlobalScope extends js.Any { + var validVar: Int = js.native + def validDef(): Int = js.native + + var `not-a-valid-identifier-var`: Int = js.native + def `not-a-valid-identifier-def`(): Int = js.native + + @JSOperator def +(that: Int): Int = js.native + + def apply(x: Int): Int = js.native + + @JSBracketAccess + def bracketSelect(name: String): Int = js.native + @JSBracketAccess + def bracketUpdate(name: String, v: Int): Unit = js.native + + @JSBracketCall + def bracketCall(name: String)(arg: Int): Int = js.native + + @JSName(Symbols.sym) + var symbolVar: Int = js.native + @JSName(Symbols.sym) + def symbolDef(): Int = js.native + + var arguments: js.Array[Any] = js.native + @JSName("arguments") def arguments2(x: Int): Int = js.native + } + """ + } + + @Test + def canAccessLegitMembers(): Unit = { + s""" + object Main { + def main(): Unit = { + val a = js.Dynamic.global.validVar + js.Dynamic.global.validVar = 3 + val b = js.Dynamic.global.validDef() + + val c = SomeGlobalScope.validVar + SomeGlobalScope.validVar = 3 + val d = SomeGlobalScope.validDef() + + val e = SomeGlobalScope.bracketSelect("validVar") + SomeGlobalScope.bracketUpdate("validVar", 3) + val f = SomeGlobalScope.bracketCall("validDef")(4) + } + } + """.hasNoWarns() + } + + @Test + def noLoadGlobalValue(): Unit = { + s""" + object Main { + def main(): Unit = { + val g1 = js.Dynamic.global + val g2 = SomeGlobalScope + } + } + """ hasErrors + s""" + |newSource1.scala:41: error: Loading the global scope as a value (anywhere but as the left-hand-side of a `.`-selection) is not allowed. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | val g1 = js.Dynamic.global + | ^ + |newSource1.scala:42: error: Loading the global scope as a value (anywhere but as the left-hand-side of a `.`-selection) is not allowed. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | val g2 = SomeGlobalScope + | ^ + """ + } + + @Test + def rejectInvalidJSIdentifiers(): Unit = { + s""" + object Main { + def main(): Unit = { + val a = js.Dynamic.global.`not-a-valid-identifier-var` + js.Dynamic.global.`not-a-valid-identifier-var` = 3 + val b = js.Dynamic.global.`not-a-valid-identifier-def`() + + val c = SomeGlobalScope.`not-a-valid-identifier-var` + SomeGlobalScope.`not-a-valid-identifier-var` = 3 + val d = SomeGlobalScope.`not-a-valid-identifier-def`() + + val e = SomeGlobalScope.bracketSelect("not-a-valid-identifier-var") + SomeGlobalScope.bracketUpdate("not-a-valid-identifier-var", 3) + val f = SomeGlobalScope.bracketCall("not-a-valid-identifier-def")(4) + } + } + """ hasErrors + s""" + |newSource1.scala:41: error: Selecting a field of the global scope whose name is not a valid JavaScript identifier is not allowed. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | val a = js.Dynamic.global.`not-a-valid-identifier-var` + | ^ + |newSource1.scala:42: error: Selecting a field of the global scope whose name is not a valid JavaScript identifier is not allowed. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | js.Dynamic.global.`not-a-valid-identifier-var` = 3 + | ^ + |newSource1.scala:43: error: Calling a method of the global scope whose name is not a valid JavaScript identifier is not allowed. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | val b = js.Dynamic.global.`not-a-valid-identifier-def`() + | ^ + |newSource1.scala:45: error: Selecting a field of the global scope whose name is not a valid JavaScript identifier is not allowed. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | val c = SomeGlobalScope.`not-a-valid-identifier-var` + | ^ + |newSource1.scala:46: error: Selecting a field of the global scope whose name is not a valid JavaScript identifier is not allowed. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | SomeGlobalScope.`not-a-valid-identifier-var` = 3 + | ^ + |newSource1.scala:47: error: Calling a method of the global scope whose name is not a valid JavaScript identifier is not allowed. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | val d = SomeGlobalScope.`not-a-valid-identifier-def`() + | ^ + |newSource1.scala:49: error: Selecting a field of the global scope whose name is not a valid JavaScript identifier is not allowed. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | val e = SomeGlobalScope.bracketSelect("not-a-valid-identifier-var") + | ^ + |newSource1.scala:50: error: Selecting a field of the global scope whose name is not a valid JavaScript identifier is not allowed. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | SomeGlobalScope.bracketUpdate("not-a-valid-identifier-var", 3) + | ^ + |newSource1.scala:51: error: Calling a method of the global scope whose name is not a valid JavaScript identifier is not allowed. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | val f = SomeGlobalScope.bracketCall("not-a-valid-identifier-def")(4) + | ^ + """ + } + + @Test + def rejectInvalidJSIdentifiersInNestedObjectClass(): Unit = { + """ + @js.native + @JSGlobalScope + object EnclosingGlobalScope extends js.Any { + @js.native + class `not-a-valid-JS-identifier` extends js.Object + + @js.native + @JSName("not-a-valid-JS-identifier") + object A extends js.Object + + @js.native + @JSName("foo.bar") + object B extends js.Object + + @js.native + @JSName("") + object C extends js.Object + } + """ hasErrors + """ + |newSource1.scala:43: error: The name of a JS global variable must be a valid JS identifier (got 'not-a-valid-JS-identifier') + | class `not-a-valid-JS-identifier` extends js.Object + | ^ + |newSource1.scala:47: error: The name of a JS global variable must be a valid JS identifier (got 'not-a-valid-JS-identifier') + | object A extends js.Object + | ^ + |newSource1.scala:51: error: The name of a JS global variable must be a valid JS identifier (got 'foo.bar') + | object B extends js.Object + | ^ + |newSource1.scala:55: error: The name of a JS global variable must be a valid JS identifier (got '') + | object C extends js.Object + | ^ + """ + } + + @Test + def rejectJSOperators(): Unit = { + """ + object Main { + def main(): Unit = { + val a = js.Dynamic.global + 3.asInstanceOf[js.Dynamic] + } + } + """ hasErrors + s""" + |newSource1.scala:41: error: type mismatch; + | found : scala.scalajs.js.Dynamic + | required: String + | val a = js.Dynamic.global + 3.asInstanceOf[js.Dynamic] + | ^ + """ + + """ + object Main { + def main(): Unit = { + val a = SomeGlobalScope + 3 + } + } + """ hasErrors + s""" + |newSource1.scala:41: error: Loading the global scope as a value (anywhere but as the left-hand-side of a `.`-selection) is not allowed. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | val a = SomeGlobalScope + 3 + | ^ + """ + } + + @Test + def rejectApply(): Unit = { + """ + object Main { + def main(): Unit = { + val a = js.Dynamic.global(3) + } + } + """ hasErrors + s""" + |newSource1.scala:41: warning: method apply in object global is deprecated${since("forever")}: The global scope cannot be called as function. + | val a = js.Dynamic.global(3) + | ^ + |newSource1.scala:41: error: Loading the global scope as a value (anywhere but as the left-hand-side of a `.`-selection) is not allowed. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | val a = js.Dynamic.global(3) + | ^ + """ + + """ + object Main { + def main(): Unit = { + val a = SomeGlobalScope(3) + } + } + """ hasErrors + s""" + |newSource1.scala:41: error: Loading the global scope as a value (anywhere but as the left-hand-side of a `.`-selection) is not allowed. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | val a = SomeGlobalScope(3) + | ^ + """ + } + + @Test + def rejectDynamicNames(): Unit = { + s""" + object Main { + def dynName: String = "foo" + + def main(): Unit = { + val a = js.Dynamic.global.selectDynamic(dynName) + js.Dynamic.global.updateDynamic(dynName)(3) + val b = js.Dynamic.global.applyDynamic(dynName)(3) + + val e = SomeGlobalScope.bracketSelect(dynName) + SomeGlobalScope.bracketUpdate(dynName, 3) + val f = SomeGlobalScope.bracketCall(dynName)(4) + + val i = SomeGlobalScope.symbolVar + SomeGlobalScope.symbolVar = 3 + val k = SomeGlobalScope.symbolDef() + } + } + """ hasErrors + s""" + |newSource1.scala:43: error: Selecting a field of the global scope with a dynamic name is not allowed. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | val a = js.Dynamic.global.selectDynamic(dynName) + | ^ + |newSource1.scala:44: error: Selecting a field of the global scope with a dynamic name is not allowed. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | js.Dynamic.global.updateDynamic(dynName)(3) + | ^ + |newSource1.scala:45: error: Calling a method of the global scope with a dynamic name is not allowed. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | val b = js.Dynamic.global.applyDynamic(dynName)(3) + | ^ + |newSource1.scala:47: error: Selecting a field of the global scope with a dynamic name is not allowed. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | val e = SomeGlobalScope.bracketSelect(dynName) + | ^ + |newSource1.scala:48: error: Selecting a field of the global scope with a dynamic name is not allowed. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | SomeGlobalScope.bracketUpdate(dynName, 3) + | ^ + |newSource1.scala:49: error: Calling a method of the global scope with a dynamic name is not allowed. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | val f = SomeGlobalScope.bracketCall(dynName)(4) + | ^ + |newSource1.scala:51: error: Selecting a field of the global scope with a dynamic name is not allowed. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | val i = SomeGlobalScope.symbolVar + | ^ + |newSource1.scala:52: error: Selecting a field of the global scope with a dynamic name is not allowed. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | SomeGlobalScope.symbolVar = 3 + | ^ + |newSource1.scala:53: error: Calling a method of the global scope with a dynamic name is not allowed. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | val k = SomeGlobalScope.symbolDef() + | ^ + """ + } + + @Test + def rejectAllReservedIdentifiers(): Unit = { + val reservedIdentifiers = List( + "arguments", "break", "case", "catch", "class", "const", "continue", + "debugger", "default", "delete", "do", "else", "enum", "export", + "extends", "false", "finally", "for", "function", "if", "implements", + "import", "in", "instanceof", "interface", "let", "new", "null", + "package", "private", "protected", "public", "return", "static", + "super", "switch", "this", "throw", "true", "try", "typeof", "var", + "void", "while", "with", "yield") + + for (reservedIdentifier <- reservedIdentifiers) { + val spaces = " " * reservedIdentifier.length() + + s""" + @js.native + @JSGlobalScope + object CustomGlobalScope extends js.Any { + var `$reservedIdentifier`: Int = js.native + @JSName("$reservedIdentifier") + def `${reservedIdentifier}2`(x: Int): Int = js.native + } + + object Main { + def main(): Unit = { + val a = js.Dynamic.global.`$reservedIdentifier` + js.Dynamic.global.`$reservedIdentifier` = 5 + val b = js.Dynamic.global.`$reservedIdentifier`(5) + + val c = CustomGlobalScope.`$reservedIdentifier` + CustomGlobalScope.`$reservedIdentifier` = 5 + val d = CustomGlobalScope.`${reservedIdentifier}2`(5) + } + } + """ hasErrors + s""" + |newSource1.scala:49: error: Invalid selection in the global scope of the reserved identifier name `$reservedIdentifier`. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | val a = js.Dynamic.global.`$reservedIdentifier` + | ^ + |newSource1.scala:50: error: Invalid selection in the global scope of the reserved identifier name `$reservedIdentifier`. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | js.Dynamic.global.`$reservedIdentifier` = 5 + | ^ + |newSource1.scala:51: error: Invalid call in the global scope of the reserved identifier name `$reservedIdentifier`. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | val b = js.Dynamic.global.`$reservedIdentifier`(5) + | $spaces^ + |newSource1.scala:53: error: Invalid selection in the global scope of the reserved identifier name `$reservedIdentifier`. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | val c = CustomGlobalScope.`$reservedIdentifier` + | ^ + |newSource1.scala:54: error: Invalid selection in the global scope of the reserved identifier name `$reservedIdentifier`. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | CustomGlobalScope.`$reservedIdentifier` = 5 + | $spaces^ + |newSource1.scala:55: error: Invalid call in the global scope of the reserved identifier name `$reservedIdentifier`. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | val d = CustomGlobalScope.`${reservedIdentifier}2`(5) + | $spaces^ + """ + } + } + + @Test + def warnAboutAwaitReservedWord_Issue4705(): Unit = { + val reservedIdentifiers = List("await") + + for (reservedIdentifier <- reservedIdentifiers) { + val spaces = " " * reservedIdentifier.length() + + s""" + @js.native + @JSGlobalScope + object CustomGlobalScope extends js.Any { + var `$reservedIdentifier`: Int = js.native + @JSName("$reservedIdentifier") + def `${reservedIdentifier}2`(x: Int): Int = js.native + } + + object Main { + def main(): Unit = { + val a = js.Dynamic.global.`$reservedIdentifier` + js.Dynamic.global.`$reservedIdentifier` = 5 + val b = js.Dynamic.global.`$reservedIdentifier`(5) + + val c = CustomGlobalScope.`$reservedIdentifier` + CustomGlobalScope.`$reservedIdentifier` = 5 + val d = CustomGlobalScope.`${reservedIdentifier}2`(5) + } + } + """ hasWarns + s""" + |newSource1.scala:49: warning: Selecting a field of the global scope with the name '$reservedIdentifier' is deprecated. + | It may produce invalid JavaScript code causing a SyntaxError in some environments. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | val a = js.Dynamic.global.`$reservedIdentifier` + | ^ + |newSource1.scala:50: warning: Selecting a field of the global scope with the name '$reservedIdentifier' is deprecated. + | It may produce invalid JavaScript code causing a SyntaxError in some environments. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | js.Dynamic.global.`$reservedIdentifier` = 5 + | ^ + |newSource1.scala:51: warning: Calling a method of the global scope with the name '$reservedIdentifier' is deprecated. + | It may produce invalid JavaScript code causing a SyntaxError in some environments. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | val b = js.Dynamic.global.`$reservedIdentifier`(5) + | $spaces^ + |newSource1.scala:53: warning: Selecting a field of the global scope with the name '$reservedIdentifier' is deprecated. + | It may produce invalid JavaScript code causing a SyntaxError in some environments. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | val c = CustomGlobalScope.`$reservedIdentifier` + | ^ + |newSource1.scala:54: warning: Selecting a field of the global scope with the name '$reservedIdentifier' is deprecated. + | It may produce invalid JavaScript code causing a SyntaxError in some environments. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | CustomGlobalScope.`$reservedIdentifier` = 5 + | $spaces^ + |newSource1.scala:55: warning: Calling a method of the global scope with the name '$reservedIdentifier' is deprecated. + | It may produce invalid JavaScript code causing a SyntaxError in some environments. + | See https://www.scala-js.org/doc/interoperability/global-scope.html for further information. + | val d = CustomGlobalScope.`${reservedIdentifier}2`(5) + | $spaces^ + """ + } + } + + @Test + def noWarnAboutAwaitReservedWordIfSelectivelyDisabled(): Unit = { + assumeTrue(scalaSupportsNoWarn) + + val reservedIdentifiers = List("await") + + for (reservedIdentifier <- reservedIdentifiers) { + val spaces = " " * reservedIdentifier.length() + + s""" + import scala.annotation.nowarn + + @js.native + @JSGlobalScope + object CustomGlobalScope extends js.Any { + var `$reservedIdentifier`: Int = js.native + @JSName("$reservedIdentifier") + def `${reservedIdentifier}2`(x: Int): Int = js.native + } + + object Main { + @nowarn("cat=deprecation") + def main(): Unit = { + val a = js.Dynamic.global.`$reservedIdentifier` + js.Dynamic.global.`$reservedIdentifier` = 5 + val b = js.Dynamic.global.`$reservedIdentifier`(5) + + val c = CustomGlobalScope.`$reservedIdentifier` + CustomGlobalScope.`$reservedIdentifier` = 5 + val d = CustomGlobalScope.`${reservedIdentifier}2`(5) + } + } + """.hasNoWarns() + } + } + +} diff --git a/compiler/src/test/scala/org/scalajs/nscplugin/test/JSInteropTest.scala b/compiler/src/test/scala/org/scalajs/nscplugin/test/JSInteropTest.scala new file mode 100644 index 0000000000..1c3f0e4330 --- /dev/null +++ b/compiler/src/test/scala/org/scalajs/nscplugin/test/JSInteropTest.scala @@ -0,0 +1,4679 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin.test + +import org.scalajs.nscplugin.test.util._ + +import org.junit.Test +import org.junit.Ignore + +// scalastyle:off line.size.limit + +class JSInteropTest extends DirectTest with TestHelpers { + + override def preamble: String = + """ + import scala.scalajs.js + import scala.scalajs.js.annotation._ + """ + + private val JSNativeLoadSpecAnnots = Seq( + "JSGlobal" -> "@JSGlobal", + "JSGlobal" -> "@JSGlobal(\"foo\")", + "JSImport" -> "@JSImport(\"foo\", \"bar\")", + "JSImport" -> "@JSImport(\"foo\", \"bar\", globalFallback = \"baz\")", + "JSGlobalScope" -> "@JSGlobalScope" + ) + + private def version = scala.util.Properties.versionNumberString + + private def ifHasNewRefChecks(msg: String): String = { + if (version.startsWith("2.11.") || + version.startsWith("2.12.")) { + "" + } else { + msg.stripMargin.trim() + } + } + + @Test def warnJSPackageObjectDeprecated: Unit = { + + s""" + package object jspackage extends js.Object + """ hasErrors + s""" + |newSource1.scala:5: error: Package objects may not extend js.Any. + | package object jspackage extends js.Object + | ^ + """ + + } + + @Test def noJSNameAnnotOnNonJSNative: Unit = { + + for { + obj <- Seq("class", "trait", "object") + } yield { + s""" + @JSName("foo") + $obj A extends js.Object + + object Sym { + val sym = js.Symbol() + } + + @JSName(Sym.sym) + $obj B extends js.Object + """ hasErrors + """ + |newSource1.scala:5: error: @JSName can only be used on members of JS types. + | @JSName("foo") + | ^ + |newSource1.scala:12: error: @JSName can only be used on members of JS types. + | @JSName(Sym.sym) + | ^ + """ + } + + for { + obj <- Seq("class", "trait", "object") + } yield { + s""" + @JSName("foo") + $obj A + + object Sym { + val sym = js.Symbol() + } + + @JSName(Sym.sym) + $obj B + """ hasErrors + """ + |newSource1.scala:5: error: @JSName can only be used on members of JS types. + | @JSName("foo") + | ^ + |newSource1.scala:12: error: @JSName can only be used on members of JS types. + | @JSName(Sym.sym) + | ^ + """ + } + + """ + object Container { + @JSName("foo") + val a: Int = 1 + + @JSName("foo") + var b: Int = 2 + + @JSName("foo") + def c: Int = 3 + + @JSName("foo") + def d_=(v: Int): Unit = () + + @JSName("foo") + def e(x: Int): Int = x + 1 + } + """ hasErrors + """ + |newSource1.scala:6: error: @JSName can only be used on members of JS types. + | @JSName("foo") + | ^ + |newSource1.scala:9: error: @JSName can only be used on members of JS types. + | @JSName("foo") + | ^ + |newSource1.scala:12: error: @JSName can only be used on members of JS types. + | @JSName("foo") + | ^ + |newSource1.scala:15: error: @JSName can only be used on members of JS types. + | @JSName("foo") + | ^ + |newSource1.scala:18: error: @JSName can only be used on members of JS types. + | @JSName("foo") + | ^ + """ + + } + + @Test def okJSNameOnNestedObjects: Unit = { + + """ + class A extends js.Object { + @JSName("foo") + object toto + + @JSName("bar") + object tata extends js.Object + } + """.hasNoWarns() + + """ + class A extends js.Object { + @JSName("foo") + private object toto + + @JSName("bar") + private object tata extends js.Object + } + """ hasErrors + """ + |newSource1.scala:6: error: @JSName cannot be used on private members. + | @JSName("foo") + | ^ + |newSource1.scala:9: error: @JSName cannot be used on private members. + | @JSName("bar") + | ^ + """ + + } + + @Test def noJSGlobalAnnotOnNonJSNative: Unit = { + + for { + obj <- Seq("class", "trait", "object") + } yield { + s""" + @JSGlobal + $obj A extends js.Object + + @JSGlobal("Foo") + $obj B extends js.Object + """ hasErrors + """ + |newSource1.scala:5: error: @JSGlobal can only be used on native JS definitions (with @js.native). + | @JSGlobal + | ^ + |newSource1.scala:8: error: @JSGlobal can only be used on native JS definitions (with @js.native). + | @JSGlobal("Foo") + | ^ + """ + } + + for { + obj <- Seq("class", "trait", "object") + } yield { + s""" + @JSGlobal + $obj A + + @JSGlobal("Foo") + $obj B + """ hasErrors + """ + |newSource1.scala:5: error: @JSGlobal can only be used on native JS definitions (with @js.native). + | @JSGlobal + | ^ + |newSource1.scala:8: error: @JSGlobal can only be used on native JS definitions (with @js.native). + | @JSGlobal("Foo") + | ^ + """ + } + + """ + object Container { + @JSGlobal + val a: Int = 1 + + @JSGlobal + var b: Int = 2 + + @JSGlobal + def c: Int = 3 + + @JSGlobal + def d_=(v: Int): Unit = () + + @JSGlobal + def e(x: Int): Int = x + 1 + } + """ hasErrors + """ + |newSource1.scala:6: error: @JSGlobal can only be used on native JS definitions (with @js.native). + | @JSGlobal + | ^ + |newSource1.scala:9: error: @JSGlobal can only be used on native JS definitions (with @js.native). + | @JSGlobal + | ^ + |newSource1.scala:12: error: @JSGlobal can only be used on native JS definitions (with @js.native). + | @JSGlobal + | ^ + |newSource1.scala:15: error: @JSGlobal can only be used on native JS definitions (with @js.native). + | @JSGlobal + | ^ + |newSource1.scala:18: error: @JSGlobal can only be used on native JS definitions (with @js.native). + | @JSGlobal + | ^ + """ + + } + + @Test def noJSImportAnnotOnNonJSNative: Unit = { + + for { + obj <- Seq("class", "trait", "object") + } yield { + s""" + @JSImport("foo", JSImport.Namespace) + $obj A extends js.Object + """ hasErrors + """ + |newSource1.scala:5: error: @JSImport can only be used on native JS definitions (with @js.native). + | @JSImport("foo", JSImport.Namespace) + | ^ + """ + } + + for { + obj <- Seq("class", "trait", "object") + } yield { + s""" + @JSImport("foo", JSImport.Namespace) + $obj A + """ hasErrors + """ + |newSource1.scala:5: error: @JSImport can only be used on native JS definitions (with @js.native). + | @JSImport("foo", JSImport.Namespace) + | ^ + """ + } + + """ + object Container { + @JSImport("foo", "bar") + val a: Int = 1 + + @JSImport("foo", "bar") + var b: Int = 2 + + @JSImport("foo", "bar") + def c: Int = 3 + + @JSImport("foo", "bar") + def d_=(v: Int): Unit = () + + @JSImport("foo", "bar") + def e(x: Int): Int = x + 1 + } + """ hasErrors + """ + |newSource1.scala:6: error: @JSImport can only be used on native JS definitions (with @js.native). + | @JSImport("foo", "bar") + | ^ + |newSource1.scala:9: error: @JSImport can only be used on native JS definitions (with @js.native). + | @JSImport("foo", "bar") + | ^ + |newSource1.scala:12: error: @JSImport can only be used on native JS definitions (with @js.native). + | @JSImport("foo", "bar") + | ^ + |newSource1.scala:15: error: @JSImport can only be used on native JS definitions (with @js.native). + | @JSImport("foo", "bar") + | ^ + |newSource1.scala:18: error: @JSImport can only be used on native JS definitions (with @js.native). + | @JSImport("foo", "bar") + | ^ + """ + + for { + obj <- Seq("class", "trait", "object") + } yield { + s""" + @JSImport("foo", JSImport.Namespace, globalFallback = "Foo") + $obj A extends js.Object + """ hasErrors + """ + |newSource1.scala:5: error: @JSImport can only be used on native JS definitions (with @js.native). + | @JSImport("foo", JSImport.Namespace, globalFallback = "Foo") + | ^ + """ + } + + for { + obj <- Seq("class", "trait", "object") + } yield { + s""" + @JSImport("foo", JSImport.Namespace, globalFallback = "Foo") + $obj A + """ hasErrors + """ + |newSource1.scala:5: error: @JSImport can only be used on native JS definitions (with @js.native). + | @JSImport("foo", JSImport.Namespace, globalFallback = "Foo") + | ^ + """ + } + + """ + object Container { + @JSImport("foo", "bar", globalFallback = "Foo") + val a: Int = 1 + + @JSImport("foo", "bar", globalFallback = "Foo") + var b: Int = 2 + + @JSImport("foo", "bar", globalFallback = "Foo") + def c: Int = 3 + + @JSImport("foo", "bar", globalFallback = "Foo") + def d_=(v: Int): Unit = () + + @JSImport("foo", "bar", globalFallback = "Foo") + def e(x: Int): Int = x + 1 + } + """ hasErrors + """ + |newSource1.scala:6: error: @JSImport can only be used on native JS definitions (with @js.native). + | @JSImport("foo", "bar", globalFallback = "Foo") + | ^ + |newSource1.scala:9: error: @JSImport can only be used on native JS definitions (with @js.native). + | @JSImport("foo", "bar", globalFallback = "Foo") + | ^ + |newSource1.scala:12: error: @JSImport can only be used on native JS definitions (with @js.native). + | @JSImport("foo", "bar", globalFallback = "Foo") + | ^ + |newSource1.scala:15: error: @JSImport can only be used on native JS definitions (with @js.native). + | @JSImport("foo", "bar", globalFallback = "Foo") + | ^ + |newSource1.scala:18: error: @JSImport can only be used on native JS definitions (with @js.native). + | @JSImport("foo", "bar", globalFallback = "Foo") + | ^ + """ + + } + + @Test def noJSGlobalScopeAnnotOnNonJSNative: Unit = { + + """ + @JSGlobalScope + object A extends js.Object + """ hasErrors + """ + |newSource1.scala:5: error: @JSGlobalScope can only be used on native JS objects (with @js.native). + | @JSGlobalScope + | ^ + """ + + """ + @JSGlobalScope + object A + """ hasErrors + """ + |newSource1.scala:5: error: @JSGlobalScope can only be used on native JS objects (with @js.native). + | @JSGlobalScope + | ^ + """ + + } + @Test def noJSNameAnnotOnClass: Unit = { + """ + @js.native + @JSName("Foo") + class A extends js.Object + + @js.native + @JSName("Foo") + abstract class B extends js.Object + """ hasErrors + """ + |newSource1.scala:6: error: @JSName can only be used on members of JS types. + | @JSName("Foo") + | ^ + |newSource1.scala:7: error: Native JS classes, vals and defs must have exactly one annotation among @JSGlobal and @JSImport. + | class A extends js.Object + | ^ + |newSource1.scala:10: error: @JSName can only be used on members of JS types. + | @JSName("Foo") + | ^ + |newSource1.scala:11: error: Native JS classes, vals and defs must have exactly one annotation among @JSGlobal and @JSImport. + | abstract class B extends js.Object + | ^ + """ + } + + @Test def noJSNameAnnotOnObject: Unit = { + """ + @js.native + @JSName("Foo") + object A extends js.Object + """ hasErrors + """ + |newSource1.scala:6: error: @JSName can only be used on members of JS types. + | @JSName("Foo") + | ^ + |newSource1.scala:7: error: Native JS objects must have exactly one annotation among @JSGlobal, @JSImport and @JSGlobalScope. + | object A extends js.Object + | ^ + """ + } + + @Test def noJSNameAnnotOnTrait: Unit = { + + s""" + object Sym { + val sym = js.Symbol() + } + + @js.native @JSGlobal + object Container extends js.Object { + @js.native + @JSName("foo") + trait A extends js.Object + + @js.native + @JSName(Sym.sym) + trait B extends js.Object + } + """ hasErrors + """ + |newSource1.scala:12: error: @JSName cannot be used on traits. + | @JSName("foo") + | ^ + |newSource1.scala:16: error: @JSName cannot be used on traits. + | @JSName(Sym.sym) + | ^ + """ + + } + + @Test def noJSNameAnnotOnNativeValDef: Unit = { + + s""" + object Sym { + val sym = js.Symbol() + } + + object Container { + @js.native + @JSName("foo") + val a: Int = js.native + + @js.native + @JSName("foo") + def b: Int = js.native + + @js.native + @JSName("foo") + def c(x: Int): Int = js.native + + @js.native + @JSName(Sym.sym) + val d: Int = js.native + + @js.native + @JSName(Sym.sym) + def e: Int = js.native + + @js.native + @JSName(Sym.sym) + def f(x: Int): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:11: error: @JSName can only be used on members of JS types. + | @JSName("foo") + | ^ + |newSource1.scala:12: error: Native JS classes, vals and defs must have exactly one annotation among @JSGlobal and @JSImport. + | val a: Int = js.native + | ^ + |newSource1.scala:15: error: @JSName can only be used on members of JS types. + | @JSName("foo") + | ^ + |newSource1.scala:16: error: Native JS classes, vals and defs must have exactly one annotation among @JSGlobal and @JSImport. + | def b: Int = js.native + | ^ + |newSource1.scala:19: error: @JSName can only be used on members of JS types. + | @JSName("foo") + | ^ + |newSource1.scala:20: error: Native JS classes, vals and defs must have exactly one annotation among @JSGlobal and @JSImport. + | def c(x: Int): Int = js.native + | ^ + |newSource1.scala:23: error: @JSName can only be used on members of JS types. + | @JSName(Sym.sym) + | ^ + |newSource1.scala:24: error: Native JS classes, vals and defs must have exactly one annotation among @JSGlobal and @JSImport. + | val d: Int = js.native + | ^ + |newSource1.scala:27: error: @JSName can only be used on members of JS types. + | @JSName(Sym.sym) + | ^ + |newSource1.scala:28: error: Native JS classes, vals and defs must have exactly one annotation among @JSGlobal and @JSImport. + | def e: Int = js.native + | ^ + |newSource1.scala:31: error: @JSName can only be used on members of JS types. + | @JSName(Sym.sym) + | ^ + |newSource1.scala:32: error: Native JS classes, vals and defs must have exactly one annotation among @JSGlobal and @JSImport. + | def f(x: Int): Int = js.native + | ^ + """ + + } + + @Test def noJSGlobalAnnotOnTrait: Unit = { + + s""" + @js.native + @JSGlobal + trait A extends js.Object + """ hasErrors + s""" + |newSource1.scala:6: error: Traits may not have an @JSGlobal annotation. + | @JSGlobal + | ^ + """ + + s""" + @js.native + @JSGlobal("Foo") + trait A extends js.Object + """ hasErrors + s""" + |newSource1.scala:6: error: Traits may not have an @JSGlobal annotation. + | @JSGlobal("Foo") + | ^ + """ + + } + + @Test def noJSImportAnnotOnTrait: Unit = { + + s""" + @js.native + @JSImport("foo", JSImport.Namespace) + trait A extends js.Object + """ hasErrors + s""" + |newSource1.scala:6: error: Traits may not have an @JSImport annotation. + | @JSImport("foo", JSImport.Namespace) + | ^ + """ + + s""" + @js.native + @JSImport("foo", JSImport.Namespace, globalFallback = "Foo") + trait A extends js.Object + """ hasErrors + s""" + |newSource1.scala:6: error: Traits may not have an @JSImport annotation. + | @JSImport("foo", JSImport.Namespace, globalFallback = "Foo") + | ^ + """ + + } + + @Test def noJSGlobalScopeExceptOnObjects: Unit = { + """ + @js.native @JSGlobalScope + class A extends js.Any + + @js.native @JSGlobalScope + trait B extends js.Any + + object Container { + @js.native @JSGlobalScope + class C extends js.Any + + @js.native @JSGlobalScope + trait D extends js.Any + + @js.native @JSGlobalScope + val a: Int = js.native + + @js.native @JSGlobalScope + def b: Int = js.native + + @js.native @JSGlobalScope + def c(x: Int): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:5: error: @JSGlobalScope can only be used on native JS objects (with @js.native). + | @js.native @JSGlobalScope + | ^ + |newSource1.scala:8: error: Traits may not have an @JSGlobalScope annotation. + | @js.native @JSGlobalScope + | ^ + |newSource1.scala:12: error: @JSGlobalScope can only be used on native JS objects (with @js.native). + | @js.native @JSGlobalScope + | ^ + |newSource1.scala:15: error: Traits may not have an @JSGlobalScope annotation. + | @js.native @JSGlobalScope + | ^ + |newSource1.scala:18: error: @JSGlobalScope can only be used on native JS objects (with @js.native). + | @js.native @JSGlobalScope + | ^ + |newSource1.scala:19: error: Native JS classes, vals and defs must have exactly one annotation among @JSGlobal and @JSImport. + | val a: Int = js.native + | ^ + |newSource1.scala:21: error: @JSGlobalScope can only be used on native JS objects (with @js.native). + | @js.native @JSGlobalScope + | ^ + |newSource1.scala:24: error: @JSGlobalScope can only be used on native JS objects (with @js.native). + | @js.native @JSGlobalScope + | ^ + """ + } + + @Test def noTwoJSNativeLoadSpecAnnots: Unit = { + for { + (firstAnnotName, firstAnnot) <- JSNativeLoadSpecAnnots + (secondAnnotName, secondAnnot) <- JSNativeLoadSpecAnnots + } { + if (firstAnnotName == "JSGlobalScope" || secondAnnotName == "JSGlobalScope") { + s""" + |@js.native + |$firstAnnot + |$secondAnnot + |object A extends js.Object + """.stripMargin hasErrors s""" + |newSource1.scala:7: error: Native JS objects must have exactly one annotation among @JSGlobal, @JSImport and @JSGlobalScope. + |$secondAnnot + | ^ + """ + } else { + s""" + |@js.native + |$firstAnnot + |$secondAnnot + |object A extends js.Object + | + |@js.native + |$firstAnnot + |$secondAnnot + |class A extends js.Object + """.stripMargin hasErrors s""" + |newSource1.scala:7: error: Native JS objects must have exactly one annotation among @JSGlobal, @JSImport and @JSGlobalScope. + |$secondAnnot + | ^ + |newSource1.scala:12: error: Native JS classes, vals and defs must have exactly one annotation among @JSGlobal and @JSImport. + |$secondAnnot + | ^ + """ + + if (firstAnnot != "@JSGlobal" && secondAnnot != "@JSGlobal") { + s""" + |object Container { + | @js.native + | $firstAnnot + | $secondAnnot + | val a: Int = js.native + | + | @js.native + | $firstAnnot + | $secondAnnot + | def b: Int = js.native + | + | @js.native + | $firstAnnot + | $secondAnnot + | def c(x: Int): Int = js.native + |} + """.stripMargin hasErrors s""" + |newSource1.scala:8: error: Native JS classes, vals and defs must have exactly one annotation among @JSGlobal and @JSImport. + | $secondAnnot + | ^ + |newSource1.scala:13: error: Native JS classes, vals and defs must have exactly one annotation among @JSGlobal and @JSImport. + | $secondAnnot + | ^ + |newSource1.scala:18: error: Native JS classes, vals and defs must have exactly one annotation among @JSGlobal and @JSImport. + | $secondAnnot + | ^ + """ + } + } + } + } + + @Test def noJSNativeAnnotWithoutJSAny: Unit = { + + // With the correct amount of native load spec annotations + """ + @js.native @JSGlobal + class A + + @js.native + trait B + + @js.native @JSGlobal + object C + + @js.native @JSGlobal + class D extends Enumeration + + @js.native @JSGlobal + object E extends Enumeration + """ hasErrors + """ + |newSource1.scala:6: error: Classes, traits and objects not extending js.Any may not have an @js.native annotation + | class A + | ^ + |newSource1.scala:9: error: Classes, traits and objects not extending js.Any may not have an @js.native annotation + | trait B + | ^ + |newSource1.scala:12: error: Classes, traits and objects not extending js.Any may not have an @js.native annotation + | object C + | ^ + |newSource1.scala:15: error: Classes, traits and objects not extending js.Any may not have an @js.native annotation + | class D extends Enumeration + | ^ + |newSource1.scala:18: error: Classes, traits and objects not extending js.Any may not have an @js.native annotation + | object E extends Enumeration + | ^ + """ + + // With an incorrect amount of native load spec annotations + """ + @js.native + class A + + @js.native @JSGlobal + trait B + + @js.native + object C + + @js.native + class D extends Enumeration + + @js.native + object E extends Enumeration + """ hasErrors + """ + |newSource1.scala:6: error: Classes, traits and objects not extending js.Any may not have an @js.native annotation + | class A + | ^ + |newSource1.scala:9: error: Classes, traits and objects not extending js.Any may not have an @js.native annotation + | trait B + | ^ + |newSource1.scala:12: error: Classes, traits and objects not extending js.Any may not have an @js.native annotation + | object C + | ^ + |newSource1.scala:15: error: Classes, traits and objects not extending js.Any may not have an @js.native annotation + | class D extends Enumeration + | ^ + |newSource1.scala:18: error: Classes, traits and objects not extending js.Any may not have an @js.native annotation + | object E extends Enumeration + | ^ + """ + + } + + @Test def noInnerScalaClassTraitObjectInJSNative: Unit = { + + for { + outer <- Seq("class", "trait") + inner <- Seq("class", "trait", "object") + } yield { + val jsGlobalAnnot = + if (outer == "trait") "" + else "@JSGlobal" + s""" + @js.native $jsGlobalAnnot + $outer A extends js.Object { + $inner A + } + """ hasErrors + s""" + |newSource1.scala:7: error: Native JS traits, classes and objects cannot contain inner Scala traits, classes or objects (i.e., not extending js.Any) + | $inner A + | ${" " * inner.length} ^ + """ + } + + } + + @Test def noInnerNonNativeJSClassTraitObjectInJSNative: Unit = { + + for { + outer <- Seq("class", "trait") + inner <- Seq("class", "trait", "object") + } yield { + val jsGlobalAnnot = + if (outer == "trait") "" + else "@JSGlobal" + s""" + @js.native $jsGlobalAnnot + $outer A extends js.Object { + $inner A extends js.Object + } + """ hasErrors + s""" + |newSource1.scala:7: error: Native JS classes and traits cannot contain non-native JS classes, traits or objects + | $inner A extends js.Object + | ${" " * inner.length} ^ + """ + } + + } + + @Test def noScalaStuffInsideNativeJSObject: Unit = { + + for { + inner <- Seq("class", "trait", "object") + } yield { + s""" + @js.native + @JSGlobal + object A extends js.Object { + $inner A + } + """ hasErrors + s""" + |newSource1.scala:8: error: Native JS traits, classes and objects cannot contain inner Scala traits, classes or objects (i.e., not extending js.Any) + | $inner A + | ${" " * inner.length} ^ + """ + } + + } + + @Test def noNonSyntheticCompanionInsideNativeJSObject: Unit = { + + // See #1891: The default parameter generates a synthetic companion object + // The synthetic companion should be allowed, but it may not be explicit + + """ + @js.native @JSGlobal object A extends js.Object { + @js.native class B(x: Int = ???) extends js.Object + object B + } + """ hasErrors + """ + |newSource1.scala:7: error: Native JS traits, classes and objects cannot contain inner Scala traits, classes or objects (i.e., not extending js.Any) + | object B + | ^ + """ + + """ + @js.native @JSGlobal object A extends js.Object { + @js.native class B(x: Int = ???) extends js.Object + } + """.succeeds() + + } + + @Test def noNonNativeJSTypesInsideNativeJSObject: Unit = { + + for { + inner <- Seq("class", "object") + } yield { + s""" + @js.native + @JSGlobal + object A extends js.Object { + $inner A extends js.Object + } + """ hasErrors + s""" + |newSource1.scala:8: error: Native JS objects cannot contain inner non-native JS classes or objects + | $inner A extends js.Object + | ${" " * inner.length} ^ + """ + } + + } + + @Test def jsNativeValDefsHaveJSNativeRHS: Unit = { + """ + object Container { + @js.native @JSGlobal("a") + val a: Int = 1 + + @js.native @JSGlobal("b") + def b: Int = 3 + + @js.native @JSGlobal("c") + def c(x: Int): Int = x + 1 + } + """ hasErrors + """ + |newSource1.scala:7: error: @js.native members may only call js.native. + | val a: Int = 1 + | ^ + |newSource1.scala:10: error: @js.native members may only call js.native. + | def b: Int = 3 + | ^ + |newSource1.scala:13: error: @js.native members may only call js.native. + | def c(x: Int): Int = x + 1 + | ^ + """ + } + + @Test def noJSBracketAccessOnJSNativeValDefs: Unit = { + """ + object Container { + @js.native @JSGlobal("a") + @JSBracketAccess + val a: Int = js.native + + @js.native @JSGlobal("b") + @JSBracketAccess + def b: Int = js.native + + @js.native @JSGlobal("c") + @JSBracketAccess + def c(x: Int): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:7: error: @JSBracketAccess can only be used on members of JS types. + | @JSBracketAccess + | ^ + |newSource1.scala:11: error: @JSBracketAccess can only be used on members of JS types. + | @JSBracketAccess + | ^ + |newSource1.scala:15: error: @JSBracketAccess can only be used on members of JS types. + | @JSBracketAccess + | ^ + """ + } + + @Test def noJSBracketCallOnJSNativeValDefs: Unit = { + """ + object Container { + @js.native @JSGlobal("a") + @JSBracketCall + val a: Int = js.native + + @js.native @JSGlobal("b") + @JSBracketCall + def b: Int = js.native + + @js.native @JSGlobal("c") + @JSBracketCall + def c(x: Int): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:7: error: @JSBracketCall can only be used on members of JS types. + | @JSBracketCall + | ^ + |newSource1.scala:11: error: @JSBracketCall can only be used on members of JS types. + | @JSBracketCall + | ^ + |newSource1.scala:15: error: @JSBracketCall can only be used on members of JS types. + | @JSBracketCall + | ^ + """ + } + + @Test def noJSNativeValDefsInJSObjects: Unit = { + """ + object A { + val sym = js.Symbol("foo") + } + + object NonNativeContainer extends js.Object { + @js.native @JSGlobal("a") + val a: Int = js.native + + @js.native @JSGlobal("b") + def b: Int = js.native + + @js.native @JSGlobal("c") + def c(x: Int): Int = js.native + + @js.native @JSName("foo") + val d: Int = js.native + + @js.native @JSName("bar") + def e(x: Int): Int = js.native + + @js.native @JSName(A.sym) + val f: Int = js.native + + @js.native @JSName(A.sym) + def g(x: Int): Int = js.native + } + + @js.native @JSGlobal + object NativeContainer extends js.Object { + @js.native @JSGlobal("a") + val a: Int = js.native + + @js.native @JSGlobal("b") + def b: Int = js.native + + @js.native @JSGlobal("c") + def c(x: Int): Int = js.native + + @js.native @JSName("foo") + val d: Int = js.native + + @js.native @JSName("bar") + def e(x: Int): Int = js.native + + @js.native @JSName(A.sym) + val f: Int = js.native + + @js.native @JSName(A.sym) + def g(x: Int): Int = js.native + } + + @js.native @JSGlobal + object NativeContainer2 extends js.Object { + @js.native + val a: Int = js.native + + @js.native + def b: Int = js.native + + @js.native + def c(x: Int): Int = js.native + + @js.native + val d: Int = js.native + + @js.native + def e(x: Int): Int = js.native + + @js.native @JSName(A.sym) + val f: Int = js.native + + @js.native @JSName(A.sym) + def g(x: Int): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:11: error: @js.native vals and defs can only appear in static Scala objects + | val a: Int = js.native + | ^ + |newSource1.scala:14: error: @js.native vals and defs can only appear in static Scala objects + | def b: Int = js.native + | ^ + |newSource1.scala:17: error: @js.native vals and defs can only appear in static Scala objects + | def c(x: Int): Int = js.native + | ^ + |newSource1.scala:20: error: @js.native vals and defs can only appear in static Scala objects + | val d: Int = js.native + | ^ + |newSource1.scala:23: error: @js.native vals and defs can only appear in static Scala objects + | def e(x: Int): Int = js.native + | ^ + |newSource1.scala:26: error: @js.native vals and defs can only appear in static Scala objects + | val f: Int = js.native + | ^ + |newSource1.scala:29: error: @js.native vals and defs can only appear in static Scala objects + | def g(x: Int): Int = js.native + | ^ + |newSource1.scala:35: error: @js.native vals and defs can only appear in static Scala objects + | val a: Int = js.native + | ^ + |newSource1.scala:38: error: @js.native vals and defs can only appear in static Scala objects + | def b: Int = js.native + | ^ + |newSource1.scala:41: error: @js.native vals and defs can only appear in static Scala objects + | def c(x: Int): Int = js.native + | ^ + |newSource1.scala:44: error: @js.native vals and defs can only appear in static Scala objects + | val d: Int = js.native + | ^ + |newSource1.scala:47: error: @js.native vals and defs can only appear in static Scala objects + | def e(x: Int): Int = js.native + | ^ + |newSource1.scala:50: error: @js.native vals and defs can only appear in static Scala objects + | val f: Int = js.native + | ^ + |newSource1.scala:53: error: @js.native vals and defs can only appear in static Scala objects + | def g(x: Int): Int = js.native + | ^ + |newSource1.scala:59: error: @js.native vals and defs can only appear in static Scala objects + | val a: Int = js.native + | ^ + |newSource1.scala:62: error: @js.native vals and defs can only appear in static Scala objects + | def b: Int = js.native + | ^ + |newSource1.scala:65: error: @js.native vals and defs can only appear in static Scala objects + | def c(x: Int): Int = js.native + | ^ + |newSource1.scala:68: error: @js.native vals and defs can only appear in static Scala objects + | val d: Int = js.native + | ^ + |newSource1.scala:71: error: @js.native vals and defs can only appear in static Scala objects + | def e(x: Int): Int = js.native + | ^ + |newSource1.scala:74: error: @js.native vals and defs can only appear in static Scala objects + | val f: Int = js.native + | ^ + |newSource1.scala:77: error: @js.native vals and defs can only appear in static Scala objects + | def g(x: Int): Int = js.native + | ^ + """ + } + + @Test def noJSNativeSetters: Unit = { + """ + object Container { + @js.native @JSGlobal("foo") + def foo_=(x: Int): Int = js.native + @js.native @JSGlobal("bar") + def bar_=(x: Int, y: Int): Unit = js.native + @js.native @JSGlobal("goo") + def goo_=(x: Int*): Unit = js.native + @js.native @JSGlobal("hoo") + def hoo_=(x: Int = 1): Unit = js.native + + @js.native @JSImport("module.js", "foo") + def foo2_=(x: Int): Int = js.native + @js.native @JSImport("module.js", "bar") + def bar2_=(x: Int, y: Int): Unit = js.native + @js.native @JSImport("module.js", "goo") + def goo2_=(x: Int*): Unit = js.native + @js.native @JSImport("module.js", "hoo") + def hoo2_=(x: Int = 1): Unit = js.native + } + """ hasErrors + """ + |newSource1.scala:7: error: @js.native is not allowed on vars, lazy vals and setter defs + | def foo_=(x: Int): Int = js.native + | ^ + |newSource1.scala:9: error: @js.native is not allowed on vars, lazy vals and setter defs + | def bar_=(x: Int, y: Int): Unit = js.native + | ^ + |newSource1.scala:11: error: @js.native is not allowed on vars, lazy vals and setter defs + | def goo_=(x: Int*): Unit = js.native + | ^ + |newSource1.scala:13: error: @js.native is not allowed on vars, lazy vals and setter defs + | def hoo_=(x: Int = 1): Unit = js.native + | ^ + |newSource1.scala:16: error: @js.native is not allowed on vars, lazy vals and setter defs + | def foo2_=(x: Int): Int = js.native + | ^ + |newSource1.scala:18: error: @js.native is not allowed on vars, lazy vals and setter defs + | def bar2_=(x: Int, y: Int): Unit = js.native + | ^ + |newSource1.scala:20: error: @js.native is not allowed on vars, lazy vals and setter defs + | def goo2_=(x: Int*): Unit = js.native + | ^ + |newSource1.scala:22: error: @js.native is not allowed on vars, lazy vals and setter defs + | def hoo2_=(x: Int = 1): Unit = js.native + | ^ + """ + + // containsErrors because some versions of the compiler use `_=` and some use `_=' (notice the quotes) + """ + object Container { + @js.native @JSGlobal("foo") + val foo_= : Int = js.native + } + """ containsErrors + """ + |newSource1.scala:7: error: Names of vals or vars may not end in `_= + """ + + // containsErrors because some versions of the compiler use `_=` and some use `_=' (notice the quotes) + """ + object Container { + @js.native @JSImport("module.js") + val foo_= : Int = js.native + } + """ containsErrors + """ + |newSource1.scala:7: error: Names of vals or vars may not end in `_= + """ + } + + @Test def noJSNativeVars: Unit = { + """ + object Container { + @js.native @JSGlobal("foo") + var foo: Int = js.native + } + """ hasErrors + """ + |newSource1.scala:7: error: @js.native is not allowed on vars, lazy vals and setter defs + | var foo: Int = js.native + | ^ + """ + } + + @Test def noJSNativeLazyVals: Unit = { + """ + object Container { + @js.native @JSGlobal("foo") + lazy val foo: Int = js.native + } + """ hasErrors + """ + |newSource1.scala:7: error: @js.native is not allowed on vars, lazy vals and setter defs + | lazy val foo: Int = js.native + | ^ + """ + } + + @Test def jsNativeValDefsCannotImplementAbstractMethod: Unit = { + """ + abstract class Parent { + val a: Int + def b: Int + def c(x: Int): Int + } + + object Container extends Parent { + @js.native @JSGlobal("a") + val a: Int = js.native + + @js.native @JSGlobal("b") + def b: Int = js.native + + @js.native @JSGlobal("c") + def c(x: Int): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:13: error: An @js.native member cannot implement the inherited member Parent.a + | val a: Int = js.native + | ^ + |newSource1.scala:16: error: An @js.native member cannot implement the inherited member Parent.b + | def b: Int = js.native + | ^ + |newSource1.scala:19: error: An @js.native member cannot implement the inherited member Parent.c + | def c(x: Int): Int = js.native + | ^ + """ + } + + @Test def jsNativeValDefsCannotOverrideConcreteMethod: Unit = { + """ + class Parent { + val a: Int = 1 + def b: Int = 2 + def c(x: Int): Int = x + 1 + } + + object Container extends Parent { + @js.native @JSGlobal("a") + override val a: Int = js.native + + @js.native @JSGlobal("b") + override def b: Int = js.native + + @js.native @JSGlobal("c") + override def c(x: Int): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:13: error: An @js.native member cannot override the inherited member Parent.a + | override val a: Int = js.native + | ^ + |newSource1.scala:16: error: An @js.native member cannot override the inherited member Parent.b + | override def b: Int = js.native + | ^ + |newSource1.scala:19: error: An @js.native member cannot override the inherited member Parent.c + | override def c(x: Int): Int = js.native + | ^ + """ + } + + @Test def noBadSetters: Unit = { + + """ + @js.native + @JSGlobal + class A extends js.Object { + def foo_=(x: Int): Int = js.native + def bar_=(x: Int, y: Int): Unit = js.native + def goo_=(x: Int*): Unit = js.native + def hoo_=(x: Int = 1): Unit = js.native + } + """ hasErrors + """ + |newSource1.scala:8: error: JS setters must return Unit + | def foo_=(x: Int): Int = js.native + | ^ + |newSource1.scala:9: error: JS setters must have exactly one argument + | def bar_=(x: Int, y: Int): Unit = js.native + | ^ + |newSource1.scala:10: error: JS setters may not have repeated params + | def goo_=(x: Int*): Unit = js.native + | ^ + |newSource1.scala:11: error: JS setters may not have default params + | def hoo_=(x: Int = 1): Unit = js.native + | ^ + """ + + } + + @Test def noBadBracketAccess: Unit = { + + """ + @js.native + @JSGlobal + class A extends js.Object { + @js.annotation.JSBracketAccess + def foo(): Int = js.native + + @js.annotation.JSBracketAccess + def bar(x: Int, y: Int, z: Int): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:9: error: @JSBracketAccess methods must have one or two parameters + | def foo(): Int = js.native + | ^ + |newSource1.scala:12: error: @JSBracketAccess methods must have one or two parameters + | def bar(x: Int, y: Int, z: Int): Int = js.native + | ^ + """ + + """ + @js.native + @JSGlobal + class A extends js.Object { + @js.annotation.JSBracketAccess + def foo(x: Int, y: Int): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:9: error: @JSBracketAccess methods with two parameters must return Unit + | def foo(x: Int, y: Int): Int = js.native + | ^ + """ + + """ + @js.native + @JSGlobal + class A extends js.Object { + @js.annotation.JSBracketAccess + def bar(x: Int*): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:9: error: @JSBracketAccess methods may not have repeated parameters + | def bar(x: Int*): Int = js.native + | ^ + """ + + """ + @js.native + @JSGlobal + class A extends js.Object { + @js.annotation.JSBracketAccess + def bar(x: Int = 1): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:9: error: @JSBracketAccess methods may not have default parameters + | def bar(x: Int = 1): Int = js.native + | ^ + """ + + } + + @Test def noBadBracketCall: Unit = { + + """ + @js.native + @JSGlobal + class A extends js.Object { + @js.annotation.JSBracketCall + def foo(): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:9: error: @JSBracketCall methods must have at least one non-repeated parameter + | def foo(): Int = js.native + | ^ + """ + + } + + @Test + def noJSOperatorAndJSName: Unit = { + """ + @js.native + @JSGlobal + class A extends js.Object { + @JSOperator + @JSName("bar") + def +(x: Int): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:9: error: A member can have at most one annotation among @JSName, @JSOperator, @JSBracketAccess and @JSBracketCall. + | @JSName("bar") + | ^ + """ + } + + @Test // #4284 + def noBracketAccessAndJSName: Unit = { + """ + @js.native + @JSGlobal + class A extends js.Object { + @JSBracketAccess + @JSName("bar") + def bar(x: Int): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:9: error: A member can have at most one annotation among @JSName, @JSOperator, @JSBracketAccess and @JSBracketCall. + | @JSName("bar") + | ^ + """ + } + + // #4284 + @Test def noBracketCallAndJSName: Unit = { + """ + @js.native + @JSGlobal + class A extends js.Object { + @JSBracketCall + @JSName("bar") + def bar(x: Int): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:9: error: A member can have at most one annotation among @JSName, @JSOperator, @JSBracketAccess and @JSBracketCall. + | @JSName("bar") + | ^ + """ + } + + // #4284 + @Test def noBracketAccessAndBracketCall: Unit = { + """ + @js.native + @JSGlobal + class A extends js.Object { + @JSBracketAccess + @JSBracketCall + def bar(x: Int): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:9: error: A member can have at most one annotation among @JSName, @JSOperator, @JSBracketAccess and @JSBracketCall. + | @JSBracketCall + | ^ + """ + } + + @Test def noBadUnaryOp: Unit = { + """ + @js.native + @JSGlobal + class A extends js.Object { + @JSOperator + def unary_!(x: Int*): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:9: error: @JSOperator methods with the name 'unary_!' may not have any parameters + | def unary_!(x: Int*): Int = js.native + | ^ + """ + + """ + @js.native + @JSGlobal + class A extends js.Object { + @JSOperator + def unary_-(x: Int): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:9: error: @JSOperator methods with the name 'unary_-' may not have any parameters + | def unary_-(x: Int): Int = js.native + | ^ + """ + + """ + @js.native + @JSGlobal + class A extends js.Object { + @JSOperator + def unary_%(): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:9: error: @JSOperator cannot be used on a method with the name 'unary_%' because it is not one of the JavaScript operators + | def unary_%(): Int = js.native + | ^ + """ + } + + @Test def noBadBinaryOp: Unit = { + """ + @js.native + @JSGlobal + class A extends js.Object { + def +(x: Int*): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:8: warning: Method '+' should have an explicit @JSName or @JSOperator annotation because its name is one of the JavaScript operators + | def +(x: Int*): Int = js.native + | ^ + |newSource1.scala:8: error: methods representing binary operations may not have repeated parameters + | def +(x: Int*): Int = js.native + | ^ + """ + + """ + @js.native + @JSGlobal + class A extends js.Object { + @JSOperator + def +(x: Int*): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:9: error: methods representing binary operations may not have repeated parameters + | def +(x: Int*): Int = js.native + | ^ + """ + + """ + @js.native + @JSGlobal + class A extends js.Object { + @JSOperator + def +(x: Int, y: Int): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:9: error: @JSOperator methods with the name '+' must have exactly one parameter + | def +(x: Int, y: Int): Int = js.native + | ^ + """ + + """ + @js.native + @JSGlobal + class A extends js.Object { + @JSOperator + def %%(x: Int): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:9: error: @JSOperator cannot be used on a method with the name '%%' because it is not one of the JavaScript operators + | def %%(x: Int): Int = js.native + | ^ + """ + } + + @Test def onlyJSTraits: Unit = { + + """ + trait A + + @js.native + @JSGlobal + class B extends js.Object with A + """ hasErrors + """ + |newSource1.scala:9: error: B extends A which does not extend js.Any. + | class B extends js.Object with A + | ^ + """ + + """ + @js.native + @JSGlobal + class B extends js.Object with java.io.Serializable + """ hasErrors + """ + |newSource1.scala:7: error: B extends java.io.Serializable which does not extend js.Any. + | class B extends js.Object with java.io.Serializable + | ^ + """ + + } + + @Test def noCaseClassObject: Unit = { + + """ + @js.native + @JSGlobal + case class A(x: Int) extends js.Object + """ hasErrors + """ + |newSource1.scala:7: error: Classes and objects extending js.Any may not have a case modifier + | case class A(x: Int) extends js.Object + | ^ + """ + + """ + @js.native + @JSGlobal + case object B extends js.Object + """ hasErrors + """ + |newSource1.scala:7: error: Classes and objects extending js.Any may not have a case modifier + | case object B extends js.Object + | ^ + """ + + """ + case class A(x: Int) extends js.Object + """ hasErrors + """ + |newSource1.scala:5: error: Classes and objects extending js.Any may not have a case modifier + | case class A(x: Int) extends js.Object + | ^ + """ + + """ + case object B extends js.Object + """ hasErrors + """ + |newSource1.scala:5: error: Classes and objects extending js.Any may not have a case modifier + | case object B extends js.Object + | ^ + """ + + } + + @Test def noNativeJSNestedInScalaClassTrait: Unit = { + + val outers = List("class", "trait") + val inners = List("trait", "class", "object") + + for { + outer <- outers + inner <- inners + } yield { + val jsGlobalAnnot = + if (inner == "trait") "" + else "@JSGlobal" + + val errTrg = if (inner == "object") "objects" else "classes" + + s""" + $outer A { + @js.native $jsGlobalAnnot + $inner Inner extends js.Object + } + """ hasErrors + s""" + |newSource1.scala:7: error: Scala traits and classes may not have native JS members + | $inner Inner extends js.Object + | ${" " * inner.length}^ + """ + } + + } + + @Test def noNativeJSNestedInNonNativeJS: Unit = { + + val outers = List("class", "trait", "object") + val inners = List("class", "trait", "object") + + for { + outer <- outers + inner <- inners + } yield { + val jsGlobalAnnot = + if (inner == "trait") "" + else "@JSGlobal" + + val errTrg = if (inner == "object") "objects" else "classes" + + s""" + $outer A extends js.Object { + @js.native $jsGlobalAnnot + $inner Inner extends js.Object + } + """ hasErrors + s""" + |newSource1.scala:7: error: non-native JS classes, traits and objects may not have native JS members + | $inner Inner extends js.Object + | ${" " * inner.length}^ + """ + } + + } + + @Test def noLocalJSNative: Unit = { + """ + object A { + def a = { + @js.native @JSGlobal + class B extends js.Object + + @js.native @JSGlobal + object C extends js.Object + + @js.native @JSGlobal + val d: Int = js.native + + @js.native @JSGlobal + var e: Int = js.native + + @js.native @JSGlobal + def f: Int = js.native + + @js.native @JSGlobal + def f_=(v: Int): Unit = js.native + + @js.native @JSGlobal + def g(x: Int): Int = js.native + + @js.native @JSGlobal + lazy val h: Int = js.native + } + } + """ hasErrors + """ + |newSource1.scala:8: error: @js.native is not allowed on local definitions + | class B extends js.Object + | ^ + |newSource1.scala:11: error: @js.native is not allowed on local definitions + | object C extends js.Object + | ^ + |newSource1.scala:14: error: @js.native is not allowed on local definitions + | val d: Int = js.native + | ^ + |newSource1.scala:17: error: @js.native is not allowed on local definitions + | var e: Int = js.native + | ^ + |newSource1.scala:20: error: @js.native is not allowed on local definitions + | def f: Int = js.native + | ^ + |newSource1.scala:23: error: @js.native is not allowed on local definitions + | def f_=(v: Int): Unit = js.native + | ^ + |newSource1.scala:26: error: @js.native is not allowed on local definitions + | def g(x: Int): Int = js.native + | ^ + |newSource1.scala:29: error: @js.native is not allowed on local definitions + | lazy val h: Int = js.native + | ^ + """ + } + + @Test def noNativeInJSAny: Unit = { + + """ + @js.native + @JSGlobal + class A extends js.Object { + @native + def value: Int = js.native + } + """ hasErrors + """ + |newSource1.scala:9: error: Methods in a js.Any may not be @native + | def value: Int = js.native + | ^ + """ + + } + + @Test def checkJSAnyBody: Unit = { + + """ + @js.native + @JSGlobal + class A extends js.Object { + def value: Int = ??? + val x: Int = ??? + } + """ hasErrors + """ + |newSource1.scala:8: error: Concrete members of JS native types may only call js.native. + | def value: Int = ??? + | ^ + |newSource1.scala:9: error: Concrete members of JS native types may only call js.native. + | val x: Int = ??? + | ^ + """ + + } + + @Test def noWarnJSAnyDeferred: Unit = { + + """ + @js.native + @JSGlobal + abstract class A extends js.Object { + def value: Int + val x: Int + } + """.hasNoWarns() + + """ + @js.native + trait A extends js.Object { + def value: Int + val x: Int + } + """.hasNoWarns() + + } + + @Test def noCallSecondaryCtor: Unit = { + + """ + @js.native + @JSGlobal + class A(x: Int, y: Int) extends js.Object { + def this(x: Int) = this(x, 5) + def this() = this(7) + } + """ hasErrors + """ + |newSource1.scala:9: error: A secondary constructor of a class extending js.Any may only call the primary constructor + | def this() = this(7) + | ^ + """ + + } + + @Test def noPrivateMemberInNative: Unit = { + + """ + @js.native + @JSGlobal + class A extends js.Object { + private[this] val a: Int = js.native + private val b: Int = js.native + private[A] val c: Int = js.native + + private[this] var d: Int = js.native + private var e: Int = js.native + private[A] var f: Int = js.native + + private[this] def g(): Int = js.native + private def h(): Int = js.native + private[A] def i(): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:8: error: Native JS classes may not have private members. Use a public member in a private facade instead. + | private[this] val a: Int = js.native + | ^ + |newSource1.scala:9: error: Native JS classes may not have private members. Use a public member in a private facade instead. + | private val b: Int = js.native + | ^ + |newSource1.scala:10: error: Native JS classes may not have private members. Use a public member in a private facade instead. + | private[A] val c: Int = js.native + | ^ + |newSource1.scala:12: error: Native JS classes may not have private members. Use a public member in a private facade instead. + | private[this] var d: Int = js.native + | ^ + |newSource1.scala:13: error: Native JS classes may not have private members. Use a public member in a private facade instead. + | private var e: Int = js.native + | ^ + |newSource1.scala:14: error: Native JS classes may not have private members. Use a public member in a private facade instead. + | private[A] var f: Int = js.native + | ^ + |newSource1.scala:16: error: Native JS classes may not have private members. Use a public member in a private facade instead. + | private[this] def g(): Int = js.native + | ^ + |newSource1.scala:17: error: Native JS classes may not have private members. Use a public member in a private facade instead. + | private def h(): Int = js.native + | ^ + |newSource1.scala:18: error: Native JS classes may not have private members. Use a public member in a private facade instead. + | private[A] def i(): Int = js.native + | ^ + """ + + } + + @Test def noPrivateConstructorInNative: Unit = { + + """ + @js.native + @JSGlobal + class A private () extends js.Object + """ hasErrors + """ + |newSource1.scala:7: error: Native JS classes may not have private constructors. Use `private[this]` to declare an internal constructor. + | class A private () extends js.Object + | ^ + """ + + """ + @js.native + @JSGlobal + class A private[A] () extends js.Object + """ hasErrors + """ + |newSource1.scala:7: error: Native JS classes may not have private constructors. Use `private[this]` to declare an internal constructor. + | class A private[A] () extends js.Object + | ^ + """ + + """ + @js.native + @JSGlobal + class A private[this] () extends js.Object + """.hasNoWarns() + + } + + @Test def noUseJsNative: Unit = { + + """ + class A { + def foo = js.native + } + """ hasErrors + """ + |newSource1.scala:6: error: js.native may only be used as stub implementation in facade types + | def foo = js.native + | ^ + """ + + } + + @Test def warnNothingInNativeJS: Unit = { + + """ + @js.native + @JSGlobal + class A extends js.Object { + def foo = js.native + val bar = js.native + } + """ hasWarns + """ + |newSource1.scala:8: warning: The type of foo got inferred as Nothing. To suppress this warning, explicitly ascribe the type. + | def foo = js.native + | ^ + |newSource1.scala:9: warning: The type of bar got inferred as Nothing. To suppress this warning, explicitly ascribe the type. + | val bar = js.native + | ^ + """ + + } + + @Test def nativeClassHasLoadingSpec: Unit = { + """ + @js.native + class A extends js.Object + + @js.native + abstract class B extends js.Object + + object Container { + @js.native + class C extends js.Object + } + """ hasErrors + """ + |newSource1.scala:6: error: Native JS classes, vals and defs must have exactly one annotation among @JSGlobal and @JSImport. + | class A extends js.Object + | ^ + |newSource1.scala:9: error: Native JS classes, vals and defs must have exactly one annotation among @JSGlobal and @JSImport. + | abstract class B extends js.Object + | ^ + |newSource1.scala:13: error: Native JS classes, vals and defs must have exactly one annotation among @JSGlobal and @JSImport. + | class C extends js.Object + | ^ + """ + } + + @Test def nativeObjectHasLoadingSpec: Unit = { + """ + @js.native + object A extends js.Object + + object Container { + @js.native + object B extends js.Object + } + """ hasErrors + """ + |newSource1.scala:6: error: Native JS objects must have exactly one annotation among @JSGlobal, @JSImport and @JSGlobalScope. + | object A extends js.Object + | ^ + |newSource1.scala:10: error: Native JS objects must have exactly one annotation among @JSGlobal, @JSImport and @JSGlobalScope. + | object B extends js.Object + | ^ + """ + } + + @Test def noNativeDefinitionNamedApplyWithoutExplicitName: Unit = { + + """ + @js.native + @JSGlobal + class apply extends js.Object + + @js.native + @JSGlobal + object apply extends js.Object + """ hasErrors + """ + |newSource1.scala:6: error: Native JS definitions named 'apply' must have an explicit name in @JSGlobal + | @JSGlobal + | ^ + |newSource1.scala:10: error: Native JS definitions named 'apply' must have an explicit name in @JSGlobal + | @JSGlobal + | ^ + """ + + """ + @js.native + @JSImport("foo.js") + class apply extends js.Object + + @js.native + @JSImport("foo.js") + object apply extends js.Object + """ hasErrors + """ + |newSource1.scala:6: error: Native JS definitions named 'apply' must have an explicit name in @JSImport + | @JSImport("foo.js") + | ^ + |newSource1.scala:10: error: Native JS definitions named 'apply' must have an explicit name in @JSImport + | @JSImport("foo.js") + | ^ + """ + + """ + object A { + @js.native + @JSGlobal + class apply extends js.Object + + @js.native + @JSGlobal + object apply extends js.Object + } + """ hasErrors + """ + |newSource1.scala:7: error: Native JS definitions named 'apply' must have an explicit name in @JSGlobal + | @JSGlobal + | ^ + |newSource1.scala:11: error: Native JS definitions named 'apply' must have an explicit name in @JSGlobal + | @JSGlobal + | ^ + """ + + """ + object A { + @js.native + @JSImport("foo.js") + class apply extends js.Object + + @js.native + @JSImport("foo.js") + object apply extends js.Object + } + """ hasErrors + """ + |newSource1.scala:7: error: Native JS definitions named 'apply' must have an explicit name in @JSImport + | @JSImport("foo.js") + | ^ + |newSource1.scala:11: error: Native JS definitions named 'apply' must have an explicit name in @JSImport + | @JSImport("foo.js") + | ^ + """ + + """ + package object A { + @js.native + @JSGlobal + class apply extends js.Object + + @js.native + @JSGlobal + object apply extends js.Object + } + """ hasErrors + """ + |newSource1.scala:7: error: Native JS definitions named 'apply' must have an explicit name in @JSGlobal + | @JSGlobal + | ^ + |newSource1.scala:11: error: Native JS definitions named 'apply' must have an explicit name in @JSGlobal + | @JSGlobal + | ^ + """ + + """ + package object A { + @js.native + @JSImport("foo.js") + class apply extends js.Object + + @js.native + @JSImport("foo.js") + object apply extends js.Object + } + """ hasErrors + """ + |newSource1.scala:7: error: Native JS definitions named 'apply' must have an explicit name in @JSImport + | @JSImport("foo.js") + | ^ + |newSource1.scala:11: error: Native JS definitions named 'apply' must have an explicit name in @JSImport + | @JSImport("foo.js") + | ^ + """ + + """ + object A { + @js.native + @JSGlobal + val apply: Int = js.native + } + """ hasErrors + """ + |newSource1.scala:7: error: Native JS definitions named 'apply' must have an explicit name in @JSGlobal + | @JSGlobal + | ^ + """ + + """ + object A { + @js.native + @JSImport("foo.js") + val apply: Int = js.native + } + """ hasErrors + """ + |newSource1.scala:7: error: Native JS definitions named 'apply' must have an explicit name in @JSImport + | @JSImport("foo.js") + | ^ + """ + + """ + object A { + @js.native + @JSGlobal + def apply: Int = js.native + } + """ hasErrors + """ + |newSource1.scala:7: error: Native JS definitions named 'apply' must have an explicit name in @JSGlobal + | @JSGlobal + | ^ + """ + + """ + object A { + @js.native + @JSImport("foo.js") + def apply: Int = js.native + } + """ hasErrors + """ + |newSource1.scala:7: error: Native JS definitions named 'apply' must have an explicit name in @JSImport + | @JSImport("foo.js") + | ^ + """ + + """ + object A { + @js.native + @JSGlobal + def apply(x: Int): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:7: error: Native JS definitions named 'apply' must have an explicit name in @JSGlobal + | @JSGlobal + | ^ + """ + + """ + object A { + @js.native + @JSImport("foo.js") + def apply(x: Int): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:7: error: Native JS definitions named 'apply' must have an explicit name in @JSImport + | @JSImport("foo.js") + | ^ + """ + + """ + @JSGlobal("apply") + @js.native + class apply extends js.Object + + @JSGlobal("apply") + @js.native + object apply extends js.Object + + object A { + @JSGlobal("apply") + @js.native + class apply extends js.Object + + @JSGlobal("apply") + @js.native + object apply extends js.Object + } + + object B { + @JSGlobal("apply") + @js.native + val apply: Int = js.native + } + + object C { + @JSGlobal("apply") + @js.native + def apply: Int = js.native + } + + object D { + @JSGlobal("apply") + @js.native + def apply(x: Int): Int = js.native + } + """.hasNoWarns() + + """ + @JSImport("foo.js", "apply") + @js.native + class apply extends js.Object + + @JSImport("foo.js", "apply") + @js.native + object apply extends js.Object + + object A { + @JSImport("foo.js", "apply") + @js.native + class apply extends js.Object + + @JSImport("foo.js", "apply") + @js.native + object apply extends js.Object + } + + object B { + @JSImport("foo.js", "apply") + @js.native + val apply: Int = js.native + } + + object C { + @JSImport("foo.js", "apply") + @js.native + def apply: Int = js.native + } + + object D { + @JSImport("foo.js", "apply") + @js.native + def apply(x: Int): Int = js.native + } + """.hasNoWarns() + + """ + @JSImport("foo.js", "apply", globalFallback = "apply") + @js.native + class apply extends js.Object + + @JSImport("foo.js", "apply", globalFallback = "apply") + @js.native + object apply extends js.Object + + object A { + @JSImport("foo.js", "apply", globalFallback = "apply") + @js.native + class apply extends js.Object + + @JSImport("foo.js", "apply", globalFallback = "apply") + @js.native + object apply extends js.Object + } + """.hasNoWarns() + + } + + @Test def noNativeDefinitionWithSetterNameWithoutExplicitName: Unit = { + + """ + @js.native + @JSGlobal + class foo_= extends js.Object + + @js.native + @JSGlobal + object foo_= extends js.Object + """ hasErrors + """ + |newSource1.scala:6: error: Native JS definitions with a name ending in '_=' must have an explicit name in @JSGlobal + | @JSGlobal + | ^ + |newSource1.scala:10: error: Native JS definitions with a name ending in '_=' must have an explicit name in @JSGlobal + | @JSGlobal + | ^ + """ + + """ + @js.native + @JSImport("foo.js") + class foo_= extends js.Object + + @js.native + @JSImport("foo.js") + object foo_= extends js.Object + """ hasErrors + """ + |newSource1.scala:6: error: Native JS definitions with a name ending in '_=' must have an explicit name in @JSImport + | @JSImport("foo.js") + | ^ + |newSource1.scala:10: error: Native JS definitions with a name ending in '_=' must have an explicit name in @JSImport + | @JSImport("foo.js") + | ^ + """ + + """ + object A { + @js.native + @JSGlobal + class foo_= extends js.Object + + @js.native + @JSGlobal + object foo_= extends js.Object + } + """ hasErrors + """ + |newSource1.scala:7: error: Native JS definitions with a name ending in '_=' must have an explicit name in @JSGlobal + | @JSGlobal + | ^ + |newSource1.scala:11: error: Native JS definitions with a name ending in '_=' must have an explicit name in @JSGlobal + | @JSGlobal + | ^ + """ + + """ + object A { + @js.native + @JSImport("foo.js") + class foo_= extends js.Object + + @js.native + @JSImport("foo.js") + object foo_= extends js.Object + } + """ hasErrors + """ + |newSource1.scala:7: error: Native JS definitions with a name ending in '_=' must have an explicit name in @JSImport + | @JSImport("foo.js") + | ^ + |newSource1.scala:11: error: Native JS definitions with a name ending in '_=' must have an explicit name in @JSImport + | @JSImport("foo.js") + | ^ + """ + + """ + package object A { + @js.native + @JSGlobal + class foo_= extends js.Object + + @js.native + @JSGlobal + object foo_= extends js.Object + } + """ hasErrors + """ + |newSource1.scala:7: error: Native JS definitions with a name ending in '_=' must have an explicit name in @JSGlobal + | @JSGlobal + | ^ + |newSource1.scala:11: error: Native JS definitions with a name ending in '_=' must have an explicit name in @JSGlobal + | @JSGlobal + | ^ + """ + + """ + package object A { + @js.native + @JSImport("foo.js") + class foo_= extends js.Object + + @js.native + @JSImport("foo.js") + object foo_= extends js.Object + } + """ hasErrors + """ + |newSource1.scala:7: error: Native JS definitions with a name ending in '_=' must have an explicit name in @JSImport + | @JSImport("foo.js") + | ^ + |newSource1.scala:11: error: Native JS definitions with a name ending in '_=' must have an explicit name in @JSImport + | @JSImport("foo.js") + | ^ + """ + + // containsErrors because some versions of the compiler use `_=` and some use `_=' (notice the quotes) + """ + object A { + @js.native + @JSGlobal + val foo_= : Int = js.native + } + """ containsErrors + """ + |newSource1.scala:8: error: Names of vals or vars may not end in `_= + """ + + // containsErrors because some versions of the compiler use `_=` and some use `_=' (notice the quotes) + """ + object A { + @js.native + @JSImport("foo.js") + val foo_= : Int = js.native + } + """ containsErrors + """ + |newSource1.scala:8: error: Names of vals or vars may not end in `_= + """ + + // containsErrors because some versions of the compiler use `_=` and some use `_=' (notice the quotes) + """ + object A { + @js.native + @JSGlobal + var foo_= : Int = js.native + } + """ containsErrors + """ + |newSource1.scala:8: error: Names of vals or vars may not end in `_= + """ + + """ + object A { + @js.native + @JSGlobal + def foo_= : Int = js.native + } + """ hasErrors + """ + |newSource1.scala:7: error: Native JS definitions with a name ending in '_=' must have an explicit name in @JSGlobal + | @JSGlobal + | ^ + |newSource1.scala:8: error: @js.native is not allowed on vars, lazy vals and setter defs + | def foo_= : Int = js.native + | ^ + """ + + """ + object A { + @js.native + @JSGlobal("foo") + def foo_= : Int = js.native + } + """ hasErrors + """ + |newSource1.scala:8: error: @js.native is not allowed on vars, lazy vals and setter defs + | def foo_= : Int = js.native + | ^ + """ + + """ + object A { + @js.native + @JSImport("foo.js") + def foo_= : Int = js.native + } + """ hasErrors + """ + |newSource1.scala:7: error: Native JS definitions with a name ending in '_=' must have an explicit name in @JSImport + | @JSImport("foo.js") + | ^ + |newSource1.scala:8: error: @js.native is not allowed on vars, lazy vals and setter defs + | def foo_= : Int = js.native + | ^ + """ + + """ + object A { + @js.native + @JSImport("foo.js", "foo") + def foo_= : Int = js.native + } + """ hasErrors + """ + |newSource1.scala:8: error: @js.native is not allowed on vars, lazy vals and setter defs + | def foo_= : Int = js.native + | ^ + """ + + """ + object A { + @js.native + @JSGlobal + def foo_=(x: Int): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:7: error: Native JS definitions with a name ending in '_=' must have an explicit name in @JSGlobal + | @JSGlobal + | ^ + |newSource1.scala:8: error: @js.native is not allowed on vars, lazy vals and setter defs + | def foo_=(x: Int): Int = js.native + | ^ + """ + + """ + object A { + @js.native + @JSGlobal("foo") + def foo_=(x: Int): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:8: error: @js.native is not allowed on vars, lazy vals and setter defs + | def foo_=(x: Int): Int = js.native + | ^ + """ + + """ + object A { + @js.native + @JSImport("foo.js") + def foo_=(x: Int): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:7: error: Native JS definitions with a name ending in '_=' must have an explicit name in @JSImport + | @JSImport("foo.js") + | ^ + |newSource1.scala:8: error: @js.native is not allowed on vars, lazy vals and setter defs + | def foo_=(x: Int): Int = js.native + | ^ + """ + + """ + object A { + @js.native + @JSImport("foo.js", "foo") + def foo_=(x: Int): Int = js.native + } + """ hasErrors + """ + |newSource1.scala:8: error: @js.native is not allowed on vars, lazy vals and setter defs + | def foo_=(x: Int): Int = js.native + | ^ + """ + + """ + @JSGlobal("foo") + @js.native + class foo_= extends js.Object + + @JSGlobal("foo") + @js.native + object foo_= extends js.Object + + object A { + @JSGlobal("foo") + @js.native + class foo_= extends js.Object + + @JSGlobal("foo") + @js.native + object foo_= extends js.Object + } + """.hasNoWarns() + + """ + @JSImport("foo.js", "foo_=") + @js.native + class foo_= extends js.Object + + @JSImport("foo.js", "foo_=") + @js.native + object foo_= extends js.Object + + object A { + @JSImport("foo.js", "foo_=") + @js.native + class foo_= extends js.Object + + @JSImport("foo.js", "foo_=") + @js.native + object foo_= extends js.Object + } + """.hasNoWarns() + + """ + @JSImport("foo.js", "foo_=", globalFallback = "foo") + @js.native + class foo_= extends js.Object + + @JSImport("foo.js", "foo_=", globalFallback = "foo") + @js.native + object foo_= extends js.Object + + object A { + @JSImport("foo.js", "foo_=", globalFallback = "foo") + @js.native + class foo_= extends js.Object + + @JSImport("foo.js", "foo_=", globalFallback = "foo") + @js.native + object foo_= extends js.Object + } + """.hasNoWarns() + + } + + @Test def noNonLiteralJSName: Unit = { + + """ + import js.annotation.JSName + + object A { + val a = "Hello" + final val b = "World" + } + + @js.native + @JSGlobal + class B extends js.Object { + @JSName(A.a) + def foo: Int = js.native + @JSName(A.b) + def bar: Int = js.native + } + """ hasErrors + """ + |newSource1.scala:15: error: A string argument to JSName must be a literal string + | @JSName(A.a) + | ^ + """ + + } + + @Test def noNonStaticStableJSNameSymbol: Unit = { + + """ + import js.annotation.JSName + + class A { + val a = js.Symbol("foo") + } + + @js.native + @JSGlobal + class B extends js.Object { + @JSName(js.Symbol()) + def foo: Int = js.native + @JSName(new A().a) + def bar: Int = js.native + } + + class C extends js.Object { + @JSName(js.Symbol()) + def foo: Int = js.native + @JSName(new A().a) + def bar: Int = js.native + } + """ hasErrors + """ + |newSource1.scala:14: error: A js.Symbol argument to JSName must be a static, stable identifier + | @JSName(js.Symbol()) + | ^ + |newSource1.scala:16: error: A js.Symbol argument to JSName must be a static, stable identifier + | @JSName(new A().a) + | ^ + |newSource1.scala:21: error: A js.Symbol argument to JSName must be a static, stable identifier + | @JSName(js.Symbol()) + | ^ + |newSource1.scala:23: error: A js.Symbol argument to JSName must be a static, stable identifier + | @JSName(new A().a) + | ^ + """ + + } + + @Test def noSelfReferenceJSNameSymbol: Unit = { + + """ + object A extends js.Object { + val a = js.Symbol("foo") + + @JSName(a) + def foo: Int = 1 + } + """ hasWarns + """ + |newSource1.scala:8: warning: This symbol is defined in the same object as the annotation's target. This will cause a stackoverflow at runtime + | @JSName(a) + | ^ + """ + + // Native objects are OK, since we do not control definition order. + """ + @JSGlobal + @js.native + object A extends js.Object { + val a: js.Symbol = js.native + + @JSName(a) + def foo: Int = js.native + } + """.succeeds() + + } + + @Test def noJSGlobalOnMembersOfClassesAndTraits: Unit = { + + for (outer <- Seq("class", "trait")) { + s""" + @js.native ${if (outer == "trait") "" else "@JSGlobal"} + $outer Foo extends js.Object { + @JSGlobal("bar1") + val bar1: Int = js.native + @JSGlobal("bar2") + var bar2: Int = js.native + @JSGlobal("bar3") + def bar3: Int = js.native + + @js.native + @JSGlobal("Inner") + class Inner extends js.Object + + @js.native + @JSGlobal("Inner") + object Inner extends js.Object + + @js.native + @JSGlobal + class InnerImplied extends js.Object + + @js.native + @JSGlobal + object InnerImplied extends js.Object + } + """ hasErrors + """ + |newSource1.scala:7: error: @JSGlobal can only be used on native JS definitions (with @js.native). + | @JSGlobal("bar1") + | ^ + |newSource1.scala:9: error: @JSGlobal can only be used on native JS definitions (with @js.native). + | @JSGlobal("bar2") + | ^ + |newSource1.scala:11: error: @JSGlobal can only be used on native JS definitions (with @js.native). + | @JSGlobal("bar3") + | ^ + |newSource1.scala:15: error: Nested JS classes and objects cannot have an @JSGlobal annotation. + | @JSGlobal("Inner") + | ^ + |newSource1.scala:19: error: Nested JS classes and objects cannot have an @JSGlobal annotation. + | @JSGlobal("Inner") + | ^ + |newSource1.scala:23: error: Nested JS classes and objects cannot have an @JSGlobal annotation. + | @JSGlobal + | ^ + |newSource1.scala:27: error: Nested JS classes and objects cannot have an @JSGlobal annotation. + | @JSGlobal + | ^ + """ + } + + } + + @Test def noJSGlobalOnMembersOfObjects: Unit = { + + s""" + @js.native @JSGlobal + object Foo extends js.Object { + @JSGlobal("bar1") + val bar1: Int = js.native + @JSGlobal("bar2") + var bar2: Int = js.native + @JSGlobal("bar3") + def bar3: Int = js.native + + @js.native + @JSGlobal("Inner") + class Inner extends js.Object + + @js.native + @JSGlobal("Inner") + object Inner extends js.Object + + @js.native + @JSGlobal + class InnerImplied extends js.Object + + @js.native + @JSGlobal + object InnerImplied extends js.Object + } + """ hasErrors + """ + |newSource1.scala:7: error: @JSGlobal can only be used on native JS definitions (with @js.native). + | @JSGlobal("bar1") + | ^ + |newSource1.scala:9: error: @JSGlobal can only be used on native JS definitions (with @js.native). + | @JSGlobal("bar2") + | ^ + |newSource1.scala:11: error: @JSGlobal can only be used on native JS definitions (with @js.native). + | @JSGlobal("bar3") + | ^ + |newSource1.scala:15: error: Nested JS classes and objects cannot have an @JSGlobal annotation. + | @JSGlobal("Inner") + | ^ + |newSource1.scala:19: error: Nested JS classes and objects cannot have an @JSGlobal annotation. + | @JSGlobal("Inner") + | ^ + |newSource1.scala:23: error: Nested JS classes and objects cannot have an @JSGlobal annotation. + | @JSGlobal + | ^ + |newSource1.scala:27: error: Nested JS classes and objects cannot have an @JSGlobal annotation. + | @JSGlobal + | ^ + """ + + } + + @Test def noJSImportOnMembersOfClassesAndTraits: Unit = { + + for { + outer <- Seq("class", "trait") + fallbackStr <- Seq("", ", globalFallback = \"Foo\"") + } { + s""" + @js.native ${if (outer == "trait") "" else "@JSGlobal"} + $outer Foo extends js.Object { + @JSImport("bar1", JSImport.Namespace$fallbackStr) + val bar1: Int = js.native + @JSImport("bar2", JSImport.Namespace$fallbackStr) + var bar2: Int = js.native + @JSImport("bar3", JSImport.Namespace$fallbackStr) + def bar3: Int = js.native + + @js.native + @JSImport("Inner", JSImport.Namespace$fallbackStr) + class Inner extends js.Object + + @js.native + @JSImport("Inner", JSImport.Namespace$fallbackStr) + object Inner extends js.Object + } + """ hasErrors + s""" + |newSource1.scala:7: error: @JSImport can only be used on native JS definitions (with @js.native). + | @JSImport("bar1", JSImport.Namespace$fallbackStr) + | ^ + |newSource1.scala:9: error: @JSImport can only be used on native JS definitions (with @js.native). + | @JSImport("bar2", JSImport.Namespace$fallbackStr) + | ^ + |newSource1.scala:11: error: @JSImport can only be used on native JS definitions (with @js.native). + | @JSImport("bar3", JSImport.Namespace$fallbackStr) + | ^ + |newSource1.scala:15: error: Nested JS classes and objects cannot have an @JSImport annotation. + | @JSImport("Inner", JSImport.Namespace$fallbackStr) + | ^ + |newSource1.scala:19: error: Nested JS classes and objects cannot have an @JSImport annotation. + | @JSImport("Inner", JSImport.Namespace$fallbackStr) + | ^ + """ + } + + } + + @Test def noJSImportOnMembersOfObjects: Unit = { + + for { + fallbackStr <- Seq("", ", globalFallback = \"Foo\"") + } { + s""" + @js.native @JSGlobal + object Foo extends js.Object { + @JSImport("bar1", JSImport.Namespace$fallbackStr) + val bar1: Int = js.native + @JSImport("bar2", JSImport.Namespace$fallbackStr) + var bar2: Int = js.native + @JSImport("bar3", JSImport.Namespace$fallbackStr) + def bar3: Int = js.native + + @js.native + @JSImport("Inner", JSImport.Namespace$fallbackStr) + class Inner extends js.Object + + @js.native + @JSImport("Inner", JSImport.Namespace$fallbackStr) + object Inner extends js.Object + } + """ hasErrors + s""" + |newSource1.scala:7: error: @JSImport can only be used on native JS definitions (with @js.native). + | @JSImport("bar1", JSImport.Namespace$fallbackStr) + | ^ + |newSource1.scala:9: error: @JSImport can only be used on native JS definitions (with @js.native). + | @JSImport("bar2", JSImport.Namespace$fallbackStr) + | ^ + |newSource1.scala:11: error: @JSImport can only be used on native JS definitions (with @js.native). + | @JSImport("bar3", JSImport.Namespace$fallbackStr) + | ^ + |newSource1.scala:15: error: Nested JS classes and objects cannot have an @JSImport annotation. + | @JSImport("Inner", JSImport.Namespace$fallbackStr) + | ^ + |newSource1.scala:19: error: Nested JS classes and objects cannot have an @JSImport annotation. + | @JSImport("Inner", JSImport.Namespace$fallbackStr) + | ^ + """ + } + + } + + @Test def noNonLiteralJSGlobal: Unit = { + + """ + object A { + val a = "Hello" + } + + @JSGlobal(A.a) + @js.native + object B extends js.Object + + @JSGlobal(A.a) + @js.native + class C extends js.Object + """ hasErrors + """ + |newSource1.scala:9: error: The argument to @JSGlobal must be a literal string. + | @JSGlobal(A.a) + | ^ + |newSource1.scala:13: error: The argument to @JSGlobal must be a literal string. + | @JSGlobal(A.a) + | ^ + """ + + } + + @Test def noNonJSIdentifierJSGlobal: Unit = { + + """ + @js.native + @JSGlobal + class `not-a-valid-JS-identifier` extends js.Object + + @js.native + @JSGlobal("not-a-valid-JS-identifier") + object A extends js.Object + + @js.native + @JSGlobal("not-a-valid-JS-identifier.further") + object B extends js.Object + + @js.native + @JSGlobal("TopLevel.not-a-valid-JS-identifier") // valid + object C extends js.Object + + @js.native + @JSGlobal("") + object D extends js.Object + + @js.native + @JSGlobal(".tricky") + object E extends js.Object + """ hasErrors + """ + |newSource1.scala:7: error: The name of a JS global variable must be a valid JS identifier (got 'not-a-valid-JS-identifier') + | class `not-a-valid-JS-identifier` extends js.Object + | ^ + |newSource1.scala:11: error: The name of a JS global variable must be a valid JS identifier (got 'not-a-valid-JS-identifier') + | object A extends js.Object + | ^ + |newSource1.scala:15: error: The name of a JS global variable must be a valid JS identifier (got 'not-a-valid-JS-identifier') + | object B extends js.Object + | ^ + |newSource1.scala:23: error: The name of a JS global variable must be a valid JS identifier (got '') + | object D extends js.Object + | ^ + |newSource1.scala:27: error: The name of a JS global variable must be a valid JS identifier (got '') + | object E extends js.Object + | ^ + """ + + """ + @js.native + @JSImport("foo.js", "foo", globalFallback = "not-a-valid-JS-identifier") + object A extends js.Object + + @js.native + @JSImport("foo.js", "foo", globalFallback = "not-a-valid-JS-identifier.further") + object B extends js.Object + + @js.native + @JSImport("foo.js", "foo", globalFallback = "TopLevel.not-a-valid-JS-identifier") // valid + object C extends js.Object + + @js.native + @JSImport("foo.js", "foo", globalFallback = "") + object D extends js.Object + + @js.native + @JSImport("foo.js", "foo", globalFallback = ".tricky") + object E extends js.Object + """ hasErrors + """ + |newSource1.scala:7: error: The name of a JS global variable must be a valid JS identifier (got 'not-a-valid-JS-identifier') + | object A extends js.Object + | ^ + |newSource1.scala:11: error: The name of a JS global variable must be a valid JS identifier (got 'not-a-valid-JS-identifier') + | object B extends js.Object + | ^ + |newSource1.scala:19: error: The name of a JS global variable must be a valid JS identifier (got '') + | object D extends js.Object + | ^ + |newSource1.scala:23: error: The name of a JS global variable must be a valid JS identifier (got '') + | object E extends js.Object + | ^ + """ + + } + + @Test def noNonLiteralJSImport: Unit = { + + // Without global fallback + + """ + object A { + val a = "Hello" + } + + @JSImport(A.a, JSImport.Namespace) + @js.native + object B1 extends js.Object + + @JSImport(A.a, "B2") + @js.native + object B2 extends js.Object + + @JSImport("B3", A.a) + @js.native + object B3 extends js.Object + + @JSImport(A.a, JSImport.Namespace) + @js.native + object C1 extends js.Object + + @JSImport(A.a, "C2") + @js.native + object C2 extends js.Object + + @JSImport("C3", A.a) + @js.native + object C3 extends js.Object + + @JSImport(A.a, A.a) + @js.native + object D extends js.Object + """ hasErrors + """ + |newSource1.scala:9: error: The first argument to @JSImport must be a literal string. + | @JSImport(A.a, JSImport.Namespace) + | ^ + |newSource1.scala:13: error: The first argument to @JSImport must be a literal string. + | @JSImport(A.a, "B2") + | ^ + |newSource1.scala:17: error: The second argument to @JSImport must be literal string or the JSImport.Namespace object. + | @JSImport("B3", A.a) + | ^ + |newSource1.scala:21: error: The first argument to @JSImport must be a literal string. + | @JSImport(A.a, JSImport.Namespace) + | ^ + |newSource1.scala:25: error: The first argument to @JSImport must be a literal string. + | @JSImport(A.a, "C2") + | ^ + |newSource1.scala:29: error: The second argument to @JSImport must be literal string or the JSImport.Namespace object. + | @JSImport("C3", A.a) + | ^ + |newSource1.scala:33: error: The first argument to @JSImport must be a literal string. + | @JSImport(A.a, A.a) + | ^ + |newSource1.scala:33: error: The second argument to @JSImport must be literal string or the JSImport.Namespace object. + | @JSImport(A.a, A.a) + | ^ + """ + + // With constant (valid) global fallback + + """ + object A { + val a = "Hello" + } + + @JSImport(A.a, JSImport.Namespace, globalFallback = "GlobB1") + @js.native + object B1 extends js.Object + + @JSImport(A.a, "B2", globalFallback = "GlobB2") + @js.native + object B2 extends js.Object + + @JSImport("B3", A.a, globalFallback = "GlobB3") + @js.native + object B3 extends js.Object + + @JSImport(A.a, JSImport.Namespace, globalFallback = "GlobC1") + @js.native + object C1 extends js.Object + + @JSImport(A.a, "C2", globalFallback = "GlobC2") + @js.native + object C2 extends js.Object + + @JSImport("C3", A.a, globalFallback = "GlobC3") + @js.native + object C3 extends js.Object + + @JSImport(A.a, A.a, globalFallback = "GlobD") + @js.native + object D extends js.Object + """ hasErrors + """ + |newSource1.scala:9: error: The first argument to @JSImport must be a literal string. + | @JSImport(A.a, JSImport.Namespace, globalFallback = "GlobB1") + | ^ + |newSource1.scala:13: error: The first argument to @JSImport must be a literal string. + | @JSImport(A.a, "B2", globalFallback = "GlobB2") + | ^ + |newSource1.scala:17: error: The second argument to @JSImport must be literal string or the JSImport.Namespace object. + | @JSImport("B3", A.a, globalFallback = "GlobB3") + | ^ + |newSource1.scala:21: error: The first argument to @JSImport must be a literal string. + | @JSImport(A.a, JSImport.Namespace, globalFallback = "GlobC1") + | ^ + |newSource1.scala:25: error: The first argument to @JSImport must be a literal string. + | @JSImport(A.a, "C2", globalFallback = "GlobC2") + | ^ + |newSource1.scala:29: error: The second argument to @JSImport must be literal string or the JSImport.Namespace object. + | @JSImport("C3", A.a, globalFallback = "GlobC3") + | ^ + |newSource1.scala:33: error: The first argument to @JSImport must be a literal string. + | @JSImport(A.a, A.a, globalFallback = "GlobD") + | ^ + |newSource1.scala:33: error: The second argument to @JSImport must be literal string or the JSImport.Namespace object. + | @JSImport(A.a, A.a, globalFallback = "GlobD") + | ^ + """ + + // With variable (invalid) global fallback + + """ + object A { + val a = "Hello" + } + + @JSImport(A.a, JSImport.Namespace, globalFallback = A.a) + @js.native + object B1 extends js.Object + + @JSImport(A.a, "B2", globalFallback = A.a) + @js.native + object B2 extends js.Object + + @JSImport("B3", A.a, globalFallback = A.a) + @js.native + object B3 extends js.Object + + @JSImport(A.a, JSImport.Namespace, globalFallback = A.a) + @js.native + object C1 extends js.Object + + @JSImport(A.a, "C2", globalFallback = A.a) + @js.native + object C2 extends js.Object + + @JSImport("C3", A.a, globalFallback = A.a) + @js.native + object C3 extends js.Object + + @JSImport(A.a, A.a, globalFallback = A.a) + @js.native + object D extends js.Object + """ hasErrors + """ + |newSource1.scala:9: error: The first argument to @JSImport must be a literal string. + | @JSImport(A.a, JSImport.Namespace, globalFallback = A.a) + | ^ + |newSource1.scala:9: error: The third argument to @JSImport, when present, must be a literal string. + | @JSImport(A.a, JSImport.Namespace, globalFallback = A.a) + | ^ + |newSource1.scala:13: error: The first argument to @JSImport must be a literal string. + | @JSImport(A.a, "B2", globalFallback = A.a) + | ^ + |newSource1.scala:13: error: The third argument to @JSImport, when present, must be a literal string. + | @JSImport(A.a, "B2", globalFallback = A.a) + | ^ + |newSource1.scala:17: error: The second argument to @JSImport must be literal string or the JSImport.Namespace object. + | @JSImport("B3", A.a, globalFallback = A.a) + | ^ + |newSource1.scala:17: error: The third argument to @JSImport, when present, must be a literal string. + | @JSImport("B3", A.a, globalFallback = A.a) + | ^ + |newSource1.scala:21: error: The first argument to @JSImport must be a literal string. + | @JSImport(A.a, JSImport.Namespace, globalFallback = A.a) + | ^ + |newSource1.scala:21: error: The third argument to @JSImport, when present, must be a literal string. + | @JSImport(A.a, JSImport.Namespace, globalFallback = A.a) + | ^ + |newSource1.scala:25: error: The first argument to @JSImport must be a literal string. + | @JSImport(A.a, "C2", globalFallback = A.a) + | ^ + |newSource1.scala:25: error: The third argument to @JSImport, when present, must be a literal string. + | @JSImport(A.a, "C2", globalFallback = A.a) + | ^ + |newSource1.scala:29: error: The second argument to @JSImport must be literal string or the JSImport.Namespace object. + | @JSImport("C3", A.a, globalFallback = A.a) + | ^ + |newSource1.scala:29: error: The third argument to @JSImport, when present, must be a literal string. + | @JSImport("C3", A.a, globalFallback = A.a) + | ^ + |newSource1.scala:33: error: The first argument to @JSImport must be a literal string. + | @JSImport(A.a, A.a, globalFallback = A.a) + | ^ + |newSource1.scala:33: error: The second argument to @JSImport must be literal string or the JSImport.Namespace object. + | @JSImport(A.a, A.a, globalFallback = A.a) + | ^ + |newSource1.scala:33: error: The third argument to @JSImport, when present, must be a literal string. + | @JSImport(A.a, A.a, globalFallback = A.a) + | ^ + """ + + } + + @Test def noApplyProperty: Unit = { + + // def apply + + """ + @js.native + trait A extends js.Object { + def apply: Int = js.native + } + """ hasErrors + """ + |newSource1.scala:7: error: A member named apply represents function application in JavaScript. A parameterless member should be exported as a property. You must add @JSName("apply") + | def apply: Int = js.native + | ^ + """ + + """ + import js.annotation.JSName + + @js.native + trait A extends js.Object { + @JSName("apply") + def apply: Int = js.native + } + """.succeeds() + + // val apply + + """ + @js.native + trait A extends js.Object { + val apply: Int = js.native + } + """ hasErrors + """ + |newSource1.scala:7: error: A member named apply represents function application in JavaScript. A parameterless member should be exported as a property. You must add @JSName("apply") + | val apply: Int = js.native + | ^ + """ + + """ + import js.annotation.JSName + + @js.native + trait A extends js.Object { + @JSName("apply") + val apply: Int = js.native + } + """.succeeds() + + // var apply + + """ + @js.native + trait A extends js.Object { + var apply: Int = js.native + } + """ hasErrors + """ + |newSource1.scala:7: error: A member named apply represents function application in JavaScript. A parameterless member should be exported as a property. You must add @JSName("apply") + | var apply: Int = js.native + | ^ + """ + + """ + import js.annotation.JSName + + @js.native + trait A extends js.Object { + @JSName("apply") + var apply: Int = js.native + } + """.succeeds() + + } + + @Test def noAbstractLocalJSClass: Unit = { + """ + object Enclosing { + def method(): Unit = { + abstract class AbstractLocalJSClass extends js.Object + } + } + """ hasErrors + """ + |newSource1.scala:7: error: Implementation restriction: local JS classes cannot be abstract + | abstract class AbstractLocalJSClass extends js.Object + | ^ + """ + } + + @Test def noLoadJSConstructorOfUnstableRef: Unit = { + """ + class Enclosing { + class InnerJSClass extends js.Object + } + + object A { + def method(): Any = + js.constructorOf[Enclosing#InnerJSClass] + } + """ hasErrors + """ + |newSource1.scala:11: error: stable reference to a JS class required but Enclosing#InnerJSClass found + | js.constructorOf[Enclosing#InnerJSClass] + | ^ + """ + + // version-dependent error message due to https://github.com/scala/bug/issues/10619 + """ + class Enclosing { + class InnerJSClass extends js.Object + } + + object A { + def newEnclosing: Enclosing = new Enclosing + + def method(): Any = + js.constructorOf[newEnclosing.InnerJSClass] + } + """.fails() + + """ + class Enclosing { + class InnerJSClass extends js.Object + } + + object A { + def method(a: Any): Boolean = + a.isInstanceOf[Enclosing#InnerJSClass] + } + """ hasErrors + """ + |newSource1.scala:11: error: stable reference to a JS class required but Enclosing#InnerJSClass found + | a.isInstanceOf[Enclosing#InnerJSClass] + | ^ + """ + + // version-dependent error message due to https://github.com/scala/bug/issues/10619 + """ + class Enclosing { + class InnerJSClass extends js.Object + } + + object A { + def newEnclosing: Enclosing = new Enclosing + + def method(a: Any): Boolean = + a.isInstanceOf[newEnclosing.InnerJSClass] + } + """.fails() + } + + @Test def noJSSymbolNameOnNestedNativeClassesAndObjects: Unit = { + for { + kind <- Seq("class", "object") + } { + s""" + object Sym { + val sym = js.Symbol() + } + + @js.native + @JSGlobal + object Enclosing extends js.Object { + @JSName(Sym.sym) + @js.native + $kind A extends js.Object + } + """ hasErrors + s""" + |newSource1.scala:12: error: Implementation restriction: @JSName with a js.Symbol is not supported on nested native classes and objects + | @JSName(Sym.sym) + | ^ + """ + } + } + + @Test def noBracketCallOrBracketAccessOnJSClasses: Unit = { + // native + """ + @js.native + @JSGlobal + @JSBracketCall + class A extends js.Object + + @js.native + @JSGlobal + @JSBracketAccess + object B extends js.Object + """ hasErrors + """ + |newSource1.scala:7: error: @JSBracketCall can only be used on members of JS types. + | @JSBracketCall + | ^ + |newSource1.scala:12: error: @JSBracketAccess can only be used on members of JS types. + | @JSBracketAccess + | ^ + """ + + // Non-native + """ + @JSBracketCall + class A extends js.Object + + @JSBracketAccess + object B extends js.Object + """ hasErrors + """ + |newSource1.scala:5: error: @JSBracketCall can only be used on members of JS types. + | @JSBracketCall + | ^ + |newSource1.scala:8: error: @JSBracketAccess can only be used on members of JS types. + | @JSBracketAccess + | ^ + """ + + // Nested native + """ + @js.native + @JSGlobal + object Enclosing extends js.Object { + @JSBracketCall + @js.native + class A extends js.Object + + @JSBracketAccess + @js.native + object B extends js.Object + } + """ hasErrors + """ + |newSource1.scala:8: error: @JSBracketCall can only be used on methods. + | @JSBracketCall + | ^ + |newSource1.scala:12: error: @JSBracketAccess can only be used on methods. + | @JSBracketAccess + | ^ + """ + + // Nested non-native + """ + object Enclosing extends js.Object { + @JSBracketCall + object A extends js.Object + + @JSBracketAccess + class B extends js.Object + } + """ hasErrors + """ + |newSource1.scala:6: error: @JSBracketCall can only be used on methods. + | @JSBracketCall + | ^ + |newSource1.scala:9: error: @JSBracketAccess can only be used on methods. + | @JSBracketAccess + | ^ + """ + } + + @Test def noDuplicateJSNameAnnotOnMember: Unit = { + for { + kind <- Seq("class", "object", "trait") + } { + """ + object A { + val a = js.Symbol() + } + + @js.native + @JSGlobal + class A extends js.Object { + @JSName(A.a) + @JSName("foo") + def a: Int = js.native + } + """ hasErrors + """ + |newSource1.scala:13: error: A member can have at most one annotation among @JSName, @JSOperator, @JSBracketAccess and @JSBracketCall. + | @JSName("foo") + | ^ + """ + } + } + + @Test def nonNativeJSTypesNameOverrideErrors: Unit = { + """ + abstract class A extends js.Object { + def bar(): Int + } + class B extends A { + override def bar() = 1 + } + """.hasNoWarns() + + """ + trait A extends js.Object { + @JSName("foo") + def bar(): Int + } + class B extends A { + @JSName("foo") + override def bar() = 1 + } + """.hasNoWarns() + + """ + abstract class A extends js.Object { + @JSName("foo") + def bar(): Int + } + class B extends A { + @JSName("foo") + override def bar() = 1 + } + """.hasNoWarns() + + // #4375 + """ + abstract class Parent extends js.Object { + type TypeMember <: CharSequence + type JSTypeMember <: js.Object + + type Foo = Int + @JSName("Babar") def Bar: Int = 5 + } + + class Child extends Parent { + type TypeMember = String + override type JSTypeMember = js.Date // the override keyword makes no difference + + @JSName("Foobar") def Foo: Int = 5 + type Bar = Int + } + """.hasNoWarns() + + """ + abstract class A extends js.Object { + @JSName("foo") + def bar(): Int + } + class B extends A { + @JSName("baz") + override def bar() = 1 + } + """ hasErrors + """ + |newSource1.scala:11: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |override def bar(): Int in class B called from JS as method 'baz' + | is conflicting with + |def bar(): Int in class A called from JS as method 'foo' + | + | override def bar() = 1 + | ^ + """ + + """ + abstract class A extends js.Object { + @JSName("foo") + def bar(): Int + } + class B extends A { + override def bar() = 1 + } + """ hasErrors + """ + |newSource1.scala:10: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |override def bar(): Int in class B called from JS as method 'bar' + | is conflicting with + |def bar(): Int in class A called from JS as method 'foo' + | + | override def bar() = 1 + | ^ + """ + + """ + abstract class A extends js.Object { + @JSName("foo") + def bar(): Object + } + abstract class B extends A { + override def bar(): String + } + class C extends B { + override def bar() = "1" + } + """ hasErrors + """ + |newSource1.scala:10: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |override def bar(): String in class B called from JS as method 'bar' + | is conflicting with + |def bar(): Object in class A called from JS as method 'foo' + | + | override def bar(): String + | ^ + |newSource1.scala:13: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |override def bar(): String in class C called from JS as method 'bar' + | is conflicting with + |def bar(): Object in class A called from JS as method 'foo' + | + | override def bar() = "1" + | ^ + """ + + """ + abstract class A extends js.Object { + def bar(): Object + } + abstract class B extends A { + @JSName("foo") + override def bar(): String + } + class C extends B { + override def bar() = "1" + } + """ hasErrors + """ + |newSource1.scala:10: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |override def bar(): String in class B called from JS as method 'foo' + | is conflicting with + |def bar(): Object in class A called from JS as method 'bar' + | + | override def bar(): String + | ^ + |newSource1.scala:13: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |override def bar(): String in class C called from JS as method 'bar' + | is conflicting with + |override def bar(): String in class B called from JS as method 'foo' + | + | override def bar() = "1" + | ^ + """ + + """ + class A extends js.Object { + def foo: Int = 5 + } + trait B extends A { + @JSName("bar") + def foo: Int + } + class C extends B + """ hasErrors + s""" + |newSource1.scala:10: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |def foo: Int in class A called from JS as property 'foo' + | is conflicting with + |def foo: Int in trait B called from JS as property 'bar' + | + | def foo: Int + | ^ + |${ifHasNewRefChecks(""" + |newSource1.scala:12: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |def foo: Int in class A called from JS as property 'foo' + | is conflicting with + |def foo: Int in trait B called from JS as property 'bar' + | + | class C extends B + | ^ + """)} + """ + + """ + class A extends js.Object { + @JSName("bar") + def foo: Int = 5 + } + trait B extends A { + def foo: Int + } + class C extends B + """ hasErrors + s""" + |newSource1.scala:10: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |def foo: Int in class A called from JS as property 'bar' + | is conflicting with + |def foo: Int in trait B called from JS as property 'foo' + | + | def foo: Int + | ^ + |${ifHasNewRefChecks(""" + |newSource1.scala:12: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |def foo: Int in class A called from JS as property 'bar' + | is conflicting with + |def foo: Int in trait B called from JS as property 'foo' + | + | class C extends B + | ^ + """)} + """ + + """ + class A[T] extends js.Object { + @JSName("bar") + def foo(x: T): T = x + } + class B extends A[Int] { + override def foo(x: Int): Int = x + } + """ hasErrors + """ + |newSource1.scala:10: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |override def foo(x: Int): Int in class B called from JS as method 'foo' + | is conflicting with + |def foo(x: Int): Int in class A called from JS as method 'bar' + | + | override def foo(x: Int): Int = x + | ^ + """ + + """ + trait A[T] extends js.Object { + @JSName("bar") + def foo(x: T): T + } + class B extends A[Int] { + override def foo(x: Int): Int = x + } + """ hasErrors + """ + |newSource1.scala:10: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |override def foo(x: Int): Int in class B called from JS as method 'foo' + | is conflicting with + |def foo(x: Int): Int in trait A called from JS as method 'bar' + | + | override def foo(x: Int): Int = x + | ^ + """ + + """ + class A[T] extends js.Object { + @JSName("bar") + def foo(x: T): T = x + } + trait B extends A[Int] { + def foo(x: Int): Int + } + class C extends B { + override def foo(x: Int): Int = x + } + """ hasErrors + """ + |newSource1.scala:10: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |def foo(x: Int): Int in class A called from JS as method 'bar' + | is conflicting with + |def foo(x: Int): Int in trait B called from JS as method 'foo' + | + | def foo(x: Int): Int + | ^ + |newSource1.scala:13: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |override def foo(x: Int): Int in class C called from JS as method 'foo' + | is conflicting with + |def foo(x: Int): Int in class A called from JS as method 'bar' + | + | override def foo(x: Int): Int = x + | ^ + """ + + """ + class A[T] extends js.Object { + def foo(x: T): T = x + } + trait B extends A[Int] { + @JSName("bar") + def foo(x: Int): Int + } + class C extends B { + override def foo(x: Int): Int = x + } + """ hasErrors + """ + |newSource1.scala:10: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |def foo(x: Int): Int in class A called from JS as method 'foo' + | is conflicting with + |def foo(x: Int): Int in trait B called from JS as method 'bar' + | + | def foo(x: Int): Int + | ^ + |newSource1.scala:13: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |override def foo(x: Int): Int in class C called from JS as method 'foo' + | is conflicting with + |def foo(x: Int): Int in trait B called from JS as method 'bar' + | + | override def foo(x: Int): Int = x + | ^ + """ + + """ + trait A extends js.Object { + def foo: Int + } + trait B extends js.Object { + @JSName("bar") + def foo: Int + } + trait C extends A with B + """ hasErrors + """ + |newSource1.scala:12: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |def foo: Int in trait B called from JS as property 'bar' + | is conflicting with + |def foo: Int in trait A called from JS as property 'foo' + | + | trait C extends A with B + | ^ + """ + + """ + trait A extends js.Object { + def foo: Int + } + trait B extends js.Object { + @JSName("bar") + def foo: Int + } + abstract class C extends A with B + """ hasErrors + """ + |newSource1.scala:12: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |def foo: Int in trait B called from JS as property 'bar' + | is conflicting with + |def foo: Int in trait A called from JS as property 'foo' + | + | abstract class C extends A with B + | ^ + """ + } + + @Test def nonNativeJSTypesJSNameWithSymbolOverrideErrors: Unit = { + """ + object Syms { + val sym1 = js.Symbol() + } + + trait A extends js.Object { + @JSName(Syms.sym1) + def bar(): Int + } + class B extends A { + @JSName(Syms.sym1) + override def bar() = 1 + } + """.hasNoWarns() + + """ + object Syms { + val sym1 = js.Symbol() + } + + abstract class A extends js.Object { + @JSName(Syms.sym1) + def bar(): Int + } + class B extends A { + @JSName(Syms.sym1) + override def bar() = 1 + } + """.hasNoWarns() + + """ + object Syms { + val sym1 = js.Symbol() + val sym2 = js.Symbol() + } + + abstract class A extends js.Object { + @JSName(Syms.sym1) + def bar(): Int + } + class B extends A { + @JSName(Syms.sym2) + override def bar() = 1 + } + """ hasErrors + """ + |newSource1.scala:16: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |override def bar(): Int in class B called from JS as method 'Syms.sym2' + | is conflicting with + |def bar(): Int in class A called from JS as method 'Syms.sym1' + | + | override def bar() = 1 + | ^ + """ + + """ + object Syms { + val sym1 = js.Symbol() + } + + abstract class A extends js.Object { + @JSName(Syms.sym1) + def bar(): Int + } + class B extends A { + @JSName("baz") + override def bar() = 1 + } + """ hasErrors + """ + |newSource1.scala:15: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |override def bar(): Int in class B called from JS as method 'baz' + | is conflicting with + |def bar(): Int in class A called from JS as method 'Syms.sym1' + | + | override def bar() = 1 + | ^ + """ + + """ + object Syms { + val sym1 = js.Symbol() + } + + abstract class A extends js.Object { + @JSName("foo") + def bar(): Int + } + class B extends A { + @JSName(Syms.sym1) + override def bar() = 1 + } + """ hasErrors + """ + |newSource1.scala:15: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |override def bar(): Int in class B called from JS as method 'Syms.sym1' + | is conflicting with + |def bar(): Int in class A called from JS as method 'foo' + | + | override def bar() = 1 + | ^ + """ + + """ + object Syms { + val sym1 = js.Symbol() + } + + abstract class A extends js.Object { + @JSName(Syms.sym1) + def bar(): Int + } + class B extends A { + override def bar() = 1 + } + """ hasErrors + """ + |newSource1.scala:14: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |override def bar(): Int in class B called from JS as method 'bar' + | is conflicting with + |def bar(): Int in class A called from JS as method 'Syms.sym1' + | + | override def bar() = 1 + | ^ + """ + + """ + object Syms { + val sym1 = js.Symbol() + } + + abstract class A extends js.Object { + @JSName(Syms.sym1) + def bar(): Object + } + abstract class B extends A { + override def bar(): String + } + class C extends B { + override def bar() = "1" + } + """ hasErrors + """ + |newSource1.scala:14: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |override def bar(): String in class B called from JS as method 'bar' + | is conflicting with + |def bar(): Object in class A called from JS as method 'Syms.sym1' + | + | override def bar(): String + | ^ + |newSource1.scala:17: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |override def bar(): String in class C called from JS as method 'bar' + | is conflicting with + |def bar(): Object in class A called from JS as method 'Syms.sym1' + | + | override def bar() = "1" + | ^ + """ + + """ + object Syms { + val sym1 = js.Symbol() + } + + abstract class A extends js.Object { + def bar(): Object + } + abstract class B extends A { + @JSName(Syms.sym1) + override def bar(): String + } + class C extends B { + override def bar() = "1" + } + """ hasErrors + """ + |newSource1.scala:14: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |override def bar(): String in class B called from JS as method 'Syms.sym1' + | is conflicting with + |def bar(): Object in class A called from JS as method 'bar' + | + | override def bar(): String + | ^ + |newSource1.scala:17: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |override def bar(): String in class C called from JS as method 'bar' + | is conflicting with + |override def bar(): String in class B called from JS as method 'Syms.sym1' + | + | override def bar() = "1" + | ^ + """ + + """ + object Syms { + val sym1 = js.Symbol() + } + + class A extends js.Object { + def foo: Int = 5 + } + trait B extends A { + @JSName(Syms.sym1) + def foo: Int + } + class C extends B + """ hasErrors + s""" + |newSource1.scala:14: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |def foo: Int in class A called from JS as property 'foo' + | is conflicting with + |def foo: Int in trait B called from JS as property 'Syms.sym1' + | + | def foo: Int + | ^ + |${ifHasNewRefChecks(""" + |newSource1.scala:16: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |def foo: Int in class A called from JS as property 'foo' + | is conflicting with + |def foo: Int in trait B called from JS as property 'Syms.sym1' + | + | class C extends B + | ^ + """)} + """ + + """ + object Syms { + val sym1 = js.Symbol() + } + + class A extends js.Object { + @JSName(Syms.sym1) + def foo: Int = 5 + } + trait B extends A { + def foo: Int + } + class C extends B + """ hasErrors + s""" + |newSource1.scala:14: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |def foo: Int in class A called from JS as property 'Syms.sym1' + | is conflicting with + |def foo: Int in trait B called from JS as property 'foo' + | + | def foo: Int + | ^ + |${ifHasNewRefChecks(""" + |newSource1.scala:16: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |def foo: Int in class A called from JS as property 'Syms.sym1' + | is conflicting with + |def foo: Int in trait B called from JS as property 'foo' + | + | class C extends B + | ^ + """)} + """ + + """ + object Syms { + val sym1 = js.Symbol() + } + + class A[T] extends js.Object { + @JSName(Syms.sym1) + def foo(x: T): T = x + } + class B extends A[Int] { + override def foo(x: Int): Int = x + } + """ hasErrors + """ + |newSource1.scala:14: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |override def foo(x: Int): Int in class B called from JS as method 'foo' + | is conflicting with + |def foo(x: Int): Int in class A called from JS as method 'Syms.sym1' + | + | override def foo(x: Int): Int = x + | ^ + """ + + """ + object Syms { + val sym1 = js.Symbol() + } + + trait A[T] extends js.Object { + @JSName(Syms.sym1) + def foo(x: T): T + } + class B extends A[Int] { + override def foo(x: Int): Int = x + } + """ hasErrors + """ + |newSource1.scala:14: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |override def foo(x: Int): Int in class B called from JS as method 'foo' + | is conflicting with + |def foo(x: Int): Int in trait A called from JS as method 'Syms.sym1' + | + | override def foo(x: Int): Int = x + | ^ + """ + + """ + object Syms { + val sym1 = js.Symbol() + } + + class A[T] extends js.Object { + @JSName(Syms.sym1) + def foo(x: T): T = x + } + trait B extends A[Int] { + def foo(x: Int): Int + } + class C extends B { + override def foo(x: Int): Int = x + } + """ hasErrors + """ + |newSource1.scala:14: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |def foo(x: Int): Int in class A called from JS as method 'Syms.sym1' + | is conflicting with + |def foo(x: Int): Int in trait B called from JS as method 'foo' + | + | def foo(x: Int): Int + | ^ + |newSource1.scala:17: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |override def foo(x: Int): Int in class C called from JS as method 'foo' + | is conflicting with + |def foo(x: Int): Int in class A called from JS as method 'Syms.sym1' + | + | override def foo(x: Int): Int = x + | ^ + """ + + """ + object Syms { + val sym1 = js.Symbol() + } + + class A[T] extends js.Object { + def foo(x: T): T = x + } + trait B extends A[Int] { + @JSName(Syms.sym1) + def foo(x: Int): Int + } + class C extends B { + override def foo(x: Int): Int = x + } + """ hasErrors + """ + |newSource1.scala:14: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |def foo(x: Int): Int in class A called from JS as method 'foo' + | is conflicting with + |def foo(x: Int): Int in trait B called from JS as method 'Syms.sym1' + | + | def foo(x: Int): Int + | ^ + |newSource1.scala:17: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |override def foo(x: Int): Int in class C called from JS as method 'foo' + | is conflicting with + |def foo(x: Int): Int in trait B called from JS as method 'Syms.sym1' + | + | override def foo(x: Int): Int = x + | ^ + """ + + """ + object Syms { + val sym1 = js.Symbol() + } + + trait A extends js.Object { + def foo: Int + } + trait B extends js.Object { + @JSName(Syms.sym1) + def foo: Int + } + trait C extends A with B + """ hasErrors + """ + |newSource1.scala:16: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |def foo: Int in trait B called from JS as property 'Syms.sym1' + | is conflicting with + |def foo: Int in trait A called from JS as property 'foo' + | + | trait C extends A with B + | ^ + """ + + """ + object Syms { + val sym1 = js.Symbol() + } + + trait A extends js.Object { + def foo: Int + } + trait B extends js.Object { + @JSName(Syms.sym1) + def foo: Int + } + abstract class C extends A with B + """ hasErrors + """ + |newSource1.scala:16: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |def foo: Int in trait B called from JS as property 'Syms.sym1' + | is conflicting with + |def foo: Int in trait A called from JS as property 'foo' + | + | abstract class C extends A with B + | ^ + """ + } + + // #4282 + @Test def jsTypesSpecialCallingConventionOverrideErrors: Unit = { + // name "apply" vs function application + """ + @js.native + @JSGlobal + class A extends js.Object { + def apply(): Int + } + + class B extends A { + @JSName("apply") + def apply(): Int + } + """ hasErrors + """ + |newSource1.scala:13: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |def apply(): Int in class B called from JS as method 'apply' + | is conflicting with + |def apply(): Int in class A called from JS as function application + | + | def apply(): Int + | ^ + """ + + // property vs method + """ + class A extends js.Object { + def a: Int + } + + class B extends A { + def a(): Int + } + """ hasErrors + """ + |newSource1.scala:10: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |def a(): Int in class B called from JS as method 'a' + | is conflicting with + |def a: Int in class A called from JS as property 'a' + | + | def a(): Int + | ^ + """ + + val postUnarySpace = { + val hasNoSpace = { + version.startsWith("2.11.") || + version == "2.12.1" || + version == "2.12.2" || + version == "2.12.3" || + version == "2.12.4" || + version == "2.12.5" || + version == "2.12.6" || + version == "2.12.7" || + version == "2.12.8" || + version == "2.12.9" || + version == "2.12.10" || + version == "2.13.0" || + version == "2.13.1" + } + if (hasNoSpace) "" + else " " + } + + // unary op vs thing named like it + """ + @js.native + @JSGlobal + class A extends js.Object { + @JSOperator + def unary_+ : Int + } + + class B extends A { + @JSName("unary_+") + def unary_+ : Int + } + """ hasErrors + s""" + |newSource1.scala:14: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |def unary_+$postUnarySpace: Int in class B called from JS as property 'unary_+' + | is conflicting with + |def unary_+$postUnarySpace: Int in class A called from JS as unary operator + | + | def unary_+ : Int + | ^ + """ + + // non-zero arg is OK + """ + class A extends js.Object { + def unary_+(x: String): Int = 1 + } + + class B extends A { + @JSName("unary_+") + override def unary_+(x: String): Int = 2 + } + """ hasWarns + """ + |newSource1.scala:6: warning: Method 'unary_+' should have an explicit @JSName or @JSOperator annotation because its name is one of the JavaScript operators + | def unary_+(x: String): Int = 1 + | ^ + """ + + // binary op vs thing named like it + """ + @js.native + @JSGlobal + class A extends js.Object { + @JSOperator + def ||(x: Int): Int + } + + class B extends A { + @JSName("||") + def ||(x: Int): Int + } + """ hasErrors + """ + |newSource1.scala:14: error: A member of a JS class is overriding another member with a different JS calling convention. + | + |def ||(x: Int): Int in class B called from JS as method '||' + | is conflicting with + |def ||(x: Int): Int in class A called from JS as binary operator + | + | def ||(x: Int): Int + | ^ + """ + + // non-single arg is OK + """ + class A extends js.Object { + def ||(): Int = 1 + } + + class B extends A { + @JSName("||") + override def ||(): Int = 2 + } + """ hasWarns + """ + |newSource1.scala:6: warning: Method '||' should have an explicit @JSName or @JSOperator annotation because its name is one of the JavaScript operators + | def ||(): Int = 1 + | ^ + """ + } + + @Test def noDefaultConstructorArgsIfModuleIsJSNative: Unit = { + """ + class A(x: Int = 1) extends js.Object + + @js.native + @JSGlobal + object A extends js.Object + """ hasErrors + """ + |newSource1.scala:5: error: Implementation restriction: constructors of non-native JS classes cannot have default parameters if their companion module is JS native. + | class A(x: Int = 1) extends js.Object + | ^ + """ + + """ + class A(x: Int = 1) + + @js.native + @JSGlobal + object A extends js.Object + """ hasErrors + """ + |newSource1.scala:5: error: Implementation restriction: constructors of Scala classes cannot have default parameters if their companion module is JS native. + | class A(x: Int = 1) + | ^ + """ + } + + // #2547 + @Test def noDefaultOverrideCrash: Unit = { + """ + @js.native + @JSGlobal + class NativeBase extends js.Object { + def add(option: js.Any = js.native): js.Any = js.native + } + class Derived extends NativeBase { + override def add(option: js.Any): js.Any = super.add(option) + } + """ hasErrors + """ + |newSource1.scala:11: error: When overriding a native method with default arguments, the overriding method must explicitly repeat the default arguments. + | override def add(option: js.Any): js.Any = super.add(option) + | ^ + """ + + """ + @js.native + trait NativeTrait extends js.Object { + def add(option: js.Any = js.native): js.Any = js.native + } + + @js.native + @JSGlobal + class NativeBase extends NativeTrait + + class Derived extends NativeBase { + override def add(option: js.Any): js.Any = super.add(option) + } + """ hasErrors + """ + |newSource1.scala:15: error: When overriding a native method with default arguments, the overriding method must explicitly repeat the default arguments. + | override def add(option: js.Any): js.Any = super.add(option) + | ^ + """ + } + + // # 3969 + @Test def overrideEqualsHashCode: Unit = { + for { + obj <- List("class", "object") + } { + s""" + $obj A extends js.Object { + override def hashCode(): Int = 1 + override def equals(obj: Any): Boolean = false + + // this one works as expected (so allowed) + override def toString(): String = "frobber" + + /* these are allowed, since they are protected in jl.Object. + * as a result, only the overrides can be called. So the fact that they + * do not truly override the methods in jl.Object is not observable. + */ + override def clone(): Object = null + override def finalize(): Unit = () + + // other methods in jl.Object are final. + } + """ hasWarns + """ + |newSource1.scala:6: warning: Overriding hashCode in a JS class does not change its hash code. To silence this warning, change the name of the method and optionally add @JSName("hashCode"). + | override def hashCode(): Int = 1 + | ^ + |newSource1.scala:7: warning: Overriding equals in a JS class does not change how it is compared. To silence this warning, change the name of the method and optionally add @JSName("equals"). + | override def equals(obj: Any): Boolean = false + | ^ + """ + } + + for { + obj <- List("class", "object") + } { + s""" + @js.native + @JSGlobal + $obj A extends js.Object { + override def hashCode(): Int = js.native + override def equals(obj: Any): Boolean = js.native + } + """ hasWarns + """ + |newSource1.scala:8: warning: Overriding hashCode in a JS class does not change its hash code. To silence this warning, change the name of the method and optionally add @JSName("hashCode"). + | override def hashCode(): Int = js.native + | ^ + |newSource1.scala:9: warning: Overriding equals in a JS class does not change how it is compared. To silence this warning, change the name of the method and optionally add @JSName("equals"). + | override def equals(obj: Any): Boolean = js.native + | ^ + """ + } + + """ + @js.native + trait A extends js.Any { + override def hashCode(): Int = js.native + override def equals(obj: Any): Boolean = js.native + } + """ hasWarns + """ + |newSource1.scala:7: warning: Overriding hashCode in a JS class does not change its hash code. To silence this warning, change the name of the method and optionally add @JSName("hashCode"). + | override def hashCode(): Int = js.native + | ^ + |newSource1.scala:8: warning: Overriding equals in a JS class does not change how it is compared. To silence this warning, change the name of the method and optionally add @JSName("equals"). + | override def equals(obj: Any): Boolean = js.native + | ^ + """ + + """ + trait A extends js.Any { + override def hashCode(): Int + override def equals(obj: Any): Boolean + } + """ hasWarns + """ + |newSource1.scala:6: warning: Overriding hashCode in a JS class does not change its hash code. To silence this warning, change the name of the method and optionally add @JSName("hashCode"). + | override def hashCode(): Int + | ^ + |newSource1.scala:7: warning: Overriding equals in a JS class does not change how it is compared. To silence this warning, change the name of the method and optionally add @JSName("equals"). + | override def equals(obj: Any): Boolean + | ^ + """ + } + +} diff --git a/compiler/src/test/scala/org/scalajs/nscplugin/test/JSNewTargetTest.scala b/compiler/src/test/scala/org/scalajs/nscplugin/test/JSNewTargetTest.scala new file mode 100644 index 0000000000..edfa1afd01 --- /dev/null +++ b/compiler/src/test/scala/org/scalajs/nscplugin/test/JSNewTargetTest.scala @@ -0,0 +1,149 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin.test + +import org.scalajs.nscplugin.test.util._ +import org.junit.Test + +// scalastyle:off line.size.limit + +class JSNewTargetTest extends DirectTest with TestHelpers { + + override def preamble: String = + """import scala.scalajs.js + """ + + @Test + def illegalInScalaClass(): Unit = { + + """ + class A { + js.`new`.target + + def this(x: Int) = { + this() + js.`new`.target + } + } + """ hasErrors + """ + |newSource1.scala:4: error: Illegal use of js.`new`.target. + |It can only be used in the constructor of a JS class, as a statement or in the rhs of a val or var. + |It cannot be used inside a lambda or by-name parameter, nor in any other location. + | js.`new`.target + | ^ + |newSource1.scala:8: error: Illegal use of js.`new`.target. + |It can only be used in the constructor of a JS class, as a statement or in the rhs of a val or var. + |It cannot be used inside a lambda or by-name parameter, nor in any other location. + | js.`new`.target + | ^ + """ + + """ + class A { + def foo(x: Int): Unit = + js.`new`.target + } + """ hasErrors + """ + |newSource1.scala:5: error: Illegal use of js.`new`.target. + |It can only be used in the constructor of a JS class, as a statement or in the rhs of a val or var. + |It cannot be used inside a lambda or by-name parameter, nor in any other location. + | js.`new`.target + | ^ + """ + + """ + class A extends js.Object { + class B { + js.`new`.target + } + } + """ hasErrors + """ + |newSource1.scala:5: error: Illegal use of js.`new`.target. + |It can only be used in the constructor of a JS class, as a statement or in the rhs of a val or var. + |It cannot be used inside a lambda or by-name parameter, nor in any other location. + | js.`new`.target + | ^ + """ + + } + + @Test + def illegalInDefOrLazyVal(): Unit = { + + """ + class A extends js.Object { + lazy val x = js.`new`.target + def y: js.Dynamic = js.`new`.target + def z(x: Int): Any = js.`new`.target + } + """ hasErrors + """ + |newSource1.scala:4: error: Illegal use of js.`new`.target. + |It can only be used in the constructor of a JS class, as a statement or in the rhs of a val or var. + |It cannot be used inside a lambda or by-name parameter, nor in any other location. + | lazy val x = js.`new`.target + | ^ + |newSource1.scala:5: error: Illegal use of js.`new`.target. + |It can only be used in the constructor of a JS class, as a statement or in the rhs of a val or var. + |It cannot be used inside a lambda or by-name parameter, nor in any other location. + | def y: js.Dynamic = js.`new`.target + | ^ + |newSource1.scala:6: error: Illegal use of js.`new`.target. + |It can only be used in the constructor of a JS class, as a statement or in the rhs of a val or var. + |It cannot be used inside a lambda or by-name parameter, nor in any other location. + | def z(x: Int): Any = js.`new`.target + | ^ + """ + + } + + @Test + def illegalInLambdaOrByName(): Unit = { + + """ + class A extends js.Object { + val x = () => js.`new`.target + val y = Option(null).getOrElse(js.`new`.target) + val z: js.Function1[Int, Any] = (x: Int) => js.`new`.target + val w: js.ThisFunction0[Any, Any] = (x: Any) => js.`new`.target + } + """ hasErrors + """ + |newSource1.scala:4: error: Illegal use of js.`new`.target. + |It can only be used in the constructor of a JS class, as a statement or in the rhs of a val or var. + |It cannot be used inside a lambda or by-name parameter, nor in any other location. + | val x = () => js.`new`.target + | ^ + |newSource1.scala:5: error: Illegal use of js.`new`.target. + |It can only be used in the constructor of a JS class, as a statement or in the rhs of a val or var. + |It cannot be used inside a lambda or by-name parameter, nor in any other location. + | val y = Option(null).getOrElse(js.`new`.target) + | ^ + |newSource1.scala:6: error: Illegal use of js.`new`.target. + |It can only be used in the constructor of a JS class, as a statement or in the rhs of a val or var. + |It cannot be used inside a lambda or by-name parameter, nor in any other location. + | val z: js.Function1[Int, Any] = (x: Int) => js.`new`.target + | ^ + |newSource1.scala:7: error: Illegal use of js.`new`.target. + |It can only be used in the constructor of a JS class, as a statement or in the rhs of a val or var. + |It cannot be used inside a lambda or by-name parameter, nor in any other location. + | val w: js.ThisFunction0[Any, Any] = (x: Any) => js.`new`.target + | ^ + """ + + } + +} diff --git a/compiler/src/test/scala/org/scalajs/nscplugin/test/JSOptionalTest.scala b/compiler/src/test/scala/org/scalajs/nscplugin/test/JSOptionalTest.scala new file mode 100644 index 0000000000..2fa4d0b6e9 --- /dev/null +++ b/compiler/src/test/scala/org/scalajs/nscplugin/test/JSOptionalTest.scala @@ -0,0 +1,213 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin.test + +import org.scalajs.nscplugin.test.util._ + +import org.junit.Test +import org.junit.Ignore + +// scalastyle:off line.size.limit + +class JSOptionalTest extends DirectTest with TestHelpers { + + override def preamble: String = { + """ + import scala.scalajs.js + import scala.scalajs.js.annotation._ + """ + } + + @Test + def optionalRequiresUndefinedRHS: Unit = { + s""" + trait A extends js.Object { + val a1: js.UndefOr[Int] = 5 + val a2: Int = 5 + + def b1: js.UndefOr[Int] = 5 + def b2: Int = 5 + + var c1: js.UndefOr[Int] = 5 + var c2: Int = 5 + } + """ hasErrors + s""" + |newSource1.scala:6: error: Members of non-native JS traits must either be abstract, or their right-hand-side must be `js.undefined`. + | val a1: js.UndefOr[Int] = 5 + | ^ + |newSource1.scala:7: error: Members of non-native JS traits must either be abstract, or their right-hand-side must be `js.undefined`. + | val a2: Int = 5 + | ^ + |newSource1.scala:9: error: Members of non-native JS traits must either be abstract, or their right-hand-side must be `js.undefined`. + | def b1: js.UndefOr[Int] = 5 + | ^ + |newSource1.scala:10: error: Members of non-native JS traits must either be abstract, or their right-hand-side must be `js.undefined`. + | def b2: Int = 5 + | ^ + |newSource1.scala:12: error: Members of non-native JS traits must either be abstract, or their right-hand-side must be `js.undefined`. + | var c1: js.UndefOr[Int] = 5 + | ^ + |newSource1.scala:13: error: Members of non-native JS traits must either be abstract, or their right-hand-side must be `js.undefined`. + | var c2: Int = 5 + | ^ + """ + } + + @Test // #4319 + def optionalDefaultParamRequiresUndefinedRHS: Unit = { + s""" + trait A extends js.Object { + def a(x: js.UndefOr[Int] = 1): Int + def b(x: String = "foo"): Unit + def c(x: js.UndefOr[Int] = js.undefined): Int // ok + } + """ hasErrors + """ + |newSource1.scala:6: error: Members of non-native JS traits may not have default parameters unless their default is `js.undefined`. + | def a(x: js.UndefOr[Int] = 1): Int + | ^ + |newSource1.scala:7: error: Members of non-native JS traits may not have default parameters unless their default is `js.undefined`. + | def b(x: String = "foo"): Unit + | ^ + """ + + // Also for custom JS function types (2.11 has more errors than expected here) + s""" + trait A extends js.Function { + def apply(x: js.UndefOr[Int] = 1): Int + } + """ containsErrors + """ + |newSource1.scala:6: error: Members of non-native JS traits may not have default parameters unless their default is `js.undefined`. + | def apply(x: js.UndefOr[Int] = 1): Int + | ^ + """ + } + + @Test + def noOptionalLazyVal: Unit = { + s""" + trait A extends js.Object { + lazy val a1: js.UndefOr[Int] = js.undefined + } + """ hasErrors + s""" + |newSource1.scala:6: error: A non-native JS trait cannot contain lazy vals + | lazy val a1: js.UndefOr[Int] = js.undefined + | ^ + """ + } + + @Test + def noOverrideConcreteNonOptionalWithOptional: Unit = { + s""" + abstract class A extends js.Object { + val a1: js.UndefOr[Int] = 5 + val a2: js.UndefOr[Int] + + def b1: js.UndefOr[Int] = 5 + def b2: js.UndefOr[Int] + } + + trait B extends A { + override val a1: js.UndefOr[Int] = js.undefined + override val a2: js.UndefOr[Int] = js.undefined + + override def b1: js.UndefOr[Int] = js.undefined + override def b2: js.UndefOr[Int] = js.undefined + } + """ hasErrors + s""" + |newSource1.scala:14: error: Cannot override concrete val a1: scala.scalajs.js.UndefOr[Int] from A in a non-native JS trait. + | override val a1: js.UndefOr[Int] = js.undefined + | ^ + |newSource1.scala:17: error: Cannot override concrete def b1: scala.scalajs.js.UndefOr[Int] from A in a non-native JS trait. + | override def b1: js.UndefOr[Int] = js.undefined + | ^ + """ + + s""" + @js.native + @JSGlobal + class A extends js.Object { + val a: js.UndefOr[Int] = js.native + def b: js.UndefOr[Int] = js.native + } + + trait B extends A { + override val a: js.UndefOr[Int] = js.undefined + override def b: js.UndefOr[Int] = js.undefined + } + """ hasErrors + s""" + |newSource1.scala:13: error: Cannot override concrete val a: scala.scalajs.js.UndefOr[Int] from A in a non-native JS trait. + | override val a: js.UndefOr[Int] = js.undefined + | ^ + |newSource1.scala:14: error: Cannot override concrete def b: scala.scalajs.js.UndefOr[Int] from A in a non-native JS trait. + | override def b: js.UndefOr[Int] = js.undefined + | ^ + """ + + s""" + @js.native + trait A extends js.Object { + val a: js.UndefOr[Int] = js.native + def b: js.UndefOr[Int] = js.native + } + + @js.native + @JSGlobal + class B extends A + + trait C extends B { + override val a: js.UndefOr[Int] = js.undefined + override def b: js.UndefOr[Int] = js.undefined + } + """ hasErrors + s""" + |newSource1.scala:16: error: Cannot override concrete val a: scala.scalajs.js.UndefOr[Int] from A in a non-native JS trait. + | override val a: js.UndefOr[Int] = js.undefined + | ^ + |newSource1.scala:17: error: Cannot override concrete def b: scala.scalajs.js.UndefOr[Int] from A in a non-native JS trait. + | override def b: js.UndefOr[Int] = js.undefined + | ^ + """ + } + + @Test + def noOptionalDefWithParens: Unit = { + s""" + trait A extends js.Object { + def a(): js.UndefOr[Int] = js.undefined + def b(x: Int): js.UndefOr[Int] = js.undefined + def c_=(v: Int): js.UndefOr[Int] = js.undefined + } + """ hasErrors + s""" + |newSource1.scala:6: error: In non-native JS traits, defs with parentheses must be abstract. + | def a(): js.UndefOr[Int] = js.undefined + | ^ + |newSource1.scala:7: error: In non-native JS traits, defs with parentheses must be abstract. + | def b(x: Int): js.UndefOr[Int] = js.undefined + | ^ + |newSource1.scala:8: error: JS setters must return Unit + | def c_=(v: Int): js.UndefOr[Int] = js.undefined + | ^ + |newSource1.scala:8: error: In non-native JS traits, defs with parentheses must be abstract. + | def c_=(v: Int): js.UndefOr[Int] = js.undefined + | ^ + """ + } + +} diff --git a/compiler/src/test/scala/org/scalajs/nscplugin/test/JSSAMTest.scala b/compiler/src/test/scala/org/scalajs/nscplugin/test/JSSAMTest.scala new file mode 100644 index 0000000000..157a38156a --- /dev/null +++ b/compiler/src/test/scala/org/scalajs/nscplugin/test/JSSAMTest.scala @@ -0,0 +1,272 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin.test + +import org.scalajs.nscplugin.test.util._ +import org.scalajs.nscplugin.test.util.VersionDependentUtils.scalaVersion + +import org.junit.Assume._ +import org.junit.Test + +// scalastyle:off line.size.limit + +class JSSAMTest extends DirectTest with TestHelpers { + + override def extraArgs: List[String] = { + if (scalaVersion.startsWith("2.11.")) + super.extraArgs :+ "-Xexperimental" + else + super.extraArgs + } + + override def preamble: String = + """ + import scala.scalajs.js + import scala.scalajs.js.annotation._ + """ + + @Test + def noSAMAsJSType211: Unit = { + assumeTrue(scalaVersion.startsWith("2.11.")) + + """ + @js.native + trait Foo extends js.Object { + def foo(x: Int): Int + } + + trait Bar extends js.Object { + def bar(x: Int): Int + } + + class Foobar extends js.Function { + def foobar(x: Int): Int + } + + class A { + val foo: Foo = x => x + 1 + val bar: Bar = x => x + 1 + val foobar: Foobar = x => x + 1 + } + """ hasErrors + """ + |newSource1.scala:19: error: Non-native JS types cannot directly extend native JS traits. + | val foo: Foo = x => x + 1 + | ^ + |newSource1.scala:20: error: $anonfun extends scala.Serializable which does not extend js.Any. + | val bar: Bar = x => x + 1 + | ^ + |newSource1.scala:21: error: $anonfun extends scala.Serializable which does not extend js.Any. + | val foobar: Foobar = x => x + 1 + | ^ + """ + } + + @Test + def noSAMAsJSType212Plus: Unit = { + assumeTrue(!scalaVersion.startsWith("2.11.")) + + """ + @js.native + trait Foo extends js.Object { + def foo(x: Int): Int + } + + trait Bar extends js.Object { + def bar(x: Int): Int + } + + class Foobar extends js.Function { + def foobar(x: Int): Int + } + + class A { + val foo: Foo = x => x + 1 + val bar: Bar = x => x + 1 + val foobar: Foobar = x => x + 1 + } + """ hasErrors + """ + |newSource1.scala:19: error: Using an anonymous function as a SAM for the JavaScript type Foo is not allowed because it is not a trait extending js.Function. Use an anonymous class instead. + | val foo: Foo = x => x + 1 + | ^ + |newSource1.scala:20: error: Using an anonymous function as a SAM for the JavaScript type Bar is not allowed because it is not a trait extending js.Function. Use an anonymous class instead. + | val bar: Bar = x => x + 1 + | ^ + |newSource1.scala:21: error: Using an anonymous function as a SAM for the JavaScript type Foobar is not allowed because it is not a trait extending js.Function. Use an anonymous class instead. + | val foobar: Foobar = x => x + 1 + | ^ + """ + } + + @Test + def noSAMOfNativeJSFunctionType211: Unit = { + assumeTrue(scalaVersion.startsWith("2.11.")) + + """ + @js.native + trait Foo extends js.Function { + def apply(x: Int): Int + } + + @js.native + trait Bar extends js.Function { + def bar(x: Int = 5): Int + } + + class A { + val foo: Foo = x => x + 1 + val bar: Bar = x => x + 1 + } + """ hasErrors + """ + |newSource1.scala:16: error: Non-native JS types cannot directly extend native JS traits. + | val foo: Foo = x => x + 1 + | ^ + |newSource1.scala:17: error: Non-native JS types cannot directly extend native JS traits. + | val bar: Bar = x => x + 1 + | ^ + """ + } + + @Test + def noSAMOfNativeJSFunctionType212Plus: Unit = { + assumeTrue(!scalaVersion.startsWith("2.11.")) + + """ + @js.native + trait Foo extends js.Function { + def apply(x: Int): Int + } + + @js.native + trait Bar extends js.Function { + def bar(x: Int = 5): Int + } + + class A { + val foo: Foo = x => x + 1 + val bar: Bar = x => x + 1 + } + """ hasErrors + """ + |newSource1.scala:16: error: Using an anonymous function as a SAM for the JavaScript type Foo is not allowed because it is a native JS type. It is not possible to directly implement it. + | val foo: Foo = x => x + 1 + | ^ + |newSource1.scala:17: error: Using an anonymous function as a SAM for the JavaScript type Bar is not allowed because it is a native JS type. It is not possible to directly implement it. + | val bar: Bar = x => x + 1 + | ^ + """ + } + + @Test + def noSAMOfNonApplyJSType: Unit = { + """ + trait Foo extends js.Function { + def foo(x: Int): Int + } + + class A { + val foo: Foo = x => x + 1 + } + """ hasErrors + """ + |newSource1.scala:10: error: Using an anonymous function as a SAM for the JavaScript type Foo is not allowed because its single abstract method is not named `apply`. Use an anonymous class instead. + | val foo: Foo = x => x + 1 + | ^ + """ + } + + @Test + def missingThisArgForJSThisFunction: Unit = { + """ + trait BadThisFunction1 extends js.ThisFunction { + def apply(): Int + } + + trait BadThisFunction2 extends js.ThisFunction { + def apply(args: Int*): Int + } + + class A { + val badThisFunction1: BadThisFunction1 = () => 42 + val badThisFunction2: BadThisFunction2 = args => args.size + } + """ hasErrors + """ + |newSource1.scala:14: error: The SAM or apply method for a js.ThisFunction must have a leading non-varargs parameter + | val badThisFunction1: BadThisFunction1 = () => 42 + | ^ + |newSource1.scala:15: error: The SAM or apply method for a js.ThisFunction must have a leading non-varargs parameter + | val badThisFunction2: BadThisFunction2 = args => args.size + | ^ + """ + } + + @Test + def noNonsensicalJSFunctionTypes: Unit = { + """ + class BadFunctionIsClass extends js.Function { + def apply(x: Int): Int + } + + trait BadFunctionExtendsNonFunction extends js.Object { + def apply(x: Int): Int + } + + class SubclassOfFunction extends js.Function + + trait BadFunctionExtendsSubclassOfFunction extends SubclassOfFunction { + def apply(x: Int): Int + } + + trait BadFunctionParametricMethod extends js.Function { + def apply[A](x: A): A + } + + trait BadFunctionOverloaded extends js.Function { + def apply(x: Int): Int + def apply(x: String): String + } + + trait BadFunctionMultipleAbstract extends js.Function { + def apply(x: Int): Int + def foo(x: Int): Int + } + """ hasErrors + """ + |newSource1.scala:6: error: A non-native JS type can only declare an abstract method named `apply` without `@JSName` if it is the SAM of a trait that extends js.Function + | def apply(x: Int): Int + | ^ + |newSource1.scala:10: error: A non-native JS type can only declare an abstract method named `apply` without `@JSName` if it is the SAM of a trait that extends js.Function + | def apply(x: Int): Int + | ^ + |newSource1.scala:16: error: A non-native JS type can only declare an abstract method named `apply` without `@JSName` if it is the SAM of a trait that extends js.Function + | def apply(x: Int): Int + | ^ + |newSource1.scala:20: error: A non-native JS type can only declare an abstract method named `apply` without `@JSName` if it is the SAM of a trait that extends js.Function + | def apply[A](x: A): A + | ^ + |newSource1.scala:24: error: A non-native JS type can only declare an abstract method named `apply` without `@JSName` if it is the SAM of a trait that extends js.Function + | def apply(x: Int): Int + | ^ + |newSource1.scala:25: error: A non-native JS type can only declare an abstract method named `apply` without `@JSName` if it is the SAM of a trait that extends js.Function + | def apply(x: String): String + | ^ + |newSource1.scala:29: error: A non-native JS type can only declare an abstract method named `apply` without `@JSName` if it is the SAM of a trait that extends js.Function + | def apply(x: Int): Int + | ^ + """ + } + +} diff --git a/compiler/src/test/scala/org/scalajs/core/compiler/test/JSUndefinedParamTest.scala b/compiler/src/test/scala/org/scalajs/nscplugin/test/JSUndefinedParamTest.scala similarity index 97% rename from compiler/src/test/scala/org/scalajs/core/compiler/test/JSUndefinedParamTest.scala rename to compiler/src/test/scala/org/scalajs/nscplugin/test/JSUndefinedParamTest.scala index 5f7e02587b..a4eb2d9850 100644 --- a/compiler/src/test/scala/org/scalajs/core/compiler/test/JSUndefinedParamTest.scala +++ b/compiler/src/test/scala/org/scalajs/nscplugin/test/JSUndefinedParamTest.scala @@ -10,9 +10,9 @@ * additional information regarding copyright ownership. */ -package org.scalajs.core.compiler.test +package org.scalajs.nscplugin.test -import org.scalajs.core.compiler.test.util._ +import org.scalajs.nscplugin.test.util._ import org.junit.Test // scalastyle:off line.size.limit diff --git a/compiler/src/test/scala/org/scalajs/nscplugin/test/MatchASTTest.scala b/compiler/src/test/scala/org/scalajs/nscplugin/test/MatchASTTest.scala new file mode 100644 index 0000000000..fa8faf6071 --- /dev/null +++ b/compiler/src/test/scala/org/scalajs/nscplugin/test/MatchASTTest.scala @@ -0,0 +1,83 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin.test + +import util._ + +import org.junit.Test +import org.junit.Assert._ + +import org.scalajs.ir.{Trees => js} + +class MatchASTTest extends JSASTTest { + + @Test + def stripIdentityMatchEndNonUnitResult: Unit = { + """ + object A { + def aString: String = "a" + def foo = aString match { + case "a" => true + case "b" => false + } + } + """.hasExactly(1, "local variable") { + case js.VarDef(_, _, _, _, _) => + } + } + + @Test + def stripIdentityMatchEndUnitResult: Unit = { + """ + object A { + def aString: String = "a" + def foo = aString match { + case "a" => + case "b" => + } + } + """.hasExactly(1, "local variable") { + case js.VarDef(_, _, _, _, _) => + } + } + + @Test + def matchWithZeroAlternativeInSwitch: Unit = { + """ + object A { + def foo(x: Int): Int = (x: @scala.annotation.switch) match { + case n if n > 5 => n + case n if n >= 0 => 0 + case n => -n + } + } + """.hasNot("any match") { + case js.Match(_, _, _) => + } + } + + @Test + def matchWithOneAlternativeInSwitch: Unit = { + """ + object A { + def foo(x: Int): Int = (x: @scala.annotation.switch) match { + case -1 => 10 + case n => n + } + } + """.hasNot("any match") { + case js.Match(_, _, _) => + } + } + +} diff --git a/compiler/src/test/scala/org/scalajs/nscplugin/test/NonNativeJSTypeTest.scala b/compiler/src/test/scala/org/scalajs/nscplugin/test/NonNativeJSTypeTest.scala new file mode 100644 index 0000000000..a6d37efc1f --- /dev/null +++ b/compiler/src/test/scala/org/scalajs/nscplugin/test/NonNativeJSTypeTest.scala @@ -0,0 +1,901 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin.test + +import org.scalajs.nscplugin.test.util._ +import org.scalajs.nscplugin.test.util.VersionDependentUtils.methodSig + +import org.junit.Test +import org.junit.Ignore + +// scalastyle:off line.size.limit + +class NonNativeJSTypeTest extends DirectTest with TestHelpers { + + override def preamble: String = + """ + import scala.scalajs.js + import scala.scalajs.js.annotation._ + """ + + @Test + def noExtendAnyRef: Unit = { + """ + class A extends js.Any + """ hasErrors + """ + |newSource1.scala:5: error: Non-native JS classes and objects cannot directly extend AnyRef. They must extend a JS class (native or not). + | class A extends js.Any + | ^ + """ + + """ + object A extends js.Any + """ hasErrors + """ + |newSource1.scala:5: error: Non-native JS classes and objects cannot directly extend AnyRef. They must extend a JS class (native or not). + | object A extends js.Any + | ^ + """ + } + + @Test + def noExtendNativeTrait: Unit = { + """ + @js.native + trait NativeTrait extends js.Object + + class A extends NativeTrait + + trait B extends NativeTrait + + object C extends NativeTrait + + object Container { + val x = new NativeTrait {} + } + """ hasErrors + """ + |newSource1.scala:8: error: Non-native JS types cannot directly extend native JS traits. + | class A extends NativeTrait + | ^ + |newSource1.scala:10: error: Non-native JS types cannot directly extend native JS traits. + | trait B extends NativeTrait + | ^ + |newSource1.scala:12: error: Non-native JS types cannot directly extend native JS traits. + | object C extends NativeTrait + | ^ + |newSource1.scala:15: error: Non-native JS types cannot directly extend native JS traits. + | val x = new NativeTrait {} + | ^ + """ + } + + @Test + def noConcreteApplyMethod: Unit = { + """ + class A extends js.Object { + def apply(arg: Int): Int = arg + } + """ hasErrors + """ + |newSource1.scala:6: error: A non-native JS class cannot declare a concrete method named `apply` without `@JSName` + | def apply(arg: Int): Int = arg + | ^ + """ + + """ + trait B extends js.Object { + def apply(arg: Int): Int + } + + class A extends B { + def apply(arg: Int): Int = arg + } + """ hasErrors + """ + |newSource1.scala:6: error: A non-native JS type can only declare an abstract method named `apply` without `@JSName` if it is the SAM of a trait that extends js.Function + | def apply(arg: Int): Int + | ^ + |newSource1.scala:10: error: A non-native JS class cannot declare a concrete method named `apply` without `@JSName` + | def apply(arg: Int): Int = arg + | ^ + """ + + """ + abstract class B extends js.Object { + def apply(arg: Int): Int + } + + class A extends B { + def apply(arg: Int): Int = arg + } + """ hasErrors + """ + |newSource1.scala:6: error: A non-native JS type can only declare an abstract method named `apply` without `@JSName` if it is the SAM of a trait that extends js.Function + | def apply(arg: Int): Int + | ^ + |newSource1.scala:10: error: A non-native JS class cannot declare a concrete method named `apply` without `@JSName` + | def apply(arg: Int): Int = arg + | ^ + """ + + """ + object Enclosing { + val f = new js.Object { + def apply(arg: Int): Int = arg + } + } + """ hasErrors + """ + |newSource1.scala:7: error: A non-native JS class cannot declare a concrete method named `apply` without `@JSName` + | def apply(arg: Int): Int = arg + | ^ + """ + + """ + object Enclosing { + val f = new js.Function { + def apply(arg: Int): Int = arg + } + } + """ hasErrors + """ + |newSource1.scala:7: error: A non-native JS class cannot declare a concrete method named `apply` without `@JSName` + | def apply(arg: Int): Int = arg + | ^ + """ + + """ + object Enclosing { + val f = new js.Function1[Int, Int] { + def apply(arg: Int): Int = arg + } + } + """ hasErrors + """ + |newSource1.scala:7: error: A non-native JS class cannot declare a concrete method named `apply` without `@JSName` + | def apply(arg: Int): Int = arg + | ^ + """ + } + + @Test + def noUnaryOp: Unit = { + """ + class A extends js.Object { + def unary_+ : Int = 1 + def unary_-() : Int = 1 + } + """ hasErrors + """ + |newSource1.scala:6: warning: Method 'unary_+' should have an explicit @JSName or @JSOperator annotation because its name is one of the JavaScript operators + | def unary_+ : Int = 1 + | ^ + |newSource1.scala:6: error: A non-native JS class cannot declare a method named like a unary operation without `@JSName` + | def unary_+ : Int = 1 + | ^ + |newSource1.scala:7: warning: Method 'unary_-' should have an explicit @JSName or @JSOperator annotation because its name is one of the JavaScript operators + | def unary_-() : Int = 1 + | ^ + |newSource1.scala:7: error: A non-native JS class cannot declare a method named like a unary operation without `@JSName` + | def unary_-() : Int = 1 + | ^ + """ + + """ + class A extends js.Object { + def unary_+(x: Int): Int = 2 + + @JSName("unary_-") + def unary_-() : Int = 1 + } + """.succeeds() + } + + @Test + def noBinaryOp: Unit = { + """ + class A extends js.Object { + def +(x: Int): Int = x + def &&(x: String): String = x + } + """ hasErrors + """ + |newSource1.scala:6: warning: Method '+' should have an explicit @JSName or @JSOperator annotation because its name is one of the JavaScript operators + | def +(x: Int): Int = x + | ^ + |newSource1.scala:6: error: A non-native JS class cannot declare a method named like a binary operation without `@JSName` + | def +(x: Int): Int = x + | ^ + |newSource1.scala:7: warning: Method '&&' should have an explicit @JSName or @JSOperator annotation because its name is one of the JavaScript operators + | def &&(x: String): String = x + | ^ + |newSource1.scala:7: error: A non-native JS class cannot declare a method named like a binary operation without `@JSName` + | def &&(x: String): String = x + | ^ + """ + + """ + class A extends js.Object { + def + : Int = 2 + + def -(x: Int, y: Int): Int = 7 + + @JSName("&&") + def &&(x: String): String = x + } + """ hasWarns + """ + |newSource1.scala:6: warning: Method '+' should have an explicit @JSName or @JSOperator annotation because its name is one of the JavaScript operators + | def + : Int = 2 + | ^ + |newSource1.scala:8: warning: Method '-' should have an explicit @JSName or @JSOperator annotation because its name is one of the JavaScript operators + | def -(x: Int, y: Int): Int = 7 + | ^ + """ + } + + @Test // #4281 + def noExtendJSFunctionAnon: Unit = { + """ + @js.native + @JSGlobal("bad") + abstract class BadFunction extends js.Function1[Int, String] + + object Test { + new BadFunction { + def apply(x: Int): String = "f" + } + } + """ hasErrors + """ + |newSource1.scala:11: error: A non-native JS class cannot declare a concrete method named `apply` without `@JSName` + | def apply(x: Int): String = "f" + | ^ + """ + + """ + class $anonfun extends js.Function1[Int, String] { + def apply(x: Int): String = "f" + } + """ hasErrors + """ + |newSource1.scala:6: error: A non-native JS class cannot declare a concrete method named `apply` without `@JSName` + | def apply(x: Int): String = "f" + | ^ + """ + } + + @Test + def noBracketAccess: Unit = { + """ + class A extends js.Object { + @JSBracketAccess + def foo(index: Int, arg: Int): Int = arg + } + """ hasErrors + """ + |newSource1.scala:7: error: @JSBracketAccess is not allowed in non-native JS classes + | def foo(index: Int, arg: Int): Int = arg + | ^ + """ + } + + @Test + def noBracketCall: Unit = { + """ + class A extends js.Object { + @JSBracketCall + def foo(m: String, arg: Int): Int = arg + } + """ hasErrors + """ + |newSource1.scala:7: error: @JSBracketCall is not allowed in non-native JS classes + | def foo(m: String, arg: Int): Int = arg + | ^ + """ + } + + @Test + def noCollapseOverloadsOnJSName: Unit = { + """ + class A extends js.Object { + @JSName("bar") + def foo(): Int = 42 + + def bar(): Int = 24 + } + """ hasErrors + s""" + |newSource1.scala:9: error: Cannot disambiguate overloads for method bar with types + | ${methodSig("()", "Int")} + | ${methodSig("()", "Int")} + | def bar(): Int = 24 + | ^ + """ + + """ + class A extends js.Object { + def bar(): Int = 24 + + @JSName("bar") + def foo(): Int = 42 + } + """ hasErrors + s""" + |newSource1.scala:9: error: Cannot disambiguate overloads for method bar with types + | ${methodSig("()", "Int")} + | ${methodSig("()", "Int")} + | def foo(): Int = 42 + | ^ + """ + + """ + class A extends js.Object { + @JSName("bar") + def foo(): Int = 42 + } + + class B extends A { + def bar(): Int = 24 + } + """ hasErrors + s""" + |newSource1.scala:11: error: Cannot disambiguate overloads for method bar with types + | ${methodSig("()", "Int")} + | ${methodSig("()", "Int")} + | def bar(): Int = 24 + | ^ + """ + + """ + @js.native + @JSGlobal + class A extends js.Object { + @JSName("bar") + def foo(): Int = js.native + } + + class B extends A { + def bar(): Int = 24 + } + """ hasErrors + s""" + |newSource1.scala:13: error: Cannot disambiguate overloads for method bar with types + | ${methodSig("()", "Int")} + | ${methodSig("()", "Int")} + | def bar(): Int = 24 + | ^ + """ + + """ + @js.native + @JSGlobal + class Foo extends js.Object { + def foo(x: Int): Int = js.native + + @JSName("foo") + def bar(x: Int): Int = js.native + } + + class Bar extends Foo { + def foo(): Int = 42 + } + """ hasErrors + s""" + |newSource1.scala:14: error: Cannot disambiguate overloads for method foo with types + | ${methodSig("(x: Int)", "Int")} + | ${methodSig("(x: Int)", "Int")} + | class Bar extends Foo { + | ^ + """ + } + + @Test + def noOverloadedPrivate: Unit = { + """ + class A extends js.Object { + private def foo(i: Int): Int = i + private def foo(s: String): String = s + } + """ hasErrors + """ + |newSource1.scala:6: error: Private methods in non-native JS classes cannot be overloaded. Use different names instead. + | private def foo(i: Int): Int = i + | ^ + |newSource1.scala:7: error: Private methods in non-native JS classes cannot be overloaded. Use different names instead. + | private def foo(s: String): String = s + | ^ + """ + + """ + object A extends js.Object { + private def foo(i: Int): Int = i + private def foo(s: String): String = s + } + """ hasErrors + """ + |newSource1.scala:6: error: Private methods in non-native JS classes cannot be overloaded. Use different names instead. + | private def foo(i: Int): Int = i + | ^ + |newSource1.scala:7: error: Private methods in non-native JS classes cannot be overloaded. Use different names instead. + | private def foo(s: String): String = s + | ^ + """ + + """ + object Enclosing { + class A extends js.Object { + private[Enclosing] def foo(i: Int): Int = i + private def foo(s: String): String = s + } + } + """ hasErrors + """ + |newSource1.scala:7: error: Private methods in non-native JS classes cannot be overloaded. Use different names instead. + | private[Enclosing] def foo(i: Int): Int = i + | ^ + |newSource1.scala:8: error: Private methods in non-native JS classes cannot be overloaded. Use different names instead. + | private def foo(s: String): String = s + | ^ + """ + + """ + class A extends js.Object { + private def foo(i: Int): Int = i + def foo(s: String): String = s + } + """ hasErrors + """ + |newSource1.scala:6: error: Private methods in non-native JS classes cannot be overloaded. Use different names instead. + | private def foo(i: Int): Int = i + | ^ + """ + + """ + object Enclosing { + class A extends js.Object { + private[Enclosing] def foo(i: Int): Int = i + def foo(s: String): String = s + } + } + """ hasErrors + """ + |newSource1.scala:7: error: Private methods in non-native JS classes cannot be overloaded. Use different names instead. + | private[Enclosing] def foo(i: Int): Int = i + | ^ + """ + } + + @Test + def noVirtualQualifiedPrivate: Unit = { + """ + object Enclosing { + class A extends js.Object { + private[Enclosing] def foo(i: Int): Int = i + private[Enclosing] val x: Int = 3 + private[Enclosing] var y: Int = 5 + } + + class B extends A { + override private[Enclosing] final def foo(i: Int): Int = i + 1 + } + } + """ hasErrors + """ + |newSource1.scala:7: error: Qualified private members in non-native JS classes must be final + | private[Enclosing] def foo(i: Int): Int = i + | ^ + |newSource1.scala:8: error: Qualified private members in non-native JS classes must be final + | private[Enclosing] val x: Int = 3 + | ^ + |newSource1.scala:9: error: Qualified private members in non-native JS classes must be final + | private[Enclosing] var y: Int = 5 + | ^ + """ + + """ + object Enclosing { + object A extends js.Object { + private[Enclosing] def foo(i: Int): Int = i + private[Enclosing] val x: Int = 3 + private[Enclosing] var y: Int = 5 + } + } + """ hasErrors + """ + |newSource1.scala:7: error: Qualified private members in non-native JS classes must be final + | private[Enclosing] def foo(i: Int): Int = i + | ^ + |newSource1.scala:8: error: Qualified private members in non-native JS classes must be final + | private[Enclosing] val x: Int = 3 + | ^ + |newSource1.scala:9: error: Qualified private members in non-native JS classes must be final + | private[Enclosing] var y: Int = 5 + | ^ + """ + + """ + object Enclosing { + abstract class A extends js.Object { + private[Enclosing] def foo(i: Int): Int + private[Enclosing] val x: Int + private[Enclosing] var y: Int + } + + class B extends A { + override private[Enclosing] final def foo(i: Int): Int = i + 1 + } + } + """ hasErrors + """ + |newSource1.scala:7: error: Qualified private members in non-native JS classes must be final + | private[Enclosing] def foo(i: Int): Int + | ^ + |newSource1.scala:8: error: Qualified private members in non-native JS classes must be final + | private[Enclosing] val x: Int + | ^ + |newSource1.scala:9: error: Qualified private members in non-native JS classes must be final + | private[Enclosing] var y: Int + | ^ + """ + + """ + object Enclosing { + trait A extends js.Object { + private[Enclosing] def foo(i: Int): Int + private[Enclosing] val x: Int + private[Enclosing] var y: Int + } + } + """ hasErrors + """ + |newSource1.scala:7: error: Qualified private members in non-native JS classes must be final + | private[Enclosing] def foo(i: Int): Int + | ^ + |newSource1.scala:8: error: Qualified private members in non-native JS classes must be final + | private[Enclosing] val x: Int + | ^ + |newSource1.scala:9: error: Qualified private members in non-native JS classes must be final + | private[Enclosing] var y: Int + | ^ + """ + + """ + object Enclosing { + class A private () extends js.Object + + class B private[this] () extends js.Object + + class C private[Enclosing] () extends js.Object + } + """.succeeds() + + """ + object Enclosing { + class A extends js.Object { + final private[Enclosing] def foo(i: Int): Int = i + } + } + """.succeeds() + + """ + object Enclosing { + class A extends js.Object { + private def foo(i: Int): Int = i + private[this] def bar(i: Int): Int = i + 1 + } + } + """.succeeds() + + """ + object Enclosing { + object A extends js.Object { + final private[Enclosing] def foo(i: Int): Int = i + } + } + """.succeeds() + + """ + object Enclosing { + object A extends js.Object { + private def foo(i: Int): Int = i + private[this] def bar(i: Int): Int = i + 1 + } + } + """.succeeds() + + """ + object Enclosing { + abstract class A extends js.Object { + final private[Enclosing] def foo(i: Int): Int + } + } + """ hasErrors + """ + |newSource1.scala:7: error: abstract member may not have final modifier + | final private[Enclosing] def foo(i: Int): Int + | ^ + """ + + """ + object Enclosing { + trait A extends js.Object { + final private[Enclosing] def foo(i: Int): Int + } + } + """ hasErrors + """ + |newSource1.scala:7: error: abstract member may not have final modifier + | final private[Enclosing] def foo(i: Int): Int + | ^ + """ + } + + @Test + def noUseJsNative: Unit = { + """ + class A extends js.Object { + def foo = js.native + } + """ hasErrors + """ + |newSource1.scala:6: error: js.native may only be used as stub implementation in facade types + | def foo = js.native + | ^ + """ + + """ + object A extends js.Object { + def foo = js.native + } + """ hasErrors + """ + |newSource1.scala:6: error: js.native may only be used as stub implementation in facade types + | def foo = js.native + | ^ + """ + + """ + class A { + val x = new js.Object { + def a: Int = js.native + } + } + """ hasErrors + """ + |newSource1.scala:7: error: js.native may only be used as stub implementation in facade types + | def a: Int = js.native + | ^ + """ + } + + @Test + def noNonLiteralJSName: Unit = { + """ + object A { + val a = "Hello" + final val b = "World" + } + + class B extends js.Object { + @JSName(A.a) + def foo: Int = 5 + @JSName(A.b) + def bar: Int = 5 + } + """ hasErrors + """ + |newSource1.scala:11: error: A string argument to JSName must be a literal string + | @JSName(A.a) + | ^ + """ + + """ + object A { + val a = "Hello" + final val b = "World" + } + + object B extends js.Object { + @JSName(A.a) + def foo: Int = 5 + @JSName(A.b) + def bar: Int = 5 + } + """ hasErrors + """ + |newSource1.scala:11: error: A string argument to JSName must be a literal string + | @JSName(A.a) + | ^ + """ + } + + @Test + def noApplyProperty: Unit = { + // def apply + + """ + class A extends js.Object { + def apply: Int = 42 + } + """ hasErrors + """ + |newSource1.scala:6: error: A member named apply represents function application in JavaScript. A parameterless member should be exported as a property. You must add @JSName("apply") + | def apply: Int = 42 + | ^ + """ + + """ + class A extends js.Object { + @JSName("apply") + def apply: Int = 42 + } + """.succeeds() + + // val apply + + """ + class A extends js.Object { + val apply: Int = 42 + } + """ hasErrors + """ + |newSource1.scala:6: error: A member named apply represents function application in JavaScript. A parameterless member should be exported as a property. You must add @JSName("apply") + | val apply: Int = 42 + | ^ + """ + + """ + class A extends js.Object { + @JSName("apply") + val apply: Int = 42 + } + """.succeeds() + + // var apply + + """ + class A extends js.Object { + var apply: Int = 42 + } + """ hasErrors + """ + |newSource1.scala:6: error: A member named apply represents function application in JavaScript. A parameterless member should be exported as a property. You must add @JSName("apply") + | var apply: Int = 42 + | ^ + """ + + """ + class A extends js.Object { + @JSName("apply") + var apply: Int = 42 + } + """.succeeds() + } + + @Test + def noExportClassWithOnlyPrivateCtors: Unit = { + """ + @JSExportTopLevel("A") + class A private () extends js.Object + """ hasErrors + """ + |newSource1.scala:5: error: You may not export a class that has only private constructors + | @JSExportTopLevel("A") + | ^ + """ + + """ + @JSExportTopLevel("A") + class A private[this] () extends js.Object + """ hasErrors + """ + |newSource1.scala:5: error: You may not export a class that has only private constructors + | @JSExportTopLevel("A") + | ^ + """ + + """ + @JSExportTopLevel("A") + class A private[A] () extends js.Object + + object A + """ hasErrors + """ + |newSource1.scala:5: error: You may not export a class that has only private constructors + | @JSExportTopLevel("A") + | ^ + """ + } + + @Test + def noConcreteMemberInTrait: Unit = { + """ + trait A extends js.Object { + def foo(x: Int): Int = x + 1 + def bar[A](x: A): A = x + + object InnerScalaObject + object InnerJSObject extends js.Object + @js.native object InnerNativeJSObject extends js.Object + + class InnerScalaClass + class InnerJSClass extends js.Object + @js.native class InnerNativeJSClass extends js.Object + } + """ hasErrors + """ + |newSource1.scala:6: error: In non-native JS traits, defs with parentheses must be abstract. + | def foo(x: Int): Int = x + 1 + | ^ + |newSource1.scala:7: error: In non-native JS traits, defs with parentheses must be abstract. + | def bar[A](x: A): A = x + | ^ + |newSource1.scala:9: error: Non-native JS traits cannot contain inner classes or objects + | object InnerScalaObject + | ^ + |newSource1.scala:10: error: Non-native JS traits cannot contain inner classes or objects + | object InnerJSObject extends js.Object + | ^ + |newSource1.scala:11: error: non-native JS classes, traits and objects may not have native JS members + | @js.native object InnerNativeJSObject extends js.Object + | ^ + |newSource1.scala:13: error: Non-native JS traits cannot contain inner classes or objects + | class InnerScalaClass + | ^ + |newSource1.scala:14: error: Non-native JS traits cannot contain inner classes or objects + | class InnerJSClass extends js.Object + | ^ + |newSource1.scala:15: error: non-native JS classes, traits and objects may not have native JS members + | @js.native class InnerNativeJSClass extends js.Object + | ^ + """ + } + + @Test // #4511 + def noConflictingProperties: Unit = { + """ + class A extends js.Object { + def a: Unit = () + + @JSName("a") + def b: Unit = () + } + """ hasErrors + s""" + |newSource1.scala:9: error: Cannot disambiguate overloads for getter a with types + | ${methodSig("()", "Unit")} + | ${methodSig("()", "Unit")} + | def b: Unit = () + | ^ + """ + + """ + class A extends js.Object { + class B extends js.Object + + object B + } + """ hasErrors + s""" + |newSource1.scala:8: error: Cannot disambiguate overloads for getter B with types + | ${methodSig("()", "A$B.type")} + | ${methodSig("()", "Object")} + | object B + | ^ + """ + } + +} diff --git a/compiler/src/test/scala/org/scalajs/nscplugin/test/OptimizationTest.scala b/compiler/src/test/scala/org/scalajs/nscplugin/test/OptimizationTest.scala new file mode 100644 index 0000000000..227eafde4d --- /dev/null +++ b/compiler/src/test/scala/org/scalajs/nscplugin/test/OptimizationTest.scala @@ -0,0 +1,571 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin.test + +import util._ + +import org.junit.Test + +import org.scalajs.ir.{Trees => js, Types => jstpe} +import org.scalajs.ir.Names._ + +class OptimizationTest extends JSASTTest { + import OptimizationTest._ + + @Test + def testArrayApplyOptimization: Unit = { + /* Make sure Array(...) is optimized away completely for several kinds + * of data types, with both the generic overload and the ones specialized + * for primitives. + */ + """ + class A { + val a = Array(5, 7, 9, -3) + val b = Array("hello", "world") + val c = Array('a', 'b') + val d = Array(Nil) + val e = Array(5.toByte, 7.toByte, 9.toByte, -3.toByte) + + // Also with exactly 1 element of a primitive type (#3938) + val f = Array('a') + val g = Array(5.toByte) + } + """. + hasNot("any LoadModule of the scala.Array companion") { + case js.LoadModule(ArrayModuleClass) => + } + + /* Using [] with primitives produces suboptimal trees, which cannot be + * optimized. We should improve this in the future, if possible. This is + * particularly annoying for Byte and Short, as it means that we need to + * write `.toByte` for every single element if we want the optimization to + * kick in. + * + * Scala/JVM has the same limitation. + */ + """ + class A { + val a = Array[Int](5, 7, 9, -3) + val b = Array[Byte](5, 7, 9, -3) + val c = Array[Int](5) + val d = Array[Byte](5) + } + """. + hasExactly(4, "calls to Array.apply methods") { + case js.Apply(_, js.LoadModule(ArrayModuleClass), js.MethodIdent(methodName), _) + if methodName.simpleName == applySimpleMethodName => + } + } + + @Test + def testJSArrayApplyOptimization: Unit = { + /* Make sure js.Array(...) is optimized away completely for several kinds + * of data types. + */ + """ + import scala.scalajs.js + + class VC(val x: Int) extends AnyVal + + class A { + val a = js.Array(5, 7, 9, -3) + val b = js.Array("hello", "world") + val c = js.Array('a', 'b') + val d = js.Array(Nil) + val e = js.Array(new VC(151189)) + } + """. + hasNot("any of the wrapArray methods") { + case WrapArrayCall() => + } + } + + @Test + def testVarArgsOptimization: Unit = { + /* Make sure varargs are optimized to use js.WrappedArray instead of + * scm.WrappedArray, for various data types. + */ + """ + import scala.scalajs.js + + class VC(val x: Int) extends AnyVal + + class A { + val a = List(5, 7, 9, -3) + val b = List("hello", "world") + val c = List('a', 'b') + val d = List(Nil) + val e = List(new VC(151189)) + } + """. + hasNot("any of the wrapArray methods") { + case WrapArrayCall() => + } + + /* #2265 and #2741: + * Make sure varargs are optimized to use js.WrappedArray instead of + * scm.WrappedArray, for different species of target method (single arg + * list, multiple arg list, in value class). + */ + """ + import scala.scalajs.js + + class VC(val x: Int) extends AnyVal { + def singleInVC(ys: Int*): Int = x + ys.size + } + + class A { + def test(): Int = { + val a = single(5, 7, 9, -3) + val b = multiple(5)(7, 9, -3) + val c = new VC(5).singleInVC(7, 9, -3) + a + b + c + } + + def single(x: Int, ys: Int*): Int = x + ys.size + def multiple(x: Int)(ys: Int*): Int = x + ys.size + } + """. + hasNot("any of the wrapArray methods") { + case WrapArrayCall() => + } + + /* Make sure our wrapper matcher has the right name. + * With the new collections, only actual varargs will produce a call to the + * methods we optimize, and we would always be able to optimize them in + * that case. So we need to explicitly call the method that the codegen + * would use. + */ + val sanityCheckCode = if (hasOldCollections) { + """ + class A { + val a: Seq[Int] = new Array[Int](5) + } + """ + } else { + """ + class A { + runtime.ScalaRunTime.wrapIntArray(new Array[Int](5)) + } + """ + } + sanityCheckCode.has("one of the wrapArray methods") { + case WrapArrayCall() => + } + } + + @Test + def testNewJSObjectAndJSArray: Unit = { + // Verify the optimized emitted code for 'new js.Object' and 'new js.Array' + """ + import scala.scalajs.js + + class A { + val o = new js.Object + val a = new js.Array + } + """. + hasNot("any reference to the global scope") { + case js.JSLinkingInfo() => + } + } + + @Test + def noLabeledBlockForWhileLoops: Unit = { + """ + class Test { + def testWhileStatWithCond(): Unit = { + var x: Int = 5 + while (x != 0) { + x -= 1 + } + println(x) + } + + def testWhileExprWithCond(s: Any): Unit = { + var x: Int = 5 + s match { + case s: String => + while (x != 0) { + x -= 1 + } + } + } + + def testWhileTrueStat(): Unit = { + var x: Int = 5 + while (true) { + x -= 1 + if (x == 0) + return + println(x) + } + } + + def testWhileTrueExpr(s: Any): Unit = { + var x: Int = 5 + s match { + case s: String => + while (true) { + x -= 1 + if (x == 0) + return + println(x) + } + } + } + + def testWhileFalseStat(): Unit = { + var x: Int = 5 + while (false) { + x -= 1 + if (x == 0) + return + println(x) + } + } + + def testWhileFalseExpr(s: Any): Unit = { + var x: Int = 5 + s match { + case s: String => + while (false) { + x -= 1 + if (x == 0) + return + println(x) + } + } + } + } + """.hasNot("non-return labeled block") { + case js.Labeled(name, _, _) if !name.name.nameString.startsWith("_return") => + } + } + + @Test + def noLabeledBlockForDoWhileLoops: Unit = { + """ + class Test { + def testDoWhileStatWithCond(): Unit = { + var x: Int = 5 + do { + x -= 1 + } while (x != 0) + println(x) + } + + def testDoWhileExprWithCond(s: Any): Unit = { + var x: Int = 5 + s match { + case s: String => + do { + x -= 1 + } while (x != 0) + } + } + + def testDoWhileTrueStat(): Unit = { + var x: Int = 5 + do { + x -= 1 + if (x == 0) + return + println(x) + } while (true) + } + + def testDoWhileTrueExpr(s: Any): Unit = { + var x: Int = 5 + s match { + case s: String => + do { + x -= 1 + if (x == 0) + return + println(x) + } while (true) + } + } + + def testDoWhileFalseStat(): Unit = { + var x: Int = 5 + do { + x -= 1 + if (x == 0) + return + println(x) + } while (false) + } + + def testDoWhileFalseExpr(s: Any): Unit = { + var x: Int = 5 + s match { + case s: String => + do { + x -= 1 + if (x == 0) + return + println(x) + } while (false) + } + } + } + """.hasNot("non-return labeled block") { + case js.Labeled(name, _, _) if !name.name.nameString.startsWith("_return") => + } + } + + @Test + def noLabeledBlockForPatmatWithToplevelCaseClassesOnlyAndNoGuards: Unit = { + """ + sealed abstract class Foo + final case class Foobar(x: Int) extends Foo + final case class Foobaz(y: String) extends Foo + + class Test { + def testWithListsStat(xs: List[Int]): Unit = { + xs match { + case head :: tail => println(head + " " + tail) + case Nil => println("nil") + } + } + + def testWithListsExpr(xs: List[Int]): Int = { + xs match { + case head :: tail => head + tail.size + case Nil => 0 + } + } + + def testWithFooStat(foo: Foo): Unit = { + foo match { + case Foobar(x) => println("foobar: " + x) + case Foobaz(y) => println(y) + } + } + + def testWithFooExpr(foo: Foo): String = { + foo match { + case Foobar(x) => "foobar: " + x + case Foobaz(y) => "foobaz: " + y + } + } + } + """.hasNot("Labeled block") { + case js.Labeled(_, _, _) => + } + } + + @Test + def switchWithoutGuards: Unit = { + """ + class Test { + def switchWithGuardsStat(x: Int, y: Int): Unit = { + x match { + case 1 => println("one") + case 2 => println("two") + case z if y > 100 => println("big " + z) + case _ => println("None of those") + } + } + } + """.hasNot("Labeled block") { + case js.Labeled(_, _, _) => + }.has("Match node") { + case js.Match(_, _, _) => + } + } + + @Test + def switchWithGuards: Unit = { + // Statement position + """ + class Test { + def switchWithGuardsStat(x: Int, y: Int): Unit = { + x match { + case 1 => println("one") + case 2 if y < 10 => println("two special") + case 2 => println("two") + case 3 if y < 10 => println("three special") + case 3 if y > 100 => println("three big special") + case z if y > 100 => println("big " + z) + case _ => println("None of those") + } + } + } + """.hasExactly(1, "default case (\"None of those\")") { + case js.StringLiteral("None of those") => + }.has("Match node") { + case js.Match(_, _, _) => + } + + // Expression position + """ + class Test { + def switchWithGuardsExpr(x: Int, y: Int): Unit = { + val message = x match { + case 1 => "one" + case 2 if y < 10 => "two special" + case 2 => "two" + case 3 if y < 10 => "three special" + case 3 if y > 100 => "three big special" + case z if y > 100 => "big " + z + case _ => "None of those" + } + println(message) + } + } + """.hasExactly(1, "default case (\"None of those\")") { + case js.StringLiteral("None of those") => + }.has("Match node") { + case js.Match(_, _, _) => + } + } + + @Test + def newSJSDefinedTraitProducesObjectConstr: Unit = { + """ + import scala.scalajs.js + import scala.scalajs.js.annotation._ + + trait Point extends js.Object { + val x: Double + val y: Double + } + + class Test { + def newSJSDefinedTraitProducesObjectConstr(): Any = { + new Point { + val x = 5.0 + val y = 6.5 + } + } + } + """.hasNot("`new Object`") { + case js.JSNew(_, _) => + }.has("object literal") { + case js.JSObjectConstr(Nil) => + } + + """ + import scala.scalajs.js + import scala.scalajs.js.annotation._ + + trait Point extends js.Object { + var x: js.UndefOr[Double] = js.undefined + var y: js.UndefOr[Double] = js.undefined + } + + class Test { + def newSJSDefinedTraitProducesObjectConstr(): Any = { + new Point { + x = 5.0 + y = 6.5 + } + } + } + """.hasNot("`new Object`") { + case js.JSNew(_, _) => + }.has("object literal") { + case js.JSObjectConstr(Nil) => + } + } + + @Test + def optimizeScalaLambda: Unit = { + val allowedNames = Set(ClassName("A$"), ClassName("A")) + + """ + object A { + val x: Int => String = _.toString + } + """.hasNot("auxiliary/anonymous class") { + case cl: js.ClassDef if !allowedNames.contains(cl.name.name) => + } + } + + @Test + def noWrapJavaScriptExceptionWhenCatchingWildcardThrowable: Unit = { + """ + class Test { + def foo(): Int = throw new IllegalArgumentException("foo") + + def testCatchFullWildcard(): Int = { + try { + foo() + } catch { + case _ => -1 // causes an expected Scala compile warning + } + } + + def testCatchWildcardOfTypeThrowable(): Int = { + try { + foo() + } catch { + case _: Throwable => -1 + } + } + } + """.hasNot("WrapAsThrowable") { + case js.WrapAsThrowable(_) => + } + + // Confidence check + """ + class Test { + def foo(): Int = throw new IllegalArgumentException("foo") + + def testCatchWildcardOfTypeRuntimeException(): Int = { + try { + foo() + } catch { + case _: RuntimeException => -1 + } + } + } + """.hasExactly(1, "WrapAsThrowable") { + case js.WrapAsThrowable(_) => + } + } +} + +object OptimizationTest { + + private val ArrayModuleClass = ClassName("scala.Array$") + + private val applySimpleMethodName = SimpleMethodName("apply") + + private val hasOldCollections = { + val version = scala.util.Properties.versionNumberString + + version.startsWith("2.11.") || + version.startsWith("2.12.") + } + + private object WrapArrayCall { + private val WrappedArrayTypeRef = { + val name = + if (hasOldCollections) "scala.collection.mutable.WrappedArray" + else "scala.collection.immutable.ArraySeq" + jstpe.ClassRef(ClassName(name)) + } + + def unapply(tree: js.Apply): Boolean = { + val methodName = tree.method.name + methodName.simpleName.nameString.startsWith("wrap") && + methodName.resultTypeRef == WrappedArrayTypeRef + } + } + +} diff --git a/compiler/src/test/scala/org/scalajs/core/compiler/test/PositionTest.scala b/compiler/src/test/scala/org/scalajs/nscplugin/test/PositionTest.scala similarity index 93% rename from compiler/src/test/scala/org/scalajs/core/compiler/test/PositionTest.scala rename to compiler/src/test/scala/org/scalajs/nscplugin/test/PositionTest.scala index de73b811ea..846560dbab 100644 --- a/compiler/src/test/scala/org/scalajs/core/compiler/test/PositionTest.scala +++ b/compiler/src/test/scala/org/scalajs/nscplugin/test/PositionTest.scala @@ -10,7 +10,7 @@ * additional information regarding copyright ownership. */ -package org.scalajs.core.compiler.test +package org.scalajs.nscplugin.test import util.JSASTTest @@ -19,7 +19,7 @@ import org.junit.Assert._ import scala.reflect.internal.util.BatchSourceFile -import org.scalajs.core.ir.{Trees => js} +import org.scalajs.ir.{Trees => js} class PositionTest extends JSASTTest { diff --git a/compiler/src/test/scala/org/scalajs/core/compiler/test/ReflectTest.scala b/compiler/src/test/scala/org/scalajs/nscplugin/test/ReflectTest.scala similarity index 96% rename from compiler/src/test/scala/org/scalajs/core/compiler/test/ReflectTest.scala rename to compiler/src/test/scala/org/scalajs/nscplugin/test/ReflectTest.scala index 799bf5bc8d..f6937e2475 100644 --- a/compiler/src/test/scala/org/scalajs/core/compiler/test/ReflectTest.scala +++ b/compiler/src/test/scala/org/scalajs/nscplugin/test/ReflectTest.scala @@ -10,9 +10,9 @@ * additional information regarding copyright ownership. */ -package org.scalajs.core.compiler.test +package org.scalajs.nscplugin.test -import org.scalajs.core.compiler.test.util._ +import org.scalajs.nscplugin.test.util._ import org.junit.Test // scalastyle:off line.size.limit diff --git a/compiler/src/test/scala/org/scalajs/nscplugin/test/StaticForwardersASTTest.scala b/compiler/src/test/scala/org/scalajs/nscplugin/test/StaticForwardersASTTest.scala new file mode 100644 index 0000000000..e718a73ff4 --- /dev/null +++ b/compiler/src/test/scala/org/scalajs/nscplugin/test/StaticForwardersASTTest.scala @@ -0,0 +1,91 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin.test + +import org.scalajs.nscplugin.test.util._ + +import org.scalajs.ir.Names._ +import org.scalajs.ir.Trees._ +import org.scalajs.ir.Types._ + +import org.junit.Assert._ +import org.junit.Test + +// scalastyle:off line.size.limit + +class StaticForwardersASTTest extends JSASTTest { + + @Test + def emitStaticForwardersInExistingClass(): Unit = { + val classDef = """ + import scala.scalajs.js, js.annotation._ + + class Foo(val y: Int = 10) + + object Foo { + def bar(x: Int = 5): Int = x + 1 + + @js.native + @JSGlobal("foobar") + def foobar(x: Int = 5): Int = js.native + } + """.extractOne("class Foo") { + case cd: ClassDef if cd.name.name == ClassName("Foo") => cd + } + + val staticMethodNames = classDef.memberDefs.collect { + case MethodDef(flags, MethodIdent(name), _, _, _, _) if flags.namespace.isStatic => + name + }.sortBy(_.simpleName) + + assertEquals( + List( + MethodName("$lessinit$greater$default$1", Nil, IntRef), + MethodName("bar", List(IntRef), IntRef), + MethodName("bar$default$1", Nil, IntRef) + ), + staticMethodNames + ) + } + + @Test + def emitStaticForwardersInSyntheticClass(): Unit = { + val classDef = """ + import scala.scalajs.js, js.annotation._ + + object Foo { + def bar(x: Int = 5): Int = x + 1 + + @js.native + @JSGlobal("foobar") + def foobar(x: Int = 5): Int = js.native + } + """.extractOne("class Foo") { + case cd: ClassDef if cd.name.name == ClassName("Foo") => cd + } + + val staticMethodNames = classDef.memberDefs.collect { + case MethodDef(flags, MethodIdent(name), _, _, _, _) if flags.namespace.isStatic => + name + }.sortBy(_.simpleName) + + assertEquals( + List( + MethodName("bar", List(IntRef), IntRef), + MethodName("bar$default$1", Nil, IntRef) + ), + staticMethodNames + ) + } + +} diff --git a/compiler/src/test/scala/org/scalajs/nscplugin/test/StaticForwardersWarningsAllObjectsTest.scala b/compiler/src/test/scala/org/scalajs/nscplugin/test/StaticForwardersWarningsAllObjectsTest.scala new file mode 100644 index 0000000000..6294d7c7ba --- /dev/null +++ b/compiler/src/test/scala/org/scalajs/nscplugin/test/StaticForwardersWarningsAllObjectsTest.scala @@ -0,0 +1,64 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin.test + +import org.scalajs.nscplugin.test.util._ +import org.scalajs.nscplugin.test.util.VersionDependentUtils.scalaSupportsNoWarn + +import org.junit.Assume._ +import org.junit.Test + +// scalastyle:off line.size.limit + +class StaticForwardersWarningsAllObjectsTest extends DirectTest with TestHelpers { + + override def extraArgs: List[String] = + super.extraArgs ::: List("-P:scalajs:genStaticForwardersForNonTopLevelObjects") + + @Test + def warnWhenAvoidingStaticForwardersForNonTopLevelObject: Unit = { + """ + object Enclosing { + class A + + object a { + def foo(x: Int): Int = x + 1 + } + } + """ hasWarns + """ + |newSource1.scala:5: warning: Not generating the static forwarders of Enclosing$a because its name differs only in case from the name of another class or trait in this compilation unit. + | object a { + | ^ + """ + } + + @Test + def noWarnIfSelectivelyDisabled: Unit = { + assumeTrue(scalaSupportsNoWarn) + + """ + import scala.annotation.nowarn + + object Enclosing { + class A + + @nowarn("cat=other") + object a { + def foo(x: Int): Int = x + 1 + } + } + """.hasNoWarns() + } + +} diff --git a/compiler/src/test/scala/org/scalajs/nscplugin/test/StaticForwardersWarningsTopLevelOnlyTest.scala b/compiler/src/test/scala/org/scalajs/nscplugin/test/StaticForwardersWarningsTopLevelOnlyTest.scala new file mode 100644 index 0000000000..e3e9cf39ea --- /dev/null +++ b/compiler/src/test/scala/org/scalajs/nscplugin/test/StaticForwardersWarningsTopLevelOnlyTest.scala @@ -0,0 +1,88 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin.test + +import org.scalajs.nscplugin.test.util._ +import org.scalajs.nscplugin.test.util.VersionDependentUtils._ + +import org.junit.Assume._ +import org.junit.Test + +// scalastyle:off line.size.limit + +class StaticForwardersWarningsTopLevelOnlyTest extends DirectTest with TestHelpers { + + @Test + def warnWhenAvoidingStaticForwardersForTopLevelObject: Unit = { + val jvmBackendIssuesWarningOfItsOwn = { + !scalaVersion.startsWith("2.11.") && + scalaVersion != "2.12.1" && + scalaVersion != "2.12.2" && + scalaVersion != "2.12.3" && + scalaVersion != "2.12.4" + } + val jvmBackendMessage = if (!jvmBackendIssuesWarningOfItsOwn) { + "" + } else { + """ + |newSource1.scala:4: warning: Generated class a differs only in case from A. + | Such classes will overwrite one another on case-insensitive filesystems. + | object a { + | ^ + """ + } + + """ + class A + + object a { + def foo(x: Int): Int = x + 1 + } + """ hasWarns + s""" + |newSource1.scala:4: warning: Not generating the static forwarders of a because its name differs only in case from the name of another class or trait in this compilation unit. + | object a { + | ^$jvmBackendMessage + """ + } + + @Test + def noWarnIfSelectivelyDisabled: Unit = { + assumeTrue(scalaSupportsNoWarn) + + """ + import scala.annotation.nowarn + + class A + + @nowarn("cat=other") + object a { + def foo(x: Int): Int = x + 1 + } + """.hasNoWarns() + } + + @Test + def noWarnForNonTopLevelObject: Unit = { + """ + object Enclosing { + class A + + object a { + def foo(x: Int): Int = x + 1 + } + } + """.hasNoWarns() + } + +} diff --git a/compiler/src/test/scala/org/scalajs/core/compiler/test/util/DirectTest.scala b/compiler/src/test/scala/org/scalajs/nscplugin/test/util/DirectTest.scala similarity index 81% rename from compiler/src/test/scala/org/scalajs/core/compiler/test/util/DirectTest.scala rename to compiler/src/test/scala/org/scalajs/nscplugin/test/util/DirectTest.scala index 737de155d9..72a2978c05 100644 --- a/compiler/src/test/scala/org/scalajs/core/compiler/test/util/DirectTest.scala +++ b/compiler/src/test/scala/org/scalajs/nscplugin/test/util/DirectTest.scala @@ -10,14 +10,15 @@ * additional information regarding copyright ownership. */ -package org.scalajs.core.compiler.test.util +package org.scalajs.nscplugin.test.util import scala.tools.nsc._ import scala.tools.nsc.plugins.Plugin -import reporters.{Reporter, ConsoleReporter} -import scala.reflect.internal.util.{ SourceFile, BatchSourceFile } +import scala.tools.nsc.reporters.ConsoleReporter -import org.scalajs.core.compiler.ScalaJSPlugin +import scala.reflect.internal.util.{SourceFile, BatchSourceFile} + +import org.scalajs.nscplugin.ScalaJSPlugin import scala.collection.mutable @@ -27,12 +28,12 @@ import java.io.File abstract class DirectTest { /** these arguments are always added to the args passed to newSettings */ - def extraArgs: List[String] = List("-P:scalajs:sjsDefinedByDefault") + def extraArgs: List[String] = Nil /** create settings objects for test from arg string */ def newSettings(args: List[String]): Settings = { val s = new Settings - s processArguments (args, true) + s.processArguments(args, true) s } @@ -59,7 +60,7 @@ abstract class DirectTest { override lazy val plugins = { val scalaJSPlugin = newScalaJSPlugin(global) - scalaJSPlugin.processOptions(scalaJSPlugin.options, + scalaJSPlugin.init(scalaJSPlugin.options, msg => throw new IllegalArgumentException(msg)) scalaJSPlugin :: Nil } @@ -71,7 +72,8 @@ abstract class DirectTest { def newScalaJSPlugin(global: Global): ScalaJSPlugin = new ScalaJSPlugin(global) - def newReporter(settings: Settings): Reporter = new ConsoleReporter(settings) + def newReporter(settings: Settings): ConsoleReporter = + new ConsoleReporter(settings) private def newSources(codes: String*) = codes.toList.zipWithIndex map { case (src, idx) => new BatchSourceFile(s"newSource${idx + 1}.scala", src) @@ -93,10 +95,9 @@ abstract class DirectTest { def compileString(sourceCode: String): Boolean = compileString(defaultGlobal)(sourceCode) - // Cannot reuse global, otherwise compiler crashes with Scala >= 2.11.5 - // on following tests: - // - org.scalajs.core.compiler.test.JSExportTest - // - org.scalajs.core.compiler.test.JSDynamicLiteralTest + // Cannot reuse global, otherwise the compiler crashes on the following tests: + // - org.scalajs.nscplugin.test.JSExportTest + // - org.scalajs.nscplugin.test.JSDynamicLiteralTest // Filed as #1443 def defaultGlobal: Global = newScalaJSCompiler() diff --git a/compiler/src/test/scala/org/scalajs/nscplugin/test/util/JSASTTest.scala b/compiler/src/test/scala/org/scalajs/nscplugin/test/util/JSASTTest.scala new file mode 100644 index 0000000000..7b1e52ca44 --- /dev/null +++ b/compiler/src/test/scala/org/scalajs/nscplugin/test/util/JSASTTest.scala @@ -0,0 +1,158 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin.test.util + +import language.implicitConversions + +import scala.tools.nsc._ +import scala.reflect.internal.util.SourceFile + +import scala.util.control.ControlThrowable + +import org.junit.Assert._ + +import org.scalajs.nscplugin.ScalaJSPlugin +import org.scalajs.ir +import ir.{Trees => js} + +abstract class JSASTTest extends DirectTest { + + private var lastAST: JSAST = _ + + class JSAST(val clDefs: List[js.ClassDef]) { + type Pat = PartialFunction[js.IRNode, Unit] + + class PFTraverser(pf: Pat) extends ir.Traversers.Traverser { + private case object Found extends ControlThrowable + + private[this] var finding = false + + def find: Boolean = { + finding = true + try { + clDefs.map(traverseClassDef) + false + } catch { + case Found => true + } + } + + def traverse(): Unit = { + finding = false + clDefs.map(traverseClassDef) + } + + override def traverse(tree: js.Tree): Unit = { + handle(tree) + super.traverse(tree) + } + + override def traverseClassDef(classDef: js.ClassDef): Unit = { + handle(classDef) + super.traverseClassDef(classDef) + } + + override def traverseMemberDef(memberDef: js.MemberDef): Unit = { + handle(memberDef) + super.traverseMemberDef(memberDef) + } + + override def traverseTopLevelExportDef( + exportDef: js.TopLevelExportDef): Unit = { + handle(exportDef) + super.traverseTopLevelExportDef(exportDef) + } + + private def handle(node: js.IRNode): Unit = { + if (finding) { + if (pf.isDefinedAt(node)) + throw Found + } else { + pf.lift(node) + } + } + } + + def has(trgName: String)(pf: Pat): this.type = { + val tr = new PFTraverser(pf) + if (!tr.find) + fail(s"AST should have $trgName but was\n$show") + this + } + + def hasNot(trgName: String)(pf: Pat): this.type = { + val tr = new PFTraverser(pf) + if (tr.find) + fail(s"AST should not have $trgName but was\n$show") + this + } + + def hasExactly(count: Int, trgName: String)(pf: Pat): this.type = { + var actualCount = 0 + val tr = new PFTraverser(pf.andThen(_ => actualCount += 1)) + tr.traverse() + if (actualCount != count) + fail(s"AST has $actualCount $trgName but expected $count; it was\n$show") + this + } + + def extractOne[A](trgName: String)(pf: PartialFunction[js.IRNode, A]): A = { + var result: Option[A] = None + val tr = new PFTraverser(pf.andThen { r => + if (result.isDefined) + fail(s"AST has more than one $trgName") + result = Some(r) + }) + tr.traverse() + result.getOrElse { + fail(s"AST should have a $trgName") + throw new AssertionError("unreachable") + } + } + + def traverse(pf: Pat): this.type = { + val tr = new PFTraverser(pf) + tr.traverse() + this + } + + def show: String = + clDefs.map(_.show).mkString("\n") + + } + + implicit def string2ast(str: String): JSAST = stringAST(str) + + override def newScalaJSPlugin(global: Global): ScalaJSPlugin = { + new ScalaJSPlugin(global) { + override def generatedJSAST(cld: List[js.ClassDef]): Unit = { + lastAST = new JSAST(cld) + } + } + } + + def stringAST(code: String): JSAST = stringAST(defaultGlobal)(code) + def stringAST(global: Global)(code: String): JSAST = { + if (!compileString(global)(code)) + throw new IllegalArgumentException("snippet did not compile") + lastAST + } + + def sourceAST(source: SourceFile): JSAST = sourceAST(defaultGlobal)(source) + def sourceAST(global: Global)(source: SourceFile): JSAST = { + if (!compileSources(global)(source)) + throw new IllegalArgumentException("snippet did not compile") + lastAST + } + +} diff --git a/compiler/src/test/scala/org/scalajs/core/compiler/test/util/TestHelpers.scala b/compiler/src/test/scala/org/scalajs/nscplugin/test/util/TestHelpers.scala similarity index 80% rename from compiler/src/test/scala/org/scalajs/core/compiler/test/util/TestHelpers.scala rename to compiler/src/test/scala/org/scalajs/nscplugin/test/util/TestHelpers.scala index e3839853a8..8336f2e472 100644 --- a/compiler/src/test/scala/org/scalajs/core/compiler/test/util/TestHelpers.scala +++ b/compiler/src/test/scala/org/scalajs/nscplugin/test/util/TestHelpers.scala @@ -10,22 +10,20 @@ * additional information regarding copyright ownership. */ -package org.scalajs.core.compiler.test.util +package org.scalajs.nscplugin.test.util import java.io._ -import scala.tools.nsc._ -import reporters.{Reporter, ConsoleReporter} +import scala.tools.nsc._ +import scala.tools.nsc.reporters.ConsoleReporter import org.junit.Assert._ -import scala.util.matching.Regex - trait TestHelpers extends DirectTest { private[this] val errBuffer = new CharArrayWriter - override def newReporter(settings: Settings): Reporter = { + override def newReporter(settings: Settings): ConsoleReporter = { val in = new BufferedReader(new StringReader("")) val out = new PrintWriter(errBuffer) new ConsoleReporter(settings, in, out) @@ -34,6 +32,12 @@ trait TestHelpers extends DirectTest { /** will be prefixed to every code that is compiled. use for imports */ def preamble: String = "" + protected def since(v: String): String = { + val version = scala.util.Properties.versionNumberString + if (version.startsWith("2.11.")) "" + else s" (since $v)" + } + /** pimps a string to compile it and apply the specified test */ implicit class CompileTests(val code: String) { private lazy val (success, output) = { @@ -48,6 +52,12 @@ trait TestHelpers extends DirectTest { assertEquals("should have right errors", expected.stripMargin.trim, output) } + def containsErrors(expected: String): Unit = { + assertFalse("snippet shouldn't compile", success) + assertTrue("should have right errors", + output.contains(expected.stripMargin.trim)) + } + def hasWarns(expected: String): Unit = { assertTrue("snippet should compile\n" + output, success) assertEquals("should have right warnings", expected.stripMargin.trim, output) diff --git a/compiler/src/test/scala/org/scalajs/nscplugin/test/util/VersionDependentUtils.scala b/compiler/src/test/scala/org/scalajs/nscplugin/test/util/VersionDependentUtils.scala new file mode 100644 index 0000000000..fe976ebe9e --- /dev/null +++ b/compiler/src/test/scala/org/scalajs/nscplugin/test/util/VersionDependentUtils.scala @@ -0,0 +1,39 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.nscplugin.test.util + +object VersionDependentUtils { + val scalaVersion = scala.util.Properties.versionNumberString + + /** Does the current Scala version support the `@nowarn` annotation? */ + val scalaSupportsNoWarn = { + !scalaVersion.startsWith("2.11.") && + !scalaVersion.startsWith("2.12.") && + scalaVersion != "2.13.0" && + scalaVersion != "2.13.1" + } + + private val usesColonInMethodSig = { + /* Yes, this is the same test as in scalaSupportsNoWarn, but that's + * completely coincidental, so we have a copy. + */ + !scalaVersion.startsWith("2.11.") && + !scalaVersion.startsWith("2.12.") && + scalaVersion != "2.13.0" && + scalaVersion != "2.13.1" + } + + def methodSig(params: String, resultType: String): String = + if (usesColonInMethodSig) params + ": " + resultType + else params + resultType +} diff --git a/examples/helloworld/helloworld-2.10-fastopt.html b/examples/helloworld/helloworld-2.10-fastopt.html deleted file mode 100644 index b8b413f796..0000000000 --- a/examples/helloworld/helloworld-2.10-fastopt.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - Hello world - Scala.js example - - - - -
-
- - - - - - - diff --git a/examples/helloworld/helloworld-2.10.html b/examples/helloworld/helloworld-2.10.html deleted file mode 100644 index ae117a00f6..0000000000 --- a/examples/helloworld/helloworld-2.10.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - Hello world - Scala.js example - - - - -
-
- - - - - - - diff --git a/examples/helloworld/helloworld-2.11-fastopt.html b/examples/helloworld/helloworld-2.11-fastopt.html index 7b30469669..8f7eceddd9 100644 --- a/examples/helloworld/helloworld-2.11-fastopt.html +++ b/examples/helloworld/helloworld-2.11-fastopt.html @@ -11,7 +11,7 @@ - + diff --git a/examples/helloworld/helloworld-2.11.html b/examples/helloworld/helloworld-2.11.html index eb9d7cfd40..ad39b7a9fe 100644 --- a/examples/helloworld/helloworld-2.11.html +++ b/examples/helloworld/helloworld-2.11.html @@ -11,7 +11,7 @@ - + diff --git a/examples/helloworld/helloworld-2.12-fastopt.html b/examples/helloworld/helloworld-2.12-fastopt.html new file mode 100644 index 0000000000..922690d7ac --- /dev/null +++ b/examples/helloworld/helloworld-2.12-fastopt.html @@ -0,0 +1,17 @@ + + + + Hello world - Scala.js example + + + + +
+
+ + + + + + + diff --git a/examples/helloworld/helloworld-2.12.html b/examples/helloworld/helloworld-2.12.html new file mode 100644 index 0000000000..a970c0c7bd --- /dev/null +++ b/examples/helloworld/helloworld-2.12.html @@ -0,0 +1,17 @@ + + + + Hello world - Scala.js example + + + + +
+
+ + + + + + + diff --git a/examples/helloworld/HelloWorld.scala b/examples/helloworld/src/main/scala/helloworld/HelloWorld.scala similarity index 93% rename from examples/helloworld/HelloWorld.scala rename to examples/helloworld/src/main/scala/helloworld/HelloWorld.scala index a79919685c..e27530ddcb 100644 --- a/examples/helloworld/HelloWorld.scala +++ b/examples/helloworld/src/main/scala/helloworld/HelloWorld.scala @@ -8,11 +8,12 @@ package helloworld import scala.scalajs.js import js.annotation._ -object HelloWorld extends js.JSApp { - def main(): Unit = { +object HelloWorld { + def main(args: Array[String]): Unit = { import js.DynamicImplicits.truthValue - if (js.Dynamic.global.document && + if (js.typeOf(js.Dynamic.global.document) != "undefined" && + js.Dynamic.global.document && js.Dynamic.global.document.getElementById("playground")) { sayHelloFromDOM() sayHelloFromTypedDOM() diff --git a/examples/reversi/reversi-2.10-fastopt.html b/examples/reversi/reversi-2.10-fastopt.html deleted file mode 100644 index 46cd1c7784..0000000000 --- a/examples/reversi/reversi-2.10-fastopt.html +++ /dev/null @@ -1,30 +0,0 @@ - - - - Reversi - Scala.js example - - - - -

Reversi - Scala.js example

- -

Somewhat inspired by -http://davidbau.com/reversi/

- -
-
- - - - - - - - - diff --git a/examples/reversi/reversi-2.10.html b/examples/reversi/reversi-2.10.html deleted file mode 100644 index 5f7b69602d..0000000000 --- a/examples/reversi/reversi-2.10.html +++ /dev/null @@ -1,30 +0,0 @@ - - - - Reversi - Scala.js example - - - - -

Reversi - Scala.js example

- -

Somewhat inspired by -http://davidbau.com/reversi/

- -
-
- - - - - - - - - diff --git a/examples/reversi/reversi-2.11-fastopt.html b/examples/reversi/reversi-2.11-fastopt.html index 524e7165ab..0f60bc72c3 100644 --- a/examples/reversi/reversi-2.11-fastopt.html +++ b/examples/reversi/reversi-2.11-fastopt.html @@ -16,7 +16,7 @@

Reversi - Scala.js example

- + - + + + + + + + + diff --git a/examples/reversi/reversi-2.12.html b/examples/reversi/reversi-2.12.html new file mode 100644 index 0000000000..370cb2be17 --- /dev/null +++ b/examples/reversi/reversi-2.12.html @@ -0,0 +1,30 @@ + + + + Reversi - Scala.js example + + + + +

Reversi - Scala.js example

+ +

Somewhat inspired by +http://davidbau.com/reversi/

+ +
+
+ + + + + + + + + diff --git a/examples/reversi/JSTypes.scala b/examples/reversi/src/main/scala/reversi/JSTypes.scala similarity index 100% rename from examples/reversi/JSTypes.scala rename to examples/reversi/src/main/scala/reversi/JSTypes.scala diff --git a/examples/reversi/Reversi.scala b/examples/reversi/src/main/scala/reversi/Reversi.scala similarity index 95% rename from examples/reversi/Reversi.scala rename to examples/reversi/src/main/scala/reversi/Reversi.scala index 65757a273d..a869580512 100644 --- a/examples/reversi/Reversi.scala +++ b/examples/reversi/src/main/scala/reversi/Reversi.scala @@ -40,7 +40,7 @@ class Reversi(jQuery: JQueryStatic, playground: JQuery) { var onOwnerChange: (OptPlayer, OptPlayer) => Unit = (oldP, newP) => () - def owner = _owner + def owner: OptPlayer = _owner def owner_=(value: OptPlayer): Unit = { val previous = _owner if (value != previous) { @@ -49,7 +49,7 @@ class Reversi(jQuery: JQueryStatic, playground: JQuery) { } } - override def toString() = "Square("+x+", "+y+", "+owner+")" + override def toString(): String = "Square("+x+", "+y+", "+owner+")" } val board = Array.tabulate[Square](BoardSize, BoardSize)(new Square(_, _)) @@ -63,19 +63,19 @@ class Reversi(jQuery: JQueryStatic, playground: JQuery) { val status = createStatus() buildUI() - def createResetButton() = { + def createResetButton(): JQuery = { jQuery("", js.Dynamic.literal( `type` = "button", value = "Reset" )).click(() => reset()) } - def createPassButton() = { + def createPassButton(): JQuery = { jQuery("", js.Dynamic.literal( `type` = "button", value = "Pass" )).click(() => pass()) } - def createStatus() = { + def createStatus(): JQuery = { jQuery("") } @@ -86,7 +86,7 @@ class Reversi(jQuery: JQueryStatic, playground: JQuery) { val PawnRadiusPx = HalfSquareSizePx-4 val BoardSizePx = BoardSize*SquareSizePx + 3 - // Creat the board canvas + // Create the board canvas val boardCanvas = jQuery( "") val domCanvas = boardCanvas.get(0).asInstanceOf[HTMLCanvasElement] @@ -118,7 +118,7 @@ class Reversi(jQuery: JQueryStatic, playground: JQuery) { } } - // Draw squares now, and everytime they change ownership + // Draw squares now, and every time they change ownership for (square <- allSquares) { drawSquare(square) square.onOwnerChange = { (prevOwner, newOwner) => diff --git a/examples/testing/src/main/scala/ElementCreator.scala b/examples/testing/src/main/scala/ElementCreator.scala index 9d0d58d833..22cf43c752 100644 --- a/examples/testing/src/main/scala/ElementCreator.scala +++ b/examples/testing/src/main/scala/ElementCreator.scala @@ -2,7 +2,9 @@ import scala.scalajs.js import js.Dynamic.global object ElementCreator { - val jQ = global.jQuery - - def create(): js.Dynamic = jQ("body").append(jQ("

Test

")) + def create(): Unit = { + val h1 = global.document.createElement("h1") + h1.innerHTML = "Test" + global.document.body.appendChild(h1) + } } diff --git a/examples/testing/src/test/scala/CollectionTest.scala b/examples/testing/src/test/scala/CollectionTest.scala index 844ff82de6..0b692bac17 100644 --- a/examples/testing/src/test/scala/CollectionTest.scala +++ b/examples/testing/src/test/scala/CollectionTest.scala @@ -2,8 +2,7 @@ import org.junit.Test import org.junit.Assert._ class CollectionTest { - @Test - def array_map_and_filter_ints(): Unit = { + @Test def arrayMapAndFilterInts(): Unit = { val array = Array(5, 7, 2, 6, -30, 33, 66, 76, 75, 0) val result = array.filter(_.toInt % 3 != 0).map(x => x*x) assertArrayEquals(Array(25, 49, 4, 76*76), result) diff --git a/examples/testing/src/test/scala/DOMExistanceTest.scala b/examples/testing/src/test/scala/DOMExistanceTest.scala index 531fd5850d..0f4ab75593 100644 --- a/examples/testing/src/test/scala/DOMExistanceTest.scala +++ b/examples/testing/src/test/scala/DOMExistanceTest.scala @@ -6,31 +6,16 @@ import org.junit.Assert._ class DOMExistenceTest { - @Test - def should_initialize_document(): Unit = { + @Test def initializeDocument(): Unit = { assertFalse(js.isUndefined(global.document)) assertEquals("#document", global.document.nodeName) } - @Test - def should_initialize_document_body(): Unit = { + @Test def initializeDocumentBody(): Unit = { assertFalse(js.isUndefined(global.document.body)) } - @Test - def should_initialize_windod(): Unit = { + @Test def initializeWindow(): Unit = { assertFalse(js.isUndefined(global.window)) } - - @Test - def should_initialize_jQuery(): Unit = { - assertFalse(js.isUndefined(global.jQuery)) - assertFalse(js.isUndefined(global.window.jQuery)) - } - - @Test - def should_initialize_dollar(): Unit = { - assertFalse(js.isUndefined(global.$)) - assertFalse(js.isUndefined(global.window.$)) - } } diff --git a/examples/testing/src/test/scala/ElementCreatorTest.scala b/examples/testing/src/test/scala/ElementCreatorTest.scala index 4adda4b7d5..57007f2ea0 100644 --- a/examples/testing/src/test/scala/ElementCreatorTest.scala +++ b/examples/testing/src/test/scala/ElementCreatorTest.scala @@ -6,17 +6,12 @@ import org.junit.Assert._ class ElementCreatorTest { - @Test - def element_creator_create_an_element_in_body(): Unit = { - // create the element + @Test def elementCreatorCreateAnElementInBody(): Unit = { + // Create the element ElementCreator.create() - // jquery would make this easier, but I wanted to - // only use pure html in the test itself - val body = global.document.getElementsByTagName("body") - .asInstanceOf[js.Array[js.Dynamic]].head - - // the Scala.js DOM API would make this easier + // Test that it was correctly created + val body = global.document.body assertEquals("H1", body.lastChild.tagName.toString) assertEquals("Test", body.lastChild.innerHTML.toString) } diff --git a/examples/testing/src/test/scala/TestMain.scala b/examples/testing/src/test/scala/TestMain.scala deleted file mode 100644 index 4d5b0d8246..0000000000 --- a/examples/testing/src/test/scala/TestMain.scala +++ /dev/null @@ -1,8 +0,0 @@ -import scala.scalajs.js - -object TestMain extends js.JSApp { - def main(): Unit = { - // Use JS console to make sure this doesn't work on the JVM - js.Dynamic.global.console.log("Test main") - } -} diff --git a/ir/js/src/main/scala/org/scalajs/ir/SHA1.scala b/ir/js/src/main/scala/org/scalajs/ir/SHA1.scala new file mode 100644 index 0000000000..f5bec7fca6 --- /dev/null +++ b/ir/js/src/main/scala/org/scalajs/ir/SHA1.scala @@ -0,0 +1,245 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.ir + +import scala.scalajs.js.typedarray._ +import scala.scalajs.js.typedarray.DataViewExt._ + +/** An implementation of the SHA-1 algorithm for use in Hashers. + * + * Reference: https://en.wikipedia.org/wiki/SHA-1#SHA-1_pseudocode + * + * This implementation MUST NOT be used for any cryptographic purposes. It did + * not receive the care and attention required for security purposes. It is + * only meant as a best-effort hash for incremental linking. + */ +object SHA1 { + final class DigestBuilder { + /** The SHA-1 state. + * + * It is an array of 5 Ints, initialized with a specific initialization + * vector specified by SHA-1, but we represent it as 5 individual Ints, + * since we always access them with static indices. + */ + private var state0: Int = 0x67452301 + private var state1: Int = 0xefcdab89 + private var state2: Int = 0x98badcfe + private var state3: Int = 0x10325476 + private var state4: Int = 0xc3d2e1f0 + + /** The number of *bytes* integrated so far in the state. + * + * This is used for two purposes: + * + * - By taking `byteCount & 63`, we get the number of bytes already + * written in the current `buffer`, which has 64 bytes. + * - In the padding during `sha1Final`, where we have to write the total + * number of *bits* (i.e., `byteCount << 3`) integrated into the digest. + */ + private var byteCount: Long = 0L + + /** The buffer for one 64-byte chunk to integrate into the state. */ + private val buffer = new Int8Array(64) + + /** A view of the buffer for accessing data in big endian. */ + private val bufferView = new DataView(buffer.buffer) + + /** The temporary array of 32-bit integers used by `sha1Transform()`, + * called `W` in the SHA-1 algorithm. + * + * Even though it is only used inside `sha1Transform()`, we declare it + * here so that we don't have to allocate a new one every time. + */ + private val W = new Int32Array(80) + + // Public API + + def update(b: Byte): Unit = + sha1Update(Array(b), 0, 1) + + def update(b: Array[Byte]): Unit = + sha1Update(b, 0, b.length) + + def update(b: Array[Byte], off: Int, len: Int): Unit = { + if (off < 0 || len < 0 || off > b.length - len) + throw new IndexOutOfBoundsException() + + sha1Update(b, off, len) + } + + def updateUTF8String(str: UTF8String): Unit = + update(str.bytes) + + def finalizeDigest(): Array[Byte] = + sha1Final() + + // Private methods + + /** Hashes a single 512-bit block. + * + * This is the core of the algorithm. + */ + private def sha1Transform(): Unit = { + import java.lang.Integer.{rotateLeft => rol} + + // Local copies + val buffer = this.buffer + val bufferView = this.bufferView + val W = this.W + + /* Perform the initial expansion of `buffer` into 80 Ints. + * The first 16 Ints are read from the buffer in big endian. The rest is + * derived from previous values. + */ + for (i <- 0 until 16) + W(i) = bufferView.getInt32(i * 4) + for (i <- 16 until 80) + W(i) = rol(W(i - 3) ^ W(i - 8) ^ W(i - 14) ^ W(i - 16), 1) + + // Copy state to working vars + var a = state0 + var b = state1 + var c = state2 + var d = state3 + var e = state4 + + // Main loop + + @inline def performOneIteration(i: Int, fi: Int, Ki: Int): Unit = { + val temp = rol(a, 5) + fi + e + Ki + W(i) + e = d + d = c + c = rol(b, 30) + b = a + a = temp + } + + for (i <- 0 until 20) + performOneIteration(i, (b & c) | (~b & d), 0x5a827999) + for (i <- 20 until 40) + performOneIteration(i, b ^ c ^ d, 0x6ed9eba1) + for (i <- 40 until 60) + performOneIteration(i, (b & c) | (b & d) | (c & d), 0x8f1bbcdc) + for (i <- 60 until 80) + performOneIteration(i, b ^ c ^ d, 0xca62c1d6) + + // Add the working vars back into `state` + state0 += a + state1 += b + state2 += c + state3 += d + state4 += e + } + + private def sha1Update(data: Array[Byte], off: Int, len: Int): Unit = { + // Local copies + val buffer = this.buffer + + /* Update the byte count. + * We use `Integer.toUnsignedLong(len)` because `len` is known to be + * non-negative, and it's faster. It also results in a `hi` part which is + * a constant 0, which makes the `+` operation faster as well. + */ + val oldByteCount = byteCount + byteCount = oldByteCount + Integer.toUnsignedLong(len) + + /* Decompose `data` into 64-byte chunks, taking into account bytes that + * were previously stored in `buffer`. + */ + + var bufferPos = oldByteCount.toInt & 63 + var dataPos = off + val dataEnd = off + len + + @inline def bufferRem = 64 - bufferPos + + while (dataEnd - dataPos >= bufferRem) { + arraycopyToInt8Array(data, dataPos, buffer, bufferPos, bufferRem) + sha1Transform() + dataPos += bufferRem + bufferPos = 0 + } + + arraycopyToInt8Array(data, dataPos, buffer, bufferPos, dataEnd - dataPos) + } + + /** Add padding and return the message digest. */ + private def sha1Final(): Array[Byte] = { + // Local copies + val buffer = this.buffer + val bufferView = this.bufferView + + // Snapshot the final bit count, before padding + val finalByteCount = byteCount + val finalBitCount = finalByteCount << 3 + + /* The padding contains: + * + * - One bit '1' + * - '0' bits to pad, until + * - the `finalBitCount`, stored in 64-bit big-endian + * + * Converted to byte-size items, this means: + * + * - One byte '0x80' + * - '0x00' bytes to pad, until + * - the `finalBitCount`, stored in 8-byte big-endian + * + * Since the `buffer` is not full when we start, we can always write the + * byte '0x80'. After that, if there are still at least 8 bytes left, we + * can fit everything in the current 64-byte chunk. Otherwise, we have to + * write '0x00' to fill the current chunk, transform, and then start a + * new chunk. + */ + + var currentBufferPos = finalByteCount.toInt & 63 + + // 0x80 + buffer(currentBufferPos) = 0x80.toByte + currentBufferPos += 1 + + // Finish one chunk if we don't have enough space in the current one + if (currentBufferPos > 56) { + buffer.fill(0x00, currentBufferPos, 64) + sha1Transform() + currentBufferPos = 0 + } + + // Write 0x00 until position 56 (64 - 8) + buffer.fill(0, currentBufferPos, 56) + + // Write the final bit count in big-endian + bufferView.setInt64(56, finalBitCount) + + // Transform one last time + sha1Transform() + + /* Compute the result digest, which is the `state` stored in big-endian. + * We reuse our internal buffer, because we can. + */ + bufferView.setInt32(0, state0) + bufferView.setInt32(4, state1) + bufferView.setInt32(8, state2) + bufferView.setInt32(12, state3) + bufferView.setInt32(16, state4) + buffer.subarray(0, 20).toArray + } + + /** Like `System.arraycopy`, but the dest is an `Int8Array`. */ + private def arraycopyToInt8Array(src: Array[Byte], srcPos: Int, + dest: Int8Array, destPos: Int, len: Int): Unit = { + for (i <- 0 until len) + dest(destPos + i) = src(srcPos + i) + } + } +} diff --git a/ir/jvm/src/main/scala/org/scalajs/ir/SHA1.scala b/ir/jvm/src/main/scala/org/scalajs/ir/SHA1.scala new file mode 100644 index 0000000000..3c5415b38c --- /dev/null +++ b/ir/jvm/src/main/scala/org/scalajs/ir/SHA1.scala @@ -0,0 +1,37 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.ir + +import java.security.MessageDigest + +/** Wrapper around java.security.MessageDigest.getInstance("SHA-1") */ +object SHA1 { + final class DigestBuilder { + private val digest = MessageDigest.getInstance("SHA-1") + + def update(b: Byte): Unit = + digest.update(b) + + def update(b: Array[Byte]): Unit = + digest.update(b) + + def update(b: Array[Byte], off: Int, len: Int): Unit = + digest.update(b, off, len) + + def updateUTF8String(str: UTF8String): Unit = + update(str.bytes) + + def finalizeDigest(): Array[Byte] = + digest.digest() + } +} diff --git a/ir/src/main/scala/org/scalajs/core/ir/ClassKind.scala b/ir/shared/src/main/scala/org/scalajs/ir/ClassKind.scala similarity index 91% rename from ir/src/main/scala/org/scalajs/core/ir/ClassKind.scala rename to ir/shared/src/main/scala/org/scalajs/ir/ClassKind.scala index 514837ecec..5d6ca2587f 100644 --- a/ir/src/main/scala/org/scalajs/core/ir/ClassKind.scala +++ b/ir/shared/src/main/scala/org/scalajs/ir/ClassKind.scala @@ -10,7 +10,7 @@ * additional information regarding copyright ownership. */ -package org.scalajs.core.ir +package org.scalajs.ir import scala.annotation.switch @@ -27,6 +27,11 @@ sealed abstract class ClassKind { case _ => false } + def isNativeJSClass: Boolean = this match { + case NativeJSClass | NativeJSModuleClass => true + case _ => false + } + def isJSType: Boolean = this match { case AbstractJSType | JSClass | JSModuleClass | NativeJSClass | NativeJSModuleClass => @@ -40,7 +45,7 @@ sealed abstract class ClassKind { case _ => false } - def isAnyScalaJSDefinedClass: Boolean = this match { + def isAnyNonNativeClass: Boolean = this match { case Class | ModuleClass | JSClass | JSModuleClass => true case _ => false } diff --git a/ir/shared/src/main/scala/org/scalajs/ir/EntryPointsInfo.scala b/ir/shared/src/main/scala/org/scalajs/ir/EntryPointsInfo.scala new file mode 100644 index 0000000000..e0f6f239b8 --- /dev/null +++ b/ir/shared/src/main/scala/org/scalajs/ir/EntryPointsInfo.scala @@ -0,0 +1,37 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.ir + +import Names.ClassName +import Trees._ + +final class EntryPointsInfo( + val className: ClassName, + val hasEntryPoint: Boolean +) + +object EntryPointsInfo { + def forClassDef(classDef: ClassDef): EntryPointsInfo = { + val hasEntryPoint = { + classDef.topLevelExportDefs.nonEmpty || + classDef.memberDefs.exists { + case m: MethodDef => + m.flags.namespace == MemberNamespace.StaticConstructor && + m.methodName.isStaticInitializer + case _ => + false + } + } + new EntryPointsInfo(classDef.name.name, hasEntryPoint) + } +} diff --git a/ir/shared/src/main/scala/org/scalajs/ir/Hashers.scala b/ir/shared/src/main/scala/org/scalajs/ir/Hashers.scala new file mode 100644 index 0000000000..cba76e8b64 --- /dev/null +++ b/ir/shared/src/main/scala/org/scalajs/ir/Hashers.scala @@ -0,0 +1,722 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.ir + +import java.io.{DataOutputStream, OutputStream} +import java.util.Arrays + +import Names._ +import Trees._ +import Types._ +import Tags._ + +object Hashers { + + def hashMethodDef(methodDef: MethodDef): MethodDef = { + if (methodDef.hash.isDefined) methodDef + else { + val hasher = new TreeHasher() + val MethodDef(flags, name, originalName, args, resultType, body) = methodDef + + hasher.mixPos(methodDef.pos) + hasher.mixInt(MemberFlags.toBits(flags)) + hasher.mixMethodIdent(name) + hasher.mixOriginalName(originalName) + hasher.mixParamDefs(args) + hasher.mixType(resultType) + body.foreach(hasher.mixTree) + hasher.mixInt(OptimizerHints.toBits(methodDef.optimizerHints)) + + val hash = hasher.finalizeHash() + + MethodDef(flags, name, originalName, args, resultType, body)( + methodDef.optimizerHints, Some(hash))(methodDef.pos) + } + } + + def hashJSConstructorDef(ctorDef: JSConstructorDef): JSConstructorDef = { + if (ctorDef.hash.isDefined) { + ctorDef + } else { + val hasher = new TreeHasher() + val JSConstructorDef(flags, params, restParam, body) = ctorDef + + hasher.mixPos(ctorDef.pos) + hasher.mixInt(MemberFlags.toBits(flags)) + hasher.mixParamDefs(params) + restParam.foreach(hasher.mixParamDef(_)) + hasher.mixPos(body.pos) + hasher.mixTrees(body.allStats) + hasher.mixInt(OptimizerHints.toBits(ctorDef.optimizerHints)) + + val hash = hasher.finalizeHash() + + JSConstructorDef(flags, params, restParam, body)( + ctorDef.optimizerHints, Some(hash))(ctorDef.pos) + } + } + + def hashJSMethodDef(methodDef: JSMethodDef): JSMethodDef = { + if (methodDef.hash.isDefined) methodDef + else { + val hasher = new TreeHasher() + val JSMethodDef(flags, name, params, restParam, body) = methodDef + + hasher.mixPos(methodDef.pos) + hasher.mixInt(MemberFlags.toBits(flags)) + hasher.mixTree(name) + hasher.mixParamDefs(params) + restParam.foreach(hasher.mixParamDef(_)) + hasher.mixTree(body) + hasher.mixInt(OptimizerHints.toBits(methodDef.optimizerHints)) + + val hash = hasher.finalizeHash() + + JSMethodDef(flags, name, params, restParam, body)( + methodDef.optimizerHints, Some(hash))(methodDef.pos) + } + } + + /** Hash definitions from a ClassDef where applicable */ + def hashMemberDefs(memberDefs: List[MemberDef]): List[MemberDef] = memberDefs.map { + case methodDef: MethodDef => hashMethodDef(methodDef) + case ctorDef: JSConstructorDef => hashJSConstructorDef(ctorDef) + case methodDef: JSMethodDef => hashJSMethodDef(methodDef) + case otherDef => otherDef + } + + /** Hash the definitions in a ClassDef (where applicable) */ + def hashClassDef(classDef: ClassDef): ClassDef = { + import classDef._ + val newMemberDefs = hashMemberDefs(memberDefs) + ClassDef(name, originalName, kind, jsClassCaptures, superClass, interfaces, + jsSuperClass, jsNativeLoadSpec, newMemberDefs, topLevelExportDefs)( + optimizerHints) + } + + def hashesEqual(x: TreeHash, y: TreeHash): Boolean = + Arrays.equals(x.hash, y.hash) + + def hashAsVersion(hash: TreeHash): String = { + // 2 chars per byte, 20 bytes in a hash + val size = 2 * 20 + val builder = new StringBuilder(size) + + def hexDigit(digit: Int): Char = Character.forDigit(digit, 16) + + for (b <- hash.hash) + builder.append(hexDigit((b >> 4) & 0x0f)).append(hexDigit(b & 0x0f)) + + builder.toString + } + + private final class TreeHasher { + private[this] val digestBuilder = new SHA1.DigestBuilder + + private[this] val digestStream = { + new DataOutputStream(new OutputStream { + def write(b: Int): Unit = + digestBuilder.update(b.toByte) + + override def write(b: Array[Byte]): Unit = + digestBuilder.update(b) + + override def write(b: Array[Byte], off: Int, len: Int): Unit = + digestBuilder.update(b, off, len) + }) + } + + def finalizeHash(): TreeHash = + new TreeHash(digestBuilder.finalizeDigest()) + + def mixParamDef(paramDef: ParamDef): Unit = { + mixPos(paramDef.pos) + mixLocalIdent(paramDef.name) + mixOriginalName(paramDef.originalName) + mixType(paramDef.ptpe) + mixBoolean(paramDef.mutable) + } + + def mixParamDefs(paramDefs: List[ParamDef]): Unit = + paramDefs.foreach(mixParamDef) + + def mixTree(tree: Tree): Unit = { + mixPos(tree.pos) + tree match { + case VarDef(ident, originalName, vtpe, mutable, rhs) => + mixTag(TagVarDef) + mixLocalIdent(ident) + mixOriginalName(originalName) + mixType(vtpe) + mixBoolean(mutable) + mixTree(rhs) + + case Skip() => + mixTag(TagSkip) + + case Block(stats) => + mixTag(TagBlock) + mixTrees(stats) + + case Labeled(label, tpe, body) => + mixTag(TagLabeled) + mixLabelIdent(label) + mixType(tpe) + mixTree(body) + + case Assign(lhs, rhs) => + mixTag(TagAssign) + mixTree(lhs) + mixTree(rhs) + + case Return(expr, label) => + mixTag(TagReturn) + mixTree(expr) + mixLabelIdent(label) + + case If(cond, thenp, elsep) => + mixTag(TagIf) + mixTree(cond) + mixTree(thenp) + mixTree(elsep) + mixType(tree.tpe) + + case While(cond, body) => + mixTag(TagWhile) + mixTree(cond) + mixTree(body) + + case DoWhile(body, cond) => + mixTag(TagDoWhile) + mixTree(body) + mixTree(cond) + + case ForIn(obj, keyVar, keyVarOriginalName, body) => + mixTag(TagForIn) + mixTree(obj) + mixLocalIdent(keyVar) + mixOriginalName(keyVarOriginalName) + mixTree(body) + + case TryCatch(block, errVar, errVarOriginalName, handler) => + mixTag(TagTryCatch) + mixTree(block) + mixLocalIdent(errVar) + mixOriginalName(errVarOriginalName) + mixTree(handler) + mixType(tree.tpe) + + case TryFinally(block, finalizer) => + mixTag(TagTryFinally) + mixTree(block) + mixTree(finalizer) + mixType(tree.tpe) + + case Throw(expr) => + mixTag(TagThrow) + mixTree(expr) + + case Match(selector, cases, default) => + mixTag(TagMatch) + mixTree(selector) + cases foreach { case (patterns, body) => + mixTrees(patterns) + mixTree(body) + } + mixTree(default) + mixType(tree.tpe) + + case Debugger() => + mixTag(TagDebugger) + + case New(className, ctor, args) => + mixTag(TagNew) + mixName(className) + mixMethodIdent(ctor) + mixTrees(args) + + case LoadModule(className) => + mixTag(TagLoadModule) + mixName(className) + + case StoreModule(className, value) => + mixTag(TagStoreModule) + mixName(className) + mixTree(value) + + case Select(qualifier, className, field) => + mixTag(TagSelect) + mixTree(qualifier) + mixName(className) + mixFieldIdent(field) + mixType(tree.tpe) + + case SelectStatic(className, field) => + mixTag(TagSelectStatic) + mixName(className) + mixFieldIdent(field) + mixType(tree.tpe) + + case SelectJSNativeMember(className, member) => + mixTag(TagSelectJSNativeMember) + mixName(className) + mixMethodIdent(member) + + case Apply(flags, receiver, method, args) => + mixTag(TagApply) + mixInt(ApplyFlags.toBits(flags)) + mixTree(receiver) + mixMethodIdent(method) + mixTrees(args) + mixType(tree.tpe) + + case ApplyStatically(flags, receiver, className, method, args) => + mixTag(TagApplyStatically) + mixInt(ApplyFlags.toBits(flags)) + mixTree(receiver) + mixName(className) + mixMethodIdent(method) + mixTrees(args) + mixType(tree.tpe) + + case ApplyStatic(flags, className, method, args) => + mixTag(TagApplyStatic) + mixInt(ApplyFlags.toBits(flags)) + mixName(className) + mixMethodIdent(method) + mixTrees(args) + mixType(tree.tpe) + + case ApplyDynamicImport(flags, className, method, args) => + mixTag(TagApplyDynamicImport) + mixInt(ApplyFlags.toBits(flags)) + mixName(className) + mixMethodIdent(method) + mixTrees(args) + + case UnaryOp(op, lhs) => + mixTag(TagUnaryOp) + mixInt(op) + mixTree(lhs) + + case BinaryOp(op, lhs, rhs) => + mixTag(TagBinaryOp) + mixInt(op) + mixTree(lhs) + mixTree(rhs) + + case NewArray(typeRef, lengths) => + mixTag(TagNewArray) + mixArrayTypeRef(typeRef) + mixTrees(lengths) + + case ArrayValue(typeRef, elems) => + mixTag(TagArrayValue) + mixArrayTypeRef(typeRef) + mixTrees(elems) + + case ArrayLength(array) => + mixTag(TagArrayLength) + mixTree(array) + + case ArraySelect(array, index) => + mixTag(TagArraySelect) + mixTree(array) + mixTree(index) + mixType(tree.tpe) + + case RecordValue(tpe, elems) => + mixTag(TagRecordValue) + mixType(tpe) + mixTrees(elems) + + case RecordSelect(record, field) => + mixTag(TagRecordSelect) + mixTree(record) + mixFieldIdent(field) + mixType(tree.tpe) + + case IsInstanceOf(expr, testType) => + mixTag(TagIsInstanceOf) + mixTree(expr) + mixType(testType) + + case AsInstanceOf(expr, tpe) => + mixTag(TagAsInstanceOf) + mixTree(expr) + mixType(tpe) + + case GetClass(expr) => + mixTag(TagGetClass) + mixTree(expr) + + case Clone(expr) => + mixTag(TagClone) + mixTree(expr) + + case IdentityHashCode(expr) => + mixTag(TagIdentityHashCode) + mixTree(expr) + + case WrapAsThrowable(expr) => + mixTag(TagWrapAsThrowable) + mixTree(expr) + + case UnwrapFromThrowable(expr) => + mixTag(TagUnwrapFromThrowable) + mixTree(expr) + + case JSNew(ctor, args) => + mixTag(TagJSNew) + mixTree(ctor) + mixTreeOrJSSpreads(args) + + case JSPrivateSelect(qualifier, className, field) => + mixTag(TagJSPrivateSelect) + mixTree(qualifier) + mixName(className) + mixFieldIdent(field) + + case JSSelect(qualifier, item) => + mixTag(TagJSSelect) + mixTree(qualifier) + mixTree(item) + + case JSFunctionApply(fun, args) => + mixTag(TagJSFunctionApply) + mixTree(fun) + mixTreeOrJSSpreads(args) + + case JSMethodApply(receiver, method, args) => + mixTag(TagJSMethodApply) + mixTree(receiver) + mixTree(method) + mixTreeOrJSSpreads(args) + + case JSSuperSelect(superClass, qualifier, item) => + mixTag(TagJSSuperSelect) + mixTree(superClass) + mixTree(qualifier) + mixTree(item) + + case JSSuperMethodCall(superClass, receiver, method, args) => + mixTag(TagJSSuperMethodCall) + mixTree(superClass) + mixTree(receiver) + mixTree(method) + mixTreeOrJSSpreads(args) + + case JSSuperConstructorCall(args) => + mixTag(TagJSSuperConstructorCall) + mixTreeOrJSSpreads(args) + + case JSImportCall(arg) => + mixTag(TagJSImportCall) + mixTree(arg) + + case JSNewTarget() => + mixTag(TagJSNewTarget) + + case JSImportMeta() => + mixTag(TagJSImportMeta) + + case LoadJSConstructor(className) => + mixTag(TagLoadJSConstructor) + mixName(className) + + case LoadJSModule(className) => + mixTag(TagLoadJSModule) + mixName(className) + + case JSDelete(qualifier, item) => + mixTag(TagJSDelete) + mixTree(qualifier) + mixTree(item) + + case JSUnaryOp(op, lhs) => + mixTag(TagJSUnaryOp) + mixInt(op) + mixTree(lhs) + + case JSBinaryOp(op, lhs, rhs) => + mixTag(TagJSBinaryOp) + mixInt(op) + mixTree(lhs) + mixTree(rhs) + + case JSArrayConstr(items) => + mixTag(TagJSArrayConstr) + mixTreeOrJSSpreads(items) + + case JSObjectConstr(fields) => + mixTag(TagJSObjectConstr) + fields.foreach { case (key, value) => + mixTree(key) + mixTree(value) + } + + case JSGlobalRef(name) => + mixTag(TagJSGlobalRef) + mixString(name) + + case JSTypeOfGlobalRef(globalRef) => + mixTag(TagJSTypeOfGlobalRef) + mixTree(globalRef) + + case JSLinkingInfo() => + mixTag(TagJSLinkingInfo) + + case Undefined() => + mixTag(TagUndefined) + + case Null() => + mixTag(TagNull) + + case BooleanLiteral(value) => + mixTag(TagBooleanLiteral) + mixBoolean(value) + + case CharLiteral(value) => + mixTag(TagCharLiteral) + mixChar(value) + + case ByteLiteral(value) => + mixTag(TagByteLiteral) + mixByte(value) + + case ShortLiteral(value) => + mixTag(TagShortLiteral) + mixShort(value) + + case IntLiteral(value) => + mixTag(TagIntLiteral) + mixInt(value) + + case LongLiteral(value) => + mixTag(TagLongLiteral) + mixLong(value) + + case FloatLiteral(value) => + mixTag(TagFloatLiteral) + mixFloat(value) + + case DoubleLiteral(value) => + mixTag(TagDoubleLiteral) + mixDouble(value) + + case StringLiteral(value) => + mixTag(TagStringLiteral) + mixString(value) + + case ClassOf(typeRef) => + mixTag(TagClassOf) + mixTypeRef(typeRef) + + case VarRef(ident) => + mixTag(TagVarRef) + mixLocalIdent(ident) + mixType(tree.tpe) + + case This() => + mixTag(TagThis) + mixType(tree.tpe) + + case Closure(arrow, captureParams, params, restParam, body, captureValues) => + mixTag(TagClosure) + mixBoolean(arrow) + mixParamDefs(captureParams) + mixParamDefs(params) + restParam.foreach(mixParamDef(_)) + mixTree(body) + mixTrees(captureValues) + + case CreateJSClass(className, captureValues) => + mixTag(TagCreateJSClass) + mixName(className) + mixTrees(captureValues) + + case Transient(value) => + throw new InvalidIRException(tree, + "Cannot hash a transient IR node (its value is of class " + + s"${value.getClass})") + } + } + + def mixOptTree(optTree: Option[Tree]): Unit = + optTree.foreach(mixTree) + + def mixTrees(trees: List[Tree]): Unit = + trees.foreach(mixTree) + + def mixTreeOrJSSpreads(trees: List[TreeOrJSSpread]): Unit = + trees.foreach(mixTreeOrJSSpread) + + def mixTreeOrJSSpread(tree: TreeOrJSSpread): Unit = { + tree match { + case JSSpread(items) => + mixTag(TagJSSpread) + mixTree(items) + case tree: Tree => + mixTree(tree) + } + } + + def mixTypeRef(typeRef: TypeRef): Unit = typeRef match { + case PrimRef(tpe) => + tpe match { + case NoType => mixTag(TagVoidRef) + case BooleanType => mixTag(TagBooleanRef) + case CharType => mixTag(TagCharRef) + case ByteType => mixTag(TagByteRef) + case ShortType => mixTag(TagShortRef) + case IntType => mixTag(TagIntRef) + case LongType => mixTag(TagLongRef) + case FloatType => mixTag(TagFloatRef) + case DoubleType => mixTag(TagDoubleRef) + case NullType => mixTag(TagNullRef) + case NothingType => mixTag(TagNothingRef) + } + case ClassRef(className) => + mixTag(TagClassRef) + mixName(className) + case typeRef: ArrayTypeRef => + mixTag(TagArrayTypeRef) + mixArrayTypeRef(typeRef) + } + + def mixArrayTypeRef(arrayTypeRef: ArrayTypeRef): Unit = { + mixTypeRef(arrayTypeRef.base) + mixInt(arrayTypeRef.dimensions) + } + + def mixType(tpe: Type): Unit = tpe match { + case AnyType => mixTag(TagAnyType) + case NothingType => mixTag(TagNothingType) + case UndefType => mixTag(TagUndefType) + case BooleanType => mixTag(TagBooleanType) + case CharType => mixTag(TagCharType) + case ByteType => mixTag(TagByteType) + case ShortType => mixTag(TagShortType) + case IntType => mixTag(TagIntType) + case LongType => mixTag(TagLongType) + case FloatType => mixTag(TagFloatType) + case DoubleType => mixTag(TagDoubleType) + case StringType => mixTag(TagStringType) + case NullType => mixTag(TagNullType) + case NoType => mixTag(TagNoType) + + case ClassType(className) => + mixTag(TagClassType) + mixName(className) + + case ArrayType(arrayTypeRef) => + mixTag(TagArrayType) + mixArrayTypeRef(arrayTypeRef) + + case RecordType(fields) => + mixTag(TagRecordType) + for (RecordType.Field(name, originalName, tpe, mutable) <- fields) { + mixName(name) + mixOriginalName(originalName) + mixType(tpe) + mixBoolean(mutable) + } + } + + def mixLocalIdent(ident: LocalIdent): Unit = { + mixPos(ident.pos) + mixName(ident.name) + } + + def mixLabelIdent(ident: LabelIdent): Unit = { + mixPos(ident.pos) + mixName(ident.name) + } + + def mixFieldIdent(ident: FieldIdent): Unit = { + mixPos(ident.pos) + mixName(ident.name) + } + + def mixMethodIdent(ident: MethodIdent): Unit = { + mixPos(ident.pos) + mixMethodName(ident.name) + } + + def mixClassIdent(ident: ClassIdent): Unit = { + mixPos(ident.pos) + mixName(ident.name) + } + + def mixName(name: Name): Unit = + mixBytes(name.encoded.bytes) + + def mixMethodName(name: MethodName): Unit = { + mixName(name.simpleName) + mixInt(name.paramTypeRefs.size) + for (typeRef <- name.paramTypeRefs) + mixTypeRef(typeRef) + mixTypeRef(name.resultTypeRef) + mixBoolean(name.isReflectiveProxy) + } + + def mixOriginalName(originalName: OriginalName): Unit = { + mixBoolean(originalName.isDefined) + if (originalName.isDefined) + mixBytes(originalName.get.bytes) + } + + private def mixBytes(bytes: Array[Byte]): Unit = { + digestStream.writeInt(bytes.length) + digestStream.write(bytes) + } + + def mixPos(pos: Position): Unit = { + digestStream.writeUTF(pos.source.toString) + digestStream.writeInt(pos.line) + digestStream.writeInt(pos.column) + } + + @inline + final def mixTag(tag: Int): Unit = mixInt(tag) + + @inline + final def mixString(str: String): Unit = digestStream.writeUTF(str) + + @inline + final def mixChar(c: Char): Unit = digestStream.writeChar(c) + + @inline + final def mixByte(b: Byte): Unit = digestStream.writeByte(b) + + @inline + final def mixShort(s: Short): Unit = digestStream.writeShort(s) + + @inline + final def mixInt(i: Int): Unit = digestStream.writeInt(i) + + @inline + final def mixLong(l: Long): Unit = digestStream.writeLong(l) + + @inline + final def mixBoolean(b: Boolean): Unit = digestStream.writeBoolean(b) + + @inline + final def mixFloat(f: Float): Unit = digestStream.writeFloat(f) + + @inline + final def mixDouble(d: Double): Unit = digestStream.writeDouble(d) + + } + +} diff --git a/ir/shared/src/main/scala/org/scalajs/ir/IRVersionNotSupportedException.scala b/ir/shared/src/main/scala/org/scalajs/ir/IRVersionNotSupportedException.scala new file mode 100644 index 0000000000..996afa9413 --- /dev/null +++ b/ir/shared/src/main/scala/org/scalajs/ir/IRVersionNotSupportedException.scala @@ -0,0 +1,25 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.ir + +import java.io.IOException + +class IRVersionNotSupportedException(val version: String, + val supported: String, message: String) extends IOException(message) { + + def this(version: String, supported: String, message: String, + exception: Exception) = { + this(version, supported, message) + initCause(exception) + } +} diff --git a/ir/src/main/scala/org/scalajs/core/ir/InvalidIRException.scala b/ir/shared/src/main/scala/org/scalajs/ir/InvalidIRException.scala similarity index 76% rename from ir/src/main/scala/org/scalajs/core/ir/InvalidIRException.scala rename to ir/shared/src/main/scala/org/scalajs/ir/InvalidIRException.scala index 4c210f4cc5..f481798458 100644 --- a/ir/src/main/scala/org/scalajs/core/ir/InvalidIRException.scala +++ b/ir/shared/src/main/scala/org/scalajs/ir/InvalidIRException.scala @@ -10,7 +10,7 @@ * additional information regarding copyright ownership. */ -package org.scalajs.core.ir +package org.scalajs.ir -class InvalidIRException(val tree: Trees.Tree, message: String) +class InvalidIRException(val tree: Trees.IRNode, message: String) extends Exception(message) diff --git a/ir/shared/src/main/scala/org/scalajs/ir/Names.scala b/ir/shared/src/main/scala/org/scalajs/ir/Names.scala new file mode 100644 index 0000000000..a3233877c3 --- /dev/null +++ b/ir/shared/src/main/scala/org/scalajs/ir/Names.scala @@ -0,0 +1,607 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.ir + +import scala.annotation.switch + +import Types._ + +object Names { + private final val ConstructorSimpleEncodedName: UTF8String = + UTF8String("") + + private final val StaticInitializerSimpleEncodedName: UTF8String = + UTF8String("") + + private final val ClassInitializerSimpleEncodedName: UTF8String = + UTF8String("") + + // scalastyle:off equals.hash.code + // we define hashCode() once in Name, but equals() separately in its subclasses + + sealed abstract class Name(val encoded: UTF8String) { + type ThisName <: Name + + // Eagerly compute the hash code + private val _hashCode = UTF8String.hashCode(encoded) + + override def hashCode(): Int = _hashCode + + protected final def equalsName(that: ThisName): Boolean = { + this._hashCode == that._hashCode && // fail fast on different hash codes + UTF8String.equals(this.encoded, that.encoded) + } + + def compareTo(that: ThisName): Int = { + // scalastyle:off return + val thisEncoded = this.encoded + val thatEncoded = that.encoded + val thisEncodedLen = thisEncoded.length + val thatEncodedLen = thatEncoded.length + val minLen = Math.min(thisEncodedLen, thatEncodedLen) + var i = 0 + while (i != minLen) { + val cmp = java.lang.Byte.compare(thisEncoded(i), thatEncoded(i)) + if (cmp != 0) + return cmp + i += 1 + } + Integer.compare(thisEncodedLen, thatEncodedLen) + // scalastyle:on return + } + + protected def stringPrefix: String + + final def nameString: String = + encoded.toString() + + override def toString(): String = + stringPrefix + "<" + nameString + ">" + } + + /** The name of a local variable or capture parameter. + * + * Local names must be non-empty, and can contain any Unicode code point + * except `/ . ; [`. + */ + final class LocalName private (encoded: UTF8String) + extends Name(encoded) with Comparable[LocalName] { + + type ThisName = LocalName + + override def equals(that: Any): Boolean = { + (this eq that.asInstanceOf[AnyRef]) || (that match { + case that: LocalName => equalsName(that) + case _ => false + }) + } + + protected def stringPrefix: String = "LocalName" + + final def withPrefix(prefix: LocalName): LocalName = + new LocalName(prefix.encoded ++ this.encoded) + + final def withPrefix(prefix: String): LocalName = + LocalName(UTF8String(prefix) ++ this.encoded) + + final def withSuffix(suffix: LocalName): LocalName = + new LocalName(this.encoded ++ suffix.encoded) + + final def withSuffix(suffix: String): LocalName = + LocalName(this.encoded ++ UTF8String(suffix)) + } + + object LocalName { + def apply(name: UTF8String): LocalName = + new LocalName(validateSimpleEncodedName(name)) + + def apply(name: String): LocalName = + LocalName(UTF8String(name)) + + private[Names] def fromFieldName(name: FieldName): LocalName = + new LocalName(name.encoded) + } + + /** The name of the label of a `Labeled` block. + * + * Label names must be non-empty, and can contain any Unicode code point + * except `/ . ; [`. + */ + final class LabelName private (encoded: UTF8String) + extends Name(encoded) with Comparable[LabelName] { + + type ThisName = LabelName + + override def equals(that: Any): Boolean = { + (this eq that.asInstanceOf[AnyRef]) || (that match { + case that: LabelName => equalsName(that) + case _ => false + }) + } + + protected def stringPrefix: String = "LabelName" + + final def withSuffix(suffix: LabelName): LabelName = + new LabelName(this.encoded ++ suffix.encoded) + + final def withSuffix(suffix: String): LabelName = + LabelName(this.encoded ++ UTF8String(suffix)) + } + + object LabelName { + def apply(name: UTF8String): LabelName = + new LabelName(validateSimpleEncodedName(name)) + + def apply(name: String): LabelName = + LabelName(UTF8String(name)) + } + + /** The name of a field. + * + * Field names must be non-empty, and can contain any Unicode code point + * except `/ . ; [`. + */ + final class FieldName private (encoded: UTF8String) + extends Name(encoded) with Comparable[FieldName] { + + type ThisName = FieldName + + override def equals(that: Any): Boolean = { + (this eq that.asInstanceOf[AnyRef]) || (that match { + case that: FieldName => equalsName(that) + case _ => false + }) + } + + protected def stringPrefix: String = "FieldName" + + final def withSuffix(suffix: String): FieldName = + FieldName(this.encoded ++ UTF8String(suffix)) + + final def toLocalName: LocalName = + LocalName.fromFieldName(this) + } + + object FieldName { + def apply(name: UTF8String): FieldName = + new FieldName(validateSimpleEncodedName(name)) + + def apply(name: String): FieldName = + FieldName(UTF8String(name)) + } + + /** The simple name of a method (excluding its signature). + * + * Simple names must be non-empty, and can contain any Unicode code point + * except `/ . ; [`. In addition, they must not contain the code point `<` + * unless they are one of ``, `` or ``. + */ + final class SimpleMethodName private (encoded: UTF8String) + extends Name(encoded) with Comparable[SimpleMethodName] { + + type ThisName = SimpleMethodName + + override def equals(that: Any): Boolean = { + (this eq that.asInstanceOf[AnyRef]) || (that match { + case that: SimpleMethodName => equalsName(that) + case _ => false + }) + } + + protected def stringPrefix: String = "SimpleMethodName" + + /** Returns `true` iff this is the name of an instance constructor. */ + def isConstructor: Boolean = + this eq SimpleMethodName.Constructor // globally unique, so `eq` is fine + + /** Returns `true` iff this is the name of a static initializer. */ + def isStaticInitializer: Boolean = + this eq SimpleMethodName.StaticInitializer // globally unique, so `eq` is fine + + /** Returns `true` iff this is the name of a class initializer. */ + def isClassInitializer: Boolean = + this eq SimpleMethodName.ClassInitializer // globally unique, so `eq` is fine + } + + object SimpleMethodName { + /** The unique `SimpleMethodName` with encoded name ``. */ + private val Constructor: SimpleMethodName = + new SimpleMethodName(ConstructorSimpleEncodedName) + + /** The unique `SimpleMethodName` with encoded name ``. */ + private val StaticInitializer: SimpleMethodName = + new SimpleMethodName(StaticInitializerSimpleEncodedName) + + /** The unique `SimpleMethodName` with encoded name ``. */ + private val ClassInitializer: SimpleMethodName = + new SimpleMethodName(ClassInitializerSimpleEncodedName) + + def apply(name: UTF8String): SimpleMethodName = { + val len = name.length + if (len == 0) + throwInvalidEncodedName(name) + + /* Handle constructor names and static initializer names. When we find + * those, we normalize the returned instance to be one of the unique + * instances, ensuring that they remain globally unique. + */ + if (name(0) == '<') { + // Must be one of '', '' or '' + len match { + case 6 if UTF8String.equals(name, ConstructorSimpleEncodedName) => + Constructor + case 8 if UTF8String.equals(name, StaticInitializerSimpleEncodedName) => + StaticInitializer + case 8 if UTF8String.equals(name, ClassInitializerSimpleEncodedName) => + ClassInitializer + case _ => + throwInvalidEncodedName(name) + } + } else { + // Normal method name + new SimpleMethodName( + validateSimpleEncodedName(name, 0, len, openAngleBracketOK = false)) + } + } + + def apply(name: String): SimpleMethodName = + SimpleMethodName(UTF8String(name)) + } + + val ConstructorSimpleName: SimpleMethodName = + SimpleMethodName(ConstructorSimpleEncodedName) + + val StaticInitializerSimpleName: SimpleMethodName = + SimpleMethodName(StaticInitializerSimpleEncodedName) + + val ClassInitializerSimpleName: SimpleMethodName = + SimpleMethodName(ClassInitializerSimpleEncodedName) + + /** The full name of a method, including its simple name and its signature. + */ + final class MethodName private (val simpleName: SimpleMethodName, + val paramTypeRefs: List[TypeRef], val resultTypeRef: TypeRef, + val isReflectiveProxy: Boolean) { + + import MethodName._ + + private val _hashCode: Int = { + import scala.util.hashing.MurmurHash3._ + var acc = 1270301484 // "MethodName".hashCode() + acc = mix(acc, simpleName.##) + acc = mix(acc, paramTypeRefs.##) + acc = mix(acc, resultTypeRef.##) + acc = mixLast(acc, isReflectiveProxy.##) + finalizeHash(acc, 4) + } + + override def equals(that: Any): Boolean = { + (this eq that.asInstanceOf[AnyRef]) || (that match { + case that: MethodName => + this._hashCode == that._hashCode && // fail fast on different hash codes + this.simpleName == that.simpleName && + this.paramTypeRefs == that.paramTypeRefs && + this.resultTypeRef == that.resultTypeRef && + this.isReflectiveProxy == that.isReflectiveProxy + case _ => + false + }) + } + + override def hashCode(): Int = _hashCode + + protected def stringPrefix: String = "MethodName" + + def nameString: String = { + val builder = new java.lang.StringBuilder + + def appendTypeRef(typeRef: TypeRef): Unit = typeRef match { + case PrimRef(tpe) => + tpe match { + case NoType => builder.append('V') + case BooleanType => builder.append('Z') + case CharType => builder.append('C') + case ByteType => builder.append('B') + case ShortType => builder.append('S') + case IntType => builder.append('I') + case LongType => builder.append('J') + case FloatType => builder.append('F') + case DoubleType => builder.append('D') + case NullType => builder.append('N') + case NothingType => builder.append('E') + } + case ClassRef(className) => + builder.append('L').append(className.nameString) + case ArrayTypeRef(base, dimensions) => + var i = 0 + while (i != dimensions) { + builder.append('[') + i += 1 + } + appendTypeRef(base) + } + + builder.append(simpleName.nameString) + for (paramTypeRef <- paramTypeRefs) { + builder.append(';') + appendTypeRef(paramTypeRef) + } + builder.append(';') + if (isReflectiveProxy) + builder.append('R') + else + appendTypeRef(resultTypeRef) + builder.toString() + } + + override def toString(): String = + "MethodName<" + nameString + ">" + + def displayName: String = { + simpleName.nameString + "(" + + paramTypeRefs.map(_.displayName).mkString(",") + ")" + + (if (isReflectiveProxy) "R" else resultTypeRef.displayName) + } + + /** Returns `true` iff this is the name of an instance constructor. */ + def isConstructor: Boolean = simpleName.isConstructor + + /** Returns `true` iff this is the name of a static initializer. */ + def isStaticInitializer: Boolean = simpleName.isStaticInitializer + + /** Returns `true` iff this is the name of a class initializer. */ + def isClassInitializer: Boolean = simpleName.isClassInitializer + } + + object MethodName { + private val ReflectiveProxyResultTypeRef = ClassRef(ObjectClass) + private final val ReflectiveProxyResultTypeName = "java.lang.Object" + + def apply(simpleName: SimpleMethodName, paramTypeRefs: List[TypeRef], + resultTypeRef: TypeRef, isReflectiveProxy: Boolean): MethodName = { + if ((simpleName.isConstructor || simpleName.isStaticInitializer || + simpleName.isClassInitializer) && resultTypeRef != VoidRef) { + throw new IllegalArgumentException( + "A constructor or static initializer must have a void result type") + } + if (isReflectiveProxy && resultTypeRef != ReflectiveProxyResultTypeRef) { + throw new IllegalArgumentException( + "A reflective proxy must have a result type of " + + ReflectiveProxyResultTypeName) + } + new MethodName(simpleName, paramTypeRefs, resultTypeRef, + isReflectiveProxy) + } + + // Convenience constructors + + def apply(simpleName: SimpleMethodName, paramTypeRefs: List[TypeRef], + resultTypeRef: TypeRef): MethodName = { + apply(simpleName, paramTypeRefs, resultTypeRef, isReflectiveProxy = false) + } + + def apply(simpleName: String, paramTypeRefs: List[TypeRef], + resultTypeRef: TypeRef): MethodName = { + apply(SimpleMethodName(simpleName), paramTypeRefs, resultTypeRef) + } + + def constructor(paramTypeRefs: List[TypeRef]): MethodName = { + new MethodName(ConstructorSimpleName, paramTypeRefs, VoidRef, + isReflectiveProxy = false) + } + + def reflectiveProxy(simpleName: SimpleMethodName, + paramTypeRefs: List[TypeRef]): MethodName = { + apply(simpleName, paramTypeRefs, ReflectiveProxyResultTypeRef, + isReflectiveProxy = true) + } + + def reflectiveProxy(simpleName: String, + paramTypeRefs: List[TypeRef]): MethodName = { + reflectiveProxy(SimpleMethodName(simpleName), paramTypeRefs) + } + } + + /** The full name of a class. + * + * A class name is non-empty sequence of `.`-separated simple names, where + * each simple name must be non-empty and can contain any Unicode code + * point except `/ . ; [`. + */ + final class ClassName private (encoded: UTF8String) + extends Name(encoded) with Comparable[ClassName] { + + type ThisName = ClassName + + override def equals(that: Any): Boolean = { + (this eq that.asInstanceOf[AnyRef]) || (that match { + case that: ClassName => equalsName(that) + case _ => false + }) + } + + protected def stringPrefix: String = "ClassName" + + def withSuffix(suffix: String): ClassName = + ClassName(encoded ++ UTF8String(suffix)) + } + + object ClassName { + def apply(name: UTF8String): ClassName = + new ClassName(validateEncodedClassName(name)) + + def apply(name: String): ClassName = + ClassName(UTF8String(name)) + } + + // scalastyle:on equals.hash.code + + /** `java.lang.Object`, the root of the class hierarchy. */ + val ObjectClass: ClassName = ClassName("java.lang.Object") + + // Hijacked classes + val BoxedUnitClass: ClassName = ClassName("java.lang.Void") + val BoxedBooleanClass: ClassName = ClassName("java.lang.Boolean") + val BoxedCharacterClass: ClassName = ClassName("java.lang.Character") + val BoxedByteClass: ClassName = ClassName("java.lang.Byte") + val BoxedShortClass: ClassName = ClassName("java.lang.Short") + val BoxedIntegerClass: ClassName = ClassName("java.lang.Integer") + val BoxedLongClass: ClassName = ClassName("java.lang.Long") + val BoxedFloatClass: ClassName = ClassName("java.lang.Float") + val BoxedDoubleClass: ClassName = ClassName("java.lang.Double") + val BoxedStringClass: ClassName = ClassName("java.lang.String") + + /** The set of all hijacked classes. */ + val HijackedClasses: Set[ClassName] = Set( + BoxedUnitClass, + BoxedBooleanClass, + BoxedCharacterClass, + BoxedByteClass, + BoxedShortClass, + BoxedIntegerClass, + BoxedLongClass, + BoxedFloatClass, + BoxedDoubleClass, + BoxedStringClass + ) + + /** The class of things returned by `ClassOf` and `GetClass`. */ + val ClassClass: ClassName = ClassName("java.lang.Class") + + /** `java.lang.Cloneable`, which is an ancestor of array classes and is used + * by `Clone`. + */ + val CloneableClass: ClassName = ClassName("java.lang.Cloneable") + + /** `java.io.Serializable`, which is an ancestor of array classes. */ + val SerializableClass: ClassName = ClassName("java.io.Serializable") + + /** The superclass of all throwables. + * + * This is the result type of `WrapAsThrowable` nodes, as well as the input + * type of `UnwrapFromThrowable`. + */ + val ThrowableClass = ClassName("java.lang.Throwable") + + /** The exception thrown by a division by 0. */ + val ArithmeticExceptionClass: ClassName = + ClassName("java.lang.ArithmeticException") + + /** The exception thrown by an `ArraySelect` that is out of bounds. */ + val ArrayIndexOutOfBoundsExceptionClass: ClassName = + ClassName("java.lang.ArrayIndexOutOfBoundsException") + + /** The exception thrown by an `Assign(ArraySelect, ...)` where the value cannot be stored. */ + val ArrayStoreExceptionClass: ClassName = + ClassName("java.lang.ArrayStoreException") + + /** The exception thrown by a `NewArray(...)` with a negative size. */ + val NegativeArraySizeExceptionClass: ClassName = + ClassName("java.lang.NegativeArraySizeException") + + /** The exception thrown by a `BinaryOp.String_charAt` that is out of bounds. */ + val StringIndexOutOfBoundsExceptionClass: ClassName = + ClassName("java.lang.StringIndexOutOfBoundsException") + + /** The exception thrown by an `AsInstanceOf` that fails. */ + val ClassCastExceptionClass: ClassName = + ClassName("java.lang.ClassCastException") + + /** The set of classes and interfaces that are ancestors of array classes. */ + private[ir] val AncestorsOfPseudoArrayClass: Set[ClassName] = { + /* This would logically be defined in Types, but that introduces a cyclic + * dependency between the initialization of Names and Types. + */ + Set(ObjectClass, CloneableClass, SerializableClass) + } + + /** Name of a constructor without argument. + * + * This is notably the signature of constructors of module classes. + */ + final val NoArgConstructorName: MethodName = + MethodName.constructor(Nil) + + /** This is used to construct a java.lang.Class. */ + final val ObjectArgConstructorName: MethodName = + MethodName.constructor(List(ClassRef(ObjectClass))) + + /** Name of the static initializer method. */ + final val StaticInitializerName: MethodName = + MethodName(StaticInitializerSimpleName, Nil, VoidRef) + + /** Name of the class initializer method. */ + final val ClassInitializerName: MethodName = + MethodName(ClassInitializerSimpleName, Nil, VoidRef) + + /** ModuleID of the default module */ + final val DefaultModuleID: String = "main" + + // --------------------------------------------------- + // ----- Private helpers for validation of names ----- + // --------------------------------------------------- + + private def throwInvalidEncodedName(encoded: UTF8String): Nothing = + throw new IllegalArgumentException(s"Invalid name: $encoded") + + private def validateSimpleEncodedName(encoded: UTF8String): UTF8String = + validateSimpleEncodedName(encoded, 0, encoded.length, openAngleBracketOK = true) + + private def validateSimpleEncodedName(encoded: UTF8String, start: Int, + end: Int, openAngleBracketOK: Boolean): UTF8String = { + + if (start == end) + throwInvalidEncodedName(encoded) + var i = start + while (i != end) { + (encoded(i).toInt: @switch) match { + case '.' | ';' | '[' | '/' => + throwInvalidEncodedName(encoded) + case '<' => + if (!openAngleBracketOK) + throwInvalidEncodedName(encoded) + case _ => + /* This case is hit for other ASCII characters, but also for the + * leading and continuation bytes of multibyte code points. They are + * all valid, since an `EncodedName` is already guaranteed to be a + * valid UTF-8 sequence. + */ + } + i += 1 + } + + encoded + } + + private def validateEncodedClassName(encoded: UTF8String): UTF8String = { + val len = encoded.length + var i = 0 + while (i < len) { + val start = i + while (i != len && encoded(i) != '.') + i += 1 + validateSimpleEncodedName(encoded, start, i, openAngleBracketOK = true) + i += 1 // goes to `len + 1` iff we successfully parsed the last segment + } + + /* Make sure that there isn't an empty segment at the end. This happens + * either when `len == 0` (in which case the *only* segment is empty) or + * when the last byte in `encoded` is a `.` (example: in `java.lang.`). + */ + if (i == len) + throwInvalidEncodedName(encoded) + + encoded + } + +} diff --git a/ir/shared/src/main/scala/org/scalajs/ir/OriginalName.scala b/ir/shared/src/main/scala/org/scalajs/ir/OriginalName.scala new file mode 100644 index 0000000000..d2211095d5 --- /dev/null +++ b/ir/shared/src/main/scala/org/scalajs/ir/OriginalName.scala @@ -0,0 +1,93 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.ir + +import Names._ + +/** An optional original name. + * + * Since an `OriginalName` is basically an optional `UTF8String`, original + * names must always be well-formed Unicode strings. Unpaired surrogates are + * not valid. + */ +final class OriginalName private (private val bytes: Array[Byte]) + extends AnyVal { + + /* The underlying field is a `bytes` instead of a `UTF8String` for two + * reasons: + * - a `UTF8String` cannot be `null`, and + * - the underlying val of a value class cannot itself be a custom value + * class. + */ + + def isEmpty: Boolean = bytes == null + def isDefined: Boolean = bytes != null + + /** Gets the underlying `UTF8String` without checking for emptiness. */ + @inline private def unsafeGet: UTF8String = + UTF8String.unsafeCreate(bytes) + + def get: UTF8String = { + if (isEmpty) + throw new NoSuchElementException("NoOriginalName.get") + unsafeGet + } + + def orElse(name: Name): OriginalName = + orElse(name.encoded) + + def orElse(name: MethodName): OriginalName = + orElse(name.simpleName) + + def orElse(name: UTF8String): OriginalName = + if (isDefined) this + else OriginalName(name) + + def getOrElse(name: Name): UTF8String = + getOrElse(name.encoded) + + def getOrElse(name: MethodName): UTF8String = + getOrElse(name.simpleName) + + def getOrElse(name: UTF8String): UTF8String = + if (isDefined) unsafeGet + else name + + def getOrElse(name: String): UTF8String = { + /* Do not use `getOrElse(UTF8Sring(name))` so that we do not pay the cost + * of encoding the `name` in UTF-8 if `this.isDefined`. + */ + if (isDefined) unsafeGet + else UTF8String(name) + } + + override def toString(): String = + if (isDefined) s"OriginalName($unsafeGet)" + else "NoOriginalName" +} + +object OriginalName { + val NoOriginalName: OriginalName = new OriginalName(null) + + def apply(name: UTF8String): OriginalName = + new OriginalName(name.bytes) + + def apply(name: Name): OriginalName = + apply(name.encoded) + + def apply(name: MethodName): OriginalName = + apply(name.simpleName) + + def apply(name: String): OriginalName = + apply(UTF8String(name)) +} diff --git a/ir/src/main/scala/org/scalajs/core/ir/Position.scala b/ir/shared/src/main/scala/org/scalajs/ir/Position.scala similarity index 97% rename from ir/src/main/scala/org/scalajs/core/ir/Position.scala rename to ir/shared/src/main/scala/org/scalajs/ir/Position.scala index 78dcb5b831..c2b60fb598 100644 --- a/ir/src/main/scala/org/scalajs/core/ir/Position.scala +++ b/ir/shared/src/main/scala/org/scalajs/ir/Position.scala @@ -10,7 +10,7 @@ * additional information regarding copyright ownership. */ -package org.scalajs.core.ir +package org.scalajs.ir final case class Position( /** Source file. */ diff --git a/ir/shared/src/main/scala/org/scalajs/ir/Printers.scala b/ir/shared/src/main/scala/org/scalajs/ir/Printers.scala new file mode 100644 index 0000000000..11dfdc81ee --- /dev/null +++ b/ir/shared/src/main/scala/org/scalajs/ir/Printers.scala @@ -0,0 +1,1212 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.ir + +import scala.annotation.switch + +// Unimport default print and println to avoid invoking them by mistake +import scala.Predef.{print => _, println => _, _} + +import java.io.Writer + +import Names._ +import Position._ +import Trees._ +import Types._ +import Utils.printEscapeJS + +object Printers { + + /** Basically copied from scala.reflect.internal.Printers */ + abstract class IndentationManager { + protected val out: Writer + + private var indentMargin = 0 + private val indentStep = 2 + private var indentString = " " // 40 + + protected def indent(): Unit = indentMargin += indentStep + protected def undent(): Unit = indentMargin -= indentStep + + protected def getIndentMargin(): Int = indentMargin + + protected def println(): Unit = { + out.write('\n') + while (indentMargin > indentString.length()) + indentString += indentString + if (indentMargin > 0) + out.write(indentString, 0, indentMargin) + } + } + + class IRTreePrinter(protected val out: Writer) extends IndentationManager { + protected final def printColumn(ts: List[IRNode], start: String, + sep: String, end: String): Unit = { + print(start); indent() + var rest = ts + while (rest.nonEmpty) { + println() + printAnyNode(rest.head) + rest = rest.tail + if (rest.nonEmpty) + print(sep) + } + undent(); println(); print(end) + } + + protected final def printRow(ts: List[IRNode], start: String, sep: String, + end: String): Unit = { + print(start) + var rest = ts + while (rest.nonEmpty) { + printAnyNode(rest.head) + rest = rest.tail + if (rest.nonEmpty) + print(sep) + } + print(end) + } + + protected def printBlock(tree: Tree): Unit = { + val trees = tree match { + case Block(trees) => trees + case _ => tree :: Nil + } + printBlock(trees) + } + + protected def printBlock(trees: List[Tree]): Unit = + printColumn(trees, "{", ";", "}") + + protected def printSig(args: List[ParamDef], restParam: Option[ParamDef], + resultType: Type): Unit = { + print("(") + var rem = args + while (rem.nonEmpty) { + printAnyNode(rem.head) + rem = rem.tail + if (rem.nonEmpty || restParam.nonEmpty) + print(", ") + } + + restParam.foreach { p => + print("...") + printAnyNode(p) + } + + print(")") + + if (resultType != NoType) { + print(": ") + print(resultType) + print(" = ") + } else { + print(' ') + } + } + + def printArgs(args: List[TreeOrJSSpread]): Unit = { + printRow(args, "(", ", ", ")") + } + + def printAnyNode(node: IRNode): Unit = { + node match { + case node: LocalIdent => print(node) + case node: LabelIdent => print(node) + case node: FieldIdent => print(node) + case node: MethodIdent => print(node) + case node: ClassIdent => print(node) + case node: ParamDef => print(node) + case node: Tree => print(node) + case node: JSSpread => print(node) + case node: ClassDef => print(node) + case node: MemberDef => print(node) + case node: JSConstructorBody => printBlock(node.allStats) + case node: TopLevelExportDef => print(node) + } + } + + def print(paramDef: ParamDef): Unit = { + val ParamDef(ident, originalName, ptpe, mutable) = paramDef + if (mutable) + print("var ") + print(ident) + print(originalName) + print(": ") + print(ptpe) + } + + def print(tree: Tree): Unit = { + tree match { + // Definitions + + case VarDef(ident, originalName, vtpe, mutable, rhs) => + if (mutable) + print("var ") + else + print("val ") + print(ident) + print(originalName) + print(": ") + print(vtpe) + print(" = ") + print(rhs) + + // Control flow constructs + + case Skip() => + print("/**/") + + case tree: Block => + printBlock(tree) + + case Labeled(label, tpe, body) => + print(label) + if (tpe != NoType) { + print('[') + print(tpe) + print(']') + } + print(": ") + printBlock(body) + + case Assign(lhs, rhs) => + print(lhs) + print(" = ") + print(rhs) + + case Return(expr, label) => + print("return@") + print(label) + print(" ") + print(expr) + + case If(cond, BooleanLiteral(true), elsep) => + print(cond) + print(" || ") + print(elsep) + + case If(cond, thenp, BooleanLiteral(false)) => + print(cond) + print(" && ") + print(thenp) + + case If(cond, thenp, elsep) => + print("if (") + print(cond) + print(") ") + + printBlock(thenp) + elsep match { + case Skip() => () + case If(_, _, _) => + print(" else ") + print(elsep) + case _ => + print(" else ") + printBlock(elsep) + } + + case While(cond, body) => + print("while (") + print(cond) + print(") ") + printBlock(body) + + case DoWhile(body, cond) => + print("do ") + printBlock(body) + print(" while (") + print(cond) + print(')') + + case ForIn(obj, keyVar, keyVarOriginalName, body) => + print("for (val ") + print(keyVar) + print(keyVarOriginalName) + print(" in ") + print(obj) + print(") ") + printBlock(body) + + case TryFinally(TryCatch(block, errVar, errVarOriginalName, handler), finalizer) => + print("try ") + printBlock(block) + print(" catch (") + print(errVar) + print(errVarOriginalName) + print(") ") + printBlock(handler) + print(" finally ") + printBlock(finalizer) + + case TryCatch(block, errVar, errVarOriginalName, handler) => + print("try ") + printBlock(block) + print(" catch (") + print(errVar) + print(errVarOriginalName) + print(") ") + printBlock(handler) + + case TryFinally(block, finalizer) => + print("try ") + printBlock(block) + print(" finally ") + printBlock(finalizer) + + case Throw(expr) => + print("throw ") + print(expr) + + case Match(selector, cases, default) => + print("match (") + print(selector) + print(") {"); indent() + for ((values, body) <- cases) { + println() + printRow(values, "case ", " | ", ":"); indent(); println() + print(body) + print(";") + undent() + } + println() + print("default:"); indent(); println() + print(default) + print(";") + undent() + undent(); println(); print('}') + + case Debugger() => + print("debugger") + + // Scala expressions + + case New(className, ctor, args) => + print("new ") + print(className) + print("().") + print(ctor) + printArgs(args) + + case LoadModule(className) => + print("mod:") + print(className) + + case StoreModule(className, value) => + print("mod:") + print(className) + print("<-") + print(value) + + case Select(qualifier, className, field) => + print(qualifier) + print('.') + print(className) + print("::") + print(field) + + case SelectStatic(className, field) => + print(className) + print("::") + print(field) + + case SelectJSNativeMember(className, member) => + print(className) + print("::") + print(member) + + case Apply(flags, receiver, method, args) => + print(receiver) + print(".") + print(method) + printArgs(args) + + case ApplyStatically(flags, receiver, className, method, args) => + print(receiver) + print(".") + print(className) + print("::") + print(flags) + print(method) + printArgs(args) + + case ApplyStatic(flags, className, method, args) => + print(className) + print("::") + print(flags) + print(method) + printArgs(args) + + case ApplyDynamicImport(flags, className, method, args) => + print("dynamicImport ") + print(className) + print("::") + print(flags) + print(method) + printArgs(args) + + case UnaryOp(UnaryOp.String_length, lhs) => + print(lhs) + print(".length") + + case UnaryOp(op, lhs) => + import UnaryOp._ + print('(') + print((op: @switch) match { + case Boolean_! => + "!" + case IntToChar => + "(char)" + case IntToByte => + "(byte)" + case IntToShort => + "(short)" + case CharToInt | ByteToInt | ShortToInt | LongToInt | DoubleToInt => + "(int)" + case IntToLong | DoubleToLong => + "(long)" + case DoubleToFloat | LongToFloat => + "(float)" + case IntToDouble | LongToDouble | FloatToDouble => + "(double)" + }) + print(lhs) + print(')') + + case BinaryOp(BinaryOp.Int_-, IntLiteral(0), rhs) => + print("(-") + print(rhs) + print(')') + + case BinaryOp(BinaryOp.Int_^, IntLiteral(-1), rhs) => + print("(~") + print(rhs) + print(')') + + case BinaryOp(BinaryOp.Long_-, LongLiteral(0L), rhs) => + print("(-") + print(rhs) + print(')') + + case BinaryOp(BinaryOp.Long_^, LongLiteral(-1L), rhs) => + print("(~") + print(rhs) + print(')') + + case BinaryOp(BinaryOp.Float_-, FloatLiteral(0.0f), rhs) => + print("(-") + print(rhs) + print(')') + + case BinaryOp(BinaryOp.Double_-, + IntLiteral(0) | FloatLiteral(0.0f) | DoubleLiteral(0.0), rhs) => + print("(-") + print(rhs) + print(')') + + case BinaryOp(BinaryOp.String_charAt, lhs, rhs) => + print(lhs) + print('[') + print(rhs) + print(']') + + case BinaryOp(op, lhs, rhs) => + import BinaryOp._ + print('(') + print(lhs) + print(' ') + print((op: @switch) match { + case === => "===" + case !== => "!==" + + case String_+ => "+[string]" + + case Boolean_== => "==[bool]" + case Boolean_!= => "!=[bool]" + case Boolean_| => "|[bool]" + case Boolean_& => "&[bool]" + + case Int_+ => "+[int]" + case Int_- => "-[int]" + case Int_* => "*[int]" + case Int_/ => "/[int]" + case Int_% => "%[int]" + + case Int_| => "|[int]" + case Int_& => "&[int]" + case Int_^ => "^[int]" + case Int_<< => "<<[int]" + case Int_>>> => ">>>[int]" + case Int_>> => ">>[int]" + + case Int_== => "==[int]" + case Int_!= => "!=[int]" + case Int_< => "<[int]" + case Int_<= => "<=[int]" + case Int_> => ">[int]" + case Int_>= => ">=[int]" + + case Long_+ => "+[long]" + case Long_- => "-[long]" + case Long_* => "*[long]" + case Long_/ => "/[long]" + case Long_% => "%[long]" + + case Long_| => "|[long]" + case Long_& => "&[long]" + case Long_^ => "^[long]" + case Long_<< => "<<[long]" + case Long_>>> => ">>>[long]" + case Long_>> => ">>[long]" + + case Long_== => "==[long]" + case Long_!= => "!=[long]" + case Long_< => "<[long]" + case Long_<= => "<=[long]" + case Long_> => ">[long]" + case Long_>= => ">=[long]" + + case Float_+ => "+[float]" + case Float_- => "-[float]" + case Float_* => "*[float]" + case Float_/ => "/[float]" + case Float_% => "%[float]" + + case Double_+ => "+[double]" + case Double_- => "-[double]" + case Double_* => "*[double]" + case Double_/ => "/[double]" + case Double_% => "%[double]" + + case Double_== => "==[double]" + case Double_!= => "!=[double]" + case Double_< => "<[double]" + case Double_<= => "<=[double]" + case Double_> => ">[double]" + case Double_>= => ">=[double]" + }) + print(' ') + print(rhs) + print(')') + + case NewArray(typeRef, lengths) => + print("new ") + print(typeRef.base) + for (length <- lengths) { + print('[') + print(length) + print(']') + } + for (dim <- lengths.size until typeRef.dimensions) + print("[]") + + case ArrayValue(typeRef, elems) => + print(typeRef) + printArgs(elems) + + case ArrayLength(array) => + print(array) + print(".length") + + case ArraySelect(array, index) => + print(array) + print('[') + print(index) + print(']') + + case RecordValue(tpe, elems) => + print('(') + var first = true + for ((field, value) <- tpe.fields zip elems) { + if (first) first = false + else print(", ") + print(field.name) + print(" = ") + print(value) + } + print(')') + + case RecordSelect(record, field) => + print(record) + print('.') + print(field) + + case IsInstanceOf(expr, testType) => + print(expr) + print(".isInstanceOf[") + print(testType) + print(']') + + case AsInstanceOf(expr, tpe) => + print(expr) + print(".asInstanceOf[") + print(tpe) + print(']') + + case GetClass(expr) => + print(expr) + print(".getClass()") + + case Clone(expr) => + print("(") + print(expr) + print(')') + + case IdentityHashCode(expr) => + print("(") + print(expr) + print(')') + + case WrapAsThrowable(expr) => + print("(") + print(expr) + print(")") + + case UnwrapFromThrowable(expr) => + print("(") + print(expr) + print(")") + + // JavaScript expressions + + case JSNew(ctor, args) => + def containsOnlySelectsFromAtom(tree: Tree): Boolean = tree match { + case JSPrivateSelect(qual, _, _) => containsOnlySelectsFromAtom(qual) + case JSSelect(qual, _) => containsOnlySelectsFromAtom(qual) + case VarRef(_) => true + case This() => true + case _ => false // in particular, Apply + } + if (containsOnlySelectsFromAtom(ctor)) { + print("new ") + print(ctor) + } else { + print("new (") + print(ctor) + print(')') + } + printArgs(args) + + case JSPrivateSelect(qualifier, className, field) => + print(qualifier) + print('.') + print(className) + print("::") + print(field) + + case JSSelect(qualifier, item) => + print(qualifier) + print('[') + print(item) + print(']') + + case JSFunctionApply(fun, args) => + fun match { + case _:JSPrivateSelect | _:JSSelect | _:Select => + print("(0, ") + print(fun) + print(')') + + case _ => + print(fun) + } + printArgs(args) + + case JSMethodApply(receiver, method, args) => + print(receiver) + print('[') + print(method) + print(']') + printArgs(args) + + case JSSuperSelect(superClass, qualifier, item) => + print("super(") + print(superClass) + print(")::") + print(qualifier) + print('[') + print(item) + print(']') + + case JSSuperMethodCall(superClass, receiver, method, args) => + print("super(") + print(superClass) + print(")::") + print(receiver) + print('[') + print(method) + print(']') + printArgs(args) + + case JSSuperConstructorCall(args) => + print("super") + printArgs(args) + + case JSImportCall(arg) => + print("import(") + print(arg) + print(')') + + case JSNewTarget() => + print("new.target") + + case JSImportMeta() => + print("import.meta") + + case LoadJSConstructor(className) => + print("constructorOf[") + print(className) + print(']') + + case LoadJSModule(className) => + print("mod:") + print(className) + + case JSDelete(qualifier, item) => + print("delete ") + print(qualifier) + print('[') + print(item) + print(']') + + case JSUnaryOp(op, lhs) => + import JSUnaryOp._ + print('(') + print((op: @switch) match { + case + => "+" + case - => "-" + case ~ => "~" + case ! => "!" + + case `typeof` => "typeof " + }) + print(lhs) + print(")") + + case JSBinaryOp(op, lhs, rhs) => + import JSBinaryOp._ + print('(') + print(lhs) + print(" ") + print((op: @switch) match { + case === => "===" + case !== => "!==" + + case + => "+" + case - => "-" + case * => "*" + case / => "/" + case % => "%" + + case | => "|" + case & => "&" + case ^ => "^" + case << => "<<" + case >> => ">>" + case >>> => ">>>" + + case < => "<" + case <= => "<=" + case > => ">" + case >= => ">=" + + case && => "&&" + case || => "||" + + case `in` => "in" + case `instanceof` => "instanceof" + + case ** => "**" + }) + print(" ") + print(rhs) + print(')') + + case JSArrayConstr(items) => + printRow(items, "[", ", ", "]") + + case JSObjectConstr(Nil) => + print("{}") + + case JSObjectConstr(fields) => + print('{'); indent(); println() + var rest = fields + while (rest.nonEmpty) { + val elem = rest.head + elem._1 match { + case key: StringLiteral => + print(key: Tree) + case key => + print('[') + print(key) + print(']') + } + print(": ") + print(rest.head._2) + rest = rest.tail + if (rest.nonEmpty) { + print(",") + println() + } + } + undent(); println(); print('}') + + case JSGlobalRef(ident) => + print("global:") + print(ident) + + case JSTypeOfGlobalRef(globalRef) => + print("(typeof ") + print(globalRef) + print(")") + + case JSLinkingInfo() => + print("") + + // Literals + + case Undefined() => + print("(void 0)") + + case Null() => + print("null") + + case BooleanLiteral(value) => + print(if (value) "true" else "false") + + case CharLiteral(value) => + print('\'') + printEscapeJS(value.toString(), out) + print('\'') + + case ByteLiteral(value) => + if (value >= 0) { + print(value.toString) + print("_b") + } else { + print('(') + print(value.toString) + print("_b)") + } + + case ShortLiteral(value) => + if (value >= 0) { + print(value.toString) + print("_s") + } else { + print('(') + print(value.toString) + print("_s)") + } + + case IntLiteral(value) => + if (value >= 0) { + print(value.toString) + } else { + print('(') + print(value.toString) + print(')') + } + + case LongLiteral(value) => + if (value < 0L) + print('(') + print(value.toString) + print('L') + if (value < 0L) + print(')') + + case FloatLiteral(value) => + if (value == 0.0f && 1.0f / value < 0.0f) { + print("(-0f)") + } else { + if (value < 0.0f) + print('(') + print(value.toString) + print('f') + if (value < 0.0f) + print(')') + } + + case DoubleLiteral(value) => + if (value == 0.0 && 1.0 / value < 0.0) { + print("(-0d)") + } else { + if (value < 0.0) + print('(') + print(value.toString) + print('d') + if (value < 0.0) + print(')') + } + + case StringLiteral(value) => + print('\"') + printEscapeJS(value, out) + print('\"') + + case ClassOf(typeRef) => + print("classOf[") + print(typeRef) + print(']') + + // Atomic expressions + + case VarRef(ident) => + print(ident) + + case This() => + print("this") + + case Closure(arrow, captureParams, params, restParam, body, captureValues) => + if (arrow) + print("(arrow-lambda<") + else + print("(lambda<") + var first = true + for ((param, value) <- captureParams.zip(captureValues)) { + if (first) + first = false + else + print(", ") + print(param) + print(" = ") + print(value) + } + print(">") + printSig(params, restParam, AnyType) + printBlock(body) + print(')') + + case CreateJSClass(className, captureValues) => + print("createjsclass[") + print(className) + printRow(captureValues, "](", ", ", ")") + + // Transient + + case Transient(value) => + value.printIR(this) + } + } + + def print(spread: JSSpread): Unit = { + print("...") + print(spread.items) + } + + def print(classDef: ClassDef): Unit = { + import classDef._ + for (jsClassCaptures <- classDef.jsClassCaptures) { + if (jsClassCaptures.isEmpty) + print("captures: none") + else + printRow(jsClassCaptures, "captures: ", ", ", "") + println() + } + print(classDef.optimizerHints) + kind match { + case ClassKind.Class => print("class ") + case ClassKind.ModuleClass => print("module class ") + case ClassKind.Interface => print("interface ") + case ClassKind.AbstractJSType => print("abstract js type ") + case ClassKind.HijackedClass => print("hijacked class ") + case ClassKind.JSClass => print("js class ") + case ClassKind.JSModuleClass => print("js module class ") + case ClassKind.NativeJSClass => print("native js class ") + case ClassKind.NativeJSModuleClass => print("native js module class ") + } + print(name) + print(originalName) + superClass.foreach { cls => + print(" extends ") + print(cls) + jsSuperClass.foreach { tree => + print(" (via ") + print(tree) + print(")") + } + } + if (interfaces.nonEmpty) { + print(" implements ") + var rest = interfaces + while (rest.nonEmpty) { + print(rest.head) + rest = rest.tail + if (rest.nonEmpty) + print(", ") + } + } + jsNativeLoadSpec.foreach { spec => + print(" loadfrom ") + print(spec) + } + print(" ") + printColumn(memberDefs ::: topLevelExportDefs, "{", "", "}") + } + + def print(memberDef: MemberDef): Unit = { + memberDef match { + case FieldDef(flags, name, originalName, vtpe) => + print(flags.namespace.prefixString) + if (flags.isMutable) + print("var ") + else + print("val ") + print(name) + print(originalName) + print(": ") + print(vtpe) + + case JSFieldDef(flags, name, vtpe) => + print(flags.namespace.prefixString) + if (flags.isMutable) + print("var ") + else + print("val ") + printJSMemberName(name) + print(": ") + print(vtpe) + + case tree: MethodDef => + val MethodDef(flags, name, originalName, args, resultType, body) = tree + print(tree.optimizerHints) + print(flags.namespace.prefixString) + print("def ") + print(name) + print(originalName) + printSig(args, restParam = None, resultType) + body.fold { + print("") + } { body => + printBlock(body) + } + + case tree: JSConstructorDef => + val JSConstructorDef(flags, args, restParam, body) = tree + print(tree.optimizerHints) + print(flags.namespace.prefixString) + print("def constructor") + printSig(args, restParam, AnyType) + printBlock(body.allStats) + + case tree: JSMethodDef => + val JSMethodDef(flags, name, args, restParam, body) = tree + print(tree.optimizerHints) + print(flags.namespace.prefixString) + print("def ") + printJSMemberName(name) + printSig(args, restParam, AnyType) + printBlock(body) + + case JSPropertyDef(flags, name, getterBody, setterArgAndBody) => + getterBody foreach { body => + print(flags.namespace.prefixString) + print("get ") + printJSMemberName(name) + printSig(Nil, None, AnyType) + printBlock(body) + } + + if (getterBody.isDefined && setterArgAndBody.isDefined) { + println() + } + + setterArgAndBody foreach { case (arg, body) => + print(flags.namespace.prefixString) + print("set ") + printJSMemberName(name) + printSig(arg :: Nil, None, NoType) + printBlock(body) + } + + case JSNativeMemberDef(flags, name, jsNativeLoadSpec) => + print(flags.namespace.prefixString) + print("native ") + print(name) + print(" loadfrom ") + print(jsNativeLoadSpec) + } + } + + def print(topLevelExportDef: TopLevelExportDef): Unit = { + print("export top[moduleID=\"") + printEscapeJS(topLevelExportDef.moduleID, out) + print("\"] ") + + topLevelExportDef match { + case TopLevelJSClassExportDef(_, exportName) => + print("class \"") + printEscapeJS(exportName, out) + print("\"") + + case TopLevelModuleExportDef(_, exportName) => + print("module \"") + printEscapeJS(exportName, out) + print("\"") + + case TopLevelMethodExportDef(_, methodDef) => + print(methodDef) + + case TopLevelFieldExportDef(_, exportName, field) => + print("static field ") + print(field) + print(" as \"") + printEscapeJS(exportName, out) + print("\"") + } + } + + def print(typeRef: TypeRef): Unit = typeRef match { + case PrimRef(tpe) => + print(tpe) + case ClassRef(className) => + print(className) + case ArrayTypeRef(base, dims) => + print(base) + for (i <- 1 to dims) + print("[]") + } + + def print(tpe: Type): Unit = tpe match { + case AnyType => print("any") + case NothingType => print("nothing") + case UndefType => print("void") + case BooleanType => print("boolean") + case CharType => print("char") + case ByteType => print("byte") + case ShortType => print("short") + case IntType => print("int") + case LongType => print("long") + case FloatType => print("float") + case DoubleType => print("double") + case StringType => print("string") + case NullType => print("null") + case ClassType(className) => print(className) + case NoType => print("") + + case ArrayType(arrayTypeRef) => + print(arrayTypeRef) + + case RecordType(fields) => + print('(') + var first = true + for (RecordType.Field(name, _, tpe, mutable) <- fields) { + if (first) + first = false + else + print(", ") + if (mutable) + print("var ") + print(name) + print(": ") + print(tpe) + } + print(')') + } + + def print(ident: LocalIdent): Unit = + print(ident.name) + + def print(ident: LabelIdent): Unit = + print(ident.name) + + def print(ident: FieldIdent): Unit = + print(ident.name) + + def print(ident: MethodIdent): Unit = + print(ident.name) + + def print(ident: ClassIdent): Unit = + print(ident.name) + + def print(name: Name): Unit = + printEscapeJS(name.nameString, out) + + def print(name: MethodName): Unit = + printEscapeJS(name.nameString, out) + + def print(originalName: OriginalName): Unit = { + if (originalName.isDefined) { + print('{') + print(originalName.get.toString()) + print('}') + } + } + + def printJSMemberName(name: Tree): Unit = name match { + case name: StringLiteral => + print(name) + case _ => + print("[") + print(name) + print("]") + } + + def print(spec: JSNativeLoadSpec): Unit = { + def printPath(path: List[String]): Unit = { + for (propName <- path) { + print("[\"") + printEscapeJS(propName, out) + print("\"]") + } + } + + spec match { + case JSNativeLoadSpec.Global(globalRef, path) => + print("global:") + print(globalRef) + printPath(path) + + case JSNativeLoadSpec.Import(module, path) => + print("import(") + print(module) + print(')') + printPath(path) + + case JSNativeLoadSpec.ImportWithGlobalFallback(importSpec, globalSpec) => + print(importSpec) + print(" fallback ") + print(globalSpec) + } + } + + def print(s: String): Unit = + out.write(s) + + def print(c: Int): Unit = + out.write(c) + + def print(optimizerHints: OptimizerHints)( + implicit dummy: DummyImplicit): Unit = { + if (optimizerHints != OptimizerHints.empty) { + print("@hints(") + print(OptimizerHints.toBits(optimizerHints).toString) + print(") ") + } + } + + def print(flags: ApplyFlags)( + implicit dummy1: DummyImplicit, dummy2: DummyImplicit): Unit = { + if (flags.isPrivate) + print("private::") + } + + // Make it public + override def println(): Unit = super.println() + + def complete(): Unit = () + } + +} diff --git a/ir/shared/src/main/scala/org/scalajs/ir/ScalaJSVersions.scala b/ir/shared/src/main/scala/org/scalajs/ir/ScalaJSVersions.scala new file mode 100644 index 0000000000..afb84b6a77 --- /dev/null +++ b/ir/shared/src/main/scala/org/scalajs/ir/ScalaJSVersions.scala @@ -0,0 +1,127 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.ir + +import java.util.concurrent.ConcurrentHashMap + +import scala.util.matching.Regex + +object ScalaJSVersions extends VersionChecks( + current = "1.12.0", + binaryEmitted = "1.12" +) + +/** Helper class to allow for testing of logic. */ +class VersionChecks private[ir] ( + /** Scala.js version. */ + final val current: String, + /** Version of binary IR emitted by this version of Scala.js. */ + final val binaryEmitted: String +) { + import VersionChecks._ + + checkConsistent(current, binaryEmitted) + + private val (binaryMajor, binaryMinor, binaryPreRelease) = parseBinary(binaryEmitted) + + /** The cross binary version. + * + * This is the version advertised in artifacts released by Scala.js users. + * + * - For a pre-release version with a minor version == 0, it is the full + * [[binaryEmitted]]. Such a version is ''before'' the final major version + * is released, and as such any release is typically fully breaking. + * - For a non-pre-release, or the pre-release of a minor version, it is + * only the major version, since binary minor versions are backwards + * compatible. + */ + final val binaryCross: String = { + val needsFull = binaryPreRelease.isDefined && binaryMinor == 0 + if (needsFull) binaryEmitted + else binaryMajor.toString + } + + private val knownSupportedBinary = { + val m = ConcurrentHashMap.newKeySet[String]() + m.add(binaryEmitted) + m + } + + /** Check we can support this binary version (used by deserializer) */ + final def checkSupported(version: String): Unit = { + if (!knownSupportedBinary.contains(version)) { + val (major, minor, preRelease) = parseBinary(version) + val supported = ( + // the exact pre-release version is supported via knownSupportedBinary + preRelease.isEmpty && + major == binaryMajor && + minor <= binaryMinor && + (binaryPreRelease.isEmpty || minor < binaryMinor) + ) + + if (supported) { + knownSupportedBinary.add(version) + } else { + throw new IRVersionNotSupportedException(version, binaryEmitted, + s"This version ($version) of Scala.js IR is not supported. " + + s"Supported versions are up to $binaryEmitted") + } + } + } +} + +private object VersionChecks { + private val fullRE = """^([0-9]+)\.([0-9]+)\.([0-9]+)(-.*)?$""".r + private val binaryRE = """^([0-9]+)\.([0-9]+)(-.*)?$""".r + + private def parseBinary(v: String): (Int, Int, Option[String]) = { + val m = mustMatch(binaryRE, v) + (m.group(1).toInt, m.group(2).toInt, preRelease(m.group(3))) + } + + private def parseFull(v: String): (Int, Int, Int, Option[String]) = { + val m = mustMatch(fullRE, v) + (m.group(1).toInt, m.group(2).toInt, m.group(3).toInt, preRelease(m.group(4))) + } + + private def mustMatch(re: Regex, v: String): Regex.Match = { + re.findFirstMatchIn(v).getOrElse( + throw new IllegalArgumentException("malformed version: " + v)) + } + + private def preRelease(v: String): Option[String] = + Option(v).map(_.stripPrefix("-")) + + private def checkConsistent(current: String, binary: String) = { + val (binaryMajor, binaryMinor, binaryPreRelease) = parseBinary(binary) + val (currentMajor, currentMinor, currentPatch, currentPreRelease) = parseFull(current) + + require(currentMajor == binaryMajor, "major(current) != major(binaryEmitted)") + + require(currentMinor >= binaryMinor, "minor(current) < minor(binaryEmitted)") + + require( + currentPreRelease.isEmpty || + currentMinor > binaryMinor || + currentPatch > 0 || + binaryPreRelease == currentPreRelease, + "current is older than binaryEmitted through pre-release") + + require( + binaryPreRelease.isEmpty || ( + currentMinor == binaryMinor && + currentPatch == 0 && + binaryPreRelease == currentPreRelease), + "binaryEmitted is in pre-release but does not match current") + } +} diff --git a/ir/shared/src/main/scala/org/scalajs/ir/Serializers.scala b/ir/shared/src/main/scala/org/scalajs/ir/Serializers.scala new file mode 100644 index 0000000000..43c00f988a --- /dev/null +++ b/ir/shared/src/main/scala/org/scalajs/ir/Serializers.scala @@ -0,0 +1,2064 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.ir + +import scala.annotation.switch + +import java.io._ +import java.nio._ +import java.net.URI + +import scala.collection.mutable +import scala.concurrent._ + +import Names._ +import Position._ +import Trees._ +import Types._ +import Tags._ + +import Utils.JumpBackByteArrayOutputStream + +object Serializers { + /** Scala.js IR File Magic Number + * + * CA FE : first part of magic number of Java class files + * 4A 53 : "JS" in ASCII + * + */ + final val IRMagicNumber = 0xCAFE4A53 + + def serialize(stream: OutputStream, classDef: ClassDef): Unit = { + new Serializer().serialize(stream, classDef) + } + + /** Deserializes entry points from the given buffer. + * + * @throws java.nio.BufferUnderflowException if not enough data is available + * in the buffer. In this case the buffer's position is unspecified and + * needs to be reset by the caller. + */ + def deserializeEntryPointsInfo(buf: ByteBuffer): EntryPointsInfo = + withBigEndian(buf)(new Deserializer(_).deserializeEntryPointsInfo()) + + /** Deserializes a class def from the given buffer. + * + * @throws java.nio.BufferUnderflowException if not enough data is available + * in the buffer. In this case the buffer's position is unspecified and + * needs to be reset by the caller. + */ + def deserialize(buf: ByteBuffer): ClassDef = + withBigEndian(buf)(new Deserializer(_).deserialize()) + + @inline + private def withBigEndian[T](buf: ByteBuffer)(body: ByteBuffer => T): T = { + val o = buf.order() + buf.order(ByteOrder.BIG_ENDIAN) + try body(buf) + finally buf.order(o) + } + + private object PositionFormat { + /* Positions are serialized incrementally as diffs wrt the last position. + * + * Formats are (the first byte is decomposed in bits): + * + * 1st byte | next bytes | description + * ----------------------------------------- + * ccccccc0 | | Column diff (7-bit signed) + * llllll01 | CC | Line diff (6-bit signed), column (8-bit unsigned) + * ____0011 | LL LL CC | Line diff (16-bit signed), column (8-bit unsigned) + * ____0111 | 12 bytes | File index, line, column (all 32-bit signed) + * 11111111 | | NoPosition (is not compared/stored in last position) + * + * Underscores are irrelevant and must be set to 0. + */ + + final val Format1Mask = 0x01 + final val Format1MaskValue = 0x00 + final val Format1Shift = 1 + + final val Format2Mask = 0x03 + final val Format2MaskValue = 0x01 + final val Format2Shift = 2 + + final val Format3Mask = 0x0f + final val Format3MaskValue = 0x03 + + final val FormatFullMask = 0x0f + final val FormatFullMaskValue = 0x7 + + final val FormatNoPositionValue = -1 + } + + private final class EncodedNameKey(val encoded: UTF8String) { + override def equals(that: Any): Boolean = that match { + case that: EncodedNameKey => + UTF8String.equals(this.encoded, that.encoded) + case _ => + false + } + + override def hashCode(): Int = + UTF8String.hashCode(encoded) + } + + private final class Serializer { + private[this] val bufferUnderlying = new JumpBackByteArrayOutputStream + private[this] val buffer = new DataOutputStream(bufferUnderlying) + + private[this] val files = mutable.ListBuffer.empty[URI] + private[this] val fileIndexMap = mutable.Map.empty[URI, Int] + private def fileToIndex(file: URI): Int = + fileIndexMap.getOrElseUpdate(file, (files += file).size - 1) + + private[this] val encodedNames = mutable.ListBuffer.empty[UTF8String] + private[this] val encodedNameIndexMap = mutable.Map.empty[EncodedNameKey, Int] + private def encodedNameToIndex(encoded: UTF8String): Int = { + val byteString = new EncodedNameKey(encoded) + encodedNameIndexMap.getOrElseUpdate(byteString, + (encodedNames += encoded).size - 1) + } + + private[this] val methodNames = mutable.ListBuffer.empty[MethodName] + private[this] val methodNameIndexMap = mutable.Map.empty[MethodName, Int] + private def methodNameToIndex(methodName: MethodName): Int = { + methodNameIndexMap.getOrElseUpdate(methodName, { + // need to reserve the internal simple names + + def reserveTypeRef(typeRef: TypeRef): Unit = typeRef match { + case _: PrimRef => + // nothing to do + case ClassRef(className) => + encodedNameToIndex(className.encoded) + case ArrayTypeRef(base, _) => + reserveTypeRef(base) + } + + encodedNameToIndex(methodName.simpleName.encoded) + methodName.paramTypeRefs.foreach(reserveTypeRef(_)) + reserveTypeRef(methodName.resultTypeRef) + (methodNames += methodName).size - 1 + }) + } + + private[this] val strings = mutable.ListBuffer.empty[String] + private[this] val stringIndexMap = mutable.Map.empty[String, Int] + private def stringToIndex(str: String): Int = + stringIndexMap.getOrElseUpdate(str, (strings += str).size - 1) + + private[this] var lastPosition: Position = Position.NoPosition + + def serialize(stream: OutputStream, classDef: ClassDef): Unit = { + // Write tree to buffer and record files, names and strings + writeClassDef(classDef) + + val s = new DataOutputStream(stream) + + // Write the Scala.js IR magic number + s.writeInt(IRMagicNumber) + + // Write the Scala.js Version + s.writeUTF(ScalaJSVersions.binaryEmitted) + + // Write the entry points info + val entryPointsInfo = EntryPointsInfo.forClassDef(classDef) + val entryPointEncodedName = entryPointsInfo.className.encoded.bytes + s.writeInt(entryPointEncodedName.length) + s.write(entryPointEncodedName) + s.writeBoolean(entryPointsInfo.hasEntryPoint) + + // Emit the files + s.writeInt(files.size) + files.foreach(f => s.writeUTF(f.toString)) + + // Emit the names + s.writeInt(encodedNames.size) + encodedNames.foreach { encodedName => + s.writeInt(encodedName.length) + s.write(encodedName.bytes) + } + + def writeTypeRef(typeRef: TypeRef): Unit = typeRef match { + case PrimRef(tpe) => + tpe match { + case NoType => s.writeByte(TagVoidRef) + case BooleanType => s.writeByte(TagBooleanRef) + case CharType => s.writeByte(TagCharRef) + case ByteType => s.writeByte(TagByteRef) + case ShortType => s.writeByte(TagShortRef) + case IntType => s.writeByte(TagIntRef) + case LongType => s.writeByte(TagLongRef) + case FloatType => s.writeByte(TagFloatRef) + case DoubleType => s.writeByte(TagDoubleRef) + case NullType => s.writeByte(TagNullRef) + case NothingType => s.writeByte(TagNothingRef) + } + case ClassRef(className) => + s.writeByte(TagClassRef) + s.writeInt(encodedNameIndexMap(new EncodedNameKey(className.encoded))) + case ArrayTypeRef(base, dimensions) => + s.writeByte(TagArrayTypeRef) + writeTypeRef(base) + s.writeInt(dimensions) + } + + // Emit the method names + s.writeInt(methodNames.size) + methodNames.foreach { methodName => + s.writeInt(encodedNameIndexMap( + new EncodedNameKey(methodName.simpleName.encoded))) + s.writeInt(methodName.paramTypeRefs.size) + methodName.paramTypeRefs.foreach(writeTypeRef(_)) + writeTypeRef(methodName.resultTypeRef) + s.writeBoolean(methodName.isReflectiveProxy) + writeName(methodName.simpleName) + } + + // Emit the strings + s.writeInt(strings.size) + strings.foreach(s.writeUTF) + + // Paste the buffer + bufferUnderlying.writeTo(s) + + s.flush() + } + + def writeTree(tree: Tree): Unit = { + import buffer._ + + def writeTagAndPos(tag: Int): Unit = { + writeByte(tag) + writePosition(tree.pos) + } + + tree match { + case VarDef(ident, originalName, vtpe, mutable, rhs) => + writeTagAndPos(TagVarDef) + writeLocalIdent(ident); writeOriginalName(originalName) + writeType(vtpe); writeBoolean(mutable); writeTree(rhs) + + case Skip() => + writeTagAndPos(TagSkip) + + case Block(stats) => + writeTagAndPos(TagBlock) + writeTrees(stats) + + case Labeled(label, tpe, body) => + writeTagAndPos(TagLabeled) + writeLabelIdent(label); writeType(tpe); writeTree(body) + + case Assign(lhs, rhs) => + writeTagAndPos(TagAssign) + writeTree(lhs); writeTree(rhs) + + case Return(expr, label) => + writeTagAndPos(TagReturn) + writeTree(expr); writeLabelIdent(label) + + case If(cond, thenp, elsep) => + writeTagAndPos(TagIf) + writeTree(cond); writeTree(thenp); writeTree(elsep) + writeType(tree.tpe) + + case While(cond, body) => + writeTagAndPos(TagWhile) + writeTree(cond); writeTree(body) + + case DoWhile(body, cond) => + writeTagAndPos(TagDoWhile) + writeTree(body); writeTree(cond) + + case ForIn(obj, keyVar, keyVarOriginalName, body) => + writeTagAndPos(TagForIn) + writeTree(obj); writeLocalIdent(keyVar) + writeOriginalName(keyVarOriginalName); writeTree(body) + + case TryCatch(block, errVar, errVarOriginalName, handler) => + writeTagAndPos(TagTryCatch) + writeTree(block); writeLocalIdent(errVar) + writeOriginalName(errVarOriginalName); writeTree(handler) + writeType(tree.tpe) + + case TryFinally(block, finalizer) => + writeTagAndPos(TagTryFinally) + writeTree(block); writeTree(finalizer) + + case Throw(expr) => + writeTagAndPos(TagThrow) + writeTree(expr) + + case Match(selector, cases, default) => + writeTagAndPos(TagMatch) + writeTree(selector) + writeInt(cases.size) + cases foreach { caze => + writeTrees(caze._1); writeTree(caze._2) + } + writeTree(default) + writeType(tree.tpe) + + case Debugger() => + writeTagAndPos(TagDebugger) + + case New(className, ctor, args) => + writeTagAndPos(TagNew) + writeName(className); writeMethodIdent(ctor); writeTrees(args) + + case LoadModule(className) => + writeTagAndPos(TagLoadModule) + writeName(className) + + case StoreModule(className, value) => + writeTagAndPos(TagStoreModule) + writeName(className); writeTree(value) + + case Select(qualifier, className, field) => + writeTagAndPos(TagSelect) + writeTree(qualifier); writeName(className); writeFieldIdent(field) + writeType(tree.tpe) + + case SelectStatic(className, field) => + writeTagAndPos(TagSelectStatic) + writeName(className); writeFieldIdent(field) + writeType(tree.tpe) + + case SelectJSNativeMember(className, member) => + writeTagAndPos(TagSelectJSNativeMember) + writeName(className); writeMethodIdent(member) + + case Apply(flags, receiver, method, args) => + writeTagAndPos(TagApply) + writeApplyFlags(flags); writeTree(receiver); writeMethodIdent(method); writeTrees(args) + writeType(tree.tpe) + + case ApplyStatically(flags, receiver, className, method, args) => + writeTagAndPos(TagApplyStatically) + writeApplyFlags(flags); writeTree(receiver); writeName(className); writeMethodIdent(method); writeTrees(args) + writeType(tree.tpe) + + case ApplyStatic(flags, className, method, args) => + writeTagAndPos(TagApplyStatic) + writeApplyFlags(flags); writeName(className); writeMethodIdent(method); writeTrees(args) + writeType(tree.tpe) + + case ApplyDynamicImport(flags, className, method, args) => + writeTagAndPos(TagApplyDynamicImport) + writeApplyFlags(flags); writeName(className); writeMethodIdent(method); writeTrees(args) + + case UnaryOp(op, lhs) => + writeTagAndPos(TagUnaryOp) + writeByte(op); writeTree(lhs) + + case BinaryOp(op, lhs, rhs) => + writeTagAndPos(TagBinaryOp) + writeByte(op); writeTree(lhs); writeTree(rhs) + + case NewArray(tpe, lengths) => + writeTagAndPos(TagNewArray) + writeArrayTypeRef(tpe); writeTrees(lengths) + + case ArrayValue(tpe, elems) => + writeTagAndPos(TagArrayValue) + writeArrayTypeRef(tpe); writeTrees(elems) + + case ArrayLength(array) => + writeTagAndPos(TagArrayLength) + writeTree(array) + + case ArraySelect(array, index) => + writeTagAndPos(TagArraySelect) + writeTree(array); writeTree(index) + writeType(tree.tpe) + + case RecordValue(tpe, elems) => + writeTagAndPos(TagRecordValue) + writeType(tpe); writeTrees(elems) + + case RecordSelect(record, field) => + writeTagAndPos(TagRecordSelect) + writeTree(record); writeFieldIdent(field) + writeType(tree.tpe) + + case IsInstanceOf(expr, testType) => + writeTagAndPos(TagIsInstanceOf) + writeTree(expr); writeType(testType) + + case AsInstanceOf(expr, tpe) => + writeTagAndPos(TagAsInstanceOf) + writeTree(expr); writeType(tpe) + + case GetClass(expr) => + writeTagAndPos(TagGetClass) + writeTree(expr) + + case Clone(expr) => + writeTagAndPos(TagClone) + writeTree(expr) + + case IdentityHashCode(expr) => + writeTagAndPos(TagIdentityHashCode) + writeTree(expr) + + case WrapAsThrowable(expr) => + writeTagAndPos(TagWrapAsThrowable) + writeTree(expr) + + case UnwrapFromThrowable(expr) => + writeTagAndPos(TagUnwrapFromThrowable) + writeTree(expr) + + case JSNew(ctor, args) => + writeTagAndPos(TagJSNew) + writeTree(ctor); writeTreeOrJSSpreads(args) + + case JSPrivateSelect(qualifier, className, field) => + writeTagAndPos(TagJSPrivateSelect) + writeTree(qualifier); writeName(className); writeFieldIdent(field) + + case JSSelect(qualifier, item) => + writeTagAndPos(TagJSSelect) + writeTree(qualifier); writeTree(item) + + case JSFunctionApply(fun, args) => + writeTagAndPos(TagJSFunctionApply) + writeTree(fun); writeTreeOrJSSpreads(args) + + case JSMethodApply(receiver, method, args) => + writeTagAndPos(TagJSMethodApply) + writeTree(receiver); writeTree(method); writeTreeOrJSSpreads(args) + + case JSSuperSelect(superClass, qualifier, item) => + writeTagAndPos(TagJSSuperSelect) + writeTree(superClass); writeTree(qualifier); writeTree(item) + + case JSSuperMethodCall(superClass, receiver, method, args) => + writeTagAndPos(TagJSSuperMethodCall) + writeTree(superClass); writeTree(receiver); writeTree(method); writeTreeOrJSSpreads(args) + + case JSSuperConstructorCall(args) => + writeTagAndPos(TagJSSuperConstructorCall) + writeTreeOrJSSpreads(args) + + case JSImportCall(arg) => + writeTagAndPos(TagJSImportCall) + writeTree(arg) + + case JSNewTarget() => + writeTagAndPos(TagJSNewTarget) + + case JSImportMeta() => + writeTagAndPos(TagJSImportMeta) + + case LoadJSConstructor(className) => + writeTagAndPos(TagLoadJSConstructor) + writeName(className) + + case LoadJSModule(className) => + writeTagAndPos(TagLoadJSModule) + writeName(className) + + case JSDelete(qualifier, item) => + writeTagAndPos(TagJSDelete) + writeTree(qualifier) + writeTree(item) + + case JSUnaryOp(op, lhs) => + writeTagAndPos(TagJSUnaryOp) + writeInt(op); writeTree(lhs) + + case JSBinaryOp(op, lhs, rhs) => + writeTagAndPos(TagJSBinaryOp) + writeInt(op); writeTree(lhs); writeTree(rhs) + + case JSArrayConstr(items) => + writeTagAndPos(TagJSArrayConstr) + writeTreeOrJSSpreads(items) + + case JSObjectConstr(fields) => + writeTagAndPos(TagJSObjectConstr) + writeInt(fields.size) + fields.foreach { field => + writeTree(field._1); writeTree(field._2) + } + + case JSGlobalRef(name) => + writeTagAndPos(TagJSGlobalRef) + writeString(name) + + case JSTypeOfGlobalRef(globalRef) => + writeTagAndPos(TagJSTypeOfGlobalRef) + writeTree(globalRef) + + case JSLinkingInfo() => + writeTagAndPos(TagJSLinkingInfo) + + case Undefined() => + writeTagAndPos(TagUndefined) + + case Null() => + writeTagAndPos(TagNull) + + case BooleanLiteral(value) => + writeTagAndPos(TagBooleanLiteral) + writeBoolean(value) + + case CharLiteral(value) => + writeTagAndPos(TagCharLiteral) + writeChar(value) + + case ByteLiteral(value) => + writeTagAndPos(TagByteLiteral) + writeByte(value) + + case ShortLiteral(value) => + writeTagAndPos(TagShortLiteral) + writeShort(value) + + case IntLiteral(value) => + writeTagAndPos(TagIntLiteral) + writeInt(value) + + case LongLiteral(value) => + writeTagAndPos(TagLongLiteral) + writeLong(value) + + case FloatLiteral(value) => + writeTagAndPos(TagFloatLiteral) + writeFloat(value) + + case DoubleLiteral(value) => + writeTagAndPos(TagDoubleLiteral) + writeDouble(value) + + case StringLiteral(value) => + writeTagAndPos(TagStringLiteral) + writeString(value) + + case ClassOf(typeRef) => + writeTagAndPos(TagClassOf) + writeTypeRef(typeRef) + + case VarRef(ident) => + writeTagAndPos(TagVarRef) + writeLocalIdent(ident) + writeType(tree.tpe) + + case This() => + writeTagAndPos(TagThis) + writeType(tree.tpe) + + case Closure(arrow, captureParams, params, restParam, body, captureValues) => + writeTagAndPos(TagClosure) + writeBoolean(arrow) + writeParamDefs(captureParams) + writeParamDefs(params) + writeOptParamDef(restParam) + writeTree(body) + writeTrees(captureValues) + + case CreateJSClass(className, captureValues) => + writeTagAndPos(TagCreateJSClass) + writeName(className) + writeTrees(captureValues) + + case Transient(value) => + throw new InvalidIRException(tree, + "Cannot serialize a transient IR node (its value is of class " + + s"${value.getClass})") + } + } + + def writeTrees(trees: List[Tree]): Unit = { + buffer.writeInt(trees.size) + trees.foreach(writeTree) + } + + def writeOptTree(optTree: Option[Tree]): Unit = { + optTree.fold { + buffer.writeByte(TagEmptyTree) + } { tree => + writeTree(tree) + } + } + + def writeTreeOrJSSpreads(trees: List[TreeOrJSSpread]): Unit = { + buffer.writeInt(trees.size) + trees.foreach(writeTreeOrJSSpread) + } + + def writeTreeOrJSSpread(tree: TreeOrJSSpread): Unit = { + tree match { + case JSSpread(items) => + buffer.writeByte(TagJSSpread) + writePosition(tree.pos) + writeTree(items) + case tree: Tree => + writeTree(tree) + } + } + + def writeClassDef(classDef: ClassDef): Unit = { + import buffer._ + import classDef._ + + writePosition(classDef.pos) + writeClassIdent(name) + writeOriginalName(originalName) + writeByte(ClassKind.toByte(kind)) + writeBoolean(jsClassCaptures.isDefined) + jsClassCaptures.foreach(writeParamDefs(_)) + writeOptClassIdent(superClass) + writeClassIdents(interfaces) + writeOptTree(jsSuperClass) + writeJSNativeLoadSpec(jsNativeLoadSpec) + writeMemberDefs(memberDefs) + writeTopLevelExportDefs(topLevelExportDefs) + writeInt(OptimizerHints.toBits(optimizerHints)) + } + + def writeMemberDef(memberDef: MemberDef): Unit = { + import buffer._ + writePosition(memberDef.pos) + memberDef match { + case FieldDef(flags, name, originalName, ftpe) => + writeByte(TagFieldDef) + writeInt(MemberFlags.toBits(flags)) + writeFieldIdent(name) + writeOriginalName(originalName) + writeType(ftpe) + + case JSFieldDef(flags, name, ftpe) => + writeByte(TagJSFieldDef) + writeInt(MemberFlags.toBits(flags)) + writeTree(name) + writeType(ftpe) + + case methodDef: MethodDef => + val MethodDef(flags, name, originalName, args, resultType, body) = methodDef + + writeByte(TagMethodDef) + writeOptHash(methodDef.hash) + + // Prepare for back-jump and write dummy length + bufferUnderlying.markJump() + writeInt(-1) + + // Write out method def + writeInt(MemberFlags.toBits(flags)); writeMethodIdent(name) + writeOriginalName(originalName) + writeParamDefs(args); writeType(resultType); writeOptTree(body) + writeInt(OptimizerHints.toBits(methodDef.optimizerHints)) + + // Jump back and write true length + val length = bufferUnderlying.jumpBack() + writeInt(length) + bufferUnderlying.continue() + + case ctorDef: JSConstructorDef => + val JSConstructorDef(flags, args, restParam, body) = ctorDef + + writeByte(TagJSConstructorDef) + writeOptHash(ctorDef.hash) + + // Prepare for back-jump and write dummy length + bufferUnderlying.markJump() + writeInt(-1) + + // Write out ctor def + writeInt(MemberFlags.toBits(flags)) + writeParamDefs(args); writeOptParamDef(restParam) + writePosition(body.pos) + writeTrees(body.beforeSuper) + writeTree(body.superCall) + writeTrees(body.afterSuper) + writeInt(OptimizerHints.toBits(ctorDef.optimizerHints)) + + // Jump back and write true length + val length = bufferUnderlying.jumpBack() + writeInt(length) + bufferUnderlying.continue() + + case methodDef: JSMethodDef => + val JSMethodDef(flags, name, args, restParam, body) = methodDef + + writeByte(TagJSMethodDef) + writeOptHash(methodDef.hash) + + // Prepare for back-jump and write dummy length + bufferUnderlying.markJump() + writeInt(-1) + + // Write out method def + writeInt(MemberFlags.toBits(flags)); writeTree(name) + writeParamDefs(args); writeOptParamDef(restParam); writeTree(body) + writeInt(OptimizerHints.toBits(methodDef.optimizerHints)) + + // Jump back and write true length + val length = bufferUnderlying.jumpBack() + writeInt(length) + bufferUnderlying.continue() + + case JSPropertyDef(flags, name, getter, setterArgAndBody) => + writeByte(TagJSPropertyDef) + writeInt(MemberFlags.toBits(flags)) + writeTree(name) + writeOptTree(getter) + writeBoolean(setterArgAndBody.isDefined) + setterArgAndBody foreach { case (arg, body) => + writeParamDef(arg); writeTree(body) + } + + case JSNativeMemberDef(flags, name, jsNativeLoadSpec) => + writeByte(TagJSNativeMemberDef) + writeInt(MemberFlags.toBits(flags)) + writeMethodIdent(name) + writeJSNativeLoadSpec(Some(jsNativeLoadSpec)) + } + } + + def writeMemberDefs(memberDefs: List[MemberDef]): Unit = { + buffer.writeInt(memberDefs.size) + memberDefs.foreach(writeMemberDef) + } + + def writeTopLevelExportDef(topLevelExportDef: TopLevelExportDef): Unit = { + import buffer._ + writePosition(topLevelExportDef.pos) + topLevelExportDef match { + case TopLevelJSClassExportDef(moduleID, exportName) => + writeByte(TagTopLevelJSClassExportDef) + writeString(moduleID); writeString(exportName) + + case TopLevelModuleExportDef(moduleID, exportName) => + writeByte(TagTopLevelModuleExportDef) + writeString(moduleID); writeString(exportName) + + case TopLevelMethodExportDef(moduleID, methodDef) => + writeByte(TagTopLevelMethodExportDef) + writeString(moduleID); writeMemberDef(methodDef) + + case TopLevelFieldExportDef(moduleID, exportName, field) => + writeByte(TagTopLevelFieldExportDef) + writeString(moduleID); writeString(exportName); writeFieldIdent(field) + } + } + + def writeTopLevelExportDefs( + topLevelExportDefs: List[TopLevelExportDef]): Unit = { + buffer.writeInt(topLevelExportDefs.size) + topLevelExportDefs.foreach(writeTopLevelExportDef) + } + + def writeLocalIdent(ident: LocalIdent): Unit = { + writePosition(ident.pos) + writeName(ident.name) + } + + def writeLabelIdent(ident: LabelIdent): Unit = { + writePosition(ident.pos) + writeName(ident.name) + } + + def writeFieldIdent(ident: FieldIdent): Unit = { + writePosition(ident.pos) + writeName(ident.name) + } + + def writeMethodIdent(ident: MethodIdent): Unit = { + writePosition(ident.pos) + writeMethodName(ident.name) + } + + def writeClassIdent(ident: ClassIdent): Unit = { + writePosition(ident.pos) + writeName(ident.name) + } + + def writeClassIdents(idents: List[ClassIdent]): Unit = { + buffer.writeInt(idents.size) + idents.foreach(writeClassIdent) + } + + def writeOptClassIdent(optIdent: Option[ClassIdent]): Unit = { + buffer.writeBoolean(optIdent.isDefined) + optIdent.foreach(writeClassIdent) + } + + def writeName(name: Name): Unit = + buffer.writeInt(encodedNameToIndex(name.encoded)) + + def writeMethodName(name: MethodName): Unit = + buffer.writeInt(methodNameToIndex(name)) + + def writeOriginalName(originalName: OriginalName): Unit = { + buffer.writeBoolean(originalName.isDefined) + if (originalName.isDefined) + buffer.writeInt(encodedNameToIndex(originalName.get)) + } + + def writeParamDef(paramDef: ParamDef): Unit = { + writePosition(paramDef.pos) + writeLocalIdent(paramDef.name) + writeOriginalName(paramDef.originalName) + writeType(paramDef.ptpe) + buffer.writeBoolean(paramDef.mutable) + } + + def writeParamDefs(paramDefs: List[ParamDef]): Unit = { + buffer.writeInt(paramDefs.size) + paramDefs.foreach(writeParamDef(_)) + } + + def writeOptParamDef(paramDef: Option[ParamDef]): Unit = { + buffer.writeBoolean(paramDef.isDefined) + paramDef.foreach(writeParamDef(_)) + } + + def writeType(tpe: Type): Unit = { + tpe match { + case AnyType => buffer.write(TagAnyType) + case NothingType => buffer.write(TagNothingType) + case UndefType => buffer.write(TagUndefType) + case BooleanType => buffer.write(TagBooleanType) + case CharType => buffer.write(TagCharType) + case ByteType => buffer.write(TagByteType) + case ShortType => buffer.write(TagShortType) + case IntType => buffer.write(TagIntType) + case LongType => buffer.write(TagLongType) + case FloatType => buffer.write(TagFloatType) + case DoubleType => buffer.write(TagDoubleType) + case StringType => buffer.write(TagStringType) + case NullType => buffer.write(TagNullType) + case NoType => buffer.write(TagNoType) + + case ClassType(className) => + buffer.write(TagClassType) + writeName(className) + + case ArrayType(arrayTypeRef) => + buffer.write(TagArrayType) + writeArrayTypeRef(arrayTypeRef) + + case RecordType(fields) => + buffer.write(TagRecordType) + buffer.writeInt(fields.size) + for (RecordType.Field(name, originalName, tpe, mutable) <- fields) { + writeName(name) + writeOriginalName(originalName) + writeType(tpe) + buffer.writeBoolean(mutable) + } + } + } + + def writeTypeRef(typeRef: TypeRef): Unit = typeRef match { + case PrimRef(tpe) => + tpe match { + case NoType => buffer.writeByte(TagVoidRef) + case BooleanType => buffer.writeByte(TagBooleanRef) + case CharType => buffer.writeByte(TagCharRef) + case ByteType => buffer.writeByte(TagByteRef) + case ShortType => buffer.writeByte(TagShortRef) + case IntType => buffer.writeByte(TagIntRef) + case LongType => buffer.writeByte(TagLongRef) + case FloatType => buffer.writeByte(TagFloatRef) + case DoubleType => buffer.writeByte(TagDoubleRef) + case NullType => buffer.writeByte(TagNullRef) + case NothingType => buffer.writeByte(TagNothingRef) + } + case ClassRef(className) => + buffer.writeByte(TagClassRef) + writeName(className) + case typeRef: ArrayTypeRef => + buffer.writeByte(TagArrayTypeRef) + writeArrayTypeRef(typeRef) + } + + def writeArrayTypeRef(typeRef: ArrayTypeRef): Unit = { + writeTypeRef(typeRef.base) + buffer.writeInt(typeRef.dimensions) + } + + def writeApplyFlags(flags: ApplyFlags): Unit = + buffer.writeInt(ApplyFlags.toBits(flags)) + + def writePosition(pos: Position): Unit = { + import buffer._ + import PositionFormat._ + + def writeFull(): Unit = { + writeByte(FormatFullMaskValue) + writeInt(fileToIndex(pos.source)) + writeInt(pos.line) + writeInt(pos.column) + } + + if (pos == Position.NoPosition) { + writeByte(FormatNoPositionValue) + } else if (lastPosition == Position.NoPosition || + pos.source != lastPosition.source) { + writeFull() + lastPosition = pos + } else { + val line = pos.line + val column = pos.column + val lineDiff = line - lastPosition.line + val columnDiff = column - lastPosition.column + val columnIsByte = column >= 0 && column < 256 + + if (lineDiff == 0 && columnDiff >= -64 && columnDiff < 64) { + writeByte((columnDiff << Format1Shift) | Format1MaskValue) + } else if (lineDiff >= -32 && lineDiff < 32 && columnIsByte) { + writeByte((lineDiff << Format2Shift) | Format2MaskValue) + writeByte(column) + } else if (lineDiff >= Short.MinValue && lineDiff <= Short.MaxValue && columnIsByte) { + writeByte(Format3MaskValue) + writeShort(lineDiff) + writeByte(column) + } else { + writeFull() + } + + lastPosition = pos + } + } + + def writeJSNativeLoadSpec(jsNativeLoadSpec: Option[JSNativeLoadSpec]): Unit = { + import buffer._ + + def writeGlobalSpec(spec: JSNativeLoadSpec.Global): Unit = { + writeString(spec.globalRef) + writeStrings(spec.path) + } + + def writeImportSpec(spec: JSNativeLoadSpec.Import): Unit = { + writeString(spec.module) + writeStrings(spec.path) + } + + jsNativeLoadSpec.fold { + writeByte(TagJSNativeLoadSpecNone) + } { spec => + spec match { + case spec: JSNativeLoadSpec.Global => + writeByte(TagJSNativeLoadSpecGlobal) + writeGlobalSpec(spec) + + case spec: JSNativeLoadSpec.Import => + writeByte(TagJSNativeLoadSpecImport) + writeImportSpec(spec) + + case JSNativeLoadSpec.ImportWithGlobalFallback(importSpec, globalSpec) => + writeByte(TagJSNativeLoadSpecImportWithGlobalFallback) + writeImportSpec(importSpec) + writeGlobalSpec(globalSpec) + } + } + } + + def writeOptHash(optHash: Option[TreeHash]): Unit = { + buffer.writeBoolean(optHash.isDefined) + for (hash <- optHash) + buffer.write(hash.hash) + } + + def writeString(s: String): Unit = + buffer.writeInt(stringToIndex(s)) + + def writeStrings(strings: List[String]): Unit = { + buffer.writeInt(strings.size) + strings.foreach(writeString) + } + } + + private final class Deserializer(buf: ByteBuffer) { + require(buf.order() == ByteOrder.BIG_ENDIAN) + + private[this] var hacks: Hacks = _ + private[this] var files: Array[URI] = _ + private[this] var encodedNames: Array[UTF8String] = _ + private[this] var localNames: Array[LocalName] = _ + private[this] var labelNames: Array[LabelName] = _ + private[this] var fieldNames: Array[FieldName] = _ + private[this] var simpleMethodNames: Array[SimpleMethodName] = _ + private[this] var classNames: Array[ClassName] = _ + private[this] var methodNames: Array[MethodName] = _ + private[this] var strings: Array[String] = _ + + private[this] var lastPosition: Position = Position.NoPosition + + private[this] var thisTypeForHack8: Type = NoType + + def deserializeEntryPointsInfo(): EntryPointsInfo = { + hacks = new Hacks(sourceVersion = readHeader()) + readEntryPointsInfo() + } + + def deserialize(): ClassDef = { + hacks = new Hacks(sourceVersion = readHeader()) + readEntryPointsInfo() // discarded + files = Array.fill(readInt())(new URI(readUTF())) + encodedNames = Array.fill(readInt()) { + val len = readInt() + val encodedName = new Array[Byte](len) + buf.get(encodedName) + UTF8String.createAcquiringByteArray(encodedName) + } + localNames = new Array(encodedNames.length) + labelNames = new Array(encodedNames.length) + fieldNames = new Array(encodedNames.length) + simpleMethodNames = new Array(encodedNames.length) + classNames = new Array(encodedNames.length) + methodNames = Array.fill(readInt()) { + val simpleName = readSimpleMethodName() + val paramTypeRefs = List.fill(readInt())(readTypeRef()) + val resultTypeRef = readTypeRef() + val isReflectiveProxy = readBoolean() + MethodName(simpleName, paramTypeRefs, resultTypeRef, isReflectiveProxy) + } + strings = Array.fill(readInt())(readUTF()) + readClassDef() + } + + /** Reads the Scala.js IR header and verifies the version compatibility. + * + * @return the binary version that was read + */ + private def readHeader(): String = { + // Check magic number + if (readInt() != IRMagicNumber) + throw new IOException("Not a Scala.js IR file") + + // Check that we support this version of the IR + val version = readUTF() + ScalaJSVersions.checkSupported(version) + + version + } + + private def readEntryPointsInfo(): EntryPointsInfo = { + val encodedNameLen = readInt() + val encodedName = new Array[Byte](encodedNameLen) + buf.get(encodedName) + val name = ClassName(UTF8String.createAcquiringByteArray(encodedName)) + val hasEntryPoint = readBoolean() + new EntryPointsInfo(name, hasEntryPoint) + } + + def readTree(): Tree = + readTreeFromTag(readByte()) + + def readOptTree(): Option[Tree] = { + val tag = readByte() + if (tag == TagEmptyTree) None + else Some(readTreeFromTag(tag)) + } + + def readTreeOrJSSpread(): TreeOrJSSpread = { + val tag = readByte() + if (tag == TagJSSpread) { + implicit val pos = readPosition() + JSSpread(readTree()) + } else { + readTreeFromTag(tag) + } + } + + def readTreeOrJSSpreads(): List[TreeOrJSSpread] = + List.fill(readInt())(readTreeOrJSSpread()) + + private def readTreeFromTag(tag: Byte): Tree = { + implicit val pos = readPosition() + (tag: @switch) match { + case TagEmptyTree => + throw new IOException("Found invalid TagEmptyTree") + + case TagVarDef => VarDef(readLocalIdent(), readOriginalName(), readType(), readBoolean(), readTree()) + case TagSkip => Skip() + case TagBlock => Block(readTrees()) + case TagLabeled => Labeled(readLabelIdent(), readType(), readTree()) + + case TagAssign => + val lhs0 = readTree() + val lhs = if (hacks.use4 && lhs0.tpe == NothingType) { + /* Note [Nothing FieldDef rewrite] + * (throw qual.field[null]) = rhs --> qual.field[null] = rhs + */ + lhs0 match { + case Throw(sel: Select) if sel.tpe == NullType => sel + case _ => lhs0 + } + } else { + lhs0 + } + + val rhs = readTree() + + Assign(lhs.asInstanceOf[AssignLhs], rhs) + + case TagReturn => Return(readTree(), readLabelIdent()) + case TagIf => If(readTree(), readTree(), readTree())(readType()) + case TagWhile => While(readTree(), readTree()) + case TagDoWhile => DoWhile(readTree(), readTree()) + case TagForIn => ForIn(readTree(), readLocalIdent(), readOriginalName(), readTree()) + + case TagTryCatch => + TryCatch(readTree(), readLocalIdent(), readOriginalName(), readTree())(readType()) + + case TagTryFinally => + TryFinally(readTree(), readTree()) + + case TagThrow => + val expr = readTree() + val patchedExpr = + if (hacks.use8) throwArgumentHack8(expr) + else expr + Throw(patchedExpr) + + case TagMatch => + Match(readTree(), List.fill(readInt()) { + (readTrees().map(_.asInstanceOf[MatchableLiteral]), readTree()) + }, readTree())(readType()) + case TagDebugger => Debugger() + + case TagNew => New(readClassName(), readMethodIdent(), readTrees()) + case TagLoadModule => LoadModule(readClassName()) + case TagStoreModule => StoreModule(readClassName(), readTree()) + + case TagSelect => + val qualifier = readTree() + val className = readClassName() + val field = readFieldIdent() + val tpe = readType() + + if (hacks.use4 && tpe == NothingType) { + /* Note [Nothing FieldDef rewrite] + * qual.field[nothing] --> throw qual.field[null] + */ + Throw(Select(qualifier, className, field)(NullType)) + } else { + Select(qualifier, className, field)(tpe) + } + + case TagSelectStatic => SelectStatic(readClassName(), readFieldIdent())(readType()) + case TagSelectJSNativeMember => SelectJSNativeMember(readClassName(), readMethodIdent()) + + case TagApply => + Apply(readApplyFlags(), readTree(), readMethodIdent(), readTrees())( + readType()) + case TagApplyStatically => + ApplyStatically(readApplyFlags(), readTree(), readClassName(), + readMethodIdent(), readTrees())(readType()) + case TagApplyStatic => + ApplyStatic(readApplyFlags(), readClassName(), readMethodIdent(), + readTrees())(readType()) + case TagApplyDynamicImport => + ApplyDynamicImport(readApplyFlags(), readClassName(), + readMethodIdent(), readTrees()) + + case TagUnaryOp => UnaryOp(readByte(), readTree()) + case TagBinaryOp => BinaryOp(readByte(), readTree(), readTree()) + case TagNewArray => NewArray(readArrayTypeRef(), readTrees()) + case TagArrayValue => ArrayValue(readArrayTypeRef(), readTrees()) + case TagArrayLength => ArrayLength(readTree()) + case TagArraySelect => ArraySelect(readTree(), readTree())(readType()) + case TagRecordValue => RecordValue(readType().asInstanceOf[RecordType], readTrees()) + case TagIsInstanceOf => IsInstanceOf(readTree(), readType()) + case TagAsInstanceOf => AsInstanceOf(readTree(), readType()) + case TagGetClass => GetClass(readTree()) + case TagClone => Clone(readTree()) + case TagIdentityHashCode => IdentityHashCode(readTree()) + + case TagWrapAsThrowable => + WrapAsThrowable(readTree()) + case TagUnwrapFromThrowable => + UnwrapFromThrowable(readTree()) + + case TagJSNew => JSNew(readTree(), readTreeOrJSSpreads()) + case TagJSPrivateSelect => JSPrivateSelect(readTree(), readClassName(), readFieldIdent()) + case TagJSSelect => JSSelect(readTree(), readTree()) + case TagJSFunctionApply => JSFunctionApply(readTree(), readTreeOrJSSpreads()) + case TagJSMethodApply => JSMethodApply(readTree(), readTree(), readTreeOrJSSpreads()) + case TagJSSuperSelect => JSSuperSelect(readTree(), readTree(), readTree()) + case TagJSSuperMethodCall => + JSSuperMethodCall(readTree(), readTree(), readTree(), readTreeOrJSSpreads()) + case TagJSSuperConstructorCall => JSSuperConstructorCall(readTreeOrJSSpreads()) + case TagJSImportCall => JSImportCall(readTree()) + case TagJSNewTarget => JSNewTarget() + case TagJSImportMeta => JSImportMeta() + case TagLoadJSConstructor => LoadJSConstructor(readClassName()) + case TagLoadJSModule => LoadJSModule(readClassName()) + case TagJSDelete => JSDelete(readTree(), readTree()) + case TagJSUnaryOp => JSUnaryOp(readInt(), readTree()) + case TagJSBinaryOp => JSBinaryOp(readInt(), readTree(), readTree()) + case TagJSArrayConstr => JSArrayConstr(readTreeOrJSSpreads()) + case TagJSObjectConstr => + JSObjectConstr(List.fill(readInt())((readTree(), readTree()))) + case TagJSGlobalRef => JSGlobalRef(readString()) + case TagJSTypeOfGlobalRef => JSTypeOfGlobalRef(readTree().asInstanceOf[JSGlobalRef]) + case TagJSLinkingInfo => JSLinkingInfo() + + case TagUndefined => Undefined() + case TagNull => Null() + case TagBooleanLiteral => BooleanLiteral(readBoolean()) + case TagCharLiteral => CharLiteral(readChar()) + case TagByteLiteral => ByteLiteral(readByte()) + case TagShortLiteral => ShortLiteral(readShort()) + case TagIntLiteral => IntLiteral(readInt()) + case TagLongLiteral => LongLiteral(readLong()) + case TagFloatLiteral => FloatLiteral(readFloat()) + case TagDoubleLiteral => DoubleLiteral(readDouble()) + case TagStringLiteral => StringLiteral(readString()) + case TagClassOf => ClassOf(readTypeRef()) + + case TagVarRef => + VarRef(readLocalIdent())(readType()) + + case TagThis => + val tpe = readType() + if (hacks.use8) + This()(thisTypeForHack8) + else + This()(tpe) + + case TagClosure => + val arrow = readBoolean() + val captureParams = readParamDefs() + val (params, restParam) = readParamDefsWithRest() + val body = if (!hacks.use8) { + readTree() + } else { + val prevThisTypeForHack8 = thisTypeForHack8 + thisTypeForHack8 = if (arrow) NoType else AnyType + try { + readTree() + } finally { + thisTypeForHack8 = prevThisTypeForHack8 + } + } + val captureValues = readTrees() + Closure(arrow, captureParams, params, restParam, body, captureValues) + + case TagCreateJSClass => + CreateJSClass(readClassName(), readTrees()) + } + } + + /** Patches the argument of a `Throw` for IR version until 1.8. + * + * Prior to Scala.js 1.11, `Throw(e)` was emitted by the compiler with + * the somewhat implied assumption that it would "throw an NPE" (but + * subject to UB so not really) when `e` is a `null` `Throwable`. + * + * Moreover, there was no other user-space way to emit a `Throw(e)` in the + * IR (`js.special.throw` was introduced in 1.11), so *all* `Throw` nodes + * are part of the semantics of a Scala `throw expr` or of an implicit + * re-throw in a Scala `try..catch`. + * + * In Scala.js 1.11, we explicitly ruled out the NPE behavior of `Throw`, + * so that `Throw(e)` only ever throws the value of `e`, while the NPE UB + * is specified by `UnwrapFromThrowable`. Among other things, this allows + * the user-space code `js.special.throw(e)` to indiscriminately throw `e` + * even if it is `null`. + * + * With this hack, we patch `Throw(e)` where `e` is a nullable `Throwable` + * by inserting an appropriate `UnwrapFromThrowable`. + * + * Naively, we would just return `UnwrapFromThrowable(e)`. Unfortunately, + * we cannot prove that this is type-correct when the type of `e` is a + * `ClassType(cls)`, as we cannot test whether `cls` is a subclass of + * `java.lang.Throwable`. So we have to produce the following instead: + * + * {{{ + * if (expr === null) unwrapFromThrowable(null) else expr + * }}} + * + * except that evaluates `expr` twice. If it is a `VarRef`, which is a + * common case, that is fine. Otherwise, we have to wrap this pattern in + * an IIFE. + * + * We also have to avoid the transformation altogether when the `expr` is + * an `AnyType`. This happens when the previous Scala.js compiler already + * provides the unwrapped exception, which is either + * + * - when automatically re-throwing an unhandled exception at the end of a + * `try..catch`, or + * - when throwing a maybe-JavaScriptException, with an explicit call to + * `runtime.package$.unwrapJavaScriptException(x)`. + */ + private def throwArgumentHack8(expr: Tree)(implicit pos: Position): Tree = { + expr.tpe match { + case NullType => + // Evaluate the expression then definitely run into an NPE UB + UnwrapFromThrowable(expr) + + case ClassType(_) => + expr match { + case New(_, _, _) => + // Common case (`throw new SomeException(...)`) that is known not to be `null` + expr + case VarRef(_) => + /* Common case (explicit re-throw of the form `throw th`) where we don't need the IIFE. + * if (expr === null) unwrapFromThrowable(null) else expr + */ + If(BinaryOp(BinaryOp.===, expr, Null()), UnwrapFromThrowable(Null()), expr)(AnyType) + case _ => + /* General case where we need to avoid evaluating `expr` twice. + * ((x) => if (x === null) unwrapFromThrowable(null) else x)(expr) + */ + val x = LocalIdent(LocalName("x")) + val xParamDef = ParamDef(x, OriginalName.NoOriginalName, AnyType, mutable = false) + val xRef = xParamDef.ref + val closure = Closure(arrow = true, Nil, List(xParamDef), None, { + If(BinaryOp(BinaryOp.===, xRef, Null()), UnwrapFromThrowable(Null()), xRef)(AnyType) + }, Nil) + JSFunctionApply(closure, List(expr)) + } + + case _ => + // Do not transform expressions of other types, in particular `AnyType` + expr + } + } + + def readTrees(): List[Tree] = + List.fill(readInt())(readTree()) + + def readClassDef(): ClassDef = { + implicit val pos = readPosition() + val name = readClassIdent() + val cls = name.name + val originalName = readOriginalName() + val kind = ClassKind.fromByte(readByte()) + + if (hacks.use8) { + thisTypeForHack8 = { + if (kind.isJSType) + AnyType + else if (kind == ClassKind.HijackedClass) + BoxedClassToPrimType.getOrElse(cls, ClassType(cls)) // getOrElse as safety guard + else + ClassType(cls) + } + } + + val hasJSClassCaptures = readBoolean() + val jsClassCaptures = + if (!hasJSClassCaptures) None + else Some(readParamDefs()) + val superClass = readOptClassIdent() + val parents = readClassIdents() + + /* jsSuperClass is not hacked like in readMemberDef.bodyHack5. The + * compilers before 1.6 always use a simple VarRef() as jsSuperClass, + * when there is one, so no hack is required. + */ + val jsSuperClass = readOptTree() + + val jsNativeLoadSpec = readJSNativeLoadSpec() + val memberDefs0 = readMemberDefs(cls, kind) + val topLevelExportDefs = readTopLevelExportDefs(cls, kind) + val optimizerHints = OptimizerHints.fromBits(readInt()) + + val memberDefs = + if (hacks.use8 && kind.isJSClass) memberDefs0.map(jsConstructorDefHack(_)) + else memberDefs0 + + ClassDef(name, originalName, kind, jsClassCaptures, superClass, parents, + jsSuperClass, jsNativeLoadSpec, memberDefs, topLevelExportDefs)( + optimizerHints) + } + + private def jsConstructorDefHack(memberDef: MemberDef): MemberDef = { + memberDef match { + case methodDef @ JSMethodDef(flags, StringLiteral("constructor"), args, restParam, body) + if flags.namespace == MemberNamespace.Public => + val bodyStats = body match { + case Block(stats) => stats + case _ => body :: Nil + } + + bodyStats.span(!_.isInstanceOf[JSSuperConstructorCall]) match { + case (beforeSuper, (superCall: JSSuperConstructorCall) :: afterSuper) => + val newFlags = flags.withNamespace(MemberNamespace.Constructor) + val newBody = JSConstructorBody(beforeSuper, superCall, afterSuper)(body.pos) + val ctorDef = JSConstructorDef(newFlags, args, restParam, newBody)( + methodDef.optimizerHints, None)(methodDef.pos) + Hashers.hashJSConstructorDef(ctorDef) + + case _ => + /* This is awkward: we have an old-style JS constructor that is + * structurally invalid. We crash in order not to silently + * ignore errors. + */ + throw new IOException( + s"Found invalid pre-1.11 JS constructor def at ${methodDef.pos}:\n${methodDef.show}") + } + + case _ => + memberDef + } + } + + def readMemberDef(owner: ClassName, ownerKind: ClassKind): MemberDef = { + implicit val pos = readPosition() + val tag = readByte() + + def bodyHack5(body: Tree, isStat: Boolean): Tree = { + if (!hacks.use5) { + body + } else { + /* #4442 and #4601: Patch Labeled, If, Match and TryCatch nodes in + * statement position to have type NoType. These 4 nodes are the + * control structures whose result type is explicitly specified (and + * not derived from their children like Block or TryFinally, or + * constant like While). + */ + new Transformers.Transformer { + override def transform(tree: Tree, isStat: Boolean): Tree = { + val newTree = super.transform(tree, isStat) + if (isStat && newTree.tpe != NoType) { + newTree match { + case Labeled(label, _, body) => + Labeled(label, NoType, body)(newTree.pos) + case If(cond, thenp, elsep) => + If(cond, thenp, elsep)(NoType)(newTree.pos) + case Match(selector, cases, default) => + Match(selector, cases, default)(NoType)(newTree.pos) + case TryCatch(block, errVar, errVarOriginalName, handler) => + TryCatch(block, errVar, errVarOriginalName, handler)(NoType)(newTree.pos) + case _ => + newTree + } + } else { + newTree + } + } + }.transform(body, isStat) + } + } + + def bodyHack5Expr(body: Tree): Tree = bodyHack5(body, isStat = false) + + (tag: @switch) match { + case TagFieldDef => + val flags = MemberFlags.fromBits(readInt()) + val name = readFieldIdent() + val originalName = readOriginalName() + + val ftpe0 = readType() + val ftpe = if (hacks.use4 && ftpe0 == NothingType) { + /* Note [Nothing FieldDef rewrite] + * val field: nothing --> val field: null + */ + NullType + } else { + ftpe0 + } + + FieldDef(flags, name, originalName, ftpe) + + case TagJSFieldDef => + JSFieldDef(MemberFlags.fromBits(readInt()), readTree(), readType()) + + case TagMethodDef => + val optHash = readOptHash() + // read and discard the length + val len = readInt() + assert(len >= 0) + + val flags = MemberFlags.fromBits(readInt()) + + val name = { + /* In versions 1.0 and 1.1 of the IR, static initializers and + * class initializers were conflated into one concept, which was + * handled differently in the linker based on whether the owner + * was a JS type or not. They were serialized as ``. + * Starting with 1.2, `` is only for class initializers. + * If we read a definition for a `` in a non-JS type, we + * rewrite it as a static initializers instead (``). + */ + val name0 = readMethodIdent() + if (hacks.use1 && + name0.name == ClassInitializerName && + !ownerKind.isJSType) { + MethodIdent(StaticInitializerName)(name0.pos) + } else { + name0 + } + } + + val originalName = readOriginalName() + val args = readParamDefs() + val resultType = readType() + val body = readOptTree() + val optimizerHints = OptimizerHints.fromBits(readInt()) + + if (hacks.use0 && + flags.namespace == MemberNamespace.Public && + owner == HackNames.SystemModule && + name.name == HackNames.identityHashCodeName) { + /* #3976: 1.0 javalib relied on wrong linker dispatch. + * We simply replace it with a correct implementation. + */ + assert(args.size == 1) + + val patchedBody = Some(IdentityHashCode(args(0).ref)) + val patchedOptimizerHints = OptimizerHints.empty.withInline(true) + + MethodDef(flags, name, originalName, args, resultType, patchedBody)( + patchedOptimizerHints, optHash) + } else if (hacks.use4 && + flags.namespace == MemberNamespace.Public && + owner == ObjectClass && + name.name == HackNames.cloneName) { + /* #4391: In version 1.5, we introduced a dedicated IR node for the + * primitive operation behind `Object.clone()`. This allowed to + * simplify the linker by removing several special-cases that + * treated it specially (for example, preventing it from being + * inlined if the receiver could be an array). The simplifications + * mean that the old implementation is not valid anymore, and so we + * must force using the new implementation if we read IR from an + * older version. + */ + assert(args.isEmpty) + + val thisValue = This()(ClassType(ObjectClass)) + val cloneableClassType = ClassType(CloneableClass) + + val patchedBody = Some { + If(IsInstanceOf(thisValue, cloneableClassType), + Clone(AsInstanceOf(thisValue, cloneableClassType)), + Throw(New( + HackNames.CloneNotSupportedExceptionClass, + MethodIdent(NoArgConstructorName), + Nil)))(cloneableClassType) + } + val patchedOptimizerHints = OptimizerHints.empty.withInline(true) + + MethodDef(flags, name, originalName, args, resultType, patchedBody)( + patchedOptimizerHints, optHash) + } else { + val patchedBody = body.map(bodyHack5(_, isStat = resultType == NoType)) + MethodDef(flags, name, originalName, args, resultType, patchedBody)( + optimizerHints, optHash) + } + + case TagJSConstructorDef => + val optHash = readOptHash() + // read and discard the length + val len = readInt() + assert(len >= 0) + + /* JSConstructorDef was introduced in 1.11. Therefore, by + * construction, they never need the body hack of 1.5. + */ + + val flags = MemberFlags.fromBits(readInt()) + val (params, restParam) = readParamDefsWithRest() + val bodyPos = readPosition() + val beforeSuper = readTrees() + val superCall = readTree().asInstanceOf[JSSuperConstructorCall] + val afterSuper = readTrees() + val body = JSConstructorBody(beforeSuper, superCall, afterSuper)(bodyPos) + JSConstructorDef(flags, params, restParam, body)( + OptimizerHints.fromBits(readInt()), optHash) + + case TagJSMethodDef => + val optHash = readOptHash() + // read and discard the length + val len = readInt() + assert(len >= 0) + + val flags = MemberFlags.fromBits(readInt()) + val name = bodyHack5Expr(readTree()) + val (params, restParam) = readParamDefsWithRest() + val body = bodyHack5Expr(readTree()) + JSMethodDef(flags, name, params, restParam, body)( + OptimizerHints.fromBits(readInt()), optHash) + + case TagJSPropertyDef => + val flags = MemberFlags.fromBits(readInt()) + val name = bodyHack5Expr(readTree()) + val getterBody = readOptTree().map(bodyHack5Expr(_)) + val setterArgAndBody = { + if (readBoolean()) + Some((readParamDef(), bodyHack5Expr(readTree()))) + else + None + } + JSPropertyDef(flags, name, getterBody, setterArgAndBody) + + case TagJSNativeMemberDef => + val flags = MemberFlags.fromBits(readInt()) + val name = readMethodIdent() + val jsNativeLoadSpec = readJSNativeLoadSpec().get + JSNativeMemberDef(flags, name, jsNativeLoadSpec) + } + } + + def readMemberDefs(owner: ClassName, ownerKind: ClassKind): List[MemberDef] = { + val memberDefs = List.fill(readInt())(readMemberDef(owner, ownerKind)) + + // #4409: Filter out abstract methods in non-native JS classes for version < 1.5 + if (ownerKind.isJSClass) { + if (hacks.use4) { + memberDefs.filter { m => + m match { + case MethodDef(_, _, _, _, _, None) => false + case _ => true + } + } + } else { + /* #4388 This check should be moved to a link-time check dependent on + * `checkIR`, but currently we only have the post-BaseLinker IR + * checker, at which points those methods have already been + * eliminated. + */ + for (m <- memberDefs) { + m match { + case MethodDef(_, _, _, _, _, None) => + throw new InvalidIRException(m, + "Invalid abstract method in non-native JS class") + case _ => + // ok + } + } + memberDefs + } + } else { + memberDefs + } + } + + def readTopLevelExportDef(owner: ClassName, + ownerKind: ClassKind): TopLevelExportDef = { + implicit val pos = readPosition() + val tag = readByte() + + def readJSMethodDef(): JSMethodDef = + readMemberDef(owner, ownerKind).asInstanceOf[JSMethodDef] + + def readModuleID(): String = + if (hacks.use2) DefaultModuleID + else readString() + + (tag: @switch) match { + case TagTopLevelJSClassExportDef => TopLevelJSClassExportDef(readModuleID(), readString()) + case TagTopLevelModuleExportDef => TopLevelModuleExportDef(readModuleID(), readString()) + case TagTopLevelMethodExportDef => TopLevelMethodExportDef(readModuleID(), readJSMethodDef()) + case TagTopLevelFieldExportDef => TopLevelFieldExportDef(readModuleID(), readString(), readFieldIdent()) + } + } + + def readTopLevelExportDefs(owner: ClassName, + ownerKind: ClassKind): List[TopLevelExportDef] = { + List.fill(readInt())(readTopLevelExportDef(owner, ownerKind)) + } + + def readLocalIdent(): LocalIdent = { + implicit val pos = readPosition() + LocalIdent(readLocalName()) + } + + def readLabelIdent(): LabelIdent = { + implicit val pos = readPosition() + LabelIdent(readLabelName()) + } + + def readFieldIdent(): FieldIdent = { + implicit val pos = readPosition() + FieldIdent(readFieldName()) + } + + def readMethodIdent(): MethodIdent = { + implicit val pos = readPosition() + MethodIdent(readMethodName()) + } + + def readClassIdent(): ClassIdent = { + implicit val pos = readPosition() + ClassIdent(readClassName()) + } + + def readClassIdents(): List[ClassIdent] = + List.fill(readInt())(readClassIdent()) + + def readOptClassIdent(): Option[ClassIdent] = { + if (readBoolean()) Some(readClassIdent()) + else None + } + + def readParamDef(): ParamDef = { + implicit val pos = readPosition() + val name = readLocalIdent() + val originalName = readOriginalName() + val ptpe = readType() + val mutable = readBoolean() + + if (hacks.use4) { + val rest = readBoolean() + assert(!rest, "Illegal rest parameter") + } + + ParamDef(name, originalName, ptpe, mutable) + } + + def readParamDefs(): List[ParamDef] = + List.fill(readInt())(readParamDef()) + + def readParamDefsWithRest(): (List[ParamDef], Option[ParamDef]) = { + if (hacks.use4) { + val (params, isRest) = List.fill(readInt()) { + implicit val pos = readPosition() + (ParamDef(readLocalIdent(), readOriginalName(), readType(), readBoolean()), readBoolean()) + }.unzip + + if (isRest.forall(!_)) { + (params, None) + } else { + assert(isRest.init.forall(!_), "illegal non-last rest parameter") + (params.init, Some(params.last)) + } + } else { + val params = readParamDefs() + + val restParam = + if (readBoolean()) Some(readParamDef()) + else None + + (params, restParam) + } + } + + def readType(): Type = { + val tag = readByte() + (tag: @switch) match { + case TagAnyType => AnyType + case TagNothingType => NothingType + case TagUndefType => UndefType + case TagBooleanType => BooleanType + case TagCharType => CharType + case TagByteType => ByteType + case TagShortType => ShortType + case TagIntType => IntType + case TagLongType => LongType + case TagFloatType => FloatType + case TagDoubleType => DoubleType + case TagStringType => StringType + case TagNullType => NullType + case TagNoType => NoType + + case TagClassType => ClassType(readClassName()) + case TagArrayType => ArrayType(readArrayTypeRef()) + + case TagRecordType => + RecordType(List.fill(readInt()) { + val name = readFieldName() + val originalName = readString() + val tpe = readType() + val mutable = readBoolean() + RecordType.Field(name, readOriginalName(), tpe, mutable) + }) + } + } + + def readTypeRef(): TypeRef = { + readByte() match { + case TagVoidRef => VoidRef + case TagBooleanRef => BooleanRef + case TagCharRef => CharRef + case TagByteRef => ByteRef + case TagShortRef => ShortRef + case TagIntRef => IntRef + case TagLongRef => LongRef + case TagFloatRef => FloatRef + case TagDoubleRef => DoubleRef + case TagNullRef => NullRef + case TagNothingRef => NothingRef + case TagClassRef => ClassRef(readClassName()) + case TagArrayTypeRef => readArrayTypeRef() + } + } + + def readArrayTypeRef(): ArrayTypeRef = + ArrayTypeRef(readTypeRef().asInstanceOf[NonArrayTypeRef], readInt()) + + def readApplyFlags(): ApplyFlags = + ApplyFlags.fromBits(readInt()) + + def readPosition(): Position = { + import PositionFormat._ + + val first = readByte() + + if (first == FormatNoPositionValue) { + Position.NoPosition + } else { + val result = if ((first & FormatFullMask) == FormatFullMaskValue) { + val file = files(readInt()) + val line = readInt() + val column = readInt() + Position(file, line, column) + } else { + assert(lastPosition != NoPosition, + "Position format error: first position must be full") + if ((first & Format1Mask) == Format1MaskValue) { + val columnDiff = first >> Format1Shift + Position(lastPosition.source, lastPosition.line, + lastPosition.column + columnDiff) + } else if ((first & Format2Mask) == Format2MaskValue) { + val lineDiff = first >> Format2Shift + val column = readByte() & 0xff // unsigned + Position(lastPosition.source, + lastPosition.line + lineDiff, column) + } else { + assert((first & Format3Mask) == Format3MaskValue, + s"Position format error: first byte $first does not match any format") + val lineDiff = readShort() + val column = readByte() & 0xff // unsigned + Position(lastPosition.source, + lastPosition.line + lineDiff, column) + } + } + lastPosition = result + result + } + } + + def readJSNativeLoadSpec(): Option[JSNativeLoadSpec] = { + def readGlobalSpec(): JSNativeLoadSpec.Global = + JSNativeLoadSpec.Global(readString(), readStrings()) + + def readImportSpec(): JSNativeLoadSpec.Import = + JSNativeLoadSpec.Import(readString(), readStrings()) + + (readByte(): @switch) match { + case TagJSNativeLoadSpecNone => + None + case TagJSNativeLoadSpecGlobal => + Some(readGlobalSpec()) + case TagJSNativeLoadSpecImport => + Some(readImportSpec()) + case TagJSNativeLoadSpecImportWithGlobalFallback => + Some(JSNativeLoadSpec.ImportWithGlobalFallback( + readImportSpec(), readGlobalSpec())) + } + } + + def readOptHash(): Option[TreeHash] = { + if (readBoolean()) { + val hash = new Array[Byte](20) + buf.get(hash) + Some(new TreeHash(hash)) + } else { + None + } + } + + def readString(): String = { + strings(readInt()) + } + + def readStrings(): List[String] = + List.fill(readInt())(readString()) + + private def readLocalName(): LocalName = { + val i = readInt() + val existing = localNames(i) + if (existing ne null) { + existing + } else { + val result = LocalName(encodedNames(i)) + localNames(i) = result + result + } + } + + private def readLabelName(): LabelName = { + val i = readInt() + val existing = labelNames(i) + if (existing ne null) { + existing + } else { + val result = LabelName(encodedNames(i)) + labelNames(i) = result + result + } + } + + private def readFieldName(): FieldName = { + val i = readInt() + val existing = fieldNames(i) + if (existing ne null) { + existing + } else { + val result = FieldName(encodedNames(i)) + fieldNames(i) = result + result + } + } + + private def readSimpleMethodName(): SimpleMethodName = { + val i = readInt() + val existing = simpleMethodNames(i) + if (existing ne null) { + existing + } else { + val result = SimpleMethodName(encodedNames(i)) + simpleMethodNames(i) = result + result + } + } + + private def readClassName(): ClassName = { + val i = readInt() + val existing = classNames(i) + if (existing ne null) { + existing + } else { + val result = ClassName(encodedNames(i)) + classNames(i) = result + result + } + } + + private def readMethodName(): MethodName = + methodNames(readInt()) + + def readOriginalName(): OriginalName = + if (readBoolean()) OriginalName(encodedNames(readInt())) + else OriginalName.NoOriginalName + + private def readBoolean() = buf.get() != 0 + private def readByte() = buf.get() + private def readChar() = buf.getChar() + private def readShort() = buf.getShort() + private def readInt() = buf.getInt() + private def readLong() = buf.getLong() + private def readFloat() = buf.getFloat() + private def readDouble() = buf.getDouble() + + private def readUTF(): String = { + // DataInput.readUTF for buffers. + + val length = buf.getShort() & 0xffff // unsigned + var res = "" + var i = 0 + + def badFormat(msg: String) = throw new UTFDataFormatException(msg) + + while (i < length) { + val a = buf.get() + + i += 1 + + val char = { + if ((a & 0x80) == 0x00) { // 0xxxxxxx + a.toChar + } else if ((a & 0xE0) == 0xC0 && i < length) { // 110xxxxx + val b = buf.get() + i += 1 + + if ((b & 0xC0) != 0x80) // 10xxxxxx + badFormat("Expected 2 bytes, found: %#02x (init: %#02x)".format(b, a)) + + (((a & 0x1F) << 6) | (b & 0x3F)).toChar + } else if ((a & 0xF0) == 0xE0 && i < length - 1) { // 1110xxxx + val b = buf.get() + val c = buf.get() + i += 2 + + if ((b & 0xC0) != 0x80) // 10xxxxxx + badFormat("Expected 3 bytes, found: %#02x (init: %#02x)".format(b, a)) + + if ((c & 0xC0) != 0x80) // 10xxxxxx + badFormat("Expected 3 bytes, found: %#02x, %#02x (init: %#02x)".format(b, c, a)) + + (((a & 0x0F) << 12) | ((b & 0x3F) << 6) | (c & 0x3F)).toChar + } else { + val rem = length - i + badFormat("Unexpected start of char: %#02x (%d bytes to go)".format(a, rem)) + } + } + + res += char + } + + res + } + } + + /** Hacks for backwards compatible deserializing. */ + private final class Hacks(sourceVersion: String) { + val use0: Boolean = sourceVersion == "1.0" + + val use1: Boolean = use0 || sourceVersion == "1.1" + + val use2: Boolean = use1 || sourceVersion == "1.2" + + private val use3: Boolean = use2 || sourceVersion == "1.3" + + val use4: Boolean = use3 || sourceVersion == "1.4" + + val use5: Boolean = use4 || sourceVersion == "1.5" + + private val use6: Boolean = use5 || sourceVersion == "1.6" + + private val use7: Boolean = use6 || sourceVersion == "1.7" + + val use8: Boolean = use7 || sourceVersion == "1.8" + } + + /** Names needed for hacks. */ + private object HackNames { + val CloneNotSupportedExceptionClass = + ClassName("java.lang.CloneNotSupportedException") + val SystemModule: ClassName = + ClassName("java.lang.System$") + + val cloneName: MethodName = + MethodName("clone", Nil, ClassRef(ObjectClass)) + val identityHashCodeName: MethodName = + MethodName("identityHashCode", List(ClassRef(ObjectClass)), IntRef) + } + + /* Note [Nothing FieldDef rewrite] + * + * Prior to Scala.js 1.5.0, the compiler back-end emitted `FieldDef`s with + * type `nothing` (`NothingType`). Until Scala.js 1.3.1, such fields happened + * to link by chance. Scala.js 1.4.0 changed the Emitter in a way that they + * did not link anymore (#4370), which broke some existing code. + * + * In Scala.js 1.5.0, we declared that such definitions are invalid IR, since + * fields need a zero value to initialize them, and `nothing` doesn't have + * one. + * + * To preserve backward binary compatibility of IR produced by earlier + * versions, we use the following rewrites as a deserialization hack: + * + * - `FieldDef`s with type `nothing` are rewritten with type `null`: + * val field: nothing --> val field: null + * - `Select`s with type `nothing` are rewritten with type `null`, but are + * then wrapped in a `throw` to preserve the well-typedness of the + * surrounding IR: + * qual.field[nothing] --> throw qual.field[null] + * - In an `Assign`, the inserted `throw` would be invalid. Therefore we have + * to unwrap the `throw`. The rhs being of type `nothing` (in IR that was + * originally well typed), it can be assigned to a field of type `null`. + * (throw qual.field[null]) = rhs --> qual.field[null] = rhs + */ +} diff --git a/ir/shared/src/main/scala/org/scalajs/ir/Tags.scala b/ir/shared/src/main/scala/org/scalajs/ir/Tags.scala new file mode 100644 index 0000000000..a084304571 --- /dev/null +++ b/ir/shared/src/main/scala/org/scalajs/ir/Tags.scala @@ -0,0 +1,196 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.ir + +/** Serialization and hashing tags for trees and types */ +private[ir] object Tags { + + // Tags for Trees + + /** Use to denote optional trees. */ + final val TagEmptyTree = 1 + + final val TagJSSpread = TagEmptyTree + 1 + + final val TagVarDef = TagJSSpread + 1 + + final val TagSkip = TagVarDef + 1 + final val TagBlock = TagSkip + 1 + final val TagLabeled = TagBlock + 1 + final val TagAssign = TagLabeled + 1 + final val TagReturn = TagAssign + 1 + final val TagIf = TagReturn + 1 + final val TagWhile = TagIf + 1 + final val TagDoWhile = TagWhile + 1 + final val TagForIn = TagDoWhile + 1 + final val TagTryCatch = TagForIn + 1 + final val TagTryFinally = TagTryCatch + 1 + final val TagThrow = TagTryFinally + 1 + final val TagMatch = TagThrow + 1 + final val TagDebugger = TagMatch + 1 + + final val TagNew = TagDebugger + 1 + final val TagLoadModule = TagNew + 1 + final val TagStoreModule = TagLoadModule + 1 + final val TagSelect = TagStoreModule + 1 + final val TagSelectStatic = TagSelect + 1 + final val TagApply = TagSelectStatic + 1 + final val TagApplyStatically = TagApply + 1 + final val TagApplyStatic = TagApplyStatically + 1 + final val TagUnaryOp = TagApplyStatic + 1 + final val TagBinaryOp = TagUnaryOp + 1 + final val TagNewArray = TagBinaryOp + 1 + final val TagArrayValue = TagNewArray + 1 + final val TagArrayLength = TagArrayValue + 1 + final val TagArraySelect = TagArrayLength + 1 + final val TagRecordValue = TagArraySelect + 1 + final val TagRecordSelect = TagRecordValue + 1 + final val TagIsInstanceOf = TagRecordSelect + 1 + final val TagAsInstanceOf = TagIsInstanceOf + 1 + final val TagGetClass = TagAsInstanceOf + 1 + + final val TagJSNew = TagGetClass + 1 + final val TagJSPrivateSelect = TagJSNew + 1 + final val TagJSSelect = TagJSPrivateSelect + 1 + final val TagJSFunctionApply = TagJSSelect + 1 + final val TagJSMethodApply = TagJSFunctionApply + 1 + final val TagJSSuperSelect = TagJSMethodApply + 1 + final val TagJSSuperMethodCall = TagJSSuperSelect + 1 + final val TagJSSuperConstructorCall = TagJSSuperMethodCall + 1 + final val TagJSImportCall = TagJSSuperConstructorCall + 1 + final val TagLoadJSConstructor = TagJSImportCall + 1 + final val TagLoadJSModule = TagLoadJSConstructor + 1 + final val TagJSDelete = TagLoadJSModule + 1 + final val TagJSUnaryOp = TagJSDelete + 1 + final val TagJSBinaryOp = TagJSUnaryOp + 1 + final val TagJSArrayConstr = TagJSBinaryOp + 1 + final val TagJSObjectConstr = TagJSArrayConstr + 1 + final val TagJSGlobalRef = TagJSObjectConstr + 1 + final val TagJSTypeOfGlobalRef = TagJSGlobalRef + 1 + final val TagJSLinkingInfo = TagJSTypeOfGlobalRef + 1 + + final val TagUndefined = TagJSLinkingInfo + 1 + final val TagNull = TagUndefined + 1 + final val TagBooleanLiteral = TagNull + 1 + final val TagCharLiteral = TagBooleanLiteral + 1 + final val TagByteLiteral = TagCharLiteral + 1 + final val TagShortLiteral = TagByteLiteral + 1 + final val TagIntLiteral = TagShortLiteral + 1 + final val TagLongLiteral = TagIntLiteral + 1 + final val TagFloatLiteral = TagLongLiteral + 1 + final val TagDoubleLiteral = TagFloatLiteral + 1 + final val TagStringLiteral = TagDoubleLiteral + 1 + final val TagClassOf = TagStringLiteral + 1 + + final val TagVarRef = TagClassOf + 1 + final val TagThis = TagVarRef + 1 + final val TagClosure = TagThis + 1 + final val TagCreateJSClass = TagClosure + 1 + + /* Note that there is no TagTransient, since transient nodes are never + * serialized nor hashed. + */ + + // New in 1.1 + + final val TagIdentityHashCode = TagCreateJSClass + 1 + final val TagSelectJSNativeMember = TagIdentityHashCode + 1 + + // New in 1.4 + + final val TagApplyDynamicImport = TagSelectJSNativeMember + 1 + + // New in 1.5 + + final val TagClone = TagApplyDynamicImport + 1 + + // New in 1.6 + + final val TagJSImportMeta = TagClone + 1 + + // New in 1.8 + + final val TagJSNewTarget = TagJSImportMeta + 1 + + // New in 1.11 + + final val TagWrapAsThrowable = TagJSNewTarget + 1 + final val TagUnwrapFromThrowable = TagWrapAsThrowable + 1 + + // Tags for member defs + + final val TagFieldDef = 1 + final val TagJSFieldDef = TagFieldDef + 1 + final val TagMethodDef = TagJSFieldDef + 1 + final val TagJSMethodDef = TagMethodDef + 1 + final val TagJSPropertyDef = TagJSMethodDef + 1 + + // New in 1.1 + + final val TagJSNativeMemberDef = TagJSPropertyDef + 1 + + // New in 1.11 + + final val TagJSConstructorDef = TagJSNativeMemberDef + 1 + + // Tags for top-level export defs + + final val TagTopLevelJSClassExportDef = 1 + final val TagTopLevelModuleExportDef = TagTopLevelJSClassExportDef + 1 + final val TagTopLevelMethodExportDef = TagTopLevelModuleExportDef + 1 + final val TagTopLevelFieldExportDef = TagTopLevelMethodExportDef + 1 + + // Tags for Types + + final val TagAnyType = 1 + final val TagNothingType = TagAnyType + 1 + final val TagUndefType = TagNothingType + 1 + final val TagBooleanType = TagUndefType + 1 + final val TagCharType = TagBooleanType + 1 + final val TagByteType = TagCharType + 1 + final val TagShortType = TagByteType + 1 + final val TagIntType = TagShortType + 1 + final val TagLongType = TagIntType + 1 + final val TagFloatType = TagLongType + 1 + final val TagDoubleType = TagFloatType + 1 + final val TagStringType = TagDoubleType + 1 + final val TagNullType = TagStringType + 1 + final val TagClassType = TagNullType + 1 + final val TagArrayType = TagClassType + 1 + final val TagRecordType = TagArrayType + 1 + final val TagNoType = TagRecordType + 1 + + // Tags for TypeRefs + + final val TagVoidRef = 1 + final val TagBooleanRef = TagVoidRef + 1 + final val TagCharRef = TagBooleanRef + 1 + final val TagByteRef = TagCharRef + 1 + final val TagShortRef = TagByteRef + 1 + final val TagIntRef = TagShortRef + 1 + final val TagLongRef = TagIntRef + 1 + final val TagFloatRef = TagLongRef + 1 + final val TagDoubleRef = TagFloatRef + 1 + final val TagNullRef = TagDoubleRef + 1 + final val TagNothingRef = TagNullRef + 1 + final val TagClassRef = TagNothingRef + 1 + final val TagArrayTypeRef = TagClassRef + 1 + + // Tags for JS native loading specs + + final val TagJSNativeLoadSpecNone = 0 + final val TagJSNativeLoadSpecGlobal = TagJSNativeLoadSpecNone + 1 + final val TagJSNativeLoadSpecImport = TagJSNativeLoadSpecGlobal + 1 + final val TagJSNativeLoadSpecImportWithGlobalFallback = TagJSNativeLoadSpecImport + 1 + +} diff --git a/ir/shared/src/main/scala/org/scalajs/ir/Transformers.scala b/ir/shared/src/main/scala/org/scalajs/ir/Transformers.scala new file mode 100644 index 0000000000..6f4820aab8 --- /dev/null +++ b/ir/shared/src/main/scala/org/scalajs/ir/Transformers.scala @@ -0,0 +1,310 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.ir + +import Trees._ +import Types._ + +object Transformers { + + abstract class Transformer { + final def transformStats(trees: List[Tree]): List[Tree] = + trees.map(transformStat(_)) + + final def transformStat(tree: Tree): Tree = + transform(tree, isStat = true) + + final def transformExpr(tree: Tree): Tree = + transform(tree, isStat = false) + + def transformExprOrJSSpread(tree: TreeOrJSSpread): TreeOrJSSpread = { + implicit val pos = tree.pos + + tree match { + case JSSpread(items) => JSSpread(transformExpr(items)) + case tree: Tree => transformExpr(tree) + } + } + + def transform(tree: Tree, isStat: Boolean): Tree = { + implicit val pos = tree.pos + + tree match { + // Definitions + + case VarDef(ident, originalName, vtpe, mutable, rhs) => + VarDef(ident, originalName, vtpe, mutable, transformExpr(rhs)) + + // Control flow constructs + + case Block(stats) => + Block(stats.init.map(transformStat) :+ transform(stats.last, isStat)) + + case Labeled(label, tpe, body) => + Labeled(label, tpe, transform(body, isStat)) + + case Assign(lhs, rhs) => + Assign(transformExpr(lhs).asInstanceOf[AssignLhs], transformExpr(rhs)) + + case Return(expr, label) => + Return(transformExpr(expr), label) + + case If(cond, thenp, elsep) => + If(transformExpr(cond), transform(thenp, isStat), + transform(elsep, isStat))(tree.tpe) + + case While(cond, body) => + While(transformExpr(cond), transformStat(body)) + + case DoWhile(body, cond) => + DoWhile(transformStat(body), transformExpr(cond)) + + case ForIn(obj, keyVar, keyVarOriginalName, body) => + ForIn(transformExpr(obj), keyVar, keyVarOriginalName, + transformStat(body)) + + case TryCatch(block, errVar, errVarOriginalName, handler) => + TryCatch(transform(block, isStat), errVar, errVarOriginalName, + transform(handler, isStat))(tree.tpe) + + case TryFinally(block, finalizer) => + TryFinally(transform(block, isStat), transformStat(finalizer)) + + case Throw(expr) => + Throw(transformExpr(expr)) + + case Match(selector, cases, default) => + Match(transformExpr(selector), + cases map (c => (c._1, transform(c._2, isStat))), + transform(default, isStat))(tree.tpe) + + // Scala expressions + + case New(className, ctor, args) => + New(className, ctor, args map transformExpr) + + case StoreModule(className, value) => + StoreModule(className, transformExpr(value)) + + case Select(qualifier, className, field) => + Select(transformExpr(qualifier), className, field)(tree.tpe) + + case Apply(flags, receiver, method, args) => + Apply(flags, transformExpr(receiver), method, + args map transformExpr)(tree.tpe) + + case ApplyStatically(flags, receiver, className, method, args) => + ApplyStatically(flags, transformExpr(receiver), className, method, + args map transformExpr)(tree.tpe) + + case ApplyStatic(flags, className, method, args) => + ApplyStatic(flags, className, method, args map transformExpr)(tree.tpe) + + case ApplyDynamicImport(flags, className, method, args) => + ApplyDynamicImport(flags, className, method, args.map(transformExpr)) + + case UnaryOp(op, lhs) => + UnaryOp(op, transformExpr(lhs)) + + case BinaryOp(op, lhs, rhs) => + BinaryOp(op, transformExpr(lhs), transformExpr(rhs)) + + case NewArray(tpe, lengths) => + NewArray(tpe, lengths map transformExpr) + + case ArrayValue(tpe, elems) => + ArrayValue(tpe, elems map transformExpr) + + case ArrayLength(array) => + ArrayLength(transformExpr(array)) + + case ArraySelect(array, index) => + ArraySelect(transformExpr(array), transformExpr(index))(tree.tpe) + + case RecordValue(tpe, elems) => + RecordValue(tpe, elems map transformExpr) + + case RecordSelect(record, field) => + RecordSelect(transformExpr(record), field)(tree.tpe) + + case IsInstanceOf(expr, testType) => + IsInstanceOf(transformExpr(expr), testType) + + case AsInstanceOf(expr, tpe) => + AsInstanceOf(transformExpr(expr), tpe) + + case GetClass(expr) => + GetClass(transformExpr(expr)) + + case Clone(expr) => + Clone(transformExpr(expr)) + + case IdentityHashCode(expr) => + IdentityHashCode(transformExpr(expr)) + + case WrapAsThrowable(expr) => + WrapAsThrowable(transformExpr(expr)) + + case UnwrapFromThrowable(expr) => + UnwrapFromThrowable(transformExpr(expr)) + + // JavaScript expressions + + case JSNew(ctor, args) => + JSNew(transformExpr(ctor), args.map(transformExprOrJSSpread)) + + case JSPrivateSelect(qualifier, className, field) => + JSPrivateSelect(transformExpr(qualifier), className, field) + + case JSSelect(qualifier, item) => + JSSelect(transformExpr(qualifier), transformExpr(item)) + + case JSFunctionApply(fun, args) => + JSFunctionApply(transformExpr(fun), args.map(transformExprOrJSSpread)) + + case JSMethodApply(receiver, method, args) => + JSMethodApply(transformExpr(receiver), transformExpr(method), + args.map(transformExprOrJSSpread)) + + case JSSuperSelect(superClass, qualifier, item) => + JSSuperSelect(superClass, transformExpr(qualifier), + transformExpr(item)) + + case JSSuperMethodCall(superClass, receiver, method, args) => + JSSuperMethodCall(superClass, transformExpr(receiver), + transformExpr(method), args.map(transformExprOrJSSpread)) + + case JSSuperConstructorCall(args) => + JSSuperConstructorCall(args.map(transformExprOrJSSpread)) + + case JSImportCall(arg) => + JSImportCall(transformExpr(arg)) + + case JSDelete(qualifier, item) => + JSDelete(transformExpr(qualifier), transformExpr(item)) + + case JSUnaryOp(op, lhs) => + JSUnaryOp(op, transformExpr(lhs)) + + case JSBinaryOp(op, lhs, rhs) => + JSBinaryOp(op, transformExpr(lhs), transformExpr(rhs)) + + case JSArrayConstr(items) => + JSArrayConstr(items.map(transformExprOrJSSpread)) + + case JSObjectConstr(fields) => + JSObjectConstr(fields.map { field => + (transformExpr(field._1), transformExpr(field._2)) + }) + + case JSTypeOfGlobalRef(globalRef) => + JSTypeOfGlobalRef(transformExpr(globalRef).asInstanceOf[JSGlobalRef]) + + // Atomic expressions + + case Closure(arrow, captureParams, params, restParam, body, captureValues) => + Closure(arrow, captureParams, params, restParam, transformExpr(body), + captureValues.map(transformExpr)) + + case CreateJSClass(className, captureValues) => + CreateJSClass(className, captureValues.map(transformExpr)) + + // Transients + case Transient(value) => + value.transform(this, isStat) + + // Trees that need not be transformed + + case _:Skip | _:Debugger | _:LoadModule | _:SelectStatic | _:SelectJSNativeMember | + _:LoadJSConstructor | _:LoadJSModule | _:JSNewTarget | _:JSImportMeta | + _:JSLinkingInfo | _:Literal | _:VarRef | _:This | _:JSGlobalRef => + tree + } + } + } + + abstract class ClassTransformer extends Transformer { + def transformClassDef(tree: ClassDef): ClassDef = { + import tree._ + ClassDef(name, originalName, kind, jsClassCaptures, superClass, + interfaces, jsSuperClass.map(transformExpr), jsNativeLoadSpec, + memberDefs.map(transformMemberDef), + topLevelExportDefs.map(transformTopLevelExportDef))( + tree.optimizerHints)(tree.pos) + } + + def transformMemberDef(memberDef: MemberDef): MemberDef = { + implicit val pos = memberDef.pos + + memberDef match { + case _:AnyFieldDef | _:JSNativeMemberDef => + memberDef + + case memberDef: MethodDef => + val MethodDef(flags, name, originalName, args, resultType, body) = memberDef + val newBody = body.map(transform(_, isStat = resultType == NoType)) + MethodDef(flags, name, originalName, args, resultType, newBody)( + memberDef.optimizerHints, None) + + case memberDef: JSConstructorDef => + val JSConstructorDef(flags, args, restParam, body) = memberDef + JSConstructorDef(flags, args, restParam, transformJSConstructorBody(body))( + memberDef.optimizerHints, None) + + case memberDef: JSMethodDef => + val JSMethodDef(flags, name, args, restParam, body) = memberDef + JSMethodDef(flags, name, args, restParam, transformExpr(body))( + memberDef.optimizerHints, None) + + case JSPropertyDef(flags, name, getterBody, setterArgAndBody) => + JSPropertyDef( + flags, + name, + getterBody.map(transformStat), + setterArgAndBody map { case (arg, body) => + (arg, transformStat(body)) + }) + } + } + + def transformJSConstructorBody(body: JSConstructorBody): JSConstructorBody = { + implicit val pos = body.pos + + val newBeforeSuper = body.beforeSuper.map(transformStat(_)) + val newSuperCall = transformStat(body.superCall).asInstanceOf[JSSuperConstructorCall] + val newAfterSuper = body.afterSuper match { + case stats :+ expr => stats.map(transformStat(_)) :+ transformExpr(expr) + case empty => empty // cannot use Nil here because the compiler does not know that it is exhaustive + } + + JSConstructorBody(newBeforeSuper, newSuperCall, newAfterSuper) + } + + def transformTopLevelExportDef( + exportDef: TopLevelExportDef): TopLevelExportDef = { + + implicit val pos = exportDef.pos + + exportDef match { + case _:TopLevelJSClassExportDef | _:TopLevelModuleExportDef | + _:TopLevelFieldExportDef => + exportDef + + case TopLevelMethodExportDef(moduleID, methodDef) => + TopLevelMethodExportDef(moduleID, + transformMemberDef(methodDef).asInstanceOf[JSMethodDef]) + } + } + } + +} diff --git a/ir/shared/src/main/scala/org/scalajs/ir/Traversers.scala b/ir/shared/src/main/scala/org/scalajs/ir/Traversers.scala new file mode 100644 index 0000000000..d202f6a4f2 --- /dev/null +++ b/ir/shared/src/main/scala/org/scalajs/ir/Traversers.scala @@ -0,0 +1,270 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.ir + +import Trees._ + +object Traversers { + + class Traverser { + def traverseTreeOrJSSpread(tree: TreeOrJSSpread): Unit = tree match { + case JSSpread(items) => traverse(items) + case tree: Tree => traverse(tree) + } + + def traverse(tree: Tree): Unit = tree match { + // Definitions + + case VarDef(_, _, _, _, rhs) => + traverse(rhs) + + // Control flow constructs + + case Block(stats) => + stats foreach traverse + + case Labeled(label, tpe, body) => + traverse(body) + + case Assign(lhs, rhs) => + traverse(lhs) + traverse(rhs) + + case Return(expr, label) => + traverse(expr) + + case If(cond, thenp, elsep) => + traverse(cond) + traverse(thenp) + traverse(elsep) + + case While(cond, body) => + traverse(cond) + traverse(body) + + case DoWhile(body, cond) => + traverse(body) + traverse(cond) + + case ForIn(obj, _, _, body) => + traverse(obj) + traverse(body) + + case TryCatch(block, _, _, handler) => + traverse(block) + traverse(handler) + + case TryFinally(block, finalizer) => + traverse(block) + traverse(finalizer) + + case Throw(expr) => + traverse(expr) + + case Match(selector, cases, default) => + traverse(selector) + cases foreach (c => (c._1 map traverse, traverse(c._2))) + traverse(default) + + // Scala expressions + + case New(_, _, args) => + args foreach traverse + + case StoreModule(_, value) => + traverse(value) + + case Select(qualifier, _, _) => + traverse(qualifier) + + case Apply(_, receiver, _, args) => + traverse(receiver) + args foreach traverse + + case ApplyStatically(_, receiver, _, _, args) => + traverse(receiver) + args foreach traverse + + case ApplyStatic(_, _, _, args) => + args foreach traverse + + case ApplyDynamicImport(_, _, _, args) => + args.foreach(traverse) + + case UnaryOp(op, lhs) => + traverse(lhs) + + case BinaryOp(op, lhs, rhs) => + traverse(lhs) + traverse(rhs) + + case NewArray(tpe, lengths) => + lengths foreach traverse + + case ArrayValue(tpe, elems) => + elems foreach traverse + + case ArrayLength(array) => + traverse(array) + + case ArraySelect(array, index) => + traverse(array) + traverse(index) + + case RecordValue(tpe, elems) => + elems foreach traverse + + case RecordSelect(record, field) => + traverse(record) + + case IsInstanceOf(expr, _) => + traverse(expr) + + case AsInstanceOf(expr, _) => + traverse(expr) + + case GetClass(expr) => + traverse(expr) + + case Clone(expr) => + traverse(expr) + + case IdentityHashCode(expr) => + traverse(expr) + + case WrapAsThrowable(expr) => + traverse(expr) + + case UnwrapFromThrowable(expr) => + traverse(expr) + + // JavaScript expressions + + case JSNew(ctor, args) => + traverse(ctor) + args.foreach(traverseTreeOrJSSpread) + + case JSPrivateSelect(qualifier, _, _) => + traverse(qualifier) + + case JSSelect(qualifier, item) => + traverse(qualifier) + traverse(item) + + case JSFunctionApply(fun, args) => + traverse(fun) + args.foreach(traverseTreeOrJSSpread) + + case JSMethodApply(receiver, method, args) => + traverse(receiver) + traverse(method) + args.foreach(traverseTreeOrJSSpread) + + case JSSuperSelect(superClass, qualifier, item) => + traverse(superClass) + traverse(qualifier) + traverse(item) + + case JSSuperMethodCall(superClass, receiver, method, args) => + traverse(superClass) + traverse(receiver) + traverse(method) + args.foreach(traverseTreeOrJSSpread) + + case JSSuperConstructorCall(args) => + args.foreach(traverseTreeOrJSSpread) + + case JSImportCall(arg) => + traverse(arg) + + case JSDelete(qualifier, item) => + traverse(qualifier) + traverse(item) + + case JSUnaryOp(op, lhs) => + traverse(lhs) + + case JSBinaryOp(op, lhs, rhs) => + traverse(lhs) + traverse(rhs) + + case JSArrayConstr(items) => + items.foreach(traverseTreeOrJSSpread) + + case JSObjectConstr(fields) => + for ((key, value) <- fields) { + traverse(key) + traverse(value) + } + + case JSTypeOfGlobalRef(globalRef) => + traverse(globalRef) + + // Atomic expressions + + case Closure(arrow, captureParams, params, restParam, body, captureValues) => + traverse(body) + captureValues.foreach(traverse) + + case CreateJSClass(_, captureValues) => + captureValues.foreach(traverse) + + // Transients + + case Transient(value) => + value.traverse(this) + + // Trees that need not be traversed + + case _:Skip | _:Debugger | _:LoadModule | _:SelectStatic | _:SelectJSNativeMember | + _:LoadJSConstructor | _:LoadJSModule | _:JSNewTarget | _:JSImportMeta | + _:JSLinkingInfo | _:Literal | _:VarRef | _:This | _:JSGlobalRef => + } + + def traverseClassDef(tree: ClassDef): Unit = { + tree.jsSuperClass.foreach(traverse) + tree.memberDefs.foreach(traverseMemberDef) + tree.topLevelExportDefs.foreach(traverseTopLevelExportDef) + } + + def traverseMemberDef(memberDef: MemberDef): Unit = { + memberDef match { + case _:AnyFieldDef | _:JSNativeMemberDef => + + case MethodDef(_, _, _, _, _, body) => + body.foreach(traverse) + + case JSConstructorDef(_, _, _, body) => + body.allStats.foreach(traverse) + + case JSMethodDef(_, _, _, _, body) => + traverse(body) + + case JSPropertyDef(_, _, getterBody, setterArgAndBody) => + getterBody.foreach(traverse) + setterArgAndBody.foreach(argAndBody => traverse(argAndBody._2)) + } + } + + def traverseTopLevelExportDef(exportDef: TopLevelExportDef): Unit = { + exportDef match { + case _:TopLevelJSClassExportDef | _:TopLevelModuleExportDef | + _:TopLevelFieldExportDef => + + case TopLevelMethodExportDef(_, methodDef) => + traverseMemberDef(methodDef) + } + } + } + +} diff --git a/ir/shared/src/main/scala/org/scalajs/ir/Trees.scala b/ir/shared/src/main/scala/org/scalajs/ir/Trees.scala new file mode 100644 index 0000000000..e454fdb196 --- /dev/null +++ b/ir/shared/src/main/scala/org/scalajs/ir/Trees.scala @@ -0,0 +1,1509 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.ir + +import scala.annotation.switch + +import Names._ +import OriginalName.NoOriginalName +import Position.NoPosition +import Types._ + +object Trees { + /* The case classes for IR Nodes are sealed instead of final because making + * them final triggers bugs with Scala 2.11.x and 2.12.{1-4}, in combination + * with their `implicit val pos`. + */ + + /** Base class for all nodes in the IR. + * + * Usually, one of the direct subclasses of `IRNode` should be used instead. + */ + abstract sealed class IRNode { + def pos: Position + + def show: String = { + val writer = new java.io.StringWriter + val printer = new Printers.IRTreePrinter(writer) + printer.printAnyNode(this) + writer.toString() + } + } + + /** Either a `Tree` or a `JSSpread`. + * + * This is the type of actual arguments to JS applications. + */ + sealed trait TreeOrJSSpread extends IRNode + + /** Node for a statement or expression in the IR. */ + abstract sealed class Tree extends IRNode with TreeOrJSSpread { + val tpe: Type + } + + // Identifiers + + sealed case class LocalIdent(name: LocalName)(implicit val pos: Position) + extends IRNode + + sealed case class LabelIdent(name: LabelName)(implicit val pos: Position) + extends IRNode + + sealed case class FieldIdent(name: FieldName)(implicit val pos: Position) + extends IRNode + + sealed case class MethodIdent(name: MethodName)(implicit val pos: Position) + extends IRNode + + sealed case class ClassIdent(name: ClassName)(implicit val pos: Position) + extends IRNode + + /** Tests whether the given name is a valid JavaScript identifier name. + * + * This test does *not* exclude keywords. + */ + def isJSIdentifierName(name: String): Boolean = { + // scalastyle:off return + /* This method is called in the constructor of some IR node classes, such + * as JSGlobalRef; it should be fast. + */ + val len = name.length() + if (len == 0) + return false + val c = name.charAt(0) + if (c != '$' && c != '_' && !Character.isUnicodeIdentifierStart(c)) + return false + var i = 1 + while (i != len) { + val c = name.charAt(i) + if (c != '$' && !Character.isUnicodeIdentifierPart(c)) + return false + i += 1 + } + true + // scalastyle:on return + } + + // Definitions + + sealed case class VarDef(name: LocalIdent, originalName: OriginalName, + vtpe: Type, mutable: Boolean, rhs: Tree)( + implicit val pos: Position) extends Tree { + val tpe = NoType // cannot be in expression position + + def ref(implicit pos: Position): VarRef = VarRef(name)(vtpe) + } + + sealed case class ParamDef(name: LocalIdent, originalName: OriginalName, + ptpe: Type, mutable: Boolean)( + implicit val pos: Position) extends IRNode { + def ref(implicit pos: Position): VarRef = VarRef(name)(ptpe) + } + + // Control flow constructs + + sealed case class Skip()(implicit val pos: Position) extends Tree { + val tpe = NoType // cannot be in expression position + } + + sealed class Block private (val stats: List[Tree])( + implicit val pos: Position) extends Tree { + val tpe = stats.last.tpe + + override def toString(): String = + stats.mkString("Block(", ",", ")") + } + + object Block { + def apply(stats: List[Tree])(implicit pos: Position): Tree = { + val flattenedStats = stats flatMap { + case Skip() => Nil + case Block(subStats) => subStats + case other => other :: Nil + } + flattenedStats match { + case Nil => Skip() + case only :: Nil => only + case _ => new Block(flattenedStats) + } + } + + def apply(stats: List[Tree], expr: Tree)(implicit pos: Position): Tree = + apply(stats :+ expr) + + def apply(stats: Tree*)(implicit pos: Position): Tree = + apply(stats.toList) + + def unapply(block: Block): Some[List[Tree]] = Some(block.stats) + } + + sealed case class Labeled(label: LabelIdent, tpe: Type, body: Tree)( + implicit val pos: Position) extends Tree + + sealed trait AssignLhs extends Tree + + sealed case class Assign(lhs: AssignLhs, rhs: Tree)( + implicit val pos: Position) extends Tree { + val tpe = NoType // cannot be in expression position + } + + sealed case class Return(expr: Tree, label: LabelIdent)( + implicit val pos: Position) extends Tree { + val tpe = NothingType + } + + sealed case class If(cond: Tree, thenp: Tree, elsep: Tree)(val tpe: Type)( + implicit val pos: Position) extends Tree + + sealed case class While(cond: Tree, body: Tree)( + implicit val pos: Position) extends Tree { + // cannot be in expression position, unless it is infinite + val tpe = cond match { + case BooleanLiteral(true) => NothingType + case _ => NoType + } + } + + sealed case class DoWhile(body: Tree, cond: Tree)( + implicit val pos: Position) extends Tree { + val tpe = NoType // cannot be in expression position + } + + sealed case class ForIn(obj: Tree, keyVar: LocalIdent, + keyVarOriginalName: OriginalName, body: Tree)( + implicit val pos: Position) extends Tree { + val tpe = NoType + } + + sealed case class TryCatch(block: Tree, errVar: LocalIdent, + errVarOriginalName: OriginalName, handler: Tree)( + val tpe: Type)(implicit val pos: Position) extends Tree + + sealed case class TryFinally(block: Tree, finalizer: Tree)( + implicit val pos: Position) extends Tree { + val tpe = block.tpe + } + + sealed case class Throw(expr: Tree)(implicit val pos: Position) extends Tree { + val tpe = NothingType + } + + /** A break-free switch (without fallthrough behavior). + * + * Unlike a JavaScript switch, it can be used in expression position. + * It supports alternatives explicitly (hence the `List[MatchableLiteral]` + * in cases), whereas in a switch one would use the fallthrough behavior to + * implement alternatives. + * (This is not a pattern matching construct like in Scala.) + * + * The selector must be either an `int` (`IntType`) or a `java.lang.String`. + * The cases can be any `MatchableLiteral`, even if they do not make sense + * for the type of the selecter (they simply will never match). + * + * Because `+0.0 === -0.0` in JavaScript, and because those semantics are + * used in a JS `switch`, we have to prevent the selector from ever being + * `-0.0`. Otherwise, it would be matched by a `case IntLiteral(0)`. At the + * same time, we must allow at least `int` and `java.lang.String` to support + * all switchable `match`es from Scala. Since the latter two have no common + * super type that does not allow `-0.0`, we really have to special-case + * those two types. + * + * This is also why we restrict `MatchableLiteral`s to `IntLiteral`, + * `StringLiteral` and `Null`. Allowing more cases would only make IR + * checking more complicated, without bringing any added value. + */ + sealed case class Match(selector: Tree, cases: List[(List[MatchableLiteral], Tree)], + default: Tree)(val tpe: Type)(implicit val pos: Position) extends Tree + + sealed case class Debugger()(implicit val pos: Position) extends Tree { + val tpe = NoType // cannot be in expression position + } + + // Scala expressions + + sealed case class New(className: ClassName, ctor: MethodIdent, + args: List[Tree])( + implicit val pos: Position) extends Tree { + val tpe = ClassType(className) + } + + sealed case class LoadModule(className: ClassName)( + implicit val pos: Position) extends Tree { + val tpe = ClassType(className) + } + + sealed case class StoreModule(className: ClassName, value: Tree)( + implicit val pos: Position) extends Tree { + val tpe = NoType // cannot be in expression position + } + + sealed case class Select(qualifier: Tree, className: ClassName, + field: FieldIdent)( + val tpe: Type)( + implicit val pos: Position) extends AssignLhs + + sealed case class SelectStatic(className: ClassName, field: FieldIdent)( + val tpe: Type)( + implicit val pos: Position) extends AssignLhs + + sealed case class SelectJSNativeMember(className: ClassName, member: MethodIdent)( + implicit val pos: Position) + extends Tree { + val tpe = AnyType + } + + /** Apply an instance method with dynamic dispatch (the default). */ + sealed case class Apply(flags: ApplyFlags, receiver: Tree, method: MethodIdent, + args: List[Tree])( + val tpe: Type)(implicit val pos: Position) extends Tree + + /** Apply an instance method with static dispatch (e.g., super calls). */ + sealed case class ApplyStatically(flags: ApplyFlags, receiver: Tree, + className: ClassName, method: MethodIdent, args: List[Tree])( + val tpe: Type)(implicit val pos: Position) extends Tree + + /** Apply a static method. */ + sealed case class ApplyStatic(flags: ApplyFlags, className: ClassName, + method: MethodIdent, args: List[Tree])( + val tpe: Type)(implicit val pos: Position) extends Tree + + /** Apply a static method via dynamic import. */ + sealed case class ApplyDynamicImport(flags: ApplyFlags, className: ClassName, + method: MethodIdent, args: List[Tree])( + implicit val pos: Position) extends Tree { + val tpe = AnyType + } + + /** Unary operation (always preserves pureness). */ + sealed case class UnaryOp(op: UnaryOp.Code, lhs: Tree)( + implicit val pos: Position) extends Tree { + + val tpe = UnaryOp.resultTypeOf(op) + } + + object UnaryOp { + /** Codes are raw Ints to be able to write switch matches on them. */ + type Code = Int + + final val Boolean_! = 1 + + // Widening conversions + final val CharToInt = 2 + final val ByteToInt = 3 + final val ShortToInt = 4 + final val IntToLong = 5 + final val IntToDouble = 6 + final val FloatToDouble = 7 + + // Narrowing conversions + final val IntToChar = 8 + final val IntToByte = 9 + final val IntToShort = 10 + final val LongToInt = 11 + final val DoubleToInt = 12 + final val DoubleToFloat = 13 + + // Long <-> Double (neither widening nor narrowing) + final val LongToDouble = 14 + final val DoubleToLong = 15 + + // Long -> Float (neither widening nor narrowing), introduced in 1.6 + final val LongToFloat = 16 + + // String.length, introduced in 1.11 + final val String_length = 17 + + def resultTypeOf(op: Code): Type = (op: @switch) match { + case Boolean_! => + BooleanType + case IntToChar => + CharType + case IntToByte => + ByteType + case IntToShort => + ShortType + case CharToInt | ByteToInt | ShortToInt | LongToInt | DoubleToInt | String_length => + IntType + case IntToLong | DoubleToLong => + LongType + case DoubleToFloat | LongToFloat => + FloatType + case IntToDouble | LongToDouble | FloatToDouble => + DoubleType + } + } + + /** Binary operation (always preserves pureness). */ + sealed case class BinaryOp(op: BinaryOp.Code, lhs: Tree, rhs: Tree)( + implicit val pos: Position) extends Tree { + + val tpe = BinaryOp.resultTypeOf(op) + } + + object BinaryOp { + /** Codes are raw Ints to be able to write switch matches on them. */ + type Code = Int + + final val === = 1 + final val !== = 2 + + final val String_+ = 3 + + final val Boolean_== = 4 + final val Boolean_!= = 5 + final val Boolean_| = 6 + final val Boolean_& = 7 + + final val Int_+ = 8 + final val Int_- = 9 + final val Int_* = 10 + final val Int_/ = 11 + final val Int_% = 12 + + final val Int_| = 13 + final val Int_& = 14 + final val Int_^ = 15 + final val Int_<< = 16 + final val Int_>>> = 17 + final val Int_>> = 18 + + final val Int_== = 19 + final val Int_!= = 20 + final val Int_< = 21 + final val Int_<= = 22 + final val Int_> = 23 + final val Int_>= = 24 + + final val Long_+ = 25 + final val Long_- = 26 + final val Long_* = 27 + final val Long_/ = 28 + final val Long_% = 29 + + final val Long_| = 30 + final val Long_& = 31 + final val Long_^ = 32 + final val Long_<< = 33 + final val Long_>>> = 34 + final val Long_>> = 35 + + final val Long_== = 36 + final val Long_!= = 37 + final val Long_< = 38 + final val Long_<= = 39 + final val Long_> = 40 + final val Long_>= = 41 + + final val Float_+ = 42 + final val Float_- = 43 + final val Float_* = 44 + final val Float_/ = 45 + final val Float_% = 46 + + final val Double_+ = 47 + final val Double_- = 48 + final val Double_* = 49 + final val Double_/ = 50 + final val Double_% = 51 + + final val Double_== = 52 + final val Double_!= = 53 + final val Double_< = 54 + final val Double_<= = 55 + final val Double_> = 56 + final val Double_>= = 57 + + // New in 1.11 + final val String_charAt = 58 + + def resultTypeOf(op: Code): Type = (op: @switch) match { + case === | !== | + Boolean_== | Boolean_!= | Boolean_| | Boolean_& | + Int_== | Int_!= | Int_< | Int_<= | Int_> | Int_>= | + Long_== | Long_!= | Long_< | Long_<= | Long_> | Long_>= | + Double_== | Double_!= | Double_< | Double_<= | Double_> | Double_>= => + BooleanType + case String_+ => + StringType + case Int_+ | Int_- | Int_* | Int_/ | Int_% | + Int_| | Int_& | Int_^ | Int_<< | Int_>>> | Int_>> => + IntType + case Long_+ | Long_- | Long_* | Long_/ | Long_% | + Long_| | Long_& | Long_^ | Long_<< | Long_>>> | Long_>> => + LongType + case Float_+ | Float_- | Float_* | Float_/ | Float_% => + FloatType + case Double_+ | Double_- | Double_* | Double_/ | Double_% => + DoubleType + case String_charAt => + CharType + } + } + + sealed case class NewArray(typeRef: ArrayTypeRef, lengths: List[Tree])( + implicit val pos: Position) extends Tree { + val tpe = ArrayType(typeRef) + } + + sealed case class ArrayValue(typeRef: ArrayTypeRef, elems: List[Tree])( + implicit val pos: Position) extends Tree { + val tpe = ArrayType(typeRef) + } + + sealed case class ArrayLength(array: Tree)(implicit val pos: Position) + extends Tree { + val tpe = IntType + } + + sealed case class ArraySelect(array: Tree, index: Tree)(val tpe: Type)( + implicit val pos: Position) extends AssignLhs + + sealed case class RecordValue(tpe: RecordType, elems: List[Tree])( + implicit val pos: Position) extends Tree + + sealed case class RecordSelect(record: Tree, field: FieldIdent)( + val tpe: Type)( + implicit val pos: Position) + extends AssignLhs + + sealed case class IsInstanceOf(expr: Tree, testType: Type)( + implicit val pos: Position) + extends Tree { + val tpe = BooleanType + } + + sealed case class AsInstanceOf(expr: Tree, tpe: Type)( + implicit val pos: Position) + extends Tree + + sealed case class GetClass(expr: Tree)(implicit val pos: Position) + extends Tree { + val tpe = ClassType(ClassClass) + } + + sealed case class Clone(expr: Tree)(implicit val pos: Position) + extends Tree { + val tpe: Type = expr.tpe // this is OK because our type system does not have singleton types + } + + sealed case class IdentityHashCode(expr: Tree)(implicit val pos: Position) + extends Tree { + val tpe = IntType + } + + sealed case class WrapAsThrowable(expr: Tree)(implicit val pos: Position) + extends Tree { + val tpe = ClassType(ThrowableClass) + } + + sealed case class UnwrapFromThrowable(expr: Tree)(implicit val pos: Position) + extends Tree { + val tpe = AnyType + } + + // JavaScript expressions + + sealed case class JSNew(ctor: Tree, args: List[TreeOrJSSpread])( + implicit val pos: Position) extends Tree { + val tpe = AnyType + } + + sealed case class JSPrivateSelect(qualifier: Tree, className: ClassName, + field: FieldIdent)( + implicit val pos: Position) extends AssignLhs { + val tpe = AnyType + } + + sealed case class JSSelect(qualifier: Tree, item: Tree)( + implicit val pos: Position) extends AssignLhs { + val tpe = AnyType + } + + sealed case class JSFunctionApply(fun: Tree, args: List[TreeOrJSSpread])( + implicit val pos: Position) extends Tree { + val tpe = AnyType + } + + sealed case class JSMethodApply(receiver: Tree, method: Tree, + args: List[TreeOrJSSpread])(implicit val pos: Position) extends Tree { + val tpe = AnyType + } + + /** Selects a property inherited from the given `superClass` on `receiver`. + * + * Given the non-native JS classes + * + * {{{ + * class Bar extends js.Object + * class Foo extends Bar + * }}} + * + * The node + * + * {{{ + * JSSuperBrackerSelect(LoadJSConstructor(ClassName("Bar")), qualifier, item) + * }}} + * + * which is printed as + * + * {{{ + * super(constructorOf[Bar])::qualifier[item] + * }}} + * + * has the semantics of an ES6 super reference + * + * {{{ + * super[item] + * }}} + * + * as if it were in an instance method of `Foo` with `qualifier` as the + * `this` value. + */ + sealed case class JSSuperSelect(superClass: Tree, receiver: Tree, item: Tree)( + implicit val pos: Position) extends AssignLhs { + val tpe = AnyType + } + + /** Calls a method inherited from the given `superClass` on `receiver`. + * + * Intuitively, this corresponds to + * + * {{{ + * superClass.prototype[method].call(receiver, ...args) + * }}} + * + * but retains more structure at the IR level than using an explicit + * encoding of the above expression. + * + * Given the non-native JS classes + * + * {{{ + * class Bar extends js.Object + * class Foo extends Bar + * }}} + * + * The node + * + * {{{ + * JSSuperBrackerCall(LoadJSConstructor(ClassName("Bar")), receiver, method, args) + * }}} + * + * which is printed as + * + * {{{ + * super(constructorOf[Bar])::receiver[method](...args) + * }}} + * + * has the following semantics: + * + * {{{ + * Bar.prototype[method].call(receiver, ...args) + * }}} + * + * If this happens to be located in an instance method of `Foo`, *and* + * `receiver` happens to be `This()`, this is equivalent to the ES6 + * statement + * + * {{{ + * super[method](...args) + * }}} + */ + sealed case class JSSuperMethodCall(superClass: Tree, receiver: Tree, + method: Tree, args: List[TreeOrJSSpread])( + implicit val pos: Position) + extends Tree { + val tpe = AnyType + } + + /** Super constructor call in the constructor of a non-native JS class. + * + * Exactly one such node must appear in the constructor of a + * non-native JS class, at the top-level (possibly as a direct child + * of a top-level `Block`). Any other use of this node is invalid. + * + * Statements before this node, as well as the `args`, cannot contain any + * `This()` node. Statements after this node can use `This()`. + * + * After the execution of this node, it is guaranteed that all fields + * declared in the current class have been created and initialized. Up to + * that point, accessing any field declared in this class (e.g., through an + * overridden method called from the super constructor) is undefined + * behavior. + * + * All in all, the shape of a constructor is therefore: + * + * {{{ + * { + * statementsNotUsingThis(); + * JSSuperConstructorCall(...argsNotUsingThis); + * statementsThatMayUseThis() + * } + * }}} + * + * which currently translates to something of the following shape: + * + * {{{ + * { + * statementsNotUsingThis(); + * super(...argsNotUsingThis); + * this.privateField1 = 0; + * this["publicField2"] = false; + * statementsThatMayUseThis() + * } + * }}} + */ + sealed case class JSSuperConstructorCall(args: List[TreeOrJSSpread])( + implicit val pos: Position) extends Tree { + val tpe = NoType + } + + /** JavaScript dynamic import of the form `import(arg)`. + * + * This form is its own node, rather than using something like + * {{{ + * JSFunctionApply(JSImport()) + * }}} + * because `import` is not a first-class term in JavaScript. + * `ImportCall` is a dedicated syntactic form that cannot be + * dissociated. + */ + sealed case class JSImportCall(arg: Tree)(implicit val pos: Position) + extends Tree { + val tpe = AnyType // it is a JavaScript Promise + } + + /** JavaScript meta-property `new.target`. + * + * This form is its own node, rather than using something like + * {{{ + * JSSelect(JSNew(), StringLiteral("target")) + * }}} + * because `new` is not a first-class term in JavaScript. `new.target` + * is a dedicated syntactic form that cannot be dissociated. + */ + sealed case class JSNewTarget()(implicit val pos: Position) extends Tree { + val tpe = AnyType + } + + /** JavaScript meta-property `import.meta`. + * + * This form is its own node, rather than using something like + * {{{ + * JSSelect(JSImport(), StringLiteral("meta")) + * }}} + * because `import` is not a first-class term in JavaScript. `import.meta` + * is a dedicated syntactic form that cannot be dissociated. + */ + sealed case class JSImportMeta()(implicit val pos: Position) extends Tree { + val tpe = AnyType + } + + /** Loads the constructor of a JS class (native or not). + * + * `className` must represent a non-trait JS class (native or not). + * + * This is used typically to instantiate a JS class, and most importantly + * if it is a non-native JS class. Given the class + * + * {{{ + * class Foo(x: Int) extends js.Object + * }}} + * + * The instantiation `new Foo(1)` would be represented as + * + * {{{ + * JSNew(LoadJSConstructor(ClassName("Foo")), List(IntLiteral(1))) + * }}} + * + * This node is also useful to encode `o.isInstanceOf[Foo]`: + * + * {{{ + * JSBinaryOp(instanceof, o, LoadJSConstructor(ClassName("Foo"))) + * }}} + * + * If `Foo` is non-native, the presence of this node makes it instantiable, + * and therefore reachable. + */ + sealed case class LoadJSConstructor(className: ClassName)( + implicit val pos: Position) extends Tree { + val tpe = AnyType + } + + /** Like [[LoadModule]] but for a JS module class. */ + sealed case class LoadJSModule(className: ClassName)( + implicit val pos: Position) extends Tree { + val tpe = AnyType + } + + /** `...items`, the "spread" operator of ECMAScript 6. + * + * @param items An Array whose items will be spread (not an arbitrary iterable) + */ + sealed case class JSSpread(items: Tree)(implicit val pos: Position) + extends IRNode with TreeOrJSSpread + + /** `delete qualifier[item]` */ + sealed case class JSDelete(qualifier: Tree, item: Tree)( + implicit val pos: Position) + extends Tree { + + val tpe = NoType // cannot be in expression position + } + + /** Unary operation (always preserves pureness). + * + * Operations which do not preserve pureness are not allowed in this tree. + * These are notably ++ and -- + */ + sealed case class JSUnaryOp(op: JSUnaryOp.Code, lhs: Tree)( + implicit val pos: Position) extends Tree { + val tpe = JSUnaryOp.resultTypeOf(op) + } + + object JSUnaryOp { + /** Codes are raw Ints to be able to write switch matches on them. */ + type Code = Int + + final val + = 1 + final val - = 2 + final val ~ = 3 + final val ! = 4 + + final val typeof = 5 + + def resultTypeOf(op: Code): Type = + AnyType + } + + /** Binary operation (always preserves pureness). + * + * Operations which do not preserve pureness are not allowed in this tree. + * These are notably +=, -=, *=, /= and %= + */ + sealed case class JSBinaryOp(op: JSBinaryOp.Code, lhs: Tree, rhs: Tree)( + implicit val pos: Position) extends Tree { + val tpe = JSBinaryOp.resultTypeOf(op) + } + + object JSBinaryOp { + /** Codes are raw Ints to be able to write switch matches on them. */ + type Code = Int + + final val === = 1 + final val !== = 2 + + final val + = 3 + final val - = 4 + final val * = 5 + final val / = 6 + final val % = 7 + + final val | = 8 + final val & = 9 + final val ^ = 10 + final val << = 11 + final val >> = 12 + final val >>> = 13 + + final val < = 14 + final val <= = 15 + final val > = 16 + final val >= = 17 + + final val && = 18 + final val || = 19 + + final val in = 20 + final val instanceof = 21 + + // New in 1.12 + final val ** = 22 + + def resultTypeOf(op: Code): Type = op match { + case === | !== => + /* We assume that ECMAScript will never pervert `===` and `!==` to the + * point of them not returning a primitive boolean. This is important + * for the trees resulting from optimizing `BinaryOp.===` into + * `JSBinaryOp.===` to be well-typed. + */ + BooleanType + case _ => + AnyType + } + } + + sealed case class JSArrayConstr(items: List[TreeOrJSSpread])( + implicit val pos: Position) extends Tree { + val tpe = AnyType + } + + sealed case class JSObjectConstr(fields: List[(Tree, Tree)])( + implicit val pos: Position) extends Tree { + val tpe = AnyType + } + + sealed case class JSGlobalRef(name: String)( + implicit val pos: Position) extends AssignLhs { + import JSGlobalRef._ + + val tpe = AnyType + + require(isValidJSGlobalRefName(name), + s"`$name` is not a valid global ref name") + } + + object JSGlobalRef { + /** Set of identifier names that can never be accessed from the global + * scope. + * + * This set includes and is limited to: + * + * - All ECMAScript 2015 keywords; + * - Identifier names that are treated as keywords or reserved identifier + * names in ECMAScript 2015 Strict Mode; + * - The identifier `arguments`, because any attempt to refer to it always + * refers to the magical `arguments` pseudo-array from the enclosing + * function, rather than a global variable. + * + * This set does *not* contain `await`, although it is a reserved word + * within ES modules. It used to be allowed before 1.11.0, and even + * browsers do not seem to reject it. For compatibility reasons, we only + * warn about it at compile time, but the IR allows it. + */ + final val ReservedJSIdentifierNames: Set[String] = Set( + "arguments", "break", "case", "catch", "class", "const", "continue", + "debugger", "default", "delete", "do", "else", "enum", "export", + "extends", "false", "finally", "for", "function", "if", "implements", + "import", "in", "instanceof", "interface", "let", "new", "null", + "package", "private", "protected", "public", "return", "static", + "super", "switch", "this", "throw", "true", "try", "typeof", "var", + "void", "while", "with", "yield" + ) + + /** Tests whether the given name is a valid name for a `JSGlobalRef`. + * + * A name is valid iff it is a JavaScript identifier name (see + * [[isJSIdentifierName]]) *and* it is not reserved (see + * [[ReservedJSIdentifierNames]]). + */ + def isValidJSGlobalRefName(name: String): Boolean = + isJSIdentifierName(name) && !ReservedJSIdentifierNames.contains(name) + } + + sealed case class JSTypeOfGlobalRef(globalRef: JSGlobalRef)( + implicit val pos: Position) extends Tree { + val tpe = AnyType + } + + sealed case class JSLinkingInfo()(implicit val pos: Position) extends Tree { + val tpe = AnyType + } + + // Literals + + /** Marker for literals. Literals are always pure. */ + sealed trait Literal extends Tree + + /** Marker for literals that can be used in a [[Match]] case. + * + * Matchable literals are: + * + * - `IntLiteral` + * - `StringLiteral` + * - `Null` + * + * See [[Match]] for the rationale about that specific set. + */ + sealed trait MatchableLiteral extends Literal + + sealed case class Undefined()(implicit val pos: Position) extends Literal { + val tpe = UndefType + } + + sealed case class Null()(implicit val pos: Position) extends MatchableLiteral { + val tpe = NullType + } + + sealed case class BooleanLiteral(value: Boolean)( + implicit val pos: Position) extends Literal { + val tpe = BooleanType + } + + sealed case class CharLiteral(value: Char)( + implicit val pos: Position) extends Literal { + val tpe = CharType + } + + sealed case class ByteLiteral(value: Byte)( + implicit val pos: Position) extends Literal { + val tpe = ByteType + } + + sealed case class ShortLiteral(value: Short)( + implicit val pos: Position) extends Literal { + val tpe = ShortType + } + + sealed case class IntLiteral(value: Int)( + implicit val pos: Position) extends MatchableLiteral { + val tpe = IntType + } + + sealed case class LongLiteral(value: Long)( + implicit val pos: Position) extends Literal { + val tpe = LongType + } + + sealed case class FloatLiteral(value: Float)( + implicit val pos: Position) extends Literal { + val tpe = FloatType + } + + sealed case class DoubleLiteral(value: Double)( + implicit val pos: Position) extends Literal { + val tpe = DoubleType + } + + sealed case class StringLiteral(value: String)( + implicit val pos: Position) extends MatchableLiteral { + val tpe = StringType + } + + sealed case class ClassOf(typeRef: TypeRef)( + implicit val pos: Position) extends Literal { + val tpe = ClassType(ClassClass) + } + + // Atomic expressions + + sealed case class VarRef(ident: LocalIdent)(val tpe: Type)( + implicit val pos: Position) extends AssignLhs + + sealed case class This()(val tpe: Type)(implicit val pos: Position) + extends Tree + + /** Closure with explicit captures. + * + * @param arrow + * If `true`, the closure is an Arrow Function (`=>`), which does not have + * an `this` parameter, and cannot be constructed (called with `new`). + * If `false`, it is a regular Function (`function`). + */ + sealed case class Closure(arrow: Boolean, captureParams: List[ParamDef], + params: List[ParamDef], restParam: Option[ParamDef], body: Tree, + captureValues: List[Tree])( + implicit val pos: Position) extends Tree { + val tpe = AnyType + } + + /** Creates a JavaScript class value. + * + * @param className + * Reference to the `ClassDef` for the class definition, which must have + * `jsClassCaptures.nonEmpty` + * + * @param captureValues + * Actual values for the captured parameters (in the `ClassDef`'s + * `jsClassCaptures.get`) + */ + sealed case class CreateJSClass(className: ClassName, + captureValues: List[Tree])( + implicit val pos: Position) + extends Tree { + val tpe = AnyType + } + + // Transient, a special one + + /** A transient node for custom purposes. + * + * A transient node is never a valid input to the [[Serializers]] nor to the + * linker, but can be used in a transient state for internal purposes. + * + * @param value + * The payload of the transient node, without any specified meaning. + */ + sealed case class Transient(value: Transient.Value)( + implicit val pos: Position) extends Tree { + val tpe = value.tpe + } + + object Transient { + /** Common interface for the values that can be stored in [[Transient]] + * nodes. + */ + trait Value { + /** Type of this transient value. */ + val tpe: Type + + /** Traverses this transient value. + * + * Implementations should delegate traversal to contained trees. + */ + def traverse(traverser: Traversers.Traverser): Unit + + /** Transforms this transient value. + * + * Implementations should transform contained trees and potentially adjust the result. + */ + def transform(transformer: Transformers.Transformer, isStat: Boolean)( + implicit pos: Position): Tree + + /** Prints the IR representation of this transient node. + * This method is called by the IR printers when encountering a + * [[org.scalajs.ir.Trees.Transient Transient]] node. + * + * @param out + * The [[org.scalajs.ir.Printers.IRTreePrinter IRTreePrinter]] to + * which the transient node must be printed. It can be used to print + * raw strings or nested IR nodes. + */ + def printIR(out: Printers.IRTreePrinter): Unit + } + } + + // Classes + + final class ClassDef( + val name: ClassIdent, + val originalName: OriginalName, + val kind: ClassKind, + /** JS class captures. + * + * - If `kind != ClassKind.JSClass`, must be `None`. + * - Otherwise, if `None`, this is a top-level class, whose JS class + * value is unique in the world and can be loaded with + * `LoadJSConstructor`. + * - If `Some(params)`, this is a nested JS class. New class values for + * this class def can be created with `CreateJSClass`. + * `LoadJSConstructor` is not valid for such a class def, since it + * does not have a unique JS class value to load. + * + * Note that `Some(Nil)` is valid and is a nested JS class that happens + * to have no captures. It will still have zero to many JS class values + * created with `CreateJSClass`. + */ + val jsClassCaptures: Option[List[ParamDef]], + val superClass: Option[ClassIdent], + val interfaces: List[ClassIdent], + /** If defined, an expression returning the JS class value of the super + * class. + * + * If `kind` is neither `ClassKind.JSClass` nor `ClassKind.JSModule`, + * this field must be `None`. + * + * The expression can depend on JS class captures. + * + * If empty for a non-native JS class, the JS super class value is + * implicitly `LoadJSConstructor(superClass.get)`. In that case the + * class def for `superClass` must have `jsClassCaptures.isEmpty`. + */ + val jsSuperClass: Option[Tree], + val jsNativeLoadSpec: Option[JSNativeLoadSpec], + val memberDefs: List[MemberDef], + val topLevelExportDefs: List[TopLevelExportDef] + )( + val optimizerHints: OptimizerHints + )(implicit val pos: Position) extends IRNode { + def className: ClassName = name.name + } + + object ClassDef { + def apply( + name: ClassIdent, + originalName: OriginalName, + kind: ClassKind, + jsClassCaptures: Option[List[ParamDef]], + superClass: Option[ClassIdent], + interfaces: List[ClassIdent], + jsSuperClass: Option[Tree], + jsNativeLoadSpec: Option[JSNativeLoadSpec], + memberDefs: List[MemberDef], + topLevelExportDefs: List[TopLevelExportDef])( + optimizerHints: OptimizerHints)( + implicit pos: Position): ClassDef = { + new ClassDef(name, originalName, kind, jsClassCaptures, superClass, + interfaces, jsSuperClass, jsNativeLoadSpec, memberDefs, + topLevelExportDefs)( + optimizerHints) + } + } + + // Class members + + /** Any member of a `ClassDef`. + * + * Partitioned into `AnyFieldDef`, `MethodDef`, `JSConstructorDef` and + * `JSMethodPropDef`. + */ + sealed abstract class MemberDef extends IRNode { + val flags: MemberFlags + } + + sealed abstract class AnyFieldDef extends MemberDef { + // val name: Ident | Tree + val ftpe: Type + } + + sealed case class FieldDef(flags: MemberFlags, name: FieldIdent, + originalName: OriginalName, ftpe: Type)( + implicit val pos: Position) extends AnyFieldDef + + sealed case class JSFieldDef(flags: MemberFlags, name: Tree, ftpe: Type)( + implicit val pos: Position) extends AnyFieldDef + + sealed case class MethodDef(flags: MemberFlags, name: MethodIdent, + originalName: OriginalName, args: List[ParamDef], resultType: Type, + body: Option[Tree])( + val optimizerHints: OptimizerHints, val hash: Option[TreeHash])( + implicit val pos: Position) extends MemberDef { + def methodName: MethodName = name.name + } + + sealed case class JSConstructorDef(flags: MemberFlags, + args: List[ParamDef], restParam: Option[ParamDef], body: JSConstructorBody)( + val optimizerHints: OptimizerHints, val hash: Option[TreeHash])( + implicit val pos: Position) + extends MemberDef + + sealed case class JSConstructorBody( + beforeSuper: List[Tree], superCall: JSSuperConstructorCall, afterSuper: List[Tree])( + implicit val pos: Position) + extends IRNode { + val allStats: List[Tree] = beforeSuper ::: superCall :: afterSuper + } + + sealed abstract class JSMethodPropDef extends MemberDef + + sealed case class JSMethodDef(flags: MemberFlags, name: Tree, + args: List[ParamDef], restParam: Option[ParamDef], body: Tree)( + val optimizerHints: OptimizerHints, val hash: Option[TreeHash])( + implicit val pos: Position) + extends JSMethodPropDef + + sealed case class JSPropertyDef(flags: MemberFlags, name: Tree, + getterBody: Option[Tree], setterArgAndBody: Option[(ParamDef, Tree)])( + implicit val pos: Position) + extends JSMethodPropDef + + sealed case class JSNativeMemberDef(flags: MemberFlags, name: MethodIdent, + jsNativeLoadSpec: JSNativeLoadSpec)( + implicit val pos: Position) + extends MemberDef + + // Top-level export defs + + sealed abstract class TopLevelExportDef extends IRNode { + import TopLevelExportDef._ + + def moduleID: String + + final def topLevelExportName: String = this match { + case TopLevelModuleExportDef(_, name) => name + case TopLevelJSClassExportDef(_, name) => name + + case TopLevelMethodExportDef(_, JSMethodDef(_, propName, _, _, _)) => + val StringLiteral(name) = propName: @unchecked // unchecked is needed for Scala 3.2+ + name + + case TopLevelFieldExportDef(_, name, _) => name + } + + require(isValidTopLevelExportName(topLevelExportName), + s"`$topLevelExportName` is not a valid top-level export name") + } + + object TopLevelExportDef { + def isValidTopLevelExportName(exportName: String): Boolean = + isJSIdentifierName(exportName) + } + + sealed case class TopLevelJSClassExportDef(moduleID: String, exportName: String)( + implicit val pos: Position) extends TopLevelExportDef + + /** Export for a top-level object. + * + * This exports the singleton instance of the containing module class. + * The instance is initialized during ES module instantiation. + */ + sealed case class TopLevelModuleExportDef(moduleID: String, exportName: String)( + implicit val pos: Position) extends TopLevelExportDef + + sealed case class TopLevelMethodExportDef(moduleID: String, + methodDef: JSMethodDef)( + implicit val pos: Position) extends TopLevelExportDef + + sealed case class TopLevelFieldExportDef(moduleID: String, + exportName: String, field: FieldIdent)( + implicit val pos: Position) extends TopLevelExportDef + + // Miscellaneous + + final class OptimizerHints private (private val bits: Int) extends AnyVal { + import OptimizerHints._ + + def inline: Boolean = (bits & InlineMask) != 0 + def noinline: Boolean = (bits & NoinlineMask) != 0 + + def withInline(value: Boolean): OptimizerHints = + if (value) new OptimizerHints(bits | InlineMask) + else new OptimizerHints(bits & ~InlineMask) + + def withNoinline(value: Boolean): OptimizerHints = + if (value) new OptimizerHints(bits | NoinlineMask) + else new OptimizerHints(bits & ~NoinlineMask) + + override def toString(): String = + s"OptimizerHints($bits)" + } + + object OptimizerHints { + private final val InlineShift = 0 + private final val InlineMask = 1 << InlineShift + + private final val NoinlineShift = 1 + private final val NoinlineMask = 1 << NoinlineShift + + final val empty: OptimizerHints = + new OptimizerHints(0) + + private[ir] def fromBits(bits: Int): OptimizerHints = + new OptimizerHints(bits) + + private[ir] def toBits(hints: OptimizerHints): Int = + hints.bits + } + + final class ApplyFlags private (private val bits: Int) extends AnyVal { + import ApplyFlags._ + + def isPrivate: Boolean = (bits & PrivateBit) != 0 + + def isConstructor: Boolean = (bits & ConstructorBit) != 0 + + def withPrivate(value: Boolean): ApplyFlags = + if (value) new ApplyFlags((bits & ~ConstructorBit) | PrivateBit) + else new ApplyFlags(bits & ~PrivateBit) + + def withConstructor(value: Boolean): ApplyFlags = + if (value) new ApplyFlags((bits & ~PrivateBit) | ConstructorBit) + else new ApplyFlags(bits & ~ConstructorBit) + } + + object ApplyFlags { + private final val PrivateShift = 0 + private final val PrivateBit = 1 << PrivateShift + + private final val ConstructorShift = 1 + private final val ConstructorBit = 1 << ConstructorShift + + final val empty: ApplyFlags = + new ApplyFlags(0) + + private[ir] def fromBits(bits: Int): ApplyFlags = + new ApplyFlags(bits) + + private[ir] def toBits(flags: ApplyFlags): Int = + flags.bits + } + + final class MemberNamespace private ( + val ordinal: Int) // intentionally public + extends AnyVal { + + import MemberNamespace._ + + def isStatic: Boolean = (ordinal & StaticFlag) != 0 + + def isPrivate: Boolean = (ordinal & PrivateFlag) != 0 + + def isConstructor: Boolean = (ordinal & ConstructorFlag) != 0 + + def prefixString: String = this match { + case Public => "" + case Private => "private " + case PublicStatic => "static " + case PrivateStatic => "private static " + case Constructor => "constructor " + case StaticConstructor => "static constructor " + } + } + + object MemberNamespace { + private final val StaticShift = 0 + private final val StaticFlag = 1 << StaticShift + + private final val PrivateShift = 1 + private final val PrivateFlag = 1 << PrivateShift + + private final val ConstructorShift = 2 + private final val ConstructorFlag = 1 << ConstructorShift + + final val Public: MemberNamespace = + new MemberNamespace(0) + + final val PublicStatic: MemberNamespace = + new MemberNamespace(StaticFlag) + + final val Private: MemberNamespace = + new MemberNamespace(PrivateFlag) + + final val PrivateStatic: MemberNamespace = + new MemberNamespace(PrivateFlag | StaticFlag) + + final val Constructor: MemberNamespace = + new MemberNamespace(ConstructorFlag) + + final val StaticConstructor: MemberNamespace = + new MemberNamespace(ConstructorFlag | StaticFlag) + + final val Count = 6 + + def fromOrdinal(ordinal: Int): MemberNamespace = { + require(0 <= ordinal && ordinal < Count, + s"Invalid namespace ordinal $ordinal") + new MemberNamespace(ordinal) + } + + private[Trees] def fromOrdinalUnchecked(ordinal: Int): MemberNamespace = + new MemberNamespace(ordinal) + + def forNonStaticCall(flags: ApplyFlags): MemberNamespace = { + if (flags.isPrivate) Private + else if (flags.isConstructor) Constructor + else Public + } + + def forStaticCall(flags: ApplyFlags): MemberNamespace = + if (flags.isPrivate) PrivateStatic else PublicStatic + } + + final class MemberFlags private (private val bits: Int) extends AnyVal { + import MemberFlags._ + + def namespace: MemberNamespace = + MemberNamespace.fromOrdinalUnchecked(bits & NamespaceMask) + + def isMutable: Boolean = (bits & MutableBit) != 0 + + def withNamespace(namespace: MemberNamespace): MemberFlags = + new MemberFlags((bits & ~NamespaceMask) | namespace.ordinal) + + def withMutable(value: Boolean): MemberFlags = + if (value) new MemberFlags(bits | MutableBit) + else new MemberFlags(bits & ~MutableBit) + } + + object MemberFlags { + /* NamespaceMask must remain with no shift, for easy conversion between + * MemberFlags and MemberNamespace. + */ + private final val NamespaceMask = 7 + + private final val MutableShift = 3 + private final val MutableBit = 1 << MutableShift + + final val empty: MemberFlags = + new MemberFlags(0) + + private[ir] def fromBits(bits: Int): MemberFlags = + new MemberFlags(bits) + + private[ir] def toBits(flags: MemberFlags): Int = + flags.bits + } + + /** Loading specification for a native JS class or object. */ + sealed abstract class JSNativeLoadSpec + + object JSNativeLoadSpec { + + /** Load from the global scope. + * + * The `globalRef` is the name of a global variable (found in the global + * scope). It must be valid according to + * [[JSGlobalRef.isValidJSGlobalRefName]]. + * + * The `path` is a series of nested property names starting from that + * variable. + * + * The path can be empty, in which case this denotes the specified global + * variable itself. + * + * Examples: + * {{{ + * // Foo + * Global("Foo", Nil) + * + * // cp.Vect + * Global("cp", List("Vect")) + * }}} + */ + final case class Global(globalRef: String, path: List[String]) + extends JSNativeLoadSpec { + + require(JSGlobalRef.isValidJSGlobalRefName(globalRef)) + } + + /** Load from a module import. + * + * The `module` is the ES module identifier. The `path` is a series of + * nested property names starting from the module object. + * + * The path can be empty, in which case the specification denotes the + * namespace import, i.e., import a special object whose fields are all + * the exports of the module. + * + * Any element in the path is a property selection from there. A module + * import info with one path element is importing that particular value + * from the module. + * + * Examples: + * {{{ + * // import { Bar as x } from 'foo' + * Import("foo", List("Bar")) + * + * // import { Bar as y } from 'foo' + * // y.Baz + * Import("foo", List("Bar", "Baz")) + * + * // import * as x from 'foo' (namespace import) + * Import("foo", Nil) + * + * // import x from 'foo' (default import) + * Import("foo", List("default")) + * }}} + */ + final case class Import(module: String, path: List[String]) + extends JSNativeLoadSpec + + /** Like [[Import]], but with a [[Global]] fallback when linking without + * modules. + * + * When linking with a module kind that supports modules, the `importSpec` + * is used. When modules are not supported, use the fallback `globalSpec`. + */ + final case class ImportWithGlobalFallback(importSpec: Import, + globalSpec: Global) + extends JSNativeLoadSpec + + } + + /** A hash of a tree (usually a MethodDef). + * + * Contains a SHA-1 hash. + */ + final class TreeHash(val hash: Array[Byte]) { + assert(hash.length == 20) + } +} diff --git a/ir/shared/src/main/scala/org/scalajs/ir/Types.scala b/ir/shared/src/main/scala/org/scalajs/ir/Types.scala new file mode 100644 index 0000000000..a82570a840 --- /dev/null +++ b/ir/shared/src/main/scala/org/scalajs/ir/Types.scala @@ -0,0 +1,373 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.ir + +import scala.annotation.tailrec + +import Names._ +import Trees._ + +object Types { + + /** Type of a term (expression or statement) in the IR. + * + * There is a many-to-one relationship from [[TypeRef]]s to `Type`s, + * because `java.lang.Object` and JS types all collapse to [[AnyType]]. + * + * In fact, there are two `Type`s that do not have any real equivalent in + * type refs: [[StringType]] and [[UndefType]], as they refer to the + * non-null variants of `java.lang.String` and `java.lang.Void`, + * respectively. + */ + abstract sealed class Type { + def show(): String = { + val writer = new java.io.StringWriter + val printer = new Printers.IRTreePrinter(writer) + printer.print(this) + writer.toString() + } + } + + sealed abstract class PrimType extends Type + + sealed abstract class PrimTypeWithRef extends PrimType { + def primRef: PrimRef = this match { + case NoType => VoidRef + case BooleanType => BooleanRef + case CharType => CharRef + case ByteType => ByteRef + case ShortType => ShortRef + case IntType => IntRef + case LongType => LongRef + case FloatType => FloatRef + case DoubleType => DoubleRef + case NullType => NullRef + case NothingType => NothingRef + } + } + + /** Any type (the top type of this type system). + * A variable of this type can contain any value, including `undefined` + * and `null` and any JS value. This type supports a very limited set + * of Scala operations, the ones common to all values. Basically only + * reference equality tests and instance tests. It also supports all + * JavaScript operations, since all Scala objects are also genuine + * JavaScript objects. + * The type java.lang.Object in the back-end maps to [[AnyType]] because it + * can hold JS values (not only instances of Scala.js classes). + */ + case object AnyType extends Type + + // Can't link to Nothing - #1969 + /** Nothing type (the bottom type of this type system). + * Expressions from which one can never come back are typed as `Nothing`. + * For example, `throw` and `return`. + */ + case object NothingType extends PrimTypeWithRef + + /** The type of `undefined`. */ + case object UndefType extends PrimType + + /** Boolean type. + * It does not accept `null` nor `undefined`. + */ + case object BooleanType extends PrimTypeWithRef + + /** `Char` type, a 16-bit UTF-16 code unit. + * It does not accept `null` nor `undefined`. + */ + case object CharType extends PrimTypeWithRef + + /** 8-bit signed integer type. + * It does not accept `null` nor `undefined`. + */ + case object ByteType extends PrimTypeWithRef + + /** 16-bit signed integer type. + * It does not accept `null` nor `undefined`. + */ + case object ShortType extends PrimTypeWithRef + + /** 32-bit signed integer type. + * It does not accept `null` nor `undefined`. + */ + case object IntType extends PrimTypeWithRef + + /** 64-bit signed integer type. + * It does not accept `null` nor `undefined`. + */ + case object LongType extends PrimTypeWithRef + + /** Float type (32-bit). + * It does not accept `null` nor `undefined`. + */ + case object FloatType extends PrimTypeWithRef + + /** Double type (64-bit). + * It does not accept `null` nor `undefined`. + */ + case object DoubleType extends PrimTypeWithRef + + /** String type. + * It does not accept `null` nor `undefined`. + */ + case object StringType extends PrimType + + /** The type of `null`. + * It does not accept `undefined`. + * The null type is a subtype of all class types and array types. + */ + case object NullType extends PrimTypeWithRef + + /** Class (or interface) type. */ + final case class ClassType(className: ClassName) extends Type + + /** Array type. */ + final case class ArrayType(arrayTypeRef: ArrayTypeRef) extends Type + + /** Record type. + * Used by the optimizer to inline classes as records with multiple fields. + * They are desugared as several local variables by JSDesugaring. + * Record types cannot cross method boundaries, so they cannot appear as + * the type of fields or parameters, nor as result types of methods. + * The compiler itself never generates record types. + */ + final case class RecordType(fields: List[RecordType.Field]) extends Type { + def findField(name: FieldName): RecordType.Field = + fields.find(_.name == name).get + } + + object RecordType { + final case class Field(name: FieldName, originalName: OriginalName, + tpe: Type, mutable: Boolean) + } + + /** No type. */ + case object NoType extends PrimTypeWithRef + + /** Type reference (allowed for classOf[], is/asInstanceOf[]). + * + * A `TypeRef` has exactly the same level of precision as a JVM type. + * There is a one-to-one relationship between a `TypeRef` and an instance of + * `java.lang.Class` at run-time. This means that: + * + * - All primitive types have their `TypeRef` (including `scala.Byte` and + * `scala.Short`), and they are different from their boxed versions. + * - JS types are not erased to `any` + * - Array types are like on the JVM + * + * A `TypeRef` therefore uniquely identifies a `classOf[T]`. It is also the + * type refs that are used in method signatures, and which therefore dictate + * JVM/IR overloading. + */ + sealed abstract class TypeRef { + def show(): String = { + val writer = new java.io.StringWriter + val printer = new Printers.IRTreePrinter(writer) + printer.print(this) + writer.toString() + } + + def displayName: String + } + + sealed abstract class NonArrayTypeRef extends TypeRef + + /** Primitive type reference. */ + final case class PrimRef private[ir] (tpe: PrimTypeWithRef) + extends NonArrayTypeRef { + + /** The display name of this primitive type. + * + * For all primitive types except `NullType` and `NothingType`, this is + * specified by the IR spec in the sense that it is the result of + * `classOf[Prim].getName()`. + * + * For `NullType` and `NothingType`, the names are `"null"` and + * `"nothing"`, respectively. + */ + val displayName: String = tpe match { + case NoType => "void" + case BooleanType => "boolean" + case CharType => "char" + case ByteType => "byte" + case ShortType => "short" + case IntType => "int" + case LongType => "long" + case FloatType => "float" + case DoubleType => "double" + case NullType => "null" + case NothingType => "nothing" + } + + /** The char code of this primitive type. + * + * For all primitive types except `NullType` and `NothingType`, this is + * specified by the IR spec in the sense that it is visible in the result + * of `classOf[Array[Prim]].getName()` (e.g., that is `"[I"` for + * `Array[Int]`). + * + * For `NullType` and `NothingType`, the char codes are `'N'` and `'E'`, + * respectively. + */ + val charCode: Char = tpe match { + case NoType => 'V' + case BooleanType => 'Z' + case CharType => 'C' + case ByteType => 'B' + case ShortType => 'S' + case IntType => 'I' + case LongType => 'J' + case FloatType => 'F' + case DoubleType => 'D' + case NullType => 'N' + case NothingType => 'E' + } + } + + /* @unchecked for the initialization checker of Scala 3 + * When we get here, `NoType` is not yet considered fully initialized because + * its method `primRef` can access `VoidRef`. Since the constructor of + * `PrimRef` pattern-matches on its `tpe`, which is `NoType`, this is flagged + * by the init checker, although our usage is safe given that we do not call + * `primRef`. The same reasoning applies to the other primitive types. + * In the future, we may want to rearrange the initialization sequence of + * this file to avoid this issue. + */ + final val VoidRef = PrimRef(NoType: @unchecked) + final val BooleanRef = PrimRef(BooleanType: @unchecked) + final val CharRef = PrimRef(CharType: @unchecked) + final val ByteRef = PrimRef(ByteType: @unchecked) + final val ShortRef = PrimRef(ShortType: @unchecked) + final val IntRef = PrimRef(IntType: @unchecked) + final val LongRef = PrimRef(LongType: @unchecked) + final val FloatRef = PrimRef(FloatType: @unchecked) + final val DoubleRef = PrimRef(DoubleType: @unchecked) + final val NullRef = PrimRef(NullType: @unchecked) + final val NothingRef = PrimRef(NothingType: @unchecked) + + /** Class (or interface) type. */ + final case class ClassRef(className: ClassName) extends NonArrayTypeRef { + def displayName: String = className.nameString + } + + /** Array type. */ + final case class ArrayTypeRef(base: NonArrayTypeRef, dimensions: Int) + extends TypeRef { + + def displayName: String = "[" * dimensions + base.displayName + } + + object ArrayTypeRef { + def of(innerType: TypeRef): ArrayTypeRef = innerType match { + case innerType: NonArrayTypeRef => ArrayTypeRef(innerType, 1) + case ArrayTypeRef(base, dim) => ArrayTypeRef(base, dim + 1) + } + } + + /** Generates a literal zero of the given type. */ + def zeroOf(tpe: Type)(implicit pos: Position): Tree = tpe match { + case BooleanType => BooleanLiteral(false) + case CharType => CharLiteral('\u0000') + case ByteType => ByteLiteral(0) + case ShortType => ShortLiteral(0) + case IntType => IntLiteral(0) + case LongType => LongLiteral(0L) + case FloatType => FloatLiteral(0.0f) + case DoubleType => DoubleLiteral(0.0) + case StringType => StringLiteral("") + case UndefType => Undefined() + + case NullType | AnyType | _:ClassType | _:ArrayType => Null() + + case tpe: RecordType => + RecordValue(tpe, tpe.fields.map(f => zeroOf(f.tpe))) + + case NothingType | NoType => + throw new IllegalArgumentException(s"cannot generate a zero for $tpe") + } + + val BoxedClassToPrimType: Map[ClassName, PrimType] = Map( + BoxedUnitClass -> UndefType, + BoxedBooleanClass -> BooleanType, + BoxedCharacterClass -> CharType, + BoxedByteClass -> ByteType, + BoxedShortClass -> ShortType, + BoxedIntegerClass -> IntType, + BoxedLongClass -> LongType, + BoxedFloatClass -> FloatType, + BoxedDoubleClass -> DoubleType, + BoxedStringClass -> StringType + ) + + val PrimTypeToBoxedClass: Map[PrimType, ClassName] = + BoxedClassToPrimType.map(_.swap) + + /** Tests whether a type `lhs` is a subtype of `rhs` (or equal). + * @param isSubclass A function testing whether a class/interface is a + * subclass of another class/interface. + */ + def isSubtype(lhs: Type, rhs: Type)( + isSubclass: (ClassName, ClassName) => Boolean): Boolean = { + (lhs == rhs) || + ((lhs, rhs) match { + case (_, NoType) => true + case (NoType, _) => false + case (_, AnyType) => true + case (NothingType, _) => true + + case (ClassType(lhsClass), ClassType(rhsClass)) => + isSubclass(lhsClass, rhsClass) + + case (NullType, ClassType(_)) => true + case (NullType, ArrayType(_)) => true + + case (primType: PrimType, ClassType(rhsClass)) => + val lhsClass = PrimTypeToBoxedClass.getOrElse(primType, { + throw new AssertionError(s"unreachable case for isSubtype($lhs, $rhs)") + }) + isSubclass(lhsClass, rhsClass) + + case (ArrayType(ArrayTypeRef(lhsBase, lhsDims)), + ArrayType(ArrayTypeRef(rhsBase, rhsDims))) => + if (lhsDims < rhsDims) { + false // because Array[A] rhsDims) { + rhsBase match { + case ClassRef(ObjectClass) => + true // because Array[Array[A]] <: Array[Object] + case _ => + false + } + } else { // lhsDims == rhsDims + // lhsBase must be <: rhsBase + (lhsBase, rhsBase) match { + case (ClassRef(lhsBaseName), ClassRef(rhsBaseName)) => + /* All things must be considered subclasses of Object for this + * purpose, even JS types and interfaces, which do not have + * Object in their ancestors. + */ + rhsBaseName == ObjectClass || isSubclass(lhsBaseName, rhsBaseName) + case _ => + lhsBase eq rhsBase + } + } + + case (ArrayType(_), ClassType(className)) => + AncestorsOfPseudoArrayClass.contains(className) + + case _ => + false + }) + } +} diff --git a/ir/shared/src/main/scala/org/scalajs/ir/UTF8String.scala b/ir/shared/src/main/scala/org/scalajs/ir/UTF8String.scala new file mode 100644 index 0000000000..00eb0c2f11 --- /dev/null +++ b/ir/shared/src/main/scala/org/scalajs/ir/UTF8String.scala @@ -0,0 +1,247 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.ir + +import java.nio.CharBuffer +import java.nio.charset.CharacterCodingException +import java.nio.charset.CodingErrorAction +import java.nio.charset.StandardCharsets.UTF_8 + +/** An immutable UTF-8 string. + * + * The contents of a `UTF8String` is guaranteed to be a well-formed UTF-8 + * string. + * + * @note + * `equals()` and `hashCode()`, along with `==` and `##`, are just as + * broken for `UTF8String` as for `Array`s. Use the methods in the + * companion object instead. This is unavoidable because we cannot override + * `equals` nor `hashCode` in an `AnyVal`. + */ +final class UTF8String private (private[ir] val bytes: Array[Byte]) + extends AnyVal { + + import UTF8String._ + + /** Returns the length in UTF-8 code units of this string. */ + @inline def length: Int = bytes.length + + /** Returns the `i`th UTF-8 code unit of this string. */ + @inline def apply(i: Int): Byte = bytes(i) + + @inline override def toString(): String = decodeUTF8(bytes) + + def ++(that: UTF8String): UTF8String = { + val thisLen = this.length + val thatLen = that.length + val result = java.util.Arrays.copyOf(this.bytes, thisLen + thatLen) + System.arraycopy(that.bytes, 0, result, thisLen, thatLen) + new UTF8String(result) + } +} + +object UTF8String { + /** Unsafely creates a `UTF8String` from a byte array. + * + * This method does not validate the input array nor copies its contents. It + * should only be used to recreate a `UTF8String` from a byte array that has + * been extracted from a correctly validated `UTF8String`. + */ + private[ir] def unsafeCreate(bytes: Array[Byte]): UTF8String = + new UTF8String(bytes) + + /** Creates a UTF-8 string from a byte array. + * + * The input byte array will be copied to ensure the immutability of + * `UTF8String`. + * + * @throws java.lang.IllegalArgumentException + * if the input byte array is not a valid UTF-8 string + */ + def apply(bytes: Array[Byte]): UTF8String = + new UTF8String(validateUTF8(bytes).clone()) + + /** Creates a UTF-8 string from a string. + * + * @throws java.lang.IllegalArgumentException + * if the input string is not a valid UTF-16 string, i.e., if it + * contains unpaired surrogates + */ + def apply(str: String): UTF8String = + new UTF8String(encodeUTF8(str)) + + /** Creates a UTF-8 string from a byte array without copying. + * + * After calling this method, the input byte array must not be mutated by + * the caller anymore. + * + * @throws java.lang.IllegalArgumentException + * if the input byte array is not a valid UTF-8 string + */ + private[ir] def createAcquiringByteArray(bytes: Array[Byte]): UTF8String = + new UTF8String(validateUTF8(bytes)) + + def equals(x: UTF8String, y: UTF8String): Boolean = + java.util.Arrays.equals(x.bytes, y.bytes) + + def hashCode(x: UTF8String): Int = + scala.util.hashing.MurmurHash3.bytesHash(x.bytes) + + // ----------------------------------------------------------------- + // ----- Private helpers for validation, encoding and decoding ----- + // ----------------------------------------------------------------- + + // --- Validation --- + + private def validateUTF8(bytes: Array[Byte]): Array[Byte] = { + val len = bytes.length + + var i = 0 + while (i != len) { + val b = bytes(i).toInt + if (b >= 0) { + // fast path: single-byte code point, ASCII repertoire + i += 1 + } else { + // slow path: multi-byte code point + i += validateMultibyteCodePointAndGetByteLen(bytes, len, i, b) + } + } + + bytes + } + + private def validateMultibyteCodePointAndGetByteLen(bytes: Array[Byte], + end: Int, i: Int, b1: Int): Int = { + + @inline def isInvalidNextByte(b: Int): Boolean = + (b & 0xc0) != 0x80 + + def throwInvalid(): Nothing = { + throw new IllegalArgumentException( + "Invalid UTF-8 byte sequence " + bytes.mkString("[", ",", "]") + + s" (error at index $i)") + } + + if ((b1 & 0xe0) == 0xc0) { // 110xxxxx + if (i > end - 2) { + throwInvalid() + } else { + val b2 = bytes(i + 1) & 0xff + if (isInvalidNextByte(b2)) { + throwInvalid() + } else { + val cp = (((b1 & 0x1f) << 6) | (b2 & 0x3f)) + if (cp >= 0x80) + 2 + else + throwInvalid() + } + } + } else if ((b1 & 0xf0) == 0xe0) { // 1110xxxx + if (i > end - 3) { + throwInvalid() + } else { + val b2 = bytes(i + 1) & 0xff + val b3 = bytes(i + 2) & 0xff + if (isInvalidNextByte(b2) || isInvalidNextByte(b3)) { + throwInvalid() + } else { + val cp = (((b1 & 0xf) << 12) | ((b2 & 0x3f) << 6) | (b3 & 0x3f)) + if (cp >= 0x800 && !Character.isSurrogate(cp.toChar)) + 3 + else + throwInvalid() + } + } + } else if ((b1 & 0xf8) == 0xf0) { // 11110xxx + if (i > end - 4) { + throwInvalid() + } else { + val b2 = bytes(i + 1) & 0xff + val b3 = bytes(i + 2) & 0xff + val b4 = bytes(i + 3) & 0xff + if (isInvalidNextByte(b2) || isInvalidNextByte(b3) || isInvalidNextByte(b4)) { + throwInvalid() + } else { + val cp = (((b1 & 0x7) << 18) | ((b2 & 0x3f) << 12) | + ((b3 & 0x3f) << 6) | (b4 & 0x3f)) + if (cp >= 0x10000 && cp <= Character.MAX_CODE_POINT) + 4 + else + throwInvalid() + } + } + } else { + throwInvalid() + } + } + + // --- Encoding --- + + private def encodeUTF8(str: String): Array[Byte] = { + // scalastyle:off return + val len = str.length() + + /* We optimistically assume that all characters are ASCII, and backtrack if + * we find a non-ASCII character. + */ + val result = new Array[Byte](len) + var i = 0 + while (i != len) { + val c = str.charAt(i).toInt + if ((c & 0x7f) != c) + return encodeUTF8WithNonASCII(str) + result(i) = c.toByte + i += 1 + } + result + // scalastyle:on return + } + + private def encodeUTF8WithNonASCII(str: String): Array[Byte] = { + // Note: a UTF-8 encoder can never encounter an "unmappable" character + val encoder = UTF_8.newEncoder().onMalformedInput(CodingErrorAction.REPORT) + try { + val outputBuffer = encoder.encode(CharBuffer.wrap(str)) + val result = new Array[Byte](outputBuffer.remaining()) + outputBuffer.get(result) + result + } catch { + case _: CharacterCodingException => + throw new IllegalArgumentException("Not a valid UTF-16 string: " + str) + } + } + + // --- Decoding --- + + private def decodeUTF8(bytes: Array[Byte]): String = { + // scalastyle:off return + /* We optimistically assume that all characters are single-byte (i.e., in + * the ASCII repertoire), and fall back to a full UTF-8 decoder if we find + * a multi-byte character. + */ + val len = bytes.length + val result = new Array[Char](len) + var i = 0 + while (i != len) { + val b = bytes(i) + if (b < 0) + return new String(bytes, UTF_8) + result(i) = (b & 0xff).toChar + i += 1 + } + new String(result) + // scalastyle:on return + } +} diff --git a/ir/shared/src/main/scala/org/scalajs/ir/Utils.scala b/ir/shared/src/main/scala/org/scalajs/ir/Utils.scala new file mode 100644 index 0000000000..807ecd56bd --- /dev/null +++ b/ir/shared/src/main/scala/org/scalajs/ir/Utils.scala @@ -0,0 +1,110 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.ir + +private[ir] object Utils { + + /* !!! BEGIN CODE VERY SIMILAR TO linker/.../javascript/Utils.scala and + * js-envs/.../JSUtils.scala + */ + + private final val EscapeJSChars = "\\b\\t\\n\\v\\f\\r\\\"\\\\" + + private[ir] def printEscapeJS(str: String, out: java.io.Writer): Unit = { + /* Note that Java and JavaScript happen to use the same encoding for + * Unicode, namely UTF-16, which means that 1 char from Java always equals + * 1 char in JavaScript. */ + val end = str.length() + var i = 0 + /* Loop prints all consecutive ASCII printable characters starting + * from current i and one non ASCII printable character (if it exists). + * The new i is set at the end of the appended characters. + */ + while (i != end) { + val start = i + var c: Int = str.charAt(i) + // Find all consecutive ASCII printable characters from `start` + while (i != end && c >= 32 && c <= 126 && c != 34 && c != 92) { + i += 1 + if (i != end) + c = str.charAt(i) + } + // Print ASCII printable characters from `start` + if (start != i) { + out.write(str, start, i - start) + } + + // Print next non ASCII printable character + if (i != end) { + def escapeJSEncoded(c: Int): Unit = { + if (7 < c && c < 14) { + val i = 2 * (c - 8) + out.write(EscapeJSChars, i, 2) + } else if (c == 34) { + out.write(EscapeJSChars, 12, 2) + } else if (c == 92) { + out.write(EscapeJSChars, 14, 2) + } else { + out.write("\\u%04x".format(c)) + } + } + escapeJSEncoded(c) + i += 1 + } + } + } + + /* !!! END CODE VERY SIMILAR TO linker/.../javascript/Utils.scala and + * js-envs/.../JSUtils.scala + */ + + /** A ByteArrayOutput stream that allows to jump back to a given + * position and complete some bytes. Methods must be called in the + * following order only: + * - [[markJump]] + * - [[jumpBack]] + * - [[continue]] + */ + private[ir] class JumpBackByteArrayOutputStream + extends java.io.ByteArrayOutputStream { + protected var jumpBackPos: Int = -1 + protected var headPos: Int = -1 + + /** Marks the current location for a jumpback */ + def markJump(): Unit = { + assert(jumpBackPos == -1) + assert(headPos == -1) + jumpBackPos = count + } + + /** Jumps back to the mark. Returns the number of bytes jumped */ + def jumpBack(): Int = { + assert(jumpBackPos >= 0) + assert(headPos == -1) + val jumped = count - jumpBackPos + headPos = count + count = jumpBackPos + jumpBackPos = -1 + jumped + } + + /** Continues to write at the head. */ + def continue(): Unit = { + assert(jumpBackPos == -1) + assert(headPos >= 0) + count = headPos + headPos = -1 + } + } + +} diff --git a/ir/shared/src/test/scala/org/scalajs/ir/HashersTest.scala b/ir/shared/src/test/scala/org/scalajs/ir/HashersTest.scala new file mode 100644 index 0000000000..3a95a15b55 --- /dev/null +++ b/ir/shared/src/test/scala/org/scalajs/ir/HashersTest.scala @@ -0,0 +1,115 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.ir + +import scala.language.implicitConversions + +import org.junit.Test +import org.junit.Assert._ + +import Hashers._ +import Names._ +import OriginalName.NoOriginalName +import Printers._ +import Trees._ +import Types._ + +import TestIRBuilder._ + +class HashersTest { + private def assertHashEquals(expected: String, actual: Option[TreeHash]): Unit = { + assertTrue(actual.isDefined) + assertEquals(expected, hashAsVersion(actual.get)) + } + + @Test def testHashAsVersion(): Unit = { + val hash: TreeHash = new TreeHash(Array( + 0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe, 0xc3, 0x7f, + 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xbb, 0x34 + ).map(_.toByte)) + + assertEquals("1032547698badcfec37f0123456789abcdefbb34", hashAsVersion(hash)) + } + + private val bodyWithInterestingStuff = Block( + // All primitive literals, which exercise hashing of primitives + BooleanLiteral(true), + CharLiteral('A'), + ByteLiteral(12), + ShortLiteral(12345), + IntLiteral(1234567890), + LongLiteral(123456789101112L), + FloatLiteral(151.189f), + DoubleLiteral(151.189), + + /* String literals, which exercise hashing strings, and, underlying + * that, hashing part of an Array[Byte], and hashing more than 64 bytes + * at a time, forcing decomposition in 64-byte chunks. + */ + s(""), + s("hello"), + s("wPtOG7TtwcP1Z3gBgUzm"), + s("JEKzMO5kLpv7ZBu5FcSdIZngrMJTmZz90siAAxC7YCkBVp9M2DJRuI8jE278zRzjlvqC8syqM5G8Ujob"), + s( + "hU9TP2tpK0AQGyccLKotncR7PafADrjb1731xzvcp0MXKfcAQYnPniUUYphqwwj5LEt74QwSssGWh59q" + + "dBifWTbHqgXAncHzMqTU07g4Pj6BaYmGAsMxeC9IRgiKfMSOFpLyrXFz7zsIRhywapYjXV" + ), + + // A var ref that contains a Name, which exercises hashing an Array[Byte] + ref("x", IntType), + + // Result value of type int, for consistency + i(5) + ) + + @Test def testHashMethodDef(): Unit = { + def test(expected: String, methodDef: MethodDef): Unit = { + val hashedMethodDef = hashMethodDef(methodDef) + assertHashEquals(expected, hashedMethodDef.hash) + } + + val mIIMethodName = MethodName("m", List(I), I) + + test( + "64940df7c6aae58962eb56f4aa6c6b085ca06c25", + MethodDef(MemberFlags.empty, mIIMethodName, NON, + List(ParamDef("x", NON, IntType, mutable = false)), + IntType, None)( + NoOptHints, None) + ) + + test( + "309805e5680ffa1804811ff5c9ebc77e91846957", + MethodDef(MemberFlags.empty, mIIMethodName, NON, + List(ParamDef("x", NON, IntType, mutable = false)), + IntType, Some(bodyWithInterestingStuff))( + NoOptHints, None) + ) + } + + @Test def testHashJSMethodDef(): Unit = { + def test(expected: String, methodDef: JSMethodDef): Unit = { + val hashedMethodDef = hashJSMethodDef(methodDef) + assertHashEquals(expected, hashedMethodDef.hash) + } + + test( + "c0f1ef1b22fd1cfdc9bba78bf3e0f433e9f82fc1", + JSMethodDef(MemberFlags.empty, s("m"), + List(ParamDef("x", NON, AnyType, mutable = false)), None, + bodyWithInterestingStuff)( + NoOptHints, None) + ) + } + +} diff --git a/ir/shared/src/test/scala/org/scalajs/ir/PrintersTest.scala b/ir/shared/src/test/scala/org/scalajs/ir/PrintersTest.scala new file mode 100644 index 0000000000..4684db9a93 --- /dev/null +++ b/ir/shared/src/test/scala/org/scalajs/ir/PrintersTest.scala @@ -0,0 +1,1432 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.ir + +import scala.language.implicitConversions + +import org.junit.Test +import org.junit.Assert._ + +import Names._ +import OriginalName.NoOriginalName +import Printers._ +import Trees._ +import Types._ + +import TestIRBuilder._ + +class PrintersTest { + import MemberNamespace.{Constructor, Private, PublicStatic => Static, PrivateStatic} + + /** An original name. */ + private val TestON = OriginalName("orig name") + + private def assertPrintEquals(expected: String, node: IRNode): Unit = + assertPrintEqualsImpl(expected, _.printAnyNode(node)) + + private def assertPrintEquals(expected: String, tpe: Type): Unit = + assertPrintEqualsImpl(expected, _.print(tpe)) + + private def assertPrintEquals(expected: String, typeRef: TypeRef): Unit = + assertPrintEqualsImpl(expected, _.print(typeRef)) + + private def assertPrintEqualsImpl(expected: String, + print: IRTreePrinter => Unit): Unit = { + val sw = new java.io.StringWriter + val printer = new IRTreePrinter(sw) + print(printer) + assertEquals(expected.stripMargin.trim, sw.toString()) + } + + @Test def printType(): Unit = { + assertPrintEquals("any", AnyType) + assertPrintEquals("nothing", NothingType) + assertPrintEquals("void", UndefType) + assertPrintEquals("boolean", BooleanType) + assertPrintEquals("char", CharType) + assertPrintEquals("byte", ByteType) + assertPrintEquals("short", ShortType) + assertPrintEquals("int", IntType) + assertPrintEquals("long", LongType) + assertPrintEquals("float", FloatType) + assertPrintEquals("double", DoubleType) + assertPrintEquals("string", StringType) + assertPrintEquals("null", NullType) + assertPrintEquals("", NoType) + + assertPrintEquals("java.lang.Object", ClassType(ObjectClass)) + + assertPrintEquals("java.lang.Object[]", arrayType(ObjectClass, 1)) + assertPrintEquals("int[][]", arrayType(IntRef, 2)) + + assertPrintEquals("(x: int, var y: any)", + RecordType(List( + RecordType.Field("x", NON, IntType, mutable = false), + RecordType.Field("y", NON, AnyType, mutable = true)))) + } + + @Test def printTypeRef(): Unit = { + assertPrintEquals("java.lang.Object", ClassRef(ObjectClass)) + + assertPrintEquals("java.lang.Object[]", ArrayTypeRef(ObjectClass, 1)) + assertPrintEquals("int[][]", ArrayTypeRef(IntRef, 2)) + } + + @Test def printVarDef(): Unit = { + assertPrintEquals("val x: int = 5", + VarDef("x", NON, IntType, mutable = false, i(5))) + assertPrintEquals("var x: int = 5", + VarDef("x", NON, IntType, mutable = true, i(5))) + assertPrintEquals("val x{orig name}: int = 5", + VarDef("x", TestON, IntType, mutable = false, i(5))) + } + + @Test def printParamDef(): Unit = { + assertPrintEquals("x: int", + ParamDef("x", NON, IntType, mutable = false)) + assertPrintEquals("var x: int", + ParamDef("x", NON, IntType, mutable = true)) + assertPrintEquals("x{orig name}: int", + ParamDef("x", TestON, IntType, mutable = false)) + } + + @Test def printSkip(): Unit = { + assertPrintEquals("/**/", Skip()) + } + + @Test def printBlock(): Unit = { + assertPrintEquals( + """ + |{ + | 5; + | 6 + |} + """, + Block(i(5), i(6))) + } + + @Test def printLabeled(): Unit = { + assertPrintEquals( + """ + |lab: { + | 6 + |} + """, + Labeled("lab", NoType, i(6))) + + assertPrintEquals( + """ + |lab[int]: { + | 6 + |} + """, + Labeled("lab", IntType, i(6))) + + assertPrintEquals( + """ + |lab: { + | 5; + | 6 + |} + """, + Labeled("lab", NoType, Block(i(5), i(6)))) + } + + @Test def printAssign(): Unit = { + assertPrintEquals("x = 5", + Assign(VarRef("x")(IntType), i(5))) + } + + @Test def printReturn(): Unit = { + assertPrintEquals("return@lab 5", Return(i(5), "lab")) + } + + @Test def printIf(): Unit = { + assertPrintEquals( + """ + |if (true) { + | 5 + |} else { + | 6 + |} + """, + If(b(true), i(5), i(6))(IntType)) + + assertPrintEquals( + """ + |if (true) { + | 5 + |} + """, + If(b(true), i(5), Skip())(NoType)) + + assertPrintEquals( + """ + |if (true) { + | 5 + |} else if (false) { + | 6 + |} else { + | 7 + |} + """, + If(b(true), i(5), If(b(false), i(6), i(7))(IntType))(IntType)) + + assertPrintEquals("x || y", + If(ref("x", BooleanType), b(true), ref("y", BooleanType))(BooleanType)) + + assertPrintEquals("x && y", + If(ref("x", BooleanType), ref("y", BooleanType), b(false))(BooleanType)) + } + + @Test def printWhile(): Unit = { + assertPrintEquals( + """ + |while (true) { + | 5 + |} + """, + While(b(true), i(5))) + } + + @Test def printDoWhile(): Unit = { + assertPrintEquals( + """ + |do { + | 5 + |} while (true) + """, + DoWhile(i(5), b(true))) + } + + @Test def printForIn(): Unit = { + assertPrintEquals( + """ + |for (val x in o) { + | 5 + |} + """, + ForIn(ref("o", AnyType), "x", NON, i(5))) + + assertPrintEquals( + """ + |for (val x{orig name} in o) { + | 5 + |} + """, + ForIn(ref("o", AnyType), "x", TestON, i(5))) + } + + @Test def printTry(): Unit = { + assertPrintEquals( + """ + |try { + | 5 + |} catch (e) { + | 6 + |} + """, + TryCatch(i(5), "e", NON, i(6))(IntType)) + + assertPrintEquals( + """ + |try { + | 5 + |} catch (e{orig name}) { + | 6 + |} + """, + TryCatch(i(5), "e", TestON, i(6))(IntType)) + + assertPrintEquals( + """ + |try { + | 5 + |} finally { + | 6 + |} + """, + TryFinally(i(5), i(6))) + + assertPrintEquals( + """ + |try { + | 5 + |} catch (e) { + | 6 + |} finally { + | 7 + |} + """, + TryFinally(TryCatch(i(5), "e", NON, i(6))(IntType), i(7))) + } + + @Test def printThrow(): Unit = { + assertPrintEquals("throw null", Throw(Null())) + } + + @Test def printMatch(): Unit = { + assertPrintEquals( + """ + |match (x) { + | case 5: + | 6; + | case 7 | 8: + | { + | 9; + | 10 + | }; + | default: + | 11; + |} + """, + Match(ref("x", IntType), List( + List(i(5)) -> i(6), + List(i(7), i(8)) -> Block(i(9), i(10))), + i(11))(IntType)) + } + + @Test def printDebugger(): Unit = { + assertPrintEquals("debugger", Debugger()) + } + + @Test def printNew(): Unit = { + assertPrintEquals("new java.lang.Object().;V()", + New(ObjectClass, NoArgConstructorName, Nil)) + assertPrintEquals("new scala.Tuple2().;Ljava.lang.Object;Ljava.lang.Object;V(5, 6)", + New("scala.Tuple2", MethodName.constructor(List(O, O)), List(i(5), i(6)))) + } + + @Test def printLoadModule(): Unit = { + assertPrintEquals("mod:scala.Predef$", LoadModule("scala.Predef$")) + } + + @Test def printStoreModule(): Unit = { + assertPrintEquals("mod:scala.Predef$<-this", + StoreModule("scala.Predef$", This()("scala.Predef$"))) + } + + @Test def printSelect(): Unit = { + assertPrintEquals("x.test.Test::f", + Select(ref("x", "test.Test"), "test.Test", "f")(IntType)) + } + + @Test def printSelectStatic(): Unit = { + assertPrintEquals("test.Test::f", + SelectStatic("test.Test", "f")(IntType)) + } + + @Test def printApply(): Unit = { + assertPrintEquals("x.m;V()", + Apply(EAF, ref("x", "test.Test"), MethodName("m", Nil, V), Nil)(NoType)) + assertPrintEquals("x.m;I;I(5)", + Apply(EAF, ref("x", "test.Test"), MethodName("m", List(I), I), + List(i(5)))(IntType)) + assertPrintEquals("x.m;I;I;I(5, 6)", + Apply(EAF, ref("x", "test.Test"), MethodName("m", List(I, I), I), + List(i(5), i(6)))(IntType)) + } + + @Test def printApplyStatically(): Unit = { + assertPrintEquals("x.test.Test::m;V()", + ApplyStatically(EAF, ref("x", "test.Test"), "test.Test", + MethodName("m", Nil, V), Nil)(NoType)) + assertPrintEquals("x.test.Test::m;I;I(5)", + ApplyStatically(EAF, ref("x", "test.Test"), "test.Test", + MethodName("m", List(I), I), List(i(5)))(IntType)) + assertPrintEquals("x.test.Test::m;I;I;I(5, 6)", + ApplyStatically(EAF, ref("x", "test.Test"), "test.Test", + MethodName("m", List(I, I), I), List(i(5), i(6)))(IntType)) + + assertPrintEquals("x.test.Test::private::m;V()", + ApplyStatically(EAF.withPrivate(true), ref("x", "test.Test"), + "test.Test", MethodName("m", Nil, V), Nil)(NoType)) + } + + @Test def printApplyStatic(): Unit = { + assertPrintEquals("test.Test::m;V()", + ApplyStatic(EAF, "test.Test", MethodName("m", Nil, V), Nil)(NoType)) + assertPrintEquals("test.Test::m;I;I(5)", + ApplyStatic(EAF, "test.Test", MethodName("m", List(I), I), + List(i(5)))(IntType)) + assertPrintEquals("test.Test::m;I;I;I(5, 6)", + ApplyStatic(EAF, "test.Test", MethodName("m", List(I, I), I), + List(i(5), i(6)))(IntType)) + + assertPrintEquals("test.Test::private::m;V()", + ApplyStatic(EAF.withPrivate(true), "test.Test", MethodName("m", Nil, V), + Nil)(NoType)) + } + + @Test def printApplyDynamicImportStatic(): Unit = { + assertPrintEquals("dynamicImport test.Test::m;Ljava.lang.Object()", + ApplyDynamicImport(EAF, "test.Test", MethodName("m", Nil, O), Nil)) + } + + @Test def printUnaryOp(): Unit = { + import UnaryOp._ + + assertPrintEquals("(!x)", UnaryOp(Boolean_!, ref("x", BooleanType))) + + assertPrintEquals("((int)x)", UnaryOp(CharToInt, ref("x", CharType))) + assertPrintEquals("((int)x)", UnaryOp(ByteToInt, ref("x", ByteType))) + assertPrintEquals("((int)x)", UnaryOp(ShortToInt, ref("x", ShortType))) + assertPrintEquals("((long)x)", UnaryOp(IntToLong, ref("x", IntType))) + assertPrintEquals("((double)x)", UnaryOp(IntToDouble, ref("x", IntType))) + assertPrintEquals("((double)x)", UnaryOp(FloatToDouble, ref("x", FloatType))) + + assertPrintEquals("((char)x)", UnaryOp(IntToChar, ref("x", IntType))) + assertPrintEquals("((byte)x)", UnaryOp(IntToByte, ref("x", IntType))) + assertPrintEquals("((short)x)", UnaryOp(IntToShort, ref("x", IntType))) + assertPrintEquals("((int)x)", UnaryOp(LongToInt, ref("x", LongType))) + assertPrintEquals("((int)x)", UnaryOp(DoubleToInt, ref("x", DoubleType))) + assertPrintEquals("((float)x)", UnaryOp(DoubleToFloat, ref("x", DoubleType))) + + assertPrintEquals("((double)x)", UnaryOp(LongToDouble, ref("x", LongType))) + assertPrintEquals("((long)x)", UnaryOp(DoubleToLong, ref("x", DoubleType))) + + assertPrintEquals("((float)x)", UnaryOp(LongToFloat, ref("x", LongType))) + + assertPrintEquals("x.length", UnaryOp(String_length, ref("x", StringType))) + } + + @Test def printPseudoUnaryOp(): Unit = { + import BinaryOp._ + + assertPrintEquals("(-x)", BinaryOp(Int_-, i(0), ref("x", IntType))) + assertPrintEquals("(-x)", BinaryOp(Long_-, l(0), ref("x", LongType))) + assertPrintEquals("(-x)", BinaryOp(Float_-, f(0), ref("x", FloatType))) + assertPrintEquals("(-x)", BinaryOp(Double_-, d(0), ref("x", DoubleType))) + + assertPrintEquals("(~x)", BinaryOp(Int_^, i(-1), ref("x", IntType))) + assertPrintEquals("(~x)", BinaryOp(Long_^, l(-1), ref("x", LongType))) + } + + @Test def printBinaryOp(): Unit = { + import BinaryOp._ + + assertPrintEquals("(x === y)", + BinaryOp(===, ref("x", AnyType), ref("y", AnyType))) + assertPrintEquals("(x !== y)", + BinaryOp(!==, ref("x", AnyType), ref("y", AnyType))) + + assertPrintEquals("(x +[string] y)", + BinaryOp(String_+, ref("x", AnyType), ref("y", AnyType))) + + assertPrintEquals("(x ==[bool] y)", + BinaryOp(Boolean_==, ref("x", BooleanType), ref("y", BooleanType))) + assertPrintEquals("(x !=[bool] y)", + BinaryOp(Boolean_!=, ref("x", BooleanType), ref("y", BooleanType))) + assertPrintEquals("(x |[bool] y)", + BinaryOp(Boolean_|, ref("x", BooleanType), ref("y", BooleanType))) + assertPrintEquals("(x &[bool] y)", + BinaryOp(Boolean_&, ref("x", BooleanType), ref("y", BooleanType))) + + assertPrintEquals("(x +[int] y)", + BinaryOp(Int_+, ref("x", IntType), ref("y", IntType))) + assertPrintEquals("(x -[int] y)", + BinaryOp(Int_-, ref("x", IntType), ref("y", IntType))) + assertPrintEquals("(x *[int] y)", + BinaryOp(Int_*, ref("x", IntType), ref("y", IntType))) + assertPrintEquals("(x /[int] y)", + BinaryOp(Int_/, ref("x", IntType), ref("y", IntType))) + assertPrintEquals("(x %[int] y)", + BinaryOp(Int_%, ref("x", IntType), ref("y", IntType))) + + assertPrintEquals("(x |[int] y)", + BinaryOp(Int_|, ref("x", IntType), ref("y", IntType))) + assertPrintEquals("(x &[int] y)", + BinaryOp(Int_&, ref("x", IntType), ref("y", IntType))) + assertPrintEquals("(x ^[int] y)", + BinaryOp(Int_^, ref("x", IntType), ref("y", IntType))) + assertPrintEquals("(x <<[int] y)", + BinaryOp(Int_<<, ref("x", IntType), ref("y", IntType))) + assertPrintEquals("(x >>>[int] y)", + BinaryOp(Int_>>>, ref("x", IntType), ref("y", IntType))) + assertPrintEquals("(x >>[int] y)", + BinaryOp(Int_>>, ref("x", IntType), ref("y", IntType))) + + assertPrintEquals("(x ==[int] y)", + BinaryOp(Int_==, ref("x", IntType), ref("y", IntType))) + assertPrintEquals("(x !=[int] y)", + BinaryOp(Int_!=, ref("x", IntType), ref("y", IntType))) + assertPrintEquals("(x <[int] y)", + BinaryOp(Int_<, ref("x", IntType), ref("y", IntType))) + assertPrintEquals("(x <=[int] y)", + BinaryOp(Int_<=, ref("x", IntType), ref("y", IntType))) + assertPrintEquals("(x >[int] y)", + BinaryOp(Int_>, ref("x", IntType), ref("y", IntType))) + assertPrintEquals("(x >=[int] y)", + BinaryOp(Int_>=, ref("x", IntType), ref("y", IntType))) + + assertPrintEquals("(x +[long] y)", + BinaryOp(Long_+, ref("x", LongType), ref("y", LongType))) + assertPrintEquals("(x -[long] y)", + BinaryOp(Long_-, ref("x", LongType), ref("y", LongType))) + assertPrintEquals("(x *[long] y)", + BinaryOp(Long_*, ref("x", LongType), ref("y", LongType))) + assertPrintEquals("(x /[long] y)", + BinaryOp(Long_/, ref("x", LongType), ref("y", LongType))) + assertPrintEquals("(x %[long] y)", + BinaryOp(Long_%, ref("x", LongType), ref("y", LongType))) + + assertPrintEquals("(x |[long] y)", + BinaryOp(Long_|, ref("x", LongType), ref("y", LongType))) + assertPrintEquals("(x &[long] y)", + BinaryOp(Long_&, ref("x", LongType), ref("y", LongType))) + assertPrintEquals("(x ^[long] y)", + BinaryOp(Long_^, ref("x", LongType), ref("y", LongType))) + assertPrintEquals("(x <<[long] y)", + BinaryOp(Long_<<, ref("x", LongType), ref("y", IntType))) + assertPrintEquals("(x >>>[long] y)", + BinaryOp(Long_>>>, ref("x", LongType), ref("y", IntType))) + assertPrintEquals("(x >>[long] y)", + BinaryOp(Long_>>, ref("x", LongType), ref("y", IntType))) + + assertPrintEquals("(x ==[long] y)", + BinaryOp(Long_==, ref("x", LongType), ref("y", LongType))) + assertPrintEquals("(x !=[long] y)", + BinaryOp(Long_!=, ref("x", LongType), ref("y", LongType))) + assertPrintEquals("(x <[long] y)", + BinaryOp(Long_<, ref("x", LongType), ref("y", LongType))) + assertPrintEquals("(x <=[long] y)", + BinaryOp(Long_<=, ref("x", LongType), ref("y", LongType))) + assertPrintEquals("(x >[long] y)", + BinaryOp(Long_>, ref("x", LongType), ref("y", LongType))) + assertPrintEquals("(x >=[long] y)", + BinaryOp(Long_>=, ref("x", LongType), ref("y", LongType))) + + assertPrintEquals("(x +[float] y)", + BinaryOp(Float_+, ref("x", FloatType), ref("y", FloatType))) + assertPrintEquals("(x -[float] y)", + BinaryOp(Float_-, ref("x", FloatType), ref("y", FloatType))) + assertPrintEquals("(x *[float] y)", + BinaryOp(Float_*, ref("x", FloatType), ref("y", FloatType))) + assertPrintEquals("(x /[float] y)", + BinaryOp(Float_/, ref("x", FloatType), ref("y", FloatType))) + assertPrintEquals("(x %[float] y)", + BinaryOp(Float_%, ref("x", FloatType), ref("y", FloatType))) + + assertPrintEquals("(x +[double] y)", + BinaryOp(Double_+, ref("x", DoubleType), ref("y", DoubleType))) + assertPrintEquals("(x -[double] y)", + BinaryOp(Double_-, ref("x", DoubleType), ref("y", DoubleType))) + assertPrintEquals("(x *[double] y)", + BinaryOp(Double_*, ref("x", DoubleType), ref("y", DoubleType))) + assertPrintEquals("(x /[double] y)", + BinaryOp(Double_/, ref("x", DoubleType), ref("y", DoubleType))) + assertPrintEquals("(x %[double] y)", + BinaryOp(Double_%, ref("x", DoubleType), ref("y", DoubleType))) + + assertPrintEquals("(x ==[double] y)", + BinaryOp(Double_==, ref("x", DoubleType), ref("y", DoubleType))) + assertPrintEquals("(x !=[double] y)", + BinaryOp(Double_!=, ref("x", DoubleType), ref("y", DoubleType))) + assertPrintEquals("(x <[double] y)", + BinaryOp(Double_<, ref("x", DoubleType), ref("y", DoubleType))) + assertPrintEquals("(x <=[double] y)", + BinaryOp(Double_<=, ref("x", DoubleType), ref("y", DoubleType))) + assertPrintEquals("(x >[double] y)", + BinaryOp(Double_>, ref("x", DoubleType), ref("y", DoubleType))) + assertPrintEquals("(x >=[double] y)", + BinaryOp(Double_>=, ref("x", DoubleType), ref("y", DoubleType))) + + assertPrintEquals("x[y]", + BinaryOp(String_charAt, ref("x", StringType), ref("y", IntType))) + } + + @Test def printNewArray(): Unit = { + assertPrintEquals("new int[3]", NewArray(ArrayTypeRef(IntRef, 1), List(i(3)))) + assertPrintEquals("new int[3][]", NewArray(ArrayTypeRef(IntRef, 2), List(i(3)))) + assertPrintEquals("new java.lang.Object[3][4][][]", + NewArray(ArrayTypeRef(ObjectClass, 4), List(i(3), i(4)))) + } + + @Test def printArrayValue(): Unit = { + assertPrintEquals("int[]()", + ArrayValue(ArrayTypeRef(IntRef, 1), List())) + assertPrintEquals("int[](5, 6)", + ArrayValue(ArrayTypeRef(IntRef, 1), List(i(5), i(6)))) + + assertPrintEquals("int[][](null)", + ArrayValue(ArrayTypeRef(IntRef, 2), List(Null()))) + } + + @Test def printArrayLength(): Unit = { + assertPrintEquals("x.length", ArrayLength(ref("x", arrayType(IntRef, 1)))) + } + + @Test def printArraySelect(): Unit = { + assertPrintEquals("x[3]", + ArraySelect(ref("x", arrayType(IntRef, 1)), i(3))(IntType)) + } + + @Test def printRecordValue(): Unit = { + assertPrintEquals("(x = 3, y = 4)", + RecordValue( + RecordType(List( + RecordType.Field("x", NON, IntType, mutable = false), + RecordType.Field("y", NON, IntType, mutable = true))), + List(i(3), i(4)))) + } + + @Test def printIsInstanceOf(): Unit = { + assertPrintEquals("x.isInstanceOf[java.lang.String]", + IsInstanceOf(ref("x", AnyType), ClassType(BoxedStringClass))) + } + + @Test def printAsInstanceOf(): Unit = { + assertPrintEquals("x.asInstanceOf[java.lang.String]", + AsInstanceOf(ref("x", AnyType), ClassType(BoxedStringClass))) + assertPrintEquals("x.asInstanceOf[int]", + AsInstanceOf(ref("x", AnyType), IntType)) + } + + @Test def printGetClass(): Unit = { + assertPrintEquals("x.getClass()", GetClass(ref("x", AnyType))) + } + + @Test def printClone(): Unit = { + assertPrintEquals("(x)", Clone(ref("x", arrayType(ObjectClass, 1)))) + } + + @Test def printIdentityHashCode(): Unit = { + assertPrintEquals("(x)", IdentityHashCode(ref("x", AnyType))) + } + + @Test def printWrapAsThrowable(): Unit = { + assertPrintEquals("(e)", WrapAsThrowable(ref("e", AnyType))) + } + + @Test def printUnwrapFromThrowable(): Unit = { + assertPrintEquals("(e)", + UnwrapFromThrowable(ref("e", ClassType(ThrowableClass)))) + } + + @Test def printJSNew(): Unit = { + assertPrintEquals("new C()", JSNew(ref("C", AnyType), Nil)) + assertPrintEquals("new C(4, 5)", JSNew(ref("C", AnyType), List(i(4), i(5)))) + assertPrintEquals("new x.test.Test::C(4, 5)", + JSNew(JSPrivateSelect(ref("x", AnyType), "test.Test", "C"), List(i(4), i(5)))) + assertPrintEquals("""new x["C"]()""", + JSNew(JSSelect(ref("x", AnyType), StringLiteral("C")), Nil)) + + val fApplied = JSFunctionApply(ref("f", AnyType), Nil) + assertPrintEquals("new (f())()", JSNew(fApplied, Nil)) + assertPrintEquals("new (f().test.Test::C)(4, 5)", + JSNew(JSPrivateSelect(fApplied, "test.Test", "C"), List(i(4), i(5)))) + assertPrintEquals("""new (f()["C"])()""", + JSNew(JSSelect(fApplied, StringLiteral("C")), Nil)) + } + + @Test def printJSPrivateSelect(): Unit = { + assertPrintEquals("x.test.Test::f", + JSPrivateSelect(ref("x", AnyType), "test.Test", "f")) + } + + @Test def printJSSelect(): Unit = { + assertPrintEquals("""x["f"]""", + JSSelect(ref("x", AnyType), StringLiteral("f"))) + } + + @Test def printJSFunctionApply(): Unit = { + assertPrintEquals("f()", JSFunctionApply(ref("f", AnyType), Nil)) + assertPrintEquals("f(3, 4)", + JSFunctionApply(ref("f", AnyType), List(i(3), i(4)))) + + assertPrintEquals("(0, x.test.Test::f)()", + JSFunctionApply(JSPrivateSelect(ref("x", AnyType), "test.Test", "f"), Nil)) + assertPrintEquals("""(0, x["f"])()""", + JSFunctionApply(JSSelect(ref("x", AnyType), StringLiteral("f")), + Nil)) + assertPrintEquals("(0, x.test.Test::f)()", + JSFunctionApply(Select(ref("x", "test.Test"), "test.Test", "f")(AnyType), + Nil)) + } + + @Test def printJSMethodApply(): Unit = { + assertPrintEquals("""x["m"]()""", + JSMethodApply(ref("x", AnyType), StringLiteral("m"), Nil)) + assertPrintEquals("""x["m"](4, 5)""", + JSMethodApply(ref("x", AnyType), StringLiteral("m"), + List(i(4), i(5)))) + } + + @Test def printJSSuperSelect(): Unit = { + assertPrintEquals("""super(sc)::x["f"]""", + JSSuperSelect(ref("sc", AnyType), ref("x", AnyType), StringLiteral("f"))) + } + + @Test def printJSSuperMethodCall(): Unit = { + assertPrintEquals("""super(sc)::x["f"]()""", + JSSuperMethodCall(ref("sc", AnyType), ref("x", AnyType), StringLiteral("f"), Nil)) + } + + @Test def printJSSuperConstructorCall(): Unit = { + assertPrintEquals("super()", JSSuperConstructorCall(Nil)) + assertPrintEquals("super(4, 5)", JSSuperConstructorCall(List(i(4), i(5)))) + } + + @Test def printJSImportCall(): Unit = { + assertPrintEquals("""import("foo.js")""", JSImportCall(StringLiteral("foo.js"))) + } + + @Test def printJSNewTarget(): Unit = { + assertPrintEquals("new.target", JSNewTarget()) + } + + @Test def printJSImportMeta(): Unit = { + assertPrintEquals("import.meta", JSImportMeta()) + } + + @Test def printLoadJSConstructor(): Unit = { + assertPrintEquals("constructorOf[Test]", LoadJSConstructor("Test")) + } + + @Test def printLoadJSModule(): Unit = { + assertPrintEquals("mod:Test$", LoadJSModule("Test$")) + } + + @Test def printJSSpread(): Unit = { + assertPrintEquals("...x", JSSpread(ref("x", AnyType))) + } + + @Test def printJSDelete(): Unit = { + assertPrintEquals("""delete x["f"]""", + JSDelete(ref("x", AnyType), StringLiteral("f"))) + } + + @Test def printJSUnaryOp(): Unit = { + assertPrintEquals("(+x)", JSUnaryOp(JSUnaryOp.+, ref("x", AnyType))) + assertPrintEquals("(-x)", JSUnaryOp(JSUnaryOp.-, ref("x", AnyType))) + assertPrintEquals("(~x)", JSUnaryOp(JSUnaryOp.~, ref("x", AnyType))) + assertPrintEquals("(!x)", JSUnaryOp(JSUnaryOp.!, ref("x", AnyType))) + assertPrintEquals("(typeof x)", + JSUnaryOp(JSUnaryOp.typeof, ref("x", AnyType))) + } + + @Test def printJSBinaryOp(): Unit = { + assertPrintEquals("(x === y)", + JSBinaryOp(JSBinaryOp.===, ref("x", AnyType), ref("y", AnyType))) + assertPrintEquals("(x !== y)", + JSBinaryOp(JSBinaryOp.!==, ref("x", AnyType), ref("y", AnyType))) + + assertPrintEquals("(x + y)", + JSBinaryOp(JSBinaryOp.+, ref("x", AnyType), ref("y", AnyType))) + assertPrintEquals("(x - y)", + JSBinaryOp(JSBinaryOp.-, ref("x", AnyType), ref("y", AnyType))) + assertPrintEquals("(x * y)", + JSBinaryOp(JSBinaryOp.*, ref("x", AnyType), ref("y", AnyType))) + assertPrintEquals("(x / y)", + JSBinaryOp(JSBinaryOp./, ref("x", AnyType), ref("y", AnyType))) + assertPrintEquals("(x % y)", + JSBinaryOp(JSBinaryOp.%, ref("x", AnyType), ref("y", AnyType))) + + assertPrintEquals("(x | y)", + JSBinaryOp(JSBinaryOp.|, ref("x", AnyType), ref("y", AnyType))) + assertPrintEquals("(x & y)", + JSBinaryOp(JSBinaryOp.&, ref("x", AnyType), ref("y", AnyType))) + assertPrintEquals("(x ^ y)", + JSBinaryOp(JSBinaryOp.^, ref("x", AnyType), ref("y", AnyType))) + assertPrintEquals("(x << y)", + JSBinaryOp(JSBinaryOp.<<, ref("x", AnyType), ref("y", AnyType))) + assertPrintEquals("(x >>> y)", + JSBinaryOp(JSBinaryOp.>>>, ref("x", AnyType), ref("y", AnyType))) + assertPrintEquals("(x >> y)", + JSBinaryOp(JSBinaryOp.>>, ref("x", AnyType), ref("y", AnyType))) + + assertPrintEquals("(x < y)", + JSBinaryOp(JSBinaryOp.<, ref("x", AnyType), ref("y", AnyType))) + assertPrintEquals("(x <= y)", + JSBinaryOp(JSBinaryOp.<=, ref("x", AnyType), ref("y", AnyType))) + assertPrintEquals("(x > y)", + JSBinaryOp(JSBinaryOp.>, ref("x", AnyType), ref("y", AnyType))) + assertPrintEquals("(x >= y)", + JSBinaryOp(JSBinaryOp.>=, ref("x", AnyType), ref("y", AnyType))) + + assertPrintEquals("(x && y)", + JSBinaryOp(JSBinaryOp.&&, ref("x", AnyType), ref("y", AnyType))) + assertPrintEquals("(x || y)", + JSBinaryOp(JSBinaryOp.||, ref("x", AnyType), ref("y", AnyType))) + + assertPrintEquals("(x in y)", + JSBinaryOp(JSBinaryOp.in, ref("x", AnyType), ref("y", AnyType))) + assertPrintEquals("(x instanceof y)", + JSBinaryOp(JSBinaryOp.instanceof, ref("x", AnyType), ref("y", AnyType))) + + assertPrintEquals("(x ** y)", + JSBinaryOp(JSBinaryOp.**, ref("x", AnyType), ref("y", AnyType))) + } + + @Test def printJSArrayConstr(): Unit = { + assertPrintEquals("[]", JSArrayConstr(Nil)) + assertPrintEquals("[5, 6]", JSArrayConstr(List(i(5), i(6)))) + } + + @Test def printJSObjectConstr(): Unit = { + assertPrintEquals("{}", JSObjectConstr(Nil)) + + assertPrintEquals( + """ + |{ + | [x]: 5, + | "g": 6 + |} + """, + JSObjectConstr(List(ref("x", AnyType) -> i(5), StringLiteral("g") -> i(6)))) + } + + @Test def printGlobalRef(): Unit = { + assertPrintEquals("global:Foo", JSGlobalRef("Foo")) + } + + @Test def printJSTypeOfGlobalRef(): Unit = { + assertPrintEquals("(typeof global:Foo)", JSTypeOfGlobalRef(JSGlobalRef("Foo"))) + } + + @Test def printJSLinkingInfo(): Unit = { + assertPrintEquals("", JSLinkingInfo()) + } + + @Test def printUndefined(): Unit = { + assertPrintEquals("(void 0)", Undefined()) + } + + @Test def printNull(): Unit = { + assertPrintEquals("null", Null()) + } + + @Test def printBoolean(): Unit = { + assertPrintEquals("true", BooleanLiteral(true)) + assertPrintEquals("false", BooleanLiteral(false)) + } + + @Test def printCharLiteral(): Unit = { + assertPrintEquals("'A'", CharLiteral('A')) + assertPrintEquals("'\\u0005'", CharLiteral('\u0005')) + assertPrintEquals("'\\ufffb'", CharLiteral('\ufffb')) + } + + @Test def printByteLiteral(): Unit = { + assertPrintEquals("5_b", ByteLiteral(5)) + assertPrintEquals("(-5_b)", ByteLiteral(-5)) + } + + @Test def printShortLiteral(): Unit = { + assertPrintEquals("5_s", ShortLiteral(5)) + assertPrintEquals("(-5_s)", ShortLiteral(-5)) + } + + @Test def printIntLiteral(): Unit = { + assertPrintEquals("5", IntLiteral(5)) + assertPrintEquals("(-5)", IntLiteral(-5)) + } + + @Test def printLongLiteral(): Unit = { + assertPrintEquals("5L", LongLiteral(5L)) + assertPrintEquals("(-5L)", LongLiteral(-5L)) + } + + @Test def printFloatLiteral(): Unit = { + assertPrintEquals(0.0f.toString + "f", FloatLiteral(0.0f)) + assertPrintEquals("(-0f)", FloatLiteral(-0.0f)) + assertPrintEquals("Infinityf", FloatLiteral(Float.PositiveInfinity)) + assertPrintEquals("(-Infinityf)", FloatLiteral(Float.NegativeInfinity)) + assertPrintEquals("NaNf", FloatLiteral(Float.NaN)) + + assertPrintEquals(1.0f.toString + "f", FloatLiteral(1.0f)) + assertPrintEquals(1.5f.toString + "f", FloatLiteral(1.5f)) + assertPrintEquals("(" + (-1.5f).toString + "f)", FloatLiteral(-1.5f)) + } + + @Test def printDoubleLiteral(): Unit = { + assertPrintEquals(0.0.toString + "d", DoubleLiteral(0.0)) + assertPrintEquals("(-0d)", DoubleLiteral(-0.0)) + assertPrintEquals("Infinityd", DoubleLiteral(Double.PositiveInfinity)) + assertPrintEquals("(-Infinityd)", DoubleLiteral(Double.NegativeInfinity)) + assertPrintEquals("NaNd", DoubleLiteral(Double.NaN)) + + assertPrintEquals(1.0.toString + "d", DoubleLiteral(1.0)) + assertPrintEquals(1.5.toString + "d", DoubleLiteral(1.5)) + assertPrintEquals("(" + (-1.5).toString + "d)", DoubleLiteral(-1.5)) + } + + @Test def printStringLiteral(): Unit = { + assertPrintEquals(raw"""""""", StringLiteral("")) + assertPrintEquals(raw""""foo"""", StringLiteral("foo")) + assertPrintEquals(raw""""fo\no"""", StringLiteral("fo\no")) + assertPrintEquals("\"a\\u1234b\"", StringLiteral("a\u1234b")) + } + + @Test def printClassOf(): Unit = { + assertPrintEquals("classOf[Test]", ClassOf("Test")) + } + + @Test def printVarRef(): Unit = { + assertPrintEquals("x", VarRef("x")(IntType)) + } + + @Test def printThis(): Unit = { + assertPrintEquals("this", This()(AnyType)) + } + + @Test def printClosure(): Unit = { + assertPrintEquals( + """ + |(lambda<>(): any = { + | 5 + |}) + """, + Closure(false, Nil, Nil, None, i(5), Nil)) + + assertPrintEquals( + """ + |(arrow-lambda(z: any): any = { + | z + |}) + """, + Closure( + true, + List( + ParamDef("x", NON, AnyType, mutable = false), + ParamDef("y", TestON, IntType, mutable = false)), + List(ParamDef("z", NON, AnyType, mutable = false)), + None, + ref("z", AnyType), + List(ref("a", IntType), i(6)))) + + assertPrintEquals( + """ + |(lambda<>(...z: any): any = { + | z + |}) + """, + Closure(false, Nil, Nil, + Some(ParamDef("z", NON, AnyType, mutable = false)), + ref("z", AnyType), Nil)) + } + + @Test def printCreateJSClass(): Unit = { + assertPrintEquals( + """ + |createjsclass[Foo](x, y) + """, + CreateJSClass("Foo", List(ref("x", IntType), ref("y", AnyType)))) + } + + @Test def printTransient(): Unit = { + class MyTransient(expr: Tree) extends Transient.Value { + val tpe: Type = AnyType + + def traverse(traverser: Traversers.Traverser): Unit = ??? + + def transform(transformer: Transformers.Transformer, isStat: Boolean)( + implicit pos: Position): Tree = ??? + + def printIR(out: Printers.IRTreePrinter): Unit = { + out.print("mytransient(") + out.print(expr) + out.print(")") + } + } + + assertPrintEquals("mytransient(5)", + Transient(new MyTransient(i(5)))) + } + + @Test def printClassDefKinds(): Unit = { + import ClassKind._ + + def makeForKind(kind: ClassKind): ClassDef = { + ClassDef("Test", NON, kind, None, Some(ObjectClass), Nil, None, None, Nil, + Nil)( + NoOptHints) + } + + assertPrintEquals( + """ + |class Test extends java.lang.Object { + |} + """, + makeForKind(Class)) + + assertPrintEquals( + """ + |module class Test extends java.lang.Object { + |} + """, + makeForKind(ModuleClass)) + + assertPrintEquals( + """ + |interface Test extends java.lang.Object { + |} + """, + makeForKind(Interface)) + + assertPrintEquals( + """ + |abstract js type Test extends java.lang.Object { + |} + """, + makeForKind(AbstractJSType)) + + assertPrintEquals( + """ + |hijacked class Test extends java.lang.Object { + |} + """, + makeForKind(HijackedClass)) + + assertPrintEquals( + """ + |js class Test extends java.lang.Object { + |} + """, + makeForKind(JSClass)) + + assertPrintEquals( + """ + |js module class Test extends java.lang.Object { + |} + """, + makeForKind(JSModuleClass)) + + assertPrintEquals( + """ + |native js class Test extends java.lang.Object { + |} + """, + makeForKind(NativeJSClass)) + + assertPrintEquals( + """ + |native js module class Test extends java.lang.Object { + |} + """, + makeForKind(NativeJSModuleClass)) + } + + @Test def printClassDefParents(): Unit = { + def makeForParents(superClass: Option[ClassIdent], + interfaces: List[ClassIdent]): ClassDef = { + ClassDef("Test", NON, ClassKind.Class, None, superClass, interfaces, None, + None, Nil, Nil)( + NoOptHints) + } + + assertPrintEquals( + """ + |class Test { + |} + """, + makeForParents(None, Nil)) + + assertPrintEquals( + """ + |class Test extends java.lang.Object implements Intf { + |} + """, + makeForParents(Some(ObjectClass), List("Intf"))) + + assertPrintEquals( + """ + |class Test extends sr_AbstractFunction0 implements Intf1, Intf2 { + |} + """, + makeForParents(Some("sr_AbstractFunction0"), List("Intf1", "Intf2"))) + } + + @Test def printClassDefJSNativeLoadSpec(): Unit = { + assertPrintEquals( + """ + |native js class Test extends java.lang.Object loadfrom global:Foo["Bar"] { + |} + """, + ClassDef("Test", NON, ClassKind.NativeJSClass, None, Some(ObjectClass), Nil, + None, Some(JSNativeLoadSpec.Global("Foo", List("Bar"))), Nil, Nil)( + NoOptHints)) + + assertPrintEquals( + """ + |native js class Test extends java.lang.Object loadfrom import(foo)["Bar"] { + |} + """, + ClassDef("Test", NON, ClassKind.NativeJSClass, None, Some(ObjectClass), Nil, + None, Some(JSNativeLoadSpec.Import("foo", List("Bar"))), Nil, Nil)( + NoOptHints)) + + assertPrintEquals( + """ + |native js class Test extends java.lang.Object loadfrom import(foo)["Bar"] fallback global:Baz["Foobar"] { + |} + """, + ClassDef("Test", NON, ClassKind.NativeJSClass, None, Some(ObjectClass), Nil, + None, + Some(JSNativeLoadSpec.ImportWithGlobalFallback( + JSNativeLoadSpec.Import("foo", List("Bar")), + JSNativeLoadSpec.Global("Baz", List("Foobar")))), Nil, Nil)( + NoOptHints)) + } + + @Test def printClassDefJSClassCaptures(): Unit = { + assertPrintEquals( + """ + |captures: none + |js class Test extends java.lang.Object { + |} + """, + ClassDef("Test", NON, ClassKind.JSClass, Some(Nil), Some(ObjectClass), Nil, + None, None, Nil, Nil)( + NoOptHints)) + + assertPrintEquals( + """ + |captures: x: int, y{orig name}: string + |js class Test extends java.lang.Object { + |} + """, + ClassDef("Test", NON, ClassKind.JSClass, + Some(List( + ParamDef("x", NON, IntType, mutable = false), + ParamDef("y", TestON, StringType, mutable = false) + )), + Some(ObjectClass), Nil, None, None, Nil, Nil)( + NoOptHints)) + } + + @Test def printClassDefJSSuperClass(): Unit = { + assertPrintEquals( + """ + |captures: sup: any + |js class Test extends Bar (via sup) { + |} + """, + ClassDef("Test", NON, ClassKind.JSClass, + Some(List(ParamDef("sup", NON, AnyType, mutable = false))), + Some("Bar"), Nil, Some(ref("sup", AnyType)), None, Nil, Nil)( + NoOptHints)) + } + + @Test def printClassDefOptimizerHints(): Unit = { + assertPrintEquals( + """ + |@hints(1) class Test extends java.lang.Object { + |} + """, + ClassDef("Test", NON, ClassKind.Class, None, Some(ObjectClass), Nil, + None, None, Nil, Nil)( + NoOptHints.withInline(true))) + } + + @Test def printClassDefOriginalName(): Unit = { + assertPrintEquals( + """ + |module class Test{orig name} extends java.lang.Object { + |} + """, + ClassDef("Test", TestON, ClassKind.ModuleClass, None, Some(ObjectClass), + Nil, None, None, Nil, Nil)( + NoOptHints)) + } + + @Test def printClassDefDefs(): Unit = { + assertPrintEquals( + """ + |module class Test extends java.lang.Object { + | val x: int + | var y: int + | export top[moduleID="main"] module "Foo" + |} + """, + ClassDef("Test", NON, ClassKind.ModuleClass, None, Some(ObjectClass), + Nil, None, None, + List( + FieldDef(MemberFlags.empty, "x", NON, IntType), + FieldDef(MemberFlags.empty.withMutable(true), "y", NON, IntType)), + List( + TopLevelModuleExportDef("main", "Foo")))( + NoOptHints)) + } + + @Test def printFieldDef(): Unit = { + assertPrintEquals("val x: int", + FieldDef(MemberFlags.empty, "x", NON, IntType)) + assertPrintEquals("var y: any", + FieldDef(MemberFlags.empty.withMutable(true), "y", NON, AnyType)) + assertPrintEquals("val x{orig name}: int", + FieldDef(MemberFlags.empty, "x", TestON, IntType)) + } + + @Test def printJSFieldDef(): Unit = { + assertPrintEquals("""val "x": int""", + JSFieldDef(MemberFlags.empty, StringLiteral("x"), IntType)) + assertPrintEquals("""var "y": any""", + JSFieldDef(MemberFlags.empty.withMutable(true), StringLiteral("y"), AnyType)) + + assertPrintEquals("""static val "x": int""", + JSFieldDef(MemberFlags.empty.withNamespace(Static), StringLiteral("x"), IntType)) + assertPrintEquals("""static var "y": any""", + JSFieldDef(MemberFlags.empty.withNamespace(Static).withMutable(true), StringLiteral("y"), AnyType)) + } + + @Test def printMethodDef(): Unit = { + val mIIMethodName = MethodName("m", List(I), I) + val mIVMethodName = MethodName("m", List(I), V) + + assertPrintEquals( + """ + |def m;I;I(x: int): int = + """, + MethodDef(MemberFlags.empty, mIIMethodName, NON, + List(ParamDef("x", NON, IntType, mutable = false)), + IntType, None)(NoOptHints, None)) + + assertPrintEquals( + """ + |def m;I;I(x: int): int = { + | 5 + |} + """, + MethodDef(MemberFlags.empty, mIIMethodName, NON, + List(ParamDef("x", NON, IntType, mutable = false)), + IntType, Some(i(5)))(NoOptHints, None)) + + assertPrintEquals( + """ + |@hints(1) def m;I;I(x: int): int = { + | 5 + |} + """, + MethodDef(MemberFlags.empty, mIIMethodName, NON, + List(ParamDef("x", NON, IntType, mutable = false)), + IntType, Some(i(5)))(NoOptHints.withInline(true), None)) + + assertPrintEquals( + """ + |def m;I;V(x: int) { + | 5 + |} + """, + MethodDef(MemberFlags.empty, mIVMethodName, NON, + List(ParamDef("x", NON, IntType, mutable = false)), + NoType, Some(i(5)))(NoOptHints, None)) + + assertPrintEquals( + """ + |static def m;I;I(x: int): int = { + | 5 + |} + """, + MethodDef(MemberFlags.empty.withNamespace(Static), mIIMethodName, NON, + List(ParamDef("x", NON, IntType, mutable = false)), + IntType, Some(i(5)))(NoOptHints, None)) + + assertPrintEquals( + """ + |private def m;I;I(x: int): int = { + | 5 + |} + """, + MethodDef(MemberFlags.empty.withNamespace(Private), mIIMethodName, NON, + List(ParamDef("x", NON, IntType, mutable = false)), + IntType, Some(i(5)))(NoOptHints, None)) + + assertPrintEquals( + """ + |private static def m;I;I(x: int): int = { + | 5 + |} + """, + MethodDef(MemberFlags.empty.withNamespace(PrivateStatic), mIIMethodName, NON, + List(ParamDef("x", NON, IntType, mutable = false)), + IntType, Some(i(5)))(NoOptHints, None)) + + assertPrintEquals( + """ + |def m;I;I{orig name}(x{orig name}: int): int = + """, + MethodDef(MemberFlags.empty, mIIMethodName, TestON, + List(ParamDef("x", TestON, IntType, mutable = false)), + IntType, None)(NoOptHints, None)) + } + + @Test def printJSConstructorDef(): Unit = { + assertPrintEquals( + """ + |constructor def constructor(x: any): any = { + | 5; + | super(6); + | (void 0) + |} + """, + JSConstructorDef(MemberFlags.empty.withNamespace(Constructor), + List(ParamDef("x", NON, AnyType, mutable = false)), None, + JSConstructorBody(List(i(5)), JSSuperConstructorCall(List(i(6))), List(Undefined())))( + NoOptHints, None)) + + assertPrintEquals( + """ + |constructor def constructor(x: any, ...y: any): any = { + | super(6); + | 7 + |} + """, + JSConstructorDef(MemberFlags.empty.withNamespace(Constructor), + List(ParamDef("x", NON, AnyType, mutable = false)), + Some(ParamDef("y", NON, AnyType, mutable = false)), + JSConstructorBody(Nil, JSSuperConstructorCall(List(i(6))), List(i(7))))( + NoOptHints, None)) + + // This example is an invalid constructor, but it should be printed anyway + assertPrintEquals( + """ + |def constructor(x{orig name}: any): any = { + | 5; + | super(6) + |} + """, + JSConstructorDef(MemberFlags.empty, + List(ParamDef("x", TestON, AnyType, mutable = false)), None, + JSConstructorBody(List(i(5)), JSSuperConstructorCall(List(i(6))), Nil))( + NoOptHints, None)) + } + + @Test def printJSMethodDef(): Unit = { + assertPrintEquals( + """ + |def "m"(x: any): any = { + | 5 + |} + """, + JSMethodDef(MemberFlags.empty, StringLiteral("m"), + List(ParamDef("x", NON, AnyType, mutable = false)), None, + i(5))(NoOptHints, None)) + + assertPrintEquals( + """ + |def "m"(x: any, ...y: any): any = { + | 5 + |} + """, + JSMethodDef(MemberFlags.empty, StringLiteral("m"), + List(ParamDef("x", NON, AnyType, mutable = false)), + Some(ParamDef("y", NON, AnyType, mutable = false)), + i(5))(NoOptHints, None)) + + assertPrintEquals( + """ + |static def "m"(x: any): any = { + | 5 + |} + """, + JSMethodDef(MemberFlags.empty.withNamespace(Static), StringLiteral("m"), + List(ParamDef("x", NON, AnyType, mutable = false)), None, + i(5))(NoOptHints, None)) + + assertPrintEquals( + """ + |def "m"(x{orig name}: any): any = { + | 5 + |} + """, + JSMethodDef(MemberFlags.empty, StringLiteral("m"), + List(ParamDef("x", TestON, AnyType, mutable = false)), None, + i(5))(NoOptHints, None)) + } + + @Test def printJSPropertyDef(): Unit = { + for (static <- Seq(false, true)) { + val staticStr = + if (static) "static " + else "" + val flags = + if (static) MemberFlags.empty.withNamespace(Static) + else MemberFlags.empty + + assertPrintEquals( + s""" + |${staticStr}get "prop"(): any = { + | 5 + |} + """, + JSPropertyDef(flags, StringLiteral("prop"), Some(i(5)), None)) + + assertPrintEquals( + s""" + |${staticStr}set "prop"(x: any) { + | 7 + |} + """, + JSPropertyDef(flags, StringLiteral("prop"), + None, + Some((ParamDef("x", NON, AnyType, mutable = false), i(7))))) + + assertPrintEquals( + s""" + |${staticStr}set "prop"(x{orig name}: any) { + | 7 + |} + """, + JSPropertyDef(flags, StringLiteral("prop"), + None, + Some((ParamDef("x", TestON, AnyType, mutable = false), i(7))))) + + assertPrintEquals( + s""" + |${staticStr}get "prop"(): any = { + | 5 + |} + |${staticStr}set "prop"(x: any) { + | 7 + |} + """, + JSPropertyDef(flags, StringLiteral("prop"), + Some(i(5)), + Some((ParamDef("x", NON, AnyType, mutable = false), + i(7))))) + } + } + + @Test def printJSClassExportDef(): Unit = { + assertPrintEquals( + """export top[moduleID="my-mod"] class "Foo"""", + TopLevelJSClassExportDef("my-mod", "Foo")) + } + + @Test def printTopLevelModuleExportDef(): Unit = { + assertPrintEquals( + """export top[moduleID="bar"] module "Foo"""", + TopLevelModuleExportDef("bar", "Foo")) + } + + @Test def printTopLevelMethodExportDef(): Unit = { + assertPrintEquals( + """ + |export top[moduleID="main"] static def "foo"(x: any): any = { + | 5 + |}""", + TopLevelMethodExportDef("main", JSMethodDef( + MemberFlags.empty.withNamespace(Static), StringLiteral("foo"), + List(ParamDef("x", NON, AnyType, mutable = false)), None, + i(5))(NoOptHints, None))) + } + + @Test def printTopLevelFieldExportDef(): Unit = { + assertPrintEquals( + """ + |export top[moduleID="main"] static field x$1 as "x" + """, + TopLevelFieldExportDef("main", "x", "x$1")) + } +} diff --git a/ir/shared/src/test/scala/org/scalajs/ir/SHA1Test.scala b/ir/shared/src/test/scala/org/scalajs/ir/SHA1Test.scala new file mode 100644 index 0000000000..74b5c75f04 --- /dev/null +++ b/ir/shared/src/test/scala/org/scalajs/ir/SHA1Test.scala @@ -0,0 +1,65 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.ir + +import java.lang.Byte.parseByte + +import org.junit.Test +import org.junit.Assert._ + +class SHA1Test { + @Test def testVector1(): Unit = { + val expected = "a9993e364706816aba3e25717850c26c9cd0d89d" + val actual = computeSHA1Full("abc") + assertEquals(expected, actual) + } + + @Test def testVector2(): Unit = { + val expected = "da39a3ee5e6b4b0d3255bfef95601890afd80709" + val actual = computeSHA1Full("") + assertEquals(expected, actual) + } + + @Test def testVector3(): Unit = { + val expected = "84983e441c3bd26ebaae4aa1f95129e5e54670f1" + val actual = computeSHA1Full("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") + assertEquals(expected, actual) + } + + @Test def testVector4(): Unit = { + val expected = "a49b2446a02c645bf419f995b67091253a04a259" + val builder = new SHA1.DigestBuilder + builder.update(string2bytes("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghij")) + builder.update(string2bytes("klmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu")) + val actual = hashString(builder.finalizeDigest()) + assertEquals(expected, actual) + } + + @Test def testVector5(): Unit = { + val expected = "34aa973cd4c4daa4f61eeb2bdbad27316534016f" + val actual = computeSHA1Full("a" * 1000000) + assertEquals(expected, actual) + } + + private def computeSHA1Full(input: String): String = { + val builder = new SHA1.DigestBuilder + builder.update(string2bytes(input)) + hashString(builder.finalizeDigest()) + } + + private def string2bytes(s: String): Array[Byte] = + s.toCharArray().map(_.toByte) + + private def hashString(hash: Array[Byte]): String = + hash.map(b => "%02x".format(b & 0xff)).mkString +} diff --git a/ir/shared/src/test/scala/org/scalajs/ir/TestIRBuilder.scala b/ir/shared/src/test/scala/org/scalajs/ir/TestIRBuilder.scala new file mode 100644 index 0000000000..7fa9de34c7 --- /dev/null +++ b/ir/shared/src/test/scala/org/scalajs/ir/TestIRBuilder.scala @@ -0,0 +1,82 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.ir + +import scala.language.implicitConversions + +import Names._ +import OriginalName.NoOriginalName +import Printers._ +import Trees._ +import Types._ + +object TestIRBuilder { + + implicit val dummyPos: Position = Position.NoPosition + + /** Empty ApplyFlags, for short. */ + val EAF = ApplyFlags.empty + + /** No original name, for short. */ + val NON = NoOriginalName + + /** No optimizer hints, for short. */ + val NoOptHints = OptimizerHints.empty + + // String -> Name conversions + implicit def string2fieldName(name: String): FieldName = + FieldName(name) + implicit def string2className(name: String): ClassName = + ClassName(name) + + // String -> Ident conversions + implicit def string2localIdent(name: String): LocalIdent = + LocalIdent(LocalName(name)) + implicit def string2labelIdent(name: String): LabelIdent = + LabelIdent(LabelName(name)) + implicit def string2fieldIdent(name: String): FieldIdent = + FieldIdent(FieldName(name)) + implicit def string2classIdent(name: String): ClassIdent = + ClassIdent(ClassName(name)) + + // String -> Type and TypeRef conversions + implicit def string2classType(className: String): ClassType = + ClassType(ClassName(className)) + implicit def string2classRef(className: String): ClassRef = + ClassRef(ClassName(className)) + + // Name -> Ident conversions + implicit def methodName2methodIdent(name: MethodName): MethodIdent = + MethodIdent(name) + implicit def className2classRef(className: ClassName): ClassRef = + ClassRef(className) + implicit def className2classIdent(name: ClassName): ClassIdent = + ClassIdent(name) + + val V = VoidRef + val I = IntRef + val O = ClassRef(ObjectClass) + + def b(value: Boolean): BooleanLiteral = BooleanLiteral(value) + def i(value: Int): IntLiteral = IntLiteral(value) + def l(value: Long): LongLiteral = LongLiteral(value) + def f(value: Float): FloatLiteral = FloatLiteral(value) + def d(value: Double): DoubleLiteral = DoubleLiteral(value) + def s(value: String): StringLiteral = StringLiteral(value) + + def ref(ident: LocalIdent, tpe: Type): VarRef = VarRef(ident)(tpe) + + def arrayType(base: NonArrayTypeRef, dimensions: Int): ArrayType = + ArrayType(ArrayTypeRef(base, dimensions)) + +} diff --git a/ir/shared/src/test/scala/org/scalajs/ir/VersionChecksTest.scala b/ir/shared/src/test/scala/org/scalajs/ir/VersionChecksTest.scala new file mode 100644 index 0000000000..2d93e52e74 --- /dev/null +++ b/ir/shared/src/test/scala/org/scalajs/ir/VersionChecksTest.scala @@ -0,0 +1,103 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.ir + +import org.junit.Test +import org.junit.Assert._ + +class VersionChecksTest { + private def assertThrows(body: => Unit) = { + val ok = try { + body + false + } catch { + case _: Exception => true + } + + if (!ok) + fail("expected exception") + } + + private def ok(current: String, binary: String) = + new VersionChecks(current, binary) + + private def bad(current: String, binary: String) = + assertThrows(new VersionChecks(current, binary)) + + @Test def failOnBadSyntax: Unit = { + bad("2.0", "2.0") // current needs patch + bad("2.0.0", "2") // binary needs major + } + + @Test def checkConsistency: Unit = { + ok("2.0.0-M1", "2.0-M1") + ok("2.0.1-M1", "2.0") + ok("2.2.0", "2.1") + ok("2.2.0", "2.2") + ok("2.2.0-M1", "2.1") + ok("2.1.1-M1", "2.1") + + // binary is newer + bad("2.1.0", "2.2") + bad("2.2.0-M1", "2.2") + + // binary is pre-release in non-matching version. + bad("2.3.0", "2.2-M1") + bad("2.2.1", "2.2-M1") + bad("2.3.0-M1", "2.2-M1") + bad("2.2.0", "2.2-M1") + + // major is different + bad("1.0.1", "2.0") + } + + @Test def checkSupportedNormal: Unit = { + val v = new VersionChecks("2.5.2", "2.4") + + v.checkSupported("2.4") + v.checkSupported("2.3") + v.checkSupported("2.2") + v.checkSupported("2.1") + v.checkSupported("2.0") + + assertThrows(v.checkSupported("1.4")) + assertThrows(v.checkSupported("2.5")) + assertThrows(v.checkSupported("2.6")) + assertThrows(v.checkSupported("2.2-SNAPSHOT")) + } + + @Test def checkSupportedPreRelease: Unit = { + val v = new VersionChecks("3.2.0-M1", "3.2-M1") + + v.checkSupported("3.0") + v.checkSupported("3.1") + v.checkSupported("3.2-M1") + + assertThrows(v.checkSupported("3.2")) + assertThrows(v.checkSupported("2.1-M1")) + } + + @Test def binaryCrossVersion: Unit = { + def test(full: String, emitted: String, cross: String): Unit = + assertEquals(cross, new VersionChecks(full, emitted).binaryCross) + + test("1.0.0", "1.0", "1") + test("1.0.2", "1.0", "1") + test("1.0.2-M1", "1.0", "1") + test("1.0.0-SNAPSHOT", "1.0-SNAPSHOT", "1.0-SNAPSHOT") + test("1.0.0-M1", "1.0-M1", "1.0-M1") + test("1.2.0-SNAPSHOT", "1.2-SNAPSHOT", "1") + test("1.2.0-M1", "1.2-M1", "1") + test("1.3.0-M1", "1.2", "1") + } +} diff --git a/ir/src/main/scala/org/scalajs/core/ir/Definitions.scala b/ir/src/main/scala/org/scalajs/core/ir/Definitions.scala deleted file mode 100644 index 88c2535c91..0000000000 --- a/ir/src/main/scala/org/scalajs/core/ir/Definitions.scala +++ /dev/null @@ -1,222 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.ir - -import Types._ - -object Definitions { - val ObjectClass = "O" - val ClassClass = "jl_Class" - - val StringClass = "T" - - val PrimitiveClasses = Set("V", "Z", "C", "B", "S", "I", "J", "F", "D") - - def isPrimitiveClass(encodedName: String): Boolean = - PrimitiveClasses.contains(encodedName) - - val BoxedUnitClass = "sr_BoxedUnit" - val BoxedBooleanClass = "jl_Boolean" - val BoxedCharacterClass = "jl_Character" - val BoxedByteClass = "jl_Byte" - val BoxedShortClass = "jl_Short" - val BoxedIntegerClass = "jl_Integer" - val BoxedLongClass = "jl_Long" - val BoxedFloatClass = "jl_Float" - val BoxedDoubleClass = "jl_Double" - - val CharSequenceClass = "jl_CharSequence" - val SerializableClass = "Ljava_io_Serializable" - val CloneableClass = "jl_Cloneable" - val ComparableClass = "jl_Comparable" - val NumberClass = "jl_Number" - - val HijackedBoxedClasses = Set( - BoxedUnitClass, BoxedBooleanClass, BoxedByteClass, BoxedShortClass, - BoxedIntegerClass, BoxedLongClass, BoxedFloatClass, BoxedDoubleClass) - val HijackedClasses = - HijackedBoxedClasses + StringClass - - val AncestorsOfStringClass = Set( - CharSequenceClass, ComparableClass, SerializableClass) - val AncestorsOfHijackedNumberClasses = Set( - NumberClass, ComparableClass, SerializableClass) - val AncestorsOfBoxedBooleanClass = Set( - ComparableClass, SerializableClass) - val AncestorsOfBoxedUnitClass = Set( - SerializableClass) - - val AncestorsOfHijackedClasses = - AncestorsOfStringClass ++ AncestorsOfHijackedNumberClasses ++ - AncestorsOfBoxedBooleanClass ++ AncestorsOfBoxedUnitClass - - val RuntimeNullClass = "sr_Null$" - val RuntimeNothingClass = "sr_Nothing$" - - val ThrowableClass = "jl_Throwable" - - val PseudoArrayClass = "s_Array" - val AncestorsOfPseudoArrayClass = Set( - ObjectClass, SerializableClass, CloneableClass) - - /** Name of the static initializer method. */ - final val StaticInitializerName = "clinit___" - - /** Name used for infos of class exports - * - * These currently are exported constructors and top level exports) - * - * TODO give this a better name once we can break backwards compat. - */ - val ClassExportsName = "__exportedInits" - - @deprecated("Use ClassExportsName instead", "0.6.14") - def ExportedConstructorsName: String = "__exportedInits" - - /** Encodes a class name. */ - def encodeClassName(fullName: String): String = { - val base = fullName.replace("_", "$und").replace(".", "_") - val encoded = compressedClasses.getOrElse(base, { - compressedPrefixes collectFirst { - case (prefix, compressed) if base.startsWith(prefix) => - compressed + base.substring(prefix.length) - } getOrElse { - "L"+base - } - }) - if (Trees.isKeyword(encoded) || encoded.charAt(0).isDigit || - encoded.charAt(0) == '$') { - "$" + encoded - } else encoded - } - - // !!! Duplicate logic: this code must be in sync with runtime.StackTrace - - /** Decodes a class name encoded with [[encodeClassName]]. */ - def decodeClassName(encodedName: String): String = { - val encoded = - if (encodedName.charAt(0) == '$') encodedName.substring(1) - else encodedName - val base = decompressedClasses.getOrElse(encoded, { - decompressedPrefixes collectFirst { - case (prefix, decompressed) if encoded.startsWith(prefix) => - decompressed + encoded.substring(prefix.length) - } getOrElse { - assert(!encoded.isEmpty && encoded.charAt(0) == 'L', - s"Cannot decode invalid encoded name '$encodedName'") - encoded.substring(1) - } - }) - base.replace("_", ".").replace("$und", "_") - } - - private val compressedClasses: Map[String, String] = Map( - "java_lang_Object" -> "O", - "java_lang_String" -> "T", - "scala_Unit" -> "V", - "scala_Boolean" -> "Z", - "scala_Char" -> "C", - "scala_Byte" -> "B", - "scala_Short" -> "S", - "scala_Int" -> "I", - "scala_Long" -> "J", - "scala_Float" -> "F", - "scala_Double" -> "D" - ) ++ ( - for (index <- 2 to 22) - yield s"scala_Tuple$index" -> ("T"+index) - ) ++ ( - for (index <- 0 to 22) - yield s"scala_Function$index" -> ("F"+index) - ) - - private val decompressedClasses: Map[String, String] = - compressedClasses map { case (a, b) => (b, a) } - - private val compressedPrefixes = Seq( - "scala_scalajs_runtime_" -> "sjsr_", - "scala_scalajs_" -> "sjs_", - "scala_collection_immutable_" -> "sci_", - "scala_collection_mutable_" -> "scm_", - "scala_collection_generic_" -> "scg_", - "scala_collection_" -> "sc_", - "scala_runtime_" -> "sr_", - "scala_" -> "s_", - "java_lang_" -> "jl_", - "java_util_" -> "ju_" - ) - - private val decompressedPrefixes: Seq[(String, String)] = - compressedPrefixes map { case (a, b) => (b, a) } - - /** Decodes a method name into its full signature. - * - * This discards the information whether the method is private or not, and - * at which class level it is private. If necessary, you can recover that - * information from `encodedName.indexOf("__p") >= 0`. - */ - def decodeMethodName( - encodedName: String): (String, List[ReferenceType], Option[ReferenceType]) = { - val (simpleName, privateAndSigString) = if (isConstructorName(encodedName)) { - val privateAndSigString = - if (encodedName == "init___") "" - else encodedName.stripPrefix("init___") + "__" - ("", privateAndSigString) - } else if (encodedName == StaticInitializerName) { - ("", "") - } else { - val pos = encodedName.indexOf("__") - val pos2 = - if (!encodedName.substring(pos + 2).startsWith("p")) pos - else encodedName.indexOf("__", pos + 2) - (encodedName.substring(0, pos), encodedName.substring(pos2 + 2)) - } - - // -1 preserves trailing empty strings - val parts = privateAndSigString.split("__", -1).toSeq - val paramsAndResultStrings = - if (parts.headOption.exists(_.startsWith("p"))) parts.tail - else parts - - val paramStrings :+ resultString = paramsAndResultStrings - - val paramTypes = paramStrings.map(decodeReferenceType).toList - val resultType = - if (resultString == "") None // constructor or reflective proxy - else Some(decodeReferenceType(resultString)) - - (simpleName, paramTypes, resultType) - } - - /** Decodes a [[Types.ReferenceType]], such as in an encoded method signature. - */ - def decodeReferenceType(encodedName: String): ReferenceType = { - val arrayDepth = encodedName.indexWhere(_ != 'A') - if (arrayDepth == 0) - ClassType(encodedName) - else - ArrayType(encodedName.substring(arrayDepth), arrayDepth) - } - - /* Common predicates on encoded names */ - - def isConstructorName(name: String): Boolean = - name.startsWith("init___") - - def isReflProxyName(name: String): Boolean = { - name.endsWith("__") && - !isConstructorName(name) && - name != StaticInitializerName - } - -} diff --git a/ir/src/main/scala/org/scalajs/core/ir/Hashers.scala b/ir/src/main/scala/org/scalajs/core/ir/Hashers.scala deleted file mode 100644 index 3f15562c11..0000000000 --- a/ir/src/main/scala/org/scalajs/core/ir/Hashers.scala +++ /dev/null @@ -1,554 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.ir - -import java.security.{MessageDigest, DigestOutputStream} -import java.io.{OutputStream, DataOutputStream} -import java.util.Arrays - -import Trees._ -import Types._ -import Tags._ - -object Hashers { - - def hashMethodDef(methodDef: MethodDef): MethodDef = { - if (methodDef.hash.isDefined) methodDef - else { - val hasher = new TreeHasher() - val MethodDef(static, name, args, resultType, body) = methodDef - - hasher.mixPos(methodDef.pos) - hasher.mixBoolean(static) - hasher.mixPropertyName(name) - hasher.mixTrees(args) - hasher.mixType(resultType) - body.foreach(hasher.mixTree) - hasher.mixInt(methodDef.optimizerHints.bits) - - val hash = hasher.finalizeHash() - - MethodDef(static, name, args, resultType, body)( - methodDef.optimizerHints, Some(hash))(methodDef.pos) - } - } - - /** Hash definitions from a ClassDef where applicable */ - def hashDefs(defs: List[Tree]): List[Tree] = defs map { - case methodDef: MethodDef => hashMethodDef(methodDef) - case otherDef => otherDef - } - - /** Hash the definitions in a ClassDef (where applicable) */ - def hashClassDef(classDef: ClassDef): ClassDef = { - classDef.copy(defs = hashDefs(classDef.defs))( - classDef.optimizerHints)(classDef.pos) - } - - def hashesEqual(x: TreeHash, y: TreeHash, considerPos: Boolean): Boolean = { - Arrays.equals(x.treeHash, y.treeHash) && - (!considerPos || Arrays.equals(x.posHash, y.posHash)) - } - - def hashAsVersion(hash: TreeHash, considerPos: Boolean): String = { - // 2 chars per byte, 20 bytes per hash - val size = 2 * (if (considerPos) 2 else 1) * 20 - val builder = new StringBuilder(size) - - def hexDigit(digit: Int): Char = Character.forDigit(digit, 16) - - def append(hash: Array[Byte]): Unit = { - for (b <- hash) - builder.append(hexDigit(b >> 4)).append(hexDigit(b & 0xF)) - } - append(hash.treeHash) - - if (considerPos) - append(hash.posHash) - - builder.toString - } - - private final class TreeHasher { - private def newDigest = MessageDigest.getInstance("SHA-1") - private def newDigestStream(digest: MessageDigest) = { - val out = new OutputStream { - def write(b: Int): Unit = () - } - val digOut = new DigestOutputStream(out, digest) - new DataOutputStream(digOut) - } - - private[this] val treeDigest = newDigest - private[this] val treeStream = newDigestStream(treeDigest) - - private[this] val posDigest = newDigest - private[this] val posStream = newDigestStream(posDigest) - - def finalizeHash(): TreeHash = - new TreeHash(treeDigest.digest(), posDigest.digest()) - - def mixTree(tree: Tree): Unit = { - mixPos(tree.pos) - tree match { - case VarDef(ident, vtpe, mutable, rhs) => - mixTag(TagVarDef) - mixIdent(ident) - mixType(vtpe) - mixBoolean(mutable) - mixTree(rhs) - - case ParamDef(ident, ptpe, mutable, rest) => - mixTag(TagParamDef) - mixIdent(ident) - mixType(ptpe) - mixBoolean(mutable) - /* TODO Remove this test in the next major release. - * In 0.6.x we need this test so that the hash of a non-rest ParamDef - * emitted in 0.6.3 format is the same as an (implicitly non-rest) - * ParamDef emitted in 0.6.0 format. - */ - if (rest) - mixBoolean(rest) - - case Skip() => - mixTag(TagSkip) - - case Block(stats) => - mixTag(TagBlock) - mixTrees(stats) - - case Labeled(label, tpe, body) => - mixTag(TagLabeled) - mixIdent(label) - mixType(tpe) - mixTree(body) - - case Assign(lhs, rhs) => - mixTag(TagAssign) - mixTree(lhs) - mixTree(rhs) - - case Return(expr, label) => - mixTag(TagReturn) - mixTree(expr) - mixOptIdent(label) - - case If(cond, thenp, elsep) => - mixTag(TagIf) - mixTree(cond) - mixTree(thenp) - mixTree(elsep) - mixType(tree.tpe) - - case While(cond, body, label) => - mixTag(TagWhile) - mixTree(cond) - mixTree(body) - mixOptIdent(label) - - case DoWhile(body, cond, label) => - mixTag(TagDoWhile) - mixTree(body) - mixTree(cond) - mixOptIdent(label) - - case TryCatch(block, errVar, handler) => - mixTag(TagTryCatch) - mixTree(block) - mixIdent(errVar) - mixTree(handler) - mixType(tree.tpe) - - case TryFinally(block, finalizer) => - mixTag(TagTryFinally) - mixTree(block) - mixTree(finalizer) - mixType(tree.tpe) - - case Throw(expr) => - mixTag(TagThrow) - mixTree(expr) - - case Continue(label) => - mixTag(TagContinue) - mixOptIdent(label) - - case Match(selector, cases, default) => - mixTag(TagMatch) - mixTree(selector) - cases foreach { case (patterns, body) => - mixTrees(patterns) - mixTree(body) - } - mixTree(default) - mixType(tree.tpe) - - case Debugger() => - mixTag(TagDebugger) - - case New(cls, ctor, args) => - mixTag(TagNew) - mixType(cls) - mixIdent(ctor) - mixTrees(args) - - case LoadModule(cls) => - mixTag(TagLoadModule) - mixType(cls) - - case StoreModule(cls, value) => - mixTag(TagStoreModule) - mixType(cls) - mixTree(value) - - case Select(qualifier, item) => - mixTag(TagSelect) - mixTree(qualifier) - mixIdent(item) - mixType(tree.tpe) - - case SelectStatic(cls, item) => - mixTag(TagSelectStatic) - mixType(cls) - mixIdent(item) - mixType(tree.tpe) - - case Apply(receiver, method, args) => - mixTag(TagApply) - mixTree(receiver) - mixIdent(method) - mixTrees(args) - mixType(tree.tpe) - - case ApplyStatically(receiver, cls, method, args) => - mixTag(TagApplyStatically) - mixTree(receiver) - mixType(cls) - mixIdent(method) - mixTrees(args) - mixType(tree.tpe) - - case ApplyStatic(cls, method, args) => - mixTag(TagApplyStatic) - mixType(cls) - mixIdent(method) - mixTrees(args) - mixType(tree.tpe) - - case UnaryOp(op, lhs) => - mixTag(TagUnaryOp) - mixInt(op) - mixTree(lhs) - - case BinaryOp(op, lhs, rhs) => - mixTag(TagBinaryOp) - mixInt(op) - mixTree(lhs) - mixTree(rhs) - - case NewArray(tpe, lengths) => - mixTag(TagNewArray) - mixType(tpe) - mixTrees(lengths) - - case ArrayValue(tpe, elems) => - mixTag(TagArrayValue) - mixType(tpe) - mixTrees(elems) - - case ArrayLength(array) => - mixTag(TagArrayLength) - mixTree(array) - - case ArraySelect(array, index) => - mixTag(TagArraySelect) - mixTree(array) - mixTree(index) - mixType(tree.tpe) - - case RecordValue(tpe, elems) => - mixTag(TagRecordValue) - mixType(tpe) - mixTrees(elems) - - case IsInstanceOf(expr, cls) => - mixTag(TagIsInstanceOf) - mixTree(expr) - mixRefType(cls) - - case AsInstanceOf(expr, cls) => - mixTag(TagAsInstanceOf) - mixTree(expr) - mixRefType(cls) - - case Unbox(expr, charCode) => - mixTag(TagUnbox) - mixTree(expr) - mixInt(charCode) - - case GetClass(expr) => - mixTag(TagGetClass) - mixTree(expr) - - case CallHelper(helper, args) => - mixTag(TagCallHelper) - mixString(helper) - mixTrees(args) - mixType(tree.tpe) - - case JSNew(ctor, args) => - mixTag(TagJSNew) - mixTree(ctor) - mixTrees(args) - - case JSDotSelect(qualifier, item) => - mixTag(TagJSDotSelect) - mixTree(qualifier) - mixIdent(item) - - case JSBracketSelect(qualifier, item) => - mixTag(TagJSBracketSelect) - mixTree(qualifier) - mixTree(item) - - case JSFunctionApply(fun, args) => - mixTag(TagJSFunctionApply) - mixTree(fun) - mixTrees(args) - - case JSDotMethodApply(receiver, method, args) => - mixTag(TagJSDotMethodApply) - mixTree(receiver) - mixIdent(method) - mixTrees(args) - - case JSBracketMethodApply(receiver, method, args) => - mixTag(TagJSBracketMethodApply) - mixTree(receiver) - mixTree(method) - mixTrees(args) - - case JSSuperBracketSelect(cls, qualifier, item) => - mixTag(TagJSSuperBracketSelect) - mixType(cls) - mixTree(qualifier) - mixTree(item) - - case JSSuperBracketCall(cls, receiver, method, args) => - mixTag(TagJSSuperBracketCall) - mixType(cls) - mixTree(receiver) - mixTree(method) - mixTrees(args) - - case JSSuperConstructorCall(args) => - mixTag(TagJSSuperConstructorCall) - mixTrees(args) - - case JSImportCall(arg) => - mixTag(TagJSImportCall) - mixTree(arg) - - case LoadJSConstructor(cls) => - mixTag(TagLoadJSConstructor) - mixType(cls) - - case LoadJSModule(cls) => - mixTag(TagLoadJSModule) - mixType(cls) - - case JSSpread(items) => - mixTag(TagJSSpread) - mixTree(items) - - case JSDelete(prop) => - mixTag(TagJSDelete) - mixTree(prop) - - case JSUnaryOp(op, lhs) => - mixTag(TagJSUnaryOp) - mixInt(op) - mixTree(lhs) - - case JSBinaryOp(op, lhs, rhs) => - mixTag(TagJSBinaryOp) - mixInt(op) - mixTree(lhs) - mixTree(rhs) - - case JSArrayConstr(items) => - mixTag(TagJSArrayConstr) - mixTrees(items) - - case JSObjectConstr(fields) => - mixTag(TagJSObjectConstr) - fields foreach { case (pn, value) => - mixPropertyName(pn) - mixTree(value) - } - - case JSLinkingInfo() => - mixTag(TagJSLinkingInfo) - - case Undefined() => - mixTag(TagUndefined) - - case UndefinedParam() => - mixTag(TagUndefinedParam) - mixType(tree.tpe) - - case Null() => - mixTag(TagNull) - - case BooleanLiteral(value) => - mixTag(TagBooleanLiteral) - mixBoolean(value) - - case IntLiteral(value) => - mixTag(TagIntLiteral) - mixInt(value) - - case LongLiteral(value) => - mixTag(TagLongLiteral) - mixLong(value) - - case FloatLiteral(value) => - mixTag(TagFloatLiteral) - mixFloat(value) - - case DoubleLiteral(value) => - mixTag(TagDoubleLiteral) - mixDouble(value) - - case StringLiteral(value) => - mixTag(TagStringLiteral) - mixString(value) - - case ClassOf(cls) => - mixTag(TagClassOf) - mixRefType(cls) - - case VarRef(ident) => - mixTag(TagVarRef) - mixIdent(ident) - mixType(tree.tpe) - - case This() => - mixTag(TagThis) - mixType(tree.tpe) - - case Closure(captureParams, params, body, captureValues) => - mixTag(TagClosure) - mixTrees(captureParams) - mixTrees(params) - mixTree(body) - mixTrees(captureValues) - - case _ => - throw new IllegalArgumentException( - s"Unable to hash tree of class ${tree.getClass}") - } - } - - def mixTrees(trees: List[Tree]): Unit = - trees.foreach(mixTree) - - def mixRefType(tpe: ReferenceType): Unit = - mixType(tpe.asInstanceOf[Type]) - - def mixType(tpe: Type): Unit = tpe match { - case AnyType => mixTag(TagAnyType) - case NothingType => mixTag(TagNothingType) - case UndefType => mixTag(TagUndefType) - case BooleanType => mixTag(TagBooleanType) - case IntType => mixTag(TagIntType) - case LongType => mixTag(TagLongType) - case FloatType => mixTag(TagFloatType) - case DoubleType => mixTag(TagDoubleType) - case StringType => mixTag(TagStringType) - case NullType => mixTag(TagNullType) - case NoType => mixTag(TagNoType) - - case tpe: ClassType => - mixTag(TagClassType) - mixString(tpe.className) - - case tpe: ArrayType => - mixTag(TagArrayType) - mixString(tpe.baseClassName) - mixInt(tpe.dimensions) - - case RecordType(fields) => - mixTag(TagRecordType) - for (RecordType.Field(name, originalName, tpe, mutable) <- fields) { - mixString(name) - originalName.foreach(mixString) - mixType(tpe) - mixBoolean(mutable) - } - } - - def mixIdent(ident: Ident): Unit = { - mixPos(ident.pos) - mixString(ident.name) - ident.originalName.foreach(mixString) - } - - def mixOptIdent(optIdent: Option[Ident]): Unit = optIdent.foreach(mixIdent) - - def mixPropertyName(name: PropertyName): Unit = name match { - case name: Ident => - mixTag(TagPropertyNameIdent) - mixIdent(name) - - case name: StringLiteral => - mixTag(TagPropertyNameStringLiteral) - mixTree(name) - - case ComputedName(tree, logicalName) => - mixTag(TagPropertyNameComputedName) - mixTree(tree) - mixString(logicalName) - } - - def mixPos(pos: Position): Unit = { - posStream.writeUTF(pos.source.toString) - posStream.writeInt(pos.line) - posStream.writeInt(pos.column) - } - - @inline - final def mixTag(tag: Int): Unit = mixInt(tag) - - @inline - final def mixString(str: String): Unit = treeStream.writeUTF(str) - - @inline - final def mixInt(i: Int): Unit = treeStream.writeInt(i) - - @inline - final def mixLong(l: Long): Unit = treeStream.writeLong(l) - - @inline - final def mixBoolean(b: Boolean): Unit = treeStream.writeBoolean(b) - - @inline - final def mixFloat(f: Float): Unit = treeStream.writeFloat(f) - - @inline - final def mixDouble(d: Double): Unit = treeStream.writeDouble(d) - - } - -} diff --git a/ir/src/main/scala/org/scalajs/core/ir/IRVersionNotSupportedException.scala b/ir/src/main/scala/org/scalajs/core/ir/IRVersionNotSupportedException.scala deleted file mode 100644 index 8e62a707f7..0000000000 --- a/ir/src/main/scala/org/scalajs/core/ir/IRVersionNotSupportedException.scala +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.ir - -import java.io.IOException - -class IRVersionNotSupportedException(val version: String, - val supported: Set[String], message: String) extends IOException(message) { - - def this(version: String, supported: Set[String], message: String, - exception: Exception) = { - this(version, supported, message) - initCause(exception) - } -} diff --git a/ir/src/main/scala/org/scalajs/core/ir/InfoSerializers.scala b/ir/src/main/scala/org/scalajs/core/ir/InfoSerializers.scala deleted file mode 100644 index 702675f628..0000000000 --- a/ir/src/main/scala/org/scalajs/core/ir/InfoSerializers.scala +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.ir - -import java.io._ - -import Infos._ - -object InfoSerializers { - - /** Scala.js IR File Magic Number - * - * CA FE : first part of magic number of Java class files - * 4A 53 : "JS" in ASCII - * - */ - final val IRMagicNumber = 0xCAFE4A53 - - def serialize(stream: OutputStream, classInfo: ClassInfo): Unit = { - new Serializer().serialize(stream, classInfo) - } - - def deserialize(stream: InputStream): ClassInfo = { - deserializeWithVersion(stream)._2 - } - - def deserializeWithVersion(stream: InputStream): (String, ClassInfo) = { - new Deserializer(stream).deserialize() - } - - private final class Serializer { - def serialize(stream: OutputStream, classInfo: ClassInfo): Unit = { - val s = new DataOutputStream(stream) - - def writeSeq[A](seq: Seq[A])(writeElem: A => Unit): Unit = { - s.writeInt(seq.size) - seq.foreach(writeElem) - } - - def writeStrings(seq: Seq[String]): Unit = - writeSeq(seq)(s.writeUTF(_)) - - // Write the Scala.js IR magic number - s.writeInt(IRMagicNumber) - - // Write the Scala.js Version - s.writeUTF(ScalaJSVersions.binaryEmitted) - - import classInfo._ - s.writeUTF(encodedName) - s.writeBoolean(isExported) - s.writeByte(ClassKind.toByte(kind)) - s.writeUTF(superClass.getOrElse("")) - writeStrings(interfaces) - - def writeMethodInfo(methodInfo: MethodInfo): Unit = { - import methodInfo._ - - def writePerClassStrings(m: Map[String, List[String]]): Unit = { - writeSeq(m.toSeq) { - case (cls, items) => s.writeUTF(cls); writeStrings(items) - } - } - - s.writeUTF(encodedName) - s.writeBoolean(isStatic) - s.writeBoolean(isAbstract) - s.writeBoolean(isExported) - writePerClassStrings(staticFieldsRead) - writePerClassStrings(staticFieldsWritten) - writePerClassStrings(methodsCalled) - writePerClassStrings(methodsCalledStatically) - writePerClassStrings(staticMethodsCalled) - writeStrings(instantiatedClasses) - writeStrings(accessedModules) - writeStrings(usedInstanceTests) - writeStrings(accessedClassData) - } - - writeSeq(methods)(writeMethodInfo(_)) - - s.flush() - } - } - - private final class Deserializer(stream: InputStream) { - private[this] val input = new DataInputStream(stream) - - def readList[A](readElem: => A): List[A] = - List.fill(input.readInt())(readElem) - - def readStrings(): List[String] = - readList(input.readUTF()) - - def deserialize(): (String, ClassInfo) = { - val version = readHeader() - - import input._ - - val useHacks065 = - Set("0.6.0", "0.6.3", "0.6.4", "0.6.5").contains(version) - val useHacks0614 = - useHacks065 || Set("0.6.6", "0.6.8", "0.6.13", "0.6.14").contains(version) - - val encodedName = readUTF() - val isExported = readBoolean() - val kind = ClassKind.fromByte(readByte()) - val superClass0 = readUTF() - val superClass = if (superClass0 == "") None else Some(superClass0) - val interfaces = readList(readUTF()) - - def readMethod(): MethodInfo = { - def readPerClassStrings(): Map[String, List[String]] = - readList(readUTF() -> readStrings()).toMap - - val encodedName = readUTF() - val isStatic = readBoolean() - val isAbstract = readBoolean() - val isExported = readBoolean() - val staticFieldsRead = - if (useHacks0614) Map.empty[String, List[String]] - else readPerClassStrings() - val staticFieldsWritten = - if (useHacks0614) Map.empty[String, List[String]] - else readPerClassStrings() - val methodsCalled = readPerClassStrings() - val methodsCalledStatically = readPerClassStrings() - val staticMethodsCalled = readPerClassStrings() - val instantiatedClasses = readStrings() - val accessedModules = readStrings() - val usedInstanceTests = readStrings() - val accessedClassData = readStrings() - MethodInfo(encodedName, isStatic, isAbstract, isExported, - staticFieldsRead, staticFieldsWritten, - methodsCalled, methodsCalledStatically, staticMethodsCalled, - instantiatedClasses, accessedModules, usedInstanceTests, - accessedClassData) - } - - val methods0 = readList(readMethod()) - val methods = if (useHacks065) { - methods0.filter(m => !Definitions.isReflProxyName(m.encodedName)) - } else { - methods0 - } - - val info = ClassInfo(encodedName, isExported, kind, - superClass, interfaces, methods) - - (version, info) - } - - /** Reads the Scala.js IR header and verifies the version compatibility. - * Returns the emitted binary version. - */ - def readHeader(): String = { - // Check magic number - if (input.readInt() != IRMagicNumber) - throw new IOException("Not a Scala.js IR file") - - // Check that we support this version of the IR - val version = input.readUTF() - val supported = ScalaJSVersions.binarySupported - if (!supported.contains(version)) { - throw new IRVersionNotSupportedException(version, supported, - s"This version ($version) of Scala.js IR is not supported. " + - s"Supported versions are: ${supported.mkString(", ")}") - } - - version - } - } -} diff --git a/ir/src/main/scala/org/scalajs/core/ir/Infos.scala b/ir/src/main/scala/org/scalajs/core/ir/Infos.scala deleted file mode 100644 index 73683ede41..0000000000 --- a/ir/src/main/scala/org/scalajs/core/ir/Infos.scala +++ /dev/null @@ -1,506 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.ir - -import scala.collection.mutable - -import Definitions._ -import Trees._ -import Types._ - -object Infos { - - final class ClassInfo private ( - val encodedName: String, - val isExported: Boolean, - val kind: ClassKind, - val superClass: Option[String], // always None for interfaces - val interfaces: List[String], // direct parent interfaces only - val methods: List[MethodInfo] - ) - - object ClassInfo { - def apply( - encodedName: String, - isExported: Boolean = false, - kind: ClassKind = ClassKind.Class, - superClass: Option[String] = None, - interfaces: List[String] = Nil, - methods: List[MethodInfo] = Nil): ClassInfo = { - new ClassInfo(encodedName, isExported, kind, superClass, - interfaces, methods) - } - } - - final class MethodInfo private ( - val encodedName: String, - val isStatic: Boolean, - val isAbstract: Boolean, - val isExported: Boolean, - val staticFieldsRead: Map[String, List[String]], - val staticFieldsWritten: Map[String, List[String]], - val methodsCalled: Map[String, List[String]], - val methodsCalledStatically: Map[String, List[String]], - val staticMethodsCalled: Map[String, List[String]], - /** For a Scala class, it is instantiated with a `New`; for a JS class, - * its constructor is accessed with a `JSLoadConstructor`. - */ - val instantiatedClasses: List[String], - val accessedModules: List[String], - val usedInstanceTests: List[String], - val accessedClassData: List[String] - ) - - object MethodInfo { - @deprecated("Use the overload with all the fields and no defaults", - "0.6.15") - def apply( - encodedName: String, - isStatic: Boolean = false, - isAbstract: Boolean = false, - isExported: Boolean = false, - methodsCalled: Map[String, List[String]] = Map.empty, - methodsCalledStatically: Map[String, List[String]] = Map.empty, - staticMethodsCalled: Map[String, List[String]] = Map.empty, - instantiatedClasses: List[String] = Nil, - accessedModules: List[String] = Nil, - usedInstanceTests: List[String] = Nil, - accessedClassData: List[String] = Nil): MethodInfo = { - apply(encodedName, isStatic, isAbstract, isExported, - staticFieldsRead = Map.empty, staticFieldsWritten = Map.empty, - methodsCalled, methodsCalledStatically, staticMethodsCalled, - instantiatedClasses, accessedModules, usedInstanceTests, - accessedClassData) - } - - def apply( - encodedName: String, - isStatic: Boolean, - isAbstract: Boolean, - isExported: Boolean, - staticFieldsRead: Map[String, List[String]], - staticFieldsWritten: Map[String, List[String]], - methodsCalled: Map[String, List[String]], - methodsCalledStatically: Map[String, List[String]], - staticMethodsCalled: Map[String, List[String]], - instantiatedClasses: List[String], - accessedModules: List[String], - usedInstanceTests: List[String], - accessedClassData: List[String]): MethodInfo = { - new MethodInfo(encodedName, isStatic, isAbstract, isExported, - staticFieldsRead, staticFieldsWritten, - methodsCalled, methodsCalledStatically, staticMethodsCalled, - instantiatedClasses, accessedModules, usedInstanceTests, - accessedClassData) - } - } - - final class ClassInfoBuilder { - private var encodedName: String = "" - private var kind: ClassKind = ClassKind.Class - private var isExported: Boolean = false - private var superClass: Option[String] = None - private val interfaces = mutable.ListBuffer.empty[String] - private val methods = mutable.ListBuffer.empty[MethodInfo] - - def setEncodedName(encodedName: String): this.type = { - this.encodedName = encodedName - this - } - - def setKind(kind: ClassKind): this.type = { - this.kind = kind - this - } - - def setIsExported(isExported: Boolean): this.type = { - this.isExported = isExported - this - } - - def setSuperClass(superClass: Option[String]): this.type = { - this.superClass = superClass - this - } - - def addInterface(interface: String): this.type = { - interfaces += interface - this - } - - def addInterfaces(interfaces: List[String]): this.type = { - this.interfaces ++= interfaces - this - } - - @deprecated("Use the overload with a List.", "0.6.29") - def addInterfaces(interfaces: TraversableOnce[String]): this.type = { - this.interfaces ++= interfaces - this - } - - def addMethod(methodInfo: MethodInfo): this.type = { - methods += methodInfo - this - } - - def result(): ClassInfo = { - ClassInfo(encodedName, isExported, kind, superClass, - interfaces.toList, methods.toList) - } - } - - final class MethodInfoBuilder { - private var encodedName: String = "" - private var isStatic: Boolean = false - private var isAbstract: Boolean = false - private var isExported: Boolean = false - - private val staticFieldsRead = mutable.Map.empty[String, mutable.Set[String]] - private val staticFieldsWritten = mutable.Map.empty[String, mutable.Set[String]] - private val methodsCalled = mutable.Map.empty[String, mutable.Set[String]] - private val methodsCalledStatically = mutable.Map.empty[String, mutable.Set[String]] - private val staticMethodsCalled = mutable.Map.empty[String, mutable.Set[String]] - private val instantiatedClasses = mutable.Set.empty[String] - private val accessedModules = mutable.Set.empty[String] - private val usedInstanceTests = mutable.Set.empty[String] - private val accessedClassData = mutable.Set.empty[String] - - def setEncodedName(encodedName: String): this.type = { - this.encodedName = encodedName - this - } - - def setIsStatic(isStatic: Boolean): this.type = { - this.isStatic = isStatic - this - } - - def setIsAbstract(isAbstract: Boolean): this.type = { - this.isAbstract = isAbstract - this - } - - def setIsExported(isExported: Boolean): this.type = { - this.isExported = isExported - this - } - - def addStaticFieldRead(cls: String, field: String): this.type = { - staticFieldsRead.getOrElseUpdate(cls, mutable.Set.empty) += field - this - } - - def addStaticFieldWritten(cls: String, field: String): this.type = { - staticFieldsWritten.getOrElseUpdate(cls, mutable.Set.empty) += field - this - } - - def addMethodCalled(receiverTpe: Type, method: String): this.type = { - receiverTpe match { - case ClassType(cls) => addMethodCalled(cls, method) - case AnyType => addMethodCalled(ObjectClass, method) - case UndefType => addMethodCalled(BoxedUnitClass, method) - case BooleanType => addMethodCalled(BoxedBooleanClass, method) - case IntType => addMethodCalled(BoxedIntegerClass, method) - case LongType => addMethodCalled(BoxedLongClass, method) - case FloatType => addMethodCalled(BoxedFloatClass, method) - case DoubleType => addMethodCalled(BoxedDoubleClass, method) - case StringType => addMethodCalled(StringClass, method) - case ArrayType(_, _) => addMethodCalled(PseudoArrayClass, method) - - case NullType | NothingType => - // Nothing to do - - case NoType | RecordType(_) => - throw new IllegalArgumentException( - s"Illegal receiver type: $receiverTpe") - } - - this - } - - def addMethodCalled(cls: String, method: String): this.type = { - methodsCalled.getOrElseUpdate(cls, mutable.Set.empty) += method - this - } - - def addMethodCalledStatically(cls: String, method: String): this.type = { - methodsCalledStatically.getOrElseUpdate(cls, mutable.Set.empty) += method - this - } - - def addStaticMethodCalled(cls: String, method: String): this.type = { - staticMethodsCalled.getOrElseUpdate(cls, mutable.Set.empty) += method - this - } - - def addInstantiatedClass(cls: String): this.type = { - instantiatedClasses += cls - this - } - - def addInstantiatedClass(cls: String, ctor: String): this.type = - addInstantiatedClass(cls).addMethodCalledStatically(cls, ctor) - - def addAccessedModule(cls: String): this.type = { - accessedModules += cls - this - } - - def addUsedInstanceTest(tpe: ReferenceType): this.type = - addUsedInstanceTest(baseNameOf(tpe)) - - def addUsedInstanceTest(cls: String): this.type = { - usedInstanceTests += cls - this - } - - def addAccessedClassData(tpe: ReferenceType): this.type = - addAccessedClassData(baseNameOf(tpe)) - - def addAccessedClassData(cls: String): this.type = { - accessedClassData += cls - this - } - - private def baseNameOf(tpe: ReferenceType): String = tpe match { - case ClassType(name) => name - case ArrayType(base, _) => base - } - - def result(): MethodInfo = { - def toMapOfLists( - m: mutable.Map[String, mutable.Set[String]]): Map[String, List[String]] = { - m.map(kv => kv._1 -> kv._2.toList).toMap - } - - MethodInfo( - encodedName = encodedName, - isStatic = isStatic, - isAbstract = isAbstract, - isExported = isExported, - staticFieldsRead = toMapOfLists(staticFieldsRead), - staticFieldsWritten = toMapOfLists(staticFieldsWritten), - methodsCalled = toMapOfLists(methodsCalled), - methodsCalledStatically = toMapOfLists(methodsCalledStatically), - staticMethodsCalled = toMapOfLists(staticMethodsCalled), - instantiatedClasses = instantiatedClasses.toList, - accessedModules = accessedModules.toList, - usedInstanceTests = usedInstanceTests.toList, - accessedClassData = accessedClassData.toList - ) - } - } - - /** Generates the [[ClassInfo]] of a [[Trees.ClassDef]]. */ - def generateClassInfo(classDef: ClassDef): ClassInfo = { - val builder = new ClassInfoBuilder() - .setEncodedName(classDef.name.name) - .setKind(classDef.kind) - .setSuperClass(classDef.superClass.map(_.name)) - .addInterfaces(classDef.interfaces.map(_.name)) - - var exportedConstructors: List[ConstructorExportDef] = Nil - var topLevelMethodExports: List[TopLevelMethodExportDef] = Nil - var topLevelFieldExports: List[TopLevelFieldExportDef] = Nil - - classDef.defs foreach { - case methodDef: MethodDef => - builder.addMethod(generateMethodInfo(methodDef)) - case propertyDef: PropertyDef => - builder.addMethod(generatePropertyInfo(propertyDef)) - case constructorDef: ConstructorExportDef => - builder.setIsExported(true) - exportedConstructors ::= constructorDef - case _:JSClassExportDef | _:ModuleExportDef | _:TopLevelModuleExportDef => - builder.setIsExported(true) - case topLevelMethodExport: TopLevelMethodExportDef => - builder.setIsExported(true) - topLevelMethodExports ::= topLevelMethodExport - case topLevelFieldExport: TopLevelFieldExportDef => - builder.setIsExported(true) - topLevelFieldExports ::= topLevelFieldExport - case _ => - } - - if (exportedConstructors.nonEmpty || topLevelMethodExports.nonEmpty || - topLevelFieldExports.nonEmpty) { - builder.addMethod(generateClassExportsInfo(classDef.name.name, - exportedConstructors, topLevelMethodExports, topLevelFieldExports)) - } - - builder.result() - } - - /** Generates the [[MethodInfo]] of a [[Trees.MethodDef]]. */ - def generateMethodInfo(methodDef: MethodDef): MethodInfo = - new GenInfoTraverser().generateMethodInfo(methodDef) - - /** Generates the [[MethodInfo]] of a [[Trees.PropertyDef]]. */ - def generatePropertyInfo(propertyDef: PropertyDef): MethodInfo = - new GenInfoTraverser().generatePropertyInfo(propertyDef) - - /** Generates the [[MethodInfo]] of a list of [[Trees.ConstructorExportDef]]s. */ - @deprecated("Use generateClassExportsInfo instead", "0.6.14") - def generateExportedConstructorsInfo( - constructorDefs: List[ConstructorExportDef]): MethodInfo = { - generateClassExportsInfo(constructorDefs, Nil) - } - - /** Generates the [[MethodInfo]] for the class exports. */ - @deprecated( - "Use the overload with an enclosingClass and topLevelFieldExports.", - "0.6.15") - def generateClassExportsInfo(constructorDefs: List[ConstructorExportDef], - topLevelMethodExports: List[TopLevelMethodExportDef]): MethodInfo = { - // enclosingClass won't be used when topLevelFieldExports is empty - generateClassExportsInfo("", constructorDefs, topLevelMethodExports, Nil) - } - - /** Generates the [[MethodInfo]] for the class exports. */ - def generateClassExportsInfo(enclosingClass: String, - constructorDefs: List[ConstructorExportDef], - topLevelMethodExports: List[TopLevelMethodExportDef], - topLevelFieldExports: List[TopLevelFieldExportDef]): MethodInfo = { - new GenInfoTraverser().generateClassExportsInfo(enclosingClass, - constructorDefs, topLevelMethodExports, topLevelFieldExports) - } - - private final class GenInfoTraverser extends Traversers.Traverser { - private val builder = new MethodInfoBuilder - - def generateMethodInfo(methodDef: MethodDef): MethodInfo = { - builder - .setEncodedName(methodDef.name.encodedName) - .setIsStatic(methodDef.static) - .setIsAbstract(methodDef.body.isEmpty) - .setIsExported(!methodDef.name.isInstanceOf[Ident]) - - methodDef.name match { - case ComputedName(tree, _) => - traverse(tree) - case _ => - } - - methodDef.body.foreach(traverse) - - builder.result() - } - - def generatePropertyInfo(propertyDef: PropertyDef): MethodInfo = { - builder - .setEncodedName(propertyDef.name.encodedName) - .setIsStatic(propertyDef.static) - .setIsExported(true) - - propertyDef.name match { - case ComputedName(tree, _) => - traverse(tree) - case _ => - } - - propertyDef.getterBody.foreach(traverse) - propertyDef.setterArgAndBody foreach { case (_, body) => - traverse(body) - } - - builder.result() - } - - def generateClassExportsInfo(enclosingClass: String, - constructorDefs: List[ConstructorExportDef], - topLevelMethodExports: List[TopLevelMethodExportDef], - topLevelFieldExports: List[TopLevelFieldExportDef]): MethodInfo = { - builder - .setEncodedName(ClassExportsName) - .setIsExported(true) - - for (constructorDef <- constructorDefs) - traverse(constructorDef.body) - - for (topLevelMethodExport <- topLevelMethodExports) - traverse(topLevelMethodExport.methodDef) - - for (topLevelFieldExport <- topLevelFieldExports) { - val field = topLevelFieldExport.field.name - builder.addStaticFieldRead(enclosingClass, field) - builder.addStaticFieldWritten(enclosingClass, field) - } - - builder.result() - } - - override def traverse(tree: Tree): Unit = { - tree match { - /* Do not call super.traverse() so that the field is not also marked as - * read. - */ - case Assign(SelectStatic(ClassType(cls), Ident(field, _)), rhs) => - builder.addStaticFieldWritten(cls, field) - traverse(rhs) - - // In all other cases, we'll have to call super.traverse() - case _ => - tree match { - case New(ClassType(cls), ctor, _) => - builder.addInstantiatedClass(cls, ctor.name) - - case SelectStatic(ClassType(cls), Ident(field, _)) => - builder.addStaticFieldRead(cls, field) - - case Apply(receiver, Ident(method, _), _) => - builder.addMethodCalled(receiver.tpe, method) - case ApplyStatically(_, ClassType(cls), method, _) => - builder.addMethodCalledStatically(cls, method.name) - case ApplyStatic(ClassType(cls), method, _) => - builder.addStaticMethodCalled(cls, method.name) - - case LoadModule(ClassType(cls)) => - builder.addAccessedModule(cls) - - case IsInstanceOf(_, tpe) => - builder.addUsedInstanceTest(tpe) - case AsInstanceOf(_, tpe) => - builder.addUsedInstanceTest(tpe) - - case NewArray(tpe, _) => - builder.addAccessedClassData(tpe) - case ArrayValue(tpe, _) => - builder.addAccessedClassData(tpe) - case ClassOf(cls) => - builder.addAccessedClassData(cls) - - case LoadJSConstructor(cls) => - builder.addInstantiatedClass(cls.className) - - case LoadJSModule(ClassType(cls)) => - builder.addAccessedModule(cls) - - /* We explicitly catch UndefinedParam here to make sure, we do not - * emit it in the compiler. This does not entirely belong here, as - * it supports GenJSCode, but it is not wrong to throw an exception. - */ - case UndefinedParam() => - throw new InvalidIRException(tree, - "Found UndefinedParam while building infos") - - case _ => - } - - super.traverse(tree) - } - } - } - -} diff --git a/ir/src/main/scala/org/scalajs/core/ir/Printers.scala b/ir/src/main/scala/org/scalajs/core/ir/Printers.scala deleted file mode 100644 index 1f64b7d7b1..0000000000 --- a/ir/src/main/scala/org/scalajs/core/ir/Printers.scala +++ /dev/null @@ -1,1141 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.ir - -import scala.annotation.switch - -// Unimport default print and println to avoid invoking them by mistake -import scala.Predef.{print => _, println => _, _} - -import java.io.Writer - -import Position._ -import Trees._ -import Types._ -import Infos._ -import Utils.printEscapeJS - -object Printers { - - /** Basically copied from scala.reflect.internal.Printers */ - abstract class IndentationManager { - protected val out: Writer - - private var indentMargin = 0 - private val indentStep = 2 - private var indentString = " " // 40 - - protected def indent(): Unit = indentMargin += indentStep - protected def undent(): Unit = indentMargin -= indentStep - - protected def getIndentMargin(): Int = indentMargin - - protected def println(): Unit = { - out.write('\n') - while (indentMargin > indentString.length()) - indentString += indentString - if (indentMargin > 0) - out.write(indentString, 0, indentMargin) - } - } - - class IRTreePrinter(protected val out: Writer) extends IndentationManager { - def printTopLevelTree(tree: Tree): Unit = { - tree match { - case Skip() => - // do not print anything - case Block(stats) => - for (stat <- stats) - printTopLevelTree(stat) - case _ => - print(tree) - println() - } - } - - protected final def printColumn(ts: List[Tree], start: String, sep: String, - end: String): Unit = { - print(start); indent() - var rest = ts - while (rest.nonEmpty) { - println() - print(rest.head) - rest = rest.tail - if (rest.nonEmpty) - print(sep) - } - undent(); println(); print(end) - } - - protected final def printRow(ts: List[Tree], start: String, sep: String, - end: String): Unit = { - print(start) - var rest = ts - while (rest.nonEmpty) { - print(rest.head) - rest = rest.tail - if (rest.nonEmpty) - print(sep) - } - print(end) - } - - protected def printBlock(tree: Tree): Unit = { - tree match { - case Block(trees) => - printColumn(trees, "{", ";", "}") - - case _ => - print('{'); indent(); println() - print(tree) - undent(); println(); print('}') - } - } - - protected def printSig(args: List[ParamDef], resultType: Type): Unit = { - printRow(args, "(", ", ", ")") - if (resultType != NoType) { - print(": ") - print(resultType) - print(" = ") - } else { - print(' ') - } - } - - protected def printArgs(args: List[Tree]): Unit = { - printRow(args, "(", ", ", ")") - } - - def print(tree: Tree): Unit = { - tree match { - // Definitions - - case VarDef(ident, vtpe, mutable, rhs) => - if (mutable) - print("var ") - else - print("val ") - print(ident) - print(": ") - print(vtpe) - print(" = ") - print(rhs) - - case ParamDef(ident, ptpe, mutable, rest) => - if (mutable) - print("var ") - if (rest) - print("...") - print(ident) - print(": ") - print(ptpe) - - // Control flow constructs - - case Skip() => - print("/**/") - - case tree: Block => - printBlock(tree) - - case Labeled(label, tpe, body) => - print(label) - if (tpe != NoType) { - print('[') - print(tpe) - print(']') - } - print(": ") - printBlock(body) - - case Assign(lhs, rhs) => - print(lhs) - print(" = ") - print(rhs) - - case Return(expr, label) => - if (label.isEmpty) { - print("return ") - print(expr) - } else { - print("return(") - print(label.get) - print(") ") - print(expr) - } - - case If(cond, BooleanLiteral(true), elsep) => - print(cond) - print(" || ") - print(elsep) - - case If(cond, thenp, BooleanLiteral(false)) => - print(cond) - print(" && ") - print(thenp) - - case If(cond, thenp, elsep) => - print("if (") - print(cond) - print(") ") - - printBlock(thenp) - elsep match { - case Skip() => () - case If(_, _, _) => - print(" else ") - print(elsep) - case _ => - print(" else ") - printBlock(elsep) - } - - case While(cond, body, label) => - if (label.isDefined) { - print(label.get) - print(": ") - } - print("while (") - print(cond) - print(") ") - printBlock(body) - - case DoWhile(body, cond, label) => - if (label.isDefined) { - print(label.get) - print(": ") - } - print("do ") - printBlock(body) - print(" while (") - print(cond) - print(')') - - case TryFinally(TryCatch(block, errVar, handler), finalizer) => - print("try ") - printBlock(block) - print(" catch (") - print(errVar) - print(") ") - printBlock(handler) - print(" finally ") - printBlock(finalizer) - - case TryCatch(block, errVar, handler) => - print("try ") - printBlock(block) - print(" catch (") - print(errVar) - print(") ") - printBlock(handler) - - case TryFinally(block, finalizer) => - print("try ") - printBlock(block) - print(" finally ") - printBlock(finalizer) - - case Throw(expr) => - print("throw ") - print(expr) - - case Continue(label) => - print("continue") - if (label.isDefined) { - print(' ') - print(label.get) - } - - case Match(selector, cases, default) => - print("match (") - print(selector) - print(") {"); indent - for ((values, body) <- cases) { - println() - printRow(values, "case ", " | ", ":"); indent; println() - print(body) - print(";") - undent - } - println() - print("default:"); indent; println() - print(default) - print(";") - undent - undent; println(); print('}') - - case Debugger() => - print("debugger") - - // Scala expressions - - case New(cls, ctor, args) => - print("new ") - print(cls) - print("().") - print(ctor) - printArgs(args) - - case LoadModule(cls) => - print("mod:") - print(cls) - - case StoreModule(cls, value) => - print("mod:") - print(cls) - print("<-") - print(value) - - case Select(qualifier, item) => - print(qualifier) - print('.') - print(item) - - case SelectStatic(cls, item) => - print(cls) - print('.') - print(item) - - case Apply(receiver, method, args) => - print(receiver) - print(".") - print(method) - printArgs(args) - - case ApplyStatically(receiver, cls, method, args) => - print(receiver) - print(".") - print(cls) - print("::") - print(method) - printArgs(args) - - case ApplyStatic(cls, method, args) => - print(cls) - print("::") - print(method) - printArgs(args) - - case UnaryOp(op, lhs) => - import UnaryOp._ - print('(') - print((op: @switch) match { - case Boolean_! => "!" - case IntToLong | DoubleToLong => "(long)" - case DoubleToInt | LongToInt => "(int)" - case DoubleToFloat => "(float)" - case LongToDouble => "(double)" - }) - print(lhs) - print(')') - - case BinaryOp(BinaryOp.Int_-, IntLiteral(0), rhs) => - print("(-") - print(rhs) - print(')') - - case BinaryOp(BinaryOp.Int_^, IntLiteral(-1), rhs) => - print("(~") - print(rhs) - print(')') - - case BinaryOp(BinaryOp.Long_-, LongLiteral(0L), rhs) => - print("(-") - print(rhs) - print(')') - - case BinaryOp(BinaryOp.Long_^, LongLiteral(-1L), rhs) => - print("(~") - print(rhs) - print(')') - - case BinaryOp(BinaryOp.Float_-, FloatLiteral(0.0f), rhs) => - print("(-") - print(rhs) - print(')') - - case BinaryOp(BinaryOp.Double_-, - IntLiteral(0) | FloatLiteral(0.0f) | DoubleLiteral(0.0), rhs) => - print("(-") - print(rhs) - print(')') - - case BinaryOp(op, lhs, rhs) => - import BinaryOp._ - print('(') - print(lhs) - print(' ') - print((op: @switch) match { - case === => "===" - case !== => "!==" - - case String_+ => "+[string]" - - case Int_+ => "+[int]" - case Int_- => "-[int]" - case Int_* => "*[int]" - case Int_/ => "/[int]" - case Int_% => "%[int]" - - case Int_| => "|[int]" - case Int_& => "&[int]" - case Int_^ => "^[int]" - case Int_<< => "<<[int]" - case Int_>>> => ">>>[int]" - case Int_>> => ">>[int]" - - case Float_+ => "+[float]" - case Float_- => "-[float]" - case Float_* => "*[float]" - case Float_/ => "/[float]" - case Float_% => "%[float]" - - case Double_+ => "+[double]" - case Double_- => "-[double]" - case Double_* => "*[double]" - case Double_/ => "/[double]" - case Double_% => "%[double]" - - case Num_== => "==" - case Num_!= => "!=" - case Num_< => "<" - case Num_<= => "<=" - case Num_> => ">" - case Num_>= => ">=" - - case Long_+ => "+[long]" - case Long_- => "-[long]" - case Long_* => "*[long]" - case Long_/ => "/[long]" - case Long_% => "%[long]" - - case Long_| => "|[long]" - case Long_& => "&[long]" - case Long_^ => "^[long]" - case Long_<< => "<<[long]" - case Long_>>> => ">>>[long]" - case Long_>> => ">>[long]" - - case Long_== => "==[long]" - case Long_!= => "!=[long]" - case Long_< => "<[long]" - case Long_<= => "<=[long]" - case Long_> => ">[long]" - case Long_>= => ">=[long]" - - case Boolean_== => "==[bool]" - case Boolean_!= => "!=[bool]" - case Boolean_| => "|[bool]" - case Boolean_& => "&[bool]" - }) - print(' ') - print(rhs) - print(')') - - case NewArray(tpe, lengths) => - print("new ") - print(tpe.baseClassName) - for (length <- lengths) { - print('[') - print(length) - print(']') - } - for (dim <- lengths.size until tpe.dimensions) - print("[]") - - case ArrayValue(tpe, elems) => - print(tpe) - printArgs(elems) - - case ArrayLength(array) => - print(array) - print(".length") - - case ArraySelect(array, index) => - print(array) - print('[') - print(index) - print(']') - - case RecordValue(tpe, elems) => - print('(') - var first = true - for ((field, value) <- tpe.fields zip elems) { - if (first) first = false - else print(", ") - print(field.name) - print(" = ") - print(value) - } - print(')') - - case IsInstanceOf(expr, cls) => - print(expr) - print(".isInstanceOf[") - printRefType(cls) - print(']') - - case AsInstanceOf(expr, cls) => - print(expr) - print(".asInstanceOf[") - printRefType(cls) - print(']') - - case Unbox(expr, charCode) => - print(expr) - print(".asInstanceOf[") - print(charCode) - print(']') - - case GetClass(expr) => - print(expr) - print(".getClass()") - - case CallHelper(helper, args) => - print(helper) - printArgs(args) - - // JavaScript expressions - - case JSNew(ctor, args) => - def containsOnlySelectsFromAtom(tree: Tree): Boolean = tree match { - case JSDotSelect(qual, _) => containsOnlySelectsFromAtom(qual) - case JSBracketSelect(qual, _) => containsOnlySelectsFromAtom(qual) - case VarRef(_) => true - case This() => true - case _ => false // in particular, Apply - } - if (containsOnlySelectsFromAtom(ctor)) { - print("new ") - print(ctor) - } else { - print("new (") - print(ctor) - print(')') - } - printArgs(args) - - case JSDotSelect(qualifier, item) => - print(qualifier) - print(".") - print(item) - - case JSBracketSelect(qualifier, item) => - print(qualifier) - print('[') - print(item) - print(']') - - case JSFunctionApply(fun, args) => - fun match { - case _:JSDotSelect | _:JSBracketSelect | _:Select => - print("(0, ") - print(fun) - print(')') - - case _ => - print(fun) - } - printArgs(args) - - case JSDotMethodApply(receiver, method, args) => - print(receiver) - print(".") - print(method) - printArgs(args) - - case JSBracketMethodApply(receiver, method, args) => - print(receiver) - print('[') - print(method) - print(']') - printArgs(args) - - case JSSuperBracketSelect(cls, qualifier, item) => - print(qualifier) - print('.') - print(cls) - print("::super[") - print(item) - print(']') - - case JSSuperBracketCall(cls, receiver, method, args) => - print(receiver) - print('.') - print(cls) - print("::super[") - print(method) - print(']') - printArgs(args) - - case JSSuperConstructorCall(args) => - print("super") - printArgs(args) - - case JSImportCall(arg) => - print("import(") - print(arg) - print(')') - - case LoadJSConstructor(cls) => - print("constructorOf[") - print(cls) - print(']') - - case LoadJSModule(cls) => - print("mod:") - print(cls) - - case JSSpread(items) => - print("...") - print(items) - - case JSDelete(prop) => - print("delete ") - print(prop) - - case JSUnaryOp(op, lhs) => - import JSUnaryOp._ - print('(') - print((op: @switch) match { - case + => "+" - case - => "-" - case ~ => "~" - case ! => "!" - - case `typeof` => "typeof " - }) - print(lhs) - print(")") - - case JSBinaryOp(op, lhs, rhs) => - import JSBinaryOp._ - print('(') - print(lhs) - print(" ") - print((op: @switch) match { - case === => "===" - case !== => "!==" - - case + => "+" - case - => "-" - case * => "*" - case / => "/" - case % => "%" - - case | => "|" - case & => "&" - case ^ => "^" - case << => "<<" - case >> => ">>" - case >>> => ">>>" - - case < => "<" - case <= => "<=" - case > => ">" - case >= => ">=" - - case && => "&&" - case || => "||" - - case `in` => "in" - case `instanceof` => "instanceof" - }) - print(" ") - print(rhs) - print(')') - - case JSArrayConstr(items) => - printRow(items, "[", ", ", "]") - - case JSObjectConstr(Nil) => - print("{}") - - case JSObjectConstr(fields) => - print('{'); indent; println() - var rest = fields - while (rest.nonEmpty) { - print(rest.head._1) - print(": ") - print(rest.head._2) - rest = rest.tail - if (rest.nonEmpty) { - print(",") - println() - } - } - undent; println(); print('}') - - case JSLinkingInfo() => - print("") - - // Literals - - case Undefined() => - print("(void 0)") - - case Null() => - print("null") - - case BooleanLiteral(value) => - print(if (value) "true" else "false") - - case IntLiteral(value) => - if (value >= 0) { - print(value.toString) - } else { - print('(') - print(value.toString) - print(')') - } - - case LongLiteral(value) => - if (value < 0L) - print('(') - print(value.toString) - print('L') - if (value < 0L) - print(')') - - case FloatLiteral(value) => - if (value == 0.0f && 1.0f / value < 0.0f) { - print("(-0f)") - } else { - if (value < 0.0f) - print('(') - print(value.toString) - print('f') - if (value < 0.0f) - print(')') - } - - case DoubleLiteral(value) => - if (value == 0.0 && 1.0 / value < 0.0) { - print("(-0d)") - } else { - if (value < 0.0) - print('(') - print(value.toString) - print('d') - if (value < 0.0) - print(')') - } - - case StringLiteral(value) => - print('\"') - printEscapeJS(value, out) - print('\"') - - case ClassOf(cls) => - print("classOf[") - printRefType(cls) - print(']') - - // Specials - - case UndefinedParam() => - print("") - - // Atomic expressions - - case VarRef(ident) => - print(ident) - - case This() => - print("this") - - case Closure(captureParams, params, body, captureValues) => - print("(lambda<") - var first = true - for ((param, value) <- captureParams.zip(captureValues)) { - if (first) - first = false - else - print(", ") - print(param) - print(" = ") - print(value) - } - printRow(params, ">(", ", ", ") = ") - printBlock(body) - print(')') - - // Classes - - case tree: ClassDef => - val ClassDef(name, kind, superClass, interfaces, jsNativeLoadSpec, - defs) = tree - print(tree.optimizerHints) - kind match { - case ClassKind.Class => print("class ") - case ClassKind.ModuleClass => print("module class ") - case ClassKind.Interface => print("interface ") - case ClassKind.AbstractJSType => print("abstract js type ") - case ClassKind.HijackedClass => print("hijacked class ") - case ClassKind.JSClass => print("js class ") - case ClassKind.JSModuleClass => print("js module class ") - case ClassKind.NativeJSClass => print("native js class ") - case ClassKind.NativeJSModuleClass => print("native js module class ") - } - print(name) - superClass.foreach { cls => - print(" extends ") - print(cls) - } - if (interfaces.nonEmpty) { - print(" implements ") - var rest = interfaces - while (rest.nonEmpty) { - print(rest.head) - rest = rest.tail - if (rest.nonEmpty) - print(", ") - } - } - jsNativeLoadSpec.foreach { spec => - print(" loadfrom ") - print(spec) - } - print(" ") - printColumn(defs, "{", "", "}") - - case FieldDef(static, name, vtpe, mutable) => - if (static) - print("static ") - if (mutable) - print("var ") - else - print("val ") - print(name) - print(": ") - print(vtpe) - - case tree: MethodDef => - val MethodDef(static, name, args, resultType, body) = tree - print(tree.optimizerHints) - if (static) - print("static ") - print("def ") - print(name) - printSig(args, resultType) - body.fold { - print("") - } { body => - printBlock(body) - } - - case PropertyDef(static, name, getterBody, setterArgAndBody) => - getterBody foreach { body => - if (static) - print("static ") - print("get ") - print(name) - printSig(Nil, AnyType) - printBlock(body) - } - - if (getterBody.isDefined && setterArgAndBody.isDefined) { - println() - } - - setterArgAndBody foreach { case (arg, body) => - if (static) - print("static ") - print("set ") - print(name) - printSig(arg :: Nil, NoType) - printBlock(body) - } - - case ConstructorExportDef(fullName, args, body) => - print("export \"") - printEscapeJS(fullName, out) - print('\"') - printSig(args, NoType) // NoType as trick not to display a type - printBlock(body) - - case JSClassExportDef(fullName) => - print("export class \"") - printEscapeJS(fullName, out) - print('\"') - - case ModuleExportDef(fullName) => - print("export module \"") - printEscapeJS(fullName, out) - print('\"') - - case TopLevelModuleExportDef(fullName) => - print("export top module \"") - printEscapeJS(fullName, out) - print('\"') - - case TopLevelMethodExportDef(methodDef) => - print("export top ") - print(methodDef) - - case TopLevelFieldExportDef(fullName, field) => - print("export top static field ") - print(field) - print(" as \"") - printEscapeJS(fullName, out) - print('\"') - - case _ => - print(s"") - } - } - - def printRefType(tpe: ReferenceType): Unit = - print(tpe.asInstanceOf[Type]) - - def print(tpe: Type): Unit = tpe match { - case AnyType => print("any") - case NothingType => print("nothing") - case UndefType => print("void") - case BooleanType => print("boolean") - case IntType => print("int") - case LongType => print("long") - case FloatType => print("float") - case DoubleType => print("double") - case StringType => print("string") - case NullType => print("null") - case ClassType(className) => print(className) - case NoType => print("") - - case ArrayType(base, dims) => - print(base) - for (i <- 1 to dims) - print("[]") - - case RecordType(fields) => - print('(') - var first = true - for (RecordType.Field(name, _, tpe, mutable) <- fields) { - if (first) - first = false - else - print(", ") - if (mutable) - print("var ") - print(name) - print(": ") - print(tpe) - } - print(')') - } - - protected def print(ident: Ident): Unit = - printEscapeJS(ident.name, out) - - private final def print(propName: PropertyName): Unit = propName match { - case lit: StringLiteral => print(lit: Tree) - case ident: Ident => print(ident) - - case ComputedName(tree, index) => - print("[") - print(tree) - print("](") - print(index) - print(")") - } - - private def print(spec: JSNativeLoadSpec): Unit = { - def printPath(path: List[String]): Unit = { - for (propName <- path) { - if (isValidIdentifier(propName)) { - print('.') - print(propName) - } else { - print('[') - print(propName) - print(']') - } - } - } - - spec match { - case JSNativeLoadSpec.Global(path) => - print("") - printPath(path) - - case JSNativeLoadSpec.Import(module, path) => - print("import(") - print(module) - print(')') - printPath(path) - - case JSNativeLoadSpec.ImportWithGlobalFallback(importSpec, globalSpec) => - print(importSpec) - print(" fallback ") - print(globalSpec) - } - } - - protected def print(s: String): Unit = - out.write(s) - - protected def print(c: Int): Unit = - out.write(c) - - protected def print(optimizerHints: OptimizerHints)( - implicit dummy: DummyImplicit): Unit = { - if (optimizerHints != OptimizerHints.empty) { - print("@hints(") - print(optimizerHints.bits.toString) - print(") ") - } - } - - // Make it public - override def println(): Unit = super.println() - - def complete(): Unit = () - } - - class InfoPrinter(protected val out: Writer) extends IndentationManager { - def printClassInfoHeader(classInfo: ClassInfo): Unit = { - import classInfo._ - print("encodedName: ") - printEscapeJS(encodedName, out) - println() - print("isExported: ") - print(isExported.toString) - println() - print("kind: ") - print(kind.toString) - println() - print("superClass: ") - print(if (superClass == null) "null" else superClass.toString) - println() - - if (interfaces.nonEmpty) { - print("interfaces: [") - var rest = interfaces - while (rest.nonEmpty) { - printEscapeJS(rest.head, out) - rest = rest.tail - if (rest.nonEmpty) - print(", ") - } - print(']') - println() - } - } - - def print(classInfo: ClassInfo): Unit = { - import classInfo._ - - printClassInfoHeader(classInfo) - - print("methods:") - indent(); println() - methods.foreach((mi: MethodInfo) => print(mi)) - undent(); println() - } - - def print(methodInfo: MethodInfo): Unit = { - import methodInfo._ - printEscapeJS(encodedName, out) - print(":") - indent(); println() - - if (isStatic) { - print("isStatic: ") - print(isStatic.toString) - println() - } - if (isAbstract) { - print("isAbstract: ") - print(isAbstract.toString) - println() - } - if (isExported) { - print("isExported: ") - print(isExported.toString) - println() - } - if (methodsCalled.nonEmpty) { - print("methodsCalled:") - indent(); println() - val iter = methodsCalled.iterator - while (iter.hasNext) { - val (cls, callers) = iter.next() - printEscapeJS(cls, out) - printRow(callers, ": [", ", ", "]") - if (iter.hasNext) - println() - } - undent(); println() - } - if (methodsCalledStatically.nonEmpty) { - print("methodsCalledStatically:") - indent(); println() - val iter = methodsCalledStatically.iterator - while (iter.hasNext) { - val (cls, callers) = iter.next - printEscapeJS(cls, out) - printRow(callers, ": [", ", ", "]") - if (iter.hasNext) - println() - } - undent(); println() - } - if (staticMethodsCalled.nonEmpty) { - print("staticMethodsCalled:") - indent(); println() - val iter = staticMethodsCalled.iterator - while (iter.hasNext) { - val (cls, callers) = iter.next() - printEscapeJS(cls, out) - printRow(callers, ": [", ", ", "]") - if (iter.hasNext) - println() - } - undent(); println() - } - if (instantiatedClasses.nonEmpty) - printRow(instantiatedClasses, "instantiatedClasses: [", ", ", "]") - if (accessedModules.nonEmpty) - printRow(accessedModules, "accessedModules: [", ", ", "]") - if (usedInstanceTests.nonEmpty) - printRow(usedInstanceTests, "usedInstanceTests: [", ", ", "]") - if (accessedClassData.nonEmpty) - printRow(accessedClassData, "accessedClassData: [", ", ", "]") - - undent(); println() - } - - protected def printRow(ts: List[String], start: String, sep: String, - end: String): Unit = { - print(start) - var rest = ts - while (rest.nonEmpty) { - print(rest.head) - rest = rest.tail - if (rest.nonEmpty) - print(sep) - } - print(end) - } - - protected def print(s: String): Unit = - out.write(s) - - protected def print(c: Int): Unit = - out.write(c) - - def complete(): Unit = () - } - -} diff --git a/ir/src/main/scala/org/scalajs/core/ir/ScalaJSVersions.scala b/ir/src/main/scala/org/scalajs/core/ir/ScalaJSVersions.scala deleted file mode 100644 index 923fdef6db..0000000000 --- a/ir/src/main/scala/org/scalajs/core/ir/ScalaJSVersions.scala +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.ir - -object ScalaJSVersions { - - /* DO NOT MAKE THESE 'final val's! - * When referring to these "constants" from separate libraries, if it is a - * 'final val', the value will be copied in the binaries of those libraries. - * If they are then linked to a different version of the IR artifact, their - * copy of these constants will not be updated. - */ - - /** Scala.js version. */ - val current: String = "0.6.33" - - /** true iff the Scala.js version is a snapshot version. */ - val currentIsSnapshot: Boolean = current endsWith "-SNAPSHOT" - - /** Version of binary IR emitted by this version of Scala.js. - * - * This should be either of: - * - a prior release version (i.e. "0.5.0", *not* "0.5.0-SNAPSHOT") - * - a copy-paste of the *rhs* of `current` (*not* a reference to the val - * `current`, so that we notice a potential "-SNAPSHOT" suffix to be - * replaced on release, to avoid issues like #3865). - */ - val binaryEmitted: String = "0.6.29" - - /** Versions whose binary files we can support (used by deserializer) */ - val binarySupported: Set[String] = { - /* Note: 0.6.30 was never meant to be a valid IR version, but it Scala.js - * v0.6.30 was published with accidentally advertising that it emits IR - * version 0.6.30, while itself not being able to consume IR v0.6.29. We - * therefore advertise that we support consuming IR v0.6.30 although we - * emit v0.6.29. - */ - Set("0.6.0", "0.6.3", "0.6.4", "0.6.5", "0.6.6", "0.6.8", "0.6.13", - "0.6.14", "0.6.15", "0.6.17", "0.6.29", "0.6.30", binaryEmitted) - } - - // Just to be extra safe - assert(binarySupported contains binaryEmitted) - -} diff --git a/ir/src/main/scala/org/scalajs/core/ir/Serializers.scala b/ir/src/main/scala/org/scalajs/core/ir/Serializers.scala deleted file mode 100644 index f4af1f4ce0..0000000000 --- a/ir/src/main/scala/org/scalajs/core/ir/Serializers.scala +++ /dev/null @@ -1,1159 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.ir - -import scala.annotation.switch - -import java.io._ -import java.net.URI - -import scala.collection.mutable - -import Definitions.isConstructorName -import Position._ -import Trees._ -import Types._ -import Tags._ - -import Utils.JumpBackByteArrayOutputStream - -object Serializers { - def serialize(stream: OutputStream, tree: Tree): Unit = { - new Serializer().serialize(stream, tree) - } - - def deserialize(stream: InputStream, version: String): Tree = { - new Deserializer(stream, version).deserialize() - } - - // true for easier debugging (not for "production", it adds 8 bytes per node) - private final val UseDebugMagic = false - private final val DebugMagic = 0x3fa8ef84 - private final val PosDebugMagic = 0x65f0ec32 - - private object PositionFormat { - /* Positions are serialized incrementally as diffs wrt the last position. - * - * Formats are (the first byte is decomposed in bits): - * - * 1st byte | next bytes | description - * ----------------------------------------- - * ccccccc0 | | Column diff (7-bit signed) - * llllll01 | CC | Line diff (6-bit signed), column (8-bit unsigned) - * ____0011 | LL LL CC | Line diff (16-bit signed), column (8-bit unsigned) - * ____0111 | 12 bytes | File index, line, column (all 32-bit signed) - * 11111111 | | NoPosition (is not compared/stored in last position) - * - * Underscores are irrelevant and must be set to 0. - */ - - final val Format1Mask = 0x01 - final val Format1MaskValue = 0x00 - final val Format1Shift = 1 - - final val Format2Mask = 0x03 - final val Format2MaskValue = 0x01 - final val Format2Shift = 2 - - final val Format3Mask = 0x0f - final val Format3MaskValue = 0x03 - - final val FormatFullMask = 0x0f - final val FormatFullMaskValue = 0x7 - - final val FormatNoPositionValue = -1 - } - - private final class Serializer { - private[this] val bufferUnderlying = new JumpBackByteArrayOutputStream - private[this] val buffer = new DataOutputStream(bufferUnderlying) - - private[this] val files = mutable.ListBuffer.empty[URI] - private[this] val fileIndexMap = mutable.Map.empty[URI, Int] - private def fileToIndex(file: URI): Int = - fileIndexMap.getOrElseUpdate(file, (files += file).size - 1) - - private[this] val strings = mutable.ListBuffer.empty[String] - private[this] val stringIndexMap = mutable.Map.empty[String, Int] - private def stringToIndex(str: String): Int = - stringIndexMap.getOrElseUpdate(str, (strings += str).size - 1) - - private[this] var lastPosition: Position = Position.NoPosition - - def serialize(stream: OutputStream, tree: Tree): Unit = { - // Write tree to buffer and record files and strings - writeTree(tree) - - val s = new DataOutputStream(stream) - - // Emit the files - s.writeInt(files.size) - files.foreach(f => s.writeUTF(f.toString)) - - // Emit the strings - s.writeInt(strings.size) - strings.foreach(s.writeUTF) - - // Paste the buffer - bufferUnderlying.writeTo(s) - - s.flush() - } - - def writeTree(tree: Tree): Unit = { - import buffer._ - writePosition(tree.pos) - tree match { - case VarDef(ident, vtpe, mutable, rhs) => - writeByte(TagVarDef) - writeIdent(ident); writeType(vtpe); writeBoolean(mutable); writeTree(rhs) - - case ParamDef(ident, ptpe, mutable, rest) => - writeByte(TagParamDef) - writeIdent(ident); writeType(ptpe); writeBoolean(mutable); writeBoolean(rest) - - case Skip() => - writeByte(TagSkip) - - case Block(stats) => - writeByte(TagBlock) - writeTrees(stats) - - case Labeled(label, tpe, body) => - writeByte(TagLabeled) - writeIdent(label); writeType(tpe); writeTree(body) - - case Assign(lhs, rhs) => - writeByte(TagAssign) - writeTree(lhs); writeTree(rhs) - - case Return(expr, label) => - writeByte(TagReturn) - writeTree(expr); writeOptIdent(label) - - case If(cond, thenp, elsep) => - writeByte(TagIf) - writeTree(cond); writeTree(thenp); writeTree(elsep) - writeType(tree.tpe) - - case While(cond, body, label) => - writeByte(TagWhile) - writeTree(cond); writeTree(body); writeOptIdent(label) - - case DoWhile(body, cond, label) => - writeByte(TagDoWhile) - writeTree(body); writeTree(cond); writeOptIdent(label) - - case TryCatch(block, errVar, handler) => - writeByte(TagTryCatch) - writeTree(block); writeIdent(errVar); writeTree(handler) - writeType(tree.tpe) - - case TryFinally(block, finalizer) => - writeByte(TagTryFinally) - writeTree(block); writeTree(finalizer) - - case Throw(expr) => - writeByte(TagThrow) - writeTree(expr) - - case Continue(label) => - writeByte(TagContinue) - writeOptIdent(label) - - case Match(selector, cases, default) => - writeByte(TagMatch) - writeTree(selector) - writeInt(cases.size) - cases foreach { caze => - writeTrees(caze._1); writeTree(caze._2) - } - writeTree(default) - writeType(tree.tpe) - - case Debugger() => - writeByte(TagDebugger) - - case New(cls, ctor, args) => - writeByte(TagNew) - writeClassType(cls); writeIdent(ctor); writeTrees(args) - - case LoadModule(cls) => - writeByte(TagLoadModule) - writeClassType(cls) - - case StoreModule(cls, value) => - writeByte(TagStoreModule) - writeClassType(cls); writeTree(value) - - case Select(qualifier, item) => - writeByte(TagSelect) - writeTree(qualifier); writeIdent(item) - writeType(tree.tpe) - - case SelectStatic(cls, item) => - writeByte(TagSelectStatic) - writeClassType(cls); writeIdent(item) - writeType(tree.tpe) - - case Apply(receiver, method, args) => - writeByte(TagApply) - writeTree(receiver); writeIdent(method); writeTrees(args) - writeType(tree.tpe) - - case ApplyStatically(receiver, cls, method, args) => - writeByte(TagApplyStatically) - writeTree(receiver); writeClassType(cls); writeIdent(method); writeTrees(args) - writeType(tree.tpe) - - case ApplyStatic(cls, method, args) => - writeByte(TagApplyStatic) - writeClassType(cls); writeIdent(method); writeTrees(args) - writeType(tree.tpe) - - case UnaryOp(op, lhs) => - writeByte(TagUnaryOp) - writeByte(op); writeTree(lhs) - - case BinaryOp(op, lhs, rhs) => - writeByte(TagBinaryOp) - writeByte(op); writeTree(lhs); writeTree(rhs) - - case NewArray(tpe, lengths) => - writeByte(TagNewArray) - writeArrayType(tpe); writeTrees(lengths) - - case ArrayValue(tpe, elems) => - writeByte(TagArrayValue) - writeArrayType(tpe); writeTrees(elems) - - case ArrayLength(array) => - writeByte(TagArrayLength) - writeTree(array) - - case ArraySelect(array, index) => - writeByte(TagArraySelect) - writeTree(array); writeTree(index) - writeType(tree.tpe) - - case RecordValue(tpe, elems) => - writeByte(TagRecordValue) - writeType(tpe); writeTrees(elems) - - case IsInstanceOf(expr, cls) => - writeByte(TagIsInstanceOf) - writeTree(expr); writeReferenceType(cls) - - case AsInstanceOf(expr, cls) => - writeByte(TagAsInstanceOf) - writeTree(expr); writeReferenceType(cls) - - case Unbox(expr, charCode) => - writeByte(TagUnbox) - writeTree(expr); writeByte(charCode.toByte) - - case GetClass(expr) => - writeByte(TagGetClass) - writeTree(expr) - - case CallHelper(helper, args) => - writeByte(TagCallHelper) - writeString(helper); writeTrees(args) - writeType(tree.tpe) - - case JSNew(ctor, args) => - writeByte(TagJSNew) - writeTree(ctor); writeTrees(args) - - case JSDotSelect(qualifier, item) => - writeByte(TagJSDotSelect) - writeTree(qualifier); writeIdent(item) - - case JSBracketSelect(qualifier, item) => - writeByte(TagJSBracketSelect) - writeTree(qualifier); writeTree(item) - - case JSFunctionApply(fun, args) => - writeByte(TagJSFunctionApply) - writeTree(fun); writeTrees(args) - - case JSDotMethodApply(receiver, method, args) => - writeByte(TagJSDotMethodApply) - writeTree(receiver); writeIdent(method); writeTrees(args) - - case JSBracketMethodApply(receiver, method, args) => - writeByte(TagJSBracketMethodApply) - writeTree(receiver); writeTree(method); writeTrees(args) - - case JSSuperBracketSelect(cls, qualifier, item) => - writeByte(TagJSSuperBracketSelect) - writeClassType(cls); writeTree(qualifier); writeTree(item) - - case JSSuperBracketCall(cls, receiver, method, args) => - writeByte(TagJSSuperBracketCall) - writeClassType(cls); writeTree(receiver); writeTree(method); writeTrees(args) - - case JSSuperConstructorCall(args) => - writeByte(TagJSSuperConstructorCall) - writeTrees(args) - - case JSImportCall(arg) => - writeByte(TagJSImportCall) - writeTree(arg) - - case LoadJSConstructor(cls) => - writeByte(TagLoadJSConstructor) - writeClassType(cls) - - case LoadJSModule(cls) => - writeByte(TagLoadJSModule) - writeClassType(cls) - - case JSSpread(items) => - writeByte(TagJSSpread) - writeTree(items) - - case JSDelete(prop) => - writeByte(TagJSDelete) - writeTree(prop) - - case JSUnaryOp(op, lhs) => - writeByte(TagJSUnaryOp) - writeInt(op); writeTree(lhs) - - case JSBinaryOp(op, lhs, rhs) => - writeByte(TagJSBinaryOp) - writeInt(op); writeTree(lhs); writeTree(rhs) - - case JSArrayConstr(items) => - writeByte(TagJSArrayConstr) - writeTrees(items) - - case JSObjectConstr(fields) => - writeByte(TagJSObjectConstr) - writeInt(fields.size) - fields foreach { field => - writePropertyName(field._1); writeTree(field._2) - } - - case JSLinkingInfo() => - writeByte(TagJSLinkingInfo) - - case Undefined() => - writeByte(TagUndefined) - - case Null() => - writeByte(TagNull) - - case BooleanLiteral(value) => - writeByte(TagBooleanLiteral) - writeBoolean(value) - - case IntLiteral(value) => - writeByte(TagIntLiteral) - writeInt(value) - - case LongLiteral(value) => - writeByte(TagLongLiteral) - writeLong(value) - - case FloatLiteral(value) => - writeByte(TagFloatLiteral) - writeFloat(value) - - case DoubleLiteral(value) => - writeByte(TagDoubleLiteral) - writeDouble(value) - - case StringLiteral(value) => - writeByte(TagStringLiteral) - writeString(value) - - case ClassOf(cls) => - writeByte(TagClassOf) - writeReferenceType(cls) - - case UndefinedParam() => - writeByte(TagUndefinedParam) - writeType(tree.tpe) - - case VarRef(ident) => - writeByte(TagVarRef) - writeIdent(ident) - writeType(tree.tpe) - - case This() => - writeByte(TagThis) - writeType(tree.tpe) - - case Closure(captureParams, params, body, captureValues) => - writeByte(TagClosure) - writeTrees(captureParams) - writeTrees(params) - writeTree(body) - writeTrees(captureValues) - - case tree: ClassDef => - val ClassDef(name, kind, superClass, parents, jsNativeLoadSpec, - defs) = tree - writeByte(TagClassDef) - writeIdent(name) - writeByte(ClassKind.toByte(kind)) - writeOptIdent(superClass) - writeIdents(parents) - writeJSNativeLoadSpec(jsNativeLoadSpec) - writeTrees(defs) - writeInt(tree.optimizerHints.bits) - - case FieldDef(static, name, ftpe, mutable) => - writeByte(TagFieldDef) - writeBoolean(static) - writePropertyName(name) - writeType(ftpe) - writeBoolean(mutable) - - case methodDef: MethodDef => - val MethodDef(static, name, args, resultType, body) = methodDef - - writeByte(TagMethodDef) - writeOptHash(methodDef.hash) - - // Prepare for back-jump and write dummy length - bufferUnderlying.markJump() - writeInt(-1) - - // Write out method def - writeBoolean(static); writePropertyName(name) - writeTrees(args); writeType(resultType); writeOptTree(body) - writeInt(methodDef.optimizerHints.bits) - - // Jump back and write true length - val length = bufferUnderlying.jumpBack() - writeInt(length) - bufferUnderlying.continue() - - case PropertyDef(static, name, getter, setterArgAndBody) => - writeByte(TagPropertyDef) - writeBoolean(static) - writePropertyName(name) - writeOptTree(getter) - writeBoolean(setterArgAndBody.isDefined) - setterArgAndBody foreach { case (arg, body) => - writeTree(arg); writeTree(body) - } - - case ConstructorExportDef(fullName, args, body) => - writeByte(TagConstructorExportDef) - writeString(fullName); writeTrees(args); writeTree(body) - - case JSClassExportDef(fullName) => - writeByte(TagJSClassExportDef) - writeString(fullName) - - case ModuleExportDef(fullName) => - writeByte(TagModuleExportDef) - writeString(fullName) - - case TopLevelModuleExportDef(fullName) => - writeByte(TagTopLevelModuleExportDef) - writeString(fullName) - - case TopLevelMethodExportDef(methodDef) => - writeByte(TagTopLevelMethodExportDef) - writeTree(methodDef) - - case TopLevelFieldExportDef(fullName, field) => - writeByte(TagTopLevelFieldExportDef) - writeString(fullName); writeIdent(field) - } - if (UseDebugMagic) - writeInt(DebugMagic) - } - - def writeTrees(trees: List[Tree]): Unit = { - buffer.writeInt(trees.size) - trees.foreach(writeTree) - } - - def writeOptTree(optTree: Option[Tree]): Unit = { - optTree.fold { - writePosition(Position.NoPosition) - buffer.writeByte(TagEmptyTree) - } { tree => - writeTree(tree) - } - } - - def writeIdent(ident: Ident): Unit = { - writePosition(ident.pos) - writeString(ident.name); writeString(ident.originalName.getOrElse("")) - } - - def writeIdents(idents: List[Ident]): Unit = { - buffer.writeInt(idents.size) - idents.foreach(writeIdent) - } - - def writeOptIdent(optIdent: Option[Ident]): Unit = { - buffer.writeBoolean(optIdent.isDefined) - optIdent.foreach(writeIdent) - } - - def writeType(tpe: Type): Unit = { - tpe match { - case AnyType => buffer.write(TagAnyType) - case NothingType => buffer.write(TagNothingType) - case UndefType => buffer.write(TagUndefType) - case BooleanType => buffer.write(TagBooleanType) - case IntType => buffer.write(TagIntType) - case LongType => buffer.write(TagLongType) - case FloatType => buffer.write(TagFloatType) - case DoubleType => buffer.write(TagDoubleType) - case StringType => buffer.write(TagStringType) - case NullType => buffer.write(TagNullType) - case NoType => buffer.write(TagNoType) - - case tpe: ClassType => - buffer.write(TagClassType) - writeClassType(tpe) - - case tpe: ArrayType => - buffer.write(TagArrayType) - writeArrayType(tpe) - - case RecordType(fields) => - buffer.write(TagRecordType) - buffer.writeInt(fields.size) - for (RecordType.Field(name, originalName, tpe, mutable) <- fields) { - writeString(name) - writeString(originalName.getOrElse("")) - writeType(tpe) - buffer.writeBoolean(mutable) - } - } - } - - def writeClassType(tpe: ClassType): Unit = - writeString(tpe.className) - - def writeArrayType(tpe: ArrayType): Unit = { - writeString(tpe.baseClassName) - buffer.writeInt(tpe.dimensions) - } - - def writeReferenceType(tpe: ReferenceType): Unit = - writeType(tpe.asInstanceOf[Type]) - - def writePropertyName(name: PropertyName): Unit = name match { - case name: Ident => - buffer.writeByte(TagPropertyNameIdent) - writeIdent(name) - - case name: StringLiteral => - buffer.writeByte(TagPropertyNameStringLiteral) - writeTree(name) - - case ComputedName(tree, index) => - buffer.writeByte(TagPropertyNameComputedName) - writeTree(tree) - writeString(index) - } - - def writePosition(pos: Position): Unit = { - import buffer._ - import PositionFormat._ - - def writeFull(): Unit = { - writeByte(FormatFullMaskValue) - writeInt(fileToIndex(pos.source)) - writeInt(pos.line) - writeInt(pos.column) - } - - if (pos == Position.NoPosition) { - writeByte(FormatNoPositionValue) - } else if (lastPosition == Position.NoPosition || - pos.source != lastPosition.source) { - writeFull() - lastPosition = pos - } else { - val line = pos.line - val column = pos.column - val lineDiff = line - lastPosition.line - val columnDiff = column - lastPosition.column - val columnIsByte = column >= 0 && column < 256 - - if (lineDiff == 0 && columnDiff >= -64 && columnDiff < 64) { - writeByte((columnDiff << Format1Shift) | Format1MaskValue) - } else if (lineDiff >= -32 && lineDiff < 32 && columnIsByte) { - writeByte((lineDiff << Format2Shift) | Format2MaskValue) - writeByte(column) - } else if (lineDiff >= Short.MinValue && lineDiff <= Short.MaxValue && columnIsByte) { - writeByte(Format3MaskValue) - writeShort(lineDiff) - writeByte(column) - } else { - writeFull() - } - - lastPosition = pos - } - - if (UseDebugMagic) - writeInt(PosDebugMagic) - } - - def writeJSNativeLoadSpec(jsNativeLoadSpec: Option[JSNativeLoadSpec]): Unit = { - import buffer._ - - def writeGlobalSpec(spec: JSNativeLoadSpec.Global): Unit = { - writeStrings(spec.path) - } - - def writeImportSpec(spec: JSNativeLoadSpec.Import): Unit = { - writeString(spec.module) - writeStrings(spec.path) - } - - jsNativeLoadSpec.fold { - writeByte(TagJSNativeLoadSpecNone) - } { spec => - spec match { - case spec: JSNativeLoadSpec.Global => - writeByte(TagJSNativeLoadSpecGlobal) - writeGlobalSpec(spec) - - case spec: JSNativeLoadSpec.Import => - writeByte(TagJSNativeLoadSpecImport) - writeImportSpec(spec) - - case JSNativeLoadSpec.ImportWithGlobalFallback(importSpec, globalSpec) => - writeByte(TagJSNativeLoadSpecImportWithGlobalFallback) - writeImportSpec(importSpec) - writeGlobalSpec(globalSpec) - } - } - } - - def writeOptHash(optHash: Option[TreeHash]): Unit = { - buffer.writeBoolean(optHash.isDefined) - for (hash <- optHash) { - buffer.write(hash.treeHash) - buffer.write(hash.posHash) - } - } - - def writeString(s: String): Unit = - buffer.writeInt(stringToIndex(s)) - - def writeStrings(strings: List[String]): Unit = { - buffer.writeInt(strings.size) - strings.foreach(writeString) - } - } - - private final class Deserializer(stream: InputStream, sourceVersion: String) { - private[this] val useHacks060 = sourceVersion == "0.6.0" - private[this] val useHacks065 = - Set("0.6.0", "0.6.3", "0.6.4", "0.6.5").contains(sourceVersion) - private[this] val useHacks066 = - useHacks065 || sourceVersion == "0.6.6" - private[this] val useHacks068 = - useHacks066 || sourceVersion == "0.6.8" - private[this] val useHacks0614 = - useHacks068 || Set("0.6.13", "0.6.14").contains(sourceVersion) - - private[this] val input = new DataInputStream(stream) - - private[this] val files = - Array.fill(input.readInt())(new URI(input.readUTF())) - - private[this] val strings = - Array.fill(input.readInt())(input.readUTF()) - - private[this] var lastPosition: Position = Position.NoPosition - - private[this] var foundArguments: Boolean = false - - def deserialize(): Tree = { - readTree() - } - - def readTree(): Tree = { - val pos = readPosition() - readTreeFromTag(input.readByte())(pos) - } - - def readOptTree(): Option[Tree] = { - // TODO switch tag and position when we can break binary compat. - val pos = readPosition() - val tag = input.readByte() - if (tag == TagEmptyTree) None - else Some(readTreeFromTag(tag)(pos)) - } - - private def readTreeFromTag(tag: Byte)(implicit pos: Position): Tree = { - import input._ - val result = (tag: @switch) match { - case TagEmptyTree => - throw new IOException("Found invalid TagEmptyTree") - - case TagVarDef => VarDef(readIdent(), readType(), readBoolean(), readTree()) - case TagParamDef => - ParamDef(readIdent(), readType(), readBoolean(), - rest = if (useHacks060) false else readBoolean()) - - case TagSkip => Skip() - case TagBlock => Block(readTrees()) - case TagLabeled => Labeled(readIdent(), readType(), readTree()) - case TagAssign => Assign(readTree(), readTree()) - case TagReturn => Return(readTree(), readOptIdent()) - case TagIf => If(readTree(), readTree(), readTree())(readType()) - case TagWhile => While(readTree(), readTree(), readOptIdent()) - case TagDoWhile => DoWhile(readTree(), readTree(), readOptIdent()) - - case TagTry => - if (!useHacks068) - throw new IOException("Invalid tag TagTry") - - val block = readTree() - val errVar = readIdent() - val handler = readOptTree() - val finalizer = readOptTree() - val tpe = readType() - - val maybeCatch = handler.fold(block)( - handler => TryCatch(block, errVar, handler)(tpe)) - finalizer.fold(maybeCatch)( - finalizer => TryFinally(maybeCatch, finalizer)) - - case TagTryCatch => - TryCatch(readTree(), readIdent(), readTree())(readType()) - - case TagTryFinally => - TryFinally(readTree(), readTree()) - - case TagThrow => Throw(readTree()) - case TagContinue => Continue(readOptIdent()) - case TagMatch => - Match(readTree(), List.fill(readInt()) { - (readTrees().map(_.asInstanceOf[Literal]), readTree()) - }, readTree())(readType()) - case TagDebugger => Debugger() - - case TagNew => New(readClassType(), readIdent(), readTrees()) - case TagLoadModule => LoadModule(readClassType()) - case TagStoreModule => StoreModule(readClassType(), readTree()) - case TagSelect => Select(readTree(), readIdent())(readType()) - case TagSelectStatic => SelectStatic(readClassType(), readIdent())(readType()) - case TagApply => Apply(readTree(), readIdent(), readTrees())(readType()) - case TagApplyStatically => - val result1 = - ApplyStatically(readTree(), readClassType(), readIdent(), readTrees())(readType()) - if (useHacks065 && result1.tpe != NoType && isConstructorName(result1.method.name)) - result1.copy()(NoType) - else - result1 - case TagApplyStatic => ApplyStatic(readClassType(), readIdent(), readTrees())(readType()) - case TagUnaryOp => UnaryOp(readByte(), readTree()) - case TagBinaryOp => BinaryOp(readByte(), readTree(), readTree()) - case TagNewArray => NewArray(readArrayType(), readTrees()) - case TagArrayValue => ArrayValue(readArrayType(), readTrees()) - case TagArrayLength => ArrayLength(readTree()) - case TagArraySelect => ArraySelect(readTree(), readTree())(readType()) - case TagRecordValue => RecordValue(readType().asInstanceOf[RecordType], readTrees()) - case TagIsInstanceOf => IsInstanceOf(readTree(), readReferenceType()) - case TagAsInstanceOf => AsInstanceOf(readTree(), readReferenceType()) - case TagUnbox => Unbox(readTree(), readByte().toChar) - case TagGetClass => GetClass(readTree()) - case TagCallHelper => CallHelper(readString(), readTrees())(readType()) - - case TagJSNew => JSNew(readTree(), readTrees()) - case TagJSDotSelect => JSDotSelect(readTree(), readIdent()) - case TagJSBracketSelect => JSBracketSelect(readTree(), readTree()) - case TagJSFunctionApply => JSFunctionApply(readTree(), readTrees()) - case TagJSDotMethodApply => JSDotMethodApply(readTree(), readIdent(), readTrees()) - case TagJSBracketMethodApply => JSBracketMethodApply(readTree(), readTree(), readTrees()) - case TagJSSuperBracketSelect => JSSuperBracketSelect(readClassType(), readTree(), readTree()) - case TagJSSuperBracketCall => - JSSuperBracketCall(readClassType(), readTree(), readTree(), readTrees()) - case TagJSSuperConstructorCall => JSSuperConstructorCall(readTrees()) - case TagJSImportCall => JSImportCall(readTree()) - case TagLoadJSConstructor => LoadJSConstructor(readClassType()) - case TagLoadJSModule => LoadJSModule(readClassType()) - case TagJSSpread => JSSpread(readTree()) - case TagJSDelete => JSDelete(readTree()) - case TagJSUnaryOp => JSUnaryOp(readInt(), readTree()) - case TagJSBinaryOp => JSBinaryOp(readInt(), readTree(), readTree()) - case TagJSArrayConstr => JSArrayConstr(readTrees()) - case TagJSObjectConstr => - JSObjectConstr(List.fill(readInt())((readPropertyName(), readTree()))) - case TagJSLinkingInfo => JSLinkingInfo() - - case TagJSEnvInfo => - if (useHacks066) - JSBracketSelect(JSLinkingInfo(), StringLiteral("envInfo")) - else - throw new MatchError(tag) - - case TagUndefined => Undefined() - case TagNull => Null() - case TagBooleanLiteral => BooleanLiteral(readBoolean()) - case TagIntLiteral => IntLiteral(readInt()) - case TagLongLiteral => LongLiteral(readLong()) - case TagFloatLiteral => FloatLiteral(readFloat()) - case TagDoubleLiteral => DoubleLiteral(readDouble()) - case TagStringLiteral => StringLiteral(readString()) - case TagClassOf => ClassOf(readReferenceType()) - - case TagUndefinedParam => UndefinedParam()(readType()) - - case TagVarRef => - val result = VarRef(readIdent())(readType()) - if (useHacks060 && result.ident.name == "arguments") - foundArguments = true - result - - case TagThis => This()(readType()) - case TagClosure => - Closure(readParamDefs(), readParamDefs(), readTree(), readTrees()) - - case TagClassDef => - val name = readIdent() - val kind0 = ClassKind.fromByte(readByte()) - val superClass = readOptIdent() - val parents = readIdents() - val jsNativeLoadSpec = readJSNativeLoadSpec() - val defs0 = readTrees() - val defs = if (useHacks065) { - defs0.filter { - case MethodDef(_, Ident(name, _), _, _, _) => - !Definitions.isReflProxyName(name) - case _ => - true - } - } else { - defs0 - } - val optimizerHints = new OptimizerHints(readInt()) - - val kind = { - if (useHacks068 && kind0 == ClassKind.AbstractJSType && - jsNativeLoadSpec.isDefined) { - ClassKind.NativeJSClass - } else { - kind0 - } - } - - ClassDef(name, kind, superClass, parents, jsNativeLoadSpec, defs)( - optimizerHints) - - case TagFieldDef => - if (useHacks0614) - FieldDef(static = false, readIdent(), readType(), readBoolean()) - else - FieldDef(readBoolean(), readPropertyName(), readType(), readBoolean()) - - case TagStringLitFieldDef if useHacks0614 => - FieldDef(static = false, readTree().asInstanceOf[StringLiteral], - readType(), readBoolean()) - - case TagMethodDef => - val optHash = readOptHash() - // read and discard the length - val len = readInt() - assert(len >= 0) - val result1 = MethodDef(readBoolean(), readPropertyName(), - readParamDefs(), readType(), readOptTree())( - new OptimizerHints(readInt()), optHash) - val result2 = if (foundArguments) { - foundArguments = false - new RewriteArgumentsTransformer().transformMethodDef(result1) - } else { - result1 - } - if (useHacks065 && result2.resultType != NoType && - isConstructorName(result2.name.encodedName)) { - result2.copy(resultType = NoType, body = result2.body)( - result2.optimizerHints, result2.hash)( - result2.pos) - } else { - result2 - } - - case TagPropertyDef => - val static = - if (useHacks0614) false - else readBoolean() - val name = readPropertyName() - val getterBody = readOptTree() - val setterArgAndBody = if (useHacks068) { - val setterArg = readTree().asInstanceOf[ParamDef] - readOptTree().map(setterBody => (setterArg, setterBody)) - } else { - if (readBoolean()) - Some((readTree().asInstanceOf[ParamDef], readTree())) - else - None - } - PropertyDef(static, name, getterBody, setterArgAndBody) - - case TagConstructorExportDef => - val result = ConstructorExportDef(readString(), readParamDefs(), readTree()) - if (foundArguments) { - foundArguments = false - new RewriteArgumentsTransformer().transformConstructorExportDef(result) - } else { - result - } - - case TagJSClassExportDef => JSClassExportDef(readString()) - case TagModuleExportDef => ModuleExportDef(readString()) - case TagTopLevelModuleExportDef => TopLevelModuleExportDef(readString()) - case TagTopLevelMethodExportDef => TopLevelMethodExportDef(readTree().asInstanceOf[MethodDef]) - case TagTopLevelFieldExportDef => TopLevelFieldExportDef(readString(), readIdent()) - } - if (UseDebugMagic) { - val magic = readInt() - assert(magic == DebugMagic, - s"Bad magic after reading a ${result.getClass}!") - } - result - } - - def readTrees(): List[Tree] = - List.fill(input.readInt())(readTree()) - - def readParamDefs(): List[ParamDef] = - readTrees().map(_.asInstanceOf[ParamDef]) - - def readIdent(): Ident = { - implicit val pos = readPosition() - val name = readString() - val originalName = readString() - Ident(name, if (originalName.isEmpty) None else Some(originalName)) - } - - def readIdents(): List[Ident] = - List.fill(input.readInt())(readIdent()) - - def readOptIdent(): Option[Ident] = { - if (input.readBoolean()) Some(readIdent()) - else None - } - - def readType(): Type = { - val tag = input.readByte() - (tag: @switch) match { - case TagAnyType => AnyType - case TagNothingType => NothingType - case TagUndefType => UndefType - case TagBooleanType => BooleanType - case TagIntType => IntType - case TagLongType => LongType - case TagFloatType => FloatType - case TagDoubleType => DoubleType - case TagStringType => StringType - case TagNullType => NullType - case TagNoType => NoType - - case TagClassType => readClassType() - case TagArrayType => readArrayType() - - case TagRecordType => - RecordType(List.fill(input.readInt()) { - val name = readString() - val originalName = readString() - val tpe = readType() - val mutable = input.readBoolean() - RecordType.Field(name, - if (originalName.isEmpty) None else Some(originalName), - tpe, mutable) - }) - } - } - - def readClassType(): ClassType = - ClassType(readString()) - - def readArrayType(): ArrayType = - ArrayType(readString(), input.readInt()) - - def readReferenceType(): ReferenceType = - readType().asInstanceOf[ReferenceType] - - def readPropertyName(): PropertyName = { - if (useHacks0614) { - if (input.readBoolean()) readIdent() - else readTree().asInstanceOf[StringLiteral] - } else { - input.readByte() match { - case TagPropertyNameIdent => - readIdent() - - case TagPropertyNameStringLiteral => - readTree().asInstanceOf[StringLiteral] - - case TagPropertyNameComputedName => - ComputedName(readTree(), readString()) - } - } - } - - def readPosition(): Position = { - import input._ - import PositionFormat._ - - val first = readByte() - - val result = if (first == FormatNoPositionValue) { - Position.NoPosition - } else { - val result = if ((first & FormatFullMask) == FormatFullMaskValue) { - val file = files(readInt()) - val line = readInt() - val column = readInt() - Position(file, line, column) - } else { - assert(lastPosition != NoPosition, - "Position format error: first position must be full") - if ((first & Format1Mask) == Format1MaskValue) { - val columnDiff = first >> Format1Shift - Position(lastPosition.source, lastPosition.line, - lastPosition.column + columnDiff) - } else if ((first & Format2Mask) == Format2MaskValue) { - val lineDiff = first >> Format2Shift - val column = readByte() & 0xff // unsigned - Position(lastPosition.source, - lastPosition.line + lineDiff, column) - } else { - assert((first & Format3Mask) == Format3MaskValue, - s"Position format error: first byte $first does not match any format") - val lineDiff = readShort() - val column = readByte() & 0xff // unsigned - Position(lastPosition.source, - lastPosition.line + lineDiff, column) - } - } - lastPosition = result - result - } - - if (UseDebugMagic) { - val magic = readInt() - assert(magic == PosDebugMagic, - s"Bad magic after reading position with first byte $first") - } - - result - } - - def readJSNativeLoadSpec(): Option[JSNativeLoadSpec] = { - if (useHacks068) { - Some(readString()).filter(_ != "").map { jsFullName => - JSNativeLoadSpec.Global(jsFullName.split("\\.").toList) - } - } else { - def readGlobalSpec(): JSNativeLoadSpec.Global = - JSNativeLoadSpec.Global(readStrings()) - - def readImportSpec(): JSNativeLoadSpec.Import = - JSNativeLoadSpec.Import(readString(), readStrings()) - - (input.readByte(): @switch) match { - case TagJSNativeLoadSpecNone => - None - case TagJSNativeLoadSpecGlobal => - Some(readGlobalSpec()) - case TagJSNativeLoadSpecImport => - Some(readImportSpec()) - case TagJSNativeLoadSpecImportWithGlobalFallback => - Some(JSNativeLoadSpec.ImportWithGlobalFallback( - readImportSpec(), readGlobalSpec())) - } - } - } - - def readOptHash(): Option[TreeHash] = { - if (input.readBoolean()) { - val treeHash = new Array[Byte](20) - val posHash = new Array[Byte](20) - input.readFully(treeHash) - input.readFully(posHash) - Some(new TreeHash(treeHash, posHash)) - } else None - } - - def readString(): String = { - strings(input.readInt()) - } - - def readStrings(): List[String] = - List.fill(input.readInt())(readString()) - } - - private class RewriteArgumentsTransformer extends Transformers.Transformer { - import RewriteArgumentsTransformer._ - - private[this] var paramToIndex: Map[String, Int] = _ - - def transformMethodDef(tree: MethodDef): MethodDef = { - /* Ideally, we would re-hash the new MethodDef here, but we cannot do - * that because it prevents the JS version of the tools to link. - * Since the hashes of exported methods are not used by our pipeline - * anyway, we simply put None. - */ - val MethodDef(static, name, args, resultType, body) = tree - setupParamToIndex(args) - MethodDef(static, name, List(argumentsParamDef(tree.pos)), - resultType, body.map(transform(_, isStat = resultType == NoType)))( - tree.optimizerHints, None)(tree.pos) - } - - def transformConstructorExportDef( - tree: ConstructorExportDef): ConstructorExportDef = { - val ConstructorExportDef(name, args, body) = tree - setupParamToIndex(args) - ConstructorExportDef(name, List(argumentsParamDef(tree.pos)), - transformStat(body))(tree.pos) - } - - private def setupParamToIndex(params: List[ParamDef]): Unit = - paramToIndex = params.map(_.name.name).zipWithIndex.toMap - - private def argumentsParamDef(implicit pos: Position): ParamDef = - ParamDef(Ident(ArgumentsName), AnyType, mutable = false, rest = true) - - private def argumentsRef(implicit pos: Position): VarRef = - VarRef(Ident(ArgumentsName))(AnyType) - - override def transform(tree: Tree, isStat: Boolean): Tree = tree match { - case VarRef(Ident(name, origName)) => - implicit val pos = tree.pos - paramToIndex.get(name).fold { - if (name == "arguments") argumentsRef - else tree - } { paramIndex => - JSBracketSelect(argumentsRef, IntLiteral(paramIndex)) - } - - case _ => - super.transform(tree, isStat) - } - } - - private object RewriteArgumentsTransformer { - private final val ArgumentsName = "$arguments" - } -} diff --git a/ir/src/main/scala/org/scalajs/core/ir/Tags.scala b/ir/src/main/scala/org/scalajs/core/ir/Tags.scala deleted file mode 100644 index d6e567651f..0000000000 --- a/ir/src/main/scala/org/scalajs/core/ir/Tags.scala +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.ir - -/** Serialization and hashing tags for trees and types */ -private[ir] object Tags { - - // Tags for Trees - - /** Use to denote optional trees. */ - final val TagEmptyTree = 1 - - final val TagVarDef = TagEmptyTree + 1 - final val TagParamDef = TagVarDef + 1 - - final val TagSkip = TagParamDef + 1 - final val TagBlock = TagSkip + 1 - final val TagLabeled = TagBlock + 1 - final val TagAssign = TagLabeled + 1 - final val TagReturn = TagAssign + 1 - final val TagIf = TagReturn + 1 - final val TagWhile = TagIf + 1 - final val TagDoWhile = TagWhile + 1 - - // TODO remove when we can break binary compat. - final val TagTry = TagDoWhile + 1 - - final val TagThrow = TagTry + 1 - final val TagContinue = TagThrow + 1 - final val TagMatch = TagContinue + 1 - final val TagDebugger = TagMatch + 1 - - final val TagNew = TagDebugger + 1 - final val TagLoadModule = TagNew + 1 - final val TagStoreModule = TagLoadModule + 1 - final val TagSelect = TagStoreModule + 1 - final val TagApply = TagSelect + 1 - final val TagApplyStatically = TagApply + 1 - final val TagApplyStatic = TagApplyStatically + 1 - final val TagUnaryOp = TagApplyStatic + 1 - final val TagBinaryOp = TagUnaryOp + 1 - final val TagNewArray = TagBinaryOp + 1 - final val TagArrayValue = TagNewArray + 1 - final val TagArrayLength = TagArrayValue + 1 - final val TagArraySelect = TagArrayLength + 1 - final val TagRecordValue = TagArraySelect + 1 - final val TagIsInstanceOf = TagRecordValue + 1 - final val TagAsInstanceOf = TagIsInstanceOf + 1 - final val TagUnbox = TagAsInstanceOf + 1 - final val TagGetClass = TagUnbox + 1 - final val TagCallHelper = TagGetClass + 1 - - final val TagJSNew = TagCallHelper + 1 - final val TagJSDotSelect = TagJSNew + 1 - final val TagJSBracketSelect = TagJSDotSelect + 1 - final val TagJSFunctionApply = TagJSBracketSelect + 1 - final val TagJSDotMethodApply = TagJSFunctionApply + 1 - final val TagJSBracketMethodApply = TagJSDotMethodApply + 1 - final val TagJSDelete = TagJSBracketMethodApply + 1 - final val TagJSUnaryOp = TagJSDelete + 1 - final val TagJSBinaryOp = TagJSUnaryOp + 1 - final val TagJSArrayConstr = TagJSBinaryOp + 1 - final val TagJSObjectConstr = TagJSArrayConstr + 1 - final val TagJSEnvInfo = TagJSObjectConstr + 1 - - final val TagUndefined = TagJSEnvInfo + 1 - final val TagUndefinedParam = TagUndefined + 1 // TODO Move this - final val TagNull = TagUndefinedParam + 1 - final val TagBooleanLiteral = TagNull + 1 - final val TagIntLiteral = TagBooleanLiteral + 1 - final val TagLongLiteral = TagIntLiteral + 1 - final val TagFloatLiteral = TagLongLiteral + 1 - final val TagDoubleLiteral = TagFloatLiteral + 1 - final val TagStringLiteral = TagDoubleLiteral + 1 - final val TagClassOf = TagStringLiteral + 1 - - final val TagVarRef = TagClassOf + 1 - final val TagThis = TagVarRef + 1 - final val TagClosure = TagThis + 1 - - final val TagClassDef = TagClosure + 1 - final val TagFieldDef = TagClassDef + 1 - final val TagMethodDef = TagFieldDef + 1 - final val TagPropertyDef = TagMethodDef + 1 - final val TagConstructorExportDef = TagPropertyDef + 1 - final val TagModuleExportDef = TagConstructorExportDef + 1 - - // TODO Reorganize these when we can break binary compatibility - final val TagJSSpread = TagModuleExportDef + 1 - final val TagJSLinkingInfo = TagJSSpread + 1 - final val TagStringLitFieldDef = TagJSLinkingInfo + 1 - final val TagJSSuperBracketSelect = TagStringLitFieldDef + 1 - final val TagJSSuperBracketCall = TagJSSuperBracketSelect + 1 - final val TagJSSuperConstructorCall = TagJSSuperBracketCall + 1 - final val TagLoadJSConstructor = TagJSSuperConstructorCall + 1 - final val TagLoadJSModule = TagLoadJSConstructor + 1 - final val TagJSClassExportDef = TagLoadJSModule + 1 - final val TagTryCatch = TagJSClassExportDef + 1 - final val TagTryFinally = TagTryCatch + 1 - final val TagTopLevelMethodExportDef = TagTryFinally + 1 - final val TagSelectStatic = TagTopLevelMethodExportDef + 1 - final val TagTopLevelFieldExportDef = TagSelectStatic + 1 - final val TagTopLevelModuleExportDef = TagTopLevelFieldExportDef + 1 - final val TagJSImportCall = TagTopLevelModuleExportDef + 1 - - // Tags for Types - - final val TagAnyType = 1 - final val TagNothingType = TagAnyType + 1 - final val TagUndefType = TagNothingType + 1 - final val TagBooleanType = TagUndefType + 1 - final val TagIntType = TagBooleanType + 1 - final val TagLongType = TagIntType + 1 - final val TagFloatType = TagLongType + 1 - final val TagDoubleType = TagFloatType + 1 - final val TagStringType = TagDoubleType + 1 - final val TagNullType = TagStringType + 1 - final val TagClassType = TagNullType + 1 - final val TagArrayType = TagClassType + 1 - final val TagRecordType = TagArrayType + 1 - final val TagNoType = TagRecordType + 1 - - // Tags for PropertyNames - - final val TagPropertyNameIdent = 1 - final val TagPropertyNameStringLiteral = TagPropertyNameIdent + 1 - final val TagPropertyNameComputedName = TagPropertyNameStringLiteral + 1 - - // Tags for JS native loading specs - - final val TagJSNativeLoadSpecNone = 0 - final val TagJSNativeLoadSpecGlobal = TagJSNativeLoadSpecNone + 1 - final val TagJSNativeLoadSpecImport = TagJSNativeLoadSpecGlobal + 1 - final val TagJSNativeLoadSpecImportWithGlobalFallback = TagJSNativeLoadSpecImport + 1 - -} diff --git a/ir/src/main/scala/org/scalajs/core/ir/Transformers.scala b/ir/src/main/scala/org/scalajs/core/ir/Transformers.scala deleted file mode 100644 index 2b513ccfa4..0000000000 --- a/ir/src/main/scala/org/scalajs/core/ir/Transformers.scala +++ /dev/null @@ -1,261 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.ir - -import Trees._ - -object Transformers { - - abstract class Transformer { - final def transformStat(tree: Tree): Tree = - transform(tree, isStat = true) - - final def transformExpr(tree: Tree): Tree = - transform(tree, isStat = false) - - def transform(tree: Tree, isStat: Boolean): Tree = { - implicit val pos = tree.pos - - tree match { - // Definitions - - case VarDef(ident, vtpe, mutable, rhs) => - VarDef(ident, vtpe, mutable, transformExpr(rhs)) - - // Control flow constructs - - case Block(stats :+ expr) => - Block(stats.map(transformStat) :+ transform(expr, isStat)) - - case Labeled(label, tpe, body) => - Labeled(label, tpe, transform(body, isStat)) - - case Assign(lhs, rhs) => - Assign(transformExpr(lhs), transformExpr(rhs)) - - case Return(expr, label) => - Return(transformExpr(expr), label) - - case If(cond, thenp, elsep) => - If(transformExpr(cond), transform(thenp, isStat), - transform(elsep, isStat))(tree.tpe) - - case While(cond, body, label) => - While(transformExpr(cond), transformStat(body), label) - - case DoWhile(body, cond, label) => - DoWhile(transformStat(body), transformExpr(cond), label) - - case TryCatch(block, errVar, handler) => - TryCatch(transform(block, isStat), errVar, - transform(handler, isStat))(tree.tpe) - - case TryFinally(block, finalizer) => - TryFinally(transform(block, isStat), transformStat(finalizer)) - - case Throw(expr) => - Throw(transformExpr(expr)) - - case Match(selector, cases, default) => - Match(transformExpr(selector), - cases map (c => (c._1, transform(c._2, isStat))), - transform(default, isStat))(tree.tpe) - - // Scala expressions - - case New(cls, ctor, args) => - New(cls, ctor, args map transformExpr) - - case StoreModule(cls, value) => - StoreModule(cls, transformExpr(value)) - - case Select(qualifier, item) => - Select(transformExpr(qualifier), item)(tree.tpe) - - case Apply(receiver, method, args) => - Apply(transformExpr(receiver), method, - args map transformExpr)(tree.tpe) - - case ApplyStatically(receiver, cls, method, args) => - ApplyStatically(transformExpr(receiver), cls, method, - args map transformExpr)(tree.tpe) - - case ApplyStatic(cls, method, args) => - ApplyStatic(cls, method, args map transformExpr)(tree.tpe) - - case UnaryOp(op, lhs) => - UnaryOp(op, transformExpr(lhs)) - - case BinaryOp(op, lhs, rhs) => - BinaryOp(op, transformExpr(lhs), transformExpr(rhs)) - - case NewArray(tpe, lengths) => - NewArray(tpe, lengths map transformExpr) - - case ArrayValue(tpe, elems) => - ArrayValue(tpe, elems map transformExpr) - - case ArrayLength(array) => - ArrayLength(transformExpr(array)) - - case ArraySelect(array, index) => - ArraySelect(transformExpr(array), transformExpr(index))(tree.tpe) - - case RecordValue(tpe, elems) => - RecordValue(tpe, elems map transformExpr) - - case IsInstanceOf(expr, cls) => - IsInstanceOf(transformExpr(expr), cls) - - case AsInstanceOf(expr, cls) => - AsInstanceOf(transformExpr(expr), cls) - - case Unbox(expr, charCode) => - Unbox(transformExpr(expr), charCode) - - case GetClass(expr) => - GetClass(transformExpr(expr)) - - case CallHelper(helper, args) => - CallHelper(helper, args map transformExpr)(tree.tpe) - - // JavaScript expressions - - case JSNew(ctor, args) => - JSNew(transformExpr(ctor), args map transformExpr) - - case JSDotSelect(qualifier, item) => - JSDotSelect(transformExpr(qualifier), item) - - case JSBracketSelect(qualifier, item) => - JSBracketSelect(transformExpr(qualifier), transformExpr(item)) - - case JSFunctionApply(fun, args) => - JSFunctionApply(transformExpr(fun), args map transformExpr) - - case JSDotMethodApply(receiver, method, args) => - JSDotMethodApply(transformExpr(receiver), method, - args map transformExpr) - - case JSBracketMethodApply(receiver, method, args) => - JSBracketMethodApply(transformExpr(receiver), transformExpr(method), - args map transformExpr) - - case JSSuperBracketSelect(cls, qualifier, item) => - JSSuperBracketSelect(cls, transformExpr(qualifier), - transformExpr(item)) - - case JSSuperBracketCall(cls, receiver, method, args) => - JSSuperBracketCall(cls, transformExpr(receiver), - transformExpr(method), args map transformExpr) - - case JSSuperConstructorCall(args) => - JSSuperConstructorCall(args map transformExpr) - - case JSImportCall(arg) => - JSImportCall(transformExpr(arg)) - - case JSSpread(items) => - JSSpread(transformExpr(items)) - - case JSDelete(prop) => - JSDelete(transformExpr(prop)) - - case JSUnaryOp(op, lhs) => - JSUnaryOp(op, transformExpr(lhs)) - - case JSBinaryOp(op, lhs, rhs) => - JSBinaryOp(op, transformExpr(lhs), transformExpr(rhs)) - - case JSArrayConstr(items) => - JSArrayConstr(items map transformExpr) - - case JSObjectConstr(fields) => - JSObjectConstr(fields map { - case (name, value) => - val newName = name match { - case ComputedName(tree, logicalName) => - ComputedName(transformExpr(tree), logicalName) - case _ => - name - } - (newName, transformExpr(value)) - }) - - // Atomic expressions - - case Closure(captureParams, params, body, captureValues) => - Closure(captureParams, params, transformExpr(body), - captureValues.map(transformExpr)) - - // Trees that need not be transformed - - case _:Skip | _:Continue | _:Debugger | _:LoadModule | _:SelectStatic | - _:LoadJSConstructor | _:LoadJSModule | _:JSLinkingInfo | - _:Literal | _:UndefinedParam | _:VarRef | _:This => - tree - - case _ => - throw new IllegalArgumentException( - s"Invalid tree in transform() of class ${tree.getClass}") - } - } - } - - abstract class ClassTransformer extends Transformer { - def transformClassDef(tree: ClassDef): ClassDef = { - val ClassDef(name, kind, superClass, parents, jsName, defs) = tree - ClassDef(name, kind, superClass, parents, jsName, defs.map(transformDef))( - tree.optimizerHints)(tree.pos) - } - - def transformDef(tree: Tree): Tree = { - implicit val pos = tree.pos - - tree match { - case FieldDef(_, _, _, _) => - tree - - case tree: MethodDef => - val MethodDef(static, name, args, resultType, body) = tree - MethodDef(static, name, args, resultType, body.map(transformStat))( - tree.optimizerHints, None) - - case PropertyDef(static, name, getterBody, setterArgAndBody) => - PropertyDef( - static, - name, - getterBody.map(transformStat), - setterArgAndBody map { case (arg, body) => - (arg, transformStat(body)) - }) - - case ConstructorExportDef(fullName, args, body) => - ConstructorExportDef(fullName, args, transformStat(body)) - - case _:JSClassExportDef | _:ModuleExportDef | - _:TopLevelModuleExportDef | _:TopLevelFieldExportDef => - tree - - case TopLevelMethodExportDef(methodDef) => - TopLevelMethodExportDef( - transformDef(methodDef).asInstanceOf[MethodDef]) - - case _ => - throw new IllegalArgumentException( - s"Invalid tree in transformDef() of class ${tree.getClass}") - } - } - } - -} diff --git a/ir/src/main/scala/org/scalajs/core/ir/Traversers.scala b/ir/src/main/scala/org/scalajs/core/ir/Traversers.scala deleted file mode 100644 index b99e94ca4b..0000000000 --- a/ir/src/main/scala/org/scalajs/core/ir/Traversers.scala +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.ir - -import Trees._ - -object Traversers { - - class Traverser { - def traverse(tree: Tree): Unit = tree match { - // Definitions - - case VarDef(ident, vtpe, mutable, rhs) => - traverse(rhs) - - // Control flow constructs - - case Block(stats) => - stats foreach traverse - - case Labeled(label, tpe, body) => - traverse(body) - - case Assign(lhs, rhs) => - traverse(lhs) - traverse(rhs) - - case Return(expr, label) => - traverse(expr) - - case If(cond, thenp, elsep) => - traverse(cond) - traverse(thenp) - traverse(elsep) - - case While(cond, body, label) => - traverse(cond) - traverse(body) - - case DoWhile(body, cond, label) => - traverse(body) - traverse(cond) - - case TryCatch(block, errVar, handler) => - traverse(block) - traverse(handler) - - case TryFinally(block, finalizer) => - traverse(block) - traverse(finalizer) - - case Throw(expr) => - traverse(expr) - - case Match(selector, cases, default) => - traverse(selector) - cases foreach (c => (c._1 map traverse, traverse(c._2))) - traverse(default) - - // Scala expressions - - case New(cls, ctor, args) => - args foreach traverse - - case StoreModule(cls, value) => - traverse(value) - - case Select(qualifier, item) => - traverse(qualifier) - - case Apply(receiver, method, args) => - traverse(receiver) - args foreach traverse - - case ApplyStatically(receiver, cls, method, args) => - traverse(receiver) - args foreach traverse - - case ApplyStatic(cls, method, args) => - args foreach traverse - - case UnaryOp(op, lhs) => - traverse(lhs) - - case BinaryOp(op, lhs, rhs) => - traverse(lhs) - traverse(rhs) - - case NewArray(tpe, lengths) => - lengths foreach traverse - - case ArrayValue(tpe, elems) => - elems foreach traverse - - case ArrayLength(array) => - traverse(array) - - case ArraySelect(array, index) => - traverse(array) - traverse(index) - - case RecordValue(tpe, elems) => - elems foreach traverse - - case IsInstanceOf(expr, cls) => - traverse(expr) - - case AsInstanceOf(expr, cls) => - traverse(expr) - - case Unbox(expr, charCode) => - traverse(expr) - - case GetClass(expr) => - traverse(expr) - - case CallHelper(helper, args) => - args foreach traverse - - // JavaScript expressions - - case JSNew(ctor, args) => - traverse(ctor) - args foreach traverse - - case JSDotSelect(qualifier, item) => - traverse(qualifier) - - case JSBracketSelect(qualifier, item) => - traverse(qualifier) - traverse(item) - - case JSFunctionApply(fun, args) => - traverse(fun) - args foreach traverse - - case JSDotMethodApply(receiver, method, args) => - traverse(receiver) - args foreach traverse - - case JSBracketMethodApply(receiver, method, args) => - traverse(receiver) - traverse(method) - args foreach traverse - - case JSSuperBracketSelect(cls, qualifier, item) => - traverse(qualifier) - traverse(item) - - case JSSuperBracketCall(cls, receiver, method, args) => - traverse(receiver) - traverse(method) - args foreach traverse - - case JSSuperConstructorCall(args) => - args foreach traverse - - case JSImportCall(arg) => - traverse(arg) - - case JSSpread(items) => - traverse(items) - - case JSDelete(prop) => - traverse(prop) - - case JSUnaryOp(op, lhs) => - traverse(lhs) - - case JSBinaryOp(op, lhs, rhs) => - traverse(lhs) - traverse(rhs) - - case JSArrayConstr(items) => - items foreach traverse - - case JSObjectConstr(fields) => - for ((key, value) <- fields) { - key match { - case ComputedName(tree, _) => - traverse(tree) - case _ => - } - traverse(value) - } - - // Atomic expressions - - case Closure(captureParams, params, body, captureValues) => - traverse(body) - captureValues.foreach(traverse) - - // Classes - - case ClassDef(name, kind, superClass, parents, jsName, defs) => - defs foreach traverse - - case MethodDef(static, name, args, resultType, body) => - body.foreach(traverse) - - case PropertyDef(static, name, getterBody, setterArgAndBody) => - getterBody.foreach(traverse) - setterArgAndBody foreach { case (_, body) => - traverse(body) - } - - case ConstructorExportDef(fullName, args, body) => - traverse(body) - - case TopLevelMethodExportDef(methodDef) => - traverse(methodDef) - - // Trees that need not be traversed - - case _:Skip | _:Continue | _:Debugger | _:LoadModule | _:SelectStatic | - _:LoadJSConstructor | _:LoadJSModule | _:JSLinkingInfo | _:Literal | - _:UndefinedParam | _:VarRef | _:This | _:FieldDef | - _:JSClassExportDef | _:ModuleExportDef | _:TopLevelModuleExportDef | - _:TopLevelFieldExportDef => - - case _ => - throw new IllegalArgumentException( - s"Invalid tree in traverse() of class ${tree.getClass}") - } - } - -} diff --git a/ir/src/main/scala/org/scalajs/core/ir/Trees.scala b/ir/src/main/scala/org/scalajs/core/ir/Trees.scala deleted file mode 100644 index f1537a3a2c..0000000000 --- a/ir/src/main/scala/org/scalajs/core/ir/Trees.scala +++ /dev/null @@ -1,981 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.ir - -import scala.annotation.switch - -import Position.NoPosition -import Types._ - -object Trees { - /** AST node of the IR. */ - abstract sealed class Tree { - val pos: Position - val tpe: Type - - def show: String = { - val writer = new java.io.StringWriter - val printer = new Printers.IRTreePrinter(writer) - printer.print(this) - writer.toString() - } - } - - // Identifiers and properties - - sealed trait PropertyName { - /** Encoded name of this PropertyName within its owner's scope. - * - * For [[ComputedName]]s, the value of `encodedName` cannot be relied on - * beyond equality tests, and the fact that it starts with `"__computed_"`. - */ - def encodedName: String - - def pos: Position - } - - case class Ident(name: String, originalName: Option[String])( - implicit val pos: Position) extends PropertyName { - requireValidIdent(name) - def encodedName: String = name - } - - object Ident { - def apply(name: String)(implicit pos: Position): Ident = - new Ident(name, Some(name)) - } - - final def isValidIdentifier(name: String): Boolean = { - val c = name.head - (c == '$' || c == '_' || c.isUnicodeIdentifierStart) && - name.tail.forall(c => (c == '$') || c.isUnicodeIdentifierPart) && - !isKeyword(name) - } - - @inline final def requireValidIdent(name: String): Unit = { - require(isValidIdentifier(name), s"${name} is not a valid identifier") - } - - final val isKeyword: Set[String] = Set( - // Value keywords - "true", "false", "null", "undefined", - - // Current JavaScript keywords - "break", "case", "catch", "continue", "debugger", "default", "delete", - "do", "else", "finally", "for", "function", "if", "in", "instanceof", - "new", "return", "switch", "this", "throw", "try", "typeof", "var", - "void", "while", "with", - - // Future reserved keywords - "class", "const", "enum", "export", "extends", "import", "super", - - // Future reserved keywords in Strict mode - "implements", "interface", "let", "package", "private", "protected", - "public", "static", "yield", - - // Other reserved keywords found on the Web but not in the spec - "abstract", "boolean", "byte", "char", "double", "final", "float", - "goto", "int", "long", "native", "short", "synchronized", "throws", - "transient", "volatile" - ) - - case class ComputedName(tree: Tree, logicalName: String) extends PropertyName { - requireValidIdent(logicalName) - def pos: Position = tree.pos - override def encodedName: String = "__computed_" + logicalName - } - - // Definitions - - case class VarDef(name: Ident, vtpe: Type, mutable: Boolean, rhs: Tree)( - implicit val pos: Position) extends Tree { - val tpe = NoType // cannot be in expression position - - def ref(implicit pos: Position): VarRef = VarRef(name)(vtpe) - } - - case class ParamDef(name: Ident, ptpe: Type, mutable: Boolean, rest: Boolean)( - implicit val pos: Position) extends Tree { - val tpe = NoType - - def ref(implicit pos: Position): VarRef = VarRef(name)(ptpe) - } - - // Control flow constructs - - case class Skip()(implicit val pos: Position) extends Tree { - val tpe = NoType // cannot be in expression position - } - - class Block private (val stats: List[Tree])( - implicit val pos: Position) extends Tree { - val tpe = stats.last.tpe - - override def toString(): String = - stats.mkString("Block(", ",", ")") - } - - object Block { - def apply(stats: List[Tree])(implicit pos: Position): Tree = { - val flattenedStats = stats flatMap { - case Skip() => Nil - case Block(subStats) => subStats - case other => other :: Nil - } - flattenedStats match { - case Nil => Skip() - case only :: Nil => only - case _ => new Block(flattenedStats) - } - } - - def apply(stats: Tree*)(implicit pos: Position): Tree = - apply(stats.toList) - - def unapply(block: Block): Some[List[Tree]] = Some(block.stats) - } - - case class Labeled(label: Ident, tpe: Type, body: Tree)( - implicit val pos: Position) extends Tree - - case class Assign(lhs: Tree, rhs: Tree)( - implicit val pos: Position) extends Tree { - require(lhs match { - case _:VarRef | _:Select | _:SelectStatic | _:ArraySelect | - _:JSDotSelect | _:JSBracketSelect | _:JSSuperBracketSelect => true - case _ => false - }, s"Invalid lhs for Assign: $lhs") - - val tpe = NoType // cannot be in expression position - } - - case class Return(expr: Tree, label: Option[Ident] = None)( - implicit val pos: Position) extends Tree { - val tpe = NothingType - } - - case class If(cond: Tree, thenp: Tree, elsep: Tree)(val tpe: Type)( - implicit val pos: Position) extends Tree - - case class While(cond: Tree, body: Tree, label: Option[Ident] = None)( - implicit val pos: Position) extends Tree { - // cannot be in expression position, unless it is infinite - val tpe = cond match { - case BooleanLiteral(true) => NothingType - case _ => NoType - } - } - - case class DoWhile(body: Tree, cond: Tree, label: Option[Ident] = None)( - implicit val pos: Position) extends Tree { - val tpe = NoType // cannot be in expression position - } - - case class TryCatch(block: Tree, errVar: Ident, handler: Tree)( - val tpe: Type)(implicit val pos: Position) extends Tree - - case class TryFinally(block: Tree, finalizer: Tree)( - implicit val pos: Position) extends Tree { - val tpe = block.tpe - } - - case class Throw(expr: Tree)(implicit val pos: Position) extends Tree { - val tpe = NothingType - } - - case class Continue(label: Option[Ident] = None)( - implicit val pos: Position) extends Tree { - val tpe = NothingType - } - - /** A break-free switch (without fallthrough behavior). - * Unlike a JavaScript switch, it can be used in expression position. - * It supports alternatives explicitly (hence the List[Tree] in cases), - * whereas in a switch one would use the fallthrough behavior to - * implement alternatives. - * (This is not a pattern matching construct like in Scala.) - */ - case class Match(selector: Tree, cases: List[(List[Literal], Tree)], - default: Tree)(val tpe: Type)(implicit val pos: Position) extends Tree - - case class Debugger()(implicit val pos: Position) extends Tree { - val tpe = NoType // cannot be in expression position - } - - // Scala expressions - - case class New(cls: ClassType, ctor: Ident, args: List[Tree])( - implicit val pos: Position) extends Tree { - val tpe = cls - } - - case class LoadModule(cls: ClassType)( - implicit val pos: Position) extends Tree { - val tpe = cls - } - - case class StoreModule(cls: ClassType, value: Tree)( - implicit val pos: Position) extends Tree { - val tpe = NoType // cannot be in expression position - } - - case class Select(qualifier: Tree, item: Ident)(val tpe: Type)( - implicit val pos: Position) extends Tree - - case class SelectStatic(cls: ClassType, item: Ident)(val tpe: Type)( - implicit val pos: Position) extends Tree - - /** Apply an instance method with dynamic dispatch (the default). */ - case class Apply(receiver: Tree, method: Ident, args: List[Tree])( - val tpe: Type)(implicit val pos: Position) extends Tree - - /** Apply an instance method with static dispatch (e.g., super calls). */ - case class ApplyStatically(receiver: Tree, cls: ClassType, method: Ident, - args: List[Tree])(val tpe: Type)(implicit val pos: Position) extends Tree - - /** Apply a static method. */ - case class ApplyStatic(cls: ClassType, method: Ident, args: List[Tree])( - val tpe: Type)(implicit val pos: Position) extends Tree - - /** Unary operation (always preserves pureness). */ - case class UnaryOp(op: UnaryOp.Code, lhs: Tree)( - implicit val pos: Position) extends Tree { - - val tpe = UnaryOp.resultTypeOf(op) - } - - object UnaryOp { - /** Codes are raw Ints to be able to write switch matches on them. */ - type Code = Int - - final val Boolean_! = 1 - - final val IntToLong = 2 - final val LongToInt = 3 - final val LongToDouble = 4 - final val DoubleToInt = 5 - final val DoubleToFloat = 6 - final val DoubleToLong = 7 - - def resultTypeOf(op: Code): Type = (op: @switch) match { - case LongToInt | DoubleToInt => IntType - case IntToLong | DoubleToLong => LongType - case DoubleToFloat => FloatType - case LongToDouble => DoubleType - case Boolean_! => BooleanType - } - } - - /** Binary operation (always preserves pureness). */ - case class BinaryOp(op: BinaryOp.Code, lhs: Tree, rhs: Tree)( - implicit val pos: Position) extends Tree { - - val tpe = BinaryOp.resultTypeOf(op) - } - - object BinaryOp { - /** Codes are raw Ints to be able to write switch matches on them. */ - type Code = Int - - final val === = 1 - final val !== = 2 - - final val String_+ = 3 - - final val Int_+ = 4 - final val Int_- = 5 - final val Int_* = 6 - final val Int_/ = 7 - final val Int_% = 8 - - final val Int_| = 9 - final val Int_& = 10 - final val Int_^ = 11 - final val Int_<< = 12 - final val Int_>>> = 13 - final val Int_>> = 14 - - final val Float_+ = 15 - final val Float_- = 16 - final val Float_* = 17 - final val Float_/ = 18 - final val Float_% = 19 - - final val Double_+ = 20 - final val Double_- = 21 - final val Double_* = 22 - final val Double_/ = 23 - final val Double_% = 24 - - final val Num_== = 25 - final val Num_!= = 26 - final val Num_< = 27 - final val Num_<= = 28 - final val Num_> = 29 - final val Num_>= = 30 - - final val Long_+ = 31 - final val Long_- = 32 - final val Long_* = 33 - final val Long_/ = 34 - final val Long_% = 35 - - final val Long_| = 36 - final val Long_& = 37 - final val Long_^ = 38 - final val Long_<< = 39 - final val Long_>>> = 40 - final val Long_>> = 41 - - final val Long_== = 42 - final val Long_!= = 43 - final val Long_< = 44 - final val Long_<= = 45 - final val Long_> = 46 - final val Long_>= = 47 - - final val Boolean_== = 48 - final val Boolean_!= = 49 - final val Boolean_| = 50 - final val Boolean_& = 51 - - def resultTypeOf(op: Code): Type = (op: @switch) match { - case === | !== | - Num_== | Num_!= | Num_< | Num_<= | Num_> | Num_>= | - Long_== | Long_!= | Long_< | Long_<= | Long_> | Long_>= | - Boolean_== | Boolean_!= | Boolean_| | Boolean_& => - BooleanType - case String_+ => - StringType - case Int_+ | Int_- | Int_* | Int_/ | Int_% | - Int_| | Int_& | Int_^ | Int_<< | Int_>>> | Int_>> => - IntType - case Float_+ | Float_- | Float_* | Float_/ | Float_% => - FloatType - case Double_+ | Double_- | Double_* | Double_/ | Double_% => - DoubleType - case Long_+ | Long_- | Long_* | Long_/ | Long_% | - Long_| | Long_& | Long_^ | Long_<< | Long_>>> | Long_>> => - LongType - } - } - - case class NewArray(tpe: ArrayType, lengths: List[Tree])( - implicit val pos: Position) extends Tree { - require(lengths.nonEmpty && lengths.size <= tpe.dimensions) - } - - case class ArrayValue(tpe: ArrayType, elems: List[Tree])( - implicit val pos: Position) extends Tree - - case class ArrayLength(array: Tree)(implicit val pos: Position) extends Tree { - val tpe = IntType - } - - case class ArraySelect(array: Tree, index: Tree)(val tpe: Type)( - implicit val pos: Position) extends Tree - - case class RecordValue(tpe: RecordType, elems: List[Tree])( - implicit val pos: Position) extends Tree - - case class IsInstanceOf(expr: Tree, cls: ReferenceType)( - implicit val pos: Position) extends Tree { - val tpe = BooleanType - } - - case class AsInstanceOf(expr: Tree, cls: ReferenceType)( - implicit val pos: Position) extends Tree { - val tpe = cls match { - case ClassType(Definitions.RuntimeNullClass) => NullType - case ClassType(Definitions.RuntimeNothingClass) => NothingType - case _ => cls.asInstanceOf[Type] - } - } - - case class Unbox(expr: Tree, charCode: Char)( - implicit val pos: Position) extends Tree { - val tpe = (charCode: @switch) match { - case 'Z' => BooleanType - case 'B' | 'S' | 'I' => IntType - case 'J' => LongType - case 'F' => FloatType - case 'D' => DoubleType - } - } - - case class GetClass(expr: Tree)(implicit val pos: Position) extends Tree { - val tpe = ClassType(Definitions.ClassClass) - } - - case class CallHelper(helper: String, args: List[Tree])(val tpe: Type)( - implicit val pos: Position) extends Tree - - object CallHelper { - def apply(helper: String, args: Tree*)(tpe: Type)( - implicit pos: Position): CallHelper = { - CallHelper(helper, args.toList)(tpe) - } - } - - // JavaScript expressions - - case class JSNew(ctor: Tree, args: List[Tree])( - implicit val pos: Position) extends Tree { - val tpe = AnyType - } - - case class JSDotSelect(qualifier: Tree, item: Ident)( - implicit val pos: Position) extends Tree { - val tpe = AnyType - } - - case class JSBracketSelect(qualifier: Tree, item: Tree)( - implicit val pos: Position) extends Tree { - val tpe = AnyType - } - - case class JSFunctionApply(fun: Tree, args: List[Tree])( - implicit val pos: Position) extends Tree { - val tpe = AnyType - } - - case class JSDotMethodApply(receiver: Tree, method: Ident, - args: List[Tree])(implicit val pos: Position) extends Tree { - val tpe = AnyType - } - - case class JSBracketMethodApply(receiver: Tree, method: Tree, - args: List[Tree])(implicit val pos: Position) extends Tree { - val tpe = AnyType - } - - /** Selects a property inherited from the parent class of `cls` on `receiver`. - * - * `cls` must be a Scala.js-defined JS class. - * - * Given the Scala.js-defined JS class - * - * {{{ - * class Foo extends Bar - * }}} - * - * The node - * - * {{{ - * JSSuperBrackerSelect(ClassType(Foo), qualifier, item) - * }}} - * - * which is printed as - * - * {{{ - * qualifier.Foo::super[item] - * }}} - * - * has the semantics of an ES6 super reference - * - * {{{ - * super[item] - * }}} - * - * as if it were in an instance method of `Foo` with `qualifier` as the - * `this` value. - */ - case class JSSuperBracketSelect(cls: ClassType, receiver: Tree, item: Tree)( - implicit val pos: Position) extends Tree { - val tpe = AnyType - } - - /** Calls a method inherited from the parent class of `cls` on `receiver`. - * - * `cls` must be a Scala.js-defined JS class. - * - * Given the Scala.js-defined JS class - * - * {{{ - * class Foo extends Bar - * }}} - * - * The node - * - * {{{ - * JSSuperBrackerCall(ClassType(Foo), receiver, method, args) - * }}} - * - * which is printed as - * - * {{{ - * receiver.Foo::super[method](...args) - * }}} - * - * has the following semantics: - * - * {{{ - * Bar.prototype[method].call(receiver, ...args) - * }}} - * - * If this happens to be located in an instance method of `Foo`, *and* - * `receiver` happens to be `This()`, this is equivalent to the ES6 - * statement - * - * {{{ - * super[method](...args) - * }}} - */ - case class JSSuperBracketCall(cls: ClassType, receiver: Tree, method: Tree, - args: List[Tree])(implicit val pos: Position) extends Tree { - val tpe = AnyType - } - - /** Super constructor call in the constructor of a Scala.js-defined JS class. - * - * Exactly one such node must appear in the constructor of a - * Scala.js-defined JS class, at the top-level (possibly as a direct child - * of a top-level `Block`). Any other use of this node is invalid. - * - * Statements before this node, as well as the `args`, cannot contain any - * `This()` node. Statements after this node can use `This()`. - * - * After the execution of this node, it is guaranteed that all fields - * declared in the current class have been created and initialized. Up to - * that point, accessing any field declared in this class (e.g., through an - * overridden method called from the super constructor) is undefined - * behavior. - * - * All in all, the shape of a constructor is therefore: - * - * {{{ - * { - * statementsNotUsingThis(); - * JSSuperConstructorCall(...argsNotUsingThis); - * statementsThatMayUseThis() - * } - * }}} - * - * which currently translates to something of the following shape: - * - * {{{ - * { - * statementsNotUsingThis(); - * super(...argsNotUsingThis); - * this.privateField1 = 0; - * this["publicField2"] = false; - * statementsThatMayUseThis() - * } - * }}} - */ - case class JSSuperConstructorCall(args: List[Tree])( - implicit val pos: Position) extends Tree { - val tpe = NoType - } - - /** JavaScript dynamic import of the form `import(arg)`. - * - * This form is its own node, rather than using something like - * {{{ - * JSFunctionApply(JSImport()) - * }}} - * because `import` is not a first-class term in JavaScript. - * `ImportCall` is a dedicated syntactic form that cannot be - * dissociated. - */ - case class JSImportCall(arg: Tree)(implicit val pos: Position) - extends Tree { - val tpe = AnyType // it is a JavaScript Promise - } - - /** Loads the constructor of a JS class (native or not). - * - * `cls` must represent a non-trait JS class (native or not). - * - * This is used typically to instantiate a JS class, and most importantly - * if it is a Scala.js-defined JS class. Given the class - * - * {{{ - * class Foo(x: Int) extends js.Object - * }}} - * - * The instantiation `new Foo(1)` would be represented as - * - * {{{ - * JSNew(LoadJSConstructor(ClassType("Foo")), List(IntLiteral(1))) - * }}} - * - * This node is also useful to encode `o.isInstanceOf[Foo]`: - * - * {{{ - * JSBinaryOp(instanceof, o, LoadJSConstructor(ClassType("Foo"))) - * }}} - * - * If `Foo` is Scala.js-defined, the presence of this node makes it - * instantiable, and therefore reachable. - */ - case class LoadJSConstructor(cls: ClassType)( - implicit val pos: Position) extends Tree { - val tpe = AnyType - } - - /** Like [[LoadModule]] but for a JS module class. */ - case class LoadJSModule(cls: ClassType)( - implicit val pos: Position) extends Tree { - val tpe = AnyType - } - - /** `...items`, the "spread" operator of ECMAScript 6. - * - * It is only valid in the `args`/`items` of a [[JSNew]], [[JSFunctionApply]], - * [[JSDotMethodApply]], [[JSBracketMethodApply]], or [[JSArrayConstr]]. - * - * @param items An Array whose items will be spread (not an arbitrary iterable) - */ - case class JSSpread(items: Tree)(implicit val pos: Position) extends Tree { - val tpe = NoType // there is no reasonable type for this tree - } - - case class JSDelete(prop: Tree)(implicit val pos: Position) extends Tree { - require(prop match { - case _:JSDotSelect | _:JSBracketSelect => true - case _ => false - }, s"Invalid prop for JSDelete: $prop") - - val tpe = NoType // cannot be in expression position - } - - /** Unary operation (always preserves pureness). - * - * Operations which do not preserve pureness are not allowed in this tree. - * These are notably ++ and -- - */ - case class JSUnaryOp(op: JSUnaryOp.Code, lhs: Tree)( - implicit val pos: Position) extends Tree { - val tpe = AnyType - } - - object JSUnaryOp { - /** Codes are raw Ints to be able to write switch matches on them. */ - type Code = Int - - final val + = 1 - final val - = 2 - final val ~ = 3 - final val ! = 4 - - final val typeof = 5 - } - - /** Binary operation (always preserves pureness). - * - * Operations which do not preserve pureness are not allowed in this tree. - * These are notably +=, -=, *=, /= and %= - */ - case class JSBinaryOp(op: JSBinaryOp.Code, lhs: Tree, rhs: Tree)( - implicit val pos: Position) extends Tree { - val tpe = AnyType - } - - object JSBinaryOp { - /** Codes are raw Ints to be able to write switch matches on them. */ - type Code = Int - - final val === = 1 - final val !== = 2 - - final val + = 3 - final val - = 4 - final val * = 5 - final val / = 6 - final val % = 7 - - final val | = 8 - final val & = 9 - final val ^ = 10 - final val << = 11 - final val >> = 12 - final val >>> = 13 - - final val < = 14 - final val <= = 15 - final val > = 16 - final val >= = 17 - - final val && = 18 - final val || = 19 - - final val in = 20 - final val instanceof = 21 - } - - case class JSArrayConstr(items: List[Tree])( - implicit val pos: Position) extends Tree { - val tpe = AnyType - } - - case class JSObjectConstr(fields: List[(PropertyName, Tree)])( - implicit val pos: Position) extends Tree { - val tpe = AnyType - } - - case class JSLinkingInfo()(implicit val pos: Position) extends Tree { - val tpe = AnyType - } - - // Literals - - /** Marker for literals. Literals are always pure. */ - sealed trait Literal extends Tree - - case class Undefined()(implicit val pos: Position) extends Literal { - val tpe = UndefType - } - - case class Null()(implicit val pos: Position) extends Literal { - val tpe = NullType - } - - case class BooleanLiteral(value: Boolean)( - implicit val pos: Position) extends Literal { - val tpe = BooleanType - } - - case class IntLiteral(value: Int)( - implicit val pos: Position) extends Literal { - val tpe = IntType - } - - case class LongLiteral(value: Long)( - implicit val pos: Position) extends Literal { - val tpe = LongType - } - - case class FloatLiteral(value: Float)( - implicit val pos: Position) extends Literal { - val tpe = FloatType - } - - case class DoubleLiteral(value: Double)( - implicit val pos: Position) extends Literal { - val tpe = DoubleType - } - - case class StringLiteral(value: String)( - implicit val pos: Position) extends Literal with PropertyName { - val tpe = StringType - override def encodedName: String = value - } - - case class ClassOf(cls: ReferenceType)( - implicit val pos: Position) extends Literal { - val tpe = ClassType(Definitions.ClassClass) - } - - // Specials - - case class UndefinedParam()(val tpe: Type)( - implicit val pos: Position) extends Tree - - // Atomic expressions - - case class VarRef(ident: Ident)(val tpe: Type)( - implicit val pos: Position) extends Tree - - case class This()(val tpe: Type)(implicit val pos: Position) extends Tree - - /** Closure with explicit captures. - * The n captures map to the n first formal arguments. - */ - case class Closure(captureParams: List[ParamDef], params: List[ParamDef], - body: Tree, captureValues: List[Tree])( - implicit val pos: Position) extends Tree { - val tpe = AnyType - } - - // Classes - - case class ClassDef(name: Ident, kind: ClassKind, superClass: Option[Ident], - interfaces: List[Ident], jsNativeLoadSpec: Option[JSNativeLoadSpec], - defs: List[Tree])( - val optimizerHints: OptimizerHints)( - implicit val pos: Position) extends Tree { - val tpe = NoType - } - - case class FieldDef(static: Boolean, name: PropertyName, ftpe: Type, - mutable: Boolean)( - implicit val pos: Position) extends Tree { - val tpe = NoType - } - - case class MethodDef(static: Boolean, name: PropertyName, - args: List[ParamDef], resultType: Type, body: Option[Tree])( - val optimizerHints: OptimizerHints, val hash: Option[TreeHash])( - implicit val pos: Position) extends Tree { - val tpe = NoType - } - - case class PropertyDef(static: Boolean, name: PropertyName, - getterBody: Option[Tree], setterArgAndBody: Option[(ParamDef, Tree)])( - implicit val pos: Position) extends Tree { - val tpe = NoType - } - - case class ConstructorExportDef(name: String, args: List[ParamDef], - body: Tree)(implicit val pos: Position) extends Tree { - val tpe = NoType - } - - case class JSClassExportDef(fullName: String)( - implicit val pos: Position) extends Tree { - val tpe = NoType - } - - /** Traditional `@JSExport` for top-level objects, as a 0-arg function. - * - * This exports a module as a 0-arg function that returns the module - * instance. It is initialized lazily in that case. - * - * This alternative should eventually disappear. - */ - case class ModuleExportDef(fullName: String)( - implicit val pos: Position) extends Tree { - val tpe = NoType - } - - /** New-style `@JSExportTopLevel` for top-level objects, directly as the - * object. - * - * This exports a module directly as a variable holding the module instance. - * The instance is initialized during ES module instantiation. - */ - case class TopLevelModuleExportDef(fullName: String)( - implicit val pos: Position) extends Tree { - val tpe = NoType - } - - case class TopLevelMethodExportDef(methodDef: MethodDef)( - implicit val pos: Position) extends Tree { - val tpe = NoType - } - - case class TopLevelFieldExportDef(fullName: String, field: Ident)( - implicit val pos: Position) extends Tree { - val tpe = NoType - } - - final class OptimizerHints(val bits: Int) extends AnyVal { - import OptimizerHints._ - - def inline: Boolean = (bits & InlineMask) != 0 - def noinline: Boolean = (bits & NoinlineMask) != 0 - - def withInline(value: Boolean): OptimizerHints = - if (value) new OptimizerHints(bits | InlineMask) - else new OptimizerHints(bits & ~InlineMask) - - def withNoinline(value: Boolean): OptimizerHints = - if (value) new OptimizerHints(bits | NoinlineMask) - else new OptimizerHints(bits & ~NoinlineMask) - - override def toString(): String = - s"OptimizerHints($bits)" - } - - object OptimizerHints { - final val InlineShift = 0 - final val InlineMask = 1 << InlineShift - - final val NoinlineShift = 1 - final val NoinlineMask = 1 << NoinlineShift - - final val empty: OptimizerHints = - new OptimizerHints(0) - } - - /** Loading specification for a native JS class or object. */ - sealed abstract class JSNativeLoadSpec - - object JSNativeLoadSpec { - - /** Load from the global scope. - * - * The `path` is a series of nested property names starting from the - * global object. - * - * The path can be empty, in which case this denotes the global object - * itself. - * - * Any element in the path is a property selection from there. A global - * scope loading spec with one path element is therefore a global variable. - * - * Examples: - * {{{ - * // - * Global(None, Nil) - * - * // .Date - * Global(None, List("Date")) - * - * // .cp.Vect - * Global(None, List("cp", "Vect")) - * }}} - */ - final case class Global(path: List[String]) extends JSNativeLoadSpec - - /** Load from a module import. - * - * The `module` is the ES module identifier. The `path` is a series of - * nested property names starting from the module object. - * - * The path can be empty, in which case the specification denotes the - * namespace import, i.e., import a special object whose fields are all - * the exports of the module. - * - * Any element in the path is a property selection from there. A module - * import info with one path element is importing that particular value - * from the module. - * - * Examples: - * {{{ - * // import { Bar as x } from 'foo' - * Import("foo", List("Bar")) - * - * // import { Bar as y } from 'foo' - * // y.Baz - * Import("foo", List("Bar", "Baz")) - * - * // import * as x from 'foo' (namespace import) - * Import("foo", Nil) - * - * // import x from 'foo' (default import) - * Import("foo", List("default")) - * }}} - */ - final case class Import(module: String, path: List[String]) - extends JSNativeLoadSpec - - /** Like [[Import]], but with a [[Global]] fallback when linking without - * modules. - * - * When linking with a module kind that supports modules, the `importSpec` - * is used. When modules are not supported, use the fallback `globalSpec`. - */ - final case class ImportWithGlobalFallback(importSpec: Import, - globalSpec: Global) - extends JSNativeLoadSpec - - } - - /** A hash of a tree (usually a MethodDef). Contains two SHA-1 hashes */ - final class TreeHash(val treeHash: Array[Byte], val posHash: Array[Byte]) { - assert(treeHash.length == 20) - assert(posHash.length == 20) - } -} diff --git a/ir/src/main/scala/org/scalajs/core/ir/Types.scala b/ir/src/main/scala/org/scalajs/core/ir/Types.scala deleted file mode 100644 index 1b9024eeb3..0000000000 --- a/ir/src/main/scala/org/scalajs/core/ir/Types.scala +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.ir - -import scala.annotation.tailrec - -import Trees._ - -object Types { - - /** Type of an term (expression or statement) in the IR. - * - * There is a many-to-one relationship from [[ReferenceType]]s to types, - * because: - * - * - `scala.Byte`, `scala.Short` and `scala.Int` collapse to [[IntType]] - * - `java.lang.Object` and raw JS types all collapse to [[AnyType]] - * - * In fact, there are two `Type`s that do not have any real equivalent in - * reference types: [[StringType]] and [[UndefType]], as they refer to the - * non-null variants of `java.lang.String` and `scala.runtime.BoxedUnit`, - * respectively. - */ - abstract sealed class Type { - def show(): String = { - val writer = new java.io.StringWriter - val printer = new Printers.IRTreePrinter(writer) - printer.print(this) - writer.toString() - } - } - - /** Any type (the top type of this type system). - * A variable of this type can contain any value, including `undefined` - * and `null` and any raw JS value. This type supports a very limited set - * of Scala operations, the ones common to all values. Basically only - * reference equality tests and instance tests. It also supports all - * JavaScript operations, since all Scala objects are also genuine - * JavaScript objects. - * The type java.lang.Object in the back-end maps to [[AnyType]] because it - * can hold raw JS values (not only instances of Scala.js classes). - */ - case object AnyType extends Type - - // Can't link to Nothing - #1969 - /** Nothing type (the bottom type of this type system). - * Expressions from which one can never come back are typed as `Nothing`. - * For example, `throw` and `return`. - */ - case object NothingType extends Type - - /** The type of `undefined`. */ - case object UndefType extends Type - - /** Boolean type. - * It does not accept `null` nor `undefined`. - */ - case object BooleanType extends Type - - /** 32-bit signed integer type. - * It does not accept `null` nor `undefined`. - */ - case object IntType extends Type - - /** 64-bit signed integer type. - * It does not accept `null` nor `undefined`. - */ - case object LongType extends Type - - /** Float type (32-bit). - * It does not accept `null` nor `undefined`. - */ - case object FloatType extends Type - - /** Double type (64-bit). - * It does not accept `null` nor `undefined`. - */ - case object DoubleType extends Type - - /** String type. - * It does not accept `null` nor `undefined`. - */ - case object StringType extends Type - - /** The type of `null`. - * It does not accept `undefined`. - * The null type is a subtype of all class types and array types. - */ - case object NullType extends Type - - /** Reference types (allowed for classOf[], is/asInstanceOf[]). - * - * A `ReferenceType` has exactly the same level of precision as a JVM type. - * There is a one-to-one relationship between a `ReferenceType` and an - * instance of `java.lang.Class` at run-time. This means that: - * - * - All primitive types have their reference type (including `scala.Byte` - * and `scala.Short`), and they are different from their boxed versions. - * - Raw JS types are not erased to `any` - * - Array types are like on the JVM - * - * A `ReferenceType` therefore uniquely identifies a `classOf[T]`. It is - * also the reference types that are used in method signatures, and which - * therefore dictate JVM/IR overloading. - */ - sealed trait ReferenceType - - /** Class (or interface) type. */ - final case class ClassType(className: String) extends Type with ReferenceType - - /** Array type. */ - final case class ArrayType(baseClassName: String, dimensions: Int) - extends Type with ReferenceType - - object ArrayType { - def apply(innerType: ReferenceType): ArrayType = innerType match { - case ClassType(className) => ArrayType(className, 1) - case ArrayType(className, dim) => ArrayType(className, dim + 1) - } - } - - /** Record type. - * Used by the optimizer to inline classes as records with multiple fields. - * They are desugared as several local variables by JSDesugaring. - * Record types cannot cross method boundaries, so they cannot appear as - * the type of fields or parameters, nor as result types of methods. - * The compiler itself never generates record types. - */ - final case class RecordType(fields: List[RecordType.Field]) extends Type { - def findField(name: String): RecordType.Field = - fields.find(_.name == name).get - } - - object RecordType { - final case class Field(name: String, originalName: Option[String], - tpe: Type, mutable: Boolean) - } - - /** No type. */ - case object NoType extends Type - - /** Generates a literal zero of the given type. */ - def zeroOf(tpe: Type)(implicit pos: Position): Literal = tpe match { - case BooleanType => BooleanLiteral(false) - case IntType => IntLiteral(0) - case LongType => LongLiteral(0L) - case FloatType => FloatLiteral(0.0f) - case DoubleType => DoubleLiteral(0.0) - case StringType => StringLiteral("") - case UndefType => Undefined() - case _ => Null() - } - - /** Tests whether a type `lhs` is a subtype of `rhs` (or equal). - * [[NoType]] is never a subtype or supertype of anything (including - * itself). All other types are subtypes of themselves. - * @param isSubclass A function testing whether a class/interface is a - * subclass of another class/interface. - */ - def isSubtype(lhs: Type, rhs: Type)( - isSubclass: (String, String) => Boolean): Boolean = { - import Definitions._ - - (lhs != NoType && rhs != NoType) && { - (lhs == rhs) || - ((lhs, rhs) match { - case (_, AnyType) => true - case (NothingType, _) => true - - case (ClassType(lhsClass), ClassType(rhsClass)) => - isSubclass(lhsClass, rhsClass) - - case (NullType, ClassType(_)) => true - case (NullType, ArrayType(_, _)) => true - - case (UndefType, ClassType(cls)) => - isSubclass(BoxedUnitClass, cls) - case (BooleanType, ClassType(cls)) => - isSubclass(BoxedBooleanClass, cls) - case (IntType, ClassType(cls)) => - isSubclass(BoxedIntegerClass, cls) || - cls == BoxedByteClass || - cls == BoxedShortClass || - cls == BoxedDoubleClass - case (LongType, ClassType(cls)) => - isSubclass(BoxedLongClass, cls) - case (FloatType, ClassType(cls)) => - isSubclass(BoxedFloatClass, cls) || - cls == BoxedDoubleClass - case (DoubleType, ClassType(cls)) => - isSubclass(BoxedDoubleClass, cls) - case (StringType, ClassType(cls)) => - isSubclass(StringClass, cls) - - case (IntType, DoubleType) => true - case (FloatType, DoubleType) => true - - case (ArrayType(lhsBase, lhsDims), ArrayType(rhsBase, rhsDims)) => - if (lhsDims < rhsDims) { - false // because Array[A] rhsDims) { - rhsBase == ObjectClass // because Array[Array[A]] <: Array[Object] - } else { // lhsDims == rhsDims - // lhsBase must be <: rhsBase - if (isPrimitiveClass(lhsBase) || isPrimitiveClass(rhsBase)) { - lhsBase == rhsBase - } else { - /* All things must be considered subclasses of Object for this - * purpose, even raw JS types and interfaces, which do not have - * Object in their ancestors. - */ - rhsBase == ObjectClass || isSubclass(lhsBase, rhsBase) - } - } - - case (ArrayType(_, _), ClassType(cls)) => - AncestorsOfPseudoArrayClass.contains(cls) - - case _ => - false - }) - } - } -} diff --git a/ir/src/main/scala/org/scalajs/core/ir/Utils.scala b/ir/src/main/scala/org/scalajs/core/ir/Utils.scala deleted file mode 100644 index 4779b9814f..0000000000 --- a/ir/src/main/scala/org/scalajs/core/ir/Utils.scala +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.ir - -import java.io.StringWriter -import java.net.URI - -import scala.annotation.switch - -object Utils { - - private final val EscapeJSChars = "\\b\\t\\n\\v\\f\\r\\\"\\\\" - - /** Relativize target URI w.r.t. base URI */ - def relativize(base0: URI, trgt0: URI): URI = { - val base = base0.normalize - val trgt = trgt0.normalize - - if (base.isOpaque || !base.isAbsolute || base.getRawPath == null || - trgt.isOpaque || !trgt.isAbsolute || trgt.getRawPath == null || - base.getScheme != trgt.getScheme || - base.getRawAuthority != trgt.getRawAuthority) - trgt - else { - val trgtCmps = trgt.getRawPath.split("/", -1) - - // Disregard the last element, since it is the filename - // (or empty string for a directory). - val baseCmps = base.getRawPath.split("/", -1).init - - val prefixLen = (trgtCmps zip baseCmps).takeWhile(t => t._1 == t._2).size - - val newPathCmps = - List.fill(baseCmps.size - prefixLen)("..") ++ trgtCmps.drop(prefixLen) - - val newPath = newPathCmps.mkString("/") - - // Relative URI does not have scheme or authority - new URI(null, null, newPath, trgt.getRawQuery, trgt.getRawFragment) - } - } - - /** Adds an empty authority to URIs with the "file" scheme without authority. - * Some browsers don't fetch URIs without authority correctly. - */ - def fixFileURI(uri: URI): URI = - if (uri.getScheme() != "file" || uri.getAuthority() != null) uri - else new URI("file", "", uri.getPath(), uri.getQuery(), uri.getFragment()) - - def escapeJS(str: String): String = { - // scalastyle:off return - val end = str.length - var i = 0 - while (i != end) { - val c = str.charAt(i) - if (c >= 32 && c <= 126 && c != '\\' && c != '"') - i += 1 - else - return createEscapeJSString(str) - } - str - // scalastyle:on return - } - - private def createEscapeJSString(str: String): String = { - val sb = new java.lang.StringBuilder(2 * str.length) - printEscapeJS(str, sb) - sb.toString - } - - def printEscapeJS(str: String, out: java.lang.Appendable): Int = { - /* Note that Java and JavaScript happen to use the same encoding for - * Unicode, namely UTF-16, which means that 1 char from Java always equals - * 1 char in JavaScript. */ - val end = str.length() - var i = 0 - var writtenChars = 0 - /* Loop prints all consecutive ASCII printable characters starting - * from current i and one non ASCII printable character (if it exists). - * The new i is set at the end of the appended characters. - */ - while (i != end) { - val start = i - var c: Int = str.charAt(i) - // Find all consecutive ASCII printable characters from `start` - while (i != end && c >= 32 && c <= 126 && c != 34 && c != 92) { - i += 1 - if (i != end) - c = str.charAt(i) - } - // Print ASCII printable characters from `start` - if (start != i) { - out.append(str, start, i) - writtenChars += i - } - - // Print next non ASCII printable character - if (i != end) { - def escapeJSEncoded(c: Int): Unit = { - if (7 < c && c < 14) { - val i = 2 * (c - 8) - out.append(EscapeJSChars, i, i + 2) - writtenChars += 2 - } else if (c == 34) { - out.append(EscapeJSChars, 12, 14) - writtenChars += 2 - } else if (c == 92) { - out.append(EscapeJSChars, 14, 16) - writtenChars += 2 - } else { - out.append(f"\\u$c%04x") - writtenChars += 6 - } - } - escapeJSEncoded(c) - i += 1 - } - } - writtenChars - } - - /** A ByteArrayOutput stream that allows to jump back to a given - * position and complete some bytes. Methods must be called in the - * following order only: - * - [[markJump]] - * - [[jumpBack]] - * - [[continue]] - */ - private[ir] class JumpBackByteArrayOutputStream - extends java.io.ByteArrayOutputStream { - protected var jumpBackPos: Int = -1 - protected var headPos: Int = -1 - - /** Marks the current location for a jumpback */ - def markJump(): Unit = { - assert(jumpBackPos == -1) - assert(headPos == -1) - jumpBackPos = count - } - - /** Jumps back to the mark. Returns the number of bytes jumped */ - def jumpBack(): Int = { - assert(jumpBackPos >= 0) - assert(headPos == -1) - val jumped = count - jumpBackPos - headPos = count - count = jumpBackPos - jumpBackPos = -1 - jumped - } - - /** Continues to write at the head. */ - def continue(): Unit = { - assert(jumpBackPos == -1) - assert(headPos >= 0) - count = headPos - headPos = -1 - } - } - -} diff --git a/ir/src/test/scala/org/scalajs/core/ir/PrintersTest.scala b/ir/src/test/scala/org/scalajs/core/ir/PrintersTest.scala deleted file mode 100644 index b2a54c4789..0000000000 --- a/ir/src/test/scala/org/scalajs/core/ir/PrintersTest.scala +++ /dev/null @@ -1,1128 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.ir - -import scala.language.implicitConversions - -import org.junit.Test -import org.junit.Assert._ - -import Definitions._ -import Printers._ -import Trees._ -import Types._ - -import OptimizerHints.{empty => NoOptHints} - -class PrintersTest { - private implicit val dummyPos = Position.NoPosition - - private def assertPrintEquals(expected: String, tree: Tree): Unit = - assertPrintEqualsImpl(expected, _.print(tree)) - - private def assertPrintEquals(expected: String, tpe: Type): Unit = - assertPrintEqualsImpl(expected, _.print(tpe)) - - private def assertPrintEqualsImpl(expected: String, - print: IRTreePrinter => Unit): Unit = { - val sw = new java.io.StringWriter - val printer = new IRTreePrinter(sw) - print(printer) - assertEquals(expected.stripMargin.trim, sw.toString()) - } - - private implicit def string2ident(name: String): Ident = Ident(name) - private implicit def string2classType(cls: String): ClassType = ClassType(cls) - - private def b(value: Boolean): BooleanLiteral = BooleanLiteral(value) - private def i(value: Int): IntLiteral = IntLiteral(value) - private def l(value: Long): LongLiteral = LongLiteral(value) - private def f(value: Float): FloatLiteral = FloatLiteral(value) - private def d(value: Double): DoubleLiteral = DoubleLiteral(value) - - private def ref(ident: Ident, tpe: Type): VarRef = VarRef(ident)(tpe) - - @Test def printType(): Unit = { - assertPrintEquals("any", AnyType) - assertPrintEquals("nothing", NothingType) - assertPrintEquals("void", UndefType) - assertPrintEquals("boolean", BooleanType) - assertPrintEquals("int", IntType) - assertPrintEquals("long", LongType) - assertPrintEquals("float", FloatType) - assertPrintEquals("double", DoubleType) - assertPrintEquals("string", StringType) - assertPrintEquals("null", NullType) - assertPrintEquals("", NoType) - - assertPrintEquals("O", ClassType(ObjectClass)) - - assertPrintEquals("O[]", ArrayType(ObjectClass, 1)) - assertPrintEquals("I[][]", ArrayType("I", 2)) - - assertPrintEquals("(x: int, var y: any)", - RecordType(List( - RecordType.Field("x", None, IntType, mutable = false), - RecordType.Field("y", None, AnyType, mutable = true)))) - } - - @Test def printVarDef(): Unit = { - assertPrintEquals("val x: int = 5", - VarDef("x", IntType, mutable = false, i(5))) - assertPrintEquals("var x: int = 5", - VarDef("x", IntType, mutable = true, i(5))) - } - - @Test def printParamDef(): Unit = { - assertPrintEquals("x: int", - ParamDef("x", IntType, mutable = false, rest = false)) - assertPrintEquals("var x: int", - ParamDef("x", IntType, mutable = true, rest = false)) - assertPrintEquals("...x: any", - ParamDef("x", AnyType, mutable = false, rest = true)) - assertPrintEquals("var ...x: any", - ParamDef("x", AnyType, mutable = true, rest = true)) - } - - @Test def printSkip(): Unit = { - assertPrintEquals("/**/", Skip()) - } - - @Test def printBlock(): Unit = { - assertPrintEquals( - """ - |{ - | 5; - | 6 - |} - """, - Block(i(5), i(6))) - } - - @Test def printLabeled(): Unit = { - assertPrintEquals( - """ - |lab: { - | 6 - |} - """, - Labeled("lab", NoType, i(6))) - - assertPrintEquals( - """ - |lab[int]: { - | 6 - |} - """, - Labeled("lab", IntType, i(6))) - - assertPrintEquals( - """ - |lab: { - | 5; - | 6 - |} - """, - Labeled("lab", NoType, Block(i(5), i(6)))) - } - - @Test def printAssign(): Unit = { - assertPrintEquals("x = 5", - Assign(VarRef("x")(IntType), i(5))) - } - - @Test def printReturn(): Unit = { - assertPrintEquals("return 5", Return(i(5))) - assertPrintEquals("return(lab) 5", Return(i(5), Some("lab"))) - } - - @Test def printIf(): Unit = { - assertPrintEquals( - """ - |if (true) { - | 5 - |} else { - | 6 - |} - """, - If(b(true), i(5), i(6))(IntType)) - - assertPrintEquals( - """ - |if (true) { - | 5 - |} - """, - If(b(true), i(5), Skip())(NoType)) - - assertPrintEquals( - """ - |if (true) { - | 5 - |} else if (false) { - | 6 - |} else { - | 7 - |} - """, - If(b(true), i(5), If(b(false), i(6), i(7))(IntType))(IntType)) - - assertPrintEquals("x || y", - If(ref("x", BooleanType), b(true), ref("y", BooleanType))(BooleanType)) - - assertPrintEquals("x && y", - If(ref("x", BooleanType), ref("y", BooleanType), b(false))(BooleanType)) - } - - @Test def printWhile(): Unit = { - assertPrintEquals( - """ - |while (true) { - | 5 - |} - """, - While(b(true), i(5))) - - assertPrintEquals( - """ - |lab: while (true) { - | 5 - |} - """, - While(b(true), i(5), Some("lab"))) - } - - @Test def printDoWhile(): Unit = { - assertPrintEquals( - """ - |do { - | 5 - |} while (true) - """, - DoWhile(i(5), b(true))) - - assertPrintEquals( - """ - |lab: do { - | 5 - |} while (true) - """, - DoWhile(i(5), b(true), Some("lab"))) - } - - @Test def printTry(): Unit = { - assertPrintEquals( - """ - |try { - | 5 - |} catch (e) { - | 6 - |} - """, - TryCatch(i(5), "e", i(6))(IntType)) - - assertPrintEquals( - """ - |try { - | 5 - |} finally { - | 6 - |} - """, - TryFinally(i(5), i(6))) - - assertPrintEquals( - """ - |try { - | 5 - |} catch (e) { - | 6 - |} finally { - | 7 - |} - """, - TryFinally(TryCatch(i(5), "e", i(6))(IntType), i(7))) - } - - @Test def printThrow(): Unit = { - assertPrintEquals("throw null", Throw(Null())) - } - - @Test def printContinue(): Unit = { - assertPrintEquals("continue", Continue()) - assertPrintEquals("continue lab", Continue(Some("lab"))) - } - - @Test def printMatch(): Unit = { - assertPrintEquals( - """ - |match (x) { - | case 5: - | 6; - | case 7 | 8: - | { - | 9; - | 10 - | }; - | default: - | 11; - |} - """, - Match(ref("x", IntType), List( - List(i(5)) -> i(6), - List(i(7), i(8)) -> Block(i(9), i(10))), - i(11))(IntType)) - } - - @Test def printDebugger(): Unit = { - assertPrintEquals("debugger", Debugger()) - } - - @Test def printNew(): Unit = { - assertPrintEquals("new O().init___()", - New(ObjectClass, "init___", Nil)) - assertPrintEquals("new T2().init___O__O(5, 6)", - New("T2", "init___O__O", List(i(5), i(6)))) - } - - @Test def printLoadModule(): Unit = { - assertPrintEquals("mod:s_Predef$", LoadModule("s_Predef$")) - } - - @Test def printStoreModule(): Unit = { - assertPrintEquals("mod:s_Predef$<-this", - StoreModule("s_Predef$", This()("s_Predef$"))) - } - - @Test def printSelect(): Unit = { - assertPrintEquals("x.f$1", Select(ref("x", "Ltest_Test"), "f$1")(IntType)) - } - - @Test def printSelectStatic(): Unit = { - assertPrintEquals("Ltest_Test.f$1", - SelectStatic("Ltest_Test", "f$1")(IntType)) - } - - @Test def printApply(): Unit = { - assertPrintEquals("x.m__V()", - Apply(ref("x", "Ltest_Test"), "m__V", Nil)(NoType)) - assertPrintEquals("x.m__I__I(5)", - Apply(ref("x", "Ltest_Test"), "m__I__I", List(i(5)))(IntType)) - assertPrintEquals("x.m__I__I__I(5, 6)", - Apply(ref("x", "Ltest_Test"), "m__I__I__I", List(i(5), i(6)))(IntType)) - } - - @Test def printApplyStatically(): Unit = { - assertPrintEquals("x.Ltest_Test::m__V()", - ApplyStatically(ref("x", "Ltest_Test"), "Ltest_Test", "m__V", - Nil)(NoType)) - assertPrintEquals("x.Ltest_Test::m__I__I(5)", - ApplyStatically(ref("x", "Ltest_Test"), "Ltest_Test", "m__I__I", - List(i(5)))(IntType)) - assertPrintEquals("x.Ltest_Test::m__I__I__I(5, 6)", - ApplyStatically(ref("x", "Ltest_Test"), "Ltest_Test", "m__I__I__I", - List(i(5), i(6)))(IntType)) - } - - @Test def printApplyStatic(): Unit = { - assertPrintEquals("Ltest_Test::m__V()", - ApplyStatic("Ltest_Test", "m__V", Nil)(NoType)) - assertPrintEquals("Ltest_Test::m__I__I(5)", - ApplyStatic("Ltest_Test", "m__I__I", List(i(5)))(IntType)) - assertPrintEquals("Ltest_Test::m__I__I__I(5, 6)", - ApplyStatic("Ltest_Test", "m__I__I__I", List(i(5), i(6)))(IntType)) - } - - @Test def printUnaryOp(): Unit = { - import UnaryOp._ - - assertPrintEquals("(!x)", UnaryOp(Boolean_!, ref("x", BooleanType))) - assertPrintEquals("((long)x)", UnaryOp(IntToLong, ref("x", IntType))) - assertPrintEquals("((int)x)", UnaryOp(LongToInt, ref("x", LongType))) - assertPrintEquals("((double)x)", UnaryOp(LongToDouble, ref("x", LongType))) - assertPrintEquals("((int)x)", UnaryOp(DoubleToInt, ref("x", DoubleType))) - assertPrintEquals("((float)x)", UnaryOp(DoubleToFloat, ref("x", DoubleType))) - assertPrintEquals("((long)x)", UnaryOp(DoubleToLong, ref("x", DoubleType))) - } - - @Test def printPseudoUnaryOp(): Unit = { - import BinaryOp._ - - assertPrintEquals("(-x)", BinaryOp(Int_-, i(0), ref("x", IntType))) - assertPrintEquals("(-x)", BinaryOp(Long_-, l(0), ref("x", LongType))) - assertPrintEquals("(-x)", BinaryOp(Float_-, f(0), ref("x", FloatType))) - assertPrintEquals("(-x)", BinaryOp(Double_-, d(0), ref("x", DoubleType))) - - assertPrintEquals("(~x)", BinaryOp(Int_^, i(-1), ref("x", IntType))) - assertPrintEquals("(~x)", BinaryOp(Long_^, l(-1), ref("x", LongType))) - } - - @Test def printBinaryOp(): Unit = { - import BinaryOp._ - - assertPrintEquals("(x === y)", - BinaryOp(===, ref("x", AnyType), ref("y", AnyType))) - assertPrintEquals("(x !== y)", - BinaryOp(!==, ref("x", AnyType), ref("y", AnyType))) - - assertPrintEquals("(x +[string] y)", - BinaryOp(String_+, ref("x", AnyType), ref("y", AnyType))) - - assertPrintEquals("(x +[int] y)", - BinaryOp(Int_+, ref("x", IntType), ref("y", IntType))) - assertPrintEquals("(x -[int] y)", - BinaryOp(Int_-, ref("x", IntType), ref("y", IntType))) - assertPrintEquals("(x *[int] y)", - BinaryOp(Int_*, ref("x", IntType), ref("y", IntType))) - assertPrintEquals("(x /[int] y)", - BinaryOp(Int_/, ref("x", IntType), ref("y", IntType))) - assertPrintEquals("(x %[int] y)", - BinaryOp(Int_%, ref("x", IntType), ref("y", IntType))) - - assertPrintEquals("(x |[int] y)", - BinaryOp(Int_|, ref("x", IntType), ref("y", IntType))) - assertPrintEquals("(x &[int] y)", - BinaryOp(Int_&, ref("x", IntType), ref("y", IntType))) - assertPrintEquals("(x ^[int] y)", - BinaryOp(Int_^, ref("x", IntType), ref("y", IntType))) - assertPrintEquals("(x <<[int] y)", - BinaryOp(Int_<<, ref("x", IntType), ref("y", IntType))) - assertPrintEquals("(x >>>[int] y)", - BinaryOp(Int_>>>, ref("x", IntType), ref("y", IntType))) - assertPrintEquals("(x >>[int] y)", - BinaryOp(Int_>>, ref("x", IntType), ref("y", IntType))) - - assertPrintEquals("(x +[float] y)", - BinaryOp(Float_+, ref("x", FloatType), ref("y", FloatType))) - assertPrintEquals("(x -[float] y)", - BinaryOp(Float_-, ref("x", FloatType), ref("y", FloatType))) - assertPrintEquals("(x *[float] y)", - BinaryOp(Float_*, ref("x", FloatType), ref("y", FloatType))) - assertPrintEquals("(x /[float] y)", - BinaryOp(Float_/, ref("x", FloatType), ref("y", FloatType))) - assertPrintEquals("(x %[float] y)", - BinaryOp(Float_%, ref("x", FloatType), ref("y", FloatType))) - - assertPrintEquals("(x +[double] y)", - BinaryOp(Double_+, ref("x", DoubleType), ref("y", DoubleType))) - assertPrintEquals("(x -[double] y)", - BinaryOp(Double_-, ref("x", DoubleType), ref("y", DoubleType))) - assertPrintEquals("(x *[double] y)", - BinaryOp(Double_*, ref("x", DoubleType), ref("y", DoubleType))) - assertPrintEquals("(x /[double] y)", - BinaryOp(Double_/, ref("x", DoubleType), ref("y", DoubleType))) - assertPrintEquals("(x %[double] y)", - BinaryOp(Double_%, ref("x", DoubleType), ref("y", DoubleType))) - - assertPrintEquals("(x == y)", - BinaryOp(Num_==, ref("x", DoubleType), ref("y", DoubleType))) - assertPrintEquals("(x != y)", - BinaryOp(Num_!=, ref("x", DoubleType), ref("y", DoubleType))) - assertPrintEquals("(x < y)", - BinaryOp(Num_<, ref("x", DoubleType), ref("y", DoubleType))) - assertPrintEquals("(x <= y)", - BinaryOp(Num_<=, ref("x", DoubleType), ref("y", DoubleType))) - assertPrintEquals("(x > y)", - BinaryOp(Num_>, ref("x", DoubleType), ref("y", DoubleType))) - assertPrintEquals("(x >= y)", - BinaryOp(Num_>=, ref("x", DoubleType), ref("y", DoubleType))) - - assertPrintEquals("(x +[long] y)", - BinaryOp(Long_+, ref("x", LongType), ref("y", LongType))) - assertPrintEquals("(x -[long] y)", - BinaryOp(Long_-, ref("x", LongType), ref("y", LongType))) - assertPrintEquals("(x *[long] y)", - BinaryOp(Long_*, ref("x", LongType), ref("y", LongType))) - assertPrintEquals("(x /[long] y)", - BinaryOp(Long_/, ref("x", LongType), ref("y", LongType))) - assertPrintEquals("(x %[long] y)", - BinaryOp(Long_%, ref("x", LongType), ref("y", LongType))) - - assertPrintEquals("(x |[long] y)", - BinaryOp(Long_|, ref("x", LongType), ref("y", LongType))) - assertPrintEquals("(x &[long] y)", - BinaryOp(Long_&, ref("x", LongType), ref("y", LongType))) - assertPrintEquals("(x ^[long] y)", - BinaryOp(Long_^, ref("x", LongType), ref("y", LongType))) - assertPrintEquals("(x <<[long] y)", - BinaryOp(Long_<<, ref("x", LongType), ref("y", IntType))) - assertPrintEquals("(x >>>[long] y)", - BinaryOp(Long_>>>, ref("x", LongType), ref("y", IntType))) - assertPrintEquals("(x >>[long] y)", - BinaryOp(Long_>>, ref("x", LongType), ref("y", IntType))) - - assertPrintEquals("(x ==[bool] y)", - BinaryOp(Boolean_==, ref("x", BooleanType), ref("y", BooleanType))) - assertPrintEquals("(x !=[bool] y)", - BinaryOp(Boolean_!=, ref("x", BooleanType), ref("y", BooleanType))) - assertPrintEquals("(x |[bool] y)", - BinaryOp(Boolean_|, ref("x", BooleanType), ref("y", BooleanType))) - assertPrintEquals("(x &[bool] y)", - BinaryOp(Boolean_&, ref("x", BooleanType), ref("y", BooleanType))) - } - - @Test def printNewArray(): Unit = { - assertPrintEquals("new I[3]", NewArray(ArrayType("I", 1), List(i(3)))) - assertPrintEquals("new I[3][]", NewArray(ArrayType("I", 2), List(i(3)))) - assertPrintEquals("new O[3][4][][]", - NewArray(ArrayType("O", 4), List(i(3), i(4)))) - } - - @Test def printArrayValue(): Unit = { - assertPrintEquals("I[]()", - ArrayValue(ArrayType("I", 1), List())) - assertPrintEquals("I[](5, 6)", - ArrayValue(ArrayType("I", 1), List(i(5), i(6)))) - - assertPrintEquals("I[][](null)", - ArrayValue(ArrayType("I", 2), List(Null()))) - } - - @Test def printArrayLength(): Unit = { - assertPrintEquals("x.length", ArrayLength(ref("x", ArrayType("I", 1)))) - } - - @Test def printArraySelect(): Unit = { - assertPrintEquals("x[3]", - ArraySelect(ref("x", ArrayType("I", 1)), i(3))(IntType)) - } - - @Test def printRecordValue(): Unit = { - assertPrintEquals("(x = 3, y = 4)", - RecordValue( - RecordType(List( - RecordType.Field("x", None, IntType, mutable = false), - RecordType.Field("y", None, IntType, mutable = true))), - List(i(3), i(4)))) - } - - @Test def printIsInstanceOf(): Unit = { - assertPrintEquals("x.isInstanceOf[T]", - IsInstanceOf(ref("x", AnyType), StringClass)) - } - - @Test def printAsInstanceOf(): Unit = { - assertPrintEquals("x.asInstanceOf[T]", - AsInstanceOf(ref("x", AnyType), StringClass)) - } - - @Test def printUnbox(): Unit = { - assertPrintEquals("x.asInstanceOf[I]", Unbox(ref("x", AnyType), 'I')) - } - - @Test def printGetClass(): Unit = { - assertPrintEquals("x.getClass()", GetClass(ref("x", AnyType))) - } - - @Test def printCallHelper(): Unit = { - assertPrintEquals("help(x, y)", - CallHelper("help", List(ref("x", AnyType), ref("y", AnyType)))(IntType)) - } - - @Test def printJSNew(): Unit = { - assertPrintEquals("new C()", JSNew(ref("C", AnyType), Nil)) - assertPrintEquals("new C(4, 5)", JSNew(ref("C", AnyType), List(i(4), i(5)))) - assertPrintEquals("new x.C(4, 5)", - JSNew(JSDotSelect(ref("x", AnyType), "C"), List(i(4), i(5)))) - assertPrintEquals("""new x["C"]()""", - JSNew(JSBracketSelect(ref("x", AnyType), StringLiteral("C")), Nil)) - - val fApplied = JSFunctionApply(ref("f", AnyType), Nil) - assertPrintEquals("new (f())()", JSNew(fApplied, Nil)) - assertPrintEquals("new (f().C)(4, 5)", - JSNew(JSDotSelect(fApplied, "C"), List(i(4), i(5)))) - assertPrintEquals("""new (f()["C"])()""", - JSNew(JSBracketSelect(fApplied, StringLiteral("C")), Nil)) - } - - @Test def printJSDotSelect(): Unit = { - assertPrintEquals("x.f", JSDotSelect(ref("x", AnyType), "f")) - } - - @Test def printJSBracketSelect(): Unit = { - assertPrintEquals("""x["f"]""", - JSBracketSelect(ref("x", AnyType), StringLiteral("f"))) - } - - @Test def printJSFunctionApply(): Unit = { - assertPrintEquals("f()", JSFunctionApply(ref("f", AnyType), Nil)) - assertPrintEquals("f(3, 4)", - JSFunctionApply(ref("f", AnyType), List(i(3), i(4)))) - - assertPrintEquals("(0, x.f)()", - JSFunctionApply(JSDotSelect(ref("x", AnyType), "f"), Nil)) - assertPrintEquals("""(0, x["f"])()""", - JSFunctionApply(JSBracketSelect(ref("x", AnyType), StringLiteral("f")), - Nil)) - assertPrintEquals("(0, x.f$1)()", - JSFunctionApply(Select(ref("x", "Ltest_Test"), "f$1")(AnyType), Nil)) - } - - @Test def printJSDotMethodApply(): Unit = { - assertPrintEquals("x.m()", JSDotMethodApply(ref("x", AnyType), "m", Nil)) - assertPrintEquals("x.m(4, 5)", - JSDotMethodApply(ref("x", AnyType), "m", List(i(4), i(5)))) - } - - @Test def printJSBracketMethodApply(): Unit = { - assertPrintEquals("""x["m"]()""", - JSBracketMethodApply(ref("x", AnyType), StringLiteral("m"), Nil)) - assertPrintEquals("""x["m"](4, 5)""", - JSBracketMethodApply(ref("x", AnyType), StringLiteral("m"), - List(i(4), i(5)))) - } - - @Test def printJSSuperBracketSelect(): Unit = { - assertPrintEquals("""x.LTest::super["f"]""", - JSSuperBracketSelect("LTest", ref("x", AnyType), StringLiteral("f"))) - } - - @Test def printJSSuperBracketCall(): Unit = { - assertPrintEquals("""x.LTest::super["f"]()""", - JSSuperBracketCall("LTest", ref("x", AnyType), StringLiteral("f"), Nil)) - } - - @Test def printJSSuperConstructorCall(): Unit = { - assertPrintEquals("super()", JSSuperConstructorCall(Nil)) - assertPrintEquals("super(4, 5)", JSSuperConstructorCall(List(i(4), i(5)))) - } - - @Test def printJSImportCall(): Unit = { - assertPrintEquals("""import("foo.js")""", JSImportCall(StringLiteral("foo.js"))) - } - - @Test def printLoadJSConstructor(): Unit = { - assertPrintEquals("constructorOf[LTest]", LoadJSConstructor("LTest")) - } - - @Test def printLoadJSModule(): Unit = { - assertPrintEquals("mod:LTest$", LoadJSModule("LTest$")) - } - - @Test def printJSSpread(): Unit = { - assertPrintEquals("...x", JSSpread(ref("x", AnyType))) - } - - @Test def printJSDelete(): Unit = { - assertPrintEquals("delete x.f", - JSDelete(JSDotSelect(ref("x", AnyType), "f"))) - } - - @Test def printJSUnaryOp(): Unit = { - assertPrintEquals("(+x)", JSUnaryOp(JSUnaryOp.+, ref("x", AnyType))) - assertPrintEquals("(-x)", JSUnaryOp(JSUnaryOp.-, ref("x", AnyType))) - assertPrintEquals("(~x)", JSUnaryOp(JSUnaryOp.~, ref("x", AnyType))) - assertPrintEquals("(!x)", JSUnaryOp(JSUnaryOp.!, ref("x", AnyType))) - assertPrintEquals("(typeof x)", - JSUnaryOp(JSUnaryOp.typeof, ref("x", AnyType))) - } - - @Test def printJSBinaryOp(): Unit = { - assertPrintEquals("(x === y)", - JSBinaryOp(JSBinaryOp.===, ref("x", AnyType), ref("y", AnyType))) - assertPrintEquals("(x !== y)", - JSBinaryOp(JSBinaryOp.!==, ref("x", AnyType), ref("y", AnyType))) - - assertPrintEquals("(x + y)", - JSBinaryOp(JSBinaryOp.+, ref("x", AnyType), ref("y", AnyType))) - assertPrintEquals("(x - y)", - JSBinaryOp(JSBinaryOp.-, ref("x", AnyType), ref("y", AnyType))) - assertPrintEquals("(x * y)", - JSBinaryOp(JSBinaryOp.*, ref("x", AnyType), ref("y", AnyType))) - assertPrintEquals("(x / y)", - JSBinaryOp(JSBinaryOp./, ref("x", AnyType), ref("y", AnyType))) - assertPrintEquals("(x % y)", - JSBinaryOp(JSBinaryOp.%, ref("x", AnyType), ref("y", AnyType))) - - assertPrintEquals("(x | y)", - JSBinaryOp(JSBinaryOp.|, ref("x", AnyType), ref("y", AnyType))) - assertPrintEquals("(x & y)", - JSBinaryOp(JSBinaryOp.&, ref("x", AnyType), ref("y", AnyType))) - assertPrintEquals("(x ^ y)", - JSBinaryOp(JSBinaryOp.^, ref("x", AnyType), ref("y", AnyType))) - assertPrintEquals("(x << y)", - JSBinaryOp(JSBinaryOp.<<, ref("x", AnyType), ref("y", AnyType))) - assertPrintEquals("(x >>> y)", - JSBinaryOp(JSBinaryOp.>>>, ref("x", AnyType), ref("y", AnyType))) - assertPrintEquals("(x >> y)", - JSBinaryOp(JSBinaryOp.>>, ref("x", AnyType), ref("y", AnyType))) - - assertPrintEquals("(x < y)", - JSBinaryOp(JSBinaryOp.<, ref("x", AnyType), ref("y", AnyType))) - assertPrintEquals("(x <= y)", - JSBinaryOp(JSBinaryOp.<=, ref("x", AnyType), ref("y", AnyType))) - assertPrintEquals("(x > y)", - JSBinaryOp(JSBinaryOp.>, ref("x", AnyType), ref("y", AnyType))) - assertPrintEquals("(x >= y)", - JSBinaryOp(JSBinaryOp.>=, ref("x", AnyType), ref("y", AnyType))) - - assertPrintEquals("(x && y)", - JSBinaryOp(JSBinaryOp.&&, ref("x", AnyType), ref("y", AnyType))) - assertPrintEquals("(x || y)", - JSBinaryOp(JSBinaryOp.||, ref("x", AnyType), ref("y", AnyType))) - - assertPrintEquals("(x in y)", - JSBinaryOp(JSBinaryOp.in, ref("x", AnyType), ref("y", AnyType))) - assertPrintEquals("(x instanceof y)", - JSBinaryOp(JSBinaryOp.instanceof, ref("x", AnyType), ref("y", AnyType))) - } - - @Test def printJSArrayConstr(): Unit = { - assertPrintEquals("[]", JSArrayConstr(Nil)) - assertPrintEquals("[5, 6]", JSArrayConstr(List(i(5), i(6)))) - } - - @Test def printJSObjectConstr(): Unit = { - assertPrintEquals("{}", JSObjectConstr(Nil)) - - assertPrintEquals( - """ - |{ - | f: 5, - | "g": 6 - |} - """, - JSObjectConstr(List(Ident("f") -> i(5), StringLiteral("g") -> i(6)))) - } - - @Test def printJSLinkingInfo(): Unit = { - assertPrintEquals("", JSLinkingInfo()) - } - - @Test def printUndefined(): Unit = { - assertPrintEquals("(void 0)", Undefined()) - } - - @Test def printNull(): Unit = { - assertPrintEquals("null", Null()) - } - - @Test def printBoolean(): Unit = { - assertPrintEquals("true", BooleanLiteral(true)) - assertPrintEquals("false", BooleanLiteral(false)) - } - - @Test def printIntLiteral(): Unit = { - assertPrintEquals("5", IntLiteral(5)) - assertPrintEquals("(-5)", IntLiteral(-5)) - } - - @Test def printLongLiteral(): Unit = { - assertPrintEquals("5L", LongLiteral(5L)) - assertPrintEquals("(-5L)", LongLiteral(-5L)) - } - - @Test def printFloatLiteral(): Unit = { - assertPrintEquals(0.0f.toString + "f", FloatLiteral(0.0f)) - assertPrintEquals("(-0f)", FloatLiteral(-0.0f)) - assertPrintEquals("Infinityf", FloatLiteral(Float.PositiveInfinity)) - assertPrintEquals("(-Infinityf)", FloatLiteral(Float.NegativeInfinity)) - assertPrintEquals("NaNf", FloatLiteral(Float.NaN)) - - assertPrintEquals(1.0f.toString + "f", FloatLiteral(1.0f)) - assertPrintEquals(1.5f.toString + "f", FloatLiteral(1.5f)) - assertPrintEquals("(" + (-1.5f).toString + "f)", FloatLiteral(-1.5f)) - } - - @Test def printDoubleLiteral(): Unit = { - assertPrintEquals(0.0.toString + "d", DoubleLiteral(0.0)) - assertPrintEquals("(-0d)", DoubleLiteral(-0.0)) - assertPrintEquals("Infinityd", DoubleLiteral(Double.PositiveInfinity)) - assertPrintEquals("(-Infinityd)", DoubleLiteral(Double.NegativeInfinity)) - assertPrintEquals("NaNd", DoubleLiteral(Double.NaN)) - - assertPrintEquals(1.0.toString + "d", DoubleLiteral(1.0)) - assertPrintEquals(1.5.toString + "d", DoubleLiteral(1.5)) - assertPrintEquals("(" + (-1.5).toString + "d)", DoubleLiteral(-1.5)) - } - - @Test def printStringLiteral(): Unit = { - assertPrintEquals(raw"""""""", StringLiteral("")) - assertPrintEquals(raw""""foo"""", StringLiteral("foo")) - assertPrintEquals(raw""""fo\no"""", StringLiteral("fo\no")) - assertPrintEquals("\"a\\u1234b\"", StringLiteral("a\u1234b")) - } - - @Test def printClassOf(): Unit = { - assertPrintEquals("classOf[LTest]", ClassOf("LTest")) - } - - @Test def printUndefinedParam(): Unit = { - assertPrintEquals("", UndefinedParam()(IntType)) - } - - @Test def printVarRef(): Unit = { - assertPrintEquals("x", VarRef("x")(IntType)) - } - - @Test def printThis(): Unit = { - assertPrintEquals("this", This()(AnyType)) - } - - @Test def printClosure(): Unit = { - assertPrintEquals( - """ - |(lambda<>() = { - | 5 - |}) - """, - Closure(Nil, Nil, i(5), Nil)) - - assertPrintEquals( - """ - |(lambda(z: any) = { - | z - |}) - """, - Closure( - List( - ParamDef("x", AnyType, mutable = false, rest = false), - ParamDef("y", IntType, mutable = false, rest = false)), - List(ParamDef("z", AnyType, mutable = false, rest = false)), - ref("z", AnyType), - List(ref("a", IntType), i(6)))) - } - - @Test def printClassDefKinds(): Unit = { - import ClassKind._ - - def makeForKind(kind: ClassKind): ClassDef = { - ClassDef("LTest", kind, Some(ObjectClass), Nil, None, Nil)(NoOptHints) - } - - assertPrintEquals( - """ - |class LTest extends O { - |} - """, - makeForKind(Class)) - - assertPrintEquals( - """ - |module class LTest extends O { - |} - """, - makeForKind(ModuleClass)) - - assertPrintEquals( - """ - |interface LTest extends O { - |} - """, - makeForKind(Interface)) - - assertPrintEquals( - """ - |abstract js type LTest extends O { - |} - """, - makeForKind(AbstractJSType)) - - assertPrintEquals( - """ - |hijacked class LTest extends O { - |} - """, - makeForKind(HijackedClass)) - - assertPrintEquals( - """ - |js class LTest extends O { - |} - """, - makeForKind(JSClass)) - - assertPrintEquals( - """ - |js module class LTest extends O { - |} - """, - makeForKind(JSModuleClass)) - - assertPrintEquals( - """ - |native js class LTest extends O { - |} - """, - makeForKind(NativeJSClass)) - - assertPrintEquals( - """ - |native js module class LTest extends O { - |} - """, - makeForKind(NativeJSModuleClass)) - } - - @Test def printClassDefParents(): Unit = { - def makeForParents(superClass: Option[Ident], - interfaces: List[Ident]): ClassDef = { - ClassDef("LTest", ClassKind.Class, superClass, interfaces, None, Nil)( - NoOptHints) - } - - assertPrintEquals( - """ - |class LTest { - |} - """, - makeForParents(None, Nil)) - - assertPrintEquals( - """ - |class LTest extends O implements LIntf { - |} - """, - makeForParents(Some(ObjectClass), List("LIntf"))) - - assertPrintEquals( - """ - |class LTest extends sr_AbstractFunction0 implements LIntf1, LIntf2 { - |} - """, - makeForParents(Some("sr_AbstractFunction0"), List("LIntf1", "LIntf2"))) - } - - @Test def printClassDefJSNativeLoadSpec(): Unit = { - assertPrintEquals( - """ - |native js class LTest extends O loadfrom .Foo { - |} - """, - ClassDef("LTest", ClassKind.NativeJSClass, Some(ObjectClass), Nil, - Some(JSNativeLoadSpec.Global(List("Foo"))), Nil)( - NoOptHints)) - - assertPrintEquals( - """ - |native js class LTest extends O loadfrom import(foo).Bar { - |} - """, - ClassDef("LTest", ClassKind.NativeJSClass, Some(ObjectClass), Nil, - Some(JSNativeLoadSpec.Import("foo", List("Bar"))), Nil)( - NoOptHints)) - - assertPrintEquals( - """ - |native js class LTest extends O loadfrom import(foo).Bar fallback .Foo { - |} - """, - ClassDef("LTest", ClassKind.NativeJSClass, Some(ObjectClass), Nil, - Some(JSNativeLoadSpec.ImportWithGlobalFallback( - JSNativeLoadSpec.Import("foo", List("Bar")), - JSNativeLoadSpec.Global(List("Foo")))), Nil)( - NoOptHints)) - } - - @Test def printClassDefOptimizerHints(): Unit = { - assertPrintEquals( - """ - |@hints(1) class LTest extends O { - |} - """, - ClassDef("LTest", ClassKind.Class, Some(ObjectClass), Nil, None, Nil)( - NoOptHints.withInline(true))) - } - - @Test def printClassDefDefs(): Unit = { - assertPrintEquals( - """ - |class LTest extends O { - | val x$1: int - | var y$1: int - |} - """, - ClassDef("LTest", ClassKind.Class, Some(ObjectClass), Nil, None, - List( - FieldDef(static = false, "x$1", IntType, mutable = false), - FieldDef(static = false, "y$1", IntType, mutable = true)))( - NoOptHints)) - } - - @Test def printFieldDef(): Unit = { - assertPrintEquals("val x$1: int", - FieldDef(static = false, "x$1", IntType, mutable = false)) - assertPrintEquals("var y$1: any", - FieldDef(static = false, "y$1", AnyType, mutable = true)) - - assertPrintEquals("""val "x": int""", - FieldDef(static = false, StringLiteral("x"), IntType, mutable = false)) - assertPrintEquals("""var "y": any""", - FieldDef(static = false, StringLiteral("y"), AnyType, mutable = true)) - - assertPrintEquals("""static val "x": int""", - FieldDef(static = true, StringLiteral("x"), IntType, mutable = false)) - assertPrintEquals("""static var "y": any""", - FieldDef(static = true, StringLiteral("y"), AnyType, mutable = true)) - } - - @Test def printMethodDef(): Unit = { - assertPrintEquals( - """ - |def m__I__I(x: int): int = - """, - MethodDef(static = false, "m__I__I", - List(ParamDef("x", IntType, mutable = false, rest = false)), - IntType, None)(NoOptHints, None)) - - assertPrintEquals( - """ - |def m__I__I(x: int): int = { - | 5 - |} - """, - MethodDef(static = false, "m__I__I", - List(ParamDef("x", IntType, mutable = false, rest = false)), - IntType, Some(i(5)))(NoOptHints, None)) - - assertPrintEquals( - """ - |@hints(1) def m__I__I(x: int): int = { - | 5 - |} - """, - MethodDef(static = false, "m__I__I", - List(ParamDef("x", IntType, mutable = false, rest = false)), - IntType, Some(i(5)))(NoOptHints.withInline(true), None)) - - assertPrintEquals( - """ - |def m__I__V(x: int) { - | 5 - |} - """, - MethodDef(static = false, "m__I__V", - List(ParamDef("x", IntType, mutable = false, rest = false)), - NoType, Some(i(5)))(NoOptHints, None)) - - assertPrintEquals( - """ - |def "m"(x: any): any = { - | 5 - |} - """, - MethodDef(static = false, StringLiteral("m"), - List(ParamDef("x", AnyType, mutable = false, rest = false)), - AnyType, Some(i(5)))(NoOptHints, None)) - - assertPrintEquals( - """ - |def "m"(...x: any): any = { - | 5 - |} - """, - MethodDef(static = false, StringLiteral("m"), - List(ParamDef("x", AnyType, mutable = false, rest = true)), - AnyType, Some(i(5)))(NoOptHints, None)) - - assertPrintEquals( - """ - |static def m__I__I(x: int): int = { - | 5 - |} - """, - MethodDef(static = true, "m__I__I", - List(ParamDef("x", IntType, mutable = false, rest = false)), - IntType, Some(i(5)))(NoOptHints, None)) - } - - @Test def printPropertyDef(): Unit = { - for (static <- Seq(false, true)) { - val staticStr = - if (static) "static " - else "" - - assertPrintEquals( - s""" - |${staticStr}get "prop"(): any = { - | 5 - |} - """, - PropertyDef(static, StringLiteral("prop"), Some(i(5)), None)) - - assertPrintEquals( - s""" - |${staticStr}set "prop"(x: any) { - | 7 - |} - """, - PropertyDef(static, StringLiteral("prop"), - None, - Some((ParamDef("x", AnyType, mutable = false, rest = false), i(7))))) - - assertPrintEquals( - s""" - |${staticStr}get "prop"(): any = { - | 5 - |} - |${staticStr}set "prop"(x: any) { - | 7 - |} - """, - PropertyDef(static, StringLiteral("prop"), - Some(i(5)), - Some((ParamDef("x", AnyType, mutable = false, rest = false), - i(7))))) - } - } - - @Test def printConstructorExportDef(): Unit = { - assertPrintEquals( - """ - |export "pkg.Foo"(x: any) { - | 5 - |} - """, - ConstructorExportDef("pkg.Foo", - List(ParamDef("x", AnyType, mutable = false, rest = false)), - i(5))) - } - - @Test def printJSClassExportDef(): Unit = { - assertPrintEquals( - """export class "pkg.Foo"""", - JSClassExportDef("pkg.Foo")) - } - - @Test def printModuleExportDef(): Unit = { - assertPrintEquals( - """export module "pkg.Foo"""", - ModuleExportDef("pkg.Foo")) - } - - @Test def printTopLevelModuleExportDef(): Unit = { - assertPrintEquals( - """export top module "pkg.Foo"""", - TopLevelModuleExportDef("pkg.Foo")) - } - - @Test def printTopLevelMethodExportDef(): Unit = { - assertPrintEquals( - """ - |export top static def "pkg.foo"(x: any): any = { - | 5 - |}""", - TopLevelMethodExportDef(MethodDef(static = true, - StringLiteral("pkg.foo"), - List(ParamDef("x", AnyType, mutable = false, rest = false)), - AnyType, Some(i(5)))(NoOptHints, None))) - } - - @Test def printTopLevelFieldExportDef(): Unit = { - assertPrintEquals( - """ - |export top static field x$1 as "x" - """, - TopLevelFieldExportDef("x", "x$1")) - } -} diff --git a/ir/src/test/scala/org/scalajs/core/ir/UtilsTest.scala b/ir/src/test/scala/org/scalajs/core/ir/UtilsTest.scala deleted file mode 100644 index 8ac1377ce4..0000000000 --- a/ir/src/test/scala/org/scalajs/core/ir/UtilsTest.scala +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.core.ir - -import java.net.URI - -import org.junit.Test -import org.junit.Assert._ - -class UtilsTest { - - @Test def relativizeURI(): Unit = { - def test(base: String, trgt: String, rel: String) = { - val baseURI = new URI(base) - val trgtURI = new URI(trgt) - val relURI = Utils.relativize(baseURI, trgtURI) - assertEquals(rel, relURI.toString) - assertEquals(trgtURI, baseURI.resolve(relURI)) - } - - test("file:///foo/bar/", "file:///foo/bar/baz", "baz") - test("file:///foo/bar/boo", "file:///foo/bar/baz", "baz") - - test("file:///foo/bar/", "file:///foo/bar/baz/", "baz/") - test("file:///foo/bar/boo", "file:///foo/bar/baz/", "baz/") - - test("file:///foo/bar/", "file:///foo/baz", "../baz") - test("file:///foo/bar/boo", "file:///foo/baz", "../baz") - - test("file:///foo/bar/", "file:///foo/baz/", "../baz/") - test("file:///foo/bar/boo", "file:///foo/baz/", "../baz/") - - test("file:///bar/foo/", "file:///foo/bar/baz", "../../foo/bar/baz") - - test("file:///foo", "http://bar.com/foo", "http://bar.com/foo") - test("http://bob.com/foo", "http://bar.com/foo", "http://bar.com/foo") - } - -} diff --git a/javalanglib/src/main/scala/java/lang/Boolean.scala b/javalanglib/src/main/scala/java/lang/Boolean.scala deleted file mode 100644 index 3c6deb828f..0000000000 --- a/javalanglib/src/main/scala/java/lang/Boolean.scala +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package java.lang - -import scala.scalajs.js - -/* This is a hijacked class. Its instances are primitive booleans. - * Constructors are not emitted. - */ -final class Boolean private () - extends AnyRef with java.io.Serializable with Comparable[Boolean] { - - def this(value: scala.Boolean) = this() - def this(v: String) = this() - - @inline def booleanValue(): scala.Boolean = - this.asInstanceOf[scala.Boolean] - - @inline override def equals(that: Any): scala.Boolean = - this eq that.asInstanceOf[AnyRef] - - @inline override def hashCode(): Int = - if (booleanValue) 1231 else 1237 - - @inline override def compareTo(that: Boolean): Int = - Boolean.compare(booleanValue, that.booleanValue) - - @inline override def toString(): String = - Boolean.toString(booleanValue) - -} - -object Boolean { - final val TYPE = scala.Predef.classOf[scala.Boolean] - - /* TRUE and FALSE are supposed to be vals. However, they are better - * optimized as defs, because they end up being just the constant true and - * false (since `new Boolean(x)` is a no-op). - * Since vals and defs are binary-compatible (although they're not strictly - * speaking source-compatible, because of stability), we implement them as - * defs. Source-compatibility is not an issue because user code is compiled - * against the JDK .class files anyway. - * Moreover, preserving the identity of TRUE and FALSE is not an issue - * either, since they are primitive booleans in the end. - */ - def TRUE: Boolean = new Boolean(true) - def FALSE: Boolean = new Boolean(false) - - @inline def valueOf(booleanValue: scala.Boolean): Boolean = { - // We don't care about identity, since they end up as primitive booleans - new Boolean(booleanValue) - } - - @inline def valueOf(s: String): Boolean = valueOf(parseBoolean(s)) - - @inline def parseBoolean(s: String): scala.Boolean = - (s != null) && s.equalsIgnoreCase("true") - - @inline def toString(b: scala.Boolean): String = - "" + b - - @inline def compare(x: scala.Boolean, y: scala.Boolean): scala.Int = - if (x == y) 0 else if (x) 1 else -1 -} diff --git a/javalanglib/src/main/scala/java/lang/Byte.scala b/javalanglib/src/main/scala/java/lang/Byte.scala deleted file mode 100644 index 357e8ac230..0000000000 --- a/javalanglib/src/main/scala/java/lang/Byte.scala +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package java.lang - -import scala.scalajs.js - -/* This is a hijacked class. Its instances are primitive numbers. - * Constructors are not emitted. - */ -final class Byte private () extends Number with Comparable[Byte] { - - def this(value: scala.Byte) = this() - def this(s: String) = this() - - @inline override def byteValue(): scala.Byte = - this.asInstanceOf[scala.Byte] - - @inline override def shortValue(): scala.Short = byteValue.toShort - @inline def intValue(): scala.Int = byteValue.toInt - @inline def longValue(): scala.Long = byteValue.toLong - @inline def floatValue(): scala.Float = byteValue.toFloat - @inline def doubleValue(): scala.Double = byteValue.toDouble - - @inline override def equals(that: Any): scala.Boolean = - this eq that.asInstanceOf[AnyRef] - - @inline override def hashCode(): Int = - byteValue - - @inline override def compareTo(that: Byte): Int = - Byte.compare(byteValue, that.byteValue) - - @inline override def toString(): String = - Byte.toString(byteValue) -} - -object Byte { - final val TYPE = scala.Predef.classOf[scala.Byte] - final val SIZE = 8 - final val BYTES = 1 - - /* MIN_VALUE and MAX_VALUE should be 'final val's. But it is impossible to - * write a proper Byte literal in Scala, that would both considered a Byte - * and a constant expression (optimized as final val). - * Since vals and defs are binary-compatible (although they're not strictly - * speaking source-compatible, because of stability), we implement them as - * defs. Source-compatibility is not an issue because user code is compiled - * against the JDK .class files anyway. - */ - def MIN_VALUE: scala.Byte = -128 - def MAX_VALUE: scala.Byte = 127 - - @inline def valueOf(byteValue: scala.Byte): Byte = new Byte(byteValue) - @inline def valueOf(s: String): Byte = valueOf(parseByte(s)) - - @inline def valueOf(s: String, radix: Int): Byte = - valueOf(parseByte(s, radix)) - - @inline def parseByte(s: String): scala.Byte = parseByte(s, 10) - - def parseByte(s: String, radix: Int): scala.Byte = { - val r = Integer.parseInt(s, radix) - if (r < MIN_VALUE || r > MAX_VALUE) - throw new NumberFormatException(s"""For input string: "$s"""") - else - r.toByte - } - - @inline def toString(b: scala.Byte): String = - "" + b - - @noinline def decode(nm: String): Byte = - Integer.decodeGeneric(nm, valueOf(_, _)) - - @inline def compare(x: scala.Byte, y: scala.Byte): scala.Int = - x - y -} diff --git a/javalanglib/src/main/scala/java/lang/Character.scala b/javalanglib/src/main/scala/java/lang/Character.scala deleted file mode 100644 index f31edea177..0000000000 --- a/javalanglib/src/main/scala/java/lang/Character.scala +++ /dev/null @@ -1,1055 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package java.lang - -import scala.scalajs.js - -import java.util.Arrays - -@inline -class Character(private val value: scala.Char) - extends AnyRef with java.io.Serializable with Comparable[Character] { - - def charValue(): scala.Char = value - - override def equals(that: Any): scala.Boolean = - that.isInstanceOf[Character] && (value == that.asInstanceOf[Character].charValue) - - override def compareTo(that: Character): Int = - Character.compare(charValue, that.charValue) - - override def toString(): String = - Character.toString(value) - - override def hashCode(): Int = value.## - - /* - * Methods on scala.Char - * The following methods are only here to properly support reflective calls - * on boxed primitive values. YOU WILL NOT BE ABLE TO USE THESE METHODS, since - * we use the true javalib to lookup symbols, this file contains only - * implementations. - */ - protected def toByte: scala.Byte = value.toByte - protected def toShort: scala.Short = value.toShort - protected def toChar: scala.Char = value.toChar - protected def toInt: scala.Int = value - protected def toLong: scala.Long = value.toLong - protected def toFloat: scala.Float = value.toFloat - protected def toDouble: scala.Double = value.toDouble - - // scalastyle:off disallow.space.before.token - protected def unary_~ : scala.Int = ~value - protected def unary_+ : scala.Int = value - protected def unary_- : scala.Int = -value - // scalastyle:on disallow.space.before.token - - protected def +(x: String): String = "" + value + x - - protected def <<(x: scala.Int): scala.Int = value << x - protected def <<(x: scala.Long): scala.Int = value << x.toInt - protected def >>>(x: scala.Int): scala.Int = value >>> x - protected def >>>(x: scala.Long): scala.Int = value >>> x.toInt - protected def >>(x: scala.Int): scala.Int = value >> x - protected def >>(x: scala.Long): scala.Int = value >> x.toInt - - protected def ==(x: scala.Byte): scala.Boolean = value == x - protected def ==(x: scala.Short): scala.Boolean = value == x - protected def ==(x: scala.Char): scala.Boolean = value == x - protected def ==(x: scala.Int): scala.Boolean = value == x - protected def ==(x: scala.Long): scala.Boolean = value == x - protected def ==(x: scala.Float): scala.Boolean = value == x - protected def ==(x: scala.Double): scala.Boolean = value == x - - protected def !=(x: scala.Byte): scala.Boolean = value != x - protected def !=(x: scala.Short): scala.Boolean = value != x - protected def !=(x: scala.Char): scala.Boolean = value != x - protected def !=(x: scala.Int): scala.Boolean = value != x - protected def !=(x: scala.Long): scala.Boolean = value != x - protected def !=(x: scala.Float): scala.Boolean = value != x - protected def !=(x: scala.Double): scala.Boolean = value != x - - protected def <(x: scala.Byte): scala.Boolean = value < x - protected def <(x: scala.Short): scala.Boolean = value < x - protected def <(x: scala.Char): scala.Boolean = value < x - protected def <(x: scala.Int): scala.Boolean = value < x - protected def <(x: scala.Long): scala.Boolean = value < x - protected def <(x: scala.Float): scala.Boolean = value < x - protected def <(x: scala.Double): scala.Boolean = value < x - - protected def <=(x: scala.Byte): scala.Boolean = value <= x - protected def <=(x: scala.Short): scala.Boolean = value <= x - protected def <=(x: scala.Char): scala.Boolean = value <= x - protected def <=(x: scala.Int): scala.Boolean = value <= x - protected def <=(x: scala.Long): scala.Boolean = value <= x - protected def <=(x: scala.Float): scala.Boolean = value <= x - protected def <=(x: scala.Double): scala.Boolean = value <= x - - protected def >(x: scala.Byte): scala.Boolean = value > x - protected def >(x: scala.Short): scala.Boolean = value > x - protected def >(x: scala.Char): scala.Boolean = value > x - protected def >(x: scala.Int): scala.Boolean = value > x - protected def >(x: scala.Long): scala.Boolean = value > x - protected def >(x: scala.Float): scala.Boolean = value > x - protected def >(x: scala.Double): scala.Boolean = value > x - - protected def >=(x: scala.Byte): scala.Boolean = value >= x - protected def >=(x: scala.Short): scala.Boolean = value >= x - protected def >=(x: scala.Char): scala.Boolean = value >= x - protected def >=(x: scala.Int): scala.Boolean = value >= x - protected def >=(x: scala.Long): scala.Boolean = value >= x - protected def >=(x: scala.Float): scala.Boolean = value >= x - protected def >=(x: scala.Double): scala.Boolean = value >= x - - protected def |(x: scala.Byte): scala.Int = value | x - protected def |(x: scala.Short): scala.Int = value | x - protected def |(x: scala.Char): scala.Int = value | x - protected def |(x: scala.Int): scala.Int = value | x - protected def |(x: scala.Long): scala.Long = value | x - - protected def &(x: scala.Byte): scala.Int = value & x - protected def &(x: scala.Short): scala.Int = value & x - protected def &(x: scala.Char): scala.Int = value & x - protected def &(x: scala.Int): scala.Int = value & x - protected def &(x: scala.Long): scala.Long = value & x - - protected def ^(x: scala.Byte): scala.Int = value ^ x - protected def ^(x: scala.Short): scala.Int = value ^ x - protected def ^(x: scala.Char): scala.Int = value ^ x - protected def ^(x: scala.Int): scala.Int = value ^ x - protected def ^(x: scala.Long): scala.Long = value ^ x - - protected def +(x: scala.Byte): scala.Int = value + x - protected def +(x: scala.Short): scala.Int = value + x - protected def +(x: scala.Char): scala.Int = value + x - protected def +(x: scala.Int): scala.Int = value + x - protected def +(x: scala.Long): scala.Long = value + x - protected def +(x: scala.Float): scala.Float = value + x - protected def +(x: scala.Double): scala.Double = value + x - - protected def -(x: scala.Byte): scala.Int = value - x - protected def -(x: scala.Short): scala.Int = value - x - protected def -(x: scala.Char): scala.Int = value - x - protected def -(x: scala.Int): scala.Int = value - x - protected def -(x: scala.Long): scala.Long = value - x - protected def -(x: scala.Float): scala.Float = value - x - protected def -(x: scala.Double): scala.Double = value - x - - protected def *(x: scala.Byte): scala.Int = value * x - protected def *(x: scala.Short): scala.Int = value * x - protected def *(x: scala.Char): scala.Int = value * x - protected def *(x: scala.Int): scala.Int = value * x - protected def *(x: scala.Long): scala.Long = value * x - protected def *(x: scala.Float): scala.Float = value * x - protected def *(x: scala.Double): scala.Double = value * x - - protected def /(x: scala.Byte): scala.Int = value / x - protected def /(x: scala.Short): scala.Int = value / x - protected def /(x: scala.Char): scala.Int = value / x - protected def /(x: scala.Int): scala.Int = value / x - protected def /(x: scala.Long): scala.Long = value / x - protected def /(x: scala.Float): scala.Float = value / x - protected def /(x: scala.Double): scala.Double = value / x - - protected def %(x: scala.Byte): scala.Int = value % x - protected def %(x: scala.Short): scala.Int = value % x - protected def %(x: scala.Char): scala.Int = value % x - protected def %(x: scala.Int): scala.Int = value % x - protected def %(x: scala.Long): scala.Long = value % x - protected def %(x: scala.Float): scala.Float = value % x - protected def %(x: scala.Double): scala.Double = value % x - -} - -object Character { - final val TYPE = scala.Predef.classOf[scala.Char] - final val MIN_VALUE = '\u0000' - final val MAX_VALUE = '\uffff' - final val SIZE = 16 - final val BYTES = 2 - - def valueOf(charValue: scala.Char): Character = new Character(charValue) - - /* These are supposed to be final vals of type Byte, but that's not possible. - * So we implement them as def's, which are binary compatible with final vals. - */ - def UNASSIGNED: scala.Byte = 0 - def UPPERCASE_LETTER: scala.Byte = 1 - def LOWERCASE_LETTER: scala.Byte = 2 - def TITLECASE_LETTER: scala.Byte = 3 - def MODIFIER_LETTER: scala.Byte = 4 - def OTHER_LETTER: scala.Byte = 5 - def NON_SPACING_MARK: scala.Byte = 6 - def ENCLOSING_MARK: scala.Byte = 7 - def COMBINING_SPACING_MARK: scala.Byte = 8 - def DECIMAL_DIGIT_NUMBER: scala.Byte = 9 - def LETTER_NUMBER: scala.Byte = 10 - def OTHER_NUMBER: scala.Byte = 11 - def SPACE_SEPARATOR: scala.Byte = 12 - def LINE_SEPARATOR: scala.Byte = 13 - def PARAGRAPH_SEPARATOR: scala.Byte = 14 - def CONTROL: scala.Byte = 15 - def FORMAT: scala.Byte = 16 - def PRIVATE_USE: scala.Byte = 18 - def SURROGATE: scala.Byte = 19 - def DASH_PUNCTUATION: scala.Byte = 20 - def START_PUNCTUATION: scala.Byte = 21 - def END_PUNCTUATION: scala.Byte = 22 - def CONNECTOR_PUNCTUATION: scala.Byte = 23 - def OTHER_PUNCTUATION: scala.Byte = 24 - def MATH_SYMBOL: scala.Byte = 25 - def CURRENCY_SYMBOL: scala.Byte = 26 - def MODIFIER_SYMBOL: scala.Byte = 27 - def OTHER_SYMBOL: scala.Byte = 28 - def INITIAL_QUOTE_PUNCTUATION: scala.Byte = 29 - def FINAL_QUOTE_PUNCTUATION: scala.Byte = 30 - - final val MIN_RADIX = 2 - final val MAX_RADIX = 36 - - final val MIN_HIGH_SURROGATE = '\uD800' - final val MAX_HIGH_SURROGATE = '\uDBFF' - final val MIN_LOW_SURROGATE = '\uDC00' - final val MAX_LOW_SURROGATE = '\uDFFF' - final val MIN_SURROGATE = MIN_HIGH_SURROGATE - final val MAX_SURROGATE = MAX_LOW_SURROGATE - - final val MIN_CODE_POINT = 0 - final val MAX_CODE_POINT = 0x10ffff - final val MIN_SUPPLEMENTARY_CODE_POINT = 0x10000 - - def getType(ch: scala.Char): Int = getType(ch.toInt) - - def getType(codePoint: Int): Int = { - if (codePoint < 0) UNASSIGNED.toInt - else if (codePoint < 256) getTypeLT256(codePoint) - else getTypeGE256(codePoint) - } - - @inline - private[this] def getTypeLT256(codePoint: Int): Int = - charTypesFirst256(codePoint) - - private[this] def getTypeGE256(codePoint: Int): Int = { - // the idx is increased by 1 due to the differences in indexing - // between charTypeIndices and charType - val idx = Arrays.binarySearch(charTypeIndices, codePoint) + 1 - // in the case where idx is negative (-insertionPoint - 1) - charTypes(Math.abs(idx)) - } - - @inline - def digit(ch: scala.Char, radix: Int): Int = - digit(ch.toInt, radix) - - @inline // because radix is probably constant at call site - def digit(codePoint: Int, radix: Int): Int = { - if (radix > MAX_RADIX || radix < MIN_RADIX) - -1 - else - digitWithValidRadix(codePoint, radix) - } - - private[lang] def digitWithValidRadix(codePoint: Int, radix: Int): Int = { - val value = if (codePoint < 256) { - // Fast-path for the ASCII repertoire - if (codePoint >= '0' && codePoint <= '9') - codePoint - '0' - else if (codePoint >= 'A' && codePoint <= 'Z') - codePoint - ('A' - 10) - else if (codePoint >= 'a' && codePoint <= 'z') - codePoint - ('a' - 10) - else - -1 - } else { - if (codePoint >= 0xff21 && codePoint <= 0xff3a) { - // Fullwidth uppercase Latin letter - codePoint - (0xff21 - 10) - } else if (codePoint >= 0xff41 && codePoint <= 0xff5a) { - // Fullwidth lowercase Latin letter - codePoint - (0xff41 - 10) - } else { - // Maybe it is a digit in a non-ASCII script - - // Find the position of the 0 digit corresponding to this code point - val p = Arrays.binarySearch(nonASCIIZeroDigitCodePoints, codePoint) - val zeroCodePointIndex = if (p < 0) -2 - p else p - - /* If the index is below 0, it cannot be a digit. Otherwise, the value - * is the difference between the given codePoint and the code point of - * its corresponding 0. We must ensure that it is not bigger than 9. - */ - if (zeroCodePointIndex < 0) { - -1 - } else { - val v = codePoint - nonASCIIZeroDigitCodePoints(zeroCodePointIndex) - if (v > 9) -1 else v - } - } - } - - if (value < radix) value - else -1 - } - - private[lang] def isZeroDigit(ch: Char): scala.Boolean = - if (ch < 256) ch == '0' - else Arrays.binarySearch(nonASCIIZeroDigitCodePoints, ch.toInt) >= 0 - - // ported from https://github.com/gwtproject/gwt/blob/master/user/super/com/google/gwt/emul/java/lang/Character.java - def forDigit(digit: Int, radix: Int): Char = { - if (radix < MIN_RADIX || radix > MAX_RADIX || digit < 0 || digit >= radix) { - 0 - } else { - val overBaseTen = digit - 10 - val result = if (overBaseTen < 0) '0' + digit else 'a' + overBaseTen - result.toChar - } - } - - def isISOControl(c: scala.Char): scala.Boolean = isISOControl(c.toInt) - - def isISOControl(codePoint: Int): scala.Boolean = { - (0x00 <= codePoint && codePoint <= 0x1F) || (0x7F <= codePoint && codePoint <= 0x9F) - } - - @deprecated("Replaced by isWhitespace(char)", "") - def isSpace(c: scala.Char): scala.Boolean = - c == '\t' || c == '\n' || c == '\f' || c == '\r' || c == ' ' - - def isWhitespace(c: scala.Char): scala.Boolean = - isWhitespace(c.toInt) - - def isWhitespace(codePoint: scala.Int): scala.Boolean = { - def isSeparator(tpe: Int): scala.Boolean = - tpe == SPACE_SEPARATOR || tpe == LINE_SEPARATOR || tpe == PARAGRAPH_SEPARATOR - if (codePoint < 256) { - codePoint == '\t' || codePoint == '\n' || codePoint == '\u000B' || - codePoint == '\f' || codePoint == '\r' || - ('\u001C' <= codePoint && codePoint <= '\u001F') || - (codePoint != '\u00A0' && isSeparator(getTypeLT256(codePoint))) - } else { - (codePoint != '\u2007' && codePoint != '\u202F') && - isSeparator(getTypeGE256(codePoint)) - } - } - - def isSpaceChar(ch: scala.Char): scala.Boolean = - isSpaceChar(ch.toInt) - - def isSpaceChar(codePoint: Int): scala.Boolean = - isSpaceCharImpl(getType(codePoint)) - - @inline private[this] def isSpaceCharImpl(tpe: Int): scala.Boolean = - tpe == SPACE_SEPARATOR || tpe == LINE_SEPARATOR || tpe == PARAGRAPH_SEPARATOR - - // --- UTF-16 surrogate pairs handling --- - // See http://en.wikipedia.org/wiki/UTF-16 - - private final val HighSurrogateMask = 0xfc00 // 111111 00 00000000 - private final val HighSurrogateID = 0xd800 // 110110 00 00000000 - private final val LowSurrogateMask = 0xfc00 // 111111 00 00000000 - private final val LowSurrogateID = 0xdc00 // 110111 00 00000000 - private final val SurrogateUsefulPartMask = 0x03ff // 000000 11 11111111 - - @inline def isHighSurrogate(c: scala.Char): scala.Boolean = - (c & HighSurrogateMask) == HighSurrogateID - @inline def isLowSurrogate(c: scala.Char): scala.Boolean = - (c & LowSurrogateMask) == LowSurrogateID - @inline def isSurrogate(c: scala.Char): scala.Boolean = - isHighSurrogate(c) || isLowSurrogate(c) - @inline def isSurrogatePair(high: scala.Char, low: scala.Char): scala.Boolean = - isHighSurrogate(high) && isLowSurrogate(low) - - @inline def charCount(codePoint: Int): Int = - if (codePoint >= MIN_SUPPLEMENTARY_CODE_POINT) 2 else 1 - - @inline def toCodePoint(high: scala.Char, low: scala.Char): Int = - ((high & SurrogateUsefulPartMask) << 10) + (low & SurrogateUsefulPartMask) + 0x10000 - - // --- End of UTF-16 surrogate pairs handling --- - - def isLowerCase(c: scala.Char): scala.Boolean = - isLowerCase(c.toInt) - - def isLowerCase(c: Int): scala.Boolean = { - if (c < 256) - c == '\u00AA' || c == '\u00BA' || getTypeLT256(c) == LOWERCASE_LETTER - else - isLowerCaseGE256(c) - } - - private[this] def isLowerCaseGE256(c: Int): scala.Boolean = { - ('\u02B0' <= c && c <= '\u02B8') || ('\u02C0' <= c && c <= '\u02C1') || - ('\u02E0' <= c && c <= '\u02E4') || c == '\u0345' || c == '\u037A' || - ('\u1D2C' <= c && c <= '\u1D6A') || c == '\u1D78' || - ('\u1D9B' <= c && c <= '\u1DBF') || c == '\u2071' || c == '\u207F' || - ('\u2090' <= c && c <= '\u209C') || ('\u2170' <= c && c <= '\u217F') || - ('\u24D0' <= c && c <= '\u24E9') || ('\u2C7C' <= c && c <= '\u2C7D') || - c == '\uA770' || ('\uA7F8' <= c && c <= '\uA7F9') || - getTypeGE256(c) == LOWERCASE_LETTER - } - - def isUpperCase(c: scala.Char): scala.Boolean = - isUpperCase(c.toInt) - - def isUpperCase(c: Int): scala.Boolean = { - ('\u2160' <= c && c <= '\u216F') || ('\u24B6' <= c && c <= '\u24CF') || - getType(c) == UPPERCASE_LETTER - } - - @inline def isValidCodePoint(codePoint: Int): scala.Boolean = - codePoint >= MIN_CODE_POINT && codePoint <= MAX_CODE_POINT - - @inline def isBmpCodePoint(codePoint: Int): scala.Boolean = - codePoint >= MIN_VALUE && codePoint <= MAX_VALUE - - @inline def isSupplementaryCodePoint(codePoint: Int): scala.Boolean = - codePoint >= MIN_SUPPLEMENTARY_CODE_POINT && codePoint <= MAX_CODE_POINT - - def isTitleCase(c: scala.Char): scala.Boolean = - isTitleCase(c.toInt) - - def isTitleCase(cp: Int): scala.Boolean = - if (cp < 256) false - else isTitleCaseImpl(getTypeGE256(cp)) - - @inline private[this] def isTitleCaseImpl(tpe: Int): scala.Boolean = - tpe == TITLECASE_LETTER - - def isDigit(c: scala.Char): scala.Boolean = - isDigit(c.toInt) - - def isDigit(cp: Int): scala.Boolean = - if (cp < 256) '0' <= cp && cp <= '9' - else isDigitImpl(getTypeGE256(cp)) - - @inline private[this] def isDigitImpl(tpe: Int): scala.Boolean = - tpe == DECIMAL_DIGIT_NUMBER - - def isDefined(c: scala.Char): scala.Boolean = - isDefined(c.toInt) - - def isDefined(c: scala.Int): scala.Boolean = { - if (c < 0) false - else if (c < 888) true - else getTypeGE256(c) != UNASSIGNED - } - - def isLetter(c: scala.Char): scala.Boolean = isLetter(c.toInt) - - def isLetter(cp: Int): scala.Boolean = isLetterImpl(getType(cp)) - - @inline private[this] def isLetterImpl(tpe: Int): scala.Boolean = { - tpe == UPPERCASE_LETTER || tpe == LOWERCASE_LETTER || - tpe == TITLECASE_LETTER || tpe == MODIFIER_LETTER || tpe == OTHER_LETTER - } - - def isLetterOrDigit(c: scala.Char): scala.Boolean = - isLetterOrDigit(c.toInt) - - def isLetterOrDigit(cp: Int): scala.Boolean = - isLetterOrDigitImpl(getType(cp)) - - @inline private[this] def isLetterOrDigitImpl(tpe: Int): scala.Boolean = - isDigitImpl(tpe) || isLetterImpl(tpe) - - def isJavaLetter(ch: scala.Char): scala.Boolean = isJavaLetterImpl(getType(ch)) - - @inline private[this] def isJavaLetterImpl(tpe: Int): scala.Boolean = { - isLetterImpl(tpe) || tpe == LETTER_NUMBER || tpe == CURRENCY_SYMBOL || - tpe == CONNECTOR_PUNCTUATION - } - - def isJavaLetterOrDigit(ch: scala.Char): scala.Boolean = - isJavaLetterOrDigitImpl(ch, getType(ch)) - - @inline private[this] def isJavaLetterOrDigitImpl(codePoint: Int, - tpe: Int): scala.Boolean = { - isJavaLetterImpl(tpe) || tpe == COMBINING_SPACING_MARK || - tpe == NON_SPACING_MARK || isIdentifierIgnorableImpl(codePoint, tpe) - } - - def isAlphabetic(codePoint: Int): scala.Boolean = { - val tpe = getType(codePoint) - tpe == UPPERCASE_LETTER || tpe == LOWERCASE_LETTER || - tpe == TITLECASE_LETTER || tpe == MODIFIER_LETTER || - tpe == OTHER_LETTER || tpe == LETTER_NUMBER - } - - def isIdeographic(c: Int): scala.Boolean = { - (12294 <= c && c <= 12295) || (12321 <= c && c <= 12329) || - (12344 <= c && c <= 12346) || (13312 <= c && c <= 19893) || - (19968 <= c && c <= 40908) || (63744 <= c && c <= 64109) || - (64112 <= c && c <= 64217) || (131072 <= c && c <= 173782) || - (173824 <= c && c <= 177972) || (177984 <= c && c <= 178205) || - (194560 <= c && c <= 195101) - } - - def isJavaIdentifierStart(ch: scala.Char): scala.Boolean = - isJavaIdentifierStart(ch.toInt) - - def isJavaIdentifierStart(codePoint: Int): scala.Boolean = - isJavaIdentifierStartImpl(getType(codePoint)) - - @inline - private[this] def isJavaIdentifierStartImpl(tpe: Int): scala.Boolean = { - isLetterImpl(tpe) || tpe == LETTER_NUMBER || tpe == CURRENCY_SYMBOL || - tpe == CONNECTOR_PUNCTUATION - } - - def isJavaIdentifierPart(ch: scala.Char): scala.Boolean = - isJavaIdentifierPart(ch.toInt) - - def isJavaIdentifierPart(codePoint: Int): scala.Boolean = - isJavaIdentifierPartImpl(codePoint, getType(codePoint)) - - @inline private[this] def isJavaIdentifierPartImpl(codePoint: Int, - tpe: Int): scala.Boolean = { - isLetterImpl(tpe) || tpe == CURRENCY_SYMBOL || - tpe == CONNECTOR_PUNCTUATION || tpe == DECIMAL_DIGIT_NUMBER || - tpe == LETTER_NUMBER || tpe == COMBINING_SPACING_MARK || - tpe == NON_SPACING_MARK || isIdentifierIgnorableImpl(codePoint, tpe) - } - - def isUnicodeIdentifierStart(ch: scala.Char): scala.Boolean = - isUnicodeIdentifierStart(ch.toInt) - - def isUnicodeIdentifierStart(codePoint: Int): scala.Boolean = - isUnicodeIdentifierStartImpl(getType(codePoint)) - - @inline - private[this] def isUnicodeIdentifierStartImpl(tpe: Int): scala.Boolean = - isLetterImpl(tpe) || tpe == LETTER_NUMBER - - def isUnicodeIdentifierPart(ch: scala.Char): scala.Boolean = - isUnicodeIdentifierPart(ch.toInt) - - def isUnicodeIdentifierPart(codePoint: Int): scala.Boolean = - isUnicodeIdentifierPartImpl(codePoint, getType(codePoint)) - - def isUnicodeIdentifierPartImpl(codePoint: Int, - tpe: Int): scala.Boolean = { - tpe == CONNECTOR_PUNCTUATION || tpe == DECIMAL_DIGIT_NUMBER || - tpe == COMBINING_SPACING_MARK || tpe == NON_SPACING_MARK || - isUnicodeIdentifierStartImpl(tpe) || - isIdentifierIgnorableImpl(codePoint, tpe) - } - - def isIdentifierIgnorable(c: scala.Char): scala.Boolean = - isIdentifierIgnorable(c.toInt) - - def isIdentifierIgnorable(codePoint: Int): scala.Boolean = - isIdentifierIgnorableImpl(codePoint, getType(codePoint)) - - @inline private[this] def isIdentifierIgnorableImpl(codePoint: Int, - tpe: Int): scala.Boolean = { - ('\u0000' <= codePoint && codePoint <= '\u0008') || - ('\u000E' <= codePoint && codePoint <= '\u001B') || - ('\u007F' <= codePoint && codePoint <= '\u009F') || - tpe == FORMAT - } - - def isMirrored(c: scala.Char): scala.Boolean = - isMirrored(c.toInt) - - def isMirrored(codePoint: Int): scala.Boolean = { - val idx = Arrays.binarySearch(isMirroredIndices, codePoint) + 1 - (Math.abs(idx) & 1) != 0 - } - - //def getDirectionality(c: scala.Char): scala.Byte - - /* Conversions */ - def toUpperCase(c: scala.Char): scala.Char = c.toString.toUpperCase().charAt(0) - def toLowerCase(c: scala.Char): scala.Char = c.toString.toLowerCase().charAt(0) - //def toTitleCase(c: scala.Char): scala.Char - //def getNumericValue(c: scala.Char): Int - - /* Misc */ - //def reverseBytes(ch: scala.Char): scala.Char - - def toChars(codePoint: Int): Array[Char] = { - if (!isValidCodePoint(codePoint)) - throw new IllegalArgumentException() - - if (isSupplementaryCodePoint(codePoint)) - Array(highSurrogateOf(codePoint), lowSurrogateOf(codePoint)) - else - Array(codePoint.toChar) - } - - def toChars(codePoint: Int, dst: Array[Char], dstIndex: Int): Int = { - if (!isValidCodePoint(codePoint)) - throw new IllegalArgumentException() - - if (isSupplementaryCodePoint(codePoint)) { - dst(dstIndex) = highSurrogateOf(codePoint) - dst(dstIndex + 1) = lowSurrogateOf(codePoint) - 2 - } else { - dst(dstIndex) = codePoint.toChar - 1 - } - } - - private[lang] def codePointToString(codePoint: Int): String = { - if (!isValidCodePoint(codePoint)) - throw new IllegalArgumentException() - - if (isSupplementaryCodePoint(codePoint)) - highSurrogateOf(codePoint).toString + lowSurrogateOf(codePoint).toString - else - codePoint.toChar.toString - } - - @inline private def highSurrogateOf(codePoint: Int): Char = - (0xd800 | ((codePoint >> 10) - (0x10000 >> 10))).toChar - - @inline private def lowSurrogateOf(codePoint: Int): Char = - (0xdc00 | (codePoint & 0x3ff)).toChar - - @inline def toString(c: scala.Char): String = - js.Dynamic.global.String.fromCharCode(c.toInt).asInstanceOf[String] - - @inline def compare(x: scala.Char, y: scala.Char): Int = - x - y - - // Based on Unicode 6.2.0, extended with chars 00BB, 20BC-20BF and 32FF - // Generated with OpenJDK 1.8.0_222 - - // Types of characters from 0 to 255 - private[this] lazy val charTypesFirst256: Array[Int] = Array(15, 15, 15, 15, - 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, - 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 12, 24, 24, 24, 26, 24, 24, 24, - 21, 22, 24, 25, 24, 20, 24, 24, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 24, 24, 25, - 25, 25, 24, 24, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 21, 24, 22, 27, 23, 27, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 21, 25, 22, 25, 15, 15, - 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, - 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 12, 24, 26, 26, 26, - 26, 28, 24, 27, 28, 5, 29, 25, 16, 28, 27, 28, 25, 11, 11, 27, 2, 24, 24, - 27, 11, 5, 30, 11, 11, 11, 24, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 25, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 25, 2, 2, 2, 2, 2, 2, - 2, 2) - - /* Character type data by ranges of types - * charTypeIndices: contains the index where the range ends - * charType: contains the type of the carater in the range ends - * note that charTypeIndices.length + 1 = charType.length and that the - * range 0 to 255 is not included because it is contained in charTypesFirst256 - * - * They where generated with the following script, which can be pasted into - * a Scala REPL. - -def formatLargeArray(array: Array[Int], indent: String): String = { - val indentMinus1 = indent.substring(1) - val builder = new java.lang.StringBuilder - builder.append(indentMinus1) - var curLineLength = indentMinus1.length - for (i <- 0 until array.length) { - val toAdd = " " + array(i) + (if (i == array.length - 1) "" else ",") - if (curLineLength + toAdd.length >= 80) { - builder.append("\n") - builder.append(indentMinus1) - curLineLength = indentMinus1.length - } - builder.append(toAdd) - curLineLength += toAdd.length - } - builder.toString() -} - -val indicesAndTypes = (256 to Character.MAX_CODE_POINT) - .map(i => (i, Character.getType(i))) - .foldLeft[List[(Int, Int)]](Nil) { - case (x :: xs, elem) if x._2 == elem._2 => x :: xs - case (prevs, elem) => elem :: prevs - }.reverse -val charTypeIndices = indicesAndTypes.map(_._1).tail -val charTypeIndicesDeltas = charTypeIndices - .zip(0 :: charTypeIndices.init) - .map(tup => tup._1 - tup._2) -val charTypes = indicesAndTypes.map(_._2) -println("charTypeIndices, deltas:") -println(" Array(") -println(formatLargeArray(charTypeIndicesDeltas.toArray, " ")) -println(" )") -println("charTypes:") -println(" Array(") -println(formatLargeArray(charTypes.toArray, " ")) -println(" )") - - */ - - private[this] lazy val charTypeIndices: Array[Int] = { - val deltas = Array( - 257, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, - 1, 1, 1, 1, 3, 2, 1, 1, 1, 2, 1, 3, 2, 4, 1, 2, 1, 3, 3, 2, 1, 2, 1, 1, - 1, 1, 1, 2, 1, 1, 2, 1, 1, 2, 1, 3, 1, 1, 1, 2, 2, 1, 1, 3, 4, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 3, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 7, 2, 1, 2, 2, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1, - 69, 1, 27, 18, 4, 12, 14, 5, 7, 1, 1, 1, 17, 112, 1, 1, 1, 1, 1, 1, 1, - 1, 2, 1, 3, 1, 5, 2, 1, 1, 3, 1, 1, 1, 2, 1, 17, 1, 9, 35, 1, 2, 3, 3, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, - 1, 1, 1, 1, 1, 2, 2, 51, 48, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 2, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 38, 2, 1, 6, 1, 39, 1, 1, 1, 4, 1, - 1, 45, 1, 1, 1, 2, 1, 2, 1, 1, 8, 27, 5, 3, 2, 11, 5, 1, 3, 2, 1, 2, 2, - 11, 1, 2, 2, 32, 1, 10, 21, 10, 4, 2, 1, 99, 1, 1, 7, 1, 1, 6, 2, 2, 1, - 4, 2, 10, 3, 2, 1, 14, 1, 1, 1, 1, 30, 27, 2, 89, 11, 1, 14, 10, 33, 9, - 2, 1, 3, 1, 5, 22, 4, 1, 9, 1, 3, 1, 5, 2, 15, 1, 25, 3, 2, 1, 65, 1, - 1, 11, 55, 27, 1, 3, 1, 54, 1, 1, 1, 1, 3, 8, 4, 1, 2, 1, 7, 10, 2, 2, - 10, 1, 1, 6, 1, 7, 1, 1, 2, 1, 8, 2, 2, 2, 22, 1, 7, 1, 1, 3, 4, 2, 1, - 1, 3, 4, 2, 2, 2, 2, 1, 1, 8, 1, 4, 2, 1, 3, 2, 2, 10, 2, 2, 6, 1, 1, - 5, 2, 1, 1, 6, 4, 2, 2, 22, 1, 7, 1, 2, 1, 2, 1, 2, 2, 1, 1, 3, 2, 4, - 2, 2, 3, 3, 1, 7, 4, 1, 1, 7, 10, 2, 3, 1, 11, 2, 1, 1, 9, 1, 3, 1, 22, - 1, 7, 1, 2, 1, 5, 2, 1, 1, 3, 5, 1, 2, 1, 1, 2, 1, 2, 1, 15, 2, 2, 2, - 10, 1, 1, 15, 1, 2, 1, 8, 2, 2, 2, 22, 1, 7, 1, 2, 1, 5, 2, 1, 1, 1, 1, - 1, 4, 2, 2, 2, 2, 1, 8, 1, 1, 4, 2, 1, 3, 2, 2, 10, 1, 1, 6, 10, 1, 1, - 1, 6, 3, 3, 1, 4, 3, 2, 1, 1, 1, 2, 3, 2, 3, 3, 3, 12, 4, 2, 1, 2, 3, - 3, 1, 3, 1, 2, 1, 6, 1, 14, 10, 3, 6, 1, 1, 6, 3, 1, 8, 1, 3, 1, 23, 1, - 10, 1, 5, 3, 1, 3, 4, 1, 3, 1, 4, 7, 2, 1, 2, 6, 2, 2, 2, 10, 8, 7, 1, - 2, 2, 1, 8, 1, 3, 1, 23, 1, 10, 1, 5, 2, 1, 1, 1, 1, 5, 1, 1, 2, 1, 2, - 2, 7, 2, 7, 1, 1, 2, 2, 2, 10, 1, 2, 15, 2, 1, 8, 1, 3, 1, 41, 2, 1, 3, - 4, 1, 3, 1, 3, 1, 1, 8, 1, 8, 2, 2, 2, 10, 6, 3, 1, 6, 2, 2, 1, 18, 3, - 24, 1, 9, 1, 1, 2, 7, 3, 1, 4, 3, 3, 1, 1, 1, 8, 18, 2, 1, 12, 48, 1, - 2, 7, 4, 1, 6, 1, 8, 1, 10, 2, 37, 2, 1, 1, 2, 2, 1, 1, 2, 1, 6, 4, 1, - 7, 1, 3, 1, 1, 1, 1, 2, 2, 1, 4, 1, 2, 6, 1, 2, 1, 2, 5, 1, 1, 1, 6, 2, - 10, 2, 4, 32, 1, 3, 15, 1, 1, 3, 2, 6, 10, 10, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 2, 8, 1, 36, 4, 14, 1, 5, 1, 2, 5, 11, 1, 36, 1, 8, 1, 6, 1, 2, - 5, 4, 2, 37, 43, 2, 4, 1, 6, 1, 2, 2, 2, 1, 10, 6, 6, 2, 2, 4, 3, 1, 3, - 2, 7, 3, 4, 13, 1, 2, 2, 6, 1, 1, 1, 10, 3, 1, 2, 38, 1, 1, 5, 1, 2, - 43, 1, 1, 332, 1, 4, 2, 7, 1, 1, 1, 4, 2, 41, 1, 4, 2, 33, 1, 4, 2, 7, - 1, 1, 1, 4, 2, 15, 1, 57, 1, 4, 2, 67, 2, 3, 9, 20, 3, 16, 10, 6, 85, - 11, 1, 620, 2, 17, 1, 26, 1, 1, 3, 75, 3, 3, 15, 13, 1, 4, 3, 11, 18, - 3, 2, 9, 18, 2, 12, 13, 1, 3, 1, 2, 12, 52, 2, 1, 7, 8, 1, 2, 11, 3, 1, - 3, 1, 1, 1, 2, 10, 6, 10, 6, 6, 1, 4, 3, 1, 1, 10, 6, 35, 1, 52, 8, 41, - 1, 1, 5, 70, 10, 29, 3, 3, 4, 2, 3, 4, 2, 1, 6, 3, 4, 1, 3, 2, 10, 30, - 2, 5, 11, 44, 4, 17, 7, 2, 6, 10, 1, 3, 34, 23, 2, 3, 2, 2, 53, 1, 1, - 1, 7, 1, 1, 1, 1, 2, 8, 6, 10, 2, 1, 10, 6, 10, 6, 7, 1, 6, 82, 4, 1, - 47, 1, 1, 5, 1, 1, 5, 1, 2, 7, 4, 10, 7, 10, 9, 9, 3, 2, 1, 30, 1, 4, - 2, 2, 1, 1, 2, 2, 10, 44, 1, 1, 2, 3, 1, 1, 3, 2, 8, 4, 36, 8, 8, 2, 2, - 3, 5, 10, 3, 3, 10, 30, 6, 2, 64, 8, 8, 3, 1, 13, 1, 7, 4, 1, 4, 2, 1, - 2, 9, 44, 63, 13, 1, 34, 37, 39, 21, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 8, 6, - 2, 6, 2, 8, 8, 8, 8, 6, 2, 6, 2, 8, 1, 1, 1, 1, 1, 1, 1, 1, 8, 8, 14, - 2, 8, 8, 8, 8, 8, 8, 5, 1, 2, 4, 1, 1, 1, 3, 3, 1, 2, 4, 1, 3, 4, 2, 2, - 4, 1, 3, 8, 5, 3, 2, 3, 1, 2, 4, 1, 2, 1, 11, 5, 6, 2, 1, 1, 1, 2, 1, - 1, 1, 8, 1, 1, 5, 1, 9, 1, 1, 4, 2, 3, 1, 1, 1, 11, 1, 1, 1, 10, 1, 5, - 5, 6, 1, 1, 2, 6, 3, 1, 1, 1, 10, 3, 1, 1, 1, 13, 3, 32, 16, 13, 4, 1, - 3, 12, 15, 2, 1, 4, 1, 2, 1, 3, 2, 3, 1, 1, 1, 2, 1, 5, 6, 1, 1, 1, 1, - 1, 1, 4, 1, 1, 4, 1, 4, 1, 2, 2, 2, 5, 1, 4, 1, 1, 2, 1, 1, 16, 35, 1, - 1, 4, 1, 6, 5, 5, 2, 4, 1, 2, 1, 2, 1, 7, 1, 31, 2, 2, 1, 1, 1, 31, - 268, 8, 4, 20, 2, 7, 1, 1, 81, 1, 30, 25, 40, 6, 18, 12, 39, 25, 11, - 21, 60, 78, 22, 183, 1, 9, 1, 54, 8, 111, 1, 144, 1, 103, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 30, 44, 5, 1, 1, 31, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 16, 256, 131, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 63, 1, 1, 1, 1, 32, 1, 1, 258, 48, 21, 2, 6, 3, 10, - 166, 47, 1, 47, 1, 1, 1, 3, 2, 1, 1, 1, 1, 1, 1, 4, 1, 1, 2, 1, 6, 2, - 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 2, 6, 1, 1, 1, 1, 3, 1, 1, 5, 4, 1, 2, 38, 1, 1, 5, 1, 2, 56, - 7, 1, 1, 14, 1, 23, 9, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, - 32, 2, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 9, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 5, 1, 10, 2, 68, 26, 1, 89, 12, 214, 26, 12, 4, 1, - 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 2, 1, 9, 4, 2, 1, 5, 2, 3, 1, 1, 1, 2, 1, 86, 2, 2, 2, 2, 1, 1, - 90, 1, 3, 1, 5, 41, 3, 94, 1, 2, 4, 10, 27, 5, 36, 12, 16, 31, 1, 10, - 30, 8, 1, 15, 32, 10, 39, 15, 320, 6582, 10, 64, 20941, 51, 21, 1, - 1143, 3, 55, 9, 40, 6, 2, 268, 1, 3, 16, 10, 2, 20, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 10, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 7, 1, 70, 10, 2, 6, 8, 23, 9, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 8, 1, 1, 1, 1, 2, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 77, 2, 1, 7, 1, 3, 1, 4, 1, 23, 2, 2, 1, 4, 4, 6, - 2, 1, 1, 6, 52, 4, 8, 2, 50, 16, 1, 9, 2, 10, 6, 18, 6, 3, 1, 4, 10, - 28, 8, 2, 23, 11, 2, 11, 1, 29, 3, 3, 1, 47, 1, 2, 4, 2, 1, 4, 13, 1, - 1, 10, 4, 2, 32, 41, 6, 2, 2, 2, 2, 9, 3, 1, 8, 1, 1, 2, 10, 2, 4, 16, - 1, 6, 3, 1, 1, 4, 48, 1, 1, 3, 2, 2, 5, 2, 1, 1, 1, 24, 2, 1, 2, 11, 1, - 2, 2, 2, 1, 2, 1, 1, 10, 6, 2, 6, 2, 6, 9, 7, 1, 7, 145, 35, 2, 1, 2, - 1, 2, 1, 1, 1, 2, 10, 6, 11172, 12, 23, 4, 49, 4, 2048, 6400, 366, 2, - 106, 38, 7, 12, 5, 5, 1, 1, 10, 1, 13, 1, 5, 1, 1, 1, 2, 1, 2, 1, 108, - 16, 17, 363, 1, 1, 16, 64, 2, 54, 40, 12, 1, 1, 2, 16, 7, 1, 1, 1, 6, - 7, 9, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, - 4, 3, 3, 1, 4, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 3, 1, 1, 1, 2, 4, 5, 1, - 135, 2, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 2, 10, 2, 3, 2, 26, 1, 1, 1, - 1, 1, 1, 26, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 10, 1, 45, 2, 31, 3, 6, 2, - 6, 2, 6, 2, 3, 3, 2, 1, 1, 1, 2, 1, 1, 4, 2, 10, 3, 2, 2, 12, 1, 26, 1, - 19, 1, 2, 1, 15, 2, 14, 34, 123, 5, 3, 4, 45, 3, 9, 53, 4, 17, 1, 5, - 12, 52, 45, 1, 130, 29, 3, 49, 47, 31, 1, 4, 12, 17, 1, 8, 1, 53, 30, - 1, 1, 36, 4, 8, 1, 5, 42, 40, 40, 78, 2, 10, 854, 6, 2, 1, 1, 44, 1, 2, - 3, 1, 2, 23, 1, 1, 8, 160, 22, 6, 3, 1, 26, 5, 1, 64, 56, 6, 2, 64, 1, - 3, 1, 2, 5, 4, 4, 1, 3, 1, 27, 4, 3, 4, 1, 8, 8, 9, 7, 29, 2, 1, 128, - 54, 3, 7, 22, 2, 8, 19, 5, 8, 128, 73, 535, 31, 385, 1, 1, 1, 53, 15, - 7, 4, 20, 10, 16, 2, 1, 45, 3, 4, 2, 2, 2, 1, 4, 14, 25, 7, 10, 6, 3, - 36, 5, 1, 8, 1, 10, 4, 60, 2, 1, 48, 3, 9, 2, 4, 4, 7, 10, 1190, 43, 1, - 1, 1, 2, 6, 1, 1, 8, 10, 2358, 879, 145, 99, 13, 4, 2956, 1071, 13265, - 569, 1223, 69, 11, 1, 46, 16, 4, 13, 16480, 2, 8190, 246, 10, 39, 2, - 60, 2, 3, 3, 6, 8, 8, 2, 7, 30, 4, 48, 34, 66, 3, 1, 186, 87, 9, 18, - 142, 26, 26, 26, 7, 1, 18, 26, 26, 1, 1, 2, 2, 1, 2, 2, 2, 4, 1, 8, 4, - 1, 1, 1, 7, 1, 11, 26, 26, 2, 1, 4, 2, 8, 1, 7, 1, 26, 2, 1, 4, 1, 5, - 1, 1, 3, 7, 1, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 28, 2, - 25, 1, 25, 1, 6, 25, 1, 25, 1, 6, 25, 1, 25, 1, 6, 25, 1, 25, 1, 6, 25, - 1, 25, 1, 6, 1, 1, 2, 50, 5632, 4, 1, 27, 1, 2, 1, 1, 2, 1, 1, 10, 1, - 4, 1, 1, 1, 1, 6, 1, 4, 1, 1, 1, 1, 1, 1, 3, 1, 2, 1, 1, 2, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 2, 1, 1, 2, 4, 1, 7, 1, 4, 1, 4, 1, 1, 1, 10, 1, 17, - 5, 3, 1, 5, 1, 17, 52, 2, 270, 44, 4, 100, 12, 15, 2, 14, 2, 15, 1, 15, - 32, 11, 5, 31, 1, 60, 4, 43, 75, 29, 13, 43, 5, 9, 7, 2, 174, 33, 15, - 6, 1, 70, 3, 20, 12, 37, 1, 5, 21, 17, 15, 63, 1, 1, 1, 182, 1, 4, 3, - 62, 2, 4, 12, 24, 147, 70, 4, 11, 48, 70, 58, 116, 2188, 42711, 41, - 4149, 11, 222, 16354, 542, 722403, 1, 30, 96, 128, 240, 65040, 65534, - 2, 65534 - ) - uncompressDeltas(deltas) - } - - private[this] lazy val charTypes: Array[Int] = Array( - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 5, 1, 2, 5, 1, 3, 2, 1, - 3, 2, 1, 3, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, - 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 3, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 5, 2, 4, 27, 4, 27, 4, 27, 4, 27, 4, 27, 6, 1, 2, 1, 2, 4, 27, 1, 2, 0, - 4, 2, 24, 0, 27, 1, 24, 1, 0, 1, 0, 1, 2, 1, 0, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 25, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, - 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 28, 6, 7, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 0, 1, 0, 4, 24, 0, 2, 0, 24, 20, 0, 26, 0, 6, 20, - 6, 24, 6, 24, 6, 24, 6, 0, 5, 0, 5, 24, 0, 16, 0, 25, 24, 26, 24, 28, 6, - 24, 0, 24, 5, 4, 5, 6, 9, 24, 5, 6, 5, 24, 5, 6, 16, 28, 6, 4, 6, 28, 6, - 5, 9, 5, 28, 5, 24, 0, 16, 5, 6, 5, 6, 0, 5, 6, 5, 0, 9, 5, 6, 4, 28, 24, - 4, 0, 5, 6, 4, 6, 4, 6, 4, 6, 0, 24, 0, 5, 6, 0, 24, 0, 5, 0, 5, 0, 6, 0, - 6, 8, 5, 6, 8, 6, 5, 8, 6, 8, 6, 8, 5, 6, 5, 6, 24, 9, 24, 4, 5, 0, 5, 0, - 6, 8, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 6, 5, 8, 6, 0, 8, 0, 8, 6, - 5, 0, 8, 0, 5, 0, 5, 6, 0, 9, 5, 26, 11, 28, 26, 0, 6, 8, 0, 5, 0, 5, 0, - 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 6, 0, 8, 6, 0, 6, 0, 6, 0, 6, 0, 5, 0, 5, - 0, 9, 6, 5, 6, 0, 6, 8, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 6, 5, 8, - 6, 0, 6, 8, 0, 8, 6, 0, 5, 0, 5, 6, 0, 9, 24, 26, 0, 6, 8, 0, 5, 0, 5, 0, - 5, 0, 5, 0, 5, 0, 5, 0, 6, 5, 8, 6, 8, 6, 0, 8, 0, 8, 6, 0, 6, 8, 0, 5, - 0, 5, 6, 0, 9, 28, 5, 11, 0, 6, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, - 5, 0, 5, 0, 5, 0, 8, 6, 8, 0, 8, 0, 8, 6, 0, 5, 0, 8, 0, 9, 11, 28, 26, - 28, 0, 8, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 6, 8, 0, 6, 0, 6, 0, 6, 0, - 5, 0, 5, 6, 0, 9, 0, 11, 28, 0, 8, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 6, 5, - 8, 6, 8, 0, 6, 8, 0, 8, 6, 0, 8, 0, 5, 0, 5, 6, 0, 9, 0, 5, 0, 8, 0, 5, - 0, 5, 0, 5, 0, 5, 8, 6, 0, 8, 0, 8, 6, 5, 0, 8, 0, 5, 6, 0, 9, 11, 0, 28, - 5, 0, 8, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 6, 0, 8, 6, 0, 6, 0, 8, 0, 8, - 24, 0, 5, 6, 5, 6, 0, 26, 5, 4, 6, 24, 9, 24, 0, 5, 0, 5, 0, 5, 0, 5, 0, - 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 6, 5, 6, 0, 6, 5, 0, 5, 0, - 4, 0, 6, 0, 9, 0, 5, 0, 5, 28, 24, 28, 24, 28, 6, 28, 9, 11, 28, 6, 28, - 6, 28, 6, 21, 22, 21, 22, 8, 5, 0, 5, 0, 6, 8, 6, 24, 6, 5, 6, 0, 6, 0, - 28, 6, 28, 0, 28, 24, 28, 24, 0, 5, 8, 6, 8, 6, 8, 6, 8, 6, 5, 9, 24, 5, - 8, 6, 5, 6, 5, 8, 5, 8, 5, 6, 5, 6, 8, 6, 8, 6, 5, 8, 9, 8, 6, 28, 1, 0, - 1, 0, 1, 0, 5, 24, 4, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, - 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 6, 24, 11, 0, 5, 28, 0, 5, - 0, 20, 5, 24, 5, 12, 5, 21, 22, 0, 5, 24, 10, 0, 5, 0, 5, 6, 0, 5, 6, 24, - 0, 5, 6, 0, 5, 0, 5, 0, 6, 0, 5, 6, 8, 6, 8, 6, 8, 6, 24, 4, 24, 26, 5, - 6, 0, 9, 0, 11, 0, 24, 20, 24, 6, 12, 0, 9, 0, 5, 4, 5, 0, 5, 6, 5, 0, 5, - 0, 5, 0, 6, 8, 6, 8, 0, 8, 6, 8, 6, 0, 28, 0, 24, 9, 5, 0, 5, 0, 5, 0, 8, - 5, 8, 0, 9, 11, 0, 28, 5, 6, 8, 0, 24, 5, 8, 6, 8, 6, 0, 6, 8, 6, 8, 6, - 8, 6, 0, 6, 9, 0, 9, 0, 24, 4, 24, 0, 6, 8, 5, 6, 8, 6, 8, 6, 8, 6, 8, 5, - 0, 9, 24, 28, 6, 28, 0, 6, 8, 5, 8, 6, 8, 6, 8, 6, 8, 5, 9, 5, 6, 8, 6, - 8, 6, 8, 6, 8, 0, 24, 5, 8, 6, 8, 6, 0, 24, 9, 0, 5, 9, 5, 4, 24, 0, 24, - 0, 6, 24, 6, 8, 6, 5, 6, 5, 8, 6, 5, 0, 2, 4, 2, 4, 2, 4, 6, 0, 6, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 0, 1, 0, 2, 1, 2, 1, 2, 0, 1, 0, 2, 0, 1, 0, 1, - 0, 1, 0, 1, 2, 1, 2, 0, 2, 3, 2, 3, 2, 3, 2, 0, 2, 1, 3, 27, 2, 27, 2, 0, - 2, 1, 3, 27, 2, 0, 2, 1, 0, 27, 2, 1, 27, 0, 2, 0, 2, 1, 3, 27, 0, 12, - 16, 20, 24, 29, 30, 21, 29, 30, 21, 29, 24, 13, 14, 16, 12, 24, 29, 30, - 24, 23, 24, 25, 21, 22, 24, 25, 24, 23, 24, 12, 16, 0, 16, 11, 4, 0, 11, - 25, 21, 22, 4, 11, 25, 21, 22, 0, 4, 0, 26, 0, 6, 7, 6, 7, 6, 0, 28, 1, - 28, 1, 28, 2, 1, 2, 1, 2, 28, 1, 28, 25, 1, 28, 1, 28, 1, 28, 1, 28, 1, - 28, 2, 1, 2, 5, 2, 28, 2, 1, 25, 1, 2, 28, 25, 28, 2, 28, 11, 10, 1, 2, - 10, 11, 0, 25, 28, 25, 28, 25, 28, 25, 28, 25, 28, 25, 28, 25, 28, 25, - 28, 25, 28, 25, 28, 25, 28, 25, 28, 21, 22, 28, 25, 28, 25, 28, 25, 28, - 0, 28, 0, 28, 0, 11, 28, 11, 28, 25, 28, 25, 28, 25, 28, 25, 28, 0, 28, - 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 11, 28, 25, 21, - 22, 25, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 25, 28, 25, 21, 22, 21, - 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, - 22, 25, 21, 22, 21, 22, 25, 21, 22, 25, 28, 25, 28, 25, 0, 28, 0, 1, 0, - 2, 0, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 4, 1, 2, 1, 2, 1, - 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, - 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, - 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, - 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 28, - 1, 2, 1, 2, 6, 1, 2, 0, 24, 11, 24, 2, 0, 2, 0, 2, 0, 5, 0, 4, 24, 0, 6, - 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 6, 24, 29, 30, 29, - 30, 24, 29, 30, 24, 29, 30, 24, 20, 24, 20, 24, 29, 30, 24, 29, 30, 21, - 22, 21, 22, 21, 22, 21, 22, 24, 4, 24, 20, 0, 28, 0, 28, 0, 28, 0, 28, 0, - 12, 24, 28, 4, 5, 10, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 28, 21, 22, - 21, 22, 21, 22, 21, 22, 20, 21, 22, 28, 10, 6, 8, 20, 4, 28, 10, 4, 5, - 24, 28, 0, 5, 0, 6, 27, 4, 5, 20, 5, 24, 4, 5, 0, 5, 0, 5, 0, 28, 11, 28, - 5, 0, 28, 0, 5, 28, 0, 11, 28, 11, 28, 11, 28, 11, 28, 11, 28, 5, 0, 28, - 5, 0, 5, 4, 5, 0, 28, 0, 5, 4, 24, 5, 4, 24, 5, 9, 5, 0, 1, 2, 1, 2, 1, - 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, - 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 5, 6, 7, 24, 6, 24, 4, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 0, 6, 5, 10, 6, 24, 0, 27, 4, 27, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, - 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, - 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, - 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 4, 2, 1, 2, 1, 2, 1, 2, 1, - 2, 1, 2, 1, 2, 1, 2, 4, 27, 1, 2, 1, 2, 0, 1, 2, 1, 2, 0, 1, 2, 1, 2, 1, - 2, 1, 2, 1, 2, 1, 0, 4, 2, 5, 6, 5, 6, 5, 6, 5, 8, 6, 8, 28, 0, 11, 28, - 26, 28, 0, 5, 24, 0, 8, 5, 8, 6, 0, 24, 9, 0, 6, 5, 24, 5, 0, 9, 5, 6, - 24, 5, 6, 8, 0, 24, 5, 0, 6, 8, 5, 6, 8, 6, 8, 6, 8, 24, 0, 4, 9, 0, 24, - 0, 5, 6, 8, 6, 8, 6, 0, 5, 6, 5, 6, 8, 0, 9, 0, 24, 5, 4, 5, 28, 5, 8, 0, - 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 0, 5, 4, 24, 5, 8, 6, 8, 24, 5, 4, 8, 6, - 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 8, 6, 8, 6, 8, 24, 8, 6, 0, 9, 0, 5, - 0, 5, 0, 5, 0, 19, 18, 5, 0, 5, 0, 2, 0, 2, 0, 5, 6, 5, 25, 5, 0, 5, 0, - 5, 0, 5, 0, 5, 0, 5, 27, 0, 5, 21, 22, 0, 5, 0, 5, 0, 5, 26, 28, 0, 6, - 24, 21, 22, 24, 0, 6, 0, 24, 20, 23, 21, 22, 21, 22, 21, 22, 21, 22, 21, - 22, 21, 22, 21, 22, 21, 22, 24, 21, 22, 24, 23, 24, 0, 24, 20, 21, 22, - 21, 22, 21, 22, 24, 25, 20, 25, 0, 24, 26, 24, 0, 5, 0, 5, 0, 16, 0, 24, - 26, 24, 21, 22, 24, 25, 24, 20, 24, 9, 24, 25, 24, 1, 21, 24, 22, 27, 23, - 27, 2, 21, 25, 22, 25, 21, 22, 24, 21, 22, 24, 5, 4, 5, 4, 5, 0, 5, 0, 5, - 0, 5, 0, 5, 0, 26, 25, 27, 28, 26, 0, 28, 25, 28, 0, 16, 28, 0, 5, 0, 5, - 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 24, 0, 11, 0, 28, 10, 11, 28, 11, 0, 28, - 0, 28, 6, 0, 5, 0, 5, 0, 5, 0, 11, 0, 5, 10, 5, 10, 0, 5, 0, 24, 5, 0, 5, - 24, 10, 0, 1, 2, 5, 0, 9, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 24, 11, - 0, 5, 11, 0, 24, 5, 0, 24, 0, 5, 0, 5, 0, 5, 6, 0, 6, 0, 6, 5, 0, 5, 0, - 5, 0, 6, 0, 6, 11, 0, 24, 0, 5, 11, 24, 0, 5, 0, 24, 5, 0, 11, 5, 0, 11, - 0, 5, 0, 11, 0, 8, 6, 8, 5, 6, 24, 0, 11, 9, 0, 6, 8, 5, 8, 6, 8, 6, 24, - 16, 24, 0, 5, 0, 9, 0, 6, 5, 6, 8, 6, 0, 9, 24, 0, 6, 8, 5, 8, 6, 8, 5, - 24, 0, 9, 0, 5, 6, 8, 6, 8, 6, 8, 6, 0, 9, 0, 5, 0, 10, 0, 24, 0, 5, 0, - 5, 0, 5, 0, 5, 8, 0, 6, 4, 0, 5, 0, 28, 0, 28, 0, 28, 8, 6, 28, 8, 16, 6, - 28, 6, 28, 6, 28, 0, 28, 6, 28, 0, 28, 0, 11, 0, 1, 2, 1, 2, 0, 2, 1, 2, - 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 0, 2, 0, 2, 0, 2, 1, 2, 1, 0, 1, 0, - 1, 0, 1, 0, 2, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 0, 1, 25, 2, 25, 2, 1, 25, 2, 25, 2, 1, 25, 2, 25, 2, 1, 25, - 2, 25, 2, 1, 25, 2, 25, 2, 1, 2, 0, 9, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, - 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, - 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, - 5, 0, 5, 0, 5, 0, 5, 0, 25, 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, - 11, 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, - 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, - 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, 5, 0, 5, 0, 5, 0, 5, 0, 16, 0, 16, 0, - 6, 0, 18, 0, 18, 0 - ) - - /* Indices representing the start of ranges of codePoint that have the same - * `isMirrored` result. It is true for the first range - * (i.e. isMirrored(40)==true, isMirrored(41)==true, isMirrored(42)==false) - * They where generated with the following script, which can be pasted into - * a Scala REPL. - -val indicesAndRes = (0 to Character.MAX_CODE_POINT) - .map(i => (i, Character.isMirrored(i))) - .foldLeft[List[(Int, Boolean)]](Nil) { - case (x :: xs, elem) if x._2 == elem._2 => x :: xs - case (prevs, elem) => elem :: prevs - }.reverse -val isMirroredIndices = indicesAndRes.map(_._1).tail -val isMirroredIndicesDeltas = isMirroredIndices - .zip(0 :: isMirroredIndices.init) - .map(tup => tup._1 - tup._2) -println("isMirroredIndices, deltas:") -println(" Array(") -println(formatLargeArray(isMirroredIndicesDeltas.toArray, " ")) -println(" )") - - */ - private[this] lazy val isMirroredIndices: Array[Int] = { - val deltas = Array( - 40, 2, 18, 1, 1, 1, 28, 1, 1, 1, 29, 1, 1, 1, 45, 1, 15, 1, 3710, 4, - 1885, 2, 2460, 2, 10, 2, 54, 2, 14, 2, 177, 1, 192, 4, 3, 6, 3, 1, 3, - 2, 3, 4, 1, 4, 1, 1, 1, 1, 4, 9, 5, 1, 1, 18, 5, 4, 9, 2, 1, 1, 1, 8, - 2, 31, 2, 4, 5, 1, 9, 2, 2, 19, 5, 2, 9, 5, 2, 2, 4, 24, 2, 16, 8, 4, - 20, 2, 7, 2, 1085, 14, 74, 1, 2, 4, 1, 2, 1, 3, 5, 4, 5, 3, 3, 14, 403, - 22, 2, 21, 8, 1, 7, 6, 3, 1, 4, 5, 1, 2, 2, 5, 4, 1, 1, 3, 2, 2, 10, 6, - 2, 2, 12, 19, 1, 4, 2, 1, 1, 1, 2, 1, 1, 4, 5, 2, 6, 3, 24, 2, 11, 2, - 4, 4, 1, 2, 2, 2, 4, 43, 2, 8, 1, 40, 5, 1, 1, 1, 3, 5, 5, 3, 4, 1, 3, - 5, 1, 1, 772, 4, 3, 2, 1, 2, 14, 2, 2, 10, 478, 10, 2, 8, 52797, 6, 5, - 2, 162, 2, 18, 1, 1, 1, 28, 1, 1, 1, 29, 1, 1, 1, 1, 2, 1, 2, 55159, 1, - 57, 1, 57, 1, 57, 1, 57, 1 - ) - uncompressDeltas(deltas) - } - - private[this] def uncompressDeltas(deltas: Array[Int]): Array[Int] = { - var acc = deltas(0) - var i = 1 - val len = deltas.length - while (i != len) { - acc += deltas(i) - deltas(i) = acc - i += 1 - } - deltas - } - - /** All the non-ASCII code points that map to the digit 0. - * - * Each of them is directly followed by 9 other code points mapping to the - * digits 1 to 9, in order. Conversely, there are no other non-ASCII code - * point mapping to digits from 0 to 9. - */ - private[this] lazy val nonASCIIZeroDigitCodePoints: Array[Int] = { - Array(0x660, 0x6f0, 0x7c0, 0x966, 0x9e6, 0xa66, 0xae6, 0xb66, 0xbe6, - 0xc66, 0xce6, 0xd66, 0xe50, 0xed0, 0xf20, 0x1040, 0x1090, 0x17e0, - 0x1810, 0x1946, 0x19d0, 0x1a80, 0x1a90, 0x1b50, 0x1bb0, 0x1c40, 0x1c50, - 0xa620, 0xa8d0, 0xa900, 0xa9d0, 0xaa50, 0xabf0, 0xff10, 0x104a0, - 0x11066, 0x110f0, 0x11136, 0x111d0, 0x116c0, 0x1d7ce, 0x1d7d8, 0x1d7e2, - 0x1d7ec, 0x1d7f6) - } -} diff --git a/javalanglib/src/main/scala/java/lang/Class.scala b/javalanglib/src/main/scala/java/lang/Class.scala deleted file mode 100644 index b1937f2a42..0000000000 --- a/javalanglib/src/main/scala/java/lang/Class.scala +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package java.lang - -import scala.scalajs.js - -@js.native -private trait ScalaJSClassData[A] extends js.Object { - val name: String = js.native - val isPrimitive: scala.Boolean = js.native - val isInterface: scala.Boolean = js.native - val isArrayClass: scala.Boolean = js.native - val isRawJSType: scala.Boolean = js.native - - def isInstance(obj: Object): scala.Boolean = js.native - def getFakeInstance(): Object = js.native - - def getSuperclass(): Class[_ >: A] = js.native - def getComponentType(): Class[_] = js.native - - def newArrayOfThisClass(dimensions: js.Array[Int]): AnyRef = js.native -} - -final class Class[A] private (data: ScalaJSClassData[A]) extends Object { - - override def toString(): String = { - (if (isInterface()) "interface " else - if (isPrimitive()) "" else "class ")+getName() - } - - def isInstance(obj: Object): scala.Boolean = - data.isInstance(obj) - - def isAssignableFrom(that: Class[_]): scala.Boolean = { - import scala.Predef.classOf - - if (this.isPrimitive || that.isPrimitive) { - /* This differs from the JVM specification to mimic the behavior of - * runtime type tests of primitive numeric types. - */ - (this eq that) || { - if (this eq classOf[scala.Short]) - (that eq classOf[scala.Byte]) - else if (this eq classOf[scala.Int]) - (that eq classOf[scala.Byte]) || (that eq classOf[scala.Short]) - else if (this eq classOf[scala.Float]) - (that eq classOf[scala.Byte]) || (that eq classOf[scala.Short]) || - (that eq classOf[scala.Int]) - else if (this eq classOf[scala.Double]) - (that eq classOf[scala.Byte]) || (that eq classOf[scala.Short]) || - (that eq classOf[scala.Int]) || (that eq classOf[scala.Float]) - else - false - } - } else { - this.isInstance(that.getFakeInstance()) - } - } - - private def getFakeInstance(): Object = - data.getFakeInstance() - - def isInterface(): scala.Boolean = - data.isInterface - - def isArray(): scala.Boolean = - data.isArrayClass - - def isPrimitive(): scala.Boolean = - data.isPrimitive - - private def isRawJSType(): scala.Boolean = - data.isRawJSType - - def getName(): String = - data.name - - def getSimpleName(): String = { - val name = data.name - var idx = name.length - 1 - while (idx >= 0 && name.charAt(idx) == '$') { - idx -= 1 - } - while (idx >= 0 && { - val currChar = name.charAt(idx) - currChar != '.' && currChar != '$' - }) { - idx -= 1 - } - name.substring(idx + 1) - } - - def getSuperclass(): Class[_ >: A] = - data.getSuperclass() - - def getComponentType(): Class[_] = - data.getComponentType() - - @inline // optimize for the Unchecked case, where this becomes identity() - def cast(obj: Object): A = { - scala.scalajs.runtime.SemanticsUtils.asInstanceOfCheck( - (obj != null && !isRawJSType && !isInstance(obj)), - new ClassCastException("" + obj + " is not an instance of " + getName)) - obj.asInstanceOf[A] - } - - // java.lang.reflect.Array support - - private[lang] def newArrayOfThisClass(dimensions: js.Array[Int]): AnyRef = - data.newArrayOfThisClass(dimensions) -} diff --git a/javalanglib/src/main/scala/java/lang/Double.scala b/javalanglib/src/main/scala/java/lang/Double.scala deleted file mode 100644 index 0b7b2a0933..0000000000 --- a/javalanglib/src/main/scala/java/lang/Double.scala +++ /dev/null @@ -1,332 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package java.lang - -import scala.scalajs.js - -/* This is a hijacked class. Its instances are primitive numbers. - * Constructors are not emitted. - */ -final class Double private () extends Number with Comparable[Double] { - - def this(value: scala.Double) = this() - def this(s: String) = this() - - @inline def doubleValue(): scala.Double = - this.asInstanceOf[scala.Double] - - @inline override def byteValue(): scala.Byte = doubleValue.toByte - @inline override def shortValue(): scala.Short = doubleValue.toShort - @inline def intValue(): scala.Int = doubleValue.toInt - @inline def longValue(): scala.Long = doubleValue.toLong - @inline def floatValue(): scala.Float = doubleValue.toFloat - - override def equals(that: Any): scala.Boolean = that match { - case that: Double => - val a = doubleValue - val b = that.doubleValue - (a == b) || (Double.isNaN(a) && Double.isNaN(b)) - case _ => - false - } - - @inline override def hashCode(): Int = - Double.hashCode(doubleValue) - - @inline override def compareTo(that: Double): Int = - Double.compare(doubleValue, that.doubleValue) - - @inline override def toString(): String = - Double.toString(doubleValue) - - @inline def isNaN(): scala.Boolean = - Double.isNaN(doubleValue) - - @inline def isInfinite(): scala.Boolean = - Double.isInfinite(doubleValue) - -} - -object Double { - final val TYPE = scala.Predef.classOf[scala.Double] - final val POSITIVE_INFINITY = 1.0 / 0.0 - final val NEGATIVE_INFINITY = 1.0 / -0.0 - final val NaN = 0.0 / 0.0 - final val MAX_VALUE = scala.Double.MaxValue - final val MIN_NORMAL = 2.2250738585072014e-308 - final val MIN_VALUE = scala.Double.MinPositiveValue - final val MAX_EXPONENT = 1023 - final val MIN_EXPONENT = -1022 - final val SIZE = 64 - final val BYTES = 8 - - @inline def valueOf(doubleValue: scala.Double): Double = - new Double(doubleValue) - - @inline def valueOf(s: String): Double = valueOf(parseDouble(s)) - - private[this] lazy val doubleStrPat = new js.RegExp( - "^" + - "[\\x00-\\x20]*(" + // optional whitespace - "[+-]?" + // optional sign - "(?:NaN|Infinity|" + // special cases - "(?:\\d+\\.?\\d*|" + // literal w/ leading digit - "\\.\\d+)" + // literal w/o leading digit - "(?:[eE][+-]?\\d+)?" + // optional exponent - ")[fFdD]?" + // optional float / double specifier (ignored) - ")[\\x00-\\x20]*" + // optional whitespace - "$") - - private[this] lazy val doubleStrHexPat = new js.RegExp( - "^" + - "[\\x00-\\x20]*" + // optional whitespace - "([+-]?)" + // optional sign - "0[xX]" + // hex marker - "([0-9A-Fa-f]*)" + // integral part - "\\.?([0-9A-Fa-f]*)" + // fractional part - "[pP]([+-]?\\d+)" + // binary exponent - "[fFdD]?" + // optional float / double specifier (ignored) - "[\\x00-\\x20]*" + // optional whitespace - "$") - - def parseDouble(s: String): scala.Double = { - def fail(): Nothing = - throw new NumberFormatException(s"""For input string: "$s"""") - - // (Very) slow path for hexadecimal notation - def parseHexDoubleImpl(match2: js.RegExp.ExecResult): scala.Double = { - // scalastyle:off return - - val signStr = match2(1).asInstanceOf[String] - val integralPartStr = match2(2).asInstanceOf[String] - val fractionalPartStr = match2(3).asInstanceOf[String] - val binaryExpStr = match2(4).asInstanceOf[String] - - if (integralPartStr == "" && fractionalPartStr == "") - fail() - - /* We concatenate the integral part and fractional part together, then - * we parse the result as an integer. This means that we need to remember - * a correction to be applied to the final result, as a diff to the - * binary exponent - */ - val mantissaStr0 = integralPartStr + fractionalPartStr - val correction1 = -(fractionalPartStr.length * 4) // 1 hex == 4 bits - - /* Remove leading 0's in `mantissaStr`, because our algorithm assumes - * that there is none. - */ - var i = 0 - while (i != mantissaStr0.length && mantissaStr0.charAt(i) == '0') - i += 1 - val mantissaStr = mantissaStr0.substring(i) - - /* If the mantissa is empty, it means there were only 0's, and we - * short-cut to directly returning 0.0 or -0.0. This is important because - * the final step of the algorithm (multiplying by `correctingPow`) - * assumes that `mantissa` is non-zero in the case of overflow. - */ - if (mantissaStr == "") { - if (signStr == "-") - return -0.0 - else - return 0.0 - } - - /* If there are more than 15 characters left, we cut them out. They will - * never influence the result because of the limited precision of - * doubles. Note that the 15th character itself gets lost too, but can - * influence the *rounding* applied to the 14th character. - * - * We need to cut them out for corner cases where the full `mantissaStr` - * would parse as Infinity because it is too large, but where the binary - * exponent can "fix it" by being sufficiently under 0. - * - * Of course, we remember that we need to apply a correction to the - * exponent of the final result. - */ - val needsCorrection2 = mantissaStr.length > 15 - val truncatedMantissaStr = - if (needsCorrection2) mantissaStr.substring(0, 15) - else mantissaStr - val correction2 = - if (needsCorrection2) (mantissaStr.length - 15) * 4 // one hex == 4 bits - else 0 - - val fullCorrection = correction1 + correction2 - - /* Note that we do not care too much about overflows and underflows when - * manipulating binary exponents and corrections, because the corrections - * are directly related to the length of the input string, so they cannot - * be *that* big (or we have bigger problems), and the final result needs - * to fit in the [-1074, 1023] range, which can only happen if the - * `binaryExp` (see below) did not stray too far from that range itself. - */ - - val mantissa = - js.Dynamic.global.parseInt(truncatedMantissaStr, 16).asInstanceOf[scala.Double] - // Assert: mantissa != 0.0 && mantissa != scala.Double.PositiveInfinity - - val binaryExpDouble = - js.Dynamic.global.parseInt(binaryExpStr, 10).asInstanceOf[scala.Double] - val binaryExp = binaryExpDouble.toInt // caps to [MinValue, MaxValue] - - val binExpAndCorrection = binaryExp + fullCorrection - - /* If `baseExponent` is the IEEE exponent of `mantissa`, then - * `binExpAndCorrection + baseExponent` must be in the valid range of - * IEEE exponents, which is [-1074, 1023]. Therefore, if - * `binExpAndCorrection` is out of twice that range, we will end up with - * an overflow or an underflow anyway. - * - * If it is inside twice that range, then we need to multiply `mantissa` - * by `Math.pow(2, binExpAndCorrection)`. However that `pow` could - * overflow or underflow itself, so we cut it in 3 parts. If that does - * not suffice for it not to overflow or underflow, it's because it - * wasn't in the safe range to begin with. - */ - val binExpAndCorrection_div_3 = binExpAndCorrection / 3 - val correctingPow = Math.pow(2, binExpAndCorrection_div_3) - val correctingPow3 = - Math.pow(2, binExpAndCorrection - 2*binExpAndCorrection_div_3) - - val r = ((mantissa * correctingPow) * correctingPow) * correctingPow3 - - if (signStr == "-") -r - else r - - // scalastyle:on return - } - - val match1 = doubleStrPat.exec(s) - if (match1 != null) { - js.Dynamic.global.parseFloat(match1(1)).asInstanceOf[scala.Double] - } else { - val match2 = doubleStrHexPat.exec(s) - if (match2 != null) - parseHexDoubleImpl(match2) - else - fail() - } - } - - @inline def toString(d: scala.Double): String = - "" + d - - def toHexString(d: scala.Double): String = { - val ebits = 11 // exponent size - val mbits = 52 // mantissa size - val bias = (1 << (ebits - 1)) - 1 - - val bits = doubleToLongBits(d) - val s = bits < 0 - val m = bits & ((1L << mbits) - 1L) - val e = (bits >>> mbits).toInt & ((1 << ebits) - 1) // biased - - val posResult = if (e > 0) { - if (e == (1 << ebits) - 1) { - // Special - if (m != 0L) "NaN" - else "Infinity" - } else { - // Normalized - "0x1." + mantissaToHexString(m) + "p" + (e - bias) - } - } else { - if (m != 0L) { - // Subnormal - "0x0." + mantissaToHexString(m) + "p-1022" - } else { - // Zero - "0x0.0p0" - } - } - - if (bits < 0) "-" + posResult else posResult - } - - @inline - private def mantissaToHexString(m: scala.Long): String = - mantissaToHexStringLoHi(m.toInt, (m >>> 32).toInt) - - private def mantissaToHexStringLoHi(lo: Int, hi: Int): String = { - @inline def padHex5(i: Int): String = { - val s = Integer.toHexString(i) - "00000".substring(s.length) + s // 5 zeros - } - - @inline def padHex8(i: Int): String = { - val s = Integer.toHexString(i) - "00000000".substring(s.length) + s // 8 zeros - } - - val padded = padHex5(hi) + padHex8(lo) - - var len = padded.length - while (len > 1 && padded.charAt(len - 1) == '0') - len -= 1 - padded.substring(0, len) - } - - def compare(a: scala.Double, b: scala.Double): scala.Int = { - // NaN must equal itself, and be greater than anything else - if (isNaN(a)) { - if (isNaN(b)) 0 - else 1 - } else if (isNaN(b)) { - -1 - } else { - if (a == b) { - // -0.0 must be smaller than 0.0 - if (a == 0.0) { - val ainf = 1.0/a - if (ainf == 1.0/b) 0 - else if (ainf < 0) -1 - else 1 - } else { - 0 - } - } else { - if (a < b) -1 - else 1 - } - } - } - - @inline def isNaN(v: scala.Double): scala.Boolean = - v != v - - @inline def isInfinite(v: scala.Double): scala.Boolean = - v == POSITIVE_INFINITY || v == NEGATIVE_INFINITY - - @inline def isFinite(d: scala.Double): scala.Boolean = - !isNaN(d) && !isInfinite(d) - - @inline def hashCode(value: scala.Double): Int = - scala.scalajs.runtime.Bits.numberHashCode(value) - - @inline def longBitsToDouble(bits: scala.Long): scala.Double = - scala.scalajs.runtime.Bits.longBitsToDouble(bits) - - @inline def doubleToLongBits(value: scala.Double): scala.Long = - scala.scalajs.runtime.Bits.doubleToLongBits(value) - - @inline def sum(a: scala.Double, b: scala.Double): scala.Double = - a + b - - @inline def max(a: scala.Double, b: scala.Double): scala.Double = - Math.max(a, b) - - @inline def min(a: scala.Double, b: scala.Double): scala.Double = - Math.min(a, b) -} diff --git a/javalanglib/src/main/scala/java/lang/Float.scala b/javalanglib/src/main/scala/java/lang/Float.scala deleted file mode 100644 index 91abeb7071..0000000000 --- a/javalanglib/src/main/scala/java/lang/Float.scala +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package java.lang - -/* This is a hijacked class. Its instances are primitive numbers. - * Constructors are not emitted. - */ -final class Float private () extends Number with Comparable[Float] { - - def this(value: scala.Float) = this() - def this(s: String) = this() - - @inline def floatValue(): scala.Float = - this.asInstanceOf[scala.Float] - - @inline override def byteValue(): scala.Byte = floatValue.toByte - @inline override def shortValue(): scala.Short = floatValue.toShort - @inline def intValue(): scala.Int = floatValue.toInt - @inline def longValue(): scala.Long = floatValue.toLong - @inline def doubleValue(): scala.Double = floatValue.toDouble - - override def equals(that: Any): scala.Boolean = that match { - case that: Double => // yes, Double - val a = doubleValue - val b = that.doubleValue - (a == b) || (Double.isNaN(a) && Double.isNaN(b)) - case _ => - false - } - - @inline override def hashCode(): Int = - Float.hashCode(floatValue) - - @inline override def compareTo(that: Float): Int = - Float.compare(floatValue, that.floatValue) - - @inline override def toString(): String = - Float.toString(floatValue) - - @inline def isNaN(): scala.Boolean = - Float.isNaN(floatValue) - - @inline def isInfinite(): scala.Boolean = - Float.isInfinite(floatValue) - -} - -object Float { - final val TYPE = scala.Predef.classOf[scala.Float] - final val POSITIVE_INFINITY = 1.0f / 0.0f - final val NEGATIVE_INFINITY = 1.0f / -0.0f - final val NaN = 0.0f / 0.0f - final val MAX_VALUE = scala.Float.MaxValue - final val MIN_NORMAL = 1.17549435e-38f - final val MIN_VALUE = scala.Float.MinPositiveValue - final val MAX_EXPONENT = 127 - final val MIN_EXPONENT = -126 - final val SIZE = 32 - final val BYTES = 4 - - @inline def valueOf(floatValue: scala.Float): Float = new Float(floatValue) - - @inline def valueOf(s: String): Float = valueOf(parseFloat(s)) - - @inline def parseFloat(s: String): scala.Float = - Double.parseDouble(s).toFloat - - @inline def toString(f: scala.Float): String = - "" + f - - def toHexString(f: scala.Float): String = { - val ebits = 8 // exponent size - val mbits = 23 // mantissa size - val bias = (1 << (ebits - 1)) - 1 - - val bits = floatToIntBits(f) - val s = bits < 0 - val m = bits & ((1 << mbits) - 1) - val e = (bits >>> mbits).toInt & ((1 << ebits) - 1) // biased - - val posResult = if (e > 0) { - if (e == (1 << ebits) - 1) { - // Special - if (m != 0) "NaN" - else "Infinity" - } else { - // Normalized - "0x1." + mantissaToHexString(m) + "p" + (e - bias) - } - } else { - if (m != 0) { - // Subnormal - "0x0." + mantissaToHexString(m) + "p-126" - } else { - // Zero - "0x0.0p0" - } - } - - if (bits < 0) "-" + posResult else posResult - } - - @inline - private def mantissaToHexString(m: Int): String = { - @inline def padHex6(i: Int): String = { - val s = Integer.toHexString(i) - "000000".substring(s.length) + s // 6 zeros - } - - // The << 1 turns `m` from a 23-bit int into a 24-bit int (multiple of 4) - val padded = padHex6(m << 1) - var len = padded.length - while (len > 1 && padded.charAt(len - 1) == '0') - len -= 1 - padded.substring(0, len) - } - - @inline def compare(a: scala.Float, b: scala.Float): scala.Int = - Double.compare(a, b) - - @inline def isNaN(v: scala.Float): scala.Boolean = - v != v - - @inline def isInfinite(v: scala.Float): scala.Boolean = - v == POSITIVE_INFINITY || v == NEGATIVE_INFINITY - - @inline def isFinite(f: scala.Float): scala.Boolean = - !isNaN(f) && !isInfinite(f) - - // Uses the hashCode of Doubles. See Bits.numberHashCode for the rationale. - @inline def hashCode(value: scala.Float): Int = - scala.scalajs.runtime.Bits.numberHashCode(value) - - @inline def intBitsToFloat(bits: scala.Int): scala.Float = - scala.scalajs.runtime.Bits.intBitsToFloat(bits) - - @inline def floatToIntBits(value: scala.Float): scala.Int = - scala.scalajs.runtime.Bits.floatToIntBits(value) - - @inline def sum(a: scala.Float, b: scala.Float): scala.Float = - a + b - - @inline def max(a: scala.Float, b: scala.Float): scala.Float = - Math.max(a, b) - - @inline def min(a: scala.Float, b: scala.Float): scala.Float = - Math.min(a, b) -} diff --git a/javalanglib/src/main/scala/java/lang/Runtime.scala b/javalanglib/src/main/scala/java/lang/Runtime.scala deleted file mode 100644 index 8e1acd40a6..0000000000 --- a/javalanglib/src/main/scala/java/lang/Runtime.scala +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package java.lang - -import scala.scalajs.js - -class Runtime private { - def exit(status: Int): Unit = - halt(status) - - //def addShutdownHook(hook: Thread): Unit - //def removeShutdownHook(hook: Thread): Unit - - def halt(status: Int): Unit = { - val envInfo = scala.scalajs.runtime.environmentInfo - - envInfo.exitFunction.fold { - // We don't have an exit function. Fail - throw new SecurityException("Cannot terminate a JavaScript program. " + - "Define a JavaScript function `__ScalaJSEnv.exitFunction` to " + - "be called on exit.") - } { exitFunction => - exitFunction(status) - throw new IllegalStateException("__ScalaJSEnv.exitFunction returned") - } - } - - def availableProcessors(): Int = 1 - //def freeMemory(): scala.Long - //def totalMemory(): scala.Long - //def maxMemory(): scala.Long - - def gc(): Unit = { - // Ignore - } - - //def runFinalization(): Unit - //def traceInstructions(on: scala.Boolean): Unit - //def traceMethodCalls(on: scala.Boolean): Unit - - //def load(filename: String): Unit - //def loadLibrary(filename: String): Unit -} - -object Runtime { - private val currentRuntime = new Runtime - - def getRuntime(): Runtime = currentRuntime -} diff --git a/javalanglib/src/main/scala/java/lang/Short.scala b/javalanglib/src/main/scala/java/lang/Short.scala deleted file mode 100644 index 78f0ab7305..0000000000 --- a/javalanglib/src/main/scala/java/lang/Short.scala +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package java.lang - -/* This is a hijacked class. Its instances are primitive numbers. - * Constructors are not emitted. - */ -final class Short private () extends Number with Comparable[Short] { - - def this(value: scala.Short) = this() - def this(s: String) = this() - - @inline override def shortValue(): scala.Short = - this.asInstanceOf[scala.Short] - - @inline override def byteValue(): scala.Byte = shortValue.toByte - @inline def intValue(): scala.Int = shortValue.toInt - @inline def longValue(): scala.Long = shortValue.toLong - @inline def floatValue(): scala.Float = shortValue.toFloat - @inline def doubleValue(): scala.Double = shortValue.toDouble - - @inline override def equals(that: Any): scala.Boolean = - this eq that.asInstanceOf[AnyRef] - - @inline override def hashCode(): Int = - shortValue - - @inline override def compareTo(that: Short): Int = - Short.compare(shortValue, that.shortValue) - - @inline override def toString(): String = - Short.toString(shortValue) - -} - -object Short { - final val TYPE = scala.Predef.classOf[scala.Short] - final val SIZE = 16 - final val BYTES = 2 - - /* MIN_VALUE and MAX_VALUE should be 'final val's. But it is impossible to - * write a proper Short literal in Scala, that would both considered a Short - * and a constant expression (optimized as final val). - * Since vals and defs are binary-compatible (although they're not strictly - * speaking source-compatible, because of stability), we implement them as - * defs. Source-compatibility is not an issue because user code is compiled - * against the JDK .class files anyway. - */ - def MIN_VALUE: scala.Short = -32768 - def MAX_VALUE: scala.Short = 32767 - - @inline def valueOf(shortValue: scala.Short): Short = new Short(shortValue) - @inline def valueOf(s: String): Short = valueOf(parseShort(s)) - - @inline def valueOf(s: String, radix: Int): Short = - valueOf(parseShort(s, radix)) - - @inline def parseShort(s: String): scala.Short = parseShort(s, 10) - - def parseShort(s: String, radix: Int): scala.Short = { - val r = Integer.parseInt(s, radix) - if (r < MIN_VALUE || r > MAX_VALUE) - throw new NumberFormatException(s"""For input string: "$s"""") - else - r.toShort - } - - @inline def toString(s: scala.Short): String = - "" + s - - @noinline def decode(nm: String): Short = - Integer.decodeGeneric(nm, valueOf(_, _)) - - @inline def compare(x: scala.Short, y: scala.Short): scala.Int = - x - y - - def reverseBytes(i: scala.Short): scala.Short = - (((i >>> 8) & 0xff) + ((i & 0xff) << 8)).toShort -} diff --git a/javalanglib/src/main/scala/java/lang/StackTraceElement.scala b/javalanglib/src/main/scala/java/lang/StackTraceElement.scala deleted file mode 100644 index 53e46695b0..0000000000 --- a/javalanglib/src/main/scala/java/lang/StackTraceElement.scala +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package java.lang - -import scala.scalajs.js -import js.annotation.JSExport - -final class StackTraceElement(declaringClass: String, methodName: String, - fileName: String, lineNumber: Int) extends AnyRef with java.io.Serializable { - - private[this] var columnNumber: Int = -1 - - def getFileName(): String = fileName - def getLineNumber(): Int = lineNumber - def getClassName(): String = declaringClass - def getMethodName(): String = methodName - def isNativeMethod(): scala.Boolean = false - - @JSExport - def getColumnNumber(): Int = columnNumber - - @JSExport - def setColumnNumber(columnNumber: Int): Unit = - this.columnNumber = columnNumber - - override def equals(that: Any): scala.Boolean = that match { - case that: StackTraceElement => - (getFileName == that.getFileName) && - (getLineNumber == that.getLineNumber) && - (getClassName == that.getClassName) && - (getMethodName == that.getMethodName) - case _ => - false - } - - override def toString(): String = { - var result = "" - if (declaringClass != "") - result += declaringClass + "." - result += methodName - if (fileName eq null) { - if (isNativeMethod) - result += "(Native Method)" - else - result += "(Unknown Source)" - } else { - result += s"($fileName" - if (lineNumber >= 0) { - result += s":$lineNumber" - if (columnNumber >= 0) - result += s":$columnNumber" - } - result += ")" - } - result - } - - override def hashCode(): Int = { - declaringClass.hashCode() ^ methodName.hashCode() - } -} diff --git a/javalanglib/src/main/scala/java/lang/System.scala b/javalanglib/src/main/scala/java/lang/System.scala deleted file mode 100644 index b0c53a8b68..0000000000 --- a/javalanglib/src/main/scala/java/lang/System.scala +++ /dev/null @@ -1,393 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package java.lang - -import java.io._ - -import scala.scalajs.js -import scala.scalajs.js.Dynamic.global -import scala.scalajs.LinkingInfo.assumingES6 -import scala.scalajs.runtime.{environmentInfo, linkingInfo, SemanticsUtils} - -import java.{util => ju} - -object System { - var out: PrintStream = new JSConsoleBasedPrintStream(isErr = false) - var err: PrintStream = new JSConsoleBasedPrintStream(isErr = true) - var in: InputStream = null - - def setIn(in: InputStream): Unit = - this.in = in - - def setOut(out: PrintStream): Unit = - this.out = out - - def setErr(err: PrintStream): Unit = - this.err = err - - def currentTimeMillis(): scala.Long = { - (new js.Date).getTime().toLong - } - - private[this] val getHighPrecisionTime: js.Function0[scala.Double] = { - import js.DynamicImplicits.truthValue - - // We've got to use selectDynamic explicitly not to crash Scala 2.10 - if (global.selectDynamic("performance")) { - if (global.performance.selectDynamic("now")) { - () => global.performance.now().asInstanceOf[scala.Double] - } else if (global.performance.selectDynamic("webkitNow")) { - () => global.performance.webkitNow().asInstanceOf[scala.Double] - } else { - () => new js.Date().getTime() - } - } else { - () => new js.Date().getTime() - } - } - - def nanoTime(): scala.Long = - (getHighPrecisionTime() * 1000000).toLong - - def arraycopy(src: Object, srcPos: scala.Int, dest: Object, - destPos: scala.Int, length: scala.Int): Unit = { - - import scala.{Boolean, Char, Byte, Short, Int, Long, Float, Double} - - @inline def checkIndices(srcLen: Int, destLen: Int): Unit = { - SemanticsUtils.arrayIndexOutOfBoundsCheck({ - srcPos < 0 || destPos < 0 || length < 0 || - srcPos > srcLen - length || - destPos > destLen - length - }, { - new ArrayIndexOutOfBoundsException() - }) - } - - def mismatch(): Nothing = - throw new ArrayStoreException("Incompatible array types") - - val forward = (src ne dest) || destPos < srcPos || srcPos + length < destPos - - def copyPrim[@specialized T](src: Array[T], dest: Array[T]): Unit = { - checkIndices(src.length, dest.length) - if (forward) { - var i = 0 - while (i < length) { - dest(i+destPos) = src(i+srcPos) - i += 1 - } - } else { - var i = length-1 - while (i >= 0) { - dest(i+destPos) = src(i+srcPos) - i -= 1 - } - } - } - - def copyRef(src: Array[AnyRef], dest: Array[AnyRef]): Unit = { - checkIndices(src.length, dest.length) - if (forward) { - var i = 0 - while (i < length) { - dest(i+destPos) = src(i+srcPos) - i += 1 - } - } else { - var i = length-1 - while (i >= 0) { - dest(i+destPos) = src(i+srcPos) - i -= 1 - } - } - } - - if (src == null || dest == null) { - throw new NullPointerException() - } else (src match { - case src: Array[AnyRef] => - dest match { - case dest: Array[AnyRef] => copyRef(src, dest) - case _ => mismatch() - } - case src: Array[Boolean] => - dest match { - case dest: Array[Boolean] => copyPrim(src, dest) - case _ => mismatch() - } - case src: Array[Char] => - dest match { - case dest: Array[Char] => copyPrim(src, dest) - case _ => mismatch() - } - case src: Array[Byte] => - dest match { - case dest: Array[Byte] => copyPrim(src, dest) - case _ => mismatch() - } - case src: Array[Short] => - dest match { - case dest: Array[Short] => copyPrim(src, dest) - case _ => mismatch() - } - case src: Array[Int] => - dest match { - case dest: Array[Int] => copyPrim(src, dest) - case _ => mismatch() - } - case src: Array[Long] => - dest match { - case dest: Array[Long] => copyPrim(src, dest) - case _ => mismatch() - } - case src: Array[Float] => - dest match { - case dest: Array[Float] => copyPrim(src, dest) - case _ => mismatch() - } - case src: Array[Double] => - dest match { - case dest: Array[Double] => copyPrim(src, dest) - case _ => mismatch() - } - case _ => - mismatch() - }) - } - - def identityHashCode(x: Object): scala.Int = { - (x: Any) match { - case null => 0 - case _:scala.Boolean | _:scala.Double | _:String | () => - x.hashCode() - case _ => - import IDHashCode._ - if (x.getClass == null) { - // This is not a Scala.js object: delegate to x.hashCode() - x.hashCode() - } else if (assumingES6 || idHashCodeMap != null) { - // Use the global WeakMap of attributed id hash codes - val hash = idHashCodeMap.get(x.asInstanceOf[js.Any]) - if (!js.isUndefined(hash)) { - hash.asInstanceOf[Int] - } else { - val newHash = nextIDHashCode() - idHashCodeMap.set(x.asInstanceOf[js.Any], newHash) - newHash - } - } else { - val hash = x.asInstanceOf[js.Dynamic].selectDynamic("$idHashCode$0") - if (!js.isUndefined(hash)) { - /* Note that this can work even if x is sealed, if - * identityHashCode() was called for the first time before x was - * sealed. - */ - hash.asInstanceOf[Int] - } else if (!js.Object.isSealed(x.asInstanceOf[js.Object])) { - /* If x is not sealed, we can (almost) safely create an additional - * field with a bizarre and relatively long name, even though it is - * technically undefined behavior. - */ - val newHash = nextIDHashCode() - x.asInstanceOf[js.Dynamic].updateDynamic("$idHashCode$0")(newHash) - newHash - } else { - // Otherwise, we unfortunately have to return a constant. - 42 - } - } - } - } - - private object IDHashCode { - private var lastIDHashCode: Int = 0 - - val idHashCodeMap = - if (assumingES6 || !js.isUndefined(global.WeakMap)) - js.Dynamic.newInstance(global.WeakMap)() - else - null - - def nextIDHashCode(): Int = { - val r = lastIDHashCode + 1 - lastIDHashCode = r - r - } - } - - private object SystemProperties { - var value = loadSystemProperties() - - private[System] def loadSystemProperties(): ju.Properties = { - val sysProp = new ju.Properties() - sysProp.setProperty("java.version", "1.8") - sysProp.setProperty("java.vm.specification.version", "1.8") - sysProp.setProperty("java.vm.specification.vendor", "Oracle Corporation") - sysProp.setProperty("java.vm.specification.name", "Java Virtual Machine Specification") - sysProp.setProperty("java.vm.name", "Scala.js") - linkingInfo.linkerVersion.foreach(v => sysProp.setProperty("java.vm.version", v)) - sysProp.setProperty("java.specification.version", "1.8") - sysProp.setProperty("java.specification.vendor", "Oracle Corporation") - sysProp.setProperty("java.specification.name", "Java Platform API Specification") - sysProp.setProperty("file.separator", "/") - sysProp.setProperty("path.separator", ":") - sysProp.setProperty("line.separator", "\n") - - for { - jsEnvProperties <- environmentInfo.javaSystemProperties - (key, value) <- jsEnvProperties - } { - sysProp.setProperty(key, value) - } - sysProp - } - } - - def getProperties(): ju.Properties = - SystemProperties.value - - def lineSeparator(): String = "\n" - - def setProperties(properties: ju.Properties): Unit = { - SystemProperties.value = - if (properties != null) properties - else SystemProperties.loadSystemProperties() - } - - def getProperty(key: String): String = - SystemProperties.value.getProperty(key) - - def getProperty(key: String, default: String): String = - SystemProperties.value.getProperty(key, default) - - def clearProperty(key: String): String = - SystemProperties.value.remove(key).asInstanceOf[String] - - def setProperty(key: String, value: String): String = - SystemProperties.value.setProperty(key, value).asInstanceOf[String] - - def getenv(): ju.Map[String, String] = - ju.Collections.emptyMap() - - def getenv(name: String): String = { - if (name eq null) - throw new NullPointerException - - null - } - - def exit(status: scala.Int): Unit = Runtime.getRuntime().exit(status) - def gc(): Unit = Runtime.getRuntime().gc() -} - -private[lang] final class JSConsoleBasedPrintStream(isErr: scala.Boolean) - extends PrintStream(new JSConsoleBasedPrintStream.DummyOutputStream) { - - import JSConsoleBasedPrintStream._ - - /** Whether the buffer is flushed. - * This can be true even if buffer != "" because of line continuations. - * However, the converse is never true, i.e., !flushed => buffer != "". - */ - private var flushed: scala.Boolean = true - private var buffer: String = "" - - override def write(b: Int): Unit = - write(Array(b.toByte), 0, 1) - - override def write(buf: Array[scala.Byte], off: Int, len: Int): Unit = { - /* This does *not* decode buf as a sequence of UTF-8 code units. - * This is not really useful, and would uselessly pull in the UTF-8 decoder - * in all applications that use OutputStreams (not just PrintStreams). - * Instead, we use a trivial ISO-8859-1 decoder in here. - */ - if (off < 0 || len < 0 || len > buf.length - off) - throw new IndexOutOfBoundsException - - var i = 0 - while (i < len) { - print((buf(i + off) & 0xff).toChar) - i += 1 - } - } - - override def print(b: scala.Boolean): Unit = printString(String.valueOf(b)) - override def print(c: scala.Char): Unit = printString(String.valueOf(c)) - override def print(i: scala.Int): Unit = printString(String.valueOf(i)) - override def print(l: scala.Long): Unit = printString(String.valueOf(l)) - override def print(f: scala.Float): Unit = printString(String.valueOf(f)) - override def print(d: scala.Double): Unit = printString(String.valueOf(d)) - override def print(s: Array[scala.Char]): Unit = printString(String.valueOf(s)) - override def print(s: String): Unit = printString(if (s == null) "null" else s) - override def print(obj: AnyRef): Unit = printString(String.valueOf(obj)) - - override def println(): Unit = printString("\n") - - // This is the method invoked by Predef.println(x). - @inline - override def println(obj: AnyRef): Unit = printString("" + obj + "\n") - - private def printString(s: String): Unit = { - var rest: String = s - while (rest != "") { - val nlPos = rest.indexOf("\n") - if (nlPos < 0) { - buffer += rest - flushed = false - rest = "" - } else { - doWriteLine(buffer + rest.substring(0, nlPos)) - buffer = "" - flushed = true - rest = rest.substring(nlPos+1) - } - } - } - - /** - * Since we cannot write a partial line in JavaScript, we write a whole - * line with continuation symbol at the end and schedule a line continuation - * symbol for the new line if the buffer is flushed. - */ - override def flush(): Unit = if (!flushed) { - doWriteLine(buffer + LineContEnd) - buffer = LineContStart - flushed = true - } - - override def close(): Unit = () - - private def doWriteLine(line: String): Unit = { - import js.DynamicImplicits.truthValue - - // We've got to use selectDynamic explicitly not to crash Scala 2.10 - if (global.selectDynamic("console")) { - if (isErr && global.console.selectDynamic("error")) - global.console.error(line) - else - global.console.log(line) - } - } -} - -private[lang] object JSConsoleBasedPrintStream { - private final val LineContEnd: String = "\u21A9" - private final val LineContStart: String = "\u21AA" - - class DummyOutputStream extends OutputStream { - def write(c: Int): Unit = - throw new AssertionError( - "Should not get in JSConsoleBasedPrintStream.DummyOutputStream") - } -} diff --git a/javalanglib/src/main/scala/java/lang/Void.scala b/javalanglib/src/main/scala/java/lang/Void.scala deleted file mode 100644 index b4de582730..0000000000 --- a/javalanglib/src/main/scala/java/lang/Void.scala +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package java.lang - -final class Void private () - -object Void { - final val TYPE = scala.Predef.classOf[scala.Unit] -} diff --git a/javalanglib/src/main/scala/java/lang/ref/PhantomReference.scala b/javalanglib/src/main/scala/java/lang/ref/PhantomReference.scala deleted file mode 100644 index 926f377989..0000000000 --- a/javalanglib/src/main/scala/java/lang/ref/PhantomReference.scala +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package java.lang.ref - -class PhantomReference[T >: Null <: AnyRef](referent: T, - queue: ReferenceQueue[_ >: T]) extends Reference[T](null) { - - override def get(): T = null -} diff --git a/javalanglib/src/main/scala/java/lang/ref/Reference.scala b/javalanglib/src/main/scala/java/lang/ref/Reference.scala deleted file mode 100644 index 85548801b4..0000000000 --- a/javalanglib/src/main/scala/java/lang/ref/Reference.scala +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package java.lang.ref - -abstract class Reference[T >: Null <: AnyRef](private[this] var referent: T) { - def get(): T = referent - def clear(): Unit = referent = null - def isEnqueued(): Boolean = false - def enqueue(): Boolean = false -} diff --git a/javalanglib/src/main/scala/java/lang/ref/ReferenceQueue.scala b/javalanglib/src/main/scala/java/lang/ref/ReferenceQueue.scala deleted file mode 100644 index 03a653be65..0000000000 --- a/javalanglib/src/main/scala/java/lang/ref/ReferenceQueue.scala +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package java.lang.ref - -class ReferenceQueue[T >: Null <: AnyRef] diff --git a/javalanglib/src/main/scala/java/lang/ref/SoftReference.scala b/javalanglib/src/main/scala/java/lang/ref/SoftReference.scala deleted file mode 100644 index 565ed8477b..0000000000 --- a/javalanglib/src/main/scala/java/lang/ref/SoftReference.scala +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package java.lang.ref - -class SoftReference[T >: Null <: AnyRef](referent: T, - queue: ReferenceQueue[_ >: T]) extends Reference[T](referent) { - - def this(referent: T) = this(referent, null) - - override def get(): T = super.get() -} diff --git a/javalanglib/src/main/scala/java/lang/ref/WeakReference.scala b/javalanglib/src/main/scala/java/lang/ref/WeakReference.scala deleted file mode 100644 index e6865f0473..0000000000 --- a/javalanglib/src/main/scala/java/lang/ref/WeakReference.scala +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package java.lang.ref - -class WeakReference[T >: Null <: AnyRef](referent: T, - queue: ReferenceQueue[_ >: T]) extends Reference[T](referent) { - - def this(referent: T) = this(referent, null) -} diff --git a/javalanglib/src/main/scala/java/lang/reflect/Array.scala b/javalanglib/src/main/scala/java/lang/reflect/Array.scala deleted file mode 100644 index 839cc55d1f..0000000000 --- a/javalanglib/src/main/scala/java/lang/reflect/Array.scala +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package java.lang.reflect - -import scala.scalajs.js - -import js.JSConverters._ - -import java.lang.Class - -object Array { - def newInstance(componentType: Class[_], length: Int): AnyRef = - componentType.newArrayOfThisClass(js.Array(length)) - - def newInstance(componentType: Class[_], dimensions: scala.Array[Int]): AnyRef = - componentType.newArrayOfThisClass(dimensions.toJSArray) - - def getLength(array: AnyRef): Int = array match { - // yes, this is kind of stupid, but that's how it is - case array: Array[Object] => array.length - case array: Array[Boolean] => array.length - case array: Array[Char] => array.length - case array: Array[Byte] => array.length - case array: Array[Short] => array.length - case array: Array[Int] => array.length - case array: Array[Long] => array.length - case array: Array[Float] => array.length - case array: Array[Double] => array.length - case _ => throw new IllegalArgumentException("argument type mismatch") - } - - def get(array: AnyRef, index: Int): AnyRef = array match { - case array: Array[Object] => array(index) - case array: Array[Boolean] => java.lang.Boolean.valueOf(array(index)) - case array: Array[Char] => java.lang.Character.valueOf(array(index)) - case array: Array[Byte] => java.lang.Byte.valueOf(array(index)) - case array: Array[Short] => java.lang.Short.valueOf(array(index)) - case array: Array[Int] => java.lang.Integer.valueOf(array(index)) - case array: Array[Long] => java.lang.Long.valueOf(array(index)) - case array: Array[Float] => java.lang.Float.valueOf(array(index)) - case array: Array[Double] => java.lang.Double.valueOf(array(index)) - case _ => throw new IllegalArgumentException("argument type mismatch") - } - - def getBoolean(array: AnyRef, index: Int): Boolean = array match { - case array: Array[Boolean] => array(index) - case _ => throw new IllegalArgumentException("argument type mismatch") - } - - def getChar(array: AnyRef, index: Int): Char = array match { - case array: Array[Char] => array(index) - case _ => throw new IllegalArgumentException("argument type mismatch") - } - - def getByte(array: AnyRef, index: Int): Byte = array match { - case array: Array[Byte] => array(index) - case _ => throw new IllegalArgumentException("argument type mismatch") - } - - def getShort(array: AnyRef, index: Int): Short = array match { - case array: Array[Short] => array(index) - case array: Array[Byte] => array(index) - case _ => throw new IllegalArgumentException("argument type mismatch") - } - - def getInt(array: AnyRef, index: Int): Int = array match { - case array: Array[Int] => array(index) - case array: Array[Char] => array(index) - case array: Array[Byte] => array(index) - case array: Array[Short] => array(index) - case _ => throw new IllegalArgumentException("argument type mismatch") - } - - def getLong(array: AnyRef, index: Int): Long = array match { - case array: Array[Long] => array(index) - case array: Array[Char] => array(index) - case array: Array[Byte] => array(index) - case array: Array[Short] => array(index) - case array: Array[Int] => array(index) - case _ => throw new IllegalArgumentException("argument type mismatch") - } - - def getFloat(array: AnyRef, index: Int): Float = array match { - case array: Array[Float] => array(index) - case array: Array[Char] => array(index) - case array: Array[Byte] => array(index) - case array: Array[Short] => array(index) - case array: Array[Int] => array(index).toFloat - case array: Array[Long] => array(index).toFloat - case _ => throw new IllegalArgumentException("argument type mismatch") - } - - def getDouble(array: AnyRef, index: Int): Double = array match { - case array: Array[Double] => array(index) - case array: Array[Char] => array(index) - case array: Array[Byte] => array(index) - case array: Array[Short] => array(index) - case array: Array[Int] => array(index) - case array: Array[Long] => array(index).toDouble - case array: Array[Float] => array(index) - case _ => throw new IllegalArgumentException("argument type mismatch") - } - - def set(array: AnyRef, index: Int, value: AnyRef): Unit = array match { - case array: Array[Object] => array(index) = value - case _ => - (value: Any) match { - case value: Boolean => setBoolean(array, index, value) - case value: Char => setChar(array, index, value) - case value: Byte => setByte(array, index, value) - case value: Short => setShort(array, index, value) - case value: Int => setInt(array, index, value) - case value: Long => setLong(array, index, value) - case value: Float => setFloat(array, index, value) - case value: Double => setDouble(array, index, value) - case _ => throw new IllegalArgumentException("argument type mismatch") - } - } - - def setBoolean(array: AnyRef, index: Int, value: Boolean): Unit = array match { - case array: Array[Boolean] => array(index) = value - case _ => throw new IllegalArgumentException("argument type mismatch") - } - - def setChar(array: AnyRef, index: Int, value: Char): Unit = array match { - case array: Array[Char] => array(index) = value - case array: Array[Int] => array(index) = value - case array: Array[Long] => array(index) = value - case array: Array[Float] => array(index) = value - case array: Array[Double] => array(index) = value - case _ => throw new IllegalArgumentException("argument type mismatch") - } - - def setByte(array: AnyRef, index: Int, value: Byte): Unit = array match { - case array: Array[Byte] => array(index) = value - case array: Array[Short] => array(index) = value - case array: Array[Int] => array(index) = value - case array: Array[Long] => array(index) = value - case array: Array[Float] => array(index) = value - case array: Array[Double] => array(index) = value - case _ => throw new IllegalArgumentException("argument type mismatch") - } - - def setShort(array: AnyRef, index: Int, value: Short): Unit = array match { - case array: Array[Short] => array(index) = value - case array: Array[Int] => array(index) = value - case array: Array[Long] => array(index) = value - case array: Array[Float] => array(index) = value - case array: Array[Double] => array(index) = value - case _ => throw new IllegalArgumentException("argument type mismatch") - } - - def setInt(array: AnyRef, index: Int, value: Int): Unit = array match { - case array: Array[Int] => array(index) = value - case array: Array[Long] => array(index) = value - case array: Array[Float] => array(index) = value.toFloat - case array: Array[Double] => array(index) = value - case _ => throw new IllegalArgumentException("argument type mismatch") - } - - def setLong(array: AnyRef, index: Int, value: Long): Unit = array match { - case array: Array[Long] => array(index) = value - case array: Array[Float] => array(index) = value.toFloat - case array: Array[Double] => array(index) = value.toDouble - case _ => throw new IllegalArgumentException("argument type mismatch") - } - - def setFloat(array: AnyRef, index: Int, value: Float): Unit = array match { - case array: Array[Float] => array(index) = value - case array: Array[Double] => array(index) = value - case _ => throw new IllegalArgumentException("argument type mismatch") - } - - def setDouble(array: AnyRef, index: Int, value: Double): Unit = array match { - case array: Array[Double] => array(index) = value - case _ => throw new IllegalArgumentException("argument type mismatch") - } -} diff --git a/javalib-ex-test-suite/src/test/scala/scala/scalajs/testsuite/javalibex/ZipInputStreamTest.scala b/javalib-ex-test-suite/src/test/scala/scala/scalajs/testsuite/javalibex/ZipInputStreamTest.scala deleted file mode 100644 index a1c08401df..0000000000 --- a/javalib-ex-test-suite/src/test/scala/scala/scalajs/testsuite/javalibex/ZipInputStreamTest.scala +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package scala.scalajs.testsuite.javalibex - -import org.junit.Test -import org.junit.Assert._ -import org.junit.Assume._ - -import scala.scalajs.testsuite.utils.Platform._ - -import java.io._ -import java.util.zip._ - -class ZipInputStreamTest { - - @Test def should_read_zip_archives(): Unit = { - assumeTrue("Assumed typed arrays", typedArrays) - - val in = new ZipInputStream(new ByteArrayInputStream(binZip)) - - def expectBinEntry(name: String, data: Seq[Int]): Unit = { - val e = in.getNextEntry() - assertEquals(name, e.getName()) - - for (d <- data) - assertEquals(d, in.read()) - - assertEquals(-1, in.read()) - } - - def expectStrEntry(name: String, content: String): Unit = { - val e = in.getNextEntry() - assertEquals(name, e.getName()) - - val r = new InputStreamReader(in) - - for (c <- content) - assertEquals(c, r.read().toChar) - - assertEquals(-1, r.read()) - } - - expectBinEntry("greetings/", Seq()) - expectStrEntry("greetings/en.txt", "Hello World, how are you doing?\n") - expectStrEntry("greetings/es.txt", "¿Hola mundo, cómo estás?\n") - expectStrEntry("greetings/fr.txt", "Bonjour, comment ça va?\n") - expectStrEntry("greetings/ja.txt", "こんにちは、お元気ですか。\n") - expectBinEntry("binary/", Seq()) - expectBinEntry("binary/bytes_0_to_50.bin", 0 to 50) - - assertTrue(in.getNextEntry() == null) - in.close() - } - - /** A zip archive for testing: - * - * $ zipinfo test.zip - * Archive: test.zip 1304 bytes 7 files - * drwxr-xr-x 3.0 unx 0 bx stor 13-Aug-14 07:42 greetings/ - * -rw-r--r-- 3.0 unx 32 tx stor 13-Aug-14 07:40 greetings/en.txt - * -rw-r--r-- 3.0 unx 28 tx stor 13-Aug-14 07:42 greetings/es.txt - * -rw-r--r-- 3.0 unx 25 tx stor 13-Aug-14 07:41 greetings/fr.txt - * -rw-r--r-- 3.0 unx 40 tx stor 13-Aug-14 07:40 greetings/ja.txt - * drwxr-xr-x 3.0 unx 0 bx stor 13-Aug-14 07:48 binary/ - * -rw-r--r-- 3.0 unx 51 bx stor 13-Aug-14 07:48 binary/bytes_0_to_50.bin - * 7 files, 176 bytes uncompressed, 176 bytes compressed: 0.0% - */ - val binZip = Array[Byte](80, 75, 3, 4, 10, 0, 0, 0, 0, 0, 89, 61, 13, 69, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 28, 0, 103, 114, 101, 101, 116, - 105, 110, 103, 115, 47, 85, 84, 9, 0, 3, -39, -6, -22, 83, -44, -4, -22, - 83, 117, 120, 11, 0, 1, 4, -4, 1, 0, 0, 4, 0, 0, 0, 0, 80, 75, 3, 4, 10, - 0, 2, 0, 0, 0, 13, 61, 13, 69, -125, -110, -96, -74, 32, 0, 0, 0, 32, 0, - 0, 0, 16, 0, 28, 0, 103, 114, 101, 101, 116, 105, 110, 103, 115, 47, 101, - 110, 46, 116, 120, 116, 85, 84, 9, 0, 3, 73, -6, -22, 83, -108, -4, -22, - 83, 117, 120, 11, 0, 1, 4, -4, 1, 0, 0, 4, 0, 0, 0, 0, 72, 101, 108, 108, - 111, 32, 87, 111, 114, 108, 100, 44, 32, 104, 111, 119, 32, 97, 114, 101, - 32, 121, 111, 117, 32, 100, 111, 105, 110, 103, 63, 10, 80, 75, 3, 4, 10, - 0, 2, 0, 0, 0, 89, 61, 13, 69, -27, 99, -56, -20, 28, 0, 0, 0, 28, 0, 0, - 0, 16, 0, 28, 0, 103, 114, 101, 101, 116, 105, 110, 103, 115, 47, 101, - 115, 46, 116, 120, 116, 85, 84, 9, 0, 3, -39, -6, -22, 83, -108, -4, -22, - 83, 117, 120, 11, 0, 1, 4, -4, 1, 0, 0, 4, 0, 0, 0, 0, -62, -65, 72, 111, - 108, 97, 32, 109, 117, 110, 100, 111, 44, 32, 99, -61, -77, 109, 111, 32, - 101, 115, 116, -61, -95, 115, 63, 10, 80, 75, 3, 4, 10, 0, 2, 0, 0, 0, 42, - 61, 13, 69, -2, -58, -42, 30, 25, 0, 0, 0, 25, 0, 0, 0, 16, 0, 28, 0, 103, - 114, 101, 101, 116, 105, 110, 103, 115, 47, 102, 114, 46, 116, 120, 116, - 85, 84, 9, 0, 3, -128, -6, -22, 83, -108, -4, -22, 83, 117, 120, 11, 0, 1, - 4, -4, 1, 0, 0, 4, 0, 0, 0, 0, 66, 111, 110, 106, 111, 117, 114, 44, 32, - 99, 111, 109, 109, 101, 110, 116, 32, -61, -89, 97, 32, 118, 97, 63, 10, - 80, 75, 3, 4, 10, 0, 2, 0, 0, 0, 24, 61, 13, 69, -26, -5, 76, 91, 40, 0, - 0, 0, 40, 0, 0, 0, 16, 0, 28, 0, 103, 114, 101, 101, 116, 105, 110, 103, - 115, 47, 106, 97, 46, 116, 120, 116, 85, 84, 9, 0, 3, 96, -6, -22, 83, - -108, -4, -22, 83, 117, 120, 11, 0, 1, 4, -4, 1, 0, 0, 4, 0, 0, 0, 0, - -29, -127, -109, -29, -126, -109, -29, -127, -85, -29, -127, -95, -29, - -127, -81, -29, -128, -127, -29, -127, -118, -27, -123, -125, -26, -80, - -105, -29, -127, -89, -29, -127, -103, -29, -127, -117, -29, -128, -126, - 10, 80, 75, 3, 4, 10, 0, 0, 0, 0, 0, 6, 62, 13, 69, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 7, 0, 28, 0, 98, 105, 110, 97, 114, 121, 47, 85, 84, 9, 0, - 3, 28, -4, -22, 83, -44, -4, -22, 83, 117, 120, 11, 0, 1, 4, -4, 1, 0, 0, - 4, 0, 0, 0, 0, 80, 75, 3, 4, 10, 0, 2, 0, 0, 0, 3, 62, 13, 69, -7, 93, 98, - 55, 51, 0, 0, 0, 51, 0, 0, 0, 24, 0, 28, 0, 98, 105, 110, 97, 114, 121, - 47, 98, 121, 116, 101, 115, 95, 48, 95, 116, 111, 95, 53, 48, 46, 98, 105, - 110, 85, 84, 9, 0, 3, 22, -4, -22, 83, -108, -4, -22, 83, 117, 120, 11, 0, - 1, 4, -4, 1, 0, 0, 4, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, - 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, - 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, - 48, 49, 50, 80, 75, 1, 2, 30, 3, 10, 0, 0, 0, 0, 0, 89, 61, 13, 69, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 24, 0, 0, 0, 0, 0, 0, 0, 16, 0, -19, - 65, 0, 0, 0, 0, 103, 114, 101, 101, 116, 105, 110, 103, 115, 47, 85, 84, - 5, 0, 3, -39, -6, -22, 83, 117, 120, 11, 0, 1, 4, -4, 1, 0, 0, 4, 0, 0, 0, - 0, 80, 75, 1, 2, 30, 3, 10, 0, 2, 0, 0, 0, 13, 61, 13, 69, -125, -110, - -96, -74, 32, 0, 0, 0, 32, 0, 0, 0, 16, 0, 24, 0, 0, 0, 0, 0, 1, 0, 0, 0, - -92, -127, 68, 0, 0, 0, 103, 114, 101, 101, 116, 105, 110, 103, 115, 47, - 101, 110, 46, 116, 120, 116, 85, 84, 5, 0, 3, 73, -6, -22, 83, 117, 120, - 11, 0, 1, 4, -4, 1, 0, 0, 4, 0, 0, 0, 0, 80, 75, 1, 2, 30, 3, 10, 0, 2, 0, - 0, 0, 89, 61, 13, 69, -27, 99, -56, -20, 28, 0, 0, 0, 28, 0, 0, 0, 16, 0, - 24, 0, 0, 0, 0, 0, 1, 0, 0, 0, -92, -127, -82, 0, 0, 0, 103, 114, 101, - 101, 116, 105, 110, 103, 115, 47, 101, 115, 46, 116, 120, 116, 85, 84, 5, - 0, 3, -39, -6, -22, 83, 117, 120, 11, 0, 1, 4, -4, 1, 0, 0, 4, 0, 0, 0, 0, - 80, 75, 1, 2, 30, 3, 10, 0, 2, 0, 0, 0, 42, 61, 13, 69, -2, -58, -42, 30, - 25, 0, 0, 0, 25, 0, 0, 0, 16, 0, 24, 0, 0, 0, 0, 0, 1, 0, 0, 0, -92, -127, - 20, 1, 0, 0, 103, 114, 101, 101, 116, 105, 110, 103, 115, 47, 102, 114, - 46, 116, 120, 116, 85, 84, 5, 0, 3, -128, -6, -22, 83, 117, 120, 11, 0, 1, - 4, -4, 1, 0, 0, 4, 0, 0, 0, 0, 80, 75, 1, 2, 30, 3, 10, 0, 2, 0, 0, 0, 24, - 61, 13, 69, -26, -5, 76, 91, 40, 0, 0, 0, 40, 0, 0, 0, 16, 0, 24, 0, 0, 0, - 0, 0, 1, 0, 0, 0, -92, -127, 119, 1, 0, 0, 103, 114, 101, 101, 116, 105, - 110, 103, 115, 47, 106, 97, 46, 116, 120, 116, 85, 84, 5, 0, 3, 96, -6, - -22, 83, 117, 120, 11, 0, 1, 4, -4, 1, 0, 0, 4, 0, 0, 0, 0, 80, 75, 1, 2, - 30, 3, 10, 0, 0, 0, 0, 0, 6, 62, 13, 69, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 7, 0, 24, 0, 0, 0, 0, 0, 0, 0, 16, 0, -19, 65, -23, 1, 0, 0, 98, 105, - 110, 97, 114, 121, 47, 85, 84, 5, 0, 3, 28, -4, -22, 83, 117, 120, 11, 0, - 1, 4, -4, 1, 0, 0, 4, 0, 0, 0, 0, 80, 75, 1, 2, 30, 3, 10, 0, 2, 0, 0, 0, - 3, 62, 13, 69, -7, 93, 98, 55, 51, 0, 0, 0, 51, 0, 0, 0, 24, 0, 24, 0, 0, - 0, 0, 0, 0, 0, 0, 0, -92, -127, 42, 2, 0, 0, 98, 105, 110, 97, 114, 121, - 47, 98, 121, 116, 101, 115, 95, 48, 95, 116, 111, 95, 53, 48, 46, 98, 105, - 110, 85, 84, 5, 0, 3, 22, -4, -22, 83, 117, 120, 11, 0, 1, 4, -4, 1, 0, 0, - 4, 0, 0, 0, 0, 80, 75, 5, 6, 0, 0, 0, 0, 7, 0, 7, 0, 83, 2, 0, 0, -81, 2, - 0, 0, 0, 0) - -} diff --git a/javalib-ex-test-suite/src/test/scala/scala/scalajs/testsuite/jsinterop/ScalaJSDefinedTestEx.scala b/javalib-ex-test-suite/src/test/scala/scala/scalajs/testsuite/jsinterop/ScalaJSDefinedTestEx.scala deleted file mode 100644 index e55aec8c65..0000000000 --- a/javalib-ex-test-suite/src/test/scala/scala/scalajs/testsuite/jsinterop/ScalaJSDefinedTestEx.scala +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package scala.scalajs.testsuite.jsinterop - -import org.junit.Test -import org.junit.Assert._ - -import scala.scalajs.js -import scala.scalajs.js.annotation._ - -/** Additional tests for Scala.js-defined JS classes that have to be in a - * separate codebase than testSuite to be meaningful. - * - * If moved to testSuite, those tests "fail to fail" due to mass effects - * produced by the immensity of the testSuite codebase. - */ -class ScalaJSDefinedTestEx { - - @Test def constructor_property_on_the_prototype_issue_1963(): Unit = { - class ParentClass extends js.Object - - class ChildClass extends ParentClass - - val child = new ChildClass().asInstanceOf[js.Dynamic] - assertSame(js.constructorOf[ChildClass], child.constructor) - } -} diff --git a/javalib-ex-test-suite/src/test/scala/scala/scalajs/testsuite/utils/AssertThrows.scala b/javalib-ex-test-suite/src/test/scala/scala/scalajs/testsuite/utils/AssertThrows.scala deleted file mode 100644 index 22b7c5015a..0000000000 --- a/javalib-ex-test-suite/src/test/scala/scala/scalajs/testsuite/utils/AssertThrows.scala +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package scala.scalajs.testsuite.utils - -/** This is a copy of the implementation in the testSuite */ -object AssertThrows { - /** Backport implementation of Assert.assertThrows to be used until JUnit 4.13 is - * released. See org.junit.Assert.scala in jUnitRuntime. - */ - private def assertThrowsBackport(expectedThrowable: Class[_ <: Throwable], - runnable: ThrowingRunnable): Unit = { - expectThrowsBackport(expectedThrowable, runnable) - } - - /** Backport implementation of Assert.expectThrows to be used until JUnit 4.13 is - * released. See org.junit.Assert.scala in jUnitRuntime. - */ - private def expectThrowsBackport[T <: Throwable](expectedThrowable: Class[T], - runnable: ThrowingRunnable): T = { - val result = { - try { - runnable.run() - null.asInstanceOf[T] - } catch { - case actualThrown: Throwable => - if (expectedThrowable.isInstance(actualThrown)) { - actualThrown.asInstanceOf[T] - } else { - val mismatchMessage = { - "unexpected exception type thrown;" + - expectedThrowable.getSimpleName + " " + actualThrown.getClass.getSimpleName - } - - val assertionError = new AssertionError(mismatchMessage) - assertionError.initCause(actualThrown) - throw assertionError - } - } - } - if (result == null) { - throw new AssertionError("expected " + expectedThrowable.getSimpleName + - " to be thrown, but nothing was thrown") - } else { - result - } - } - - /** Backport implementation of Assert.ThrowingRunnable to be used until - * JUnit 4.13 is released. See org.junit.Assert.scala in jUnitRuntime. - */ - private trait ThrowingRunnable { - def run(): Unit - } - - private def throwingRunnable(code: => Unit): ThrowingRunnable = { - new ThrowingRunnable { - def run(): Unit = code - } - } - - def assertThrows[T <: Throwable, U](expectedThrowable: Class[T], code: => U): Unit = { - assertThrowsBackport(expectedThrowable, throwingRunnable { - code - }) - } - - def expectThrows[T <: Throwable, U](expectedThrowable: Class[T], code: => U): T = { - expectThrowsBackport(expectedThrowable, throwingRunnable { - code - }) - } -} diff --git a/javalib-ex-test-suite/src/test/scala/scala/scalajs/testsuite/utils/Platform.scala b/javalib-ex-test-suite/src/test/scala/scala/scalajs/testsuite/utils/Platform.scala deleted file mode 100644 index be8a1808e3..0000000000 --- a/javalib-ex-test-suite/src/test/scala/scala/scalajs/testsuite/utils/Platform.scala +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package scala.scalajs.testsuite.utils - -/** This is a partial copy of the implementation in the testSuite */ -object Platform { - - def executingInRhino: Boolean = sysProp("rhino") - def typedArrays: Boolean = sysProp("typedarray") - - private def sysProp(key: String): Boolean = - System.getProperty("scalajs." + key, "false") == "true" -} diff --git a/javalib-ex/src/main/scala/java/util/zip/InflaterInputStream.scala b/javalib-ex/src/main/scala/java/util/zip/InflaterInputStream.scala deleted file mode 100644 index a9fbd90517..0000000000 --- a/javalib-ex/src/main/scala/java/util/zip/InflaterInputStream.scala +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package java.util.zip - -import java.io._ - -/** Dummy implementation of InflatorInputStream. Does not do anything. */ -class InflaterInputStream(in: InputStream) extends FilterInputStream(in) { - - // Not implemented: - // def this(in: InputStream, inf: Inflater) - // def this(in: InputStream, inf: Inflater, size: Int) - // protected var buf: Array[Byte] - // protected var inf: Inflater - // protected var len: Int - - override def markSupported(): Boolean = false - override def mark(readlimit: Int): Unit = {} - override def reset(): Unit = throw new IOException("Reset not supported") - -} diff --git a/javalib-ex/src/main/scala/java/util/zip/ZipEntry.scala b/javalib-ex/src/main/scala/java/util/zip/ZipEntry.scala deleted file mode 100644 index c70bd051da..0000000000 --- a/javalib-ex/src/main/scala/java/util/zip/ZipEntry.scala +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package java.util.zip - -// scalastyle:off equals.hash.code - -/** Pure Scala implementation of ZipEntry */ -class ZipEntry(private[this] val _name: String) extends Cloneable { - - private[this] var _comment: String = null - private[this] var _csize: Long = -1 - private[this] var _crc: Long = -1 - private[this] var _extra: Array[Byte] = null - private[this] var _method: Int = -1 - private[this] var _size: Long = -1 - private[this] var _time: Long = -1 - - def this(e: ZipEntry) = { - this(e.getName()) - setComment(e.getComment()) - setCompressedSize(e.getCompressedSize()) - setCrc(e.getCrc()) - setExtra(e.getExtra()) - setMethod(e.getMethod()) - setSize(e.getSize()) - setTime(e.getTime()) - } - - override def clone(): Object = { - val result = super.clone() - if (getExtra() != null) - setExtra(getExtra().clone().asInstanceOf[Array[Byte]]) - result - } - - def getComment(): String = _comment - def getCompressedSize(): Long = _csize - def getCrc(): Long = _crc - def getExtra(): Array[Byte] = _extra - def getMethod(): Int = _method - def getName(): String = _name - def getSize(): Long = _size - def getTime(): Long = _time - - // Strangely, the Javalib defines hashCode, but not equals. - override def hashCode(): Int = { - import scala.util.hashing.MurmurHash3._ - - var acc = 0x45322 - acc = mix(acc, getComment.##) - acc = mix(acc, getCompressedSize.##) - acc = mix(acc, getCrc.##) - acc = mix(acc, getExtra.##) - acc = mix(acc, getMethod.##) - acc = mix(acc, getName.##) - acc = mix(acc, getSize.##) - acc = mixLast(acc, getTime.##) - finalizeHash(acc, 8) - } - - def isDirectory(): Boolean = _name.endsWith("/") - - def setComment(comment: String): Unit = { _comment = comment } - def setCompressedSize(csize: Long): Unit = { _csize = csize } - def setCrc(crc: Long): Unit = { _crc = crc } - def setExtra(extra: Array[Byte]): Unit = { _extra = extra } - def setMethod(method: Int): Unit = { _method = method } - def setSize(size: Long): Unit = { _size = size } - def setTime(time: Long): Unit = { _time = time } - override def toString(): String = _name - -} diff --git a/javalib-ex/src/main/scala/java/util/zip/ZipInputStream.scala b/javalib-ex/src/main/scala/java/util/zip/ZipInputStream.scala deleted file mode 100644 index 3e03482dc1..0000000000 --- a/javalib-ex/src/main/scala/java/util/zip/ZipInputStream.scala +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package java.util.zip - -import java.io._ - -import scala.scalajs.js -import scala.scalajs.js.typedarray._ - -/** - * External: JSZip - * ZipInputStream implementation using - * JSZip - */ -class ZipInputStream(in: InputStream) extends InflaterInputStream(in) { - - // Not implemented - // - All static constant fields (zip internals) - // - protected def createZipEntry(name: String): ZipEntry - - private[this] val entryIter = { - import js.Dynamic.{global => g} - - val data = in match { - case in: ArrayBufferInputStream => - // Simulate reading all the data - while (in.skip(in.available()) > 0) {} - new Uint8Array(in.buffer, in.offset, in.length) - case _ => - val arr = new js.Array[Int] - var x = in.read() - while (x != -1) { - arr.push(x) - x = in.read() - } - new Uint8Array(arr) - } - - val zip = js.Dynamic.newInstance(g.JSZip)(data) - val entries = zip.files.asInstanceOf[js.Dictionary[js.Dynamic]] - - entries.iterator - } - - private[this] var inner: ArrayBufferInputStream = null - - override def close(): Unit = { - closeEntry() - super.close() - } - - override def available(): Int = { - if (inner == null || inner.available() <= 0) 0 - else 1 - } - - def closeEntry(): Unit = { - if (inner != null) - inner.close() - inner = null - } - - def getNextEntry(): ZipEntry = { - closeEntry() - if (entryIter.hasNext) { - val (name, jsEntry) = entryIter.next() - val res = new ZipEntry(name) - res.setTime(jsEntry.date.asInstanceOf[js.Date].getTime().toLong) - res.setComment(jsEntry.comment.asInstanceOf[String]) - - inner = new ArrayBufferInputStream( - jsEntry.asArrayBuffer().asInstanceOf[ArrayBuffer]) - - res - } else null - } - - override def read(): Int = { - if (inner == null) -1 - else inner.read() - } - - override def read(buf: Array[Byte], off: Int, len: Int): Int = { - if (len == 0) 0 - else if (inner == null) -1 - else inner.read(buf, off, len) - } - - override def skip(n: Long): Long = { - if (inner == null) 0 - else inner.skip(n) - } - -} diff --git a/javalib-ext-dummies/src/main/scala/java/security/SecureRandom.scala b/javalib-ext-dummies/src/main/scala/java/security/SecureRandom.scala new file mode 100644 index 0000000000..47f9555fbe --- /dev/null +++ b/javalib-ext-dummies/src/main/scala/java/security/SecureRandom.scala @@ -0,0 +1,19 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.security + +/** Fake implementation of `SecureRandom` that is not actually secure at all. + * + * It directly delegates to `java.util.Random`. + */ +class SecureRandom extends java.util.Random diff --git a/javalib-ext-dummies/src/main/scala/java/text/DecimalFormat.scala b/javalib-ext-dummies/src/main/scala/java/text/DecimalFormat.scala new file mode 100644 index 0000000000..e89b71431a --- /dev/null +++ b/javalib-ext-dummies/src/main/scala/java/text/DecimalFormat.scala @@ -0,0 +1,19 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.text + +import java.util.Locale + +class DecimalFormat(locale: Locale) extends NumberFormat { + def getGroupingSize(): Int = 3 +} diff --git a/javalib-ext-dummies/src/main/scala/java/text/DecimalFormatSymbols.scala b/javalib-ext-dummies/src/main/scala/java/text/DecimalFormatSymbols.scala new file mode 100644 index 0000000000..8710078c3d --- /dev/null +++ b/javalib-ext-dummies/src/main/scala/java/text/DecimalFormatSymbols.scala @@ -0,0 +1,55 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.text + +import java.util.Locale + +/** Dummy implementation of `DecimalFormatSymbols`. + * + * It is even worse than most other dummies, in the sense that it + * special-cases the locales that we use in our tests (`FormatterTestEx`). + * It is incorrect for most locales. + */ +class DecimalFormatSymbols(locale: Locale) extends NumberFormat { + def getZeroDigit(): Char = { + val ext = locale.getExtension('u') + if (ext != null && ext.contains("nu-deva")) + '\u0966' // '०' DEVANAGARI DIGIT ZERO + else + '0' + } + + def getGroupingSeparator(): Char = { + locale.getLanguage() match { + case "fr" => '\u202F' // NARROW NO-BREAK SPACE + case "" | "en" | "hi" => ',' + case _ => unsupported() + } + } + + def getDecimalSeparator(): Char = { + locale.getLanguage() match { + case "fr" => ',' + case "" | "en" | "hi" => '.' + case _ => unsupported() + } + } + + private def unsupported(): Nothing = + throw new Error(s"Unsupported locale '$locale' in DecimalFormatSymbols") +} + +object DecimalFormatSymbols { + def getInstance(locale: Locale): DecimalFormatSymbols = + new DecimalFormatSymbols(locale) +} diff --git a/javalib-ext-dummies/src/main/scala/java/text/Format.scala b/javalib-ext-dummies/src/main/scala/java/text/Format.scala new file mode 100644 index 0000000000..8dd6f107fe --- /dev/null +++ b/javalib-ext-dummies/src/main/scala/java/text/Format.scala @@ -0,0 +1,16 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.text + +abstract class Format protected () + extends AnyRef with java.io.Serializable with java.lang.Cloneable diff --git a/javalib-ext-dummies/src/main/scala/java/text/NumberFormat.scala b/javalib-ext-dummies/src/main/scala/java/text/NumberFormat.scala new file mode 100644 index 0000000000..d054aec3de --- /dev/null +++ b/javalib-ext-dummies/src/main/scala/java/text/NumberFormat.scala @@ -0,0 +1,22 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.text + +import java.util.Locale + +abstract class NumberFormat protected () extends Format + +object NumberFormat { + def getNumberInstance(inLocale: Locale): NumberFormat = + new DecimalFormat(inLocale) +} diff --git a/javalib-ext-dummies/src/main/scala/java/time/DateTimeException.scala b/javalib-ext-dummies/src/main/scala/java/time/DateTimeException.scala new file mode 100644 index 0000000000..c87c703c8f --- /dev/null +++ b/javalib-ext-dummies/src/main/scala/java/time/DateTimeException.scala @@ -0,0 +1,19 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.time + +class DateTimeException(message: String, cause: Throwable) + extends RuntimeException(message, cause) { + + def this(message: String) = this(message, null) +} diff --git a/javalib-ext-dummies/src/main/scala/java/time/Instant.scala b/javalib-ext-dummies/src/main/scala/java/time/Instant.scala new file mode 100644 index 0000000000..ccc6123037 --- /dev/null +++ b/javalib-ext-dummies/src/main/scala/java/time/Instant.scala @@ -0,0 +1,84 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.time + +final class Instant(private val epochSecond: Long, private val nano: Int) { + def getEpochSecond(): Long = epochSecond + + def getNano(): Int = nano + + def toEpochMilli(): Long = { + if (epochSecond == -9223372036854776L) { + /* Special case: epochSecond * 1000L would overflow, but the addition + * of the nanos might save the day. So we transfer one unit of the + * seconds into the contribution of the nanos. + */ + Math.addExact(-9223372036854775000L, (nano / 1000000) - 1000) + } else { + Math.addExact(Math.multiplyExact(epochSecond, 1000L), nano / 1000000) + } + } + + def isAfter(otherInstant: Instant): Boolean = { + this.epochSecond > otherInstant.epochSecond || { + this.epochSecond == otherInstant.epochSecond && + this.nano > otherInstant.nano + } + } + + def isBefore(otherInstant: Instant): Boolean = { + this.epochSecond < otherInstant.epochSecond || { + this.epochSecond == otherInstant.epochSecond && + this.nano < otherInstant.nano + } + } + + override def equals(that: Any): Boolean = that match { + case that: Instant => + this.epochSecond == that.epochSecond && + this.nano == that.nano + case _ => + false + } + + override def hashCode(): Int = + java.lang.Long.hashCode(epochSecond) ^ java.lang.Integer.hashCode(nano) + + // non compliant, for debugging purposes only + override def toString(): String = + "Instant(" + epochSecond + ", " + nano + ")" +} + +object Instant { + final val MIN: Instant = new Instant(-31557014167219200L, 0) + final val MAX: Instant = new Instant(31556889864403199L, 999999999) + + private def checkAndCreate(epochSecond: Long, nano: Int): Instant = { + val instant = new Instant(epochSecond, nano) + if (instant.isBefore(MIN) || instant.isAfter(MAX)) + throw new DateTimeException("Instant exceeds minimum or maximum instant") + instant + } + + def ofEpochSecond(epochSecond: Long, nanoAdjustment: Long): Instant = { + val adjustedSecond = + Math.addExact(epochSecond, Math.floorDiv(nanoAdjustment, 1000000000L)) + val adjustedNano = Math.floorMod(nanoAdjustment, 1000000000L).toInt + checkAndCreate(adjustedSecond, adjustedNano) + } + + def ofEpochMilli(epochMilli: Long): Instant = { + new Instant(Math.floorDiv(epochMilli, 1000L), + 1000000 * Math.floorMod(epochMilli, 1000L).toInt) + } +} diff --git a/javalib-ext-dummies/src/main/scala/java/util/Locale.scala b/javalib-ext-dummies/src/main/scala/java/util/Locale.scala new file mode 100644 index 0000000000..ae4a624341 --- /dev/null +++ b/javalib-ext-dummies/src/main/scala/java/util/Locale.scala @@ -0,0 +1,117 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util + +final class Locale private (languageRaw: String, countryRaw: String, + variant: String, private val extensions: Map[Char, String]) + extends AnyRef with java.lang.Cloneable with java.io.Serializable { + + def this(languageRaw: String, countryRaw: String, variantRaw: String) = + this(languageRaw, countryRaw, variantRaw, Collections.emptyMap()) + + def this(languageRaw: String, countryRaw: String) = + this(languageRaw, countryRaw, "") + + def this(languageRaw: String) = this(languageRaw, "", "") + + private[this] val language: String = languageRaw.toLowerCase() + + private[this] val country: String = countryRaw.toUpperCase() + + def getLanguage(): String = language + + def getCountry(): String = country + + def getVariant(): String = variant + + def hasExtensions(): Boolean = !extensions.isEmpty() + + def getExtension(key: Char): String = extensions.get(key) // nullable + + // Not fully compliant, for debugging purposes only + override def toString(): String = { + var result = language + if (country != "" || variant != "" || hasExtensions()) + result += "_" + country + if (variant != "" || hasExtensions()) + result += "_" + variant + + if (hasExtensions()) { + import scala.Predef.charWrapper // for `to` + + val keyValues = for { + key <- 'a' to 'z' + value = getExtension(key) + if value != null + } yield { + s"$key-$value" + } + + result += keyValues.mkString("#", "-", "") + } + + result + } + + override def hashCode(): Int = + language.## ^ country.## ^ variant.## ^ extensions.## + + override def equals(that: Any): Boolean = that match { + case that: Locale => + this.getLanguage() == that.getLanguage() && + this.getCountry() == that.getCountry() && + this.getVariant() == that.getVariant() && + this.extensions == that.extensions + case _ => + false + } +} + +object Locale { + val ROOT: Locale = new Locale("", "") + + // By specification, the default locale in Scala.js is always `ROOT`. + def getDefault(): Locale = ROOT + + final class Builder { + private var language: String = "" + private var country: String = "" + private var variant: String = "" + private val extensions = new java.util.HashMap[Char, String] + + def setLanguage(language: String): Builder = { + this.language = language.toLowerCase() + this + } + + def setCountry(country: String): Builder = { + this.country = country.toUpperCase() + this + } + + def setVariant(variant: String): Builder = { + this.variant = variant + this + } + + def setExtension(key: Char, value: String): Builder = { + extensions.put(key, value) + this + } + + def build(): Locale = { + new Locale(language, country, variant, + extensions.clone().asInstanceOf[Map[Char, String]]) + } + } +} diff --git a/javalib/src/main/scala/java/io/BufferedReader.scala b/javalib/src/main/scala/java/io/BufferedReader.scala index 3257c5b9d1..4cb0afdd32 100644 --- a/javalib/src/main/scala/java/io/BufferedReader.scala +++ b/javalib/src/main/scala/java/io/BufferedReader.scala @@ -16,7 +16,9 @@ class BufferedReader(in: Reader, sz: Int) extends Reader { def this(in: Reader) = this(in, 4096) - private[this] var buf = new Array[Char](sz) + // Workaround 2.11 with no-specialization ; buf should be initialized on the same line + private[this] var buf: Array[Char] = null + buf = new Array[Char](sz) /** Last valid value in the buffer (exclusive) */ private[this] var end = 0 diff --git a/javalib/src/main/scala/java/io/CharArrayReader.scala b/javalib/src/main/scala/java/io/CharArrayReader.scala new file mode 100644 index 0000000000..627f0613dd --- /dev/null +++ b/javalib/src/main/scala/java/io/CharArrayReader.scala @@ -0,0 +1,96 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.io + +class CharArrayReader(protected var buf: Array[Char], offset: Int, length: Int) extends Reader { + if (offset < 0 || offset > buf.length || length < 0 || offset + length < 0) + throw new IllegalArgumentException + + protected var pos: Int = offset + protected var markedPos: Int = offset + + // count is actually the "end" index + protected var count: Int = Math.min(offset + length, buf.length) + + def this(buf: Array[Char]) = this(buf, 0, buf.length) + + override def close(): Unit = this.buf = null + + override def mark(readAheadLimit: Int): Unit = { + ensureOpen() + + // The parameter readAheadLimit is ignored for CharArrayReaders + this.markedPos = this.pos + } + + override def markSupported(): Boolean = true + + override def read(): Int = { + ensureOpen() + + if (this.pos == this.count) { + -1 + } else { + this.pos += 1 + buf(this.pos - 1) + } + } + + override def read(buffer: Array[Char], offset: Int, len: Int): Int = { + if (offset < 0 || offset > buffer.length) + throw new ArrayIndexOutOfBoundsException("Offset out of bounds : " + offset) + + if (len < 0 || len > buffer.length - offset) + throw new ArrayIndexOutOfBoundsException("Length out of bounds : " + len) + + ensureOpen() + + if (this.pos < this.count) { + val bytesRead = Math.min(len, this.count - this.pos) + System.arraycopy(this.buf, this.pos, buffer, offset, bytesRead) + this.pos += bytesRead + bytesRead + } else { + -1 + } + } + + override def ready(): Boolean = { + ensureOpen() + + /* JDK spec says "Character-array readers are always ready to be read." + * However, testing shows it returns false when pos == count + */ + this.pos != this.count + } + + override def reset(): Unit = { + ensureOpen() + + this.pos = this.markedPos + } + + override def skip(n: Long): Long = { + ensureOpen() + + val available: Long = (this.count - this.pos).toLong + val skipped: Long = Math.max(0L, Math.min(n, available)) + this.pos += skipped.toInt + skipped + } + + private def ensureOpen(): Unit = { + if (this.buf == null) + throw new IOException("CharArrayReader is closed.") + } +} diff --git a/javalib/src/main/scala/java/io/CharArrayWriter.scala b/javalib/src/main/scala/java/io/CharArrayWriter.scala new file mode 100644 index 0000000000..e794bacce2 --- /dev/null +++ b/javalib/src/main/scala/java/io/CharArrayWriter.scala @@ -0,0 +1,92 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.io + +class CharArrayWriter(initialSize: Int) extends Writer { + if (initialSize < 0) + throw new IllegalArgumentException("size must be >= 0") + + protected var buf: Array[Char] = new Array[Char](initialSize) + protected var count: Int = 0 + + def this() = this(32) + + override def close(): Unit = () + + private def ensureCapacity(i: Int): Unit = { + if (i > this.buf.length - this.count) { + val newLen = Math.max(2 * this.buf.length, this.count + i) + // If newLen is negative due to (integer) overflow, copyOf will throw. + this.buf = java.util.Arrays.copyOf(this.buf, newLen) + } + } + + override def flush(): Unit = () + + def reset(): Unit = this.count = 0 + + def size(): Int = this.count + + def toCharArray(): Array[Char] = java.util.Arrays.copyOf(buf, count) + + override def toString(): String = new String(this.buf, 0, this.count) + + override def write(c: Array[Char], offset: Int, len: Int): Unit = { + if (offset < 0 || offset > c.length || len < 0 || len > c.length - offset) + throw new IndexOutOfBoundsException + + ensureCapacity(len) + System.arraycopy(c, offset, this.buf, this.count, len) + this.count += len + } + + override def write(oneChar: Int): Unit = { + ensureCapacity(1) + this.buf(this.count) = oneChar.toChar + this.count += 1 + } + + override def write(str: String, offset: Int, len: Int): Unit = { + if (offset < 0 || offset > str.length || len < 0 || len > str.length - offset) + throw new StringIndexOutOfBoundsException + + ensureCapacity(len) + str.getChars(offset, offset + len, this.buf, this.count) + this.count += len + } + + def writeTo(out: Writer): Unit = out.write(this.buf, 0, count) + + override def append(c: Char): CharArrayWriter = { + write(c) + this + } + + override def append(csq: CharSequence): CharArrayWriter = { + if (csq == null) + write("null") + else + write(csq.toString()) + + this + } + + override def append(csq: CharSequence, start: Int, end: Int): CharArrayWriter = { + if (csq == null) + write("null", start, end) + else + write(csq.subSequence(start, end).toString()) + + this + } +} diff --git a/javalib/src/main/scala/java/io/DataInputStream.scala b/javalib/src/main/scala/java/io/DataInputStream.scala index 81412ebf85..9cc6905678 100644 --- a/javalib/src/main/scala/java/io/DataInputStream.scala +++ b/javalib/src/main/scala/java/io/DataInputStream.scala @@ -24,34 +24,6 @@ class DataInputStream(in: InputStream) extends FilterInputStream(in) private var pushedBack: Int = -1 private var pushedBackMark: Int = -1 - /* ArrayBufferInputStream mode helpers - * - * These variables are used to special case on ArrayBufferInputStreams - * They allow directly accessing the underlying ArrayBuffer rather than - * creating byte arrays first. - */ - private val inArrayBufferStream = in match { - case in: ArrayBufferInputStream => in - case _ => null - } - private val hasArrayBuffer = inArrayBufferStream != null - private val bufDataView = { - if (hasArrayBuffer) { - val in = inArrayBufferStream - new DataView(in.buffer, in.offset, in.length) - } else { - null - } - } - - private def consumePos(n: Int) = { - val off = if (pushedBack != -1) 1 else 0 - val resultPos = inArrayBufferStream.pos - off - val toSkip = n - off - if (in.skip(toSkip) != toSkip) eof() - resultPos - } - // General Helpers private def eof() = throw new EOFException() private def pushBack(v: Int) = { pushedBack = v } @@ -65,26 +37,14 @@ class DataInputStream(in: InputStream) extends FilterInputStream(in) res.toByte } - def readChar(): Char = { - if (hasArrayBuffer) - bufDataView.getUint16(consumePos(2)).toChar - else - ((readByte() << 8) | readUnsignedByte()).toChar - } + def readChar(): Char = + ((readByte() << 8) | readUnsignedByte()).toChar - def readDouble(): Double = { - if (hasArrayBuffer) - bufDataView.getFloat64(consumePos(8)) - else - java.lang.Double.longBitsToDouble(readLong()) - } + def readDouble(): Double = + java.lang.Double.longBitsToDouble(readLong()) - def readFloat(): Float = { - if (hasArrayBuffer) - bufDataView.getFloat32(consumePos(4)) - else - java.lang.Float.intBitsToFloat(readInt()) - } + def readFloat(): Float = + java.lang.Float.intBitsToFloat(readInt()) def readFully(b: Array[Byte]): Unit = readFully(b, 0, b.length) @@ -103,12 +63,8 @@ class DataInputStream(in: InputStream) extends FilterInputStream(in) } def readInt(): Int = { - if (hasArrayBuffer) { - bufDataView.getInt32(consumePos(4)) - } else { - (readUnsignedByte() << 24) | (readUnsignedByte() << 16) | - (readUnsignedByte() << 8) | readUnsignedByte() - } + (readUnsignedByte() << 24) | (readUnsignedByte() << 16) | + (readUnsignedByte() << 8) | readUnsignedByte() } def readLine(): String = { @@ -135,12 +91,8 @@ class DataInputStream(in: InputStream) extends FilterInputStream(in) (hi << 32) | (lo & 0xFFFFFFFFL) } - def readShort(): Short = { - if (hasArrayBuffer) - bufDataView.getInt16(consumePos(2)) - else - ((readByte() << 8) | readUnsignedByte()).toShort - } + def readShort(): Short = + ((readByte() << 8) | readUnsignedByte()).toShort def readUnsignedByte(): Int = { val res = read() @@ -148,12 +100,8 @@ class DataInputStream(in: InputStream) extends FilterInputStream(in) res } - def readUnsignedShort(): Int = { - if (hasArrayBuffer) - bufDataView.getUint16(consumePos(2)) - else - (readUnsignedByte() << 8) | readUnsignedByte() - } + def readUnsignedShort(): Int = + (readUnsignedByte() << 8) | readUnsignedByte() def readUTF(): String = { val length = readUnsignedShort() @@ -221,8 +169,8 @@ class DataInputStream(in: InputStream) extends FilterInputStream(in) // Methods on FilterInputStream. // Overridden to track pushedBack / pushedBackMark override def available(): Int = { - if (pushedBack != -1) in.available + 1 - else in.available + if (pushedBack != -1) in.available() + 1 + else in.available() } override def mark(readlimit: Int): Unit = { diff --git a/javalib/src/main/scala/java/io/InputStreamReader.scala b/javalib/src/main/scala/java/io/InputStreamReader.scala index b794edf05c..9fd53f8fc2 100644 --- a/javalib/src/main/scala/java/io/InputStreamReader.scala +++ b/javalib/src/main/scala/java/io/InputStreamReader.scala @@ -47,12 +47,12 @@ class InputStreamReader(private[this] var in: InputStream, def this(in: InputStream, charset: Charset) = this(in, - charset.newDecoder + charset.newDecoder() .onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE)) def this(in: InputStream) = - this(in, Charset.defaultCharset) + this(in, Charset.defaultCharset()) def this(in: InputStream, charsetName: String) = this(in, Charset.forName(charsetName)) @@ -66,12 +66,12 @@ class InputStreamReader(private[this] var in: InputStream, } def getEncoding(): String = - if (closed) null else decoder.charset.name + if (closed) null else decoder.charset().name() override def read(): Int = { ensureOpen() - if (outBuf.hasRemaining) outBuf.get() + if (outBuf.hasRemaining()) outBuf.get() else super.read() } @@ -83,9 +83,9 @@ class InputStreamReader(private[this] var in: InputStream, if (len == 0) { 0 - } else if (outBuf.hasRemaining) { + } else if (outBuf.hasRemaining()) { // Reuse chars decoded last time - val available = Math.min(outBuf.remaining, len) + val available = Math.min(outBuf.remaining(), len) outBuf.get(cbuf, off, available) available } else if (!endOfInput) { @@ -111,12 +111,12 @@ class InputStreamReader(private[this] var in: InputStream, // In a separate method because this is (hopefully) not a common case private def readMoreThroughOutBuf(cbuf: Array[Char], off: Int, len: Int): Int = { // Return outBuf to its full capacity - outBuf.limit(outBuf.capacity) + outBuf.limit(outBuf.capacity()) outBuf.position(0) @tailrec // but not inline, this is not a common path def loopWithOutBuf(desiredOutBufSize: Int): Int = { - if (outBuf.capacity < desiredOutBufSize) + if (outBuf.capacity() < desiredOutBufSize) outBuf = CharBuffer.allocate(desiredOutBufSize) val charsRead = readImpl(outBuf) if (charsRead == InputStreamReader.Overflow) @@ -153,16 +153,16 @@ class InputStreamReader(private[this] var in: InputStream, * at all), which will cause one of the following cases to be handled. */ out.position() - initPos - } else if (result.isUnderflow) { + } else if (result.isUnderflow()) { if (endOfInput) { - if (inBuf.hasRemaining) { + if (inBuf.hasRemaining()) { throw new AssertionError( "CharsetDecoder.decode() should not have returned UNDERFLOW " + "when both endOfInput and inBuf.hasRemaining are true. It " + "should have returned a MalformedInput error instead.") } // Flush - if (decoder.flush(out).isOverflow) { + if (decoder.flush(out).isOverflow()) { InputStreamReader.Overflow } else { // Done @@ -171,13 +171,13 @@ class InputStreamReader(private[this] var in: InputStream, } } else { // We need to read more from the underlying input stream - if (inBuf.limit() == inBuf.capacity) { + if (inBuf.limit() == inBuf.capacity()) { inBuf.compact() - if (!inBuf.hasRemaining) { + if (!inBuf.hasRemaining()) { throw new AssertionError( "Scala.js implementation restriction: " + - inBuf.capacity + " bytes do not seem to be enough for " + - getEncoding + " to decode a single code point. " + + inBuf.capacity() + " bytes do not seem to be enough for " + + getEncoding() + " to decode a single code point. " + "Please report this as a bug.") } inBuf.limit(inBuf.position()) @@ -189,7 +189,7 @@ class InputStreamReader(private[this] var in: InputStream, * according to the specification of InputStreamReader. */ val bytesRead = - in.read(inBuf.array, inBuf.limit, inBuf.capacity - inBuf.limit()) + in.read(inBuf.array(), inBuf.limit(), inBuf.capacity() - inBuf.limit()) if (bytesRead == -1) endOfInput = true @@ -198,7 +198,7 @@ class InputStreamReader(private[this] var in: InputStream, readImpl(out) } - } else if (result.isOverflow) { + } else if (result.isOverflow()) { InputStreamReader.Overflow } else { result.throwException() @@ -212,7 +212,7 @@ class InputStreamReader(private[this] var in: InputStream, * is the expected behavior. */ override def ready(): Boolean = - outBuf.hasRemaining || in.available() > 0 + outBuf.hasRemaining() || in.available() > 0 private def ensureOpen(): Unit = { if (closed) diff --git a/javalib/src/main/scala/java/io/OutputStreamWriter.scala b/javalib/src/main/scala/java/io/OutputStreamWriter.scala index 0a61f4f7c9..0bb5a63b24 100644 --- a/javalib/src/main/scala/java/io/OutputStreamWriter.scala +++ b/javalib/src/main/scala/java/io/OutputStreamWriter.scala @@ -37,12 +37,12 @@ class OutputStreamWriter(private[this] var out: OutputStream, def this(out: OutputStream, cs: Charset) = this(out, - cs.newEncoder + cs.newEncoder() .onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE)) def this(out: OutputStream) = - this(out, Charset.defaultCharset) + this(out, Charset.defaultCharset()) def this(out: OutputStream, charsetName: String) = { this(out, try { @@ -54,7 +54,7 @@ class OutputStreamWriter(private[this] var out: OutputStream, } def getEncoding(): String = - if (closed) null else enc.charset.name + if (closed) null else enc.charset().name() override def write(c: Int): Unit = write(c.toChar.toString, 0, 1) @@ -78,8 +78,8 @@ class OutputStreamWriter(private[this] var out: OutputStream, @tailrec def loopEncode(): Unit = { val result = enc.encode(cbuf1, outBuf, false) - if (result.isUnderflow) () - else if (result.isOverflow) { + if (result.isUnderflow()) () + else if (result.isOverflow()) { makeRoomInOutBuf() loopEncode() } else { @@ -89,7 +89,7 @@ class OutputStreamWriter(private[this] var out: OutputStream, } loopEncode() - if (cbuf1.hasRemaining) + if (cbuf1.hasRemaining()) inBuf = cbuf1.toString } @@ -106,14 +106,14 @@ class OutputStreamWriter(private[this] var out: OutputStream, def loopEncode(): Unit = { val cbuf = CharBuffer.wrap(inBuf) val result = enc.encode(cbuf, outBuf, true) - if (result.isUnderflow) { - if (cbuf.hasRemaining) { + if (result.isUnderflow()) { + if (cbuf.hasRemaining()) { throw new AssertionError( "CharsetEncoder.encode() should not have returned UNDERFLOW " + "when both endOfInput and inBuf.hasRemaining are true. It " + "should have returned a MalformedInput error instead.") } - } else if (result.isOverflow) { + } else if (result.isOverflow()) { makeRoomInOutBuf() loopEncode() } else { @@ -125,7 +125,7 @@ class OutputStreamWriter(private[this] var out: OutputStream, @inline @tailrec def loopFlush(): Unit = { - if (enc.flush(outBuf).isOverflow) { + if (enc.flush(outBuf).isOverflow()) { makeRoomInOutBuf() loopFlush() } @@ -159,7 +159,7 @@ class OutputStreamWriter(private[this] var out: OutputStream, } else { // Very unlikely (outBuf.capacity is not enough to encode a single code point) outBuf.flip() - val newBuf = ByteBuffer.allocate(outBuf.capacity * 2) + val newBuf = ByteBuffer.allocate(outBuf.capacity() * 2) newBuf.put(outBuf) outBuf = newBuf } @@ -173,7 +173,7 @@ class OutputStreamWriter(private[this] var out: OutputStream, // Don't use outBuf.flip() first, in case out.write() throws // Hence, use 0 instead of position, and position instead of limit - out.write(outBuf.array, outBuf.arrayOffset, outBuf.position()) + out.write(outBuf.array(), outBuf.arrayOffset(), outBuf.position()) outBuf.clear() } diff --git a/javalib/src/main/scala/java/io/PrintStream.scala b/javalib/src/main/scala/java/io/PrintStream.scala index fc5d2c64e0..d6141609c3 100644 --- a/javalib/src/main/scala/java/io/PrintStream.scala +++ b/javalib/src/main/scala/java/io/PrintStream.scala @@ -64,7 +64,7 @@ class PrintStream private (_out: OutputStream, autoFlush: Boolean, private lazy val encoder = { val c = - if (charset == null) Charset.defaultCharset + if (charset == null) Charset.defaultCharset() else charset /* We pass `this` as the output stream for the encoding writer so that * we can apply auto-flushing. Note that this will flush() more often diff --git a/javalib/src/main/scala/java/io/Reader.scala b/javalib/src/main/scala/java/io/Reader.scala index 68bea4dc81..d2733b550c 100644 --- a/javalib/src/main/scala/java/io/Reader.scala +++ b/javalib/src/main/scala/java/io/Reader.scala @@ -16,24 +16,26 @@ import java.nio.CharBuffer import scala.annotation.tailrec -abstract class Reader private[this] (_lock: Option[Object]) - extends Readable with Closeable { - - protected val lock = _lock.getOrElse(this) - - protected def this(lock: Object) = this(Some(lock)) - protected def this() = this(None) +abstract class Reader() extends Readable with Closeable { + protected var lock: Object = this + + protected def this(lock: Object) = { + this() + if (lock eq null) + throw new NullPointerException() + this.lock = lock + } def read(target: CharBuffer): Int = { - if (!target.hasRemaining) 0 - else if (target.hasArray) { - val charsRead = read(target.array, - target.position() + target.arrayOffset, target.remaining) + if (!target.hasRemaining()) 0 + else if (target.hasArray()) { + val charsRead = read(target.array(), + target.position() + target.arrayOffset(), target.remaining()) if (charsRead != -1) target.position(target.position() + charsRead) charsRead } else { - val buf = new Array[Char](target.remaining) + val buf = new Array[Char](target.remaining()) val charsRead = read(buf) if (charsRead != -1) target.put(buf, 0, charsRead) diff --git a/javalib/src/main/scala/java/io/Writer.scala b/javalib/src/main/scala/java/io/Writer.scala index 92f9de2305..4dd6e1bd0d 100644 --- a/javalib/src/main/scala/java/io/Writer.scala +++ b/javalib/src/main/scala/java/io/Writer.scala @@ -12,13 +12,15 @@ package java.io -abstract class Writer private[this] (_lock: Option[Object]) extends - Appendable with Closeable with Flushable { - - protected val lock = _lock.getOrElse(this) - - protected def this(lock: Object) = this(Some(lock)) - protected def this() = this(None) +abstract class Writer() extends Appendable with Closeable with Flushable { + protected var lock: Object = this + + protected def this(lock: Object) = { + this() + if (lock eq null) + throw new NullPointerException() + this.lock = lock + } def write(c: Int): Unit = write(Array(c.toChar)) diff --git a/javalanglib/src/main/scala/java/lang/Appendable.scala b/javalib/src/main/scala/java/lang/Appendable.scala similarity index 100% rename from javalanglib/src/main/scala/java/lang/Appendable.scala rename to javalib/src/main/scala/java/lang/Appendable.scala diff --git a/javalanglib/src/main/scala/java/lang/AutoCloseable.scala b/javalib/src/main/scala/java/lang/AutoCloseable.scala similarity index 100% rename from javalanglib/src/main/scala/java/lang/AutoCloseable.scala rename to javalib/src/main/scala/java/lang/AutoCloseable.scala diff --git a/javalib/src/main/scala/java/lang/Boolean.scala b/javalib/src/main/scala/java/lang/Boolean.scala new file mode 100644 index 0000000000..cf56abbb59 --- /dev/null +++ b/javalib/src/main/scala/java/lang/Boolean.scala @@ -0,0 +1,81 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.lang + +import java.lang.constant.Constable + +import scala.scalajs.js + +/* This is a hijacked class. Its instances are primitive booleans. + * Constructors are not emitted. + */ +final class Boolean private () + extends AnyRef with java.io.Serializable with Comparable[Boolean] + with Constable { + + def this(value: scala.Boolean) = this() + def this(v: String) = this() + + @inline def booleanValue(): scala.Boolean = + this.asInstanceOf[scala.Boolean] + + @inline override def equals(that: Any): scala.Boolean = + this eq that.asInstanceOf[AnyRef] + + @inline override def hashCode(): Int = + if (booleanValue()) 1231 else 1237 + + @inline override def compareTo(that: Boolean): Int = + Boolean.compare(booleanValue(), that.booleanValue()) + + @inline override def toString(): String = + Boolean.toString(booleanValue()) + +} + +object Boolean { + /* TYPE should be a `final val`, but that crashes the JVM back-end, so we + * use a 'def' instead, which is binary compatible. + */ + def TYPE: Class[_] = scala.Predef.classOf[scala.Boolean] + + /* TRUE and FALSE are supposed to be vals. However, they are better + * optimized as defs, because they end up being just the constant true and + * false (since `new Boolean(x)` is a no-op). + * Since vals and defs are binary-compatible (although they're not strictly + * speaking source-compatible, because of stability), we implement them as + * defs. Source-compatibility is not an issue because user code is compiled + * against the JDK .class files anyway. + * Moreover, preserving the identity of TRUE and FALSE is not an issue + * either, since they are primitive booleans in the end. + */ + @inline def TRUE: Boolean = valueOf(true) + @inline def FALSE: Boolean = valueOf(false) + + @inline def `new`(value: scala.Boolean): Boolean = valueOf(value) + + @inline def `new`(s: String): Boolean = valueOf(s) + + @inline def valueOf(b: scala.Boolean): Boolean = b.asInstanceOf[Boolean] + + @inline def valueOf(s: String): Boolean = valueOf(parseBoolean(s)) + + @inline def parseBoolean(s: String): scala.Boolean = + (s != null) && s.equalsIgnoreCase("true") + + @inline def toString(b: scala.Boolean): String = + "" + b + + @inline def compare(x: scala.Boolean, y: scala.Boolean): scala.Int = + if (x == y) 0 else if (x) 1 else -1 +} diff --git a/javalib/src/main/scala/java/lang/Byte.scala b/javalib/src/main/scala/java/lang/Byte.scala new file mode 100644 index 0000000000..ef2287af35 --- /dev/null +++ b/javalib/src/main/scala/java/lang/Byte.scala @@ -0,0 +1,105 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.lang + +import java.lang.constant.Constable + +import scala.scalajs.js + +/* This is a hijacked class. Its instances are primitive numbers. + * Constructors are not emitted. + */ +final class Byte private () + extends Number with Comparable[Byte] with Constable { + + def this(value: scala.Byte) = this() + def this(s: String) = this() + + @inline override def byteValue(): scala.Byte = + this.asInstanceOf[scala.Byte] + + @inline override def shortValue(): scala.Short = byteValue().toShort + @inline def intValue(): scala.Int = byteValue().toInt + @inline def longValue(): scala.Long = byteValue().toLong + @inline def floatValue(): scala.Float = byteValue().toFloat + @inline def doubleValue(): scala.Double = byteValue().toDouble + + @inline override def equals(that: Any): scala.Boolean = + this eq that.asInstanceOf[AnyRef] + + @inline override def hashCode(): Int = + byteValue() + + @inline override def compareTo(that: Byte): Int = + Byte.compare(byteValue(), that.byteValue()) + + @inline override def toString(): String = + Byte.toString(byteValue()) +} + +object Byte { + /* TYPE should be a `final val`, but that crashes the JVM back-end, so we + * use a 'def' instead, which is binary compatible. + */ + def TYPE: Class[_] = scala.Predef.classOf[scala.Byte] + + final val SIZE = 8 + final val BYTES = 1 + + /* MIN_VALUE and MAX_VALUE should be 'final val's. But it is impossible to + * write a proper Byte literal in Scala, that would both considered a Byte + * and a constant expression (optimized as final val). + * Since vals and defs are binary-compatible (although they're not strictly + * speaking source-compatible, because of stability), we implement them as + * defs. Source-compatibility is not an issue because user code is compiled + * against the JDK .class files anyway. + */ + def MIN_VALUE: scala.Byte = -128 + def MAX_VALUE: scala.Byte = 127 + + @inline def `new`(value: scala.Byte): Byte = valueOf(value) + + @inline def `new`(s: String): Byte = valueOf(s) + + @inline def valueOf(b: scala.Byte): Byte = b.asInstanceOf[Byte] + + @inline def valueOf(s: String): Byte = valueOf(parseByte(s)) + + @inline def valueOf(s: String, radix: Int): Byte = + valueOf(parseByte(s, radix)) + + @inline def parseByte(s: String): scala.Byte = parseByte(s, 10) + + def parseByte(s: String, radix: Int): scala.Byte = { + val r = Integer.parseInt(s, radix) + if (r < MIN_VALUE || r > MAX_VALUE) + throw new NumberFormatException(s"""For input string: "$s"""") + else + r.toByte + } + + @inline def toString(b: scala.Byte): String = + "" + b + + @noinline def decode(nm: String): Byte = + Integer.decodeGeneric(nm, valueOf(_, _)) + + @inline def compare(x: scala.Byte, y: scala.Byte): scala.Int = + x - y + + @inline def toUnsignedInt(x: scala.Byte): scala.Int = + x.toInt & 0xff + + @inline def toUnsignedLong(x: scala.Byte): scala.Long = + toUnsignedInt(x).toLong +} diff --git a/javalanglib/src/main/scala/java/lang/CharSequence.scala b/javalib/src/main/scala/java/lang/CharSequence.scala similarity index 100% rename from javalanglib/src/main/scala/java/lang/CharSequence.scala rename to javalib/src/main/scala/java/lang/CharSequence.scala diff --git a/javalib/src/main/scala/java/lang/Character.scala b/javalib/src/main/scala/java/lang/Character.scala new file mode 100644 index 0000000000..b260948a6d --- /dev/null +++ b/javalib/src/main/scala/java/lang/Character.scala @@ -0,0 +1,1572 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.lang + +import scala.annotation.{tailrec, switch} +import scala.scalajs.js + +import java.lang.constant.Constable +import java.util.{ArrayList, Arrays, HashMap} + +/* This is a hijacked class. Its instances are primitive chars. + * + * In fact, "primitive" is only true at the IR level. In JS, there is no such + * thing as a primitive character. Turning IR chars into valid JS is the + * responsibility of the Emitter. + * + * Constructors are not emitted. + */ +class Character private () + extends AnyRef with java.io.Serializable with Comparable[Character] + with Constable { + + def this(value: scala.Char) = this() + + @inline def charValue(): scala.Char = + this.asInstanceOf[scala.Char] + + @inline override def hashCode(): Int = + Character.hashCode(charValue()) + + @inline override def equals(that: Any): scala.Boolean = { + that.isInstanceOf[Character] && + (charValue() == that.asInstanceOf[Character].charValue()) + } + + @inline override def toString(): String = + Character.toString(charValue()) + + @inline override def compareTo(that: Character): Int = + Character.compare(charValue(), that.charValue()) +} + +object Character { + /* TYPE should be a `final val`, but that crashes the JVM back-end, so we + * use a 'def' instead, which is binary compatible. + */ + def TYPE: Class[_] = scala.Predef.classOf[scala.Char] + + final val MIN_VALUE = '\u0000' + final val MAX_VALUE = '\uffff' + final val SIZE = 16 + final val BYTES = 2 + + @inline def `new`(value: scala.Char): Character = valueOf(value) + + @inline def valueOf(c: scala.Char): Character = c.asInstanceOf[Character] + + /* These are supposed to be final vals of type Byte, but that's not possible. + * So we implement them as def's, which are binary compatible with final vals. + */ + def UNASSIGNED: scala.Byte = 0 + def UPPERCASE_LETTER: scala.Byte = 1 + def LOWERCASE_LETTER: scala.Byte = 2 + def TITLECASE_LETTER: scala.Byte = 3 + def MODIFIER_LETTER: scala.Byte = 4 + def OTHER_LETTER: scala.Byte = 5 + def NON_SPACING_MARK: scala.Byte = 6 + def ENCLOSING_MARK: scala.Byte = 7 + def COMBINING_SPACING_MARK: scala.Byte = 8 + def DECIMAL_DIGIT_NUMBER: scala.Byte = 9 + def LETTER_NUMBER: scala.Byte = 10 + def OTHER_NUMBER: scala.Byte = 11 + def SPACE_SEPARATOR: scala.Byte = 12 + def LINE_SEPARATOR: scala.Byte = 13 + def PARAGRAPH_SEPARATOR: scala.Byte = 14 + def CONTROL: scala.Byte = 15 + def FORMAT: scala.Byte = 16 + def PRIVATE_USE: scala.Byte = 18 + def SURROGATE: scala.Byte = 19 + def DASH_PUNCTUATION: scala.Byte = 20 + def START_PUNCTUATION: scala.Byte = 21 + def END_PUNCTUATION: scala.Byte = 22 + def CONNECTOR_PUNCTUATION: scala.Byte = 23 + def OTHER_PUNCTUATION: scala.Byte = 24 + def MATH_SYMBOL: scala.Byte = 25 + def CURRENCY_SYMBOL: scala.Byte = 26 + def MODIFIER_SYMBOL: scala.Byte = 27 + def OTHER_SYMBOL: scala.Byte = 28 + def INITIAL_QUOTE_PUNCTUATION: scala.Byte = 29 + def FINAL_QUOTE_PUNCTUATION: scala.Byte = 30 + + final val MIN_RADIX = 2 + final val MAX_RADIX = 36 + + final val MIN_HIGH_SURROGATE = '\uD800' + final val MAX_HIGH_SURROGATE = '\uDBFF' + final val MIN_LOW_SURROGATE = '\uDC00' + final val MAX_LOW_SURROGATE = '\uDFFF' + final val MIN_SURROGATE = MIN_HIGH_SURROGATE + final val MAX_SURROGATE = MAX_LOW_SURROGATE + + final val MIN_CODE_POINT = 0 + final val MAX_CODE_POINT = 0x10ffff + final val MIN_SUPPLEMENTARY_CODE_POINT = 0x10000 + + // Hash code and toString --------------------------------------------------- + + @inline def hashCode(value: Char): Int = value.toInt + + @inline def toString(c: Char): String = + js.Dynamic.global.String.fromCharCode(c.toInt).asInstanceOf[String] + + def toString(codePoint: Int): String = { + if (isBmpCodePoint(codePoint)) { + js.Dynamic.global.String + .fromCharCode(codePoint) + .asInstanceOf[String] + } else if (isValidCodePoint(codePoint)) { + js.Dynamic.global.String + .fromCharCode(highSurrogate(codePoint).toInt, lowSurrogate(codePoint).toInt) + .asInstanceOf[String] + } else { + throw new IllegalArgumentException() + } + } + + // Low-level code point and code unit manipulations ------------------------- + + private final val HighSurrogateMask = 0xfc00 // 111111 00 00000000 + private final val HighSurrogateID = 0xd800 // 110110 00 00000000 + private final val LowSurrogateMask = 0xfc00 // 111111 00 00000000 + private final val LowSurrogateID = 0xdc00 // 110111 00 00000000 + private final val SurrogateMask = 0xf800 // 111110 00 00000000 + private final val SurrogateID = 0xd800 // 110110 00 00000000 + private final val SurrogateUsefulPartMask = 0x03ff // 000000 11 11111111 + + private final val SurrogatePairMask = (HighSurrogateMask << 16) | LowSurrogateMask + private final val SurrogatePairID = (HighSurrogateID << 16) | LowSurrogateID + + private final val HighSurrogateShift = 10 + private final val HighSurrogateAddValue = 0x10000 >> HighSurrogateShift + + @inline def isValidCodePoint(codePoint: Int): scala.Boolean = + (codePoint >= 0) && (codePoint <= MAX_CODE_POINT) + + @inline def isBmpCodePoint(codePoint: Int): scala.Boolean = + (codePoint >= 0) && (codePoint < MIN_SUPPLEMENTARY_CODE_POINT) + + @inline def isSupplementaryCodePoint(codePoint: Int): scala.Boolean = + (codePoint >= MIN_SUPPLEMENTARY_CODE_POINT) && (codePoint <= MAX_CODE_POINT) + + @inline def isHighSurrogate(ch: Char): scala.Boolean = + (ch & HighSurrogateMask) == HighSurrogateID + + @inline def isLowSurrogate(ch: Char): scala.Boolean = + (ch & LowSurrogateMask) == LowSurrogateID + + @inline def isSurrogate(ch: Char): scala.Boolean = + (ch & SurrogateMask) == SurrogateID + + @inline def isSurrogatePair(high: Char, low: Char): scala.Boolean = + (((high << 16) | low) & SurrogatePairMask) == SurrogatePairID + + @inline def charCount(codePoint: Int): Int = + if (codePoint >= MIN_SUPPLEMENTARY_CODE_POINT) 2 else 1 + + @inline def toCodePoint(high: Char, low: Char): Int = { + (((high & SurrogateUsefulPartMask) + HighSurrogateAddValue) << HighSurrogateShift) | + (low & SurrogateUsefulPartMask) + } + + @inline def highSurrogate(codePoint: Int): Char = + (HighSurrogateID | ((codePoint >> HighSurrogateShift) - HighSurrogateAddValue)).toChar + + @inline def lowSurrogate(codePoint: Int): Char = + (LowSurrogateID | (codePoint & SurrogateUsefulPartMask)).toChar + + // Code point manipulation in character sequences --------------------------- + + def toChars(codePoint: Int, dst: Array[Char], dstIndex: Int): Int = { + if (isBmpCodePoint(codePoint)) { + dst(dstIndex) = codePoint.toChar + 1 + } else if (isValidCodePoint(codePoint)) { + dst(dstIndex) = highSurrogate(codePoint) + dst(dstIndex + 1) = lowSurrogate(codePoint) + 2 + } else { + throw new IllegalArgumentException() + } + } + + def toChars(codePoint: Int): Array[Char] = { + if (isBmpCodePoint(codePoint)) + Array(codePoint.toChar) + else if (isValidCodePoint(codePoint)) + Array(highSurrogate(codePoint), lowSurrogate(codePoint)) + else + throw new IllegalArgumentException() + } + + def codePointCount(seq: CharSequence, beginIndex: Int, endIndex: Int): Int = { + if (endIndex > seq.length() || beginIndex < 0 || endIndex < beginIndex) + throw new IndexOutOfBoundsException + var res = endIndex - beginIndex + var i = beginIndex + val end = endIndex - 1 + while (i < end) { + if (isSurrogatePair(seq.charAt(i), seq.charAt(i + 1))) + res -= 1 + i += 1 + } + res + } + + // Unicode Character Database-related functions ----------------------------- + + def getType(ch: scala.Char): Int = getType(ch.toInt) + + def getType(codePoint: Int): Int = { + if (codePoint < 0) UNASSIGNED.toInt + else if (codePoint < 256) getTypeLT256(codePoint) + else getTypeGE256(codePoint) + } + + @inline + private[this] def getTypeLT256(codePoint: Int): Int = + charTypesFirst256(codePoint) + + private[this] def getTypeGE256(codePoint: Int): Int = { + charTypes(findIndexOfRange( + charTypeIndices, codePoint, hasEmptyRanges = false)) + } + + @inline + def digit(ch: scala.Char, radix: Int): Int = + digit(ch.toInt, radix) + + @inline // because radix is probably constant at call site + def digit(codePoint: Int, radix: Int): Int = { + if (radix > MAX_RADIX || radix < MIN_RADIX) + -1 + else + digitWithValidRadix(codePoint, radix) + } + + private[lang] def digitWithValidRadix(codePoint: Int, radix: Int): Int = { + val value = if (codePoint < 256) { + // Fast-path for the ASCII repertoire + if (codePoint >= '0' && codePoint <= '9') + codePoint - '0' + else if (codePoint >= 'A' && codePoint <= 'Z') + codePoint - ('A' - 10) + else if (codePoint >= 'a' && codePoint <= 'z') + codePoint - ('a' - 10) + else + -1 + } else { + if (codePoint >= 0xff21 && codePoint <= 0xff3a) { + // Fullwidth uppercase Latin letter + codePoint - (0xff21 - 10) + } else if (codePoint >= 0xff41 && codePoint <= 0xff5a) { + // Fullwidth lowercase Latin letter + codePoint - (0xff41 - 10) + } else { + // Maybe it is a digit in a non-ASCII script + + // Find the position of the 0 digit corresponding to this code point + val p = Arrays.binarySearch(nonASCIIZeroDigitCodePoints, codePoint) + val zeroCodePointIndex = if (p < 0) -2 - p else p + + /* If the index is below 0, it cannot be a digit. Otherwise, the value + * is the difference between the given codePoint and the code point of + * its corresponding 0. We must ensure that it is not bigger than 9. + */ + if (zeroCodePointIndex < 0) { + -1 + } else { + val v = codePoint - nonASCIIZeroDigitCodePoints(zeroCodePointIndex) + if (v > 9) -1 else v + } + } + } + + if (value < radix) value + else -1 + } + + private[lang] def isZeroDigit(ch: Char): scala.Boolean = + if (ch < 256) ch == '0' + else Arrays.binarySearch(nonASCIIZeroDigitCodePoints, ch.toInt) >= 0 + + // ported from https://github.com/gwtproject/gwt/blob/master/user/super/com/google/gwt/emul/java/lang/Character.java + def forDigit(digit: Int, radix: Int): Char = { + if (radix < MIN_RADIX || radix > MAX_RADIX || digit < 0 || digit >= radix) { + 0 + } else { + val overBaseTen = digit - 10 + val result = if (overBaseTen < 0) '0' + digit else 'a' + overBaseTen + result.toChar + } + } + + def isISOControl(c: scala.Char): scala.Boolean = isISOControl(c.toInt) + + def isISOControl(codePoint: Int): scala.Boolean = { + (0x00 <= codePoint && codePoint <= 0x1F) || (0x7F <= codePoint && codePoint <= 0x9F) + } + + @deprecated("Replaced by isWhitespace(char)", "") + def isSpace(c: scala.Char): scala.Boolean = + c == '\t' || c == '\n' || c == '\f' || c == '\r' || c == ' ' + + def isWhitespace(c: scala.Char): scala.Boolean = + isWhitespace(c.toInt) + + def isWhitespace(codePoint: scala.Int): scala.Boolean = { + def isSeparator(tpe: Int): scala.Boolean = + tpe == SPACE_SEPARATOR || tpe == LINE_SEPARATOR || tpe == PARAGRAPH_SEPARATOR + if (codePoint < 256) { + codePoint == '\t' || codePoint == '\n' || codePoint == '\u000B' || + codePoint == '\f' || codePoint == '\r' || + ('\u001C' <= codePoint && codePoint <= '\u001F') || + (codePoint != '\u00A0' && isSeparator(getTypeLT256(codePoint))) + } else { + (codePoint != '\u2007' && codePoint != '\u202F') && + isSeparator(getTypeGE256(codePoint)) + } + } + + def isSpaceChar(ch: scala.Char): scala.Boolean = + isSpaceChar(ch.toInt) + + def isSpaceChar(codePoint: Int): scala.Boolean = + isSpaceCharImpl(getType(codePoint)) + + @inline private[this] def isSpaceCharImpl(tpe: Int): scala.Boolean = + tpe == SPACE_SEPARATOR || tpe == LINE_SEPARATOR || tpe == PARAGRAPH_SEPARATOR + + def isLowerCase(c: scala.Char): scala.Boolean = + isLowerCase(c.toInt) + + def isLowerCase(c: Int): scala.Boolean = { + if (c < 256) + c == '\u00AA' || c == '\u00BA' || getTypeLT256(c) == LOWERCASE_LETTER + else + isLowerCaseGE256(c) + } + + private[this] def isLowerCaseGE256(c: Int): scala.Boolean = { + ('\u02B0' <= c && c <= '\u02B8') || ('\u02C0' <= c && c <= '\u02C1') || + ('\u02E0' <= c && c <= '\u02E4') || c == '\u0345' || c == '\u037A' || + ('\u1D2C' <= c && c <= '\u1D6A') || c == '\u1D78' || + ('\u1D9B' <= c && c <= '\u1DBF') || c == '\u2071' || c == '\u207F' || + ('\u2090' <= c && c <= '\u209C') || ('\u2170' <= c && c <= '\u217F') || + ('\u24D0' <= c && c <= '\u24E9') || ('\u2C7C' <= c && c <= '\u2C7D') || + c == '\uA770' || ('\uA7F8' <= c && c <= '\uA7F9') || + getTypeGE256(c) == LOWERCASE_LETTER + } + + def isUpperCase(c: scala.Char): scala.Boolean = + isUpperCase(c.toInt) + + def isUpperCase(c: Int): scala.Boolean = { + ('\u2160' <= c && c <= '\u216F') || ('\u24B6' <= c && c <= '\u24CF') || + getType(c) == UPPERCASE_LETTER + } + + def isTitleCase(c: scala.Char): scala.Boolean = + isTitleCase(c.toInt) + + def isTitleCase(cp: Int): scala.Boolean = + if (cp < 256) false + else isTitleCaseImpl(getTypeGE256(cp)) + + @inline private[this] def isTitleCaseImpl(tpe: Int): scala.Boolean = + tpe == TITLECASE_LETTER + + def isDigit(c: scala.Char): scala.Boolean = + isDigit(c.toInt) + + def isDigit(cp: Int): scala.Boolean = + if (cp < 256) '0' <= cp && cp <= '9' + else isDigitImpl(getTypeGE256(cp)) + + @inline private[this] def isDigitImpl(tpe: Int): scala.Boolean = + tpe == DECIMAL_DIGIT_NUMBER + + def isDefined(c: scala.Char): scala.Boolean = + isDefined(c.toInt) + + def isDefined(c: scala.Int): scala.Boolean = { + if (c < 0) false + else if (c < 888) true + else getTypeGE256(c) != UNASSIGNED + } + + def isLetter(c: scala.Char): scala.Boolean = isLetter(c.toInt) + + def isLetter(cp: Int): scala.Boolean = isLetterImpl(getType(cp)) + + @inline private[this] def isLetterImpl(tpe: Int): scala.Boolean = { + tpe == UPPERCASE_LETTER || tpe == LOWERCASE_LETTER || + tpe == TITLECASE_LETTER || tpe == MODIFIER_LETTER || tpe == OTHER_LETTER + } + + def isLetterOrDigit(c: scala.Char): scala.Boolean = + isLetterOrDigit(c.toInt) + + def isLetterOrDigit(cp: Int): scala.Boolean = + isLetterOrDigitImpl(getType(cp)) + + @inline private[this] def isLetterOrDigitImpl(tpe: Int): scala.Boolean = + isDigitImpl(tpe) || isLetterImpl(tpe) + + def isJavaLetter(ch: scala.Char): scala.Boolean = isJavaLetterImpl(getType(ch)) + + @inline private[this] def isJavaLetterImpl(tpe: Int): scala.Boolean = { + isLetterImpl(tpe) || tpe == LETTER_NUMBER || tpe == CURRENCY_SYMBOL || + tpe == CONNECTOR_PUNCTUATION + } + + def isJavaLetterOrDigit(ch: scala.Char): scala.Boolean = + isJavaLetterOrDigitImpl(ch, getType(ch)) + + @inline private[this] def isJavaLetterOrDigitImpl(codePoint: Int, + tpe: Int): scala.Boolean = { + isJavaLetterImpl(tpe) || tpe == COMBINING_SPACING_MARK || + tpe == NON_SPACING_MARK || isIdentifierIgnorableImpl(codePoint, tpe) + } + + def isAlphabetic(codePoint: Int): scala.Boolean = { + val tpe = getType(codePoint) + tpe == UPPERCASE_LETTER || tpe == LOWERCASE_LETTER || + tpe == TITLECASE_LETTER || tpe == MODIFIER_LETTER || + tpe == OTHER_LETTER || tpe == LETTER_NUMBER + } + + def isIdeographic(c: Int): scala.Boolean = { + (12294 <= c && c <= 12295) || (12321 <= c && c <= 12329) || + (12344 <= c && c <= 12346) || (13312 <= c && c <= 19893) || + (19968 <= c && c <= 40908) || (63744 <= c && c <= 64109) || + (64112 <= c && c <= 64217) || (131072 <= c && c <= 173782) || + (173824 <= c && c <= 177972) || (177984 <= c && c <= 178205) || + (194560 <= c && c <= 195101) + } + + def isJavaIdentifierStart(ch: scala.Char): scala.Boolean = + isJavaIdentifierStart(ch.toInt) + + def isJavaIdentifierStart(codePoint: Int): scala.Boolean = + isJavaIdentifierStartImpl(getType(codePoint)) + + @inline + private[this] def isJavaIdentifierStartImpl(tpe: Int): scala.Boolean = { + isLetterImpl(tpe) || tpe == LETTER_NUMBER || tpe == CURRENCY_SYMBOL || + tpe == CONNECTOR_PUNCTUATION + } + + def isJavaIdentifierPart(ch: scala.Char): scala.Boolean = + isJavaIdentifierPart(ch.toInt) + + def isJavaIdentifierPart(codePoint: Int): scala.Boolean = + isJavaIdentifierPartImpl(codePoint, getType(codePoint)) + + @inline private[this] def isJavaIdentifierPartImpl(codePoint: Int, + tpe: Int): scala.Boolean = { + isLetterImpl(tpe) || tpe == CURRENCY_SYMBOL || + tpe == CONNECTOR_PUNCTUATION || tpe == DECIMAL_DIGIT_NUMBER || + tpe == LETTER_NUMBER || tpe == COMBINING_SPACING_MARK || + tpe == NON_SPACING_MARK || isIdentifierIgnorableImpl(codePoint, tpe) + } + + def isUnicodeIdentifierStart(ch: scala.Char): scala.Boolean = + isUnicodeIdentifierStart(ch.toInt) + + def isUnicodeIdentifierStart(codePoint: Int): scala.Boolean = + isUnicodeIdentifierStartImpl(getType(codePoint)) + + @inline + private[this] def isUnicodeIdentifierStartImpl(tpe: Int): scala.Boolean = + isLetterImpl(tpe) || tpe == LETTER_NUMBER + + def isUnicodeIdentifierPart(ch: scala.Char): scala.Boolean = + isUnicodeIdentifierPart(ch.toInt) + + def isUnicodeIdentifierPart(codePoint: Int): scala.Boolean = + isUnicodeIdentifierPartImpl(codePoint, getType(codePoint)) + + def isUnicodeIdentifierPartImpl(codePoint: Int, + tpe: Int): scala.Boolean = { + tpe == CONNECTOR_PUNCTUATION || tpe == DECIMAL_DIGIT_NUMBER || + tpe == COMBINING_SPACING_MARK || tpe == NON_SPACING_MARK || + isUnicodeIdentifierStartImpl(tpe) || + isIdentifierIgnorableImpl(codePoint, tpe) + } + + def isIdentifierIgnorable(c: scala.Char): scala.Boolean = + isIdentifierIgnorable(c.toInt) + + def isIdentifierIgnorable(codePoint: Int): scala.Boolean = + isIdentifierIgnorableImpl(codePoint, getType(codePoint)) + + @inline private[this] def isIdentifierIgnorableImpl(codePoint: Int, + tpe: Int): scala.Boolean = { + ('\u0000' <= codePoint && codePoint <= '\u0008') || + ('\u000E' <= codePoint && codePoint <= '\u001B') || + ('\u007F' <= codePoint && codePoint <= '\u009F') || + tpe == FORMAT + } + + def isMirrored(c: scala.Char): scala.Boolean = + isMirrored(c.toInt) + + def isMirrored(codePoint: Int): scala.Boolean = { + val indexOfRange = findIndexOfRange( + isMirroredIndices, codePoint, hasEmptyRanges = false) + (indexOfRange & 1) != 0 + } + + //def getDirectionality(c: scala.Char): scala.Byte + + /* Conversions */ + def toUpperCase(ch: Char): Char = toUpperCase(ch.toInt).toChar + + def toUpperCase(codePoint: scala.Int): scala.Int = { + codePoint match { + case 0x1fb3 | 0x1fc3 | 0x1ff3 => + (codePoint + 0x0009) + case _ if codePoint >= 0x1f80 && codePoint <= 0x1faf => + (codePoint | 0x0008) + case _ => + val upperChars = toString(codePoint).toUpperCase() + upperChars.length match { + case 1 => + upperChars.charAt(0).toInt + case 2 => + val high = upperChars.charAt(0) + val low = upperChars.charAt(1) + if (isSurrogatePair(high, low)) + toCodePoint(high, low) + else + codePoint + case _ => + codePoint + } + } + } + + def toLowerCase(ch: scala.Char): scala.Char = toLowerCase(ch.toInt).toChar + + def toLowerCase(codePoint: scala.Int): scala.Int = { + codePoint match { + case 0x0130 => + 0x0069 // İ => i + case _ => + val lowerChars = toString(codePoint).toLowerCase() + lowerChars.length match { + case 1 => + lowerChars.charAt(0).toInt + case 2 => + val high = lowerChars.charAt(0) + val low = lowerChars.charAt(1) + if (isSurrogatePair(high, low)) + toCodePoint(high, low) + else + codePoint + case _ => + codePoint + } + } + } + + def toTitleCase(ch: scala.Char): scala.Char = toTitleCase(ch.toInt).toChar + +/* +def format(codePoint: Int): String = "0x%04x".format(codePoint) + +for (cp <- 0 to Character.MAX_CODE_POINT) { + val titleCaseCP: Int = Character.toTitleCase(cp) + val upperCaseCP: Int = Character.toUpperCase(cp) + + if (titleCaseCP != upperCaseCP) { + println(s" case ${format(cp)} => ${format(titleCaseCP)}") + } +} +*/ + def toTitleCase(codePoint: scala.Int): scala.Int = { + (codePoint: @switch) match { + case 0x01c4 => 0x01c5 + case 0x01c5 => 0x01c5 + case 0x01c6 => 0x01c5 + case 0x01c7 => 0x01c8 + case 0x01c8 => 0x01c8 + case 0x01c9 => 0x01c8 + case 0x01ca => 0x01cb + case 0x01cb => 0x01cb + case 0x01cc => 0x01cb + case 0x01f1 => 0x01f2 + case 0x01f2 => 0x01f2 + case 0x01f3 => 0x01f2 + case _ => toUpperCase(codePoint) + } + } + + //def getNumericValue(c: scala.Char): Int + + // Miscellaneous ------------------------------------------------------------ + + @inline def compare(x: scala.Char, y: scala.Char): Int = + x - y + + @inline def reverseBytes(ch: scala.Char): scala.Char = + ((ch >> 8) | (ch << 8)).toChar + + // UnicodeBlock + + class Subset protected (name: String) { + override final def equals(that: Any): scala.Boolean = super.equals(that) + override final def hashCode(): scala.Int = super.hashCode + override final def toString(): String = name + } + + final class UnicodeBlock private (name: String, + private val start: Int, private val end: Int) extends Subset(name) + + object UnicodeBlock { + // Initial size from script below + private[this] val allBlocks: ArrayList[UnicodeBlock] = new ArrayList[UnicodeBlock](220) + private[this] val blocksByNormalizedName = new HashMap[String, UnicodeBlock]() + + private[this] def addNameAliases(properName: String, block: UnicodeBlock): Unit = { + // Add normalized aliases + val lower = properName.toLowerCase + // lowercase + spaces + blocksByNormalizedName.put(lower, block) + // lowercase + no spaces + blocksByNormalizedName.put(lower.replace(" ", ""), block) + } + + private[this] def addUnicodeBlock(properName: String, start: Int, end: Int): UnicodeBlock = { + val jvmName = properName.toUpperCase() + .replace(' ', '_') + .replace('-', '_') + + val block = new UnicodeBlock(jvmName, start, end) + allBlocks.add(block) + addNameAliases(properName, block) + blocksByNormalizedName.put(jvmName.toLowerCase(), block) + + block + } + + private[this] def addUnicodeBlock(properName: String, historicalName: String, + start: Int, end: Int): UnicodeBlock = { + val jvmName = historicalName.toUpperCase() + .replace(' ', '_') + .replace('-', '_') + + val block = new UnicodeBlock(jvmName, start, end) + allBlocks.add(block) + addNameAliases(properName, block) + addNameAliases(historicalName, block) + blocksByNormalizedName.put(jvmName.toLowerCase(), block) + + block + } + + // Special JVM Constant, don't add to allBlocks + val SURROGATES_AREA = new UnicodeBlock("SURROGATES_AREA", 0x0, 0x0) + blocksByNormalizedName.put("surrogates_area", SURROGATES_AREA) + +/* + // JVMName -> (historicalName, properName) + val historicalMap = Map( + "GREEK" -> ("Greek", "Greek and Coptic"), + "CYRILLIC_SUPPLEMENTARY" -> ("Cyrillic Supplementary", "Cyrillic Supplement"), + "COMBINING_MARKS_FOR_SYMBOLS" -> ("Combining Marks For Symbols", "Combining Diacritical Marks for Symbols") + ) + + // Get the "proper name" for JVM block name + val blockNameMap: Map[String, String] = { + val blocksSourceURL = new java.net.URL("http://unicode.org/Public/UCD/latest/ucd/Blocks.txt") + val source = scala.io.Source.fromURL(blocksSourceURL, "UTF-8") + source + .getLines() + .filterNot { + _.startsWith("#") + } + .flatMap { line => + line.split(';') match { + case Array(_, name) => + val trimmed = name.trim + val jvmName = trimmed.replaceAll(raw"[\s\-]", "_").toUpperCase + Some(jvmName -> trimmed) + case _ => None + } + }.toMap + } + + val blocksAndCharacters = (0 to Character.MAX_CODE_POINT) + .map(cp => Character.UnicodeBlock.of(cp) -> cp).filterNot(_._1 == null) + + val orderedBlocks = blocksAndCharacters.map(_._1).distinct + + val blockLowAndHighCodePointsMap = { + blocksAndCharacters.groupBy(_._1).mapValues { v => + val codePoints = v.map(_._2) + (codePoints.min, codePoints.max) + } + } + + println("private[this] val allBlocks: ArrayList[UnicodeBlock] = " + + s"new ArrayList[UnicodeBlock](${orderedBlocks.size})\n\n\n\n") + + orderedBlocks.foreach { b => + val minCodePoint = "0x%04x".format(blockLowAndHighCodePointsMap(b)._1) + val maxCodePoint = "0x%04x".format(blockLowAndHighCodePointsMap(b)._2) + + historicalMap.get(b.toString) match { + case Some((historicalName, properName)) => + println(s""" val $b = addUnicodeBlock("$properName", "$historicalName", $minCodePoint, $maxCodePoint)""") + case None => + val properBlockName = blockNameMap.getOrElse(b.toString, throw new IllegalArgumentException("$b")) + val jvmBlockName = properBlockName.toUpperCase.replaceAll("[\\s\\-_]", "_") + assert(jvmBlockName == b.toString) + println(s""" val $jvmBlockName = addUnicodeBlock("$properBlockName", $minCodePoint, $maxCodePoint)""") + } + } +*/ + + ////////////////////////////////////////////////////////////////////////// + // Begin Generated, last updated with (AdoptOpenJDK) (build 1.8.0_265-b01) + ////////////////////////////////////////////////////////////////////////// + // scalastyle:off line.size.limit + + val BASIC_LATIN = addUnicodeBlock("Basic Latin", 0x0000, 0x007f) + val LATIN_1_SUPPLEMENT = addUnicodeBlock("Latin-1 Supplement", 0x0080, 0x00ff) + val LATIN_EXTENDED_A = addUnicodeBlock("Latin Extended-A", 0x0100, 0x017f) + val LATIN_EXTENDED_B = addUnicodeBlock("Latin Extended-B", 0x0180, 0x024f) + val IPA_EXTENSIONS = addUnicodeBlock("IPA Extensions", 0x0250, 0x02af) + val SPACING_MODIFIER_LETTERS = addUnicodeBlock("Spacing Modifier Letters", 0x02b0, 0x02ff) + val COMBINING_DIACRITICAL_MARKS = addUnicodeBlock("Combining Diacritical Marks", 0x0300, 0x036f) + val GREEK = addUnicodeBlock("Greek and Coptic", "Greek", 0x0370, 0x03ff) + val CYRILLIC = addUnicodeBlock("Cyrillic", 0x0400, 0x04ff) + val CYRILLIC_SUPPLEMENTARY = addUnicodeBlock("Cyrillic Supplement", "Cyrillic Supplementary", 0x0500, 0x052f) + val ARMENIAN = addUnicodeBlock("Armenian", 0x0530, 0x058f) + val HEBREW = addUnicodeBlock("Hebrew", 0x0590, 0x05ff) + val ARABIC = addUnicodeBlock("Arabic", 0x0600, 0x06ff) + val SYRIAC = addUnicodeBlock("Syriac", 0x0700, 0x074f) + val ARABIC_SUPPLEMENT = addUnicodeBlock("Arabic Supplement", 0x0750, 0x077f) + val THAANA = addUnicodeBlock("Thaana", 0x0780, 0x07bf) + val NKO = addUnicodeBlock("NKo", 0x07c0, 0x07ff) + val SAMARITAN = addUnicodeBlock("Samaritan", 0x0800, 0x083f) + val MANDAIC = addUnicodeBlock("Mandaic", 0x0840, 0x085f) + val ARABIC_EXTENDED_A = addUnicodeBlock("Arabic Extended-A", 0x08a0, 0x08ff) + val DEVANAGARI = addUnicodeBlock("Devanagari", 0x0900, 0x097f) + val BENGALI = addUnicodeBlock("Bengali", 0x0980, 0x09ff) + val GURMUKHI = addUnicodeBlock("Gurmukhi", 0x0a00, 0x0a7f) + val GUJARATI = addUnicodeBlock("Gujarati", 0x0a80, 0x0aff) + val ORIYA = addUnicodeBlock("Oriya", 0x0b00, 0x0b7f) + val TAMIL = addUnicodeBlock("Tamil", 0x0b80, 0x0bff) + val TELUGU = addUnicodeBlock("Telugu", 0x0c00, 0x0c7f) + val KANNADA = addUnicodeBlock("Kannada", 0x0c80, 0x0cff) + val MALAYALAM = addUnicodeBlock("Malayalam", 0x0d00, 0x0d7f) + val SINHALA = addUnicodeBlock("Sinhala", 0x0d80, 0x0dff) + val THAI = addUnicodeBlock("Thai", 0x0e00, 0x0e7f) + val LAO = addUnicodeBlock("Lao", 0x0e80, 0x0eff) + val TIBETAN = addUnicodeBlock("Tibetan", 0x0f00, 0x0fff) + val MYANMAR = addUnicodeBlock("Myanmar", 0x1000, 0x109f) + val GEORGIAN = addUnicodeBlock("Georgian", 0x10a0, 0x10ff) + val HANGUL_JAMO = addUnicodeBlock("Hangul Jamo", 0x1100, 0x11ff) + val ETHIOPIC = addUnicodeBlock("Ethiopic", 0x1200, 0x137f) + val ETHIOPIC_SUPPLEMENT = addUnicodeBlock("Ethiopic Supplement", 0x1380, 0x139f) + val CHEROKEE = addUnicodeBlock("Cherokee", 0x13a0, 0x13ff) + val UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS = addUnicodeBlock("Unified Canadian Aboriginal Syllabics", 0x1400, 0x167f) + val OGHAM = addUnicodeBlock("Ogham", 0x1680, 0x169f) + val RUNIC = addUnicodeBlock("Runic", 0x16a0, 0x16ff) + val TAGALOG = addUnicodeBlock("Tagalog", 0x1700, 0x171f) + val HANUNOO = addUnicodeBlock("Hanunoo", 0x1720, 0x173f) + val BUHID = addUnicodeBlock("Buhid", 0x1740, 0x175f) + val TAGBANWA = addUnicodeBlock("Tagbanwa", 0x1760, 0x177f) + val KHMER = addUnicodeBlock("Khmer", 0x1780, 0x17ff) + val MONGOLIAN = addUnicodeBlock("Mongolian", 0x1800, 0x18af) + val UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS_EXTENDED = addUnicodeBlock("Unified Canadian Aboriginal Syllabics Extended", 0x18b0, 0x18ff) + val LIMBU = addUnicodeBlock("Limbu", 0x1900, 0x194f) + val TAI_LE = addUnicodeBlock("Tai Le", 0x1950, 0x197f) + val NEW_TAI_LUE = addUnicodeBlock("New Tai Lue", 0x1980, 0x19df) + val KHMER_SYMBOLS = addUnicodeBlock("Khmer Symbols", 0x19e0, 0x19ff) + val BUGINESE = addUnicodeBlock("Buginese", 0x1a00, 0x1a1f) + val TAI_THAM = addUnicodeBlock("Tai Tham", 0x1a20, 0x1aaf) + val BALINESE = addUnicodeBlock("Balinese", 0x1b00, 0x1b7f) + val SUNDANESE = addUnicodeBlock("Sundanese", 0x1b80, 0x1bbf) + val BATAK = addUnicodeBlock("Batak", 0x1bc0, 0x1bff) + val LEPCHA = addUnicodeBlock("Lepcha", 0x1c00, 0x1c4f) + val OL_CHIKI = addUnicodeBlock("Ol Chiki", 0x1c50, 0x1c7f) + val SUNDANESE_SUPPLEMENT = addUnicodeBlock("Sundanese Supplement", 0x1cc0, 0x1ccf) + val VEDIC_EXTENSIONS = addUnicodeBlock("Vedic Extensions", 0x1cd0, 0x1cff) + val PHONETIC_EXTENSIONS = addUnicodeBlock("Phonetic Extensions", 0x1d00, 0x1d7f) + val PHONETIC_EXTENSIONS_SUPPLEMENT = addUnicodeBlock("Phonetic Extensions Supplement", 0x1d80, 0x1dbf) + val COMBINING_DIACRITICAL_MARKS_SUPPLEMENT = addUnicodeBlock("Combining Diacritical Marks Supplement", 0x1dc0, 0x1dff) + val LATIN_EXTENDED_ADDITIONAL = addUnicodeBlock("Latin Extended Additional", 0x1e00, 0x1eff) + val GREEK_EXTENDED = addUnicodeBlock("Greek Extended", 0x1f00, 0x1fff) + val GENERAL_PUNCTUATION = addUnicodeBlock("General Punctuation", 0x2000, 0x206f) + val SUPERSCRIPTS_AND_SUBSCRIPTS = addUnicodeBlock("Superscripts and Subscripts", 0x2070, 0x209f) + val CURRENCY_SYMBOLS = addUnicodeBlock("Currency Symbols", 0x20a0, 0x20cf) + val COMBINING_MARKS_FOR_SYMBOLS = addUnicodeBlock("Combining Diacritical Marks for Symbols", "Combining Marks For Symbols", 0x20d0, 0x20ff) + val LETTERLIKE_SYMBOLS = addUnicodeBlock("Letterlike Symbols", 0x2100, 0x214f) + val NUMBER_FORMS = addUnicodeBlock("Number Forms", 0x2150, 0x218f) + val ARROWS = addUnicodeBlock("Arrows", 0x2190, 0x21ff) + val MATHEMATICAL_OPERATORS = addUnicodeBlock("Mathematical Operators", 0x2200, 0x22ff) + val MISCELLANEOUS_TECHNICAL = addUnicodeBlock("Miscellaneous Technical", 0x2300, 0x23ff) + val CONTROL_PICTURES = addUnicodeBlock("Control Pictures", 0x2400, 0x243f) + val OPTICAL_CHARACTER_RECOGNITION = addUnicodeBlock("Optical Character Recognition", 0x2440, 0x245f) + val ENCLOSED_ALPHANUMERICS = addUnicodeBlock("Enclosed Alphanumerics", 0x2460, 0x24ff) + val BOX_DRAWING = addUnicodeBlock("Box Drawing", 0x2500, 0x257f) + val BLOCK_ELEMENTS = addUnicodeBlock("Block Elements", 0x2580, 0x259f) + val GEOMETRIC_SHAPES = addUnicodeBlock("Geometric Shapes", 0x25a0, 0x25ff) + val MISCELLANEOUS_SYMBOLS = addUnicodeBlock("Miscellaneous Symbols", 0x2600, 0x26ff) + val DINGBATS = addUnicodeBlock("Dingbats", 0x2700, 0x27bf) + val MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A = addUnicodeBlock("Miscellaneous Mathematical Symbols-A", 0x27c0, 0x27ef) + val SUPPLEMENTAL_ARROWS_A = addUnicodeBlock("Supplemental Arrows-A", 0x27f0, 0x27ff) + val BRAILLE_PATTERNS = addUnicodeBlock("Braille Patterns", 0x2800, 0x28ff) + val SUPPLEMENTAL_ARROWS_B = addUnicodeBlock("Supplemental Arrows-B", 0x2900, 0x297f) + val MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B = addUnicodeBlock("Miscellaneous Mathematical Symbols-B", 0x2980, 0x29ff) + val SUPPLEMENTAL_MATHEMATICAL_OPERATORS = addUnicodeBlock("Supplemental Mathematical Operators", 0x2a00, 0x2aff) + val MISCELLANEOUS_SYMBOLS_AND_ARROWS = addUnicodeBlock("Miscellaneous Symbols and Arrows", 0x2b00, 0x2bff) + val GLAGOLITIC = addUnicodeBlock("Glagolitic", 0x2c00, 0x2c5f) + val LATIN_EXTENDED_C = addUnicodeBlock("Latin Extended-C", 0x2c60, 0x2c7f) + val COPTIC = addUnicodeBlock("Coptic", 0x2c80, 0x2cff) + val GEORGIAN_SUPPLEMENT = addUnicodeBlock("Georgian Supplement", 0x2d00, 0x2d2f) + val TIFINAGH = addUnicodeBlock("Tifinagh", 0x2d30, 0x2d7f) + val ETHIOPIC_EXTENDED = addUnicodeBlock("Ethiopic Extended", 0x2d80, 0x2ddf) + val CYRILLIC_EXTENDED_A = addUnicodeBlock("Cyrillic Extended-A", 0x2de0, 0x2dff) + val SUPPLEMENTAL_PUNCTUATION = addUnicodeBlock("Supplemental Punctuation", 0x2e00, 0x2e7f) + val CJK_RADICALS_SUPPLEMENT = addUnicodeBlock("CJK Radicals Supplement", 0x2e80, 0x2eff) + val KANGXI_RADICALS = addUnicodeBlock("Kangxi Radicals", 0x2f00, 0x2fdf) + val IDEOGRAPHIC_DESCRIPTION_CHARACTERS = addUnicodeBlock("Ideographic Description Characters", 0x2ff0, 0x2fff) + val CJK_SYMBOLS_AND_PUNCTUATION = addUnicodeBlock("CJK Symbols and Punctuation", 0x3000, 0x303f) + val HIRAGANA = addUnicodeBlock("Hiragana", 0x3040, 0x309f) + val KATAKANA = addUnicodeBlock("Katakana", 0x30a0, 0x30ff) + val BOPOMOFO = addUnicodeBlock("Bopomofo", 0x3100, 0x312f) + val HANGUL_COMPATIBILITY_JAMO = addUnicodeBlock("Hangul Compatibility Jamo", 0x3130, 0x318f) + val KANBUN = addUnicodeBlock("Kanbun", 0x3190, 0x319f) + val BOPOMOFO_EXTENDED = addUnicodeBlock("Bopomofo Extended", 0x31a0, 0x31bf) + val CJK_STROKES = addUnicodeBlock("CJK Strokes", 0x31c0, 0x31ef) + val KATAKANA_PHONETIC_EXTENSIONS = addUnicodeBlock("Katakana Phonetic Extensions", 0x31f0, 0x31ff) + val ENCLOSED_CJK_LETTERS_AND_MONTHS = addUnicodeBlock("Enclosed CJK Letters and Months", 0x3200, 0x32ff) + val CJK_COMPATIBILITY = addUnicodeBlock("CJK Compatibility", 0x3300, 0x33ff) + val CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A = addUnicodeBlock("CJK Unified Ideographs Extension A", 0x3400, 0x4dbf) + val YIJING_HEXAGRAM_SYMBOLS = addUnicodeBlock("Yijing Hexagram Symbols", 0x4dc0, 0x4dff) + val CJK_UNIFIED_IDEOGRAPHS = addUnicodeBlock("CJK Unified Ideographs", 0x4e00, 0x9fff) + val YI_SYLLABLES = addUnicodeBlock("Yi Syllables", 0xa000, 0xa48f) + val YI_RADICALS = addUnicodeBlock("Yi Radicals", 0xa490, 0xa4cf) + val LISU = addUnicodeBlock("Lisu", 0xa4d0, 0xa4ff) + val VAI = addUnicodeBlock("Vai", 0xa500, 0xa63f) + val CYRILLIC_EXTENDED_B = addUnicodeBlock("Cyrillic Extended-B", 0xa640, 0xa69f) + val BAMUM = addUnicodeBlock("Bamum", 0xa6a0, 0xa6ff) + val MODIFIER_TONE_LETTERS = addUnicodeBlock("Modifier Tone Letters", 0xa700, 0xa71f) + val LATIN_EXTENDED_D = addUnicodeBlock("Latin Extended-D", 0xa720, 0xa7ff) + val SYLOTI_NAGRI = addUnicodeBlock("Syloti Nagri", 0xa800, 0xa82f) + val COMMON_INDIC_NUMBER_FORMS = addUnicodeBlock("Common Indic Number Forms", 0xa830, 0xa83f) + val PHAGS_PA = addUnicodeBlock("Phags-pa", 0xa840, 0xa87f) + val SAURASHTRA = addUnicodeBlock("Saurashtra", 0xa880, 0xa8df) + val DEVANAGARI_EXTENDED = addUnicodeBlock("Devanagari Extended", 0xa8e0, 0xa8ff) + val KAYAH_LI = addUnicodeBlock("Kayah Li", 0xa900, 0xa92f) + val REJANG = addUnicodeBlock("Rejang", 0xa930, 0xa95f) + val HANGUL_JAMO_EXTENDED_A = addUnicodeBlock("Hangul Jamo Extended-A", 0xa960, 0xa97f) + val JAVANESE = addUnicodeBlock("Javanese", 0xa980, 0xa9df) + val CHAM = addUnicodeBlock("Cham", 0xaa00, 0xaa5f) + val MYANMAR_EXTENDED_A = addUnicodeBlock("Myanmar Extended-A", 0xaa60, 0xaa7f) + val TAI_VIET = addUnicodeBlock("Tai Viet", 0xaa80, 0xaadf) + val MEETEI_MAYEK_EXTENSIONS = addUnicodeBlock("Meetei Mayek Extensions", 0xaae0, 0xaaff) + val ETHIOPIC_EXTENDED_A = addUnicodeBlock("Ethiopic Extended-A", 0xab00, 0xab2f) + val MEETEI_MAYEK = addUnicodeBlock("Meetei Mayek", 0xabc0, 0xabff) + val HANGUL_SYLLABLES = addUnicodeBlock("Hangul Syllables", 0xac00, 0xd7af) + val HANGUL_JAMO_EXTENDED_B = addUnicodeBlock("Hangul Jamo Extended-B", 0xd7b0, 0xd7ff) + val HIGH_SURROGATES = addUnicodeBlock("High Surrogates", 0xd800, 0xdb7f) + val HIGH_PRIVATE_USE_SURROGATES = addUnicodeBlock("High Private Use Surrogates", 0xdb80, 0xdbff) + val LOW_SURROGATES = addUnicodeBlock("Low Surrogates", 0xdc00, 0xdfff) + val PRIVATE_USE_AREA = addUnicodeBlock("Private Use Area", 0xe000, 0xf8ff) + val CJK_COMPATIBILITY_IDEOGRAPHS = addUnicodeBlock("CJK Compatibility Ideographs", 0xf900, 0xfaff) + val ALPHABETIC_PRESENTATION_FORMS = addUnicodeBlock("Alphabetic Presentation Forms", 0xfb00, 0xfb4f) + val ARABIC_PRESENTATION_FORMS_A = addUnicodeBlock("Arabic Presentation Forms-A", 0xfb50, 0xfdff) + val VARIATION_SELECTORS = addUnicodeBlock("Variation Selectors", 0xfe00, 0xfe0f) + val VERTICAL_FORMS = addUnicodeBlock("Vertical Forms", 0xfe10, 0xfe1f) + val COMBINING_HALF_MARKS = addUnicodeBlock("Combining Half Marks", 0xfe20, 0xfe2f) + val CJK_COMPATIBILITY_FORMS = addUnicodeBlock("CJK Compatibility Forms", 0xfe30, 0xfe4f) + val SMALL_FORM_VARIANTS = addUnicodeBlock("Small Form Variants", 0xfe50, 0xfe6f) + val ARABIC_PRESENTATION_FORMS_B = addUnicodeBlock("Arabic Presentation Forms-B", 0xfe70, 0xfeff) + val HALFWIDTH_AND_FULLWIDTH_FORMS = addUnicodeBlock("Halfwidth and Fullwidth Forms", 0xff00, 0xffef) + val SPECIALS = addUnicodeBlock("Specials", 0xfff0, 0xffff) + val LINEAR_B_SYLLABARY = addUnicodeBlock("Linear B Syllabary", 0x10000, 0x1007f) + val LINEAR_B_IDEOGRAMS = addUnicodeBlock("Linear B Ideograms", 0x10080, 0x100ff) + val AEGEAN_NUMBERS = addUnicodeBlock("Aegean Numbers", 0x10100, 0x1013f) + val ANCIENT_GREEK_NUMBERS = addUnicodeBlock("Ancient Greek Numbers", 0x10140, 0x1018f) + val ANCIENT_SYMBOLS = addUnicodeBlock("Ancient Symbols", 0x10190, 0x101cf) + val PHAISTOS_DISC = addUnicodeBlock("Phaistos Disc", 0x101d0, 0x101ff) + val LYCIAN = addUnicodeBlock("Lycian", 0x10280, 0x1029f) + val CARIAN = addUnicodeBlock("Carian", 0x102a0, 0x102df) + val OLD_ITALIC = addUnicodeBlock("Old Italic", 0x10300, 0x1032f) + val GOTHIC = addUnicodeBlock("Gothic", 0x10330, 0x1034f) + val UGARITIC = addUnicodeBlock("Ugaritic", 0x10380, 0x1039f) + val OLD_PERSIAN = addUnicodeBlock("Old Persian", 0x103a0, 0x103df) + val DESERET = addUnicodeBlock("Deseret", 0x10400, 0x1044f) + val SHAVIAN = addUnicodeBlock("Shavian", 0x10450, 0x1047f) + val OSMANYA = addUnicodeBlock("Osmanya", 0x10480, 0x104af) + val CYPRIOT_SYLLABARY = addUnicodeBlock("Cypriot Syllabary", 0x10800, 0x1083f) + val IMPERIAL_ARAMAIC = addUnicodeBlock("Imperial Aramaic", 0x10840, 0x1085f) + val PHOENICIAN = addUnicodeBlock("Phoenician", 0x10900, 0x1091f) + val LYDIAN = addUnicodeBlock("Lydian", 0x10920, 0x1093f) + val MEROITIC_HIEROGLYPHS = addUnicodeBlock("Meroitic Hieroglyphs", 0x10980, 0x1099f) + val MEROITIC_CURSIVE = addUnicodeBlock("Meroitic Cursive", 0x109a0, 0x109ff) + val KHAROSHTHI = addUnicodeBlock("Kharoshthi", 0x10a00, 0x10a5f) + val OLD_SOUTH_ARABIAN = addUnicodeBlock("Old South Arabian", 0x10a60, 0x10a7f) + val AVESTAN = addUnicodeBlock("Avestan", 0x10b00, 0x10b3f) + val INSCRIPTIONAL_PARTHIAN = addUnicodeBlock("Inscriptional Parthian", 0x10b40, 0x10b5f) + val INSCRIPTIONAL_PAHLAVI = addUnicodeBlock("Inscriptional Pahlavi", 0x10b60, 0x10b7f) + val OLD_TURKIC = addUnicodeBlock("Old Turkic", 0x10c00, 0x10c4f) + val RUMI_NUMERAL_SYMBOLS = addUnicodeBlock("Rumi Numeral Symbols", 0x10e60, 0x10e7f) + val BRAHMI = addUnicodeBlock("Brahmi", 0x11000, 0x1107f) + val KAITHI = addUnicodeBlock("Kaithi", 0x11080, 0x110cf) + val SORA_SOMPENG = addUnicodeBlock("Sora Sompeng", 0x110d0, 0x110ff) + val CHAKMA = addUnicodeBlock("Chakma", 0x11100, 0x1114f) + val SHARADA = addUnicodeBlock("Sharada", 0x11180, 0x111df) + val TAKRI = addUnicodeBlock("Takri", 0x11680, 0x116cf) + val CUNEIFORM = addUnicodeBlock("Cuneiform", 0x12000, 0x123ff) + val CUNEIFORM_NUMBERS_AND_PUNCTUATION = addUnicodeBlock("Cuneiform Numbers and Punctuation", 0x12400, 0x1247f) + val EGYPTIAN_HIEROGLYPHS = addUnicodeBlock("Egyptian Hieroglyphs", 0x13000, 0x1342f) + val BAMUM_SUPPLEMENT = addUnicodeBlock("Bamum Supplement", 0x16800, 0x16a3f) + val MIAO = addUnicodeBlock("Miao", 0x16f00, 0x16f9f) + val KANA_SUPPLEMENT = addUnicodeBlock("Kana Supplement", 0x1b000, 0x1b0ff) + val BYZANTINE_MUSICAL_SYMBOLS = addUnicodeBlock("Byzantine Musical Symbols", 0x1d000, 0x1d0ff) + val MUSICAL_SYMBOLS = addUnicodeBlock("Musical Symbols", 0x1d100, 0x1d1ff) + val ANCIENT_GREEK_MUSICAL_NOTATION = addUnicodeBlock("Ancient Greek Musical Notation", 0x1d200, 0x1d24f) + val TAI_XUAN_JING_SYMBOLS = addUnicodeBlock("Tai Xuan Jing Symbols", 0x1d300, 0x1d35f) + val COUNTING_ROD_NUMERALS = addUnicodeBlock("Counting Rod Numerals", 0x1d360, 0x1d37f) + val MATHEMATICAL_ALPHANUMERIC_SYMBOLS = addUnicodeBlock("Mathematical Alphanumeric Symbols", 0x1d400, 0x1d7ff) + val ARABIC_MATHEMATICAL_ALPHABETIC_SYMBOLS = addUnicodeBlock("Arabic Mathematical Alphabetic Symbols", 0x1ee00, 0x1eeff) + val MAHJONG_TILES = addUnicodeBlock("Mahjong Tiles", 0x1f000, 0x1f02f) + val DOMINO_TILES = addUnicodeBlock("Domino Tiles", 0x1f030, 0x1f09f) + val PLAYING_CARDS = addUnicodeBlock("Playing Cards", 0x1f0a0, 0x1f0ff) + val ENCLOSED_ALPHANUMERIC_SUPPLEMENT = addUnicodeBlock("Enclosed Alphanumeric Supplement", 0x1f100, 0x1f1ff) + val ENCLOSED_IDEOGRAPHIC_SUPPLEMENT = addUnicodeBlock("Enclosed Ideographic Supplement", 0x1f200, 0x1f2ff) + val MISCELLANEOUS_SYMBOLS_AND_PICTOGRAPHS = addUnicodeBlock("Miscellaneous Symbols and Pictographs", 0x1f300, 0x1f5ff) + val EMOTICONS = addUnicodeBlock("Emoticons", 0x1f600, 0x1f64f) + val TRANSPORT_AND_MAP_SYMBOLS = addUnicodeBlock("Transport and Map Symbols", 0x1f680, 0x1f6ff) + val ALCHEMICAL_SYMBOLS = addUnicodeBlock("Alchemical Symbols", 0x1f700, 0x1f77f) + val CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B = addUnicodeBlock("CJK Unified Ideographs Extension B", 0x20000, 0x2a6df) + val CJK_UNIFIED_IDEOGRAPHS_EXTENSION_C = addUnicodeBlock("CJK Unified Ideographs Extension C", 0x2a700, 0x2b73f) + val CJK_UNIFIED_IDEOGRAPHS_EXTENSION_D = addUnicodeBlock("CJK Unified Ideographs Extension D", 0x2b740, 0x2b81f) + val CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT = addUnicodeBlock("CJK Compatibility Ideographs Supplement", 0x2f800, 0x2fa1f) + val TAGS = addUnicodeBlock("Tags", 0xe0000, 0xe007f) + val VARIATION_SELECTORS_SUPPLEMENT = addUnicodeBlock("Variation Selectors Supplement", 0xe0100, 0xe01ef) + val SUPPLEMENTARY_PRIVATE_USE_AREA_A = addUnicodeBlock("Supplementary Private Use Area-A", 0xf0000, 0xfffff) + val SUPPLEMENTARY_PRIVATE_USE_AREA_B = addUnicodeBlock("Supplementary Private Use Area-B", 0x100000, 0x10ffff) + + // scalastyle:on line.size.limit + //////////////// + // End Generated + //////////////// + + def forName(blockName: String): UnicodeBlock = { + val key: String = blockName.toLowerCase() + val block = blocksByNormalizedName.get(key) + if (block == null) + throw new IllegalArgumentException() + block + } + + def of(c: scala.Char): UnicodeBlock = of(c.toInt) + + def of(codePoint: scala.Int): UnicodeBlock = { + if (!Character.isValidCodePoint(codePoint)) + throw new IllegalArgumentException() + + binarySearch(codePoint, 0, allBlocks.size()) + } + + @tailrec + private[this] def binarySearch(codePoint: scala.Int, lo: scala.Int, hi: scala.Int): UnicodeBlock = { + if (lo < hi) { + val mid = lo + (hi - lo) / 2 + val block = allBlocks.get(mid) + + if (codePoint >= block.start && codePoint <= block.end) block + else if (codePoint > block.end) binarySearch(codePoint, mid + 1, hi) + else binarySearch(codePoint, lo, mid) + } else { + null + } + } + } + + // Based on Unicode 6.2.0, extended with chars 00BB, 20BC-20BF and 32FF + // Generated with OpenJDK 1.8.0_222 + + // Types of characters from 0 to 255 + private[this] lazy val charTypesFirst256: Array[Int] = Array(15, 15, 15, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 12, 24, 24, 24, 26, 24, 24, 24, + 21, 22, 24, 25, 24, 20, 24, 24, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 24, 24, 25, + 25, 25, 24, 24, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 21, 24, 22, 27, 23, 27, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 21, 25, 22, 25, 15, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 12, 24, 26, 26, 26, + 26, 28, 24, 27, 28, 5, 29, 25, 16, 28, 27, 28, 25, 11, 11, 27, 2, 24, 24, + 27, 11, 5, 30, 11, 11, 11, 24, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 25, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 25, 2, 2, 2, 2, 2, 2, + 2, 2) + + /* Character type data by ranges of types + * charTypeIndices: contains the index where the range ends + * charType: contains the type of the character in the range ends + * note that charTypeIndices.length + 1 = charType.length and that the + * range 0 to 255 is not included because it is contained in charTypesFirst256 + * + * They where generated with the following script, which can be pasted into + * a Scala REPL. + +def formatLargeArray(array: Array[Int], indent: String): String = { + val indentMinus1 = indent.substring(1) + val builder = new java.lang.StringBuilder + builder.append(indentMinus1) + var curLineLength = indentMinus1.length + for (i <- 0 until array.length) { + val toAdd = " " + array(i) + (if (i == array.length - 1) "" else ",") + if (curLineLength + toAdd.length >= 80) { + builder.append("\n") + builder.append(indentMinus1) + curLineLength = indentMinus1.length + } + builder.append(toAdd) + curLineLength += toAdd.length + } + builder.toString() +} + +val indicesAndTypes = (256 to Character.MAX_CODE_POINT) + .map(i => (i, Character.getType(i))) + .foldLeft[List[(Int, Int)]](Nil) { + case (x :: xs, elem) if x._2 == elem._2 => x :: xs + case (prevs, elem) => elem :: prevs + }.reverse +val charTypeIndices = indicesAndTypes.map(_._1).tail +val charTypeIndicesDeltas = charTypeIndices + .zip(0 :: charTypeIndices.init) + .map(tup => tup._1 - tup._2) +val charTypes = indicesAndTypes.map(_._2) +println("charTypeIndices, deltas:") +println(" Array(") +println(formatLargeArray(charTypeIndicesDeltas.toArray, " ")) +println(" )") +println("charTypes:") +println(" Array(") +println(formatLargeArray(charTypes.toArray, " ")) +println(" )") + + */ + + private[this] lazy val charTypeIndices: Array[Int] = { + val deltas = Array( + 257, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, + 1, 1, 1, 1, 3, 2, 1, 1, 1, 2, 1, 3, 2, 4, 1, 2, 1, 3, 3, 2, 1, 2, 1, 1, + 1, 1, 1, 2, 1, 1, 2, 1, 1, 2, 1, 3, 1, 1, 1, 2, 2, 1, 1, 3, 4, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 3, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 7, 2, 1, 2, 2, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1, + 69, 1, 27, 18, 4, 12, 14, 5, 7, 1, 1, 1, 17, 112, 1, 1, 1, 1, 1, 1, 1, + 1, 2, 1, 3, 1, 5, 2, 1, 1, 3, 1, 1, 1, 2, 1, 17, 1, 9, 35, 1, 2, 3, 3, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, + 1, 1, 1, 1, 1, 2, 2, 51, 48, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 2, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 38, 2, 1, 6, 1, 39, 1, 1, 1, 4, 1, + 1, 45, 1, 1, 1, 2, 1, 2, 1, 1, 8, 27, 5, 3, 2, 11, 5, 1, 3, 2, 1, 2, 2, + 11, 1, 2, 2, 32, 1, 10, 21, 10, 4, 2, 1, 99, 1, 1, 7, 1, 1, 6, 2, 2, 1, + 4, 2, 10, 3, 2, 1, 14, 1, 1, 1, 1, 30, 27, 2, 89, 11, 1, 14, 10, 33, 9, + 2, 1, 3, 1, 5, 22, 4, 1, 9, 1, 3, 1, 5, 2, 15, 1, 25, 3, 2, 1, 65, 1, + 1, 11, 55, 27, 1, 3, 1, 54, 1, 1, 1, 1, 3, 8, 4, 1, 2, 1, 7, 10, 2, 2, + 10, 1, 1, 6, 1, 7, 1, 1, 2, 1, 8, 2, 2, 2, 22, 1, 7, 1, 1, 3, 4, 2, 1, + 1, 3, 4, 2, 2, 2, 2, 1, 1, 8, 1, 4, 2, 1, 3, 2, 2, 10, 2, 2, 6, 1, 1, + 5, 2, 1, 1, 6, 4, 2, 2, 22, 1, 7, 1, 2, 1, 2, 1, 2, 2, 1, 1, 3, 2, 4, + 2, 2, 3, 3, 1, 7, 4, 1, 1, 7, 10, 2, 3, 1, 11, 2, 1, 1, 9, 1, 3, 1, 22, + 1, 7, 1, 2, 1, 5, 2, 1, 1, 3, 5, 1, 2, 1, 1, 2, 1, 2, 1, 15, 2, 2, 2, + 10, 1, 1, 15, 1, 2, 1, 8, 2, 2, 2, 22, 1, 7, 1, 2, 1, 5, 2, 1, 1, 1, 1, + 1, 4, 2, 2, 2, 2, 1, 8, 1, 1, 4, 2, 1, 3, 2, 2, 10, 1, 1, 6, 10, 1, 1, + 1, 6, 3, 3, 1, 4, 3, 2, 1, 1, 1, 2, 3, 2, 3, 3, 3, 12, 4, 2, 1, 2, 3, + 3, 1, 3, 1, 2, 1, 6, 1, 14, 10, 3, 6, 1, 1, 6, 3, 1, 8, 1, 3, 1, 23, 1, + 10, 1, 5, 3, 1, 3, 4, 1, 3, 1, 4, 7, 2, 1, 2, 6, 2, 2, 2, 10, 8, 7, 1, + 2, 2, 1, 8, 1, 3, 1, 23, 1, 10, 1, 5, 2, 1, 1, 1, 1, 5, 1, 1, 2, 1, 2, + 2, 7, 2, 7, 1, 1, 2, 2, 2, 10, 1, 2, 15, 2, 1, 8, 1, 3, 1, 41, 2, 1, 3, + 4, 1, 3, 1, 3, 1, 1, 8, 1, 8, 2, 2, 2, 10, 6, 3, 1, 6, 2, 2, 1, 18, 3, + 24, 1, 9, 1, 1, 2, 7, 3, 1, 4, 3, 3, 1, 1, 1, 8, 18, 2, 1, 12, 48, 1, + 2, 7, 4, 1, 6, 1, 8, 1, 10, 2, 37, 2, 1, 1, 2, 2, 1, 1, 2, 1, 6, 4, 1, + 7, 1, 3, 1, 1, 1, 1, 2, 2, 1, 4, 1, 2, 6, 1, 2, 1, 2, 5, 1, 1, 1, 6, 2, + 10, 2, 4, 32, 1, 3, 15, 1, 1, 3, 2, 6, 10, 10, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 2, 8, 1, 36, 4, 14, 1, 5, 1, 2, 5, 11, 1, 36, 1, 8, 1, 6, 1, 2, + 5, 4, 2, 37, 43, 2, 4, 1, 6, 1, 2, 2, 2, 1, 10, 6, 6, 2, 2, 4, 3, 1, 3, + 2, 7, 3, 4, 13, 1, 2, 2, 6, 1, 1, 1, 10, 3, 1, 2, 38, 1, 1, 5, 1, 2, + 43, 1, 1, 332, 1, 4, 2, 7, 1, 1, 1, 4, 2, 41, 1, 4, 2, 33, 1, 4, 2, 7, + 1, 1, 1, 4, 2, 15, 1, 57, 1, 4, 2, 67, 2, 3, 9, 20, 3, 16, 10, 6, 85, + 11, 1, 620, 2, 17, 1, 26, 1, 1, 3, 75, 3, 3, 15, 13, 1, 4, 3, 11, 18, + 3, 2, 9, 18, 2, 12, 13, 1, 3, 1, 2, 12, 52, 2, 1, 7, 8, 1, 2, 11, 3, 1, + 3, 1, 1, 1, 2, 10, 6, 10, 6, 6, 1, 4, 3, 1, 1, 10, 6, 35, 1, 52, 8, 41, + 1, 1, 5, 70, 10, 29, 3, 3, 4, 2, 3, 4, 2, 1, 6, 3, 4, 1, 3, 2, 10, 30, + 2, 5, 11, 44, 4, 17, 7, 2, 6, 10, 1, 3, 34, 23, 2, 3, 2, 2, 53, 1, 1, + 1, 7, 1, 1, 1, 1, 2, 8, 6, 10, 2, 1, 10, 6, 10, 6, 7, 1, 6, 82, 4, 1, + 47, 1, 1, 5, 1, 1, 5, 1, 2, 7, 4, 10, 7, 10, 9, 9, 3, 2, 1, 30, 1, 4, + 2, 2, 1, 1, 2, 2, 10, 44, 1, 1, 2, 3, 1, 1, 3, 2, 8, 4, 36, 8, 8, 2, 2, + 3, 5, 10, 3, 3, 10, 30, 6, 2, 64, 8, 8, 3, 1, 13, 1, 7, 4, 1, 4, 2, 1, + 2, 9, 44, 63, 13, 1, 34, 37, 39, 21, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 8, 6, + 2, 6, 2, 8, 8, 8, 8, 6, 2, 6, 2, 8, 1, 1, 1, 1, 1, 1, 1, 1, 8, 8, 14, + 2, 8, 8, 8, 8, 8, 8, 5, 1, 2, 4, 1, 1, 1, 3, 3, 1, 2, 4, 1, 3, 4, 2, 2, + 4, 1, 3, 8, 5, 3, 2, 3, 1, 2, 4, 1, 2, 1, 11, 5, 6, 2, 1, 1, 1, 2, 1, + 1, 1, 8, 1, 1, 5, 1, 9, 1, 1, 4, 2, 3, 1, 1, 1, 11, 1, 1, 1, 10, 1, 5, + 5, 6, 1, 1, 2, 6, 3, 1, 1, 1, 10, 3, 1, 1, 1, 13, 3, 32, 16, 13, 4, 1, + 3, 12, 15, 2, 1, 4, 1, 2, 1, 3, 2, 3, 1, 1, 1, 2, 1, 5, 6, 1, 1, 1, 1, + 1, 1, 4, 1, 1, 4, 1, 4, 1, 2, 2, 2, 5, 1, 4, 1, 1, 2, 1, 1, 16, 35, 1, + 1, 4, 1, 6, 5, 5, 2, 4, 1, 2, 1, 2, 1, 7, 1, 31, 2, 2, 1, 1, 1, 31, + 268, 8, 4, 20, 2, 7, 1, 1, 81, 1, 30, 25, 40, 6, 18, 12, 39, 25, 11, + 21, 60, 78, 22, 183, 1, 9, 1, 54, 8, 111, 1, 144, 1, 103, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 30, 44, 5, 1, 1, 31, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 16, 256, 131, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 63, 1, 1, 1, 1, 32, 1, 1, 258, 48, 21, 2, 6, 3, 10, + 166, 47, 1, 47, 1, 1, 1, 3, 2, 1, 1, 1, 1, 1, 1, 4, 1, 1, 2, 1, 6, 2, + 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 2, 6, 1, 1, 1, 1, 3, 1, 1, 5, 4, 1, 2, 38, 1, 1, 5, 1, 2, 56, + 7, 1, 1, 14, 1, 23, 9, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, + 32, 2, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 9, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 5, 1, 10, 2, 68, 26, 1, 89, 12, 214, 26, 12, 4, 1, + 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 2, 1, 9, 4, 2, 1, 5, 2, 3, 1, 1, 1, 2, 1, 86, 2, 2, 2, 2, 1, 1, + 90, 1, 3, 1, 5, 41, 3, 94, 1, 2, 4, 10, 27, 5, 36, 12, 16, 31, 1, 10, + 30, 8, 1, 15, 32, 10, 39, 15, 320, 6582, 10, 64, 20941, 51, 21, 1, + 1143, 3, 55, 9, 40, 6, 2, 268, 1, 3, 16, 10, 2, 20, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 10, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 7, 1, 70, 10, 2, 6, 8, 23, 9, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 8, 1, 1, 1, 1, 2, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 77, 2, 1, 7, 1, 3, 1, 4, 1, 23, 2, 2, 1, 4, 4, 6, + 2, 1, 1, 6, 52, 4, 8, 2, 50, 16, 1, 9, 2, 10, 6, 18, 6, 3, 1, 4, 10, + 28, 8, 2, 23, 11, 2, 11, 1, 29, 3, 3, 1, 47, 1, 2, 4, 2, 1, 4, 13, 1, + 1, 10, 4, 2, 32, 41, 6, 2, 2, 2, 2, 9, 3, 1, 8, 1, 1, 2, 10, 2, 4, 16, + 1, 6, 3, 1, 1, 4, 48, 1, 1, 3, 2, 2, 5, 2, 1, 1, 1, 24, 2, 1, 2, 11, 1, + 2, 2, 2, 1, 2, 1, 1, 10, 6, 2, 6, 2, 6, 9, 7, 1, 7, 145, 35, 2, 1, 2, + 1, 2, 1, 1, 1, 2, 10, 6, 11172, 12, 23, 4, 49, 4, 2048, 6400, 366, 2, + 106, 38, 7, 12, 5, 5, 1, 1, 10, 1, 13, 1, 5, 1, 1, 1, 2, 1, 2, 1, 108, + 16, 17, 363, 1, 1, 16, 64, 2, 54, 40, 12, 1, 1, 2, 16, 7, 1, 1, 1, 6, + 7, 9, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, + 4, 3, 3, 1, 4, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 3, 1, 1, 1, 2, 4, 5, 1, + 135, 2, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 2, 10, 2, 3, 2, 26, 1, 1, 1, + 1, 1, 1, 26, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 10, 1, 45, 2, 31, 3, 6, 2, + 6, 2, 6, 2, 3, 3, 2, 1, 1, 1, 2, 1, 1, 4, 2, 10, 3, 2, 2, 12, 1, 26, 1, + 19, 1, 2, 1, 15, 2, 14, 34, 123, 5, 3, 4, 45, 3, 9, 53, 4, 17, 1, 5, + 12, 52, 45, 1, 130, 29, 3, 49, 47, 31, 1, 4, 12, 17, 1, 8, 1, 53, 30, + 1, 1, 36, 4, 8, 1, 5, 42, 40, 40, 78, 2, 10, 854, 6, 2, 1, 1, 44, 1, 2, + 3, 1, 2, 23, 1, 1, 8, 160, 22, 6, 3, 1, 26, 5, 1, 64, 56, 6, 2, 64, 1, + 3, 1, 2, 5, 4, 4, 1, 3, 1, 27, 4, 3, 4, 1, 8, 8, 9, 7, 29, 2, 1, 128, + 54, 3, 7, 22, 2, 8, 19, 5, 8, 128, 73, 535, 31, 385, 1, 1, 1, 53, 15, + 7, 4, 20, 10, 16, 2, 1, 45, 3, 4, 2, 2, 2, 1, 4, 14, 25, 7, 10, 6, 3, + 36, 5, 1, 8, 1, 10, 4, 60, 2, 1, 48, 3, 9, 2, 4, 4, 7, 10, 1190, 43, 1, + 1, 1, 2, 6, 1, 1, 8, 10, 2358, 879, 145, 99, 13, 4, 2956, 1071, 13265, + 569, 1223, 69, 11, 1, 46, 16, 4, 13, 16480, 2, 8190, 246, 10, 39, 2, + 60, 2, 3, 3, 6, 8, 8, 2, 7, 30, 4, 48, 34, 66, 3, 1, 186, 87, 9, 18, + 142, 26, 26, 26, 7, 1, 18, 26, 26, 1, 1, 2, 2, 1, 2, 2, 2, 4, 1, 8, 4, + 1, 1, 1, 7, 1, 11, 26, 26, 2, 1, 4, 2, 8, 1, 7, 1, 26, 2, 1, 4, 1, 5, + 1, 1, 3, 7, 1, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 28, 2, + 25, 1, 25, 1, 6, 25, 1, 25, 1, 6, 25, 1, 25, 1, 6, 25, 1, 25, 1, 6, 25, + 1, 25, 1, 6, 1, 1, 2, 50, 5632, 4, 1, 27, 1, 2, 1, 1, 2, 1, 1, 10, 1, + 4, 1, 1, 1, 1, 6, 1, 4, 1, 1, 1, 1, 1, 1, 3, 1, 2, 1, 1, 2, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 2, 1, 1, 2, 4, 1, 7, 1, 4, 1, 4, 1, 1, 1, 10, 1, 17, + 5, 3, 1, 5, 1, 17, 52, 2, 270, 44, 4, 100, 12, 15, 2, 14, 2, 15, 1, 15, + 32, 11, 5, 31, 1, 60, 4, 43, 75, 29, 13, 43, 5, 9, 7, 2, 174, 33, 15, + 6, 1, 70, 3, 20, 12, 37, 1, 5, 21, 17, 15, 63, 1, 1, 1, 182, 1, 4, 3, + 62, 2, 4, 12, 24, 147, 70, 4, 11, 48, 70, 58, 116, 2188, 42711, 41, + 4149, 11, 222, 16354, 542, 722403, 1, 30, 96, 128, 240, 65040, 65534, + 2, 65534 + ) + uncompressDeltas(deltas) + } + + private[this] lazy val charTypes: Array[Int] = Array( + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 5, 1, 2, 5, 1, 3, 2, 1, + 3, 2, 1, 3, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, + 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 3, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 5, 2, 4, 27, 4, 27, 4, 27, 4, 27, 4, 27, 6, 1, 2, 1, 2, 4, 27, 1, 2, 0, + 4, 2, 24, 0, 27, 1, 24, 1, 0, 1, 0, 1, 2, 1, 0, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 25, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, + 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 28, 6, 7, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 0, 1, 0, 4, 24, 0, 2, 0, 24, 20, 0, 26, 0, 6, 20, + 6, 24, 6, 24, 6, 24, 6, 0, 5, 0, 5, 24, 0, 16, 0, 25, 24, 26, 24, 28, 6, + 24, 0, 24, 5, 4, 5, 6, 9, 24, 5, 6, 5, 24, 5, 6, 16, 28, 6, 4, 6, 28, 6, + 5, 9, 5, 28, 5, 24, 0, 16, 5, 6, 5, 6, 0, 5, 6, 5, 0, 9, 5, 6, 4, 28, 24, + 4, 0, 5, 6, 4, 6, 4, 6, 4, 6, 0, 24, 0, 5, 6, 0, 24, 0, 5, 0, 5, 0, 6, 0, + 6, 8, 5, 6, 8, 6, 5, 8, 6, 8, 6, 8, 5, 6, 5, 6, 24, 9, 24, 4, 5, 0, 5, 0, + 6, 8, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 6, 5, 8, 6, 0, 8, 0, 8, 6, + 5, 0, 8, 0, 5, 0, 5, 6, 0, 9, 5, 26, 11, 28, 26, 0, 6, 8, 0, 5, 0, 5, 0, + 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 6, 0, 8, 6, 0, 6, 0, 6, 0, 6, 0, 5, 0, 5, + 0, 9, 6, 5, 6, 0, 6, 8, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 6, 5, 8, + 6, 0, 6, 8, 0, 8, 6, 0, 5, 0, 5, 6, 0, 9, 24, 26, 0, 6, 8, 0, 5, 0, 5, 0, + 5, 0, 5, 0, 5, 0, 5, 0, 6, 5, 8, 6, 8, 6, 0, 8, 0, 8, 6, 0, 6, 8, 0, 5, + 0, 5, 6, 0, 9, 28, 5, 11, 0, 6, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, + 5, 0, 5, 0, 5, 0, 8, 6, 8, 0, 8, 0, 8, 6, 0, 5, 0, 8, 0, 9, 11, 28, 26, + 28, 0, 8, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 6, 8, 0, 6, 0, 6, 0, 6, 0, + 5, 0, 5, 6, 0, 9, 0, 11, 28, 0, 8, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 6, 5, + 8, 6, 8, 0, 6, 8, 0, 8, 6, 0, 8, 0, 5, 0, 5, 6, 0, 9, 0, 5, 0, 8, 0, 5, + 0, 5, 0, 5, 0, 5, 8, 6, 0, 8, 0, 8, 6, 5, 0, 8, 0, 5, 6, 0, 9, 11, 0, 28, + 5, 0, 8, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 6, 0, 8, 6, 0, 6, 0, 8, 0, 8, + 24, 0, 5, 6, 5, 6, 0, 26, 5, 4, 6, 24, 9, 24, 0, 5, 0, 5, 0, 5, 0, 5, 0, + 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 6, 5, 6, 0, 6, 5, 0, 5, 0, + 4, 0, 6, 0, 9, 0, 5, 0, 5, 28, 24, 28, 24, 28, 6, 28, 9, 11, 28, 6, 28, + 6, 28, 6, 21, 22, 21, 22, 8, 5, 0, 5, 0, 6, 8, 6, 24, 6, 5, 6, 0, 6, 0, + 28, 6, 28, 0, 28, 24, 28, 24, 0, 5, 8, 6, 8, 6, 8, 6, 8, 6, 5, 9, 24, 5, + 8, 6, 5, 6, 5, 8, 5, 8, 5, 6, 5, 6, 8, 6, 8, 6, 5, 8, 9, 8, 6, 28, 1, 0, + 1, 0, 1, 0, 5, 24, 4, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, + 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 6, 24, 11, 0, 5, 28, 0, 5, + 0, 20, 5, 24, 5, 12, 5, 21, 22, 0, 5, 24, 10, 0, 5, 0, 5, 6, 0, 5, 6, 24, + 0, 5, 6, 0, 5, 0, 5, 0, 6, 0, 5, 6, 8, 6, 8, 6, 8, 6, 24, 4, 24, 26, 5, + 6, 0, 9, 0, 11, 0, 24, 20, 24, 6, 12, 0, 9, 0, 5, 4, 5, 0, 5, 6, 5, 0, 5, + 0, 5, 0, 6, 8, 6, 8, 0, 8, 6, 8, 6, 0, 28, 0, 24, 9, 5, 0, 5, 0, 5, 0, 8, + 5, 8, 0, 9, 11, 0, 28, 5, 6, 8, 0, 24, 5, 8, 6, 8, 6, 0, 6, 8, 6, 8, 6, + 8, 6, 0, 6, 9, 0, 9, 0, 24, 4, 24, 0, 6, 8, 5, 6, 8, 6, 8, 6, 8, 6, 8, 5, + 0, 9, 24, 28, 6, 28, 0, 6, 8, 5, 8, 6, 8, 6, 8, 6, 8, 5, 9, 5, 6, 8, 6, + 8, 6, 8, 6, 8, 0, 24, 5, 8, 6, 8, 6, 0, 24, 9, 0, 5, 9, 5, 4, 24, 0, 24, + 0, 6, 24, 6, 8, 6, 5, 6, 5, 8, 6, 5, 0, 2, 4, 2, 4, 2, 4, 6, 0, 6, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 0, 1, 0, 2, 1, 2, 1, 2, 0, 1, 0, 2, 0, 1, 0, 1, + 0, 1, 0, 1, 2, 1, 2, 0, 2, 3, 2, 3, 2, 3, 2, 0, 2, 1, 3, 27, 2, 27, 2, 0, + 2, 1, 3, 27, 2, 0, 2, 1, 0, 27, 2, 1, 27, 0, 2, 0, 2, 1, 3, 27, 0, 12, + 16, 20, 24, 29, 30, 21, 29, 30, 21, 29, 24, 13, 14, 16, 12, 24, 29, 30, + 24, 23, 24, 25, 21, 22, 24, 25, 24, 23, 24, 12, 16, 0, 16, 11, 4, 0, 11, + 25, 21, 22, 4, 11, 25, 21, 22, 0, 4, 0, 26, 0, 6, 7, 6, 7, 6, 0, 28, 1, + 28, 1, 28, 2, 1, 2, 1, 2, 28, 1, 28, 25, 1, 28, 1, 28, 1, 28, 1, 28, 1, + 28, 2, 1, 2, 5, 2, 28, 2, 1, 25, 1, 2, 28, 25, 28, 2, 28, 11, 10, 1, 2, + 10, 11, 0, 25, 28, 25, 28, 25, 28, 25, 28, 25, 28, 25, 28, 25, 28, 25, + 28, 25, 28, 25, 28, 25, 28, 25, 28, 21, 22, 28, 25, 28, 25, 28, 25, 28, + 0, 28, 0, 28, 0, 11, 28, 11, 28, 25, 28, 25, 28, 25, 28, 25, 28, 0, 28, + 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 11, 28, 25, 21, + 22, 25, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 25, 28, 25, 21, 22, 21, + 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, + 22, 25, 21, 22, 21, 22, 25, 21, 22, 25, 28, 25, 28, 25, 0, 28, 0, 1, 0, + 2, 0, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 4, 1, 2, 1, 2, 1, + 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, + 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, + 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, + 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 28, + 1, 2, 1, 2, 6, 1, 2, 0, 24, 11, 24, 2, 0, 2, 0, 2, 0, 5, 0, 4, 24, 0, 6, + 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 6, 24, 29, 30, 29, + 30, 24, 29, 30, 24, 29, 30, 24, 20, 24, 20, 24, 29, 30, 24, 29, 30, 21, + 22, 21, 22, 21, 22, 21, 22, 24, 4, 24, 20, 0, 28, 0, 28, 0, 28, 0, 28, 0, + 12, 24, 28, 4, 5, 10, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 28, 21, 22, + 21, 22, 21, 22, 21, 22, 20, 21, 22, 28, 10, 6, 8, 20, 4, 28, 10, 4, 5, + 24, 28, 0, 5, 0, 6, 27, 4, 5, 20, 5, 24, 4, 5, 0, 5, 0, 5, 0, 28, 11, 28, + 5, 0, 28, 0, 5, 28, 0, 11, 28, 11, 28, 11, 28, 11, 28, 11, 28, 5, 0, 28, + 5, 0, 5, 4, 5, 0, 28, 0, 5, 4, 24, 5, 4, 24, 5, 9, 5, 0, 1, 2, 1, 2, 1, + 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, + 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 5, 6, 7, 24, 6, 24, 4, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 0, 6, 5, 10, 6, 24, 0, 27, 4, 27, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, + 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, + 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, + 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 4, 2, 1, 2, 1, 2, 1, 2, 1, + 2, 1, 2, 1, 2, 1, 2, 4, 27, 1, 2, 1, 2, 0, 1, 2, 1, 2, 0, 1, 2, 1, 2, 1, + 2, 1, 2, 1, 2, 1, 0, 4, 2, 5, 6, 5, 6, 5, 6, 5, 8, 6, 8, 28, 0, 11, 28, + 26, 28, 0, 5, 24, 0, 8, 5, 8, 6, 0, 24, 9, 0, 6, 5, 24, 5, 0, 9, 5, 6, + 24, 5, 6, 8, 0, 24, 5, 0, 6, 8, 5, 6, 8, 6, 8, 6, 8, 24, 0, 4, 9, 0, 24, + 0, 5, 6, 8, 6, 8, 6, 0, 5, 6, 5, 6, 8, 0, 9, 0, 24, 5, 4, 5, 28, 5, 8, 0, + 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 0, 5, 4, 24, 5, 8, 6, 8, 24, 5, 4, 8, 6, + 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 8, 6, 8, 6, 8, 24, 8, 6, 0, 9, 0, 5, + 0, 5, 0, 5, 0, 19, 18, 5, 0, 5, 0, 2, 0, 2, 0, 5, 6, 5, 25, 5, 0, 5, 0, + 5, 0, 5, 0, 5, 0, 5, 27, 0, 5, 21, 22, 0, 5, 0, 5, 0, 5, 26, 28, 0, 6, + 24, 21, 22, 24, 0, 6, 0, 24, 20, 23, 21, 22, 21, 22, 21, 22, 21, 22, 21, + 22, 21, 22, 21, 22, 21, 22, 24, 21, 22, 24, 23, 24, 0, 24, 20, 21, 22, + 21, 22, 21, 22, 24, 25, 20, 25, 0, 24, 26, 24, 0, 5, 0, 5, 0, 16, 0, 24, + 26, 24, 21, 22, 24, 25, 24, 20, 24, 9, 24, 25, 24, 1, 21, 24, 22, 27, 23, + 27, 2, 21, 25, 22, 25, 21, 22, 24, 21, 22, 24, 5, 4, 5, 4, 5, 0, 5, 0, 5, + 0, 5, 0, 5, 0, 26, 25, 27, 28, 26, 0, 28, 25, 28, 0, 16, 28, 0, 5, 0, 5, + 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 24, 0, 11, 0, 28, 10, 11, 28, 11, 0, 28, + 0, 28, 6, 0, 5, 0, 5, 0, 5, 0, 11, 0, 5, 10, 5, 10, 0, 5, 0, 24, 5, 0, 5, + 24, 10, 0, 1, 2, 5, 0, 9, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 24, 11, + 0, 5, 11, 0, 24, 5, 0, 24, 0, 5, 0, 5, 0, 5, 6, 0, 6, 0, 6, 5, 0, 5, 0, + 5, 0, 6, 0, 6, 11, 0, 24, 0, 5, 11, 24, 0, 5, 0, 24, 5, 0, 11, 5, 0, 11, + 0, 5, 0, 11, 0, 8, 6, 8, 5, 6, 24, 0, 11, 9, 0, 6, 8, 5, 8, 6, 8, 6, 24, + 16, 24, 0, 5, 0, 9, 0, 6, 5, 6, 8, 6, 0, 9, 24, 0, 6, 8, 5, 8, 6, 8, 5, + 24, 0, 9, 0, 5, 6, 8, 6, 8, 6, 8, 6, 0, 9, 0, 5, 0, 10, 0, 24, 0, 5, 0, + 5, 0, 5, 0, 5, 8, 0, 6, 4, 0, 5, 0, 28, 0, 28, 0, 28, 8, 6, 28, 8, 16, 6, + 28, 6, 28, 6, 28, 0, 28, 6, 28, 0, 28, 0, 11, 0, 1, 2, 1, 2, 0, 2, 1, 2, + 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 0, 2, 0, 2, 0, 2, 1, 2, 1, 0, 1, 0, + 1, 0, 1, 0, 2, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 0, 1, 25, 2, 25, 2, 1, 25, 2, 25, 2, 1, 25, 2, 25, 2, 1, 25, + 2, 25, 2, 1, 25, 2, 25, 2, 1, 2, 0, 9, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, + 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, + 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0, + 5, 0, 5, 0, 5, 0, 5, 0, 25, 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, + 11, 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, + 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, + 28, 0, 28, 0, 28, 0, 28, 0, 28, 0, 5, 0, 5, 0, 5, 0, 5, 0, 16, 0, 16, 0, + 6, 0, 18, 0, 18, 0 + ) + + /* Indices representing the start of ranges of codePoint that have the same + * `isMirrored` result. It is true for the first range + * (i.e. isMirrored(40)==true, isMirrored(41)==true, isMirrored(42)==false) + * They where generated with the following script, which can be pasted into + * a Scala REPL. + +val indicesAndRes = (0 to Character.MAX_CODE_POINT) + .map(i => (i, Character.isMirrored(i))) + .foldLeft[List[(Int, Boolean)]](Nil) { + case (x :: xs, elem) if x._2 == elem._2 => x :: xs + case (prevs, elem) => elem :: prevs + }.reverse +val isMirroredIndices = indicesAndRes.map(_._1).tail +val isMirroredIndicesDeltas = isMirroredIndices + .zip(0 :: isMirroredIndices.init) + .map(tup => tup._1 - tup._2) +println("isMirroredIndices, deltas:") +println(" Array(") +println(formatLargeArray(isMirroredIndicesDeltas.toArray, " ")) +println(" )") + + */ + private[this] lazy val isMirroredIndices: Array[Int] = { + val deltas = Array( + 40, 2, 18, 1, 1, 1, 28, 1, 1, 1, 29, 1, 1, 1, 45, 1, 15, 1, 3710, 4, + 1885, 2, 2460, 2, 10, 2, 54, 2, 14, 2, 177, 1, 192, 4, 3, 6, 3, 1, 3, + 2, 3, 4, 1, 4, 1, 1, 1, 1, 4, 9, 5, 1, 1, 18, 5, 4, 9, 2, 1, 1, 1, 8, + 2, 31, 2, 4, 5, 1, 9, 2, 2, 19, 5, 2, 9, 5, 2, 2, 4, 24, 2, 16, 8, 4, + 20, 2, 7, 2, 1085, 14, 74, 1, 2, 4, 1, 2, 1, 3, 5, 4, 5, 3, 3, 14, 403, + 22, 2, 21, 8, 1, 7, 6, 3, 1, 4, 5, 1, 2, 2, 5, 4, 1, 1, 3, 2, 2, 10, 6, + 2, 2, 12, 19, 1, 4, 2, 1, 1, 1, 2, 1, 1, 4, 5, 2, 6, 3, 24, 2, 11, 2, + 4, 4, 1, 2, 2, 2, 4, 43, 2, 8, 1, 40, 5, 1, 1, 1, 3, 5, 5, 3, 4, 1, 3, + 5, 1, 1, 772, 4, 3, 2, 1, 2, 14, 2, 2, 10, 478, 10, 2, 8, 52797, 6, 5, + 2, 162, 2, 18, 1, 1, 1, 28, 1, 1, 1, 29, 1, 1, 1, 1, 2, 1, 2, 55159, 1, + 57, 1, 57, 1, 57, 1, 57, 1 + ) + uncompressDeltas(deltas) + } + + private[lang] final val CombiningClassIsNone = 0 + private[lang] final val CombiningClassIsAbove = 1 + private[lang] final val CombiningClassIsOther = 2 + + /* Indices representing the start of ranges of codePoint that have the same + * `combiningClassNoneOrAboveOrOther` result. The results cycle modulo 3 at + * every range: + * + * - 0 for the range [0, array(0)) + * - 1 for the range [array(0), array(1)) + * - 2 for the range [array(1), array(2)) + * - 0 for the range [array(2), array(3)) + * - etc. + * + * In general, for a range ending at `array(i)` (excluded), the result is + * `i % 3`. + * + * A range can be empty, i.e., it can happen that `array(i) == array(i + 1)` + * (but then it is different from `array(i - 1)` and `array(i + 2)`). + * + * They where generated with the following script, which can be pasted into + * a Scala REPL. + +val url = new java.net.URL("http://unicode.org/Public/UCD/latest/ucd/UnicodeData.txt") +val cpToValue = scala.io.Source.fromURL(url, "UTF-8") + .getLines() + .filter(!_.startsWith("#")) + .map(_.split(';')) + .map { arr => + val cp = Integer.parseInt(arr(0), 16) + val value = arr(3).toInt match { + case 0 => 0 + case 230 => 1 + case _ => 2 + } + cp -> value + } + .toMap + .withDefault(_ => 0) + +var lastValue = 0 +val indicesBuilder = List.newBuilder[Int] +for (cp <- 0 to Character.MAX_CODE_POINT) { + val value = cpToValue(cp) + while (lastValue != value) { + indicesBuilder += cp + lastValue = (lastValue + 1) % 3 + } +} +val indices = indicesBuilder.result() + +val indicesDeltas = indices + .zip(0 :: indices.init) + .map(tup => tup._1 - tup._2) +println("combiningClassNoneOrAboveOrOtherIndices, deltas:") +println(" Array(") +println(formatLargeArray(indicesDeltas.toArray, " ")) +println(" )") + + */ + private[this] lazy val combiningClassNoneOrAboveOrOtherIndices: Array[Int] = { + val deltas = Array( + 768, 21, 40, 0, 8, 1, 0, 1, 3, 0, 3, 2, 1, 3, 4, 0, 1, 3, 0, 1, 7, 0, + 13, 0, 275, 5, 0, 265, 0, 1, 0, 4, 1, 0, 3, 2, 0, 6, 6, 0, 2, 1, 0, 2, + 2, 0, 1, 14, 1, 0, 1, 1, 0, 2, 1, 1, 1, 1, 0, 1, 72, 8, 3, 48, 0, 8, 0, + 2, 2, 0, 5, 1, 0, 2, 1, 16, 0, 1, 101, 7, 0, 2, 4, 1, 0, 1, 0, 2, 2, 0, + 1, 0, 1, 0, 2, 1, 35, 0, 1, 30, 1, 1, 0, 2, 1, 0, 2, 3, 0, 1, 2, 0, 1, + 1, 0, 3, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 2, 0, 160, 7, 1, 0, 1, 0, 9, + 0, 1, 24, 4, 0, 1, 9, 0, 1, 3, 0, 1, 5, 0, 43, 0, 3, 119, 0, 1, 0, 14, + 0, 1, 0, 1, 0, 2, 1, 0, 2, 1, 0, 3, 6, 0, 3, 1, 0, 2, 2, 0, 5, 0, 60, + 0, 1, 16, 0, 1, 3, 1, 1, 0, 2, 0, 103, 0, 1, 16, 0, 1, 48, 1, 0, 61, 0, + 1, 16, 0, 1, 110, 0, 1, 16, 0, 1, 110, 0, 1, 16, 0, 1, 127, 0, 1, 127, + 0, 1, 7, 0, 2, 101, 0, 1, 16, 0, 1, 109, 0, 2, 16, 0, 1, 124, 0, 1, + 109, 0, 3, 13, 0, 4, 108, 0, 3, 13, 0, 4, 76, 0, 2, 27, 0, 1, 1, 0, 1, + 1, 0, 1, 55, 0, 2, 1, 0, 1, 5, 0, 4, 2, 0, 1, 1, 2, 1, 1, 2, 0, 62, 0, + 1, 112, 0, 1, 1, 0, 2, 82, 0, 1, 719, 3, 0, 948, 0, 1, 31, 0, 1, 157, + 0, 1, 10, 1, 0, 203, 0, 1, 143, 0, 1, 0, 1, 1, 219, 1, 1, 71, 0, 1, 20, + 8, 0, 2, 0, 1, 48, 5, 6, 0, 2, 1, 1, 0, 2, 115, 0, 1, 15, 0, 1, 38, 1, + 1, 0, 7, 0, 54, 0, 2, 58, 0, 1, 11, 0, 2, 67, 0, 1, 152, 3, 0, 1, 0, 6, + 0, 2, 4, 0, 1, 0, 1, 0, 7, 4, 0, 1, 6, 1, 0, 3, 2, 0, 198, 2, 1, 0, 7, + 1, 0, 2, 4, 0, 37, 4, 1, 1, 2, 0, 1, 1, 720, 2, 2, 0, 4, 3, 0, 2, 0, 4, + 1, 0, 3, 0, 2, 0, 1, 1, 0, 1, 6, 0, 1, 0, 3070, 3, 0, 141, 0, 1, 96, + 32, 0, 554, 0, 6, 105, 0, 2, 30164, 1, 0, 4, 10, 0, 32, 2, 0, 80, 2, 0, + 276, 0, 1, 37, 0, 1, 151, 0, 1, 27, 18, 0, 57, 0, 3, 37, 0, 1, 95, 0, + 1, 12, 0, 1, 239, 1, 0, 1, 2, 1, 2, 2, 0, 5, 2, 0, 1, 1, 0, 52, 0, 1, + 246, 0, 1, 20272, 0, 1, 769, 7, 7, 0, 2, 0, 973, 0, 1, 226, 0, 1, 149, + 5, 0, 1682, 0, 1, 1, 1, 0, 40, 1, 2, 4, 0, 1, 165, 1, 1, 573, 4, 0, + 387, 2, 0, 153, 0, 2, 0, 3, 1, 0, 1, 4, 245, 0, 1, 56, 0, 1, 57, 0, 2, + 69, 3, 0, 48, 0, 2, 62, 0, 1, 76, 0, 1, 9, 0, 1, 106, 0, 2, 178, 0, 2, + 80, 0, 2, 16, 0, 1, 24, 7, 0, 3, 5, 0, 205, 0, 1, 3, 0, 1, 23, 1, 0, + 99, 0, 2, 251, 0, 2, 126, 0, 1, 118, 0, 2, 115, 0, 1, 269, 0, 2, 258, + 0, 2, 4, 0, 1, 156, 0, 1, 83, 0, 1, 18, 0, 1, 81, 0, 1, 421, 0, 1, 258, + 0, 1, 1, 0, 2, 81, 0, 1, 19800, 0, 5, 59, 7, 0, 1209, 0, 2, 19628, 0, + 1, 5318, 0, 5, 3, 0, 6, 8, 0, 8, 2, 5, 2, 30, 4, 0, 148, 3, 0, 3515, 7, + 0, 1, 17, 0, 2, 7, 0, 1, 2, 0, 1, 5, 0, 261, 7, 0, 437, 4, 0, 1504, 0, + 7, 109, 6, 1 + ) + uncompressDeltas(deltas) + } + + /** Tests whether the given code point's combining class is 0 (None), 230 + * (Above) or something else (Other). + * + * This is a special-purpose method for use by `String.toLowerCase` and + * `String.toUpperCase`. + */ + private[lang] def combiningClassNoneOrAboveOrOther(cp: Int): Int = { + val indexOfRange = findIndexOfRange( + combiningClassNoneOrAboveOrOtherIndices, cp, hasEmptyRanges = true) + indexOfRange % 3 + } + + private[this] def uncompressDeltas(deltas: Array[Int]): Array[Int] = { + var acc = deltas(0) + var i = 1 + val len = deltas.length + while (i != len) { + acc += deltas(i) + deltas(i) = acc + i += 1 + } + deltas + } + + private[this] def findIndexOfRange(startOfRangesArray: Array[Int], + value: Int, hasEmptyRanges: scala.Boolean): Int = { + val i = Arrays.binarySearch(startOfRangesArray, value) + if (i >= 0) { + /* `value` is at the start of a range. Its range index is therefore + * `i + 1`, since there is an implicit range starting at 0 in the + * beginning. + * + * If the array has empty ranges, we may need to advance further than + * `i + 1` until the first index `j > i` where + * `startOfRangesArray(j) != value`. + */ + if (hasEmptyRanges) { + var j = i + 1 + while (j < startOfRangesArray.length && startOfRangesArray(j) == value) + j += 1 + j + } else { + i + 1 + } + } else { + /* i is `-p - 1` where `p` is the insertion point. In that case the index + * of the range is precisely `p`. + */ + -i - 1 + } + } + + /** All the non-ASCII code points that map to the digit 0. + * + * Each of them is directly followed by 9 other code points mapping to the + * digits 1 to 9, in order. Conversely, there are no other non-ASCII code + * point mapping to digits from 0 to 9. + */ + private[this] lazy val nonASCIIZeroDigitCodePoints: Array[Int] = { + Array(0x660, 0x6f0, 0x7c0, 0x966, 0x9e6, 0xa66, 0xae6, 0xb66, 0xbe6, + 0xc66, 0xce6, 0xd66, 0xe50, 0xed0, 0xf20, 0x1040, 0x1090, 0x17e0, + 0x1810, 0x1946, 0x19d0, 0x1a80, 0x1a90, 0x1b50, 0x1bb0, 0x1c40, 0x1c50, + 0xa620, 0xa8d0, 0xa900, 0xa9d0, 0xaa50, 0xabf0, 0xff10, 0x104a0, + 0x11066, 0x110f0, 0x11136, 0x111d0, 0x116c0, 0x1d7ce, 0x1d7d8, 0x1d7e2, + 0x1d7ec, 0x1d7f6) + } +} diff --git a/javalib/src/main/scala/java/lang/Class.scala b/javalib/src/main/scala/java/lang/Class.scala new file mode 100644 index 0000000000..db5cc45ec3 --- /dev/null +++ b/javalib/src/main/scala/java/lang/Class.scala @@ -0,0 +1,153 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.lang + +import scala.scalajs.js + +@js.native +private trait ScalaJSClassData[A] extends js.Object { + val name: String = js.native + val isPrimitive: scala.Boolean = js.native + val isInterface: scala.Boolean = js.native + val isArrayClass: scala.Boolean = js.native + + def isInstance(obj: Any): scala.Boolean = js.native + def isAssignableFrom(that: ScalaJSClassData[_]): scala.Boolean = js.native + def checkCast(obj: Any): scala.Unit = js.native + + def getSuperclass(): Class[_ >: A] = js.native + def getComponentType(): Class[_] = js.native + + def newArrayOfThisClass(dimensions: js.Array[Int]): AnyRef = js.native +} + +final class Class[A] private (data0: Object) extends Object { + private[this] val data: ScalaJSClassData[A] = + data0.asInstanceOf[ScalaJSClassData[A]] + + private[this] var cachedSimpleName: String = _ + + /** Access to `data` for other instances or `@inline` methods. + * + * Directly accessing the `data` field from `@inline` methods will cause + * scalac to make the field public and mangle its name. Since the Emitter + * relies on the field being called exactly `data` in some of its + * optimizations, we must avoid that. + * + * This non-`@noinline` method can be used to access the field without + * triggering scalac's mangling. Since it is a trivial accessor, the + * Scala.js optimizer will inline it anyway. + */ + private def getData(): ScalaJSClassData[A] = data + + override def toString(): String = { + (if (isInterface()) "interface " else + if (isPrimitive()) "" else "class ")+getName() + } + + def isInstance(obj: Any): scala.Boolean = + data.isInstance(obj) + + def isAssignableFrom(that: Class[_]): scala.Boolean = + this.data.isAssignableFrom(that.getData()) + + def isInterface(): scala.Boolean = + data.isInterface + + def isArray(): scala.Boolean = + data.isArrayClass + + def isPrimitive(): scala.Boolean = + data.isPrimitive + + def getName(): String = + data.name + + def getSimpleName(): String = { + if (cachedSimpleName == null) + cachedSimpleName = computeCachedSimpleNameBestEffort() + cachedSimpleName + } + + /** Computes a best-effort guess of what `getSimpleName()` should return. + * + * The JavaDoc says: + * + * > Returns the simple name of the underlying class as given in the source + * > code. Returns an empty string if the underlying class is anonymous. + * > + * > The simple name of an array is the simple name of the component type + * > with "[]" appended. In particular the simple name of an array whose + * > component type is anonymous is "[]". + * + * Note the "as given in the source code" part. Clearly, this is not always + * the case, since Scala local classes receive a numeric suffix, for + * example. + * + * In the absence of precise algorithm, we make a best-effort to make + * reasonable use cases mimic the JVM. + */ + private def computeCachedSimpleNameBestEffort(): String = { + @inline def isDigit(c: Char): scala.Boolean = c >= '0' && c <= '9' + + if (isArray()) { + getComponentType().getSimpleName() + "[]" + } else { + val name = data.name + var idx = name.length - 1 + + // Include trailing '$'s for module class names + while (idx >= 0 && name.charAt(idx) == '$') { + idx -= 1 + } + + // Include '$'s followed by '0-9's for local class names + if (idx >= 0 && isDigit(name.charAt(idx))) { + idx -= 1 + while (idx >= 0 && isDigit(name.charAt(idx))) { + idx -= 1 + } + while (idx >= 0 && name.charAt(idx) == '$') { + idx -= 1 + } + } + + // Include until the next '$' (inner class) or '.' (top-level class) + while (idx >= 0 && { + val currChar = name.charAt(idx) + currChar != '.' && currChar != '$' + }) { + idx -= 1 + } + + name.substring(idx + 1) + } + } + + def getSuperclass(): Class[_ >: A] = + data.getSuperclass() + + def getComponentType(): Class[_] = + data.getComponentType() + + @inline + def cast(obj: Any): A = { + getData().checkCast(obj) + obj.asInstanceOf[A] + } + + // java.lang.reflect.Array support + + private[lang] def newArrayOfThisClass(dimensions: js.Array[Int]): AnyRef = + data.newArrayOfThisClass(dimensions) +} diff --git a/javalanglib/src/main/scala/java/lang/ClassLoader.scala b/javalib/src/main/scala/java/lang/ClassLoader.scala similarity index 100% rename from javalanglib/src/main/scala/java/lang/ClassLoader.scala rename to javalib/src/main/scala/java/lang/ClassLoader.scala diff --git a/javalib/src/main/scala/java/lang/ClassValue.scala b/javalib/src/main/scala/java/lang/ClassValue.scala new file mode 100644 index 0000000000..94f46965e4 --- /dev/null +++ b/javalib/src/main/scala/java/lang/ClassValue.scala @@ -0,0 +1,83 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.lang + +import java.util.HashMap + +import scala.scalajs.js +import scala.scalajs.js.annotation._ +import scala.scalajs.runtime.linkingInfo +import scala.scalajs.LinkingInfo.ESVersion + +import Utils._ + +abstract class ClassValue[T] protected () { + private val jsMap: js.Map[Class[_], T] = { + if (linkingInfo.esVersion >= ESVersion.ES2015 || js.typeOf(js.Dynamic.global.Map) != "undefined") + new js.Map() + else + null + } + + @inline + private def useJSMap: scala.Boolean = { + /* The linking-info test allows to constant-fold this method as `true` when + * emitting ES 2015 code, which allows to dead-code-eliminate the branches + * using `HashMap`s, and therefore `HashMap` itself. + */ + linkingInfo.esVersion >= ESVersion.ES2015 || jsMap != null + } + + /* We use a HashMap instead of an IdentityHashMap because the latter is + * implemented in terms of the former anyway, to a HashMap is leaner and + * faster. + */ + private val javaMap: HashMap[Class[_], T] = + if (useJSMap) null + else new HashMap() + + protected def computeValue(`type`: Class[_]): T + + def get(`type`: Class[_]): T = { + if (useJSMap) { + mapGetOrElseUpdate(jsMap, `type`)(computeValue(`type`)) + } else { + /* We first perform `get`, and if the result is null, we use + * `containsKey` to disambiguate a present null from an absent key. + * Since the purpose of ClassValue is to be used a cache indexed by Class + * values, the expected use case will have more hits than misses, and so + * this ordering should be faster on average than first performing `has` + * then `get`. + */ + javaMap.get(`type`) match { + case null => + if (javaMap.containsKey(`type`)) { + null.asInstanceOf[T] + } else { + val newValue = computeValue(`type`) + javaMap.put(`type`, newValue) + newValue + } + case value => + value + } + } + } + + def remove(`type`: Class[_]): Unit = { + if (useJSMap) + jsMap.delete(`type`) + else + javaMap.remove(`type`) + } +} diff --git a/javalanglib/src/main/scala/java/lang/Cloneable.scala b/javalib/src/main/scala/java/lang/Cloneable.scala similarity index 100% rename from javalanglib/src/main/scala/java/lang/Cloneable.scala rename to javalib/src/main/scala/java/lang/Cloneable.scala diff --git a/javalanglib/src/main/scala/java/lang/Comparable.scala b/javalib/src/main/scala/java/lang/Comparable.scala similarity index 100% rename from javalanglib/src/main/scala/java/lang/Comparable.scala rename to javalib/src/main/scala/java/lang/Comparable.scala diff --git a/javalib/src/main/scala/java/lang/Double.scala b/javalib/src/main/scala/java/lang/Double.scala new file mode 100644 index 0000000000..bb6626981e --- /dev/null +++ b/javalib/src/main/scala/java/lang/Double.scala @@ -0,0 +1,383 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.lang + +import java.lang.constant.{Constable, ConstantDesc} + +import scala.scalajs.js + +import Utils._ + +/* This is a hijacked class. Its instances are primitive numbers. + * Constructors are not emitted. + */ +final class Double private () + extends Number with Comparable[Double] with Constable with ConstantDesc { + + def this(value: scala.Double) = this() + def this(s: String) = this() + + @inline def doubleValue(): scala.Double = + this.asInstanceOf[scala.Double] + + @inline override def byteValue(): scala.Byte = doubleValue().toByte + @inline override def shortValue(): scala.Short = doubleValue().toShort + @inline def intValue(): scala.Int = doubleValue().toInt + @inline def longValue(): scala.Long = doubleValue().toLong + @inline def floatValue(): scala.Float = doubleValue().toFloat + + @inline override def equals(that: Any): scala.Boolean = + this eq that.asInstanceOf[AnyRef] + + @inline override def hashCode(): Int = + Double.hashCode(doubleValue()) + + @inline override def compareTo(that: Double): Int = + Double.compare(doubleValue(), that.doubleValue()) + + @inline override def toString(): String = + Double.toString(doubleValue()) + + @inline def isNaN(): scala.Boolean = + Double.isNaN(doubleValue()) + + @inline def isInfinite(): scala.Boolean = + Double.isInfinite(doubleValue()) + +} + +object Double { + /* TYPE should be a `final val`, but that crashes the JVM back-end, so we + * use a 'def' instead, which is binary compatible. + */ + def TYPE: Class[_] = scala.Predef.classOf[scala.Double] + + final val POSITIVE_INFINITY = 1.0 / 0.0 + final val NEGATIVE_INFINITY = 1.0 / -0.0 + final val NaN = 0.0 / 0.0 + final val MAX_VALUE = scala.Double.MaxValue + final val MIN_NORMAL = 2.2250738585072014e-308 + final val MIN_VALUE = scala.Double.MinPositiveValue + final val MAX_EXPONENT = 1023 + final val MIN_EXPONENT = -1022 + final val SIZE = 64 + final val BYTES = 8 + + @inline def `new`(value: scala.Double): Double = valueOf(value) + + @inline def `new`(s: String): Double = valueOf(s) + + @inline def valueOf(d: scala.Double): Double = d.asInstanceOf[Double] + + @inline def valueOf(s: String): Double = valueOf(parseDouble(s)) + + private[this] lazy val doubleStrPat = new js.RegExp( + "^" + + "[\\x00-\\x20]*(" + // optional whitespace + "[+-]?" + // optional sign + "(?:NaN|Infinity|" + // special cases + "(?:\\d+\\.?\\d*|" + // literal w/ leading digit + "\\.\\d+)" + // literal w/o leading digit + "(?:[eE][+-]?\\d+)?" + // optional exponent + ")[fFdD]?" + // optional float / double specifier (ignored) + ")[\\x00-\\x20]*" + // optional whitespace + "$") + + private[this] lazy val doubleStrHexPat = new js.RegExp( + "^" + + "[\\x00-\\x20]*" + // optional whitespace + "([+-]?)" + // optional sign + "0[xX]" + // hex marker + "([0-9A-Fa-f]*)" + // integral part + "\\.?([0-9A-Fa-f]*)" + // fractional part + "[pP]([+-]?\\d+)" + // binary exponent + "[fFdD]?" + // optional float / double specifier (ignored) + "[\\x00-\\x20]*" + // optional whitespace + "$") + + def parseDouble(s: String): scala.Double = { + val groups = doubleStrPat.exec(s) + if (groups != null) + js.Dynamic.global.parseFloat(undefOrForceGet[String](groups(1))).asInstanceOf[scala.Double] + else + parseDoubleSlowPath(s) + } + + // Slow path of `parseDouble` for hexadecimal notation and failure + private def parseDoubleSlowPath(s: String): scala.Double = { + def fail(): Nothing = + throw new NumberFormatException(s"""For input string: "$s"""") + + val groups = doubleStrHexPat.exec(s) + if (groups == null) + fail() + + val signStr = undefOrForceGet(groups(1)) + val integralPartStr = undefOrForceGet(groups(2)) + val fractionalPartStr = undefOrForceGet(groups(3)) + val binaryExpStr = undefOrForceGet(groups(4)) + + if (integralPartStr == "" && fractionalPartStr == "") + fail() + + val absResult = parseHexDoubleImpl(integralPartStr, fractionalPartStr, + binaryExpStr, maxPrecisionChars = 15) + + if (signStr == "-") + -absResult + else + absResult + } + + /** Parses a non-negative Double expressed in hexadecimal notation. + * + * This returns the result of parsing + * {{{ + * "0x" + integralPartStr + "." + fractionalPartStr + "p" + binaryExpStr + * }}} + * but truncating the total number of characters in `integralPartStr` and + * `fractionalPartStr` participating in the resulting precision to + * `maxPrecisionChars`. + * + * `maxPrecisionChars` must be 15 to parse Double values, and 7 to parse + * Float values. + */ + private[lang] def parseHexDoubleImpl(integralPartStr: String, + fractionalPartStr: String, binaryExpStr: String, + maxPrecisionChars: Int): scala.Double = { + // scalastyle:off return + + /* We concatenate the integral part and fractional part together, then + * we parse the result as an integer. This means that we need to remember + * a correction to be applied to the final result, as a diff to the + * binary exponent + */ + val mantissaStr0 = integralPartStr + fractionalPartStr + val correction1 = -(fractionalPartStr.length * 4) // 1 hex == 4 bits + + /* Remove leading 0's in `mantissaStr`, because our algorithm assumes + * that there is none. + */ + var i = 0 + while (i != mantissaStr0.length && mantissaStr0.charAt(i) == '0') + i += 1 + val mantissaStr = mantissaStr0.substring(i) + + /* If the mantissa is empty, it means there were only 0's, and we + * short-cut to directly returning 0.0 or -0.0. This is important because + * the final step of the algorithm (multiplying by `correctingPow`) + * assumes that `mantissa` is non-zero in the case of overflow. + */ + if (mantissaStr == "") + return 0.0 + + /* If there are more than `maxPrecisionChars` characters left, we compress + * the tail as a single character. This has two purposes: + * + * - First, if we don't, there can be corner cases where the `mantissaStr` + * would parse as `Infinity` because it is too large on its own, but + * where the binary exponent can "fix it" by being sufficiently under or + * above 0. (see #4431) + * - Second, when parsing Floats, this ensures that values very close above + * or below a Float midpoint are parsed as a Double that is actually + * above or below the midpoint. If we don't, the parsed value can be + * rounded to exactly the midpoint, which will cause incorrect rounding + * when later converting it to a Float value. (see #4035) + * + * Only `maxPrecisionChars` characters can directly participate in the + * precision of the final result. The last one may already loose precision, + * but will determine whether to round up or down. If its low-order bits + * that are lost are exactly a '1' followed by '0's, then even a character + * very far away in the tail can make the difference between rounding up + * or down (see #4431). However the only possible difference is between + * "all-zeros" or "at least one non-zero" after the `maxPrecisionChars`th + * character. We can therefore compress the entire tail as single "0" or + * "1". + * + * Of course, we remember that we need to apply a correction to the + * exponent of the final result. + * + * (A similar strategy is used in the primitive Long-to-Float conversion.) + */ + val mantissaStrLen = mantissaStr.length() + val needsCorrection2 = mantissaStrLen > maxPrecisionChars + val truncatedMantissaStr = if (needsCorrection2) { + var hasNonZeroChar = false + var j = maxPrecisionChars + while (!hasNonZeroChar && j != mantissaStrLen) { + if (mantissaStr.charAt(j) != '0') + hasNonZeroChar = true + j += 1 + } + val compressedTail = if (hasNonZeroChar) "1" else "0" + mantissaStr.substring(0, maxPrecisionChars) + compressedTail + } else { + mantissaStr + } + val correction2 = + if (needsCorrection2) (mantissaStr.length - (maxPrecisionChars + 1)) * 4 // one hex == 4 bits + else 0 + + val fullCorrection = correction1 + correction2 + + /* Note that we do not care too much about overflows and underflows when + * manipulating binary exponents and corrections, because the corrections + * are directly related to the length of the input string, so they cannot + * be *that* big (or we have bigger problems), and the final result needs + * to fit in the [-1024, 1023] range, which can only happen if the + * `binaryExp` (see below) did not stray too far from that range itself. + */ + + @inline def nativeParseInt(s: String, radix: Int): scala.Double = + js.Dynamic.global.parseInt(s, radix).asInstanceOf[scala.Double] + + val mantissa = nativeParseInt(truncatedMantissaStr, 16) + // Assert: mantissa != 0.0 && mantissa != scala.Double.PositiveInfinity + + val binaryExpDouble = nativeParseInt(binaryExpStr, 10) + val binaryExp = binaryExpDouble.toInt // caps to [MinValue, MaxValue] + + val binExpAndCorrection = binaryExp + fullCorrection + + /* If `baseExponent` is the IEEE exponent of `mantissa`, then + * `binExpAndCorrection + baseExponent` must be in the valid range of + * IEEE exponents, which is [-1074, 1023]. Therefore, if + * `binExpAndCorrection` is out of twice that range, we will end up with + * an overflow or an underflow anyway. + * + * If it is inside twice that range, then we need to multiply `mantissa` + * by `Math.pow(2, binExpAndCorrection)`. However that `pow` could + * overflow or underflow itself, so we cut it in 3 parts. If that does + * not suffice for it not to overflow or underflow, it's because it + * wasn't in the safe range to begin with. + */ + val binExpAndCorrection_div_3 = binExpAndCorrection / 3 + val correctingPow = Math.pow(2, binExpAndCorrection_div_3) + val correctingPow3 = + Math.pow(2, binExpAndCorrection - 2*binExpAndCorrection_div_3) + + ((mantissa * correctingPow) * correctingPow) * correctingPow3 + + // scalastyle:on return + } + + @inline def toString(d: scala.Double): String = + "" + d + + def toHexString(d: scala.Double): String = { + val ebits = 11 // exponent size + val mbits = 52 // mantissa size + val bias = (1 << (ebits - 1)) - 1 + + val bits = doubleToLongBits(d) + val s = bits < 0 + val m = bits & ((1L << mbits) - 1L) + val e = (bits >>> mbits).toInt & ((1 << ebits) - 1) // biased + + val posResult = if (e > 0) { + if (e == (1 << ebits) - 1) { + // Special + if (m != 0L) "NaN" + else "Infinity" + } else { + // Normalized + "0x1." + mantissaToHexString(m) + "p" + (e - bias) + } + } else { + if (m != 0L) { + // Subnormal + "0x0." + mantissaToHexString(m) + "p-1022" + } else { + // Zero + "0x0.0p0" + } + } + + if (bits < 0) "-" + posResult else posResult + } + + @inline + private def mantissaToHexString(m: scala.Long): String = + mantissaToHexStringLoHi(m.toInt, (m >>> 32).toInt) + + private def mantissaToHexStringLoHi(lo: Int, hi: Int): String = { + @inline def padHex5(i: Int): String = { + val s = Integer.toHexString(i) + "00000".substring(s.length) + s // 5 zeros + } + + @inline def padHex8(i: Int): String = { + val s = Integer.toHexString(i) + "00000000".substring(s.length) + s // 8 zeros + } + + val padded = padHex5(hi) + padHex8(lo) + + var len = padded.length + while (len > 1 && padded.charAt(len - 1) == '0') + len -= 1 + padded.substring(0, len) + } + + def compare(a: scala.Double, b: scala.Double): scala.Int = { + // NaN must equal itself, and be greater than anything else + if (isNaN(a)) { + if (isNaN(b)) 0 + else 1 + } else if (isNaN(b)) { + -1 + } else { + if (a == b) { + // -0.0 must be smaller than 0.0 + if (a == 0.0) { + val ainf = 1.0/a + if (ainf == 1.0/b) 0 + else if (ainf < 0) -1 + else 1 + } else { + 0 + } + } else { + if (a < b) -1 + else 1 + } + } + } + + @inline def isNaN(v: scala.Double): scala.Boolean = + v != v + + @inline def isInfinite(v: scala.Double): scala.Boolean = + v == POSITIVE_INFINITY || v == NEGATIVE_INFINITY + + @inline def isFinite(d: scala.Double): scala.Boolean = + !isNaN(d) && !isInfinite(d) + + @inline def hashCode(value: scala.Double): Int = + FloatingPointBits.numberHashCode(value) + + @inline def longBitsToDouble(bits: scala.Long): scala.Double = + FloatingPointBits.longBitsToDouble(bits) + + @inline def doubleToLongBits(value: scala.Double): scala.Long = + FloatingPointBits.doubleToLongBits(value) + + @inline def sum(a: scala.Double, b: scala.Double): scala.Double = + a + b + + @inline def max(a: scala.Double, b: scala.Double): scala.Double = + Math.max(a, b) + + @inline def min(a: scala.Double, b: scala.Double): scala.Double = + Math.min(a, b) +} diff --git a/javalanglib/src/main/scala/java/lang/Enum.scala b/javalib/src/main/scala/java/lang/Enum.scala similarity index 99% rename from javalanglib/src/main/scala/java/lang/Enum.scala rename to javalib/src/main/scala/java/lang/Enum.scala index 8f4dfb50b1..08e9c80085 100644 --- a/javalanglib/src/main/scala/java/lang/Enum.scala +++ b/javalib/src/main/scala/java/lang/Enum.scala @@ -30,7 +30,7 @@ abstract class Enum[E <: Enum[E]] protected (_name: String, _ordinal: Int) override protected final def clone(): AnyRef = throw new CloneNotSupportedException("Enums are not cloneable") - final def compareTo(o: E): Int = Integer.compare(_ordinal, o.ordinal) + final def compareTo(o: E): Int = Integer.compare(_ordinal, o.ordinal()) // Not implemented: // final def getDeclaringClass(): Class[E] diff --git a/javalib/src/main/scala/java/lang/Float.scala b/javalib/src/main/scala/java/lang/Float.scala new file mode 100644 index 0000000000..4dcd15a6c1 --- /dev/null +++ b/javalib/src/main/scala/java/lang/Float.scala @@ -0,0 +1,395 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.lang + +import java.lang.constant.{Constable, ConstantDesc} +import java.math.BigInteger + +import scala.scalajs.js + +/* This is a hijacked class. Its instances are primitive numbers. + * Constructors are not emitted. + */ +final class Float private () + extends Number with Comparable[Float] with Constable with ConstantDesc { + + def this(value: scala.Float) = this() + def this(s: String) = this() + + @inline def floatValue(): scala.Float = + this.asInstanceOf[scala.Float] + + @inline override def byteValue(): scala.Byte = floatValue().toByte + @inline override def shortValue(): scala.Short = floatValue().toShort + @inline def intValue(): scala.Int = floatValue().toInt + @inline def longValue(): scala.Long = floatValue().toLong + @inline def doubleValue(): scala.Double = floatValue().toDouble + + @inline override def equals(that: Any): scala.Boolean = + this eq that.asInstanceOf[AnyRef] + + @inline override def hashCode(): Int = + Float.hashCode(floatValue()) + + @inline override def compareTo(that: Float): Int = + Float.compare(floatValue(), that.floatValue()) + + @inline override def toString(): String = + Float.toString(floatValue()) + + @inline def isNaN(): scala.Boolean = + Float.isNaN(floatValue()) + + @inline def isInfinite(): scala.Boolean = + Float.isInfinite(floatValue()) + +} + +object Float { + /* TYPE should be a `final val`, but that crashes the JVM back-end, so we + * use a 'def' instead, which is binary compatible. + */ + def TYPE: Class[_] = scala.Predef.classOf[scala.Float] + + final val POSITIVE_INFINITY = 1.0f / 0.0f + final val NEGATIVE_INFINITY = 1.0f / -0.0f + final val NaN = 0.0f / 0.0f + final val MAX_VALUE = scala.Float.MaxValue + final val MIN_NORMAL = 1.17549435e-38f + final val MIN_VALUE = scala.Float.MinPositiveValue + final val MAX_EXPONENT = 127 + final val MIN_EXPONENT = -126 + final val SIZE = 32 + final val BYTES = 4 + + @inline def `new`(value: scala.Float): Float = valueOf(value) + + @inline def `new`(value: scala.Double): Float = valueOf(value.toFloat) + + @inline def `new`(s: String): Float = valueOf(s) + + @inline def valueOf(f: scala.Float): Float = f.asInstanceOf[Float] + + @inline def valueOf(s: String): Float = valueOf(parseFloat(s)) + + private[this] lazy val parseFloatRegExp = new js.RegExp( + "^" + + "[\\x00-\\x20]*" + // optional whitespace + "([+-]?)" + // 1: optional sign + "(?:" + + "(NaN)|" + // 2: NaN + "(Infinity)|" + // 3: Infinity + "(?:" + + "(" + // 4: decimal notation + "(?:(\\d+)(?:\\.(\\d*))?|" + // 5-6: w/ digit before . + "\\.(\\d+))" + // 7: w/o digit before . + "(?:[eE]([+-]?\\d+))?" + // 8: optional exponent + ")|" + + "(" + // 9: hexadecimal notation + "0[xX]" + // hex marker + "(?:([0-9A-Fa-f]+)(?:\\.([0-9A-Fa-f]*))?|" + // 10-11: w/ digit before . + "\\.([0-9A-Fa-f]+))" + // 12: w/o digit before . + "[pP]([+-]?\\d+)" + // 13: binary exponent + ")" + + ")" + + "[fFdD]?" + // optional float / double specifier (ignored) + ")" + + "[\\x00-\\x20]*" + // optional whitespace + "$" + ) + + def parseFloat(s: String): scala.Float = { + import Utils._ + + val groups = parseFloatRegExp.exec(s) + if (groups == null) + throw new NumberFormatException(s"""For input string: "$s"""") + + val absResult = if (undefOrIsDefined(groups(2))) { + scala.Float.NaN + } else if (undefOrIsDefined(groups(3))) { + scala.Float.PositiveInfinity + } else if (undefOrIsDefined(groups(4))) { + // Decimal notation + val fullNumberStr = undefOrForceGet(groups(4)) + val integralPartStr = undefOrGetOrElse(groups(5))("") + val fractionalPartStr = undefOrGetOrElse(groups(6))("") + undefOrGetOrElse(groups(7))("") + val exponentStr = undefOrGetOrElse(groups(8))("0") + parseFloatDecimal(fullNumberStr, integralPartStr, fractionalPartStr, exponentStr) + } else { + // Hexadecimal notation + val integralPartStr = undefOrGetOrElse(groups(10))("") + val fractionalPartStr = undefOrGetOrElse(groups(11))("") + undefOrGetOrElse(groups(12))("") + val binaryExpStr = undefOrForceGet(groups(13)) + parseFloatHexadecimal(integralPartStr, fractionalPartStr, binaryExpStr) + } + + val signStr = undefOrForceGet(groups(1)) + if (signStr == "-") + -absResult + else + absResult + } + + private def parseFloatDecimal(fullNumberStr: String, + integralPartStr: String, fractionalPartStr: String, + exponentStr: String): scala.Float = { + + val z0 = js.Dynamic.global.parseFloat(fullNumberStr).asInstanceOf[scala.Double] + val z = z0.toFloat + val zDouble = z.toDouble + + if (zDouble == z0) { + /* This branch is always taken when strictFloats are disabled, and there + * is no Math.fround support. In that case, Floats are basically + * equivalent to Doubles, and we make no specific guarantee about the + * result, so we can quickly return `z`. + * More importantly, the computations in the `else` branch assume that + * Float operations are exact, so we must return early. + * + * This branch is also always taken when z0 is 0.0 or Infinity, which the + * `else` branch assumes does not happen. + */ + z + } else { + /* #4035 `z` might be 1 ULP above or below the best approximation if `z0` + * is exactly halfway between two adjacent Float values. + * We need to detect that case, and fall back to the slow algorithm. + */ + if (zDouble == scala.Double.PositiveInfinity) { + // Magical constant = Float.MaxValue.toDouble + (Math.ulp(Float.MaxValue).toDouble / 2.0) + val mid = 3.4028235677973366e38 + if (z0 == mid) + parseFloatDecimalCorrection(integralPartStr, fractionalPartStr, exponentStr, MAX_VALUE, z, mid) + else + z + } else if (zDouble < z0) { + val zUp = Math.nextUp(z) + val mid = (zDouble + zUp.toDouble) / 2.0 + if (z0 == mid) + parseFloatDecimalCorrection(integralPartStr, fractionalPartStr, exponentStr, z, zUp, mid) + else + z + } else { + val zDown = Math.nextDown(z) + val mid = (zDouble + zDown.toDouble) / 2.0 + if (z0 == mid) + parseFloatDecimalCorrection(integralPartStr, fractionalPartStr, exponentStr, zDown, z, mid) + else + z + } + } + } + + /** Slow algorithm to correct the initial approximation. + * + * `zDown` and `zUp` must be adjacent Float values that surround the exact + * result, `zDown` being the smallest one. `zUp` can be `Infinity`. + * + * `mid` must be the mid-point between `zDown` and `zUp`. It is a `Double` + * so that it can exactly hold that value. If the exact value is below + * `mid`, this function returns `zDown`; if it is above `mid`, it returns + * `zUp`. If it is exactly equal to `mid`, `parseFloatCorrection` breaks + * the tie to even. + * + * When `zUp` is `Infinity`, `mid` must be the value + * `3.4028235677973366e38`, which is equal to + * `Float.MaxValue.toDouble + (Math.ulp(Float.MaxValue).toDouble / 2.0)`. + * + * --- + * + * As proven in the paper "How to Read Float Point Numbers Accurately" by + * William D. Clinger, there is no solution that does not require big + * integer arithmetic at some point. We take inspiration from the + * `AlgorithmR` from that paper, which takes an initial value "close" to the + * best approximation and improves it by 1 ULP. Since we already have a + * close approximation (one that is at most 1 ULP away from the best one), + * we can use that. However, we can dramatically simplify the algorithm + * because we can leverage Double arithmetics to parse only a Float. In + * particular, we can accurately compute and represent the two adjacent + * Floats that enclose the best approximation, as well as the midpoint + * between those, which is a Double. We receive those from + * `parseFloatDecimal`, which already had to compute them in order to decide + * whether a correction was needed. The only real thing we keep from the + * paper is the step 3: how to accurately compare that midpoint with the + * exact value represented by the string, using big integer arithmetics. + * This allows us to decide whether we need to round up, down, or break a + * tie to even. + * + * `AlgorithmR` in the paper is generic wrt. the bases of the input and + * output. In our case, the input base Δ is 10 and the output base β is 2. + */ + private def parseFloatDecimalCorrection(integralPartStr: String, + fractionalPartStr: String, exponentStr: String, + zDown: scala.Float, zUp: scala.Float, mid: scala.Double): scala.Float = { + + // 1. Accurately parse the string with the representation f × 10ᵉ + + val f: BigInteger = new BigInteger(integralPartStr + fractionalPartStr) + val e: Int = Integer.parseInt(exponentStr) - fractionalPartStr.length() + + /* Note: we know that `e` is "reasonable" (in the range [-324, +308]). If + * it were way too big or way too small, the original JS `parseFloat` in + * `parseFloatDecimal` would have returned `Infinity` or `0.0`, + * respectively. In that case, we would have selected the first branch, and + * never called `parseFloatDecimalCorrection`. + * + * Since `e` is reasonable and `fractionPartStr.length()` is a non-negative + * Int, the above computation cannot underflow, and the only way it could + * overflow is if the length of the string were `>= (Int.MaxValue - 308)`, + * which is not worth caring for. + */ + + // 2. Accurately decompose `mid` with the representation m × 2ᵏ + + val mbits = 52 // number of bits of the mantissa (without the implicit '1') + val kbits = 11 // number of bits of the exponent + val bias = (1 << (kbits - 1)) - 1 // the bias of the exponent + + val midBits = Double.doubleToLongBits(mid) + val biasedK = (midBits >> mbits).toInt + + /* Because `mid` is a double value halfway between two floats, it cannot + * be a double subnormal (even if the two floats that surround it are + * subnormal floats). + */ + if (biasedK == 0) + throw new AssertionError(s"parseFloatCorrection was given a subnormal mid: $mid") + + val mExplicitBits = midBits & ((1L << mbits) - 1) + val mImplicit1Bit = 1L << mbits // the implicit '1' bit of a normalized floating-point number + val m = BigInteger.valueOf(mExplicitBits | mImplicit1Bit) + val k = biasedK - bias - mbits + + // 3. Accurately compare f × 10ᵉ to m × 2ᵏ + + @inline def compare(x: BigInteger, y: BigInteger): Int = + x.compareTo(y) + + val cmp = if (e >= 0) { + if (k >= 0) + compare(multiplyBy10Pow(f, e), multiplyBy2Pow(m, k)) + else + compare(multiplyBy2Pow(multiplyBy10Pow(f, e), -k), m) // this branch may be dead code in practice + } else { + if (k >= 0) + compare(f, multiplyBy2Pow(multiplyBy10Pow(m, -e), k)) + else + compare(multiplyBy2Pow(f, -k), multiplyBy10Pow(m, -e)) + } + + // 4. Choose zDown or zUp depending on the result of the comparison + + if (cmp < 0) + zDown + else if (cmp > 0) + zUp + else if ((floatToIntBits(zDown) & 1) == 0) // zDown is even + zDown + else + zUp + } + + @inline private def multiplyBy10Pow(v: BigInteger, e: Int): BigInteger = + v.multiply(BigInteger.TEN.pow(e)) + + @inline private def multiplyBy2Pow(v: BigInteger, e: Int): BigInteger = + v.shiftLeft(e) + + private def parseFloatHexadecimal(integralPartStr: String, + fractionalPartStr: String, binaryExpStr: String): scala.Float = { + val doubleValue = Double.parseHexDoubleImpl(integralPartStr, + fractionalPartStr, binaryExpStr, maxPrecisionChars = 7) + doubleValue.toFloat + } + + @inline def toString(f: scala.Float): String = + "" + f + + def toHexString(f: scala.Float): String = { + val ebits = 8 // exponent size + val mbits = 23 // mantissa size + val bias = (1 << (ebits - 1)) - 1 + + val bits = floatToIntBits(f) + val s = bits < 0 + val m = bits & ((1 << mbits) - 1) + val e = (bits >>> mbits).toInt & ((1 << ebits) - 1) // biased + + val posResult = if (e > 0) { + if (e == (1 << ebits) - 1) { + // Special + if (m != 0) "NaN" + else "Infinity" + } else { + // Normalized + "0x1." + mantissaToHexString(m) + "p" + (e - bias) + } + } else { + if (m != 0) { + // Subnormal + "0x0." + mantissaToHexString(m) + "p-126" + } else { + // Zero + "0x0.0p0" + } + } + + if (bits < 0) "-" + posResult else posResult + } + + @inline + private def mantissaToHexString(m: Int): String = { + @inline def padHex6(i: Int): String = { + val s = Integer.toHexString(i) + "000000".substring(s.length) + s // 6 zeros + } + + // The << 1 turns `m` from a 23-bit int into a 24-bit int (multiple of 4) + val padded = padHex6(m << 1) + var len = padded.length + while (len > 1 && padded.charAt(len - 1) == '0') + len -= 1 + padded.substring(0, len) + } + + @inline def compare(a: scala.Float, b: scala.Float): scala.Int = + Double.compare(a, b) + + @inline def isNaN(v: scala.Float): scala.Boolean = + v != v + + @inline def isInfinite(v: scala.Float): scala.Boolean = + v == POSITIVE_INFINITY || v == NEGATIVE_INFINITY + + @inline def isFinite(f: scala.Float): scala.Boolean = + !isNaN(f) && !isInfinite(f) + + @inline def hashCode(value: scala.Float): Int = + FloatingPointBits.numberHashCode(value) + + @inline def intBitsToFloat(bits: scala.Int): scala.Float = + FloatingPointBits.intBitsToFloat(bits) + + @inline def floatToIntBits(value: scala.Float): scala.Int = + FloatingPointBits.floatToIntBits(value) + + @inline def sum(a: scala.Float, b: scala.Float): scala.Float = + a + b + + @inline def max(a: scala.Float, b: scala.Float): scala.Float = + Math.max(a, b) + + @inline def min(a: scala.Float, b: scala.Float): scala.Float = + Math.min(a, b) +} diff --git a/javalib/src/main/scala/java/lang/FloatingPointBits.scala b/javalib/src/main/scala/java/lang/FloatingPointBits.scala new file mode 100644 index 0000000000..3b3f972346 --- /dev/null +++ b/javalib/src/main/scala/java/lang/FloatingPointBits.scala @@ -0,0 +1,356 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.lang + +import scala.scalajs.js +import scala.scalajs.js.Dynamic.global +import scala.scalajs.js.typedarray +import scala.scalajs.LinkingInfo.ESVersion + +/** Manipulating the bits of floating point numbers. */ +private[lang] object FloatingPointBits { + + import scala.scalajs.runtime.linkingInfo + + private[this] val _areTypedArraysSupported = { + // Here we use the `esVersion` test to dce the 4 subsequent tests + linkingInfo.esVersion >= ESVersion.ES2015 || { + js.typeOf(global.ArrayBuffer) != "undefined" && + js.typeOf(global.Int32Array) != "undefined" && + js.typeOf(global.Float32Array) != "undefined" && + js.typeOf(global.Float64Array) != "undefined" + } + } + + @inline + private def areTypedArraysSupported: scala.Boolean = { + /* We have a forwarder to the internal `val _areTypedArraysSupported` to + * be able to inline it. This achieves the following: + * * If we emit ES2015+, dce `|| _areTypedArraysSupported` and replace + * `areTypedArraysSupported` by `true` in the calling code, allowing + * polyfills in the calling code to be dce'ed in turn. + * * If we emit ES5, replace `areTypedArraysSupported` by + * `_areTypedArraysSupported` so we do not calculate it multiple times. + */ + linkingInfo.esVersion >= ESVersion.ES2015 || _areTypedArraysSupported + } + + private val arrayBuffer = + if (areTypedArraysSupported) new typedarray.ArrayBuffer(8) + else null + + private val int32Array = + if (areTypedArraysSupported) new typedarray.Int32Array(arrayBuffer, 0, 2) + else null + + private val float32Array = + if (areTypedArraysSupported) new typedarray.Float32Array(arrayBuffer, 0, 2) + else null + + private val float64Array = + if (areTypedArraysSupported) new typedarray.Float64Array(arrayBuffer, 0, 1) + else null + + private val areTypedArraysBigEndian = { + if (areTypedArraysSupported) { + int32Array(0) = 0x01020304 + (new typedarray.Int8Array(arrayBuffer, 0, 8))(0) == 0x01 + } else { + true // as good a value as any + } + } + + private val highOffset = if (areTypedArraysBigEndian) 0 else 1 + private val lowOffset = if (areTypedArraysBigEndian) 1 else 0 + + private val floatPowsOf2: js.Array[scala.Double] = + if (areTypedArraysSupported) null + else makePowsOf2(len = 1 << 8, java.lang.Float.MIN_NORMAL.toDouble) + + private val doublePowsOf2: js.Array[scala.Double] = + if (areTypedArraysSupported) null + else makePowsOf2(len = 1 << 11, java.lang.Double.MIN_NORMAL) + + private def makePowsOf2(len: Int, minNormal: scala.Double): js.Array[scala.Double] = { + val r = new js.Array[scala.Double](len) + r(0) = 0.0 + var i = 1 + var next = minNormal + while (i != len - 1) { + r(i) = next + i += 1 + next *= 2 + } + r(len - 1) = scala.Double.PositiveInfinity + r + } + + /** Hash code of a number (excluding Longs). + * + * Because of the common encoding for integer and floating point values, + * the hashCode of Floats and Doubles must align with that of Ints for the + * common values. + * + * For other values, we use the hashCode specified by the JavaDoc for + * *Doubles*, even for values which are valid Float values. Because of the + * previous point, we cannot align completely with the Java specification, + * so there is no point trying to be a bit more aligned here. Always using + * the Double version should typically be faster on VMs without fround + * support because we avoid several fround operations. + */ + def numberHashCode(value: scala.Double): Int = { + val iv = rawToInt(value) + if (iv == value && 1.0/value != scala.Double.NegativeInfinity) { + iv + } else { + /* Basically an inlined version of `Long.hashCode(doubleToLongBits(value))`, + * so that we never allocate a RuntimeLong instance (or anything, for + * that matter). + * + * In addition, in the happy path where typed arrays are supported, since + * we xor together the two Ints, it doesn't matter which one comes first + * or second, and hence we can use constants 0 and 1 instead of having an + * indirection through `highOffset` and `lowOffset`. + */ + if (areTypedArraysSupported) { + float64Array(0) = value + int32Array(0) ^ int32Array(1) + } else { + doubleHashCodePolyfill(value) + } + } + } + + @noinline + private def doubleHashCodePolyfill(value: scala.Double): Int = + Long.hashCode(doubleToLongBitsPolyfillInline(value)) + + def intBitsToFloat(bits: Int): scala.Float = { + if (areTypedArraysSupported) { + int32Array(0) = bits + float32Array(0) + } else { + intBitsToFloatPolyfill(bits).toFloat + } + } + + def floatToIntBits(value: scala.Float): Int = { + if (areTypedArraysSupported) { + float32Array(0) = value + int32Array(0) + } else { + floatToIntBitsPolyfill(value.toDouble) + } + } + + def longBitsToDouble(bits: scala.Long): scala.Double = { + if (areTypedArraysSupported) { + int32Array(highOffset) = (bits >>> 32).toInt + int32Array(lowOffset) = bits.toInt + float64Array(0) + } else { + longBitsToDoublePolyfill(bits) + } + } + + def doubleToLongBits(value: scala.Double): scala.Long = { + if (areTypedArraysSupported) { + float64Array(0) = value + ((int32Array(highOffset).toLong << 32) | + (int32Array(lowOffset).toLong & 0xffffffffL)) + } else { + doubleToLongBitsPolyfill(value) + } + } + + /* --- Polyfills for floating point bit manipulations --- + * + * Originally inspired by + * https://github.com/inexorabletash/polyfill/blob/3447582628b6e3ea81959c4d5987aa332c22d1ca/typedarray.js#L150-L264 + * + * Note that if typed arrays are not supported, it is almost certain that + * fround is not supported natively, so Float operations are extremely slow. + * + * We therefore do all computations in Doubles here, which is also more + * predictable, since the results do not depend on strict floats semantics. + */ + + private def intBitsToFloatPolyfill(bits: Int): scala.Double = { + val ebits = 8 + val fbits = 23 + val sign = (bits >> 31) | 1 // -1 or 1 + val e = (bits >> fbits) & ((1 << ebits) - 1) + val f = bits & ((1 << fbits) - 1) + decodeIEEE754(ebits, fbits, floatPowsOf2, scala.Float.MinPositiveValue, sign, e, f) + } + + private def floatToIntBitsPolyfill(value: scala.Double): Int = { + // Some constants + val ebits = 8 + val fbits = 23 + + // Determine sign bit and compute the absolute value av + val sign = if (value < 0.0 || (value == 0.0 && 1.0 / value < 0.0)) -1 else 1 + val s = sign & scala.Int.MinValue + val av = sign * value + + // Compute e and f + val avr = forceFround(av) + val powsOf2 = this.floatPowsOf2 // local cache + val e = encodeIEEE754Exponent(ebits, powsOf2, avr) + val f = encodeIEEE754MantissaBits(ebits, fbits, powsOf2, scala.Float.MinPositiveValue.toDouble, avr, e) + + // Encode + s | (e << fbits) | rawToInt(f) + } + + private def longBitsToDoublePolyfill(bits: scala.Long): scala.Double = { + val ebits = 11 + val fbits = 52 + val hifbits = fbits - 32 + val hi = (bits >>> 32).toInt + val lo = Utils.toUint(bits.toInt) + val sign = (hi >> 31) | 1 // -1 or 1 + val e = (hi >> hifbits) & ((1 << ebits) - 1) + val f = (hi & ((1 << hifbits) - 1)).toDouble * 0x100000000L.toDouble + lo + decodeIEEE754(ebits, fbits, doublePowsOf2, scala.Double.MinPositiveValue, sign, e, f) + } + + @noinline + private def doubleToLongBitsPolyfill(value: scala.Double): scala.Long = + doubleToLongBitsPolyfillInline(value) + + @inline + private def doubleToLongBitsPolyfillInline(value: scala.Double): scala.Long = { + // Some constants + val ebits = 11 + val fbits = 52 + val hifbits = fbits - 32 + + // Determine sign bit and compute the absolute value av + val sign = if (value < 0.0 || (value == 0.0 && 1.0 / value < 0.0)) -1 else 1 + val s = sign & scala.Int.MinValue + val av = sign * value + + // Compute e and f + val powsOf2 = this.doublePowsOf2 // local cache + val e = encodeIEEE754Exponent(ebits, powsOf2, av) + val f = encodeIEEE754MantissaBits(ebits, fbits, powsOf2, scala.Double.MinPositiveValue, av, e) + + // Encode + val hi = s | (e << hifbits) | rawToInt(f / 0x100000000L.toDouble) + val lo = rawToInt(f) + (hi.toLong << 32) | (lo.toLong & 0xffffffffL) + } + + @inline + private def decodeIEEE754(ebits: Int, fbits: Int, + powsOf2: js.Array[scala.Double], minPositiveValue: scala.Double, + sign: scala.Int, e: Int, f: scala.Double): scala.Double = { + + // Some constants + val specialExponent = (1 << ebits) - 1 + val twoPowFbits = (1L << fbits).toDouble + + if (e == specialExponent) { + // Special + if (f == 0.0) + sign * scala.Double.PositiveInfinity + else + scala.Double.NaN + } else if (e > 0) { + // Normalized + sign * powsOf2(e) * (1 + f / twoPowFbits) + } else { + // Subnormal + sign * f * minPositiveValue + } + } + + /** Force rounding of `av` to fit in 32 bits (this is a manual `fround`). + * + * `av` must not be negative, i.e., `av < 0.0` must be false (it can be + * `NaN` or `Infinity`). + * + * When we use strict-float semantics, this is redundant, because the input + * came from a `Float` and is therefore guaranteed to be rounded already. + * However, here we don't know whether we use strict floats semantics or + * not, so we must always do it. This is not a big deal because, if this + * code is called, then any operation on `Float`s is calling the same code + * from the `CoreJSLib`, so doing one more such operation for + * `floatToIntBits` is negligible. + * + * TODO Remove this when we get rid of non-strict float semantics altogether. + */ + @inline + private def forceFround(av: scala.Double): scala.Double = { + // See the `fround` polyfill in CoreJSLib + val overflowThreshold = 3.4028235677973366e38 + val normalThreshold = 1.1754943508222875e-38 + if (av >= overflowThreshold) { + scala.Double.PositiveInfinity + } else if (av >= normalThreshold) { + val p = av * 536870913.0 // pow(2, 29) + 1 + p + (av - p) + } else { + val roundingFactor = scala.Double.MinPositiveValue / scala.Float.MinPositiveValue.toDouble + (av * roundingFactor) / roundingFactor + } + } + + private def encodeIEEE754Exponent(ebits: Int, + powsOf2: js.Array[scala.Double], av: scala.Double): Int = { + + /* Binary search of `av` inside `powsOf2`. + * There are exactly `ebits` iterations of this loop (11 for Double, 8 for Float). + */ + var eMin = 0 + var eMax = 1 << ebits + while (eMin + 1 < eMax) { + val e = (eMin + eMax) >> 1 + if (av < powsOf2(e)) // false when av is NaN + eMax = e + else + eMin = e + } + eMin + } + + @inline + private def encodeIEEE754MantissaBits(ebits: Int, fbits: Int, + powsOf2: js.Array[scala.Double], minPositiveValue: scala.Double, + av: scala.Double, e: Int): scala.Double = { + + // Some constants + val specialExponent = (1 << ebits) - 1 + val twoPowFbits = (1L << fbits).toDouble + + if (e == specialExponent) { + if (av != av) + (1L << (fbits - 1)).toDouble // NaN + else + 0.0 // Infinity + } else { + if (e == 0) + av / minPositiveValue // Subnormal + else + ((av / powsOf2(e)) - 1.0) * twoPowFbits // Normal + } + } + + @inline private def rawToInt(x: scala.Double): Int = { + import scala.scalajs.js.DynamicImplicits.number2dynamic + (x | 0).asInstanceOf[Int] + } + +} diff --git a/javalanglib/src/main/scala/java/lang/InheritableThreadLocal.scala b/javalib/src/main/scala/java/lang/InheritableThreadLocal.scala similarity index 100% rename from javalanglib/src/main/scala/java/lang/InheritableThreadLocal.scala rename to javalib/src/main/scala/java/lang/InheritableThreadLocal.scala diff --git a/javalanglib/src/main/scala/java/lang/Integer.scala b/javalib/src/main/scala/java/lang/Integer.scala similarity index 77% rename from javalanglib/src/main/scala/java/lang/Integer.scala rename to javalib/src/main/scala/java/lang/Integer.scala index 1d6996753c..90c46d364f 100644 --- a/javalanglib/src/main/scala/java/lang/Integer.scala +++ b/javalib/src/main/scala/java/lang/Integer.scala @@ -12,12 +12,17 @@ package java.lang +import java.lang.constant.{Constable, ConstantDesc} + import scala.scalajs.js +import scala.scalajs.runtime.linkingInfo +import scala.scalajs.LinkingInfo.ESVersion /* This is a hijacked class. Its instances are primitive numbers. * Constructors are not emitted. */ -final class Integer private () extends Number with Comparable[Integer] { +final class Integer private () + extends Number with Comparable[Integer] with Constable with ConstantDesc { def this(value: scala.Int) = this() def this(s: String) = this() @@ -25,49 +30,42 @@ final class Integer private () extends Number with Comparable[Integer] { @inline def intValue(): scala.Int = this.asInstanceOf[scala.Int] - @inline override def byteValue(): scala.Byte = intValue.toByte - @inline override def shortValue(): scala.Short = intValue.toShort - @inline def longValue(): scala.Long = intValue.toLong - @inline def floatValue(): scala.Float = intValue.toFloat - @inline def doubleValue(): scala.Double = intValue.toDouble + @inline override def byteValue(): scala.Byte = intValue().toByte + @inline override def shortValue(): scala.Short = intValue().toShort + @inline def longValue(): scala.Long = intValue().toLong + @inline def floatValue(): scala.Float = intValue().toFloat + @inline def doubleValue(): scala.Double = intValue().toDouble @inline override def equals(that: Any): scala.Boolean = this eq that.asInstanceOf[AnyRef] @inline override def hashCode(): Int = - intValue + intValue() @inline override def compareTo(that: Integer): Int = - Integer.compare(intValue, that.intValue) + Integer.compare(intValue(), that.intValue()) @inline override def toString(): String = - Integer.toString(intValue) - - /* Methods of java.lang.Byte and java.lang.Short. - * When calling a method of j.l.Byte or j.l.Short on a primitive value, - * it appears to be called directly on the primitive value, which has type - * IntType. Call resolution, by the analyzer and the optimizer, will then - * look for the method in the class j.l.Integer instead of j.l.Byte or - * j.l.Short. This is why we add here the methods of these two classes that - * are not already in j.l.Integer. - */ - - @inline def compareTo(that: Byte): Int = - Integer.compare(intValue, that.intValue) - - @inline def compareTo(that: Short): Int = - Integer.compare(intValue, that.intValue) - + Integer.toString(intValue()) } object Integer { - final val TYPE = scala.Predef.classOf[scala.Int] + /* TYPE should be a `final val`, but that crashes the JVM back-end, so we + * use a 'def' instead, which is binary compatible. + */ + def TYPE: Class[_] = scala.Predef.classOf[scala.Int] + final val MIN_VALUE = -2147483648 final val MAX_VALUE = 2147483647 final val SIZE = 32 final val BYTES = 4 - @inline def valueOf(intValue: scala.Int): Integer = new Integer(intValue) + @inline def `new`(value: scala.Int): Integer = valueOf(value) + + @inline def `new`(s: String): Integer = valueOf(s) + + @inline def valueOf(i: scala.Int): Integer = i.asInstanceOf[Integer] + @inline def valueOf(s: String): Integer = valueOf(parseInt(s)) @inline def valueOf(s: String, radix: Int): Integer = @@ -191,9 +189,9 @@ object Integer { if (x == y) 0 else if (x < y) -1 else 1 @inline def compareUnsigned(x: scala.Int, y: scala.Int): scala.Int = { - import js.JSNumberOps._ + import Utils.toUint if (x == y) 0 - else if (x.toUint > y.toUint) 1 + else if (toUint(x) > toUint(y)) 1 else -1 } @@ -221,15 +219,13 @@ object Integer { (((t2 + (t2 >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24 } - @inline def divideUnsigned(dividend: Int, divisor: Int): Int = { - import js.JSNumberOps._ - asInt(dividend.toUint / divisor.toUint) - } + @inline def divideUnsigned(dividend: Int, divisor: Int): Int = + if (divisor == 0) 0 / 0 + else asInt(asUint(dividend) / asUint(divisor)) - @inline def remainderUnsigned(dividend: Int, divisor: Int): Int = { - import js.JSNumberOps._ - asInt(dividend.toUint % divisor.toUint) - } + @inline def remainderUnsigned(dividend: Int, divisor: Int): Int = + if (divisor == 0) 0 % 0 + else asInt(asUint(dividend) % asUint(divisor)) @inline def highestOneBit(i: Int): Int = { /* The natural way of implementing this is: @@ -276,19 +272,27 @@ object Integer { @inline def signum(i: scala.Int): scala.Int = if (i == 0) 0 else if (i < 0) -1 else 1 - // Intrinsic - def numberOfLeadingZeros(i: scala.Int): scala.Int = { - // See Hacker's Delight, Section 5-3 - var x = i - if (x == 0) { - 32 + @inline def numberOfLeadingZeros(i: scala.Int): scala.Int = { + if (linkingInfo.esVersion >= ESVersion.ES2015) js.Math.clz32(i) + else clz32Dynamic(i) + } + + private def clz32Dynamic(i: scala.Int) = { + if (js.typeOf(js.Dynamic.global.Math.clz32) == "function") { + js.Math.clz32(i) } else { - var r = 1 - if ((x & 0xffff0000) == 0) { x <<= 16; r += 16 } - if ((x & 0xff000000) == 0) { x <<= 8; r += 8 } - if ((x & 0xf0000000) == 0) { x <<= 4; r += 4 } - if ((x & 0xc0000000) == 0) { x <<= 2; r += 2 } - r + (x >> 31) + // See Hacker's Delight, Section 5-3 + var x = i + if (x == 0) { + 32 + } else { + var r = 1 + if ((x & 0xffff0000) == 0) { x <<= 16; r += 16 } + if ((x & 0xff000000) == 0) { x <<= 8; r += 8 } + if ((x & 0xf0000000) == 0) { x <<= 4; r += 4 } + if ((x & 0xc0000000) == 0) { x <<= 2; r += 2 } + r + (x >> 31) + } } } @@ -319,10 +323,17 @@ object Integer { @inline def min(a: Int, b: Int): Int = Math.min(a, b) @inline private[this] def toStringBase(i: scala.Int, base: scala.Int): String = { - import js.JSNumberOps._ - i.toUint.toString(base) + import js.JSNumberOps.enableJSNumberOps + asUint(i).toString(base) + } + + @inline private def asInt(n: scala.Double): scala.Int = { + import js.DynamicImplicits.number2dynamic + (n | 0).asInstanceOf[Int] } - @inline private def asInt(n: scala.Double): scala.Int = - (n.asInstanceOf[js.Dynamic] | 0.asInstanceOf[js.Dynamic]).asInstanceOf[Int] + @inline private def asUint(n: scala.Int): scala.Double = { + import js.DynamicImplicits.number2dynamic + (n.toDouble >>> 0).asInstanceOf[scala.Double] + } } diff --git a/javalanglib/src/main/scala/java/lang/Iterable.scala b/javalib/src/main/scala/java/lang/Iterable.scala similarity index 100% rename from javalanglib/src/main/scala/java/lang/Iterable.scala rename to javalib/src/main/scala/java/lang/Iterable.scala diff --git a/javalanglib/src/main/scala/java/lang/Long.scala b/javalib/src/main/scala/java/lang/Long.scala similarity index 91% rename from javalanglib/src/main/scala/java/lang/Long.scala rename to javalib/src/main/scala/java/lang/Long.scala index 4aca4b87f4..e6bf36ac1c 100644 --- a/javalanglib/src/main/scala/java/lang/Long.scala +++ b/javalib/src/main/scala/java/lang/Long.scala @@ -14,44 +14,50 @@ package java.lang import scala.annotation.{switch, tailrec} +import java.lang.constant.{Constable, ConstantDesc} + import scala.scalajs.js /* This is a hijacked class. Its instances are the representation of scala.Longs. * Constructors are not emitted. */ -final class Long private () extends Number with Comparable[Long] { +final class Long private () + extends Number with Comparable[Long] with Constable with ConstantDesc { + def this(value: scala.Long) = this() def this(s: String) = this() @inline def longValue(): scala.Long = this.asInstanceOf[scala.Long] - @inline override def byteValue(): scala.Byte = longValue.toByte - @inline override def shortValue(): scala.Short = longValue.toShort - @inline def intValue(): scala.Int = longValue.toInt - @inline def floatValue(): scala.Float = longValue.toFloat - @inline def doubleValue(): scala.Double = longValue.toDouble + @inline override def byteValue(): scala.Byte = longValue().toByte + @inline override def shortValue(): scala.Short = longValue().toShort + @inline def intValue(): scala.Int = longValue().toInt + @inline def floatValue(): scala.Float = longValue().toFloat + @inline def doubleValue(): scala.Double = longValue().toDouble @inline override def equals(that: Any): scala.Boolean = that match { - case that: Long => longValue == that.longValue + case that: Long => longValue() == that.longValue() case _ => false } @inline override def hashCode(): Int = - Long.hashCode(longValue) + Long.hashCode(longValue()) @inline override def compareTo(that: Long): Int = - Long.compare(longValue, that.longValue) + Long.compare(longValue(), that.longValue()) @inline override def toString(): String = - Long.toString(longValue) + Long.toString(longValue()) } object Long { - import scala.scalajs.runtime.RuntimeLong + /* TYPE should be a `final val`, but that crashes the JVM back-end, so we + * use a 'def' instead, which is binary compatible. + */ + def TYPE: Class[_] = scala.Predef.classOf[scala.Long] - final val TYPE = scala.Predef.classOf[scala.Long] final val MIN_VALUE = -9223372036854775808L final val MAX_VALUE = 9223372036854775807L final val SIZE = 64 @@ -71,7 +77,7 @@ object Long { var radix = 0 while (radix < Character.MIN_RADIX) { - r += null + r.push(null) radix += 1 } @@ -96,8 +102,8 @@ object Long { } val radixPowLengthLong = radixPowLength.toLong val overflowBarrier = Long.divideUnsigned(-1L, radixPowLengthLong) - r += new StringRadixInfo(chunkLength, radixPowLengthLong, - paddingZeros, overflowBarrier) + r.push(new StringRadixInfo(chunkLength, radixPowLengthLong, + paddingZeros, overflowBarrier)) radix += 1 } @@ -127,8 +133,7 @@ object Long { } // Intrinsic - @inline def toString(i: scala.Long): String = - toStringImpl(i, 10) + @inline def toString(i: scala.Long): String = "" + i @inline def toUnsignedString(i: scala.Long): String = toUnsignedStringImpl(i, 10) @@ -152,8 +157,8 @@ object Long { private def toUnsignedStringImpl(i: scala.Long, radix: Int): String = { if ((i >>> 32).toInt == 0) { // It's an unsigned int32 - import js.JSNumberOps._ - i.toInt.toUint.toString(radix) + import js.JSNumberOps.enableJSNumberOps + Utils.toUint(i.toInt).toString(radix) } else { toUnsignedStringInternalLarge(i, radix) } @@ -161,8 +166,8 @@ object Long { // Must be called only with valid radix private def toUnsignedStringInternalLarge(i: scala.Long, radix: Int): String = { - import js.JSNumberOps._ - import js.JSStringOps._ + import js.JSNumberOps.enableJSNumberOps + import js.JSStringOps.enableJSStringOps val radixInfo = StringRadixInfos(radix) val divisor = radixInfo.radixPowLength @@ -315,7 +320,12 @@ object Long { private def parseLongError(s: String): Nothing = throw new NumberFormatException(s"""For input string: "$s"""") - @inline def valueOf(longValue: scala.Long): Long = new Long(longValue) + @inline def `new`(value: scala.Long): Long = valueOf(value) + + @inline def `new`(s: String): Long = valueOf(s) + + @inline def valueOf(l: scala.Long): Long = l.asInstanceOf[Long] + @inline def valueOf(s: String): Long = valueOf(parseLong(s)) @inline def valueOf(s: String, radix: Int): Long = diff --git a/javalanglib/src/main/scala/java/lang/Math.scala b/javalib/src/main/scala/java/lang/Math.scala similarity index 91% rename from javalanglib/src/main/scala/java/lang/Math.scala rename to javalib/src/main/scala/java/lang/Math.scala index df510cee73..eebe0d67e4 100644 --- a/javalanglib/src/main/scala/java/lang/Math.scala +++ b/javalib/src/main/scala/java/lang/Math.scala @@ -16,12 +16,16 @@ package lang import scala.scalajs.js import js.Dynamic.{ global => g } -import scala.scalajs.LinkingInfo.assumingES6 +import scala.scalajs.runtime.linkingInfo +import scala.scalajs.LinkingInfo.ESVersion object Math { final val E = 2.718281828459045 final val PI = 3.141592653589793 + @inline private def assumingES6: scala.Boolean = + linkingInfo.esVersion >= ESVersion.ES2015 + @inline def abs(a: scala.Int): scala.Int = if (a < 0) -a else a @inline def abs(a: scala.Long): scala.Long = if (a < 0) -a else a @inline def abs(a: scala.Float): scala.Float = js.Math.abs(a).toFloat @@ -63,14 +67,14 @@ object Math { @inline def log(a: scala.Double): scala.Double = js.Math.log(a) @inline def log10(a: scala.Double): scala.Double = { - if (assumingES6 || !js.isUndefined(g.Math.log10)) + if (assumingES6 || !Utils.isUndefined(g.Math.log10)) js.Math.log10(a) else log(a) / 2.302585092994046 } @inline def log1p(a: scala.Double): scala.Double = { - if (assumingES6 || !js.isUndefined(g.Math.log1p)) + if (assumingES6 || !Utils.isUndefined(g.Math.log1p)) js.Math.log1p(a) else if (a == 0.0) a else log(a + 1) @@ -102,7 +106,7 @@ object Math { } def cbrt(a: scala.Double): scala.Double = { - if (assumingES6 || !js.isUndefined(g.Math.cbrt)) { + if (assumingES6 || !Utils.isUndefined(g.Math.cbrt)) { js.Math.cbrt(a) } else { if (a == 0 || Double.isNaN(a) || Double.isInfinite(a)) { @@ -198,16 +202,27 @@ object Math { } def ulp(a: scala.Double): scala.Double = { - if (abs(a) == scala.Double.PositiveInfinity) + val absa = abs(a) + if (absa == scala.Double.PositiveInfinity) scala.Double.PositiveInfinity - else if (abs(a) == scala.Double.MaxValue) - pow(2, 971) + else if (absa == scala.Double.MaxValue) + 1.9958403095347198e292 + else + nextUp(absa) - absa // this case handles NaN as well + } + + def ulp(a: scala.Float): scala.Float = { + val absa = abs(a) + if (absa == scala.Float.PositiveInfinity) + scala.Float.PositiveInfinity + else if (absa == scala.Float.MaxValue) + 2.028241e31f else - nextAfter(abs(a), scala.Double.MaxValue) - a + nextUp(absa) - absa // this case handles NaN as well } def hypot(a: scala.Double, b: scala.Double): scala.Double = { - if (assumingES6 || !js.isUndefined(g.Math.hypot)) { + if (assumingES6 || !Utils.isUndefined(g.Math.hypot)) { js.Math.hypot(a, b) } else { // http://en.wikipedia.org/wiki/Hypot#Implementation @@ -230,7 +245,7 @@ object Math { } def expm1(a: scala.Double): scala.Double = { - if (assumingES6 || !js.isUndefined(g.Math.expm1)) { + if (assumingES6 || !Utils.isUndefined(g.Math.expm1)) { js.Math.expm1(a) } else { // https://github.com/ghewgill/picomath/blob/master/javascript/expm1.js @@ -246,7 +261,7 @@ object Math { } def sinh(a: scala.Double): scala.Double = { - if (assumingES6 || !js.isUndefined(g.Math.sinh)) { + if (assumingES6 || !Utils.isUndefined(g.Math.sinh)) { js.Math.sinh(a) } else { if (Double.isNaN(a) || a == 0.0 || abs(a) == scala.Double.PositiveInfinity) a @@ -255,7 +270,7 @@ object Math { } def cosh(a: scala.Double): scala.Double = { - if (assumingES6 || !js.isUndefined(g.Math.cosh)) { + if (assumingES6 || !Utils.isUndefined(g.Math.cosh)) { js.Math.cosh(a) } else { if (Double.isNaN(a)) @@ -270,7 +285,7 @@ object Math { } def tanh(a: scala.Double): scala.Double = { - if (assumingES6 || !js.isUndefined(g.Math.tanh)) { + if (assumingES6 || !Utils.isUndefined(g.Math.tanh)) { js.Math.tanh(a) } else { if (Double.isNaN(a) || a == 0.0) @@ -417,7 +432,6 @@ object Math { // TODO // def IEEEremainder(f1: scala.Double, f2: scala.Double): Double - // def ulp(a: scala.Float): scala.Float // def copySign(magnitude: scala.Double, sign: scala.Double): scala.Double // def copySign(magnitude: scala.Float, sign: scala.Float): scala.Float // def getExponent(a: scala.Float): scala.Int diff --git a/javalanglib/src/main/scala/java/lang/Number.scala b/javalib/src/main/scala/java/lang/Number.scala similarity index 83% rename from javalanglib/src/main/scala/java/lang/Number.scala rename to javalib/src/main/scala/java/lang/Number.scala index 757c04673d..70d97efc81 100644 --- a/javalanglib/src/main/scala/java/lang/Number.scala +++ b/javalib/src/main/scala/java/lang/Number.scala @@ -15,8 +15,8 @@ package java.lang import scala.scalajs.js abstract class Number extends Object with java.io.Serializable { - def byteValue(): scala.Byte = intValue.toByte - def shortValue(): scala.Short = intValue.toShort + def byteValue(): scala.Byte = intValue().toByte + def shortValue(): scala.Short = intValue().toShort def intValue(): scala.Int def longValue(): scala.Long def floatValue(): scala.Float diff --git a/javalanglib/src/main/scala/java/lang/Readable.scala b/javalib/src/main/scala/java/lang/Readable.scala similarity index 100% rename from javalanglib/src/main/scala/java/lang/Readable.scala rename to javalib/src/main/scala/java/lang/Readable.scala diff --git a/javalanglib/src/main/scala/java/lang/Runnable.scala b/javalib/src/main/scala/java/lang/Runnable.scala similarity index 100% rename from javalanglib/src/main/scala/java/lang/Runnable.scala rename to javalib/src/main/scala/java/lang/Runnable.scala diff --git a/javalib/src/main/scala/java/lang/Runtime.scala b/javalib/src/main/scala/java/lang/Runtime.scala new file mode 100644 index 0000000000..cad1798d08 --- /dev/null +++ b/javalib/src/main/scala/java/lang/Runtime.scala @@ -0,0 +1,43 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.lang + +import scala.scalajs.js + +class Runtime private { + //def exit(status: Int): Unit + //def addShutdownHook(hook: Thread): Unit + //def removeShutdownHook(hook: Thread): Unit + //def halt(status: Int): Unit + def availableProcessors(): Int = 1 + //def freeMemory(): scala.Long + //def totalMemory(): scala.Long + //def maxMemory(): scala.Long + + def gc(): Unit = { + // Ignore + } + + //def runFinalization(): Unit + //def traceInstructions(on: scala.Boolean): Unit + //def traceMethodCalls(on: scala.Boolean): Unit + + //def load(filename: String): Unit + //def loadLibrary(filename: String): Unit +} + +object Runtime { + private val currentRuntime = new Runtime + + def getRuntime(): Runtime = currentRuntime +} diff --git a/javalib/src/main/scala/java/lang/Short.scala b/javalib/src/main/scala/java/lang/Short.scala new file mode 100644 index 0000000000..12149680ef --- /dev/null +++ b/javalib/src/main/scala/java/lang/Short.scala @@ -0,0 +1,107 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.lang + +import java.lang.constant.Constable + +/* This is a hijacked class. Its instances are primitive numbers. + * Constructors are not emitted. + */ +final class Short private () + extends Number with Comparable[Short] with Constable { + + def this(value: scala.Short) = this() + def this(s: String) = this() + + @inline override def shortValue(): scala.Short = + this.asInstanceOf[scala.Short] + + @inline override def byteValue(): scala.Byte = shortValue().toByte + @inline def intValue(): scala.Int = shortValue().toInt + @inline def longValue(): scala.Long = shortValue().toLong + @inline def floatValue(): scala.Float = shortValue().toFloat + @inline def doubleValue(): scala.Double = shortValue().toDouble + + @inline override def equals(that: Any): scala.Boolean = + this eq that.asInstanceOf[AnyRef] + + @inline override def hashCode(): Int = + shortValue() + + @inline override def compareTo(that: Short): Int = + Short.compare(shortValue(), that.shortValue()) + + @inline override def toString(): String = + Short.toString(shortValue()) + +} + +object Short { + /* TYPE should be a `final val`, but that crashes the JVM back-end, so we + * use a 'def' instead, which is binary compatible. + */ + def TYPE: Class[_] = scala.Predef.classOf[scala.Short] + + final val SIZE = 16 + final val BYTES = 2 + + /* MIN_VALUE and MAX_VALUE should be 'final val's. But it is impossible to + * write a proper Short literal in Scala, that would both considered a Short + * and a constant expression (optimized as final val). + * Since vals and defs are binary-compatible (although they're not strictly + * speaking source-compatible, because of stability), we implement them as + * defs. Source-compatibility is not an issue because user code is compiled + * against the JDK .class files anyway. + */ + def MIN_VALUE: scala.Short = -32768 + def MAX_VALUE: scala.Short = 32767 + + @inline def `new`(value: scala.Short): Short = valueOf(value) + + @inline def `new`(s: String): Short = valueOf(s) + + @inline def valueOf(s: scala.Short): Short = s.asInstanceOf[Short] + + @inline def valueOf(s: String): Short = valueOf(parseShort(s)) + + @inline def valueOf(s: String, radix: Int): Short = + valueOf(parseShort(s, radix)) + + @inline def parseShort(s: String): scala.Short = parseShort(s, 10) + + def parseShort(s: String, radix: Int): scala.Short = { + val r = Integer.parseInt(s, radix) + if (r < MIN_VALUE || r > MAX_VALUE) + throw new NumberFormatException(s"""For input string: "$s"""") + else + r.toShort + } + + @inline def toString(s: scala.Short): String = + "" + s + + @noinline def decode(nm: String): Short = + Integer.decodeGeneric(nm, valueOf(_, _)) + + @inline def compare(x: scala.Short, y: scala.Short): scala.Int = + x - y + + def reverseBytes(i: scala.Short): scala.Short = + (((i >>> 8) & 0xff) + ((i & 0xff) << 8)).toShort + + @inline def toUnsignedInt(x: scala.Short): scala.Int = + x.toInt & 0xffff + + @inline def toUnsignedLong(x: scala.Short): scala.Long = + toUnsignedInt(x).toLong +} diff --git a/javalib/src/main/scala/java/lang/StackTrace.scala b/javalib/src/main/scala/java/lang/StackTrace.scala new file mode 100644 index 0000000000..4dac37591c --- /dev/null +++ b/javalib/src/main/scala/java/lang/StackTrace.scala @@ -0,0 +1,478 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.lang + +import scala.annotation.tailrec + +import scala.scalajs.js +import scala.scalajs.js.JSStringOps.enableJSStringOps + +import Utils._ + +/** Conversions of JavaScript stack traces to Java stack traces. + */ +private[lang] object StackTrace { + + /* !!! Note that in this unit, we go to great lengths *not* to use anything + * from the collections library, and in general to use as little non-JS APIs + * as possible. + * + * This minimizes the risk of run-time errors during the process of decoding + * errors, which would be very bad if it happened. + */ + + /** Returns the current stack trace. + * + * If the stack trace cannot be analyzed in a meaningful way (normally, + * only in case we don't know the engine's format for stack traces), an + * empty array is returned. + */ + def getCurrentStackTrace(): Array[StackTraceElement] = + extract(new js.Error()) + + /** Captures a JavaScript error object recording the stack trace of the given + * `Throwable`. + * + * The state is stored as a magic field of the throwable, and will be used + * by `extract()` to create an Array[StackTraceElement]. + */ + @inline def captureJSError(throwable: Throwable): Any = { + val reference = js.special.unwrapFromThrowable(throwable) + val identifyingString: Any = { + js.constructorOf[js.Object].prototype + .selectDynamic("toString") + .call(reference.asInstanceOf[js.Any]) + } + if ("[object Error]" == identifyingString) { + /* The `reference` has an `[[ErrorData]]` internal slot, which is as good + * a guarantee as any that it contains stack trace data itself. In + * practice, this happens when we emit ES 2015 classes, and no other + * compiler down the line has compiled them away as ES 5.1 functions and + * prototypes. + */ + reference + } else if (js.constructorOf[js.Error].captureStackTrace eq ().asInstanceOf[AnyRef]) { + // Create a JS Error with the current stack trace. + new js.Error() + } else { + /* V8-specific. + * + * The `Error.captureStackTrace(e)` method records the current stack + * trace on `e` as would do `new Error()`, thereby turning `e` into a + * proper exception. This avoids creating a dummy exception, but is + * mostly important so that Node.js will show stack traces if the + * exception is never caught and reaches the global event queue. + * + * We use the `throwable` itself instead of the `reference` in this case, + * since the latter is not under our control, and could even be a + * primitive value which cannot be passed to `captureStackTrace`. + */ + js.constructorOf[js.Error].captureStackTrace(throwable.asInstanceOf[js.Any]) + throwable + } + } + + /** Extracts a stack trace from a JavaScript error object. + * If the provided error is not a JavaScript object, or if its stack data + * otherwise cannot be analyzed in a meaningful way (normally, only in case + * we don't know the engine's format for stack traces), an empty array is + * returned. + */ + def extract(jsError: Any): Array[StackTraceElement] = { + val lines = normalizeStackTraceLines(jsError.asInstanceOf[js.Dynamic]) + normalizedLinesToStackTrace(lines) + } + + /* Converts an array of frame entries in normalized form to a stack trace. + * Each line must have either the format + * @:: + * or + * @: + * For some reason, on some browsers, we sometimes have empty lines too. + * In the rest of the function, we convert the non-empty lines into + * StackTraceElements. + */ + private def normalizedLinesToStackTrace( + lines: js.Array[String]): Array[StackTraceElement] = { + + val NormalizedFrameLine = """^([^@]*)@(.*?):([0-9]+)(?::([0-9]+))?$""".re + + @inline def parseInt(s: String): Int = + js.Dynamic.global.parseInt(s).asInstanceOf[Int] + + val trace = js.Array[StackTraceElement]() + var i = 0 + while (i < lines.length) { + val line = lines(i) + if (!line.isEmpty) { + val mtch = NormalizedFrameLine.exec(line) + if (mtch ne null) { + val classAndMethodName = + extractClassMethod(undefOrForceGet(mtch(1))) + trace.push(new StackTraceElement(classAndMethodName(0), + classAndMethodName(1), undefOrForceGet(mtch(2)), + parseInt(undefOrForceGet(mtch(3))), + undefOrFold(mtch(4))(-1)(parseInt(_)))) + } else { + // just in case + // (explicitly use the constructor with column number so that STE has an inlineable init) + trace.push(new StackTraceElement("", line, null, -1, -1)) + } + } + i += 1 + } + + // Convert the JS array into a Scala array + val len = trace.length + val result = new Array[StackTraceElement](len) + i = 0 + while (i < len) { + result(i) = trace(i) + i += 1 + } + + result + } + + /** Tries and extract the class name and method from the JS function name. + * + * The recognized patterns are + * {{{ + * new \$c_ + * \$c_.prototype. + * \$b_.prototype. + * \$c_. + * \$b_. + * \$s___ + * \$f___ + * \$m_ + * }}} + * all of them optionally prefixed by `Object.`, `[object Object].` or + * `Module.`. (it comes after the "new " for the patterns where it start with + * a "new ") + * + * When the function name is none of those, the pair + * `("", functionName)` + * is returned, which will instruct [[StackTraceElement.toString()]] to only + * display the function name. + * + * @return + * A 2-element array with the recovered class and method names, in that + * order. It is an array instead of a tuple because tuples have user code + * in the Scala.js standard library, which we cannot reference from the + * javalanglib. + */ + private def extractClassMethod(functionName: String): js.Array[String] = { + val PatBC = """^(?:Object\.|\[object Object\]\.|Module\.)?\$[bc]_([^\.]+)(?:\.prototype)?\.([^\.]+)$""".re + val PatS = """^(?:Object\.|\[object Object\]\.|Module\.)?\$(?:ps?|s|f)_((?:_[^_]|[^_])+)__([^\.]+)$""".re + val PatCT = """^(?:Object\.|\[object Object\]\.|Module\.)?\$ct_((?:_[^_]|[^_])+)__([^\.]*)$""".re + val PatN = """^new (?:Object\.|\[object Object\]\.|Module\.)?\$c_([^\.]+)$""".re + val PatM = """^(?:Object\.|\[object Object\]\.|Module\.)?\$m_([^\.]+)$""".re + + val matchBC = PatBC.exec(functionName) + val matchBCOrS = if (matchBC ne null) matchBC else PatS.exec(functionName) + if (matchBCOrS ne null) { + js.Array[String](decodeClassName(undefOrForceGet(matchBCOrS(1))), + decodeMethodName(undefOrForceGet(matchBCOrS(2)))) + } else { + val matchCT = PatCT.exec(functionName) + val matchCTOrN = if (matchCT ne null) matchCT else PatN.exec(functionName) + if (matchCTOrN ne null) { + js.Array[String](decodeClassName(undefOrForceGet(matchCTOrN(1))), "") + } else { + val matchM = PatM.exec(functionName) + if (matchM ne null) { + js.Array[String](decodeClassName(undefOrForceGet(matchM(1))), "") + } else { + js.Array[String]("", functionName) + } + } + } + } + + // decodeClassName ----------------------------------------------------------- + + private def decodeClassName(encodedName: String): String = { + val base = if (dictContains(decompressedClasses, encodedName)) { + dictRawApply(decompressedClasses, encodedName) + } else { + @tailrec + def loop(i: Int): String = { + if (i < compressedPrefixes.length) { + val prefix = compressedPrefixes(i) + if (encodedName.startsWith(prefix)) + dictRawApply(decompressedPrefixes, prefix) + encodedName.jsSubstring(prefix.length) + else + loop(i+1) + } else { + // no prefix matches + if (encodedName.startsWith("L")) encodedName.jsSubstring(1) + else encodedName // just in case + } + } + loop(0) + } + base.replace("_", ".").replace("\uff3f", "_") + } + + private lazy val decompressedClasses: js.Dictionary[String] = { + val dict = new js.Object().asInstanceOf[js.Dictionary[String]] + dictSet(dict, "O", "java_lang_Object") + dictSet(dict, "T", "java_lang_String") + + var index = 0 + while (index <= 22) { + if (index >= 2) + dictSet(dict, s"T$index", s"scala_Tuple$index") + dictSet(dict, s"F$index", s"scala_Function$index") + index += 1 + } + + dict + } + + private lazy val decompressedPrefixes: js.Dictionary[String] = { + val dict = new js.Object().asInstanceOf[js.Dictionary[String]] + dictSet(dict, "sjsr_", "scala_scalajs_runtime_") + dictSet(dict, "sjs_", "scala_scalajs_") + dictSet(dict, "sci_", "scala_collection_immutable_") + dictSet(dict, "scm_", "scala_collection_mutable_") + dictSet(dict, "scg_", "scala_collection_generic_") + dictSet(dict, "sc_", "scala_collection_") + dictSet(dict, "sr_", "scala_runtime_") + dictSet(dict, "s_", "scala_") + dictSet(dict, "jl_", "java_lang_") + dictSet(dict, "ju_", "java_util_") + dict + } + + private lazy val compressedPrefixes = + js.Object.keys(decompressedPrefixes.asInstanceOf[js.Object]) + + // end of decodeClassName ---------------------------------------------------- + + private def decodeMethodName(encodedName: String): String = { + if (encodedName startsWith "init___") { + "" + } else { + val methodNameLen = encodedName.indexOf("__") + if (methodNameLen < 0) encodedName + else encodedName.jsSubstring(0, methodNameLen) + } + } + + private implicit class StringRE(private val s: String) extends AnyVal { + def re: js.RegExp = new js.RegExp(s) + def re(mods: String): js.RegExp = new js.RegExp(s, mods) + } + + /* --------------------------------------------------------------------------- + * Start copy-paste-translate from stacktrace.js + * + * From here on, most of the code has been copied from + * https://github.com/stacktracejs/stacktrace.js + * and translated to Scala.js almost literally, with some adaptations. + * + * Most comments -and lack thereof- have also been copied therefrom. + */ + + private def normalizeStackTraceLines(e: js.Dynamic): js.Array[String] = { + import js.DynamicImplicits.{truthValue, number2dynamic} + + /* You would think that we could test once and for all which "mode" to + * adopt. But the format can actually differ for different exceptions + * on some browsers, e.g., exceptions in Chrome there may or may not have + * arguments or stack. + */ + + if (!e) { + js.Array[String]() + } else if (e.arguments && e.stack) { + extractChrome(e) + } else if (e.stack && e.sourceURL) { + extractSafari(e) + } else if (e.stack && e.number) { + extractIE(e) + } else if (e.stack && e.fileName) { + extractFirefox(e) + } else if (e.message && e.`opera#sourceloc`) { + // e.message.indexOf("Backtrace:") > -1 -> opera9 + // 'opera#sourceloc' in e -> opera9, opera10a + // !e.stacktrace -> opera9 + @inline def messageIsLongerThanStacktrace = + e.message.split("\n").length > e.stacktrace.split("\n").length + if (!e.stacktrace) { + extractOpera9(e) // use e.message + } else if ((e.message.indexOf("\n") > -1) && messageIsLongerThanStacktrace) { + // e.message may have more stack entries than e.stacktrace + extractOpera9(e) // use e.message + } else { + extractOpera10a(e) // use e.stacktrace + } + } else if (e.message && e.stack && e.stacktrace) { + // stacktrace && stack -> opera10b + if (e.stacktrace.indexOf("called from line") < 0) { + extractOpera10b(e) + } else { + extractOpera11(e) + } + } else if (e.stack && !e.fileName) { + /* Chrome 27 does not have e.arguments as earlier versions, + * but still does not have e.fileName as Firefox */ + extractChrome(e) + } else { + extractOther(e) + } + } + + private def extractChrome(e: js.Dynamic): js.Array[String] = { + (e.stack.asInstanceOf[String] + "\n") + .jsReplace("""^[\s\S]+?\s+at\s+""".re, " at ") // remove message + .jsReplace("""^\s+(at eval )?at\s+""".re("gm"), "") // remove 'at' and indentation + .jsReplace("""^([^\(]+?)([\n])""".re("gm"), "{anonymous}() ($1)$2") // see note + .jsReplace("""^Object.\s*\(([^\)]+)\)""".re("gm"), "{anonymous}() ($1)") + .jsReplace("""^([^\(]+|\{anonymous\}\(\)) \((.+)\)$""".re("gm"), "$1@$2") + .jsSplit("\n") + .jsSlice(0, -1) + + /* Note: there was a $ next to the \n here in the original code, but it + * chokes with method names with $'s, which are generated often by Scala.js. + */ + } + + private def extractFirefox(e: js.Dynamic): js.Array[String] = { + (e.stack.asInstanceOf[String]) + .jsReplace("""(?:\n@:0)?\s+$""".re("m"), "") + .jsReplace("""^(?:\((\S*)\))?@""".re("gm"), "{anonymous}($1)@") + .jsSplit("\n") + } + + private def extractIE(e: js.Dynamic): js.Array[String] = { + (e.stack.asInstanceOf[String]) + .jsReplace("""^\s*at\s+(.*)$""".re("gm"), "$1") + .jsReplace("""^Anonymous function\s+""".re("gm"), "{anonymous}() ") + .jsReplace("""^([^\(]+|\{anonymous\}\(\))\s+\((.+)\)$""".re("gm"), "$1@$2") + .jsSplit("\n") + .jsSlice(1) + } + + private def extractSafari(e: js.Dynamic): js.Array[String] = { + (e.stack.asInstanceOf[String]) + .jsReplace("""\[native code\]\n""".re("m"), "") + .jsReplace("""^(?=\w+Error\:).*$\n""".re("m"), "") + .jsReplace("""^@""".re("gm"), "{anonymous}()@") + .jsSplit("\n") + } + + private def extractOpera9(e: js.Dynamic): js.Array[String] = { + // " Line 43 of linked script file://localhost/G:/js/stacktrace.js\n" + // " Line 7 of inline#1 script in file://localhost/G:/js/test/functional/testcase1.html\n" + val lineRE = """Line (\d+).*script (?:in )?(\S+)""".re("i") + val lines = (e.message.asInstanceOf[String]).jsSplit("\n") + val result = new js.Array[String] + + var i = 2 + val len = lines.length + while (i < len) { + val mtch = lineRE.exec(lines(i)) + if (mtch ne null) { + result.push( + "{anonymous}()@" + undefOrForceGet(mtch(2)) + ":" + + undefOrForceGet(mtch(1)) + /* + " -- " + lines(i+1).replace("""^\s+""".re, "") */) + } + i += 2 + } + + result + } + + private def extractOpera10a(e: js.Dynamic): js.Array[String] = { + // " Line 27 of linked script file://localhost/G:/js/stacktrace.js\n" + // " Line 11 of inline#1 script in file://localhost/G:/js/test/functional/testcase1.html: In function foo\n" + val lineRE = """Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$""".re("i") + val lines = (e.stacktrace.asInstanceOf[String]).jsSplit("\n") + val result = new js.Array[String] + + var i = 0 + val len = lines.length + while (i < len) { + val mtch = lineRE.exec(lines(i)) + if (mtch ne null) { + val fnName = undefOrGetOrElse(mtch(3))("{anonymous}") + result.push( + fnName + "()@" + undefOrForceGet(mtch(2)) + ":" + + undefOrForceGet(mtch(1)) + /* + " -- " + lines(i+1).replace("""^\s+""".re, "")*/) + } + i += 2 + } + + result + } + + private def extractOpera10b(e: js.Dynamic): js.Array[String] = { + // "([arguments not available])@file://localhost/G:/js/stacktrace.js:27\n" + + // "printStackTrace([arguments not available])@file://localhost/G:/js/stacktrace.js:18\n" + + // "@file://localhost/G:/js/test/functional/testcase1.html:15" + val lineRE = """^(.*)@(.+):(\d+)$""".re + val lines = (e.stacktrace.asInstanceOf[String]).jsSplit("\n") + val result = new js.Array[String] + + var i = 0 + val len = lines.length + while (i < len) { + val mtch = lineRE.exec(lines(i)) + if (mtch ne null) { + val fnName = undefOrFold(mtch(1))("global code")(_ + "()") + result.push(fnName + "@" + undefOrForceGet(mtch(2)) + ":" + undefOrForceGet(mtch(3))) + } + i += 1 + } + + result + } + + private def extractOpera11(e: js.Dynamic): js.Array[String] = { + val lineRE = """^.*line (\d+), column (\d+)(?: in (.+))? in (\S+):$""".re + val lines = (e.stacktrace.asInstanceOf[String]).jsSplit("\n") + val result = new js.Array[String] + + var i = 0 + val len = lines.length + while (i < len) { + val mtch = lineRE.exec(lines(i)) + if (mtch ne null) { + val location = undefOrForceGet(mtch(4)) + ":" + undefOrForceGet(mtch(1)) + ":" + undefOrForceGet(mtch(2)) + val fnName0 = undefOrGetOrElse(mtch(2))("global code") + val fnName = fnName0 + .jsReplace("""""".re, "$1") + .jsReplace("""""".re, "{anonymous}") + result.push(fnName + "@" + location + /* + " -- " + lines(i+1).replace("""^\s+""".re, "")*/) + } + i += 2 + } + + result + } + + private def extractOther(e: js.Dynamic): js.Array[String] = { + js.Array() + } + + /* End copy-paste-translate from stacktrace.js + * --------------------------------------------------------------------------- + */ + +} diff --git a/javalib/src/main/scala/java/lang/StackTraceElement.scala b/javalib/src/main/scala/java/lang/StackTraceElement.scala new file mode 100644 index 0000000000..8795a1de82 --- /dev/null +++ b/javalib/src/main/scala/java/lang/StackTraceElement.scala @@ -0,0 +1,83 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.lang + +import scala.scalajs.js +import js.annotation.JSExport + +/* The primary constructor, taking a `columnNumber`, is not part of the JDK + * API. It is used internally in `java.lang.StackTrace`, and could be accessed + * by third-party libraries with a bit of IR manipulation. + */ +final class StackTraceElement(declaringClass: String, methodName: String, + fileName: String, lineNumber: Int, private[this] var columnNumber: Int) + extends AnyRef with java.io.Serializable { + + def this(declaringClass: String, methodName: String, fileName: String, lineNumber: Int) = + this(declaringClass, methodName, fileName, lineNumber, -1) + + def getFileName(): String = fileName + def getLineNumber(): Int = lineNumber + def getClassName(): String = declaringClass + def getMethodName(): String = methodName + def isNativeMethod(): scala.Boolean = false + + // Not part of the JDK API, accessible through reflection. + def getColumnNumber(): Int = columnNumber + + // Not part of the JDK API, accessible through reflection. + @deprecated("old internal API; use the constructor with a column number instead", "1.11.0") + def setColumnNumber(columnNumber: Int): Unit = + this.columnNumber = columnNumber + + override def equals(that: Any): scala.Boolean = that match { + case that: StackTraceElement => + (getFileName() == that.getFileName()) && + (getLineNumber() == that.getLineNumber()) && + (getColumnNumber() == that.getColumnNumber()) && + (getClassName() == that.getClassName()) && + (getMethodName() == that.getMethodName()) + case _ => + false + } + + override def toString(): String = { + var result = "" + if (declaringClass != "") + result += declaringClass + "." + result += methodName + if (fileName eq null) { + if (isNativeMethod()) + result += "(Native Method)" + else + result += "(Unknown Source)" + } else { + result += "(" + fileName + if (lineNumber >= 0) { + result += ":" + lineNumber + if (columnNumber >= 0) + result += ":" + columnNumber + } + result += ")" + } + result + } + + override def hashCode(): Int = { + declaringClass.hashCode() ^ + methodName.hashCode() ^ + fileName.hashCode() ^ + lineNumber ^ + columnNumber + } +} diff --git a/javalanglib/src/main/scala/java/lang/StringBuffer.scala b/javalib/src/main/scala/java/lang/StringBuffer.scala similarity index 100% rename from javalanglib/src/main/scala/java/lang/StringBuffer.scala rename to javalib/src/main/scala/java/lang/StringBuffer.scala diff --git a/javalanglib/src/main/scala/java/lang/StringBuilder.scala b/javalib/src/main/scala/java/lang/StringBuilder.scala similarity index 99% rename from javalanglib/src/main/scala/java/lang/StringBuilder.scala rename to javalib/src/main/scala/java/lang/StringBuilder.scala index 9623dac31d..580a463ced 100644 --- a/javalanglib/src/main/scala/java/lang/StringBuilder.scala +++ b/javalib/src/main/scala/java/lang/StringBuilder.scala @@ -66,7 +66,7 @@ class StringBuilder def append(d: scala.Double): StringBuilder = append(d.toString()) def appendCodePoint(codePoint: Int): StringBuilder = - append(Character.codePointToString(codePoint)) + append(Character.toString(codePoint)) def delete(start: Int, end: Int): StringBuilder = replace(start, end, "") diff --git a/javalib/src/main/scala/java/lang/System.scala b/javalib/src/main/scala/java/lang/System.scala new file mode 100644 index 0000000000..c7424a218a --- /dev/null +++ b/javalib/src/main/scala/java/lang/System.scala @@ -0,0 +1,405 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.lang + +import java.io._ + +import scala.scalajs.js +import scala.scalajs.js.Dynamic.global +import scala.scalajs.runtime.linkingInfo + +import java.{util => ju} + +object System { + /* System contains a bag of unrelated features. If we naively implement + * everything inside System, reaching any of these features can reach + * unrelated code. For example, using `nanoTime()` would reach + * `JSConsoleBasedPrintStream` and therefore a bunch of `java.io` classes. + * + * Instead, every feature that requires its own fields is extracted in a + * separate private object, and corresponding methods of System delegate to + * methods of that private object. + * + * All non-intrinsic methods are marked `@inline` so that the module accessor + * of `System` can always be completely elided. + */ + + // Standard streams (out, err, in) ------------------------------------------ + + private object Streams { + var out: PrintStream = new JSConsoleBasedPrintStream(isErr = false) + var err: PrintStream = new JSConsoleBasedPrintStream(isErr = true) + var in: InputStream = null + } + + @inline + def out: PrintStream = Streams.out + + @inline + def err: PrintStream = Streams.err + + @inline + def in: InputStream = Streams.in + + @inline + def setIn(in: InputStream): Unit = + Streams.in = in + + @inline + def setOut(out: PrintStream): Unit = + Streams.out = out + + @inline + def setErr(err: PrintStream): Unit = + Streams.err = err + + // System time -------------------------------------------------------------- + + @inline + def currentTimeMillis(): scala.Long = + (new js.Date).getTime().toLong + + private object NanoTime { + val getHighPrecisionTime: () => scala.Double = { + import js.DynamicImplicits.truthValue + + if (js.typeOf(global.performance) != "undefined") { + if (global.performance.now) { + () => global.performance.now().asInstanceOf[scala.Double] + } else if (global.performance.webkitNow) { + () => global.performance.webkitNow().asInstanceOf[scala.Double] + } else { + () => new js.Date().getTime() + } + } else { + () => new js.Date().getTime() + } + } + } + + @inline + def nanoTime(): scala.Long = + (NanoTime.getHighPrecisionTime() * 1000000).toLong + + // arraycopy ---------------------------------------------------------------- + + // Intrinsic + def arraycopy(src: Object, srcPos: scala.Int, dest: Object, + destPos: scala.Int, length: scala.Int): Unit = { + + import scala.{Boolean, Char, Byte, Short, Int, Long, Float, Double} + + def mismatch(): Nothing = + throw new ArrayStoreException("Incompatible array types") + + def impl(srcLen: Int, destLen: Int, f: (Int, Int) => Any): Unit = { + /* Perform dummy swaps to trigger an ArrayIndexOutOfBoundsException or + * UBE if the positions / lengths are bad. + */ + if (srcPos < 0 || destPos < 0) + f(destPos, srcPos) + if (length < 0) + f(length, length) + if (srcPos > srcLen - length || destPos > destLen - length) + f(destPos + length, srcPos + length) + + if ((src ne dest) || destPos < srcPos || srcPos + length < destPos) { + var i = 0 + while (i < length) { + f(i + destPos, i + srcPos) + i += 1 + } + } else { + var i = length - 1 + while (i >= 0) { + f(i + destPos, i + srcPos) + i -= 1 + } + } + } + + if (src == null || dest == null) { + throw new NullPointerException() + } else (src match { + case src: Array[AnyRef] => + dest match { + case dest: Array[AnyRef] => impl(src.length, dest.length, (i, j) => dest(i) = src(j)) + case _ => mismatch() + } + case src: Array[Boolean] => + dest match { + case dest: Array[Boolean] => impl(src.length, dest.length, (i, j) => dest(i) = src(j)) + case _ => mismatch() + } + case src: Array[Char] => + dest match { + case dest: Array[Char] => impl(src.length, dest.length, (i, j) => dest(i) = src(j)) + case _ => mismatch() + } + case src: Array[Byte] => + dest match { + case dest: Array[Byte] => impl(src.length, dest.length, (i, j) => dest(i) = src(j)) + case _ => mismatch() + } + case src: Array[Short] => + dest match { + case dest: Array[Short] => impl(src.length, dest.length, (i, j) => dest(i) = src(j)) + case _ => mismatch() + } + case src: Array[Int] => + dest match { + case dest: Array[Int] => impl(src.length, dest.length, (i, j) => dest(i) = src(j)) + case _ => mismatch() + } + case src: Array[Long] => + dest match { + case dest: Array[Long] => impl(src.length, dest.length, (i, j) => dest(i) = src(j)) + case _ => mismatch() + } + case src: Array[Float] => + dest match { + case dest: Array[Float] => impl(src.length, dest.length, (i, j) => dest(i) = src(j)) + case _ => mismatch() + } + case src: Array[Double] => + dest match { + case dest: Array[Double] => impl(src.length, dest.length, (i, j) => dest(i) = src(j)) + case _ => mismatch() + } + case _ => + mismatch() + }) + } + + @inline + def identityHashCode(x: Any): scala.Int = + scala.scalajs.runtime.identityHashCode(x.asInstanceOf[AnyRef]) + + // System properties -------------------------------------------------------- + + private object SystemProperties { + import Utils._ + + private[this] var dict: js.Dictionary[String] = loadSystemProperties() + private[this] var properties: ju.Properties = null + + private def loadSystemProperties(): js.Dictionary[String] = { + val result = new js.Object().asInstanceOf[js.Dictionary[String]] + dictSet(result, "java.version", "1.8") + dictSet(result, "java.vm.specification.version", "1.8") + dictSet(result, "java.vm.specification.vendor", "Oracle Corporation") + dictSet(result, "java.vm.specification.name", "Java Virtual Machine Specification") + dictSet(result, "java.vm.name", "Scala.js") + dictSet(result, "java.vm.version", linkingInfo.linkerVersion) + dictSet(result, "java.specification.version", "1.8") + dictSet(result, "java.specification.vendor", "Oracle Corporation") + dictSet(result, "java.specification.name", "Java Platform API Specification") + dictSet(result, "file.separator", "/") + dictSet(result, "path.separator", ":") + dictSet(result, "line.separator", "\n") + result + } + + def getProperties(): ju.Properties = { + if (properties eq null) { + properties = new ju.Properties + val keys = js.Object.keys(dict.asInstanceOf[js.Object]) + forArrayElems(keys) { key => + properties.setProperty(key, dictRawApply(dict, key)) + } + dict = null + } + properties + } + + def setProperties(properties: ju.Properties): Unit = { + if (properties eq null) { + dict = loadSystemProperties() + this.properties = null + } else { + dict = null + this.properties = properties + } + } + + def getProperty(key: String): String = + if (dict ne null) dictGetOrElse(dict, key)(null) + else properties.getProperty(key) + + def getProperty(key: String, default: String): String = + if (dict ne null) dictGetOrElse(dict, key)(default) + else properties.getProperty(key, default) + + def clearProperty(key: String): String = + if (dict ne null) dictGetOrElseAndRemove(dict, key, null) + else properties.remove(key).asInstanceOf[String] + + def setProperty(key: String, value: String): String = { + if (dict ne null) { + val oldValue = getProperty(key) + dictSet(dict, key, value) + oldValue + } else { + properties.setProperty(key, value).asInstanceOf[String] + } + } + } + + @inline + def getProperties(): ju.Properties = + SystemProperties.getProperties() + + @inline + def lineSeparator(): String = "\n" + + @inline + def setProperties(properties: ju.Properties): Unit = + SystemProperties.setProperties(properties) + + @inline + def getProperty(key: String): String = + SystemProperties.getProperty(key) + + @inline + def getProperty(key: String, default: String): String = + SystemProperties.getProperty(key, default) + + @inline + def clearProperty(key: String): String = + SystemProperties.clearProperty(key) + + @inline + def setProperty(key: String, value: String): String = + SystemProperties.setProperty(key, value) + + // Environment variables ---------------------------------------------------- + + @inline + def getenv(): ju.Map[String, String] = + ju.Collections.emptyMap() + + @inline + def getenv(name: String): String = { + if (name eq null) + throw new NullPointerException + + null + } + + // Runtime ------------------------------------------------------------------ + + //def exit(status: scala.Int): Unit + + @inline + def gc(): Unit = Runtime.getRuntime().gc() +} + +private final class JSConsoleBasedPrintStream(isErr: scala.Boolean) + extends PrintStream(new JSConsoleBasedPrintStream.DummyOutputStream) { + + import JSConsoleBasedPrintStream._ + + /** Whether the buffer is flushed. + * This can be true even if buffer != "" because of line continuations. + * However, the converse is never true, i.e., !flushed => buffer != "". + */ + private var flushed: scala.Boolean = true + private var buffer: String = "" + + override def write(b: Int): Unit = + write(Array(b.toByte), 0, 1) + + override def write(buf: Array[scala.Byte], off: Int, len: Int): Unit = { + /* This does *not* decode buf as a sequence of UTF-8 code units. + * This is not really useful, and would uselessly pull in the UTF-8 decoder + * in all applications that use OutputStreams (not just PrintStreams). + * Instead, we use a trivial ISO-8859-1 decoder in here. + */ + if (off < 0 || len < 0 || len > buf.length - off) + throw new IndexOutOfBoundsException + + var i = 0 + while (i < len) { + print((buf(i + off) & 0xff).toChar) + i += 1 + } + } + + override def print(b: scala.Boolean): Unit = printString(String.valueOf(b)) + override def print(c: scala.Char): Unit = printString(String.valueOf(c)) + override def print(i: scala.Int): Unit = printString(String.valueOf(i)) + override def print(l: scala.Long): Unit = printString(String.valueOf(l)) + override def print(f: scala.Float): Unit = printString(String.valueOf(f)) + override def print(d: scala.Double): Unit = printString(String.valueOf(d)) + override def print(s: Array[scala.Char]): Unit = printString(String.valueOf(s)) + override def print(s: String): Unit = printString(if (s == null) "null" else s) + override def print(obj: AnyRef): Unit = printString(String.valueOf(obj)) + + override def println(): Unit = printString("\n") + + // This is the method invoked by Predef.println(x). + @inline + override def println(obj: AnyRef): Unit = printString(s"$obj\n") + + private def printString(s: String): Unit = { + var rest: String = s + while (rest != "") { + val nlPos = rest.indexOf("\n") + if (nlPos < 0) { + buffer += rest + flushed = false + rest = "" + } else { + doWriteLine(buffer + rest.substring(0, nlPos)) + buffer = "" + flushed = true + rest = rest.substring(nlPos+1) + } + } + } + + /** + * Since we cannot write a partial line in JavaScript, we write a whole + * line with continuation symbol at the end and schedule a line continuation + * symbol for the new line if the buffer is flushed. + */ + override def flush(): Unit = if (!flushed) { + doWriteLine(buffer + LineContEnd) + buffer = LineContStart + flushed = true + } + + override def close(): Unit = () + + private def doWriteLine(line: String): Unit = { + import js.DynamicImplicits.truthValue + + if (js.typeOf(global.console) != "undefined") { + if (isErr && global.console.error) + global.console.error(line) + else + global.console.log(line) + } + } +} + +private[lang] object JSConsoleBasedPrintStream { + private final val LineContEnd: String = "\u21A9" + private final val LineContStart: String = "\u21AA" + + class DummyOutputStream extends OutputStream { + def write(c: Int): Unit = + throw new AssertionError( + "Should not get in JSConsoleBasedPrintStream.DummyOutputStream") + } +} diff --git a/javalanglib/src/main/scala/java/lang/Thread.scala b/javalib/src/main/scala/java/lang/Thread.scala similarity index 89% rename from javalanglib/src/main/scala/java/lang/Thread.scala rename to javalib/src/main/scala/java/lang/Thread.scala index 750bbe8190..60de1c3e03 100644 --- a/javalanglib/src/main/scala/java/lang/Thread.scala +++ b/javalib/src/main/scala/java/lang/Thread.scala @@ -36,7 +36,7 @@ class Thread private (dummy: Unit) extends Runnable { this.name def getStackTrace(): Array[StackTraceElement] = - scala.scalajs.runtime.StackTrace.getCurrentStackTrace() + StackTrace.getCurrentStackTrace() def getId(): scala.Long = 1 } @@ -47,8 +47,8 @@ object Thread { def currentThread(): Thread = SingleThread def interrupted(): scala.Boolean = { - val ret = currentThread.isInterrupted - currentThread.interruptedState = false + val ret = currentThread().isInterrupted() + currentThread().interruptedState = false ret } } diff --git a/javalanglib/src/main/scala/java/lang/ThreadLocal.scala b/javalib/src/main/scala/java/lang/ThreadLocal.scala similarity index 96% rename from javalanglib/src/main/scala/java/lang/ThreadLocal.scala rename to javalib/src/main/scala/java/lang/ThreadLocal.scala index 11cbaeb627..a36be61a1b 100644 --- a/javalanglib/src/main/scala/java/lang/ThreadLocal.scala +++ b/javalib/src/main/scala/java/lang/ThreadLocal.scala @@ -20,7 +20,7 @@ class ThreadLocal[T] { def get(): T = { if (!hasValue) - set(initialValue) + set(initialValue()) v } diff --git a/javalanglib/src/main/scala/java/lang/Throwables.scala b/javalib/src/main/scala/java/lang/Throwables.scala similarity index 86% rename from javalanglib/src/main/scala/java/lang/Throwables.scala rename to javalib/src/main/scala/java/lang/Throwables.scala index 3b14418097..38b17384b9 100644 --- a/javalanglib/src/main/scala/java/lang/Throwables.scala +++ b/javalib/src/main/scala/java/lang/Throwables.scala @@ -13,6 +13,7 @@ package java.lang import scala.scalajs.js +import scala.scalajs.js.annotation.JSExport class Throwable protected (s: String, private var e: Throwable, enableSuppression: scala.Boolean, writableStackTrace: scala.Boolean) @@ -23,6 +24,7 @@ class Throwable protected (s: String, private var e: Throwable, def this(s: String) = this(s, null) def this(e: Throwable) = this(if (e == null) null else e.toString, e) + private[this] var jsErrorForStackTrace: Any = _ private[this] var stackTrace: Array[StackTraceElement] = _ /* We use an Array rather than, say, a List, so that Throwable does not @@ -43,14 +45,14 @@ class Throwable protected (s: String, private var e: Throwable, def getLocalizedMessage(): String = getMessage() def fillInStackTrace(): Throwable = { - scala.scalajs.runtime.StackTrace.captureState(this) + jsErrorForStackTrace = StackTrace.captureJSError(this) this } def getStackTrace(): Array[StackTraceElement] = { if (stackTrace eq null) { if (writableStackTrace) - stackTrace = scala.scalajs.runtime.StackTrace.extract(this) + stackTrace = StackTrace.extract(jsErrorForStackTrace) else stackTrace = new Array[StackTraceElement](0) } @@ -88,7 +90,7 @@ class Throwable protected (s: String, private var e: Throwable, if (stackTrace.length != 0) { var i = 0 while (i < stackTrace.length) { - sprintln(" at "+stackTrace(i)) + sprintln(s" at ${stackTrace(i)}") i += 1 } } else { @@ -97,15 +99,15 @@ class Throwable protected (s: String, private var e: Throwable, // Causes var wCause: Throwable = this - while ((wCause ne wCause.getCause) && (wCause.getCause ne null)) { - val parentTrace = wCause.getStackTrace - wCause = wCause.getCause - val thisTrace = wCause.getStackTrace + while ((wCause ne wCause.getCause()) && (wCause.getCause() ne null)) { + val parentTrace = wCause.getStackTrace() + wCause = wCause.getCause() + val thisTrace = wCause.getStackTrace() val thisLength = thisTrace.length val parentLength = parentTrace.length - sprintln("Caused by: " + wCause.toString) + sprintln(s"Caused by: $wCause") if (thisLength != 0) { /* Count how many frames are shared between this stack trace and the @@ -127,23 +129,27 @@ class Throwable protected (s: String, private var e: Throwable, val lengthToPrint = thisLength - sameFrameCount var i = 0 while (i < lengthToPrint) { - sprintln(" at "+thisTrace(i)) + sprintln(s" at ${thisTrace(i)}") i += 1 } if (sameFrameCount > 0) - sprintln(" ... " + sameFrameCount + " more") + sprintln(s" ... $sameFrameCount more") } else { sprintln(" ") } } } + /* Re-export toString() because Throwable will be disconnected from Object + * to extend js.Error instead, and exports are not transferred. + */ + @JSExport override def toString(): String = { - val className = getClass.getName + val className = getClass().getName() val message = getMessage() if (message eq null) className - else className + ": " + message + else s"$className: $message" } def addSuppressed(exception: Throwable): Unit = { @@ -171,6 +177,23 @@ class Throwable protected (s: String, private var e: Throwable, else suppressed.clone() } + + /* A JavaScript Error object should have a `name` property containing a + * string representation of the class of the error. + */ + @JSExport("name") + @inline + protected def js_name: String = getClass().getName() + + /* A JavaScript Error object should have a `message` property containing a + * string representation of the message associated with the error. + */ + @JSExport("message") + @inline + protected def js_message: String = { + val m = getMessage() + if (m eq null) "" else m + } } class ThreadDeath() extends Error() @@ -292,8 +315,15 @@ class VerifyError(s: String) extends LinkageError(s) { def this() = this(null) } -abstract class VirtualMachineError(s: String) extends Error(s) { - def this() = this(null) +abstract class VirtualMachineError(message: String, cause: Throwable) + extends Error(message, cause) { + + def this() = this(null, null) + + def this(message: String) = this(message, null) + + def this(cause: Throwable) = + this(if (cause == null) null else cause.toString, cause) } @@ -304,7 +334,7 @@ class ArithmeticException(s: String) extends RuntimeException(s) { } class ArrayIndexOutOfBoundsException(s: String) extends IndexOutOfBoundsException(s) { - def this(index: Int) = this("Array index out of range: " + index) + def this(index: Int) = this(s"Array index out of range: $index") def this() = this(null) } @@ -328,7 +358,7 @@ class CloneNotSupportedException(s: String) extends Exception(s) { } class EnumConstantNotPresentException(e: Class[_ <: Enum[_]], c: String) - extends RuntimeException(e.getName() + "." + c) { + extends RuntimeException(s"${e.getName()}.$c") { def enumType(): Class[_ <: Enum[_]] = e def constantName(): String = c } @@ -426,12 +456,12 @@ class SecurityException(s: String, e: Throwable) extends RuntimeException(s, e) } class StringIndexOutOfBoundsException(s: String) extends IndexOutOfBoundsException(s) { - def this(index: Int) = this("String index out of range: " + index) + def this(index: Int) = this(s"String index out of range: $index") def this() = this(null) } class TypeNotPresentException(t: String, e: Throwable) - extends RuntimeException("Type " + t + " not present", e) { + extends RuntimeException(s"Type $t not present", e) { def typeName(): String = t } diff --git a/javalib/src/main/scala/java/lang/Utils.scala b/javalib/src/main/scala/java/lang/Utils.scala new file mode 100644 index 0000000000..b57bc2a520 --- /dev/null +++ b/javalib/src/main/scala/java/lang/Utils.scala @@ -0,0 +1,193 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.lang + +import scala.language.implicitConversions + +import scala.scalajs.js +import scala.scalajs.js.annotation._ + +private[java] object Utils { + @inline + def undefined: js.UndefOr[Nothing] = ().asInstanceOf[js.UndefOr[Nothing]] + + @inline + def isUndefined(x: Any): scala.Boolean = + x.asInstanceOf[AnyRef] eq ().asInstanceOf[AnyRef] + + @inline + def undefOrIsDefined[A](x: js.UndefOr[A]): scala.Boolean = + x ne ().asInstanceOf[AnyRef] + + @inline + def undefOrForceGet[A](x: js.UndefOr[A]): A = + x.asInstanceOf[A] + + @inline + def undefOrGetOrElse[A](x: js.UndefOr[A])(default: => A): A = + if (undefOrIsDefined(x)) undefOrForceGet(x) + else default + + @inline + def undefOrGetOrNull[A >: Null](x: js.UndefOr[A]): A = + if (undefOrIsDefined(x)) undefOrForceGet(x) + else null + + @inline + def undefOrForeach[A](x: js.UndefOr[A])(f: A => Any): Unit = { + if (undefOrIsDefined(x)) + f(undefOrForceGet(x)) + } + + @inline + def undefOrFold[A, B](x: js.UndefOr[A])(default: => B)(f: A => B): B = + if (undefOrIsDefined(x)) f(undefOrForceGet(x)) + else default + + private object Cache { + val safeHasOwnProperty = + js.Dynamic.global.Object.prototype.hasOwnProperty + .asInstanceOf[js.ThisFunction1[js.Dictionary[_], String, scala.Boolean]] + } + + @inline + private def safeHasOwnProperty(dict: js.Dictionary[_], key: String): scala.Boolean = + Cache.safeHasOwnProperty(dict, key) + + @js.native + private trait DictionaryRawApply[A] extends js.Object { + /** Reads a field of this object by its name. + * + * This must not be called if the dictionary does not contain the key. + */ + @JSBracketAccess + def rawApply(key: String): A = js.native + + /** Writes a field of this object. */ + @JSBracketAccess + def rawUpdate(key: String, value: A): Unit = js.native + } + + @inline + def dictEmpty[A](): js.Dictionary[A] = + new js.Object().asInstanceOf[js.Dictionary[A]] + + @inline + def dictGetOrElse[A](dict: js.Dictionary[_ <: A], key: String)( + default: => A): A = { + if (dictContains(dict, key)) + dictRawApply(dict, key) + else + default + } + + def dictGetOrElseAndRemove[A](dict: js.Dictionary[_ <: A], key: String, + default: A): A = { + if (dictContains(dict, key)) { + val result = dictRawApply(dict, key) + js.special.delete(dict, key) + result + } else { + default + } + } + + @inline + def dictRawApply[A](dict: js.Dictionary[A], key: String): A = + dict.asInstanceOf[DictionaryRawApply[A]].rawApply(key) + + def dictContains[A](dict: js.Dictionary[A], key: String): scala.Boolean = { + /* We have to use a safe version of hasOwnProperty, because + * "hasOwnProperty" could be a key of this dictionary. + */ + safeHasOwnProperty(dict, key) + } + + @inline + def dictSet[A](dict: js.Dictionary[A], key: String, value: A): Unit = + dict.asInstanceOf[DictionaryRawApply[A]].rawUpdate(key, value) + + @js.native + private trait MapRaw[K, V] extends js.Object { + def has(key: K): scala.Boolean = js.native + def get(key: K): V = js.native + @JSName("get") def getOrUndefined(key: K): js.UndefOr[V] = js.native + def set(key: K, value: V): Unit = js.native + def keys(): js.Iterator[K] = js.native + } + + @inline + def mapHas[K, V](map: js.Map[K, V], key: K): scala.Boolean = + map.asInstanceOf[MapRaw[K, V]].has(key) + + @inline + def mapGet[K, V](map: js.Map[K, V], key: K): V = + map.asInstanceOf[MapRaw[K, V]].get(key) + + @inline + def mapSet[K, V](map: js.Map[K, V], key: K, value: V): Unit = + map.asInstanceOf[MapRaw[K, V]].set(key, value) + + @inline + def mapGetOrElse[K, V](map: js.Map[K, V], key: K)(default: => V): V = { + val value = map.asInstanceOf[MapRaw[K, V]].getOrUndefined(key) + if (!isUndefined(value) || mapHas(map, key)) value.asInstanceOf[V] + else default + } + + @inline + def mapGetOrElseUpdate[K, V](map: js.Map[K, V], key: K)(default: => V): V = { + mapGetOrElse(map, key) { + val value = default + mapSet(map, key, value) + value + } + } + + @inline + def forArrayElems[A](array: js.Array[A])(f: A => Any): Unit = { + val len = array.length + var i = 0 + while (i != len) { + f(array(i)) + i += 1 + } + } + + @inline + def arrayRemove[A](array: js.Array[A], index: Int): Unit = + array.splice(index, 1) + + @inline + def arrayRemoveAndGet[A](array: js.Array[A], index: Int): A = + array.splice(index, 1)(0) + + @inline + def arrayExists[A](array: js.Array[A])(f: A => scala.Boolean): scala.Boolean = { + // scalastyle:off return + val len = array.length + var i = 0 + while (i != len) { + if (f(array(i))) + return true + i += 1 + } + false + // scalastyle:on return + } + + @inline def toUint(x: scala.Double): scala.Double = { + import js.DynamicImplicits.number2dynamic + (x >>> 0).asInstanceOf[scala.Double] + } +} diff --git a/javalib/src/main/scala/java/lang/Void.scala b/javalib/src/main/scala/java/lang/Void.scala new file mode 100644 index 0000000000..00a98113c8 --- /dev/null +++ b/javalib/src/main/scala/java/lang/Void.scala @@ -0,0 +1,36 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.lang + +/* This is a hijacked class. Its only instance is the value 'undefined'. + * Constructors are not emitted. + * + * On the JVM, this class has no instance. In Scala.js, it is repurposed as the + * boxed class for unit, aka `void`. The instance methods are + * Scala.js-specific. + */ +final class Void private () extends AnyRef { + @inline override def equals(that: Any): scala.Boolean = + this eq that.asInstanceOf[AnyRef] + + @inline override def hashCode(): Int = 0 + + @inline override def toString(): String = "undefined" +} + +object Void { + /* TYPE should be a `final val`, but that crashes the JVM back-end, so we + * use a 'def' instead, which is binary compatible. + */ + def TYPE: Class[_] = scala.Predef.classOf[scala.Unit] +} diff --git a/javalib/src/main/scala/java/lang/_String.scala b/javalib/src/main/scala/java/lang/_String.scala new file mode 100644 index 0000000000..1daea18ac3 --- /dev/null +++ b/javalib/src/main/scala/java/lang/_String.scala @@ -0,0 +1,1051 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.lang + +import scala.annotation.{switch, tailrec} + +import java.util.Comparator + +import scala.scalajs.js +import scala.scalajs.js.annotation._ +import scala.scalajs.js.JSStringOps.enableJSStringOps +import scala.scalajs.runtime.linkingInfo +import scala.scalajs.LinkingInfo.ESVersion + +import java.lang.constant.{Constable, ConstantDesc} +import java.nio.ByteBuffer +import java.nio.charset.Charset +import java.util.Locale +import java.util.regex._ + +/* This is the implementation of java.lang.String, which is a hijacked class. + * Its instances are primitive strings. Constructors are not emitted. + * + * It should be declared as `class String`, but scalac really does not like + * being forced to compile java.lang.String, so we call it `_String` instead. + * The Scala.js compiler back-end applies some magic to rename it into `String` + * when emitting the IR. + */ +final class _String private () // scalastyle:ignore + extends AnyRef with java.io.Serializable with Comparable[String] + with CharSequence with Constable with ConstantDesc { + + import _String._ + + @inline + private def thisString: String = + this.asInstanceOf[String] + + @inline + def length(): Int = + throw new Error("stub") // body replaced by the compiler back-end + + @inline + def charAt(index: Int): Char = + throw new Error("stub") // body replaced by the compiler back-end + + def codePointAt(index: Int): Int = { + if (linkingInfo.esVersion >= ESVersion.ES2015) { + charAt(index) // bounds check + this.asInstanceOf[js.Dynamic].codePointAt(index).asInstanceOf[Int] + } else { + val high = charAt(index) + if (index+1 < length()) { + val low = charAt(index+1) + if (Character.isSurrogatePair(high, low)) + Character.toCodePoint(high, low) + else + high.toInt + } else { + high.toInt + } + } + } + + def codePointBefore(index: Int): Int = { + val low = charAt(index - 1) + if (index > 1) { + val high = charAt(index - 2) + if (Character.isSurrogatePair(high, low)) + Character.toCodePoint(high, low) + else + low.toInt + } else { + low.toInt + } + } + + def codePointCount(beginIndex: Int, endIndex: Int): Int = + Character.codePointCount(this, beginIndex, endIndex) + + def offsetByCodePoints(index: Int, codePointOffset: Int): Int = { + val len = length() + if (index < 0 || index > len) + throw new StringIndexOutOfBoundsException(index) + + if (codePointOffset >= 0) { + var i = 0 + var result = index + while (i != codePointOffset) { + if (result >= len) + throw new StringIndexOutOfBoundsException + if ((result < len - 1) && + Character.isHighSurrogate(charAt(result)) && + Character.isLowSurrogate(charAt(result + 1))) { + result += 2 + } else { + result += 1 + } + i += 1 + } + result + } else { + var i = 0 + var result = index + while (i != codePointOffset) { + if (result <= 0) + throw new StringIndexOutOfBoundsException + if ((result > 1) && Character.isLowSurrogate(charAt(result - 1)) && + Character.isHighSurrogate(charAt(result - 2))) { + result -= 2 + } else { + result -= 1 + } + i -= 1 + } + result + } + } + + override def hashCode(): Int = { + var res = 0 + var mul = 1 // holds pow(31, length-i-1) + var i = length() - 1 + while (i >= 0) { + res += charAt(i) * mul + mul *= 31 + i -= 1 + } + res + } + + @inline + override def equals(that: Any): scala.Boolean = + this eq that.asInstanceOf[AnyRef] + + def compareTo(anotherString: String): Int = { + // scalastyle:off return + val thisLength = this.length() + val strLength = anotherString.length() + val minLength = Math.min(thisLength, strLength) + + var i = 0 + while (i != minLength) { + val cmp = this.charAt(i) - anotherString.charAt(i) + if (cmp != 0) + return cmp + i += 1 + } + thisLength - strLength + // scalastyle:on return + } + + def compareToIgnoreCase(str: String): Int = { + // scalastyle:off return + val thisLength = this.length() + val strLength = str.length() + val minLength = Math.min(thisLength, strLength) + + var i = 0 + while (i != minLength) { + val cmp = caseFold(this.charAt(i)) - caseFold(str.charAt(i)) + if (cmp != 0) + return cmp + i += 1 + } + thisLength - strLength + // scalastyle:on return + } + + @inline + def equalsIgnoreCase(anotherString: String): scala.Boolean = { + // scalastyle:off return + val len = length() + if (anotherString == null || anotherString.length() != len) { + false + } else { + var i = 0 + while (i != len) { + if (caseFold(this.charAt(i)) != caseFold(anotherString.charAt(i))) + return false + i += 1 + } + true + } + // scalastyle:on return + } + + /** Performs case folding of a single character for use by `equalsIgnoreCase` + * and `compareToIgnoreCase`. + * + * This implementation respects the specification of those two methods, + * although that behavior does not generally conform to Unicode Case + * Folding. + */ + @inline private def caseFold(c: Char): Char = + Character.toLowerCase(Character.toUpperCase(c)) + + @inline + def concat(s: String): String = + thisString + s + + @inline + def contains(s: CharSequence): scala.Boolean = + indexOf(s.toString) != -1 + + def endsWith(suffix: String): scala.Boolean = + thisString.jsSubstring(this.length() - suffix.length()) == suffix + + def getBytes(): Array[scala.Byte] = + getBytes(Charset.defaultCharset()) + + def getBytes(charsetName: String): Array[scala.Byte] = + getBytes(Charset.forName(charsetName)) + + def getBytes(charset: Charset): Array[scala.Byte] = { + val buf = charset.encode(thisString) + val res = new Array[scala.Byte](buf.remaining()) + buf.get(res) + res + } + + def getChars(srcBegin: Int, srcEnd: Int, dst: Array[Char], + dstBegin: Int): Unit = { + if (srcEnd > length() || srcBegin < 0 || srcEnd < 0 || srcBegin > srcEnd) + throw new StringIndexOutOfBoundsException("Index out of Bound") + + val offset = dstBegin - srcBegin + var i = srcBegin + while (i < srcEnd) { + dst(i + offset) = charAt(i) + i += 1 + } + } + + def indexOf(ch: Int): Int = + indexOf(Character.toString(ch)) + + def indexOf(ch: Int, fromIndex: Int): Int = + indexOf(Character.toString(ch), fromIndex) + + @inline + def indexOf(str: String): Int = + thisString.jsIndexOf(str) + + @inline + def indexOf(str: String, fromIndex: Int): Int = + thisString.jsIndexOf(str, fromIndex) + + /* Just returning this string is a valid implementation for `intern` in + * JavaScript, since strings are primitive values. Therefore, value equality + * and reference equality is the same. + */ + @inline + def intern(): String = thisString + + @inline + def isEmpty(): scala.Boolean = (this: AnyRef) eq ("": AnyRef) + + def lastIndexOf(ch: Int): Int = + lastIndexOf(Character.toString(ch)) + + def lastIndexOf(ch: Int, fromIndex: Int): Int = + if (fromIndex < 0) -1 + else lastIndexOf(Character.toString(ch), fromIndex) + + @inline + def lastIndexOf(str: String): Int = + thisString.jsLastIndexOf(str) + + @inline + def lastIndexOf(str: String, fromIndex: Int): Int = + if (fromIndex < 0) -1 + else thisString.jsLastIndexOf(str, fromIndex) + + @inline + def matches(regex: String): scala.Boolean = + Pattern.matches(regex, thisString) + + /* Both regionMatches ported from + * https://github.com/gwtproject/gwt/blob/master/user/super/com/google/gwt/emul/java/lang/String.java + */ + def regionMatches(ignoreCase: scala.Boolean, toffset: Int, other: String, + ooffset: Int, len: Int): scala.Boolean = { + if (other == null) { + throw new NullPointerException() + } else if (toffset < 0 || ooffset < 0 || toffset + len > this.length() || + ooffset + len > other.length()) { + false + } else if (len <= 0) { + true + } else { + val left = this.substring(toffset, toffset + len) + val right = other.substring(ooffset, ooffset + len) + if (ignoreCase) left.equalsIgnoreCase(right) else left == right + } + } + + @inline + def regionMatches(toffset: Int, other: String, ooffset: Int, + len: Int): scala.Boolean = { + regionMatches(false, toffset, other, ooffset, len) + } + + def repeat(count: Int): String = { + if (count < 0) { + throw new IllegalArgumentException + } else if (linkingInfo.esVersion >= ESVersion.ES2015) { + /* This will throw a `js.RangeError` if `count` is too large, instead of + * an `OutOfMemoryError`. That's fine because the behavior of `repeat` is + * not specified for `count` too large. + */ + this.asInstanceOf[js.Dynamic].repeat(count).asInstanceOf[String] + } else if (thisString == "" || count == 0) { + "" + } else if (thisString.length > (Int.MaxValue / count)) { + throw new OutOfMemoryError + } else { + var str = thisString + val resultLength = thisString.length * count + var remainingIters = 31 - Integer.numberOfLeadingZeros(count) + while (remainingIters > 0) { + str += str + remainingIters -= 1 + } + str += str.jsSubstring(0, resultLength - str.length) + str + } + } + + @inline + def replace(oldChar: Char, newChar: Char): String = + replace(oldChar.toString, newChar.toString) + + @inline + def replace(target: CharSequence, replacement: CharSequence): String = + thisString.jsSplit(target.toString).join(replacement.toString) + + def replaceAll(regex: String, replacement: String): String = + Pattern.compile(regex).matcher(thisString).replaceAll(replacement) + + def replaceFirst(regex: String, replacement: String): String = + Pattern.compile(regex).matcher(thisString).replaceFirst(replacement) + + @inline + def split(regex: String): Array[String] = + split(regex, 0) + + def split(regex: String, limit: Int): Array[String] = + Pattern.compile(regex).split(thisString, limit) + + @inline + def startsWith(prefix: String): scala.Boolean = + startsWith(prefix, 0) + + @inline + def startsWith(prefix: String, toffset: Int): scala.Boolean = { + (toffset <= length() && toffset >= 0 && + thisString.jsSubstring(toffset, toffset + prefix.length()) == prefix) + } + + @inline + def subSequence(beginIndex: Int, endIndex: Int): CharSequence = + substring(beginIndex, endIndex) + + @inline + def substring(beginIndex: Int): String = { + // Bounds check + if (beginIndex < 0 || beginIndex > length()) + charAt(beginIndex) + + thisString.jsSubstring(beginIndex) + } + + @inline + def substring(beginIndex: Int, endIndex: Int): String = { + // Bounds check + if (beginIndex < 0) + charAt(beginIndex) + if (endIndex > length()) + charAt(endIndex) + if (endIndex < beginIndex) + charAt(-1) + + thisString.jsSubstring(beginIndex, endIndex) + } + + def toCharArray(): Array[Char] = { + val len = length() + val result = new Array[Char](len) + var i = 0 + while (i < len) { + result(i) = charAt(i) + i += 1 + } + result + } + + /* toLowerCase() and toUpperCase() + * + * The overloads without an explicit locale use the default locale, which is + * the root locale by specification. They are implemented by direct + * delegation to ECMAScript's `toLowerCase()` and `toUpperCase()`, which are + * specified as locale-insensitive, therefore equivalent to the root locale. + * + * It turns out virtually every locale behaves in the same way as the root + * locale for default case algorithms. Only Lithuanian (lt), Turkish (tr) + * and Azeri (az) have different behaviors. + * + * The overloads with a `Locale` specifically test for those three languages + * and delegate to dedicated methods to handle them. Those methods start by + * handling their respective special cases, then delegate to the locale- + * insensitive version. The special cases are specified in the Unicode + * reference file at + * + * https://unicode.org/Public/13.0.0/ucd/SpecialCasing.txt + * + * That file first contains a bunch of locale-insensitive special cases, + * which we do not need to handle. Only the last two sections about locale- + * sensitive special-cases are important for us. + * + * Some of the rules are further context-sensitive, using predicates that are + * defined in Section 3.13 "Default Case Algorithms" of the Unicode Standard, + * available at + * + * http://www.unicode.org/versions/Unicode13.0.0/ + * + * We based the implementations on Unicode 13.0.0. It is worth noting that + * there has been no non-comment changes in the SpecialCasing.txt file + * between Unicode 4.1.0 and 13.0.0 (perhaps even earlier; the version 4.1.0 + * is the earliest that is easily accessible). + */ + + def toLowerCase(locale: Locale): String = { + locale.getLanguage() match { + case "lt" => toLowerCaseLithuanian() + case "tr" | "az" => toLowerCaseTurkishAndAzeri() + case _ => toLowerCase() + } + } + + private def toLowerCaseLithuanian(): String = { + /* Relevant excerpt from SpecialCasing.txt + * + * # Lithuanian + * + * # Lithuanian retains the dot in a lowercase i when followed by accents. + * + * [...] + * + * # Introduce an explicit dot above when lowercasing capital I's and J's + * # whenever there are more accents above. + * # (of the accents used in Lithuanian: grave, acute, tilde above, and ogonek) + * + * 0049; 0069 0307; 0049; 0049; lt More_Above; # LATIN CAPITAL LETTER I + * 004A; 006A 0307; 004A; 004A; lt More_Above; # LATIN CAPITAL LETTER J + * 012E; 012F 0307; 012E; 012E; lt More_Above; # LATIN CAPITAL LETTER I WITH OGONEK + * 00CC; 0069 0307 0300; 00CC; 00CC; lt; # LATIN CAPITAL LETTER I WITH GRAVE + * 00CD; 0069 0307 0301; 00CD; 00CD; lt; # LATIN CAPITAL LETTER I WITH ACUTE + * 0128; 0069 0307 0303; 0128; 0128; lt; # LATIN CAPITAL LETTER I WITH TILDE + */ + + /* Tests whether we are in an `More_Above` context. + * From Table 3.17 in the Unicode standard: + * - Description: C is followed by a character of combining class + * 230 (Above) with no intervening character of combining class 0 or + * 230 (Above). + * - Regex, after C: [^\p{ccc=230}\p{ccc=0}]*[\p{ccc=230}] + */ + def moreAbove(i: Int): scala.Boolean = { + import Character._ + val len = length() + + @tailrec def loop(j: Int): scala.Boolean = { + if (j == len) { + false + } else { + val cp = this.codePointAt(j) + combiningClassNoneOrAboveOrOther(cp) match { + case CombiningClassIsNone => false + case CombiningClassIsAbove => true + case _ => loop(j + charCount(cp)) + } + } + } + + loop(i + 1) + } + + val preprocessed = replaceCharsAtIndex { i => + (this.charAt(i): @switch) match { + case '\u0049' if moreAbove(i) => "\u0069\u0307" + case '\u004A' if moreAbove(i) => "\u006A\u0307" + case '\u012E' if moreAbove(i) => "\u012F\u0307" + case '\u00CC' => "\u0069\u0307\u0300" + case '\u00CD' => "\u0069\u0307\u0301" + case '\u0128' => "\u0069\u0307\u0303" + case _ => null + } + } + + preprocessed.toLowerCase() + } + + private def toLowerCaseTurkishAndAzeri(): String = { + /* Relevant excerpt from SpecialCasing.txt + * + * # Turkish and Azeri + * + * # I and i-dotless; I-dot and i are case pairs in Turkish and Azeri + * # The following rules handle those cases. + * + * 0130; 0069; 0130; 0130; tr; # LATIN CAPITAL LETTER I WITH DOT ABOVE + * 0130; 0069; 0130; 0130; az; # LATIN CAPITAL LETTER I WITH DOT ABOVE + * + * # When lowercasing, remove dot_above in the sequence I + dot_above, which will turn into i. + * # This matches the behavior of the canonically equivalent I-dot_above + * + * 0307; ; 0307; 0307; tr After_I; # COMBINING DOT ABOVE + * 0307; ; 0307; 0307; az After_I; # COMBINING DOT ABOVE + * + * # When lowercasing, unless an I is before a dot_above, it turns into a dotless i. + * + * 0049; 0131; 0049; 0049; tr Not_Before_Dot; # LATIN CAPITAL LETTER I + * 0049; 0131; 0049; 0049; az Not_Before_Dot; # LATIN CAPITAL LETTER I + */ + + /* Tests whether we are in an `After_I` context. + * From Table 3.17 in the Unicode standard: + * - Description: There is an uppercase I before C, and there is no + * intervening combining character class 230 (Above) or 0. + * - Regex, before C: [I]([^\p{ccc=230}\p{ccc=0}])* + */ + def afterI(i: Int): scala.Boolean = { + val j = skipCharsWithCombiningClassOtherThanNoneOrAboveBackwards(i) + j > 0 && charAt(j - 1) == 'I' + } + + /* Tests whether we are in an `Before_Dot` context. + * From Table 3.17 in the Unicode standard: + * - Description: C is followed by combining dot above (U+0307). Any + * sequence of characters with a combining class that is neither 0 nor + * 230 may intervene between the current character and the combining dot + * above. + * - Regex, after C: ([^\p{ccc=230}\p{ccc=0}])*[\u0307] + */ + def beforeDot(i: Int): scala.Boolean = { + val j = skipCharsWithCombiningClassOtherThanNoneOrAboveForwards(i + 1) + j != length() && charAt(j) == '\u0307' + } + + val preprocessed = replaceCharsAtIndex { i => + (this.charAt(i): @switch) match { + case '\u0130' => "\u0069" + case '\u0307' if afterI(i) => "" + case '\u0049' if !beforeDot(i) => "\u0131" + case _ => null + } + } + + preprocessed.toLowerCase() + } + + @inline + def toLowerCase(): String = + this.asInstanceOf[js.Dynamic].toLowerCase().asInstanceOf[String] + + def toUpperCase(locale: Locale): String = { + locale.getLanguage() match { + case "lt" => toUpperCaseLithuanian() + case "tr" | "az" => toUpperCaseTurkishAndAzeri() + case _ => toUpperCase() + } + } + + private def toUpperCaseLithuanian(): String = { + /* Relevant excerpt from SpecialCasing.txt + * + * # Lithuanian + * + * # Lithuanian retains the dot in a lowercase i when followed by accents. + * + * # Remove DOT ABOVE after "i" with upper or titlecase + * + * 0307; 0307; ; ; lt After_Soft_Dotted; # COMBINING DOT ABOVE + */ + + /* Tests whether we are in an `After_Soft_Dotted` context. + * From Table 3.17 in the Unicode standard: + * - Description: There is a Soft_Dotted character before C, with no + * intervening character of combining class 0 or 230 (Above). + * - Regex, before C: [\p{Soft_Dotted}]([^\p{ccc=230} \p{ccc=0}])* + * + * According to https://unicode.org/Public/13.0.0/ucd/PropList.txt, there + * are 44 code points with the Soft_Dotted property. However, + * experimentation on the JVM reveals that the JDK (8 and 14 were tested) + * only recognizes 8 code points when deciding whether to remove the 0x0307 + * code points. The following script reproduces the list: + +for (cp <- 0 to Character.MAX_CODE_POINT) { + val input = new String(Array(cp, 0x0307, 0x0301), 0, 3) + val output = input.toUpperCase(new java.util.Locale("lt")) + if (!output.contains('\u0307')) + println(cp.toHexString) +} + + */ + def afterSoftDotted(i: Int): scala.Boolean = { + val j = skipCharsWithCombiningClassOtherThanNoneOrAboveBackwards(i) + j > 0 && (codePointBefore(j) match { + case 0x0069 | 0x006a | 0x012f | 0x0268 | 0x0456 | 0x0458 | 0x1e2d | 0x1ecb => true + case _ => false + }) + } + + val preprocessed = replaceCharsAtIndex { i => + (this.charAt(i): @switch) match { + case '\u0307' if afterSoftDotted(i) => "" + case _ => null + } + } + + preprocessed.toUpperCase() + } + + private def toUpperCaseTurkishAndAzeri(): String = { + /* Relevant excerpt from SpecialCasing.txt + * + * # Turkish and Azeri + * + * # When uppercasing, i turns into a dotted capital I + * + * 0069; 0069; 0130; 0130; tr; # LATIN SMALL LETTER I + * 0069; 0069; 0130; 0130; az; # LATIN SMALL LETTER I + */ + + val preprocessed = replaceCharsAtIndex { i => + (this.charAt(i): @switch) match { + case '\u0069' => "\u0130" + case _ => null + } + } + + preprocessed.toUpperCase() + } + + @inline + def toUpperCase(): String = + this.asInstanceOf[js.Dynamic].toUpperCase().asInstanceOf[String] + + /** Replaces special characters in this string (possibly in special contexts) + * by dedicated strings. + * + * This method encodes the general pattern of + * + * - `toLowerCaseLithuanian()` + * - `toLowerCaseTurkishAndAzeri()` + * - `toUpperCaseLithuanian()` + * - `toUpperCaseTurkishAndAzeri()` + * + * @param replacementAtIndex + * A function from index to `String | Null`, which should return a special + * replacement string for the character at the given index, or `null` if + * the character at the given index is not special. + */ + @inline + private def replaceCharsAtIndex(replacementAtIndex: Int => String): String = { + var prep = "" + val len = this.length() + var i = 0 + var startOfSegment = 0 + + while (i != len) { + val replacement = replacementAtIndex(i) + if (replacement != null) { + prep += this.substring(startOfSegment, i) + prep += replacement + startOfSegment = i + 1 + } + i += 1 + } + + if (startOfSegment == 0) + thisString // opt: no character needed replacing, directly return the original string + else + prep + this.substring(startOfSegment, i) + } + + private def skipCharsWithCombiningClassOtherThanNoneOrAboveForwards(i: Int): Int = { + // scalastyle:off return + import Character._ + val len = length() + var j = i + while (j != len) { + val cp = codePointAt(j) + if (combiningClassNoneOrAboveOrOther(cp) != CombiningClassIsOther) + return j + j += charCount(cp) + } + j + // scalastyle:on return + } + + private def skipCharsWithCombiningClassOtherThanNoneOrAboveBackwards(i: Int): Int = { + // scalastyle:off return + import Character._ + var j = i + while (j > 0) { + val cp = codePointBefore(j) + if (combiningClassNoneOrAboveOrOther(cp) != CombiningClassIsOther) + return j + j -= charCount(cp) + } + 0 + // scalastyle:on return + } + + def trim(): String = { + val len = length() + var start = 0 + while (start != len && charAt(start) <= ' ') + start += 1 + if (start == len) { + "" + } else { + /* If we get here, 0 <= start < len, so the original string is not empty. + * We also know that charAt(start) > ' '. + */ + var end = len + while (charAt(end - 1) <= ' ') // no need for a bounds check here since charAt(start) > ' ' + end -= 1 + if (start == 0 && end == len) thisString + else substring(start, end) + } + } + + def stripLeading(): String = { + val len = length() + var idx = 0 + while (idx < len && Character.isWhitespace(charAt(idx))) + idx += 1 + substring(idx) + } + + def stripTrailing(): String = { + val len = length() + var idx = len - 1 + while (idx >= 0 && Character.isWhitespace(charAt(idx))) + idx -= 1 + substring(0, idx + 1) + } + + def strip(): String = { + val len = length() + var leading = 0 + while (leading < len && Character.isWhitespace(charAt(leading))) + leading += 1 + if (leading == len) { + "" + } else { + var trailing = len + while (Character.isWhitespace(charAt(trailing - 1))) + trailing -= 1 + if (leading == 0 && trailing == len) thisString + else substring(leading, trailing) + } + } + + def isBlank(): scala.Boolean = { + val len = length() + var start = 0 + while (start != len && Character.isWhitespace(charAt(start))) + start += 1 + start == len + } + + private def splitLines(): js.Array[String] = { + val xs = js.Array[String]() + val len = length() + var idx = 0 + var last = 0 + while (idx < len) { + val c = charAt(idx) + if (c == '\n' || c == '\r') { + xs.push(substring(last, idx)) + if (c == '\r' && idx + 1 < len && charAt(idx + 1) == '\n') + idx += 1 + last = idx + 1 + } + idx += 1 + } + // make sure we add the last segment, but not the last new line + if (last != len) + xs.push(substring(last)) + xs + } + + def indent(n: Int): String = { + + def forEachLn(f: String => String): String = { + var out = "" + var i = 0 + val xs = splitLines() + while (i < xs.length) { + out += f(xs(i)) + "\n" + i += 1 + } + out + } + + if (n < 0) { + forEachLn { l => + // n is negative here + var idx = 0 + val lim = if (l.length() <= -n) l.length() else -n + while (idx < lim && Character.isWhitespace(l.charAt(idx))) + idx += 1 + l.substring(idx) + } + } else { + val padding = " ".asInstanceOf[_String].repeat(n) + forEachLn(padding + _) + } + } + + def stripIndent(): String = { + if (isEmpty()) { + "" + } else { + import Character.{isWhitespace => isWS} + // splitLines discards the last NL if it's empty so we identify it here first + val trailingNL = charAt(length() - 1) match { + // this also covers the \r\n case via the last \n + case '\r' | '\n' => true + case _ => false + } + + val xs = splitLines() + var i = 0 + var minLeading = Int.MaxValue + + while (i < xs.length) { + val l = xs(i) + // count the last line even if blank + if (i == xs.length - 1 || !l.asInstanceOf[_String].isBlank()) { + var idx = 0 + while (idx < l.length() && isWS(l.charAt(idx))) + idx += 1 + if (idx < minLeading) + minLeading = idx + } + i += 1 + } + // if trailingNL, then the last line is zero width + if (trailingNL || minLeading == Int.MaxValue) + minLeading = 0 + + var out = "" + var j = 0 + while (j < xs.length) { + val line = xs(j) + if (!line.asInstanceOf[_String].isBlank()) { + // we strip the computed leading WS and also any *trailing* WS + out += line.substring(minLeading).asInstanceOf[_String].stripTrailing() + } + // different from indent, we don't add an LF at the end unless there's already one + if (j != xs.length - 1) + out += "\n" + j += 1 + } + if (trailingNL) + out += "\n" + out + } + } + + def translateEscapes(): String = { + def isOctalDigit(c: Char): scala.Boolean = c >= '0' && c <= '7' + def isValidIndex(n: Int): scala.Boolean = n < length() + var i = 0 + var result = "" + while (i < length()) { + if (charAt(i) == '\\') { + if (isValidIndex(i + 1)) { + charAt(i + 1) match { + // , so CR(\r), LF(\n), or CRLF(\r\n) + case '\r' if isValidIndex(i + 2) && charAt(i + 2) == '\n' => + i += 1 // skip \r and \n and discard, so 2+1 chars + case '\r' | '\n' => // skip and discard + + // normal one char escapes + case 'b' => result += "\b" + case 't' => result += "\t" + case 'n' => result += "\n" + case 'f' => result += "\f" + case 'r' => result += "\r" + case 's' => result += " " + case '"' => result += "\"" + case '\'' => result += "\'" + case '\\' => result += "\\" + + // we're parsing octal now, as per JLS-3, we got three cases: + // 1) [0-3][0-7][0-7] + case a @ ('0' | '1' | '2' | '3') + if isValidIndex(i + 3) && isOctalDigit(charAt(i + 2)) && isOctalDigit(charAt(i + 3)) => + val codePoint = + ((a - '0') * 64) + ((charAt(i + 2) - '0') * 8) + (charAt(i + 3) - '0') + result += codePoint.toChar + i += 2 // skip two other numbers, so 2+2 chars + // 2) [0-7][0-7] + case a if isOctalDigit(a) && isValidIndex(i + 2) && isOctalDigit(charAt(i + 2)) => + val codePoint = ((a - '0') * 8) + (charAt(i + 2) - '0') + result += codePoint.toChar + i += 1 // skip one other number, so 2+1 chars + // 3) [0-7] + case a if isOctalDigit(a) => + val codePoint = a - '0' + result += codePoint.toChar + // bad escape otherwise, this catches everything else including the Unicode ones + case bad => + throw new IllegalArgumentException(s"Illegal escape: `\\$bad`") + } + // skip ahead 2 chars (\ and the escape char) at minimum, cases above can add more if needed + i += 2 + } else { + throw new IllegalArgumentException("Illegal escape: `\\(end-of-string)`") + } + } else { + result += charAt(i) + i += 1 + } + } + result + } + + def transform[R](f: java.util.function.Function[String, R]): R = + f.apply(thisString) + + @inline + override def toString(): String = + thisString +} + +object _String { // scalastyle:ignore + final lazy val CASE_INSENSITIVE_ORDER: Comparator[String] = { + new Comparator[String] with Serializable { + def compare(o1: String, o2: String): Int = o1.compareToIgnoreCase(o2) + } + } + + // Constructors + + def `new`(): String = "" + + def `new`(value: Array[Char]): String = + `new`(value, 0, value.length) + + def `new`(value: Array[Char], offset: Int, count: Int): String = { + val end = offset + count + if (offset < 0 || end < offset || end > value.length) + throw new StringIndexOutOfBoundsException + + var result = "" + var i = offset + while (i != end) { + result += value(i).toString + i += 1 + } + result + } + + def `new`(bytes: Array[scala.Byte]): String = + `new`(bytes, Charset.defaultCharset()) + + def `new`(bytes: Array[scala.Byte], charsetName: String): String = + `new`(bytes, Charset.forName(charsetName)) + + def `new`(bytes: Array[scala.Byte], charset: Charset): String = + charset.decode(ByteBuffer.wrap(bytes)).toString() + + def `new`(bytes: Array[scala.Byte], offset: Int, length: Int): String = + `new`(bytes, offset, length, Charset.defaultCharset()) + + def `new`(bytes: Array[scala.Byte], offset: Int, length: Int, + charsetName: String): String = + `new`(bytes, offset, length, Charset.forName(charsetName)) + + def `new`(bytes: Array[scala.Byte], offset: Int, length: Int, + charset: Charset): String = + charset.decode(ByteBuffer.wrap(bytes, offset, length)).toString() + + def `new`(codePoints: Array[Int], offset: Int, count: Int): String = { + val end = offset + count + if (offset < 0 || end < offset || end > codePoints.length) + throw new StringIndexOutOfBoundsException + + var result = "" + var i = offset + while (i != end) { + result += Character.toString(codePoints(i)) + i += 1 + } + result + } + + def `new`(original: String): String = { + if (original == null) + throw new NullPointerException + original + } + + def `new`(buffer: java.lang.StringBuffer): String = + buffer.toString + + def `new`(builder: java.lang.StringBuilder): String = + builder.toString + + // Static methods (aka methods on the companion object) + + def valueOf(b: scala.Boolean): String = b.toString() + def valueOf(c: scala.Char): String = c.toString() + def valueOf(i: scala.Int): String = i.toString() + def valueOf(l: scala.Long): String = l.toString() + def valueOf(f: scala.Float): String = f.toString() + def valueOf(d: scala.Double): String = d.toString() + + @inline def valueOf(obj: Object): String = + "" + obj // if (obj eq null), returns "null" + + def valueOf(data: Array[Char]): String = + valueOf(data, 0, data.length) + + def valueOf(data: Array[Char], offset: Int, count: Int): String = + `new`(data, offset, count) + + def format(format: String, args: Array[AnyRef]): String = + new java.util.Formatter().format(format, args).toString() + + def format(l: Locale, format: String, args: Array[AnyRef]): String = + new java.util.Formatter(l).format(format, args).toString() + +} diff --git a/javalanglib/src/main/scala/java/lang/annotation/Annotation.scala b/javalib/src/main/scala/java/lang/annotation/Annotation.scala similarity index 100% rename from javalanglib/src/main/scala/java/lang/annotation/Annotation.scala rename to javalib/src/main/scala/java/lang/annotation/Annotation.scala diff --git a/javalib/src/main/scala/java/lang/constant/Constable.scala b/javalib/src/main/scala/java/lang/constant/Constable.scala new file mode 100644 index 0000000000..0a4faa91fe --- /dev/null +++ b/javalib/src/main/scala/java/lang/constant/Constable.scala @@ -0,0 +1,20 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.lang.constant + +// scalastyle:off empty.class + +trait Constable { + // Cannot be implemented + //def describeConstable(): java.util.Optional[_ <: ConstantDesc] +} diff --git a/javalib/src/main/scala/java/lang/constant/ConstantDesc.scala b/javalib/src/main/scala/java/lang/constant/ConstantDesc.scala new file mode 100644 index 0000000000..7d7d005835 --- /dev/null +++ b/javalib/src/main/scala/java/lang/constant/ConstantDesc.scala @@ -0,0 +1,20 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.lang.constant + +// scalastyle:off empty.class + +trait ConstantDesc { + // Cannot be implemented + //def resolveConstantDesc(lookup: java.lang.invoke.MethodHandles.Lookup): Object +} diff --git a/javalib/src/main/scala/java/lang/reflect/Array.scala b/javalib/src/main/scala/java/lang/reflect/Array.scala new file mode 100644 index 0000000000..688d97b5d1 --- /dev/null +++ b/javalib/src/main/scala/java/lang/reflect/Array.scala @@ -0,0 +1,194 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.lang.reflect + +import scala.scalajs.js + +import java.lang.Class + +object Array { + def newInstance(componentType: Class[_], length: Int): AnyRef = + componentType.newArrayOfThisClass(js.Array(length)) + + def newInstance(componentType: Class[_], dimensions: scala.Array[Int]): AnyRef = { + val jsDims = js.Array[Int]() + val len = dimensions.length + var i = 0 + while (i != len) { + jsDims.push(dimensions(i)) + i += 1 + } + componentType.newArrayOfThisClass(jsDims) + } + + def getLength(array: AnyRef): Int = array match { + // yes, this is kind of stupid, but that's how it is + case array: Array[Object] => array.length + case array: Array[Boolean] => array.length + case array: Array[Char] => array.length + case array: Array[Byte] => array.length + case array: Array[Short] => array.length + case array: Array[Int] => array.length + case array: Array[Long] => array.length + case array: Array[Float] => array.length + case array: Array[Double] => array.length + case _ => throw new IllegalArgumentException("argument type mismatch") + } + + def get(array: AnyRef, index: Int): AnyRef = array match { + case array: Array[Object] => array(index) + case array: Array[Boolean] => java.lang.Boolean.valueOf(array(index)) + case array: Array[Char] => java.lang.Character.valueOf(array(index)) + case array: Array[Byte] => java.lang.Byte.valueOf(array(index)) + case array: Array[Short] => java.lang.Short.valueOf(array(index)) + case array: Array[Int] => java.lang.Integer.valueOf(array(index)) + case array: Array[Long] => java.lang.Long.valueOf(array(index)) + case array: Array[Float] => java.lang.Float.valueOf(array(index)) + case array: Array[Double] => java.lang.Double.valueOf(array(index)) + case _ => throw new IllegalArgumentException("argument type mismatch") + } + + def getBoolean(array: AnyRef, index: Int): Boolean = array match { + case array: Array[Boolean] => array(index) + case _ => throw new IllegalArgumentException("argument type mismatch") + } + + def getChar(array: AnyRef, index: Int): Char = array match { + case array: Array[Char] => array(index) + case _ => throw new IllegalArgumentException("argument type mismatch") + } + + def getByte(array: AnyRef, index: Int): Byte = array match { + case array: Array[Byte] => array(index) + case _ => throw new IllegalArgumentException("argument type mismatch") + } + + def getShort(array: AnyRef, index: Int): Short = array match { + case array: Array[Short] => array(index) + case array: Array[Byte] => array(index) + case _ => throw new IllegalArgumentException("argument type mismatch") + } + + def getInt(array: AnyRef, index: Int): Int = array match { + case array: Array[Int] => array(index) + case array: Array[Char] => array(index) + case array: Array[Byte] => array(index) + case array: Array[Short] => array(index) + case _ => throw new IllegalArgumentException("argument type mismatch") + } + + def getLong(array: AnyRef, index: Int): Long = array match { + case array: Array[Long] => array(index) + case array: Array[Char] => array(index) + case array: Array[Byte] => array(index) + case array: Array[Short] => array(index) + case array: Array[Int] => array(index) + case _ => throw new IllegalArgumentException("argument type mismatch") + } + + def getFloat(array: AnyRef, index: Int): Float = array match { + case array: Array[Float] => array(index) + case array: Array[Char] => array(index) + case array: Array[Byte] => array(index) + case array: Array[Short] => array(index) + case array: Array[Int] => array(index).toFloat + case array: Array[Long] => array(index).toFloat + case _ => throw new IllegalArgumentException("argument type mismatch") + } + + def getDouble(array: AnyRef, index: Int): Double = array match { + case array: Array[Double] => array(index) + case array: Array[Char] => array(index) + case array: Array[Byte] => array(index) + case array: Array[Short] => array(index) + case array: Array[Int] => array(index) + case array: Array[Long] => array(index).toDouble + case array: Array[Float] => array(index) + case _ => throw new IllegalArgumentException("argument type mismatch") + } + + def set(array: AnyRef, index: Int, value: AnyRef): Unit = array match { + case array: Array[Object] => array(index) = value + case _ => + (value: Any) match { + case value: Boolean => setBoolean(array, index, value) + case value: Char => setChar(array, index, value) + case value: Byte => setByte(array, index, value) + case value: Short => setShort(array, index, value) + case value: Int => setInt(array, index, value) + case value: Long => setLong(array, index, value) + case value: Float => setFloat(array, index, value) + case value: Double => setDouble(array, index, value) + case _ => throw new IllegalArgumentException("argument type mismatch") + } + } + + def setBoolean(array: AnyRef, index: Int, value: Boolean): Unit = array match { + case array: Array[Boolean] => array(index) = value + case _ => throw new IllegalArgumentException("argument type mismatch") + } + + def setChar(array: AnyRef, index: Int, value: Char): Unit = array match { + case array: Array[Char] => array(index) = value + case array: Array[Int] => array(index) = value + case array: Array[Long] => array(index) = value + case array: Array[Float] => array(index) = value + case array: Array[Double] => array(index) = value + case _ => throw new IllegalArgumentException("argument type mismatch") + } + + def setByte(array: AnyRef, index: Int, value: Byte): Unit = array match { + case array: Array[Byte] => array(index) = value + case array: Array[Short] => array(index) = value + case array: Array[Int] => array(index) = value + case array: Array[Long] => array(index) = value + case array: Array[Float] => array(index) = value + case array: Array[Double] => array(index) = value + case _ => throw new IllegalArgumentException("argument type mismatch") + } + + def setShort(array: AnyRef, index: Int, value: Short): Unit = array match { + case array: Array[Short] => array(index) = value + case array: Array[Int] => array(index) = value + case array: Array[Long] => array(index) = value + case array: Array[Float] => array(index) = value + case array: Array[Double] => array(index) = value + case _ => throw new IllegalArgumentException("argument type mismatch") + } + + def setInt(array: AnyRef, index: Int, value: Int): Unit = array match { + case array: Array[Int] => array(index) = value + case array: Array[Long] => array(index) = value + case array: Array[Float] => array(index) = value.toFloat + case array: Array[Double] => array(index) = value + case _ => throw new IllegalArgumentException("argument type mismatch") + } + + def setLong(array: AnyRef, index: Int, value: Long): Unit = array match { + case array: Array[Long] => array(index) = value + case array: Array[Float] => array(index) = value.toFloat + case array: Array[Double] => array(index) = value.toDouble + case _ => throw new IllegalArgumentException("argument type mismatch") + } + + def setFloat(array: AnyRef, index: Int, value: Float): Unit = array match { + case array: Array[Float] => array(index) = value + case array: Array[Double] => array(index) = value + case _ => throw new IllegalArgumentException("argument type mismatch") + } + + def setDouble(array: AnyRef, index: Int, value: Double): Unit = array match { + case array: Array[Double] => array(index) = value + case _ => throw new IllegalArgumentException("argument type mismatch") + } +} diff --git a/javalib/src/main/scala/java/math/BigDecimal.scala b/javalib/src/main/scala/java/math/BigDecimal.scala index 0b8e571918..98baffe296 100644 --- a/javalib/src/main/scala/java/math/BigDecimal.scala +++ b/javalib/src/main/scala/java/math/BigDecimal.scala @@ -58,8 +58,13 @@ object BigDecimal { private final val LongFivePows = newArrayOfPows(28, 5) - private final val LongFivePowsBitLength = - Array.tabulate[Int](LongFivePows.length)(i => bitLength(LongFivePows(i))) + private final val LongFivePowsBitLength = { + val len = LongFivePows.length + val result = new Array[Int](len) + for (i <- 0 until len) + result(i) = bitLength(LongFivePows(i)) + result + } /** An array of longs with powers of ten. * @@ -68,8 +73,13 @@ object BigDecimal { */ private[math] final val LongTenPows = newArrayOfPows(19, 10) - private final val LongTenPowsBitLength = - Array.tabulate[Int](LongTenPows.length)(i => bitLength(LongTenPows(i))) + private final val LongTenPowsBitLength = { + val len = LongTenPows.length + val result = new Array[Int](len) + for (i <- 0 until len) + result(i) = bitLength(LongTenPows(i)) + result + } private final val BigIntScaledByZeroLength = 11 @@ -77,15 +87,23 @@ object BigDecimal { * * ([0,0],[1,0],...,[10,0]). */ - private final val BigIntScaledByZero = - Array.tabulate[BigDecimal](BigIntScaledByZeroLength)(new BigDecimal(_, 0)) + private final val BigIntScaledByZero = { + val result = new Array[BigDecimal](BigIntScaledByZeroLength) + for (i <- 0 until BigIntScaledByZeroLength) + result(i) = new BigDecimal(i, 0) + result + } /** An array with the zero number scaled by the first positive scales. * * (0*10^0, 0*10^1, ..., 0*10^10). */ - private final val ZeroScaledBy = - Array.tabulate[BigDecimal](BigIntScaledByZeroLength)(new BigDecimal(0, _)) + private final val ZeroScaledBy = { + val result = new Array[BigDecimal](BigIntScaledByZeroLength) + for (i <- 0 until BigIntScaledByZeroLength) + result(i) = new BigDecimal(0, i) + result + } /** A string filled with 100 times the character `'0'`. * It is not a `final` val so that it isn't copied at every call site. @@ -132,8 +150,8 @@ object BigDecimal { val unscaled = thisValue._smallValue + augPlusPowLength valueOf(unscaled, thisValue._scale) } else { - val bi = Multiplication.multiplyByTenPow(augend.getUnscaledValue(), diffScale) - new BigDecimal(thisValue.getUnscaledValue().add(bi), thisValue.scale) + val bi = Multiplication.multiplyByTenPow(augend.getUnscaledValue, diffScale) + new BigDecimal(thisValue.getUnscaledValue.add(bi), thisValue.scale()) } } @@ -205,8 +223,13 @@ object BigDecimal { else 0 } - private[math] def newArrayOfPows(len: Int, pow: Int): Array[Long] = - Array.iterate(1L, len)(_ * pow) + private[math] def newArrayOfPows(len: Int, pow: Int): Array[Long] = { + val result = new Array[Long](len) + result(0) = 1L + for (i <- 1 until len) + result(i) = result(i - 1) * pow + result + } /** Return an increment that can be -1,0 or 1, depending on {@code roundingMode}. * @@ -276,11 +299,20 @@ object BigDecimal { 32 - java.lang.Integer.numberOfLeadingZeros(smallValue) } - @inline - private def charNotEqualTo(c: Char, cs: Char*): Boolean = !cs.contains(c) + private def charNotEqualTo(c: Char, cs: Array[Char]): Boolean = !charEqualTo(c, cs) - @inline - private def charEqualTo(c: Char, cs: Char*): Boolean = cs.contains(c) + private def charEqualTo(c: Char, cs: Array[Char]): Boolean = { + // scalastyle:off return + val len = cs.length + var i = 0 + while (i != len) { + if (cs(i) == c) + return true + i += 1 + } + false + // scalastyle:on return + } @inline private def insertString(s: String, pos: Int, s2: String): String = @@ -292,7 +324,7 @@ object BigDecimal { insertString(s, pos, s2.substring(s2Start, s2Start + s2Len)) } - private implicit class StringOps(val s: String) extends AnyVal { + private implicit class StringOps(private val s: String) extends AnyVal { @inline def insert(pos: Int, s2: String): String = insertString(s, pos, s2) @@ -374,12 +406,12 @@ class BigDecimal() extends Number with Comparable[BigDecimal] { if (offset <= last && in(offset) == '+') { index += 1 // Fail if the next character is another sign. - if (index < last && charEqualTo(in(index), '+', '-')) + if (index < last && charEqualTo(in(index), Array('+', '-'))) throw new NumberFormatException("For input string: " + in.toString) } else { // check that '-' is not followed by another sign val isMinus = index <= last && in(index) == '-' - val nextIsSign = index + 1 < last && charEqualTo(in(index + 1), '+', '-') + val nextIsSign = index + 1 < last && charEqualTo(in(index + 1), Array('+', '-')) if (isMinus && nextIsSign) throw new NumberFormatException("For input string: " + in.toString) } @@ -388,7 +420,7 @@ class BigDecimal() extends Number with Comparable[BigDecimal] { var counter = 0 var wasNonZero = false // Accumulating all digits until a possible decimal point - while (index <= last && charNotEqualTo(in(index), '.', 'e', 'E')) { + while (index <= last && charNotEqualTo(in(index), Array('.', 'e', 'E'))) { if (!wasNonZero) { if (in(index) == '0') counter += 1 else wasNonZero = true @@ -404,7 +436,7 @@ class BigDecimal() extends Number with Comparable[BigDecimal] { index += 1 // Accumulating all digits until a possible exponent val begin = index - while (index <= last && charNotEqualTo(in(index), 'e', 'E')) { + while (index <= last && charNotEqualTo(in(index), Array('e', 'E'))) { if (!wasNonZero) { if (in(index) == '0') counter += 1 else wasNonZero = true @@ -420,7 +452,7 @@ class BigDecimal() extends Number with Comparable[BigDecimal] { } // An exponent was found - if ((index <= last) && charEqualTo(in(index), 'e', 'E')) { + if ((index <= last) && charEqualTo(in(index), Array('e', 'E'))) { index += 1 // Checking for a possible sign of scale val indexIsPlus = index <= last && in(index) == '+' @@ -792,7 +824,7 @@ class BigDecimal() extends Number with Comparable[BigDecimal] { val p = thisUnscaled.divide(gcd) val q1 = divisorUnscaled.divide(gcd) // To simplify all "2" factors of q, dividing by 2^k - val k = q1.getLowestSetBit // number of factors "2" in 'q' + val k = q1.getLowestSetBit() // number of factors "2" in 'q' @inline @tailrec @@ -811,7 +843,7 @@ class BigDecimal() extends Number with Comparable[BigDecimal] { val (q, l) = loop(1, q1.shiftRight(k), 0) // If abs(q) != 1 then the quotient is periodic - if (q.abs() != BigInteger.ONE) { + if (!q.abs().equals(BigInteger.ONE)) { throw new ArithmeticException( "Non-terminating decimal expansion; no exact representable decimal result") } @@ -1015,9 +1047,7 @@ class BigDecimal() extends Number with Comparable[BigDecimal] { if (resultPrecision > mcPrecision) throw new ArithmeticException("Division impossible") - integralValue._scale = safeLongToInt(finalScale) - integralValue.setUnscaledValue(strippedBI) - integralValue + new BigDecimal(strippedBI, safeLongToInt(finalScale)) // scalastyle:on return } @@ -1116,7 +1146,7 @@ class BigDecimal() extends Number with Comparable[BigDecimal] { else if (_smallValue > 0) 1 else 0 } else { - getUnscaledValue().signum() + getUnscaledValue.signum() } } @@ -1266,7 +1296,7 @@ class BigDecimal() extends Number with Comparable[BigDecimal] { case that: BigDecimal => that._scale == this._scale && ( if (_bitLength < 64) that._smallValue == this._smallValue - else this._intVal == that._intVal) + else this._intVal.equals(that._intVal)) case _ => false } @@ -1439,7 +1469,7 @@ class BigDecimal() extends Number with Comparable[BigDecimal] { getUnscaledValue.multiply(powerOf10(-_scale.toLong)) } else { // (scale > 0) // An optimization before do a heavy division - if (_scale > approxPrecision() || _scale > getUnscaledValue.getLowestSetBit) + if (_scale > approxPrecision() || _scale > getUnscaledValue.getLowestSetBit()) throw new ArithmeticException("Rounding necessary") val integerAndFraction = getUnscaledValue.divideAndRemainder(powerOf10(_scale)) @@ -1479,116 +1509,14 @@ class BigDecimal() extends Number with Comparable[BigDecimal] { def byteValueExact(): Byte = valueExact(8).toByte - override def floatValue(): Float = { - /* A similar code like in doubleValue() could be repeated here, - * but this simple implementation is quite efficient. */ - val powerOfTwo = this._bitLength - (_scale / Log2).toLong - val floatResult0: Float = signum().toFloat - val floatResult: Float = { - if (powerOfTwo < -149 || floatResult0 == 0.0f) // 'this' is very small - floatResult0 * 0.0f - else if (powerOfTwo > 129) // 'this' is very large - floatResult0 * Float.PositiveInfinity - else - doubleValue().toFloat - } - floatResult - } - - override def doubleValue(): Double = { - val sign = signum() - val powerOfTwo = this._bitLength - (_scale / Log2).toLong - - if (powerOfTwo < -1074 || sign == 0) { - // Cases which 'this' is very small - sign * 0.0d - } else if (powerOfTwo > 1025) { - // Cases which 'this' is very large - sign * Double.PositiveInfinity - } else { - val mantissa0 = getUnscaledValue.abs() - var exponent = 1076 // bias + 53 + @noinline override def floatValue(): Float = + java.lang.Float.parseFloat(toStringForFloatingPointValue()) - val mantissa = { - if (_scale <= 0) { - mantissa0.multiply(powerOf10(-_scale)) - } else { - val powerOfTen: BigInteger = powerOf10(_scale) - val k = 100 - powerOfTwo.toInt - val m = { - if (k > 0) { - /* Computing (mantissa * 2^k) , where 'k' is a enough big - * power of '2' to can divide by 10^s */ - exponent -= k - mantissa0.shiftLeft(k) - } else { - mantissa0 - } - } - // Computing (mantissa * 2^k) / 10^s - val qr = m.divideAndRemainderImpl(powerOfTen) - // To check if the fractional part >= 0.5 - val compRem = qr.rem.shiftLeftOneBit().compareTo(powerOfTen) - // To add two rounded bits at end of mantissa - exponent -= 2 - qr.quot.shiftLeft(2).add(BigInteger.valueOf((compRem * (compRem + 3)) / 2 + 1)) - } - } + @noinline override def doubleValue(): Double = + java.lang.Double.parseDouble(toStringForFloatingPointValue()) - val lowestSetBit = mantissa.getLowestSetBit - val discardedSize = mantissa.bitLength() - 54 - var bits: Long = 0L // IEEE-754 Standard - var tempBits: Long = 0L // for temporal calculations - if (discardedSize > 0) { // (#bits > 54) - bits = mantissa.shiftRight(discardedSize).longValue() - tempBits = bits - if (((bits & 1) == 1 && lowestSetBit < discardedSize) || (bits & 3) == 3) - bits += 2 - } else { // (#bits <= 54) - bits = mantissa.longValue() << -discardedSize - tempBits = bits - if ((bits & 3) == 3) - bits += 2 - } - // Testing bit 54 to check if the carry creates a new binary digit - if ((bits & 0x40000000000000L) == 0) { - // To drop the last bit of mantissa (first discarded) - bits >>= 1 - exponent += discardedSize - } else { - // #bits = 54 - bits >>= 2 - exponent += (discardedSize + 1) - } - // To test if the 53-bits number fits in 'double' - if (exponent > 2046) { - // (exponent - bias > 1023) - sign * Double.PositiveInfinity - } else if (exponent < -53) { - sign * 0.0d - } else { - if (exponent <= 0) { - bits = tempBits >> 1 - tempBits = bits & (-1L >>> (63 + exponent)) - bits >>= (-exponent) - // To test if after discard bits, a new carry is generated - if (((bits & 3) == 3) || - (((bits & 1) == 1) && (tempBits != 0) && (lowestSetBit < discardedSize))) { - bits += 1 - } - exponent = 0 - bits >>= 1 - } - - // Construct the 64 double bits: [sign(1), exponent(11), mantissa(52)] - val resultBits = - (sign & 0x8000000000000000L) | - (exponent.toLong << 52) | - (bits & 0xFFFFFFFFFFFFFL) - java.lang.Double.longBitsToDouble(resultBits) - } - } - } + @inline private def toStringForFloatingPointValue(): String = + s"${unscaledValue()}e${-scale()}" def ulp(): BigDecimal = valueOf(1, _scale) @@ -1672,7 +1600,7 @@ class BigDecimal() extends Number with Comparable[BigDecimal] { } } - private def isZero(): Boolean = _bitLength == 0 && this._smallValue != -1 + private def isZero: Boolean = _bitLength == 0 && this._smallValue != -1 private def movePoint(newScale: Long): BigDecimal = { def lptbLen = LongTenPowsBitLength(-newScale.toInt) @@ -1749,7 +1677,7 @@ class BigDecimal() extends Number with Comparable[BigDecimal] { */ private def valueExact(bitLengthOfType: Int): Long = { // Fast path to avoid some large BigInteger creations by toBigIntegerExact - if (-scale.toLong + approxPrecision() > 19) { + if (-scale().toLong + approxPrecision() > 19) { /* If there are more digits than the number of digits of Long.MaxValue in * base 10, this BigDecimal cannot possibly be an exact Long. */ @@ -1777,7 +1705,7 @@ class BigDecimal() extends Number with Comparable[BigDecimal] { else ((this._bitLength - 1) * Log2).toInt + 1 } - private def getUnscaledValue(): BigInteger = { + private def getUnscaledValue: BigInteger = { if (_intVal == null) _intVal = BigInteger.valueOf(_smallValue) _intVal diff --git a/javalib/src/main/scala/java/math/BigInteger.scala b/javalib/src/main/scala/java/math/BigInteger.scala index a9a0855736..59ce0d1c49 100644 --- a/javalib/src/main/scala/java/math/BigInteger.scala +++ b/javalib/src/main/scala/java/math/BigInteger.scala @@ -74,7 +74,12 @@ object BigInteger { new BigInteger(1, 4), new BigInteger(1, 5), new BigInteger(1, 6), new BigInteger(1, 7), new BigInteger(1, 8), new BigInteger(1, 9), TEN) - private final val TWO_POWS = Array.tabulate[BigInteger](32)(i => BigInteger.valueOf(1L << i)) + private final val TWO_POWS = { + val result = new Array[BigInteger](32) + for (i <- 0 until 32) + result(i) = BigInteger.valueOf(1L << i) + result + } /** The first non zero digit is either -1 if sign is zero, otherwise it is >= 0. * @@ -789,7 +794,7 @@ class BigInteger extends Number with Comparable[BigInteger] { // scalastyle:on return } - private[math] def getFirstNonzeroDigit(): Int = { + private[math] def getFirstNonzeroDigit: Int = { if (firstNonzeroDigit == firstNonzeroDigitNotSet) { firstNonzeroDigit = { if (this.sign == 0) { @@ -807,7 +812,7 @@ class BigInteger extends Number with Comparable[BigInteger] { } /** Tests if {@code this.abs()} is equals to {@code ONE}. */ - private[math] def isOne(): Boolean = + private[math] def isOne: Boolean = numberLength == 1 && digits(0) == 1 private[math] def shiftLeftOneBit(): BigInteger = { diff --git a/javalib/src/main/scala/java/math/Conversion.scala b/javalib/src/main/scala/java/math/Conversion.scala index dacf373c58..cb8c233ef5 100644 --- a/javalib/src/main/scala/java/math/Conversion.scala +++ b/javalib/src/main/scala/java/math/Conversion.scala @@ -252,10 +252,10 @@ private[math] object Conversion { result = (prev - v * 10).toInt.toString + result } while (v != 0) - val exponent = resLengthInChars - currentChar - scale - 1 + val exponent: Long = resLengthInChars - currentChar - scale.toLong - 1 - if (scale > 0 && exponent >= -6) { - val index = exponent + 1 + if (scale > 0 && exponent >= -6L) { + val index = exponent.toInt + 1 if (index > 0) { // special case 1 result = result.substring(0, index) + "." + result.substring(index) @@ -266,54 +266,20 @@ private[math] object Conversion { } result = "0." + result } - } else if (scale !=0) { - var result1 = exponent.toString - if (exponent > 0) - result1 = "+" + result1 - result1 = "E" + result1 + } else if (scale != 0) { + val exponentStr = + if (exponent > 0) "E+" + exponent + else "E" + exponent result = if (resLengthInChars - currentChar > 1) - result.substring(0, 1) + "." + result.substring(1) + result1 + result.substring(0, 1) + "." + result.substring(1) + exponentStr else - result + result1 + result + exponentStr } if (negNumber) "-" + result else result } } - - def bigInteger2Double(bi: BigInteger): Double = { - if (bi.numberLength < 2 || ((bi.numberLength == 2) && (bi.digits(1) > 0))) { - bi.longValue().toDouble - } else if (bi.numberLength > 32) { - if (bi.sign > 0) Double.PositiveInfinity - else Double.NegativeInfinity - } else { - val bitLen = bi.abs().bitLength() - var exponent: Long = bitLen - 1 - val delta = bitLen - 54 - val lVal = bi.abs().shiftRight(delta).longValue() - var mantissa = lVal & 0x1FFFFFFFFFFFFFL - - if (exponent == 1023 && mantissa == 0X1FFFFFFFFFFFFFL) { - if (bi.sign > 0) Double.PositiveInfinity - else Double.NegativeInfinity - } else if (exponent == 1023 && mantissa == 0x1FFFFFFFFFFFFEL) { - if (bi.sign > 0) Double.MaxValue - else -Double.MaxValue - } else { - val droppedBits = BitLevel.nonZeroDroppedBits(delta, bi.digits) - if (((mantissa & 1) == 1) && (((mantissa & 2) == 2) || droppedBits)) - mantissa += 2 - - mantissa >>= 1 - val resSign = if (bi.sign < 0) 0x8000000000000000L else 0 - exponent = ((1023 + exponent) << 52) & 0x7FF0000000000000L - val result = resSign | exponent | mantissa - java.lang.Double.longBitsToDouble(result) - } - } - } } diff --git a/javalib/src/main/scala/java/math/Division.scala b/javalib/src/main/scala/java/math/Division.scala index d52a2f4366..a69382135b 100644 --- a/javalib/src/main/scala/java/math/Division.scala +++ b/javalib/src/main/scala/java/math/Division.scala @@ -253,7 +253,7 @@ private[math] object Division { def evenModPow(base: BigInteger, exponent: BigInteger, modulus: BigInteger): BigInteger = { // STEP 1: Obtain the factorization 'modulus'= q * 2^j. - val j = modulus.getLowestSetBit + val j = modulus.getLowestSetBit() val q = modulus.shiftRight(j) // STEP 2: Compute x1 := base^exponent (mod q). @@ -319,8 +319,8 @@ private[math] object Division { * Divide both number the maximal possible times by 2 without rounding * gcd(2*a, 2*b) = 2 * gcd(a,b) */ - val lsb1 = op1.getLowestSetBit - val lsb2 = op2.getLowestSetBit + val lsb1 = op1.getLowestSetBit() + val lsb2 = op2.getLowestSetBit() val pow2Count = Math.min(lsb1, lsb2) BitLevel.inplaceShiftRight(op1, lsb1) BitLevel.inplaceShiftRight(op2, lsb2) @@ -347,21 +347,21 @@ private[math] object Division { if (op2.numberLength > op1.numberLength * 1.2) { op2 = op2.remainder(op1) if (op2.signum() != 0) { - BitLevel.inplaceShiftRight(op2, op2.getLowestSetBit) + BitLevel.inplaceShiftRight(op2, op2.getLowestSetBit()) } } else { // Use Knuth's algorithm of successive subtract and shifting do { Elementary.inplaceSubtract(op2, op1) - BitLevel.inplaceShiftRight(op2, op2.getLowestSetBit) - } while (op2.compareTo(op1) >= BigInteger.EQUALS); + BitLevel.inplaceShiftRight(op2, op2.getLowestSetBit()) + } while (op2.compareTo(op1) >= BigInteger.EQUALS) } // now op1 >= op2 val swap: BigInteger = op2 op2 = op1 op1 = swap if (op1.sign != 0) - loop + loop() } } @@ -529,8 +529,8 @@ private[math] object Division { s.digits(0) = 1 var k = 0 - val lsbu = u.getLowestSetBit - val lsbv = v.getLowestSetBit + val lsbu = u.getLowestSetBit() + val lsbv = v.getLowestSetBit() if (lsbu > lsbv) { BitLevel.inplaceShiftRight(u, lsbu) BitLevel.inplaceShiftRight(v, lsbv) @@ -547,7 +547,7 @@ private[math] object Division { while (v.signum() > 0) { while (u.compareTo(v) > BigInteger.EQUALS) { Elementary.inplaceSubtract(u, v) - val toShift = u.getLowestSetBit + val toShift = u.getLowestSetBit() BitLevel.inplaceShiftRight(u, toShift) Elementary.inplaceAdd(r, s) BitLevel.inplaceShiftLeft(s, toShift) @@ -560,7 +560,7 @@ private[math] object Division { if (u.compareTo(v) <= BigInteger.EQUALS) { Elementary.inplaceSubtract(v, u) if (v.signum() != 0) { - val toShift = v.getLowestSetBit + val toShift = v.getLowestSetBit() BitLevel.inplaceShiftRight(v, toShift) Elementary.inplaceAdd(s, r) BitLevel.inplaceShiftLeft(r, toShift) @@ -854,7 +854,7 @@ private[math] object Division { while (bi.testBit(i)) { i -= 1 } - n - 1 - Math.max(i, bi.getLowestSetBit) + n - 1 - Math.max(i, bi.getLowestSetBit()) } } @@ -884,11 +884,14 @@ private[math] object Division { for (i <- 0 until modulusLen) { var innnerCarry: Int = 0 // unsigned val m = Multiplication.unsignedMultAddAdd(res(i), n2, 0, 0).toInt - for (j <- 0 until modulusLen) { + // Work around Scala 2.11 limitation with the IR cleaner ; should be for (j <- 0 until modulusLen) + var j = 0 + while (j < modulusLen) { val nextInnnerCarry = unsignedMultAddAdd(m, modulusDigits(j), res(i + j), innnerCarry) res(i + j) = nextInnnerCarry.toInt innnerCarry = (nextInnnerCarry >> 32).toInt + j += 1 } val nextOuterCarry = (outerCarry & UINT_MAX) + (res(i + modulusLen) & UINT_MAX) + (innnerCarry & UINT_MAX) diff --git a/javalib/src/main/scala/java/math/Logical.scala b/javalib/src/main/scala/java/math/Logical.scala index 62dc37493f..7f40b12da6 100644 --- a/javalib/src/main/scala/java/math/Logical.scala +++ b/javalib/src/main/scala/java/math/Logical.scala @@ -44,7 +44,7 @@ private[math] object Logical { // scalastyle:off return if (bi.sign == 0) { BigInteger.MINUS_ONE - } else if (bi == BigInteger.MINUS_ONE) { + } else if (bi.equals(BigInteger.MINUS_ONE)) { BigInteger.ZERO } else { val resDigits = new Array[Int](bi.numberLength + 1) @@ -88,9 +88,9 @@ private[math] object Logical { def and(bi: BigInteger, that: BigInteger): BigInteger = { if (that.sign == 0 || bi.sign == 0) BigInteger.ZERO - else if (that == BigInteger.MINUS_ONE) + else if (that.equals(BigInteger.MINUS_ONE)) bi - else if (bi == BigInteger.MINUS_ONE) + else if (bi.equals(BigInteger.MINUS_ONE)) that else if (bi.sign > 0 && that.sign > 0) andPositive(bi, that) @@ -235,9 +235,9 @@ private[math] object Logical { bi else if (bi.sign == 0) BigInteger.ZERO - else if (bi == BigInteger.MINUS_ONE) + else if (bi.equals(BigInteger.MINUS_ONE)) that.not() - else if (that == BigInteger.MINUS_ONE) + else if (that.equals(BigInteger.MINUS_ONE)) BigInteger.ZERO else if (bi.sign > 0 && that.sign > 0) andNotPositive(bi, that) @@ -446,7 +446,7 @@ private[math] object Logical { /** @see BigInteger#or(BigInteger) */ def or(bi: BigInteger, that: BigInteger): BigInteger = { - if (that == BigInteger.MINUS_ONE || bi == BigInteger.MINUS_ONE) { + if (that.equals(BigInteger.MINUS_ONE) || bi.equals(BigInteger.MINUS_ONE)) { BigInteger.MINUS_ONE } else if (that.sign == 0) { bi @@ -593,9 +593,9 @@ private[math] object Logical { bi } else if (bi.sign == 0) { that - } else if (that == BigInteger.MINUS_ONE) { + } else if (that.equals(BigInteger.MINUS_ONE)) { bi.not() - } else if (bi == BigInteger.MINUS_ONE) { + } else if (bi.equals(BigInteger.MINUS_ONE)) { that.not() } else if (bi.sign > 0) { if (that.sign > 0) { diff --git a/javalib/src/main/scala/java/math/Multiplication.scala b/javalib/src/main/scala/java/math/Multiplication.scala index 9f0ca4188e..10ecb738cc 100644 --- a/javalib/src/main/scala/java/math/Multiplication.scala +++ b/javalib/src/main/scala/java/math/Multiplication.scala @@ -124,10 +124,13 @@ private[math] object Multiplication { for (i <- 0 until aLen) { carry = 0 - for (j <- i + 1 until aLen) { + // Work around Scala 2.11 limitation with the IR cleaner ; should be for (j <- i + 1 until aLen) + var j = i + 1 + while (j < aLen) { val t = unsignedMultAddAdd(a(i), a(j), res(i + j), carry) res(i + j) = t.toInt carry = (t >>> 32).toInt + j += 1 } res(i + aLen) = carry } @@ -439,16 +442,24 @@ private[math] object Multiplication { for (i <- 0 until aLen) { var carry = 0 val aI = a(i) - for (j <- 0 until bLen) { + // Work around Scala 2.11 limitation with the IR cleaner ; should be for (j <- 0 until bLen) + var j = 0 + while (j < bLen) { val added = unsignedMultAddAdd(aI, b(j), t(i + j), carry) t(i + j) = added.toInt carry = (added >>> 32).toInt + j += 1 } t(i + bLen) = carry } } } - private def newArrayOfPows(len: Int, pow: Int): Array[Int] = - Array.iterate(1, len)(_ * pow) + private def newArrayOfPows(len: Int, pow: Int): Array[Int] = { + val result = new Array[Int](len) + result(0) = 1 + for (i <- 1 until len) + result(i) = result(i - 1) * pow + result + } } diff --git a/javalib/src/main/scala/java/math/Primality.scala b/javalib/src/main/scala/java/math/Primality.scala index 06e8bf2752..b7fd19101b 100644 --- a/javalib/src/main/scala/java/math/Primality.scala +++ b/javalib/src/main/scala/java/math/Primality.scala @@ -79,8 +79,13 @@ private[math] object Primality { (18, 13), (31, 23), (54, 43), (97, 75)) /** All {@code BigInteger} prime numbers with bit length lesser than 8 bits. */ - private val BiPrimes = - Array.tabulate[BigInteger](Primes.length)(i => BigInteger.valueOf(Primes(i))) + private val BiPrimes = { + val len = Primes.length + val result = new Array[BigInteger](len) + for (i <- 0 until len) + result(i) = BigInteger.valueOf(Primes(i)) + result + } /** A random number is generated until a probable prime number is found. * @@ -134,13 +139,15 @@ private[math] object Primality { Arrays.binarySearch(Primes, n.digits(0)) >= 0 } else { // To check if 'n' is divisible by some prime of the table - for (i <- 1 until Primes.length) { + var i: Int = 1 + val primesLength = Primes.length + while (i != primesLength) { if (Division.remainderArrayByInt(n.digits, n.numberLength, Primes(i)) == 0) return false + i += 1 } // To set the number of iterations necessary for Miller-Rabin test - var i: Int = 0 val bitLength = n.bitLength() i = 2 while (bitLength < Bits(i)) { @@ -218,13 +225,15 @@ private[math] object Primality { } } // To execute Miller-Rabin for non-divisible numbers by all first primes - for (j <- 0 until gapSize) { + var j = 0 + while (j != gapSize) { if (!isDivisible(j)) { Elementary.inplaceAdd(probPrime, j) if (millerRabin(probPrime, certainty)) { return probPrime } } + j += 1 } Elementary.inplaceAdd(startPoint, gapSize) } @@ -248,16 +257,18 @@ private[math] object Primality { var y: BigInteger = null val nMinus1 = n.subtract(BigInteger.ONE) val bitLength = nMinus1.bitLength() - val k = nMinus1.getLowestSetBit + val k = nMinus1.getLowestSetBit() val q = nMinus1.shiftRight(k) val rnd = new Random() - for (i <- 0 until t) { + + var i = 0 + while (i != t) { // To generate a witness 'x', first it use the primes of table if (i < Primes.length) { x = BiPrimes(i) } else { /* - * It generates random witness only if it's necesssary. Note that all + * It generates random witness only if it's necessary. Note that all * methods would call Miller-Rabin with t <= 50 so this part is only to * do more robust the algorithm */ @@ -267,17 +278,21 @@ private[math] object Primality { } y = x.modPow(q, n) - if (!(y.isOne || y == nMinus1)) { - for (j <- 1 until k) { - if (y != nMinus1) { + if (!(y.isOne || y.equals(nMinus1))) { + var j = 1 + while (j != k) { + if (!y.equals(nMinus1)) { y = y.multiply(y).mod(n) if (y.isOne) return false } + j += 1 } - if (y != nMinus1) + if (!y.equals(nMinus1)) return false } + + i += 1 } true // scalastyle:on return diff --git a/javalib/src/main/scala/java/math/RoundingMode.scala b/javalib/src/main/scala/java/math/RoundingMode.scala index afc7c3567a..58d800f71a 100644 --- a/javalib/src/main/scala/java/math/RoundingMode.scala +++ b/javalib/src/main/scala/java/math/RoundingMode.scala @@ -58,7 +58,7 @@ object RoundingMode { var i = 0 while (i != len) { val value = values(i) - if (value.name == name) + if (value.name() == name) return value i += 1 } diff --git a/javalib/src/main/scala/java/net/URI.scala b/javalib/src/main/scala/java/net/URI.scala index 522be63b61..cb19355b36 100644 --- a/javalib/src/main/scala/java/net/URI.scala +++ b/javalib/src/main/scala/java/net/URI.scala @@ -17,6 +17,7 @@ import scala.scalajs.js import scala.annotation.tailrec +import java.lang.Utils._ import java.nio._ import java.nio.charset.{CodingErrorAction, StandardCharsets} @@ -31,42 +32,64 @@ final class URI(origStr: String) extends Serializable with Comparable[URI] { * This is a local val for the primary constructor. It is a val, * since we'll set it to null after initializing all fields. */ - private[this] var _fld = Option(URI.uriRe.exec(origStr)).getOrElse { + private[this] var _fld: RegExp.ExecResult = URI.uriRe.exec(origStr) + if (_fld == null) throw new URISyntaxException(origStr, "Malformed URI") - } - private val _isAbsolute = fld(AbsScheme).isDefined - private val _isOpaque = fld(AbsOpaquePart).isDefined + private val _isAbsolute = undefOrIsDefined(_fld(AbsScheme)) + private val _isOpaque = undefOrIsDefined(_fld(AbsOpaquePart)) - @inline private def fld(idx: Int): js.UndefOr[String] = _fld(idx) + @inline private def fld(idx: Int): String = undefOrGetOrNull(_fld(idx)) - @inline private def fld(absIdx: Int, relIdx: Int): js.UndefOr[String] = - if (_isAbsolute) _fld(absIdx) else _fld(relIdx) + @inline private def fld(absIdx: Int, relIdx: Int): String = + if (_isAbsolute) fld(absIdx) else fld(relIdx) + /** Nullable */ private val _scheme = fld(AbsScheme) + /** Non-nullable */ private val _schemeSpecificPart = { if (!_isAbsolute) fld(RelSchemeSpecificPart) else if (_isOpaque) fld(AbsOpaquePart) else fld(AbsHierPart) - }.get + } + + /** Nullable */ + private val _authority = { + val authPart = fld(AbsAuthority, RelAuthority) + if (authPart == "") null else authPart + } - private val _authority = fld(AbsAuthority, RelAuthority).filter(_ != "") + /** Nullable */ private val _userInfo = fld(AbsUserInfo, RelUserInfo) + + /** Nullable */ private val _host = fld(AbsHost, RelHost) - private val _port = fld(AbsPort, RelPort).map(Integer.parseInt(_)) + /** `-1` means not present */ + private val _port = { + val portPart = fld(AbsPort, RelPort) + if (portPart == null) -1 else Integer.parseInt(portPart) + } + + /** Nullable */ private val _path = { - val useNetPath = fld(AbsAuthority, RelAuthority).isDefined - if (useNetPath) - fld(AbsNetPath, RelNetPath) orElse "" - else if (_isAbsolute) + val useNetPath = fld(AbsAuthority, RelAuthority) != null + if (useNetPath) { + val netPath = fld(AbsNetPath, RelNetPath) + if (netPath == null) "" else netPath + } else if (_isAbsolute) { fld(AbsAbsPath) - else - fld(RelAbsPath) orElse fld(RelRelPath) + } else { + val relAbsPath = fld(RelAbsPath) + if (relAbsPath != null) relAbsPath else fld(RelRelPath) + } } + /** Nullable */ private val _query = fld(AbsQuery, RelQuery) + + /** Nullable */ private val _fragment = fld(Fragment) // End of default ctor. Unset helper field @@ -93,37 +116,26 @@ final class URI(origStr: String) extends Serializable with Comparable[URI] { // parseServerAuthority() } - /** Compare this URI to another URI while supplying a comparator - * - * This helper is required to account for the semantic differences - * between [[compareTo]] and [[equals]]. ([[equals]] does treat - * URI escapes specially: they are never case-sensitive). - */ - @inline - private def internalCompare(that: URI)(cmp: (String, String) => Int): Int = { - @inline - def cmpOpt[T](x: js.UndefOr[T], y: js.UndefOr[T])(comparator: (T, T) => Int): Int = { - if (x == y) 0 - // Undefined components are considered less than defined components - else x.fold(-1)(s1 => y.fold(1)(s2 => comparator(s1, s2))) - } + def compareTo(that: URI): Int = { + import URI.{caseInsensitiveCompare, escapeAwareCompare => cmp} + def comparePathQueryFragement(): Int = { - val cmpPath = cmpOpt(this._path, that._path)(cmp) + val cmpPath = cmp(this._path, that._path) if (cmpPath != 0) { cmpPath } else { - val cmpQuery = cmpOpt(this._query, that._query)(cmp) + val cmpQuery = cmp(this._query, that._query) if (cmpQuery != 0) cmpQuery - else cmpOpt(this._fragment, that._fragment)(cmp) + else cmp(this._fragment, that._fragment) } } - val cmpScheme = cmpOpt(this._scheme, that._scheme)(_.compareToIgnoreCase(_)) + val cmpScheme = caseInsensitiveCompare(this._scheme, that._scheme) if (cmpScheme != 0) { cmpScheme } else { // A hierarchical URI is less than an opaque URI - val cmpIsOpaque = java.lang.Boolean.compare(this.isOpaque, that.isOpaque) + val cmpIsOpaque = java.lang.Boolean.compare(this.isOpaque(), that.isOpaque()) if (cmpIsOpaque != 0) { cmpIsOpaque } else { @@ -131,22 +143,22 @@ final class URI(origStr: String) extends Serializable with Comparable[URI] { val cmpSchemeSpecificPart = cmp(this._schemeSpecificPart, that._schemeSpecificPart) if (cmpSchemeSpecificPart != 0) cmpSchemeSpecificPart else comparePathQueryFragement() - } else if (this._host.isDefined && that._host.isDefined) { - val cmpUserInfo = cmpOpt(this._userInfo, that._userInfo)(cmp) + } else if (this._host != null && that._host != null) { + val cmpUserInfo = cmp(this._userInfo, that._userInfo) if (cmpUserInfo != 0) { cmpUserInfo } else { - val cmpHost = cmpOpt(this._host, that._host)(_.compareToIgnoreCase(_)) + val cmpHost = caseInsensitiveCompare(this._host, that._host) if (cmpHost != 0) { cmpHost } else { - val cmpPort = cmpOpt(this._port, that._port)(_ - _) + val cmpPort = this._port - that._port // absent as -1 is smaller than valid port numbers if (cmpPort != 0) cmpPort else comparePathQueryFragement() } } } else { - val cmpAuthority = cmpOpt(this._authority, that._authority)(cmp) + val cmpAuthority = cmp(this._authority, that._authority) if (cmpAuthority != 0) cmpAuthority else comparePathQueryFragement() } @@ -154,62 +166,64 @@ final class URI(origStr: String) extends Serializable with Comparable[URI] { } } - def compareTo(that: URI): Int = internalCompare(that)(_.compareTo(_)) - override def equals(that: Any): Boolean = that match { - case that: URI => internalCompare(that)(URI.escapeAwareCompare) == 0 + case that: URI => this.compareTo(that) == 0 case _ => false } - def getAuthority(): String = _authority.map(decodeComponent).orNull - def getFragment(): String = _fragment.map(decodeComponent).orNull - def getHost(): String = _host.orNull - def getPath(): String = _path.map(decodeComponent).orNull - def getPort(): Int = _port.getOrElse(-1) - def getQuery(): String = _query.map(decodeComponent).orNull - def getRawAuthority(): String = _authority.orNull - def getRawFragment(): String = _fragment.orNull - def getRawPath(): String = _path.orNull - def getRawQuery(): String = _query.orNull + def getAuthority(): String = decodeComponent(_authority) + def getFragment(): String = decodeComponent(_fragment) + def getHost(): String = _host + def getPath(): String = decodeComponent(_path) + def getPort(): Int = _port + def getQuery(): String = decodeComponent(_query) + def getRawAuthority(): String = _authority + def getRawFragment(): String = _fragment + def getRawPath(): String = _path + def getRawQuery(): String = _query def getRawSchemeSpecificPart(): String = _schemeSpecificPart - def getRawUserInfo(): String = _userInfo.orNull - def getScheme(): String = _scheme.orNull + def getRawUserInfo(): String = _userInfo + def getScheme(): String = _scheme def getSchemeSpecificPart(): String = decodeComponent(_schemeSpecificPart) - def getUserInfo(): String = _userInfo.map(decodeComponent).orNull + def getUserInfo(): String = decodeComponent(_userInfo) override def hashCode(): Int = { - import scala.util.hashing.MurmurHash3._ + import java.util.internal.MurmurHash3._ import URI.normalizeEscapes + def normalizeEscapesHash(str: String): Int = + if (str == null) 0 + else normalizeEscapes(str).hashCode() + var acc = URI.uriSeed - acc = mix(acc, _scheme.map(_.toLowerCase).##) // scheme may not contain escapes + acc = mix(acc, if (_scheme == null) 0 else _scheme.toLowerCase.hashCode()) // scheme may not contain escapes if (this.isOpaque()) { - acc = mix(acc, normalizeEscapes(this._schemeSpecificPart).##) - } else if (this._host.isDefined) { - acc = mix(acc, normalizeEscapes(this._userInfo).##) - acc = mix(acc, this._host.map(_.toLowerCase).##) - acc = mix(acc, this._port.##) + acc = mix(acc, normalizeEscapesHash(this._schemeSpecificPart)) + } else if (this._host != null) { + acc = mix(acc, normalizeEscapesHash(this._userInfo)) + acc = mix(acc, this._host.toLowerCase.hashCode()) + acc = mix(acc, this._port.hashCode()) } else { - acc = mix(acc, normalizeEscapes(this._authority).##) + acc = mix(acc, normalizeEscapesHash(this._authority)) } - acc = mix(acc, normalizeEscapes(this._path).##) - acc = mix(acc, normalizeEscapes(this._query).##) - acc = mixLast(acc, normalizeEscapes(this._fragment).##) + acc = mix(acc, normalizeEscapesHash(this._path)) + acc = mix(acc, normalizeEscapesHash(this._query)) + acc = mixLast(acc, normalizeEscapesHash(this._fragment)) finalizeHash(acc, 3) } def isAbsolute(): Boolean = _isAbsolute def isOpaque(): Boolean = _isOpaque - def normalize(): URI = if (_isOpaque || _path.isEmpty) this else { + def normalize(): URI = if (_isOpaque || _path == null) this else { import js.JSStringOps._ - val origPath = _path.get + val origPath = _path val segments = origPath.jsSplit("/") // Step 1: Remove all "." segments - // Step 2: Remove ".." segments preceeded by non ".." segment until no + // Step 2: Remove ".." segments preceded by non ".." segment until no // longer applicable val inLen = segments.length @@ -284,19 +298,16 @@ final class URI(origStr: String) extends Serializable with Comparable[URI] { } def parseServerAuthority(): URI = { - if (_authority.nonEmpty && _host.isEmpty) + if (_authority != null && _host == null) throw new URISyntaxException(origStr, "No Host in URI") else this } def relativize(uri: URI): URI = { - def authoritiesEqual = this._authority.fold(uri._authority.isEmpty) { a1 => - uri._authority.fold(false)(a2 => URI.escapeAwareCompare(a1, a2) == 0) - } - - if (this.isOpaque || uri.isOpaque || - this._scheme != uri._scheme || !authoritiesEqual) uri - else { + if (this.isOpaque() || uri.isOpaque() || this._scheme != uri._scheme || + URI.escapeAwareCompare(this._authority, uri._authority) != 0) { + uri + } else { val thisN = this.normalize() val uriN = uri.normalize() @@ -316,8 +327,8 @@ final class URI(origStr: String) extends Serializable with Comparable[URI] { def resolve(uri: URI): URI = { if (uri.isAbsolute() || this.isOpaque()) uri - else if (uri._scheme.isEmpty && uri._authority.isEmpty && - uri._path.get == "" && uri._query.isEmpty) + else if (uri._scheme == null && uri._authority == null && + uri._path == "" && uri._query == null) // This is a special case for URIs like: "#foo". This allows to // just change the fragment in the current document. new URI( @@ -326,14 +337,14 @@ final class URI(origStr: String) extends Serializable with Comparable[URI] { this.getRawPath(), this.getRawQuery(), uri.getRawFragment()) - else if (uri._authority.isDefined) + else if (uri._authority != null) new URI( this.getScheme(), uri.getRawAuthority(), uri.getRawPath(), uri.getRawQuery(), uri.getRawFragment()) - else if (uri._path.get.startsWith("/")) + else if (uri._path.startsWith("/")) new URI( this.getScheme(), this.getRawAuthority(), @@ -341,8 +352,8 @@ final class URI(origStr: String) extends Serializable with Comparable[URI] { uri.getRawQuery(), uri.getRawFragment()) else { - val basePath = this._path.get - val relPath = uri._path.get + val basePath = this._path + val relPath = uri._path val endIdx = basePath.lastIndexOf('/') val path = if (endIdx == -1) relPath @@ -685,15 +696,15 @@ object URI { // scalastyle:on return } - // Fast-track, if no encoded components - if (containsNoEncodedComponent()) { + // Fast-track, if null or no encoded components + if (str == null || containsNoEncodedComponent()) { str } else { val inBuf = CharBuffer.wrap(str) - val outBuf = CharBuffer.allocate(inBuf.capacity) + val outBuf = CharBuffer.allocate(inBuf.capacity()) val byteBuf = ByteBuffer.allocate(64) var decoding = false - val decoder = StandardCharsets.UTF_8.newDecoder + val decoder = StandardCharsets.UTF_8.newDecoder() .onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE) @@ -709,10 +720,10 @@ object URI { } } - while (inBuf.hasRemaining) { + while (inBuf.hasRemaining()) { inBuf.get() match { case '%' => - if (!byteBuf.hasRemaining) + if (!byteBuf.hasRemaining()) decode(false) // get two chars - they must exist, otherwise the URI would not have @@ -741,8 +752,8 @@ object URI { val buf = StandardCharsets.UTF_8.encode(str) var res = "" - while (buf.hasRemaining) { - val c = buf.get & 0xff + while (buf.hasRemaining()) { + val c = buf.get() & 0xff res += (if (c <= 0xf) "%0" else "%") + Integer.toHexString(c).toUpperCase } @@ -829,9 +840,23 @@ object URI { str.jsReplace(nonASCIIQuoteRe, quoteStr) } + /** Case-insensitive comparison that accepts `null` values. + * + * `null` is considered smaller than any other value. + */ + private def caseInsensitiveCompare(x: String, y: String): Int = { + if (x == null) + if (y == null) 0 else -1 + else + if (y == null) 1 else x.compareToIgnoreCase(y) + } + /** Case-sensitive comparison that is case-insensitive inside URI * escapes. Will compare `a%A0` and `a%a0` as equal, but `a%A0` and * `A%A0` as different. + * + * Accepts `null` arguments. `null` is considered smaller than any other + * value. */ private def escapeAwareCompare(x: String, y: String): Int = { @tailrec @@ -853,12 +878,17 @@ object URI { } } - loop(0) + if (x == null) + if (y == null) 0 else -1 + else + if (y == null) 1 else loop(0) } - /** Upper-cases all URI escape sequences in `str`. Used for hashing */ - private def normalizeEscapes(maybeStr: js.UndefOr[String]): js.UndefOr[String] = { - maybeStr.map { str => + /** Upper-cases all URI escape sequences in the nullable `str`. Used for hashing */ + private def normalizeEscapes(str: String): String = { + if (str == null) { + null + } else { var i = 0 var res = "" while (i < str.length) { diff --git a/javalib/src/main/scala/java/net/URLDecoder.scala b/javalib/src/main/scala/java/net/URLDecoder.scala index 64a07837e7..5bf068cf36 100644 --- a/javalib/src/main/scala/java/net/URLDecoder.scala +++ b/javalib/src/main/scala/java/net/URLDecoder.scala @@ -12,36 +12,31 @@ package java.net +import scala.scalajs.js + import java.io.UnsupportedEncodingException import java.nio.{CharBuffer, ByteBuffer} -import java.nio.charset.{Charset, MalformedInputException} +import java.nio.charset.{Charset, CharsetDecoder} object URLDecoder { @Deprecated - def decode(s: String): String = decodeImpl(s, Charset.defaultCharset) + def decode(s: String): String = decode(s, Charset.defaultCharset()) def decode(s: String, enc: String): String = { - /* An exception is thrown only if the - * character encoding needs to be consulted - */ - lazy val charset = { - if (!Charset.isSupported(enc)) - throw new UnsupportedEncodingException(enc) - else - Charset.forName(enc) - } - - decodeImpl(s, charset) + if (!Charset.isSupported(enc)) + throw new UnsupportedEncodingException(enc) + decode(s, Charset.forName(enc)) } - private def decodeImpl(s: String, charset: => Charset): String = { + def decode(s: String, charset: Charset): String = { val len = s.length - lazy val charsetDecoder = charset.newDecoder() - - lazy val byteBuffer = ByteBuffer.allocate(len / 3) val charBuffer = CharBuffer.allocate(len) + // For charset-based decoding + var decoder: CharsetDecoder = null + var byteBuffer: ByteBuffer = null + def throwIllegalHex() = { throw new IllegalArgumentException( "URLDecoder: Illegal hex characters in escape (%) pattern") @@ -58,10 +53,13 @@ object URLDecoder { throwIllegalHex() case '%' => - val decoder = charsetDecoder - val buffer = byteBuffer - buffer.clear() - decoder.reset() + if (decoder == null) { // equivalent to `byteBuffer == null` + decoder = charset.newDecoder() + byteBuffer = ByteBuffer.allocate(len / 3) + } else { + byteBuffer.clear() + decoder.reset() + } while (i + 3 <= len && s.charAt(i) == '%') { val c1 = Character.digit(s.charAt(i + 1), 16) @@ -70,15 +68,15 @@ object URLDecoder { if (c1 < 0 || c2 < 0) throwIllegalHex() - buffer.put(((c1 << 4) + c2).toByte) + byteBuffer.put(((c1 << 4) + c2).toByte) i += 3 } - buffer.flip() - val decodeResult = decoder.decode(buffer, charBuffer, true) + byteBuffer.flip() + val decodeResult = decoder.decode(byteBuffer, charBuffer, true) val flushResult = decoder.flush(charBuffer) - if (decodeResult.isError || flushResult.isError) + if (decodeResult.isError() || flushResult.isError()) throwIllegalHex() case c => diff --git a/javalib/src/main/scala/java/net/URLEncoder.scala b/javalib/src/main/scala/java/net/URLEncoder.scala new file mode 100644 index 0000000000..1f9d200b50 --- /dev/null +++ b/javalib/src/main/scala/java/net/URLEncoder.scala @@ -0,0 +1,121 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.net + +import scala.annotation.switch + +import java.io.UnsupportedEncodingException +import java.nio.{CharBuffer, ByteBuffer} +import java.nio.charset.{Charset, CharsetDecoder} + +import java.util.ScalaOps._ +import java.nio.charset.CodingErrorAction + +object URLEncoder { + private final val EncodeAsIsLength = 128 + + private val EncodedAsIs: Array[Boolean] = { + val r = new Array[Boolean](EncodeAsIsLength) // initialized with false + r('.') = true + r('-') = true + r('*') = true + r('_') = true + for (c <- '0'.toInt to '9'.toInt) + r(c) = true + for (c <- 'A'.toInt to 'Z'.toInt) + r(c) = true + for (c <- 'a'.toInt to 'z'.toInt) + r(c) = true + r + } + + private val PercentEncoded: Array[String] = { + val hexDigits = "0123456789ABCDEF" + val r = new Array[String](256) + for (b <- 0 until 256) + r(b) = "%" + hexDigits.charAt(b >>> 4) + hexDigits.charAt(b & 0xf) + r + } + + @Deprecated + def encode(s: String): String = encode(s, Charset.defaultCharset()) + + def encode(s: String, enc: String): String = { + if (!Charset.isSupported(enc)) + throw new UnsupportedEncodingException(enc) + encode(s, Charset.forName(enc)) + } + + def encode(s: String, charset: Charset): String = { + val EncodedAsIs = this.EncodedAsIs // local copy + + @inline def encodeAsIs(c: Char): Boolean = + c < EncodeAsIsLength && EncodedAsIs(c) + + @inline def encodeUsingCharset(c: Char): Boolean = + c != ' ' && !encodeAsIs(c) + + var len = s.length() + var i = 0 + + while (i != len && encodeAsIs(s.charAt(i))) + i += 1 + + if (i == len) { + s + } else { + val PercentEncoded = this.PercentEncoded // local copy + + val charBuffer = CharBuffer.wrap(s) + val encoder = charset.newEncoder().onUnmappableCharacter(CodingErrorAction.REPLACE) + val bufferArray = new Array[Byte](((len - i + 1) * encoder.maxBytesPerChar()).toInt) + val buffer = ByteBuffer.wrap(bufferArray) + + var result = s.substring(0, i) + + while (i != len) { + val startOfChunk = i + val firstChar = s.charAt(startOfChunk) + i += 1 + + if (encodeAsIs(firstChar)) { + // A chunk of characters encoded as is + while (i != len && encodeAsIs(s.charAt(i))) + i += 1 + result += s.substring(startOfChunk, i) + } else if (firstChar == ' ') { + // A single ' ' + result += "+" + } else { + /* A chunk of characters to encode using the charset. + * + * Encoding as big a chunk as possible is not only good for + * performance. It allows us to deal with surrogate pairs without + * additional logic. + */ + while (i != len && encodeUsingCharset(s.charAt(i))) + i += 1 + charBuffer.limit(i) // must be done before setting position + charBuffer.position(startOfChunk) + buffer.rewind() + encoder.reset().encode(charBuffer, buffer, true) + for (j <- 0 until buffer.position()) + result += PercentEncoded(bufferArray(j) & 0xff) + } + } + + result + } + } + +} diff --git a/javalib/src/main/scala/java/nio/Buffer.scala b/javalib/src/main/scala/java/nio/Buffer.scala index 8ce5babf28..2913e96650 100644 --- a/javalib/src/main/scala/java/nio/Buffer.scala +++ b/javalib/src/main/scala/java/nio/Buffer.scala @@ -12,6 +12,8 @@ package java.nio +import java.util.internal.GenericArrayOps._ + import scala.scalajs.js.typedarray._ abstract class Buffer private[nio] (val _capacity: Int) { @@ -25,7 +27,7 @@ abstract class Buffer private[nio] (val _capacity: Int) { // Normal implementation of Buffer - private var _limit: Int = capacity + private var _limit: Int = capacity() private var _position: Int = 0 private[nio] var _mark: Int = -1 @@ -71,7 +73,7 @@ abstract class Buffer private[nio] (val _capacity: Int) { def clear(): Buffer = { _mark = -1 _position = 0 - _limit = capacity + _limit = capacity() this } @@ -88,9 +90,9 @@ abstract class Buffer private[nio] (val _capacity: Int) { this } - @inline final def remaining(): Int = limit - position + @inline final def remaining(): Int = limit() - position() - @inline final def hasRemaining(): Boolean = position != limit + @inline final def hasRemaining(): Boolean = position() != limit() def isReadOnly(): Boolean @@ -106,42 +108,42 @@ abstract class Buffer private[nio] (val _capacity: Int) { def isDirect(): Boolean override def toString(): String = - s"${getClass.getName}[pos=$position lim=$limit cap=$capacity]" + s"${getClass().getName()}[pos=${position()} lim=${limit()} cap=${capacity()}]" /* Extended API - exposed to user-space with a hacky bridge and extension * methods. */ def hasArrayBuffer(): Boolean = - _arrayBuffer != null && !isReadOnly + _arrayBuffer != null && !isReadOnly() def arrayBuffer(): ArrayBuffer = { val buffer = _arrayBuffer - if (buffer == null || isReadOnly) + if (buffer == null || isReadOnly()) throw new UnsupportedOperationException buffer } def arrayBufferOffset(): Int = { val offset = _arrayBufferOffset - if (offset == -1 || isReadOnly) + if (offset == -1 || isReadOnly()) throw new UnsupportedOperationException offset } def dataView(): DataView = { val view = _dataView - if (view == null || isReadOnly) + if (view == null || isReadOnly()) throw new UnsupportedOperationException view } def hasTypedArray(): Boolean = - _typedArray != null && !isReadOnly + _typedArray != null && !isReadOnly() def typedArray(): TypedArrayType = { val array = _typedArray - if (array == null || isReadOnly) + if (array == null || isReadOnly()) throw new UnsupportedOperationException array } @@ -187,19 +189,20 @@ abstract class Buffer private[nio] (val _capacity: Int) { // Helpers @inline private[nio] def ensureNotReadOnly(): Unit = { - if (isReadOnly) + if (isReadOnly()) throw new ReadOnlyBufferException } @inline private[nio] def validateArrayIndexRange( - array: Array[_], offset: Int, length: Int): Unit = { - if (offset < 0 || length < 0 || offset > array.length - length) + array: Array[ElementType], offset: Int, length: Int)( + implicit arrayOps: ArrayOps[ElementType]): Unit = { + if (offset < 0 || length < 0 || offset > arrayOps.length(array) - length) throw new IndexOutOfBoundsException } @inline private[nio] def getPosAndAdvanceRead(): Int = { val p = _position - if (p == limit) + if (p == limit()) throw new BufferUnderflowException _position = p + 1 p @@ -208,7 +211,7 @@ abstract class Buffer private[nio] (val _capacity: Int) { @inline private[nio] def getPosAndAdvanceRead(length: Int): Int = { val p = _position val newPos = p + length - if (newPos > limit) + if (newPos > limit()) throw new BufferUnderflowException _position = newPos p @@ -216,7 +219,7 @@ abstract class Buffer private[nio] (val _capacity: Int) { @inline private[nio] def getPosAndAdvanceWrite(): Int = { val p = _position - if (p == limit) + if (p == limit()) throw new BufferOverflowException _position = p + 1 p @@ -225,20 +228,20 @@ abstract class Buffer private[nio] (val _capacity: Int) { @inline private[nio] def getPosAndAdvanceWrite(length: Int): Int = { val p = _position val newPos = p + length - if (newPos > limit) + if (newPos > limit()) throw new BufferOverflowException _position = newPos p } @inline private[nio] def validateIndex(index: Int): Int = { - if (index < 0 || index >= limit) + if (index < 0 || index >= limit()) throw new IndexOutOfBoundsException index } @inline private[nio] def validateIndex(index: Int, length: Int): Int = { - if (index < 0 || index + length > limit) + if (index < 0 || index + length > limit()) throw new IndexOutOfBoundsException index } diff --git a/javalib/src/main/scala/java/nio/ByteBuffer.scala b/javalib/src/main/scala/java/nio/ByteBuffer.scala index 8b100204f8..ed073c6cf2 100644 --- a/javalib/src/main/scala/java/nio/ByteBuffer.scala +++ b/javalib/src/main/scala/java/nio/ByteBuffer.scala @@ -17,11 +17,15 @@ import scala.scalajs.js.typedarray._ object ByteBuffer { private final val HashSeed = -547316498 // "java.nio.ByteBuffer".## - def allocate(capacity: Int): ByteBuffer = + def allocate(capacity: Int): ByteBuffer = { + GenBuffer.validateAllocateCapacity(capacity) wrap(new Array[Byte](capacity)) + } - def allocateDirect(capacity: Int): ByteBuffer = + def allocateDirect(capacity: Int): ByteBuffer = { + GenBuffer.validateAllocateCapacity(capacity) TypedArrayByteBuffer.allocate(capacity) + } def wrap(array: Array[Byte], offset: Int, length: Int): ByteBuffer = HeapByteBuffer.wrap(array, 0, array.length, offset, length, false) @@ -31,14 +35,8 @@ object ByteBuffer { // Extended API - def wrap(array: ArrayBuffer): ByteBuffer = - TypedArrayByteBuffer.wrap(array) - - def wrap(array: ArrayBuffer, byteOffset: Int, length: Int): ByteBuffer = - TypedArrayByteBuffer.wrap(array, byteOffset, length) - - def wrap(array: Int8Array): ByteBuffer = - TypedArrayByteBuffer.wrap(array) + def wrapInt8Array(array: Int8Array): ByteBuffer = + TypedArrayByteBuffer.wrapInt8Array(array) } abstract class ByteBuffer private[nio] ( diff --git a/javalib/src/main/scala/java/nio/ByteOrder.scala b/javalib/src/main/scala/java/nio/ByteOrder.scala index b209b3ee5e..d14de26e3d 100644 --- a/javalib/src/main/scala/java/nio/ByteOrder.scala +++ b/javalib/src/main/scala/java/nio/ByteOrder.scala @@ -12,6 +12,9 @@ package java.nio +import scala.scalajs.js +import scala.scalajs.js.typedarray._ + final class ByteOrder private (name: String) { override def toString(): String = name } @@ -20,8 +23,18 @@ object ByteOrder { val BIG_ENDIAN: ByteOrder = new ByteOrder("BIG_ENDIAN") val LITTLE_ENDIAN: ByteOrder = new ByteOrder("LITTLE_ENDIAN") + private[nio] val areTypedArraysBigEndian = { + if (js.typeOf(js.Dynamic.global.Int32Array) != "undefined") { + val arrayBuffer = new ArrayBuffer(4) + (new Int32Array(arrayBuffer))(0) = 0x01020304 + (new Int8Array(arrayBuffer))(0) == 0x01 + } else { + true // as good a value as any + } + } + def nativeOrder(): ByteOrder = { - if (scala.scalajs.runtime.Bits.areTypedArraysBigEndian) BIG_ENDIAN + if (areTypedArraysBigEndian) BIG_ENDIAN else LITTLE_ENDIAN } } diff --git a/javalib/src/main/scala/java/nio/CharBuffer.scala b/javalib/src/main/scala/java/nio/CharBuffer.scala index d418ba9435..31adf671be 100644 --- a/javalib/src/main/scala/java/nio/CharBuffer.scala +++ b/javalib/src/main/scala/java/nio/CharBuffer.scala @@ -17,8 +17,10 @@ import scala.scalajs.js.typedarray._ object CharBuffer { private final val HashSeed = -182887236 // "java.nio.CharBuffer".## - def allocate(capacity: Int): CharBuffer = + def allocate(capacity: Int): CharBuffer = { + GenBuffer.validateAllocateCapacity(capacity) wrap(new Array[Char](capacity)) + } def wrap(array: Array[Char], offset: Int, length: Int): CharBuffer = HeapCharBuffer.wrap(array, 0, array.length, offset, length, false) @@ -27,15 +29,15 @@ object CharBuffer { wrap(array, 0, array.length) def wrap(csq: CharSequence, start: Int, end: Int): CharBuffer = - StringCharBuffer.wrap(csq, 0, csq.length, start, end - start) + StringCharBuffer.wrap(csq, 0, csq.length(), start, end - start) def wrap(csq: CharSequence): CharBuffer = - wrap(csq, 0, csq.length) + wrap(csq, 0, csq.length()) // Extended API - def wrap(array: Uint16Array): CharBuffer = - TypedArrayCharBuffer.wrap(array) + def wrapUint16Array(array: Uint16Array): CharBuffer = + TypedArrayCharBuffer.wrapUint16Array(array) } abstract class CharBuffer private[nio] ( @@ -52,7 +54,7 @@ abstract class CharBuffer private[nio] ( def read(target: CharBuffer): Int = { // Attention: this method must not change this buffer's position - val n = remaining + val n = remaining() if (n == 0) -1 else if (_array != null) { // even if read-only target.put(_array, _arrayOffset, n) @@ -166,9 +168,9 @@ abstract class CharBuffer private[nio] ( override def toString(): String = { if (_array != null) { // even if read-only - new String(_array, position() + _arrayOffset, remaining) + new String(_array, position() + _arrayOffset, remaining()) } else { - val chars = new Array[Char](remaining) + val chars = new Array[Char](remaining()) val savedPos = position() get(chars) position(savedPos) @@ -176,7 +178,7 @@ abstract class CharBuffer private[nio] ( } } - final def length(): Int = remaining + final def length(): Int = remaining() final def charAt(index: Int): Char = get(position() + index) diff --git a/javalib/src/main/scala/java/nio/DataViewCharBuffer.scala b/javalib/src/main/scala/java/nio/DataViewCharBuffer.scala index d94624f9d1..ad0c3b72f4 100644 --- a/javalib/src/main/scala/java/nio/DataViewCharBuffer.scala +++ b/javalib/src/main/scala/java/nio/DataViewCharBuffer.scala @@ -43,10 +43,10 @@ private[nio] final class DataViewCharBuffer private ( GenDataViewBuffer(this).generic_asReadOnlyBuffer() def subSequence(start: Int, end: Int): CharBuffer = { - if (start < 0 || end < start || end > remaining) + if (start < 0 || end < start || end > remaining()) throw new IndexOutOfBoundsException new DataViewCharBuffer(_dataView, - position() + start, position() + end, isReadOnly, isBigEndian) + position() + start, position() + end, isReadOnly(), isBigEndian) } @noinline diff --git a/javalib/src/main/scala/java/nio/DataViewExt.scala b/javalib/src/main/scala/java/nio/DataViewExt.scala new file mode 100644 index 0000000000..f034f2f915 --- /dev/null +++ b/javalib/src/main/scala/java/nio/DataViewExt.scala @@ -0,0 +1,46 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.nio + +import scala.scalajs.js.typedarray.DataView + +/** Copy of features in `scala.scalajs.js.typedarray.DateViewExt`. + * + * Defined as functions instead of extension methods, because the AnyVal over + * a JS type generates an `equals` method that references `BoxesRunTime`. + */ +private[nio] object DataViewExt { + /** Reads a 2's complement signed 64-bit integers from the data view. + * @param index Starting index + * @param littleEndian Whether the number is stored in little endian + */ + @inline + def dataViewGetInt64(dataView: DataView, index: Int, littleEndian: Boolean): Long = { + val high = dataView.getInt32(index + (if (littleEndian) 4 else 0), littleEndian) + val low = dataView.getInt32(index + (if (littleEndian) 0 else 4), littleEndian) + (high.toLong << 32) | (low.toLong & 0xffffffffL) + } + + /** Writes a 2's complement signed 64-bit integers to the data view. + * @param index Starting index + * @param value Value to be written + * @param littleEndian Whether to store the number in little endian + */ + @inline + def dataViewSetInt64(dataView: DataView, index: Int, value: Long, littleEndian: Boolean): Unit = { + val high = (value >>> 32).toInt + val low = value.toInt + dataView.setInt32(index + (if (littleEndian) 4 else 0), high, littleEndian) + dataView.setInt32(index + (if (littleEndian) 0 else 4), low, littleEndian) + } +} diff --git a/javalib/src/main/scala/java/nio/DataViewLongBuffer.scala b/javalib/src/main/scala/java/nio/DataViewLongBuffer.scala index 3ee08fee13..3d083001cb 100644 --- a/javalib/src/main/scala/java/nio/DataViewLongBuffer.scala +++ b/javalib/src/main/scala/java/nio/DataViewLongBuffer.scala @@ -12,8 +12,9 @@ package java.nio +import java.nio.DataViewExt._ + import scala.scalajs.js.typedarray._ -import DataViewExt._ private[nio] final class DataViewLongBuffer private ( override private[nio] val _dataView: DataView, @@ -86,11 +87,11 @@ private[nio] final class DataViewLongBuffer private ( @inline private[nio] def load(index: Int): Long = - _dataView.getInt64(8 * index, !isBigEndian) + dataViewGetInt64(_dataView, 8 * index, !isBigEndian) @inline private[nio] def store(index: Int, elem: Long): Unit = - _dataView.setInt64(8 * index, elem, !isBigEndian) + dataViewSetInt64(_dataView, 8 * index, elem, !isBigEndian) @inline override private[nio] def load(startIndex: Int, diff --git a/javalib/src/main/scala/java/nio/DoubleBuffer.scala b/javalib/src/main/scala/java/nio/DoubleBuffer.scala index 34c77ba0c5..20c1f8f5a2 100644 --- a/javalib/src/main/scala/java/nio/DoubleBuffer.scala +++ b/javalib/src/main/scala/java/nio/DoubleBuffer.scala @@ -17,8 +17,10 @@ import scala.scalajs.js.typedarray._ object DoubleBuffer { private final val HashSeed = 2140173175 // "java.nio.DoubleBuffer".## - def allocate(capacity: Int): DoubleBuffer = + def allocate(capacity: Int): DoubleBuffer = { + GenBuffer.validateAllocateCapacity(capacity) wrap(new Array[Double](capacity)) + } def wrap(array: Array[Double], offset: Int, length: Int): DoubleBuffer = HeapDoubleBuffer.wrap(array, 0, array.length, offset, length, false) @@ -28,8 +30,8 @@ object DoubleBuffer { // Extended API - def wrap(array: Float64Array): DoubleBuffer = - TypedArrayDoubleBuffer.wrap(array) + def wrapFloat64Array(array: Float64Array): DoubleBuffer = + TypedArrayDoubleBuffer.wrapFloat64Array(array) } abstract class DoubleBuffer private[nio] ( diff --git a/javalib/src/main/scala/java/nio/FloatBuffer.scala b/javalib/src/main/scala/java/nio/FloatBuffer.scala index dc816242c6..3def688001 100644 --- a/javalib/src/main/scala/java/nio/FloatBuffer.scala +++ b/javalib/src/main/scala/java/nio/FloatBuffer.scala @@ -17,8 +17,10 @@ import scala.scalajs.js.typedarray._ object FloatBuffer { private final val HashSeed = 1920204022 // "java.nio.FloatBuffer".## - def allocate(capacity: Int): FloatBuffer = + def allocate(capacity: Int): FloatBuffer = { + GenBuffer.validateAllocateCapacity(capacity) wrap(new Array[Float](capacity)) + } def wrap(array: Array[Float], offset: Int, length: Int): FloatBuffer = HeapFloatBuffer.wrap(array, 0, array.length, offset, length, false) @@ -28,8 +30,8 @@ object FloatBuffer { // Extended API - def wrap(array: Float32Array): FloatBuffer = - TypedArrayFloatBuffer.wrap(array) + def wrapFloat32Array(array: Float32Array): FloatBuffer = + TypedArrayFloatBuffer.wrapFloat32Array(array) } abstract class FloatBuffer private[nio] ( diff --git a/javalib/src/main/scala/java/nio/GenBuffer.scala b/javalib/src/main/scala/java/nio/GenBuffer.scala index f799e52bf5..9aa57e92d8 100644 --- a/javalib/src/main/scala/java/nio/GenBuffer.scala +++ b/javalib/src/main/scala/java/nio/GenBuffer.scala @@ -12,12 +12,25 @@ package java.nio +import java.util.internal.GenericArrayOps._ + private[nio] object GenBuffer { def apply[B <: Buffer](self: B): GenBuffer[B] = new GenBuffer(self) + + @inline def validateAllocateCapacity(capacity: Int): Unit = { + if (capacity < 0) + throw new IllegalArgumentException + } } -private[nio] final class GenBuffer[B <: Buffer](val self: B) extends AnyVal { +/* The underlying `val self` is intentionally public because + * `self.ElementType` and `self.BufferType` appear in signatures. + * It's tolerable because the class is `private[nio]` anyway. + */ +private[nio] final class GenBuffer[B <: Buffer] private (val self: B) + extends AnyVal { + import self._ @inline @@ -43,8 +56,8 @@ private[nio] final class GenBuffer[B <: Buffer](val self: B) extends AnyVal { } @inline - def generic_get(dst: Array[ElementType], - offset: Int, length: Int): BufferType = { + def generic_get(dst: Array[ElementType], offset: Int, length: Int)( + implicit arrayOps: ArrayOps[ElementType]): BufferType = { validateArrayIndexRange(dst, offset, length) load(getPosAndAdvanceRead(length), dst, offset, length) self @@ -55,8 +68,8 @@ private[nio] final class GenBuffer[B <: Buffer](val self: B) extends AnyVal { if (src eq self) throw new IllegalArgumentException ensureNotReadOnly() - val srcLimit = src.limit - var srcPos = src.position + val srcLimit = src.limit() + var srcPos = src.position() val length = srcLimit - srcPos var selfPos = getPosAndAdvanceWrite(length) src.position(srcLimit) @@ -76,8 +89,8 @@ private[nio] final class GenBuffer[B <: Buffer](val self: B) extends AnyVal { } @inline - def generic_put(src: Array[ElementType], - offset: Int, length: Int): BufferType = { + def generic_put(src: Array[ElementType], offset: Int, length: Int)( + implicit arrayOps: ArrayOps[ElementType]): BufferType = { ensureNotReadOnly() validateArrayIndexRange(src, offset, length) store(getPosAndAdvanceWrite(length), src, offset, length) @@ -86,14 +99,14 @@ private[nio] final class GenBuffer[B <: Buffer](val self: B) extends AnyVal { @inline def generic_hasArray(): Boolean = - _array != null && !isReadOnly + _array != null && !isReadOnly() @inline def generic_array(): Array[ElementType] = { val a = _array if (a == null) throw new UnsupportedOperationException - if (isReadOnly) + if (isReadOnly()) throw new ReadOnlyBufferException a } @@ -103,20 +116,20 @@ private[nio] final class GenBuffer[B <: Buffer](val self: B) extends AnyVal { val o = _arrayOffset if (o == -1) throw new UnsupportedOperationException - if (isReadOnly) + if (isReadOnly()) throw new ReadOnlyBufferException o } @inline def generic_hashCode(hashSeed: Int): Int = { - import scala.util.hashing.MurmurHash3._ - val start = position - val end = limit + import java.util.internal.MurmurHash3._ + val start = position() + val end = limit() var h = hashSeed var i = start while (i != end) { - h = mix(h, load(i).##) + h = mix(h, load(i).hashCode()) i += 1 } finalizeHash(h, end-start) @@ -129,10 +142,10 @@ private[nio] final class GenBuffer[B <: Buffer](val self: B) extends AnyVal { if (self eq that) { 0 } else { - val thisStart = self.position - val thisRemaining = self.limit - thisStart - val thatStart = that.position - val thatRemaining = that.limit - thatStart + val thisStart = self.position() + val thisRemaining = self.limit() - thisStart + val thatStart = that.position() + val thatRemaining = that.limit() - thatStart val shortestLength = Math.min(thisRemaining, thatRemaining) var i = 0 @@ -150,12 +163,13 @@ private[nio] final class GenBuffer[B <: Buffer](val self: B) extends AnyVal { @inline def generic_load(startIndex: Int, - dst: Array[ElementType], offset: Int, length: Int): Unit = { + dst: Array[ElementType], offset: Int, length: Int)( + implicit arrayOps: ArrayOps[ElementType]): Unit = { var selfPos = startIndex val endPos = selfPos + length var arrayIndex = offset while (selfPos != endPos) { - dst(arrayIndex) = load(selfPos) + arrayOps.set(dst, arrayIndex, load(selfPos)) selfPos += 1 arrayIndex += 1 } @@ -163,12 +177,13 @@ private[nio] final class GenBuffer[B <: Buffer](val self: B) extends AnyVal { @inline def generic_store(startIndex: Int, - src: Array[ElementType], offset: Int, length: Int): Unit = { + src: Array[ElementType], offset: Int, length: Int)( + implicit arrayOps: ArrayOps[ElementType]): Unit = { var selfPos = startIndex val endPos = selfPos + length var arrayIndex = offset while (selfPos != endPos) { - store(selfPos, src(arrayIndex)) + store(selfPos, arrayOps.get(src, arrayIndex)) selfPos += 1 arrayIndex += 1 } diff --git a/javalib/src/main/scala/java/nio/GenDataViewBuffer.scala b/javalib/src/main/scala/java/nio/GenDataViewBuffer.scala index d73eade50e..299a26271c 100644 --- a/javalib/src/main/scala/java/nio/GenDataViewBuffer.scala +++ b/javalib/src/main/scala/java/nio/GenDataViewBuffer.scala @@ -37,29 +37,21 @@ private[nio] object GenDataViewBuffer { val viewCapacity = (byteBufferLimit - byteBufferPos) / newDataViewBuffer.bytesPerElem val byteLength = viewCapacity * newDataViewBuffer.bytesPerElem - val dataView = newDataView( + val dataView = new DataView( byteArray.buffer, byteArray.byteOffset + byteBufferPos, byteLength) newDataViewBuffer(dataView, - 0, viewCapacity, byteBuffer.isReadOnly, byteBuffer.isBigEndian) - } - - /* Work around for https://github.com/joyent/node/issues/6051 - * node 0.10 does not like creating a DataView whose byteOffset is equal to - * the buffer's length, even if byteLength == 0. - */ - @inline - private def newDataView(buffer: ArrayBuffer, byteOffset: Int, byteLength: Int): DataView = { - if (byteLength == 0) - lit(buffer = buffer, byteOffset = byteOffset, byteLength = byteLength).asInstanceOf[DataView] - else - new DataView(buffer, byteOffset, byteLength) + 0, viewCapacity, byteBuffer.isReadOnly(), byteBuffer.isBigEndian) } } -private[nio] final class GenDataViewBuffer[B <: Buffer](val self: B) extends AnyVal { - import self._ +/* The underlying `val self` is intentionally public because + * `self.BufferType` appears in signatures. + * It's tolerable because the class is `private[nio]` anyway. + */ +private[nio] final class GenDataViewBuffer[B <: Buffer] private (val self: B) + extends AnyVal { - import GenDataViewBuffer.newDataView + import self._ type NewThisDataViewBuffer = GenDataViewBuffer.NewDataViewBuffer[BufferType] @@ -68,19 +60,19 @@ private[nio] final class GenDataViewBuffer[B <: Buffer](val self: B) extends Any implicit newDataViewBuffer: NewThisDataViewBuffer): BufferType = { val bytesPerElem = newDataViewBuffer.bytesPerElem val dataView = _dataView - val pos = position - val newCapacity = limit - pos - val slicedDataView = newDataView(dataView.buffer, + val pos = position() + val newCapacity = limit() - pos + val slicedDataView = new DataView(dataView.buffer, dataView.byteOffset + bytesPerElem*pos, bytesPerElem*newCapacity) newDataViewBuffer(slicedDataView, - 0, newCapacity, isReadOnly, isBigEndian) + 0, newCapacity, isReadOnly(), isBigEndian) } @inline def generic_duplicate()( implicit newDataViewBuffer: NewThisDataViewBuffer): BufferType = { val result = newDataViewBuffer(_dataView, - position, limit, isReadOnly, isBigEndian) + position(), limit(), isReadOnly(), isBigEndian) result._mark = _mark result } @@ -89,7 +81,7 @@ private[nio] final class GenDataViewBuffer[B <: Buffer](val self: B) extends Any def generic_asReadOnlyBuffer()( implicit newDataViewBuffer: NewThisDataViewBuffer): BufferType = { val result = newDataViewBuffer(_dataView, - position, limit, true, isBigEndian) + position(), limit(), true, isBigEndian) result._mark = _mark result } @@ -97,18 +89,18 @@ private[nio] final class GenDataViewBuffer[B <: Buffer](val self: B) extends Any @inline def generic_compact()( implicit newDataViewBuffer: NewThisDataViewBuffer): BufferType = { - if (isReadOnly) + if (isReadOnly()) throw new ReadOnlyBufferException val dataView = _dataView val bytesPerElem = newDataViewBuffer.bytesPerElem val byteArray = new Int8Array(dataView.buffer, dataView.byteOffset, dataView.byteLength) - val pos = position - val lim = limit + val pos = position() + val lim = limit() byteArray.set(byteArray.subarray(bytesPerElem * pos, bytesPerElem * lim)) _mark = -1 - limit(capacity) + limit(capacity()) position(lim - pos) self } diff --git a/javalib/src/main/scala/java/nio/GenHeapBuffer.scala b/javalib/src/main/scala/java/nio/GenHeapBuffer.scala index 4556f735d6..f4e5c8a40d 100644 --- a/javalib/src/main/scala/java/nio/GenHeapBuffer.scala +++ b/javalib/src/main/scala/java/nio/GenHeapBuffer.scala @@ -12,6 +12,8 @@ package java.nio +import java.util.internal.GenericArrayOps._ + private[nio] object GenHeapBuffer { def apply[B <: Buffer](self: B): GenHeapBuffer[B] = new GenHeapBuffer(self) @@ -25,8 +27,9 @@ private[nio] object GenHeapBuffer { def generic_wrap[BufferType <: Buffer, ElementType]( array: Array[ElementType], arrayOffset: Int, capacity: Int, initialPosition: Int, initialLength: Int, isReadOnly: Boolean)( - implicit newHeapBuffer: NewHeapBuffer[BufferType, ElementType]): BufferType = { - if (arrayOffset < 0 || capacity < 0 || arrayOffset+capacity > array.length) + implicit arrayOps: ArrayOps[ElementType], + newHeapBuffer: NewHeapBuffer[BufferType, ElementType]): BufferType = { + if (arrayOffset < 0 || capacity < 0 || arrayOffset+capacity > arrayOps.length(array)) throw new IndexOutOfBoundsException val initialLimit = initialPosition + initialLength if (initialPosition < 0 || initialLength < 0 || initialLimit > capacity) @@ -36,7 +39,13 @@ private[nio] object GenHeapBuffer { } } -private[nio] final class GenHeapBuffer[B <: Buffer](val self: B) extends AnyVal { +/* The underlying `val self` is intentionally public because + * `self.ElementType` and `self.BufferType` appear in signatures. + * It's tolerable because the class is `private[nio]` anyway. + */ +private[nio] final class GenHeapBuffer[B <: Buffer] private (val self: B) + extends AnyVal { + import self._ type NewThisHeapBuffer = GenHeapBuffer.NewHeapBuffer[BufferType, ElementType] @@ -44,16 +53,16 @@ private[nio] final class GenHeapBuffer[B <: Buffer](val self: B) extends AnyVal @inline def generic_slice()( implicit newHeapBuffer: NewThisHeapBuffer): BufferType = { - val newCapacity = remaining - newHeapBuffer(newCapacity, _array, _arrayOffset + position, - 0, newCapacity, isReadOnly) + val newCapacity = remaining() + newHeapBuffer(newCapacity, _array, _arrayOffset + position(), + 0, newCapacity, isReadOnly()) } @inline def generic_duplicate()( implicit newHeapBuffer: NewThisHeapBuffer): BufferType = { - val result = newHeapBuffer(capacity, _array, _arrayOffset, - position, limit, isReadOnly) + val result = newHeapBuffer(capacity(), _array, _arrayOffset, + position(), limit(), isReadOnly()) result._mark = _mark result } @@ -61,8 +70,8 @@ private[nio] final class GenHeapBuffer[B <: Buffer](val self: B) extends AnyVal @inline def generic_asReadOnlyBuffer()( implicit newHeapBuffer: NewThisHeapBuffer): BufferType = { - val result = newHeapBuffer(capacity, _array, _arrayOffset, - position, limit, true) + val result = newHeapBuffer(capacity(), _array, _arrayOffset, + position(), limit(), true) result._mark = _mark result } @@ -71,21 +80,21 @@ private[nio] final class GenHeapBuffer[B <: Buffer](val self: B) extends AnyVal def generic_compact(): BufferType = { ensureNotReadOnly() - val len = remaining - System.arraycopy(_array, _arrayOffset + position, _array, _arrayOffset, len) + val len = remaining() + System.arraycopy(_array, _arrayOffset + position(), _array, _arrayOffset, len) _mark = -1 - limit(capacity) + limit(capacity()) position(len) self } @inline - def generic_load(index: Int): ElementType = - _array(_arrayOffset + index) + def generic_load(index: Int)(implicit arrayOps: ArrayOps[ElementType]): ElementType = + arrayOps.get(_array, _arrayOffset + index) @inline - def generic_store(index: Int, elem: ElementType): Unit = - _array(_arrayOffset + index) = elem + def generic_store(index: Int, elem: ElementType)(implicit arrayOps: ArrayOps[ElementType]): Unit = + arrayOps.set(_array, _arrayOffset + index, elem) @inline def generic_load(startIndex: Int, diff --git a/javalib/src/main/scala/java/nio/GenHeapBufferView.scala b/javalib/src/main/scala/java/nio/GenHeapBufferView.scala index 1222958f55..5764174a2b 100644 --- a/javalib/src/main/scala/java/nio/GenHeapBufferView.scala +++ b/javalib/src/main/scala/java/nio/GenHeapBufferView.scala @@ -33,11 +33,16 @@ private[nio] object GenHeapBufferView { (byteBuffer.limit() - byteBufferPos) / newHeapBufferView.bytesPerElem newHeapBufferView(viewCapacity, byteBuffer._array, byteBuffer._arrayOffset + byteBufferPos, - 0, viewCapacity, byteBuffer.isReadOnly, byteBuffer.isBigEndian) + 0, viewCapacity, byteBuffer.isReadOnly(), byteBuffer.isBigEndian) } } -private[nio] final class GenHeapBufferView[B <: Buffer](val self: B) extends AnyVal { +/* The underlying `val self` is intentionally public because + * `self.BufferType` appears in signatures. + * It's tolerable because the class is `private[nio]` anyway. + */ +private[nio] final class GenHeapBufferView[B <: Buffer] private (val self: B) + extends AnyVal { import self._ type NewThisHeapBufferView = GenHeapBufferView.NewHeapBufferView[BufferType] @@ -45,18 +50,18 @@ private[nio] final class GenHeapBufferView[B <: Buffer](val self: B) extends Any @inline def generic_slice()( implicit newHeapBufferView: NewThisHeapBufferView): BufferType = { - val newCapacity = remaining + val newCapacity = remaining() val bytesPerElem = newHeapBufferView.bytesPerElem newHeapBufferView(newCapacity, _byteArray, - _byteArrayOffset + bytesPerElem*position, - 0, newCapacity, isReadOnly, isBigEndian) + _byteArrayOffset + bytesPerElem*position(), + 0, newCapacity, isReadOnly(), isBigEndian) } @inline def generic_duplicate()( implicit newHeapBufferView: NewThisHeapBufferView): BufferType = { - val result = newHeapBufferView(capacity, _byteArray, _byteArrayOffset, - position, limit, isReadOnly, isBigEndian) + val result = newHeapBufferView(capacity(), _byteArray, _byteArrayOffset, + position(), limit(), isReadOnly(), isBigEndian) result._mark = _mark result } @@ -64,8 +69,8 @@ private[nio] final class GenHeapBufferView[B <: Buffer](val self: B) extends Any @inline def generic_asReadOnlyBuffer()( implicit newHeapBufferView: NewThisHeapBufferView): BufferType = { - val result = newHeapBufferView(capacity, _byteArray, _byteArrayOffset, - position, limit, true, isBigEndian) + val result = newHeapBufferView(capacity(), _byteArray, _byteArrayOffset, + position(), limit(), true, isBigEndian) result._mark = _mark result } @@ -73,15 +78,15 @@ private[nio] final class GenHeapBufferView[B <: Buffer](val self: B) extends Any @inline def generic_compact()( implicit newHeapBufferView: NewThisHeapBufferView): BufferType = { - if (isReadOnly) + if (isReadOnly()) throw new ReadOnlyBufferException - val len = remaining + val len = remaining() val bytesPerElem = newHeapBufferView.bytesPerElem - System.arraycopy(_byteArray, _byteArrayOffset + bytesPerElem*position, + System.arraycopy(_byteArray, _byteArrayOffset + bytesPerElem*position(), _byteArray, _byteArrayOffset, bytesPerElem * len) _mark = -1 - limit(capacity) + limit(capacity()) position(len) self } diff --git a/javalib/src/main/scala/java/nio/GenTypedArrayBuffer.scala b/javalib/src/main/scala/java/nio/GenTypedArrayBuffer.scala index b357db30e7..522ead56c5 100644 --- a/javalib/src/main/scala/java/nio/GenTypedArrayBuffer.scala +++ b/javalib/src/main/scala/java/nio/GenTypedArrayBuffer.scala @@ -40,12 +40,17 @@ private[nio] object GenTypedArrayBuffer { val viewTypedArray = newTypedArrayBuffer.newTypedArray( byteArray.buffer, byteArray.byteOffset + byteBufferPos, viewCapacity) newTypedArrayBuffer(viewTypedArray, - 0, viewCapacity, byteBuffer.isReadOnly) + 0, viewCapacity, byteBuffer.isReadOnly()) } } -private[nio] final class GenTypedArrayBuffer[B <: Buffer]( - val self: B) extends AnyVal { +/* The underlying `val self` is intentionally public because + * `self.BufferType` appears in signatures. + * It's tolerable because the class is `private[nio]` anyway. + */ +private[nio] final class GenTypedArrayBuffer[B <: Buffer] private (val self: B) + extends AnyVal { + import self._ type NewThisTypedArrayBuffer = @@ -54,15 +59,15 @@ private[nio] final class GenTypedArrayBuffer[B <: Buffer]( @inline def generic_slice()( implicit newTypedArrayBuffer: NewThisTypedArrayBuffer): BufferType = { - val slicedTypedArray = _typedArray.subarray(position, limit) + val slicedTypedArray = _typedArray.subarray(position(), limit()) newTypedArrayBuffer(slicedTypedArray, - 0, slicedTypedArray.length, isReadOnly) + 0, slicedTypedArray.length, isReadOnly()) } @inline def generic_duplicate()( implicit newTypedArrayBuffer: NewThisTypedArrayBuffer): BufferType = { - val result = newTypedArrayBuffer(_typedArray, position, limit, isReadOnly) + val result = newTypedArrayBuffer(_typedArray, position(), limit(), isReadOnly()) result._mark = _mark result } @@ -70,7 +75,7 @@ private[nio] final class GenTypedArrayBuffer[B <: Buffer]( @inline def generic_asReadOnlyBuffer()( implicit newTypedArrayBuffer: NewThisTypedArrayBuffer): BufferType = { - val result = newTypedArrayBuffer(_typedArray, position, limit, true) + val result = newTypedArrayBuffer(_typedArray, position(), limit(), true) result._mark = _mark result } @@ -80,11 +85,11 @@ private[nio] final class GenTypedArrayBuffer[B <: Buffer]( ensureNotReadOnly() val typedArray = _typedArray - val pos = position - val lim = limit + val pos = position() + val lim = limit() typedArray.set(typedArray.subarray(pos, lim)) _mark = -1 - limit(capacity) + limit(capacity()) position(lim - pos) self } @@ -102,7 +107,7 @@ private[nio] final class GenTypedArrayBuffer[B <: Buffer]( implicit newTypedArrayBuffer: NewThisTypedArrayBuffer): DataView = { val bytesPerElem = newTypedArrayBuffer.bytesPerElem val array = _typedArray - new DataView(array.buffer, array.byteOffset, capacity * bytesPerElem) + new DataView(array.buffer, array.byteOffset, capacity() * bytesPerElem) } } diff --git a/javalib/src/main/scala/java/nio/HeapByteBufferCharView.scala b/javalib/src/main/scala/java/nio/HeapByteBufferCharView.scala index fb48c228bc..cef615e30a 100644 --- a/javalib/src/main/scala/java/nio/HeapByteBufferCharView.scala +++ b/javalib/src/main/scala/java/nio/HeapByteBufferCharView.scala @@ -43,10 +43,10 @@ private[nio] final class HeapByteBufferCharView private ( GenHeapBufferView(this).generic_asReadOnlyBuffer() def subSequence(start: Int, end: Int): CharBuffer = { - if (start < 0 || end < start || end > remaining) + if (start < 0 || end < start || end > remaining()) throw new IndexOutOfBoundsException - new HeapByteBufferCharView(capacity, _byteArray, _byteArrayOffset, - position() + start, position() + end, isReadOnly, isBigEndian) + new HeapByteBufferCharView(capacity(), _byteArray, _byteArrayOffset, + position() + start, position() + end, isReadOnly(), isBigEndian) } @noinline diff --git a/javalib/src/main/scala/java/nio/HeapCharBuffer.scala b/javalib/src/main/scala/java/nio/HeapCharBuffer.scala index e4c490f8ce..2eae690217 100644 --- a/javalib/src/main/scala/java/nio/HeapCharBuffer.scala +++ b/javalib/src/main/scala/java/nio/HeapCharBuffer.scala @@ -39,10 +39,10 @@ private[nio] final class HeapCharBuffer private ( GenHeapBuffer(this).generic_asReadOnlyBuffer() def subSequence(start: Int, end: Int): CharBuffer = { - if (start < 0 || end < start || end > remaining) + if (start < 0 || end < start || end > remaining()) throw new IndexOutOfBoundsException - new HeapCharBuffer(capacity, _array, _arrayOffset, - position() + start, position() + end, isReadOnly) + new HeapCharBuffer(capacity(), _array, _arrayOffset, + position() + start, position() + end, isReadOnly()) } @noinline diff --git a/javalib/src/main/scala/java/nio/IntBuffer.scala b/javalib/src/main/scala/java/nio/IntBuffer.scala index 09cfa88515..34de3249b2 100644 --- a/javalib/src/main/scala/java/nio/IntBuffer.scala +++ b/javalib/src/main/scala/java/nio/IntBuffer.scala @@ -17,8 +17,10 @@ import scala.scalajs.js.typedarray._ object IntBuffer { private final val HashSeed = 39599817 // "java.nio.IntBuffer".## - def allocate(capacity: Int): IntBuffer = + def allocate(capacity: Int): IntBuffer = { + GenBuffer.validateAllocateCapacity(capacity) wrap(new Array[Int](capacity)) + } def wrap(array: Array[Int], offset: Int, length: Int): IntBuffer = HeapIntBuffer.wrap(array, 0, array.length, offset, length, false) @@ -28,8 +30,8 @@ object IntBuffer { // Extended API - def wrap(array: Int32Array): IntBuffer = - TypedArrayIntBuffer.wrap(array) + def wrapInt32Array(array: Int32Array): IntBuffer = + TypedArrayIntBuffer.wrapInt32Array(array) } abstract class IntBuffer private[nio] ( diff --git a/javalib/src/main/scala/java/nio/LongBuffer.scala b/javalib/src/main/scala/java/nio/LongBuffer.scala index c1879a2cf3..74a66c1df5 100644 --- a/javalib/src/main/scala/java/nio/LongBuffer.scala +++ b/javalib/src/main/scala/java/nio/LongBuffer.scala @@ -15,8 +15,10 @@ package java.nio object LongBuffer { private final val HashSeed = -1709696158 // "java.nio.LongBuffer".## - def allocate(capacity: Int): LongBuffer = + def allocate(capacity: Int): LongBuffer = { + GenBuffer.validateAllocateCapacity(capacity) wrap(new Array[Long](capacity)) + } def wrap(array: Array[Long], offset: Int, length: Int): LongBuffer = HeapLongBuffer.wrap(array, 0, array.length, offset, length, false) diff --git a/javalib/src/main/scala/java/nio/ShortBuffer.scala b/javalib/src/main/scala/java/nio/ShortBuffer.scala index d31b13fec8..2f8fd53ea1 100644 --- a/javalib/src/main/scala/java/nio/ShortBuffer.scala +++ b/javalib/src/main/scala/java/nio/ShortBuffer.scala @@ -17,8 +17,10 @@ import scala.scalajs.js.typedarray._ object ShortBuffer { private final val HashSeed = 383731478 // "java.nio.ShortBuffer".## - def allocate(capacity: Int): ShortBuffer = + def allocate(capacity: Int): ShortBuffer = { + GenBuffer.validateAllocateCapacity(capacity) wrap(new Array[Short](capacity)) + } def wrap(array: Array[Short], offset: Int, length: Int): ShortBuffer = HeapShortBuffer.wrap(array, 0, array.length, offset, length, false) @@ -28,8 +30,8 @@ object ShortBuffer { // Extended API - def wrap(array: Int16Array): ShortBuffer = - TypedArrayShortBuffer.wrap(array) + def wrapInt16Array(array: Int16Array): ShortBuffer = + TypedArrayShortBuffer.wrapInt16Array(array) } abstract class ShortBuffer private[nio] ( diff --git a/javalib/src/main/scala/java/nio/StringCharBuffer.scala b/javalib/src/main/scala/java/nio/StringCharBuffer.scala index 770fd2a7ff..241534d7f5 100644 --- a/javalib/src/main/scala/java/nio/StringCharBuffer.scala +++ b/javalib/src/main/scala/java/nio/StringCharBuffer.scala @@ -25,13 +25,13 @@ private[nio] final class StringCharBuffer private ( def isDirect(): Boolean = false def slice(): CharBuffer = { - val cap = remaining + val cap = remaining() new StringCharBuffer(cap, _csq, _csqOffset + position(), 0, cap) } def duplicate(): CharBuffer = { - val result = new StringCharBuffer(capacity, _csq, _csqOffset, - position, limit) + val result = new StringCharBuffer(capacity(), _csq, _csqOffset, + position(), limit()) result._mark = this._mark result } @@ -39,9 +39,9 @@ private[nio] final class StringCharBuffer private ( def asReadOnlyBuffer(): CharBuffer = duplicate() def subSequence(start: Int, end: Int): CharBuffer = { - if (start < 0 || end < start || end > remaining) + if (start < 0 || end < start || end > remaining()) throw new IndexOutOfBoundsException - new StringCharBuffer(capacity, _csq, _csqOffset, + new StringCharBuffer(capacity(), _csq, _csqOffset, position() + start, position() + end) } @@ -100,7 +100,7 @@ private[nio] final class StringCharBuffer private ( private[nio] object StringCharBuffer { private[nio] def wrap(csq: CharSequence, csqOffset: Int, capacity: Int, initialPosition: Int, initialLength: Int): CharBuffer = { - if (csqOffset < 0 || capacity < 0 || csqOffset+capacity > csq.length) + if (csqOffset < 0 || capacity < 0 || csqOffset + capacity > csq.length()) throw new IndexOutOfBoundsException val initialLimit = initialPosition + initialLength if (initialPosition < 0 || initialLength < 0 || initialLimit > capacity) diff --git a/javalib/src/main/scala/java/nio/TypedArrayByteBuffer.scala b/javalib/src/main/scala/java/nio/TypedArrayByteBuffer.scala index 424fb131be..d7c1479f69 100644 --- a/javalib/src/main/scala/java/nio/TypedArrayByteBuffer.scala +++ b/javalib/src/main/scala/java/nio/TypedArrayByteBuffer.scala @@ -12,8 +12,9 @@ package java.nio +import java.nio.DataViewExt._ + import scala.scalajs.js.typedarray._ -import DataViewExt._ private[nio] final class TypedArrayByteBuffer private ( override private[nio] val _typedArray: Int8Array, @@ -21,7 +22,7 @@ private[nio] final class TypedArrayByteBuffer private ( extends ByteBuffer(_typedArray.length, null, -1) { override private[nio] lazy val _dataView: DataView = - new DataView(_typedArray.buffer, _typedArray.byteOffset, capacity) + new DataView(_typedArray.buffer, _typedArray.byteOffset, capacity()) position(_initialPosition) limit(_initialLimit) @@ -77,7 +78,7 @@ private[nio] final class TypedArrayByteBuffer private ( @inline def hasNativeOrder: Boolean = - isBigEndian == scala.scalajs.runtime.Bits.areTypedArraysBigEndian + isBigEndian == ByteOrder.areTypedArraysBigEndian @noinline def getChar(): Char = _dataView.getUint16(getPosAndAdvanceRead(2), !isBigEndian).toChar @@ -128,13 +129,13 @@ private[nio] final class TypedArrayByteBuffer private ( } @noinline def getLong(): Long = - _dataView.getInt64(getPosAndAdvanceRead(8), !isBigEndian) + dataViewGetInt64(_dataView, getPosAndAdvanceRead(8), !isBigEndian) @noinline def putLong(value: Long): ByteBuffer = - { ensureNotReadOnly(); _dataView.setInt64(getPosAndAdvanceWrite(8), value, !isBigEndian); this } + { ensureNotReadOnly(); dataViewSetInt64(_dataView, getPosAndAdvanceWrite(8), value, !isBigEndian); this } @noinline def getLong(index: Int): Long = - _dataView.getInt64(validateIndex(index, 8), !isBigEndian) + dataViewGetInt64(_dataView, validateIndex(index, 8), !isBigEndian) @noinline def putLong(index: Int, value: Long): ByteBuffer = - { ensureNotReadOnly(); _dataView.setInt64(validateIndex(index, 8), value, !isBigEndian); this } + { ensureNotReadOnly(); dataViewSetInt64(_dataView, validateIndex(index, 8), value, !isBigEndian); this } def asLongBuffer(): LongBuffer = DataViewLongBuffer.fromTypedArrayByteBuffer(this) @@ -225,15 +226,9 @@ private[nio] object TypedArrayByteBuffer { new TypedArrayByteBuffer(new Int8Array(capacity), 0, capacity, false) } - def wrap(array: ArrayBuffer): ByteBuffer = - wrap(new Int8Array(array)) - - def wrap(array: ArrayBuffer, byteOffset: Int, length: Int): ByteBuffer = - wrap(new Int8Array(array, byteOffset, length)) - - def wrap(typedArray: Int8Array): ByteBuffer = { + def wrapInt8Array(typedArray: Int8Array): ByteBuffer = { val buf = new TypedArrayByteBuffer(typedArray, 0, typedArray.length, false) - buf._isBigEndian = scala.scalajs.runtime.Bits.areTypedArraysBigEndian + buf._isBigEndian = ByteOrder.areTypedArraysBigEndian buf } } diff --git a/javalib/src/main/scala/java/nio/TypedArrayCharBuffer.scala b/javalib/src/main/scala/java/nio/TypedArrayCharBuffer.scala index b945bd007c..71a51057d2 100644 --- a/javalib/src/main/scala/java/nio/TypedArrayCharBuffer.scala +++ b/javalib/src/main/scala/java/nio/TypedArrayCharBuffer.scala @@ -42,10 +42,10 @@ private[nio] final class TypedArrayCharBuffer private ( GenTypedArrayBuffer(this).generic_asReadOnlyBuffer() def subSequence(start: Int, end: Int): CharBuffer = { - if (start < 0 || end < start || end > remaining) + if (start < 0 || end < start || end > remaining()) throw new IndexOutOfBoundsException new TypedArrayCharBuffer(_typedArray, - position() + start, position() + end, isReadOnly) + position() + start, position() + end, isReadOnly()) } @noinline @@ -135,6 +135,6 @@ private[nio] object TypedArrayCharBuffer { def fromTypedArrayByteBuffer(byteBuffer: TypedArrayByteBuffer): CharBuffer = GenTypedArrayBuffer.generic_fromTypedArrayByteBuffer(byteBuffer) - def wrap(array: Uint16Array): CharBuffer = + def wrapUint16Array(array: Uint16Array): CharBuffer = new TypedArrayCharBuffer(array, 0, array.length, false) } diff --git a/javalib/src/main/scala/java/nio/TypedArrayDoubleBuffer.scala b/javalib/src/main/scala/java/nio/TypedArrayDoubleBuffer.scala index 5cb48beace..4211fb143b 100644 --- a/javalib/src/main/scala/java/nio/TypedArrayDoubleBuffer.scala +++ b/javalib/src/main/scala/java/nio/TypedArrayDoubleBuffer.scala @@ -128,6 +128,6 @@ private[nio] object TypedArrayDoubleBuffer { def fromTypedArrayByteBuffer(byteBuffer: TypedArrayByteBuffer): DoubleBuffer = GenTypedArrayBuffer.generic_fromTypedArrayByteBuffer(byteBuffer) - def wrap(array: Float64Array): DoubleBuffer = + def wrapFloat64Array(array: Float64Array): DoubleBuffer = new TypedArrayDoubleBuffer(array, 0, array.length, false) } diff --git a/javalib/src/main/scala/java/nio/TypedArrayFloatBuffer.scala b/javalib/src/main/scala/java/nio/TypedArrayFloatBuffer.scala index d485e87054..cab3cbc756 100644 --- a/javalib/src/main/scala/java/nio/TypedArrayFloatBuffer.scala +++ b/javalib/src/main/scala/java/nio/TypedArrayFloatBuffer.scala @@ -128,6 +128,6 @@ private[nio] object TypedArrayFloatBuffer { def fromTypedArrayByteBuffer(byteBuffer: TypedArrayByteBuffer): FloatBuffer = GenTypedArrayBuffer.generic_fromTypedArrayByteBuffer(byteBuffer) - def wrap(array: Float32Array): FloatBuffer = + def wrapFloat32Array(array: Float32Array): FloatBuffer = new TypedArrayFloatBuffer(array, 0, array.length, false) } diff --git a/javalib/src/main/scala/java/nio/TypedArrayIntBuffer.scala b/javalib/src/main/scala/java/nio/TypedArrayIntBuffer.scala index 2d73e5025e..8beab4ac58 100644 --- a/javalib/src/main/scala/java/nio/TypedArrayIntBuffer.scala +++ b/javalib/src/main/scala/java/nio/TypedArrayIntBuffer.scala @@ -128,6 +128,6 @@ private[nio] object TypedArrayIntBuffer { def fromTypedArrayByteBuffer(byteBuffer: TypedArrayByteBuffer): IntBuffer = GenTypedArrayBuffer.generic_fromTypedArrayByteBuffer(byteBuffer) - def wrap(array: Int32Array): IntBuffer = + def wrapInt32Array(array: Int32Array): IntBuffer = new TypedArrayIntBuffer(array, 0, array.length, false) } diff --git a/javalib/src/main/scala/java/nio/TypedArrayShortBuffer.scala b/javalib/src/main/scala/java/nio/TypedArrayShortBuffer.scala index 0c77246b34..09a9ca38dc 100644 --- a/javalib/src/main/scala/java/nio/TypedArrayShortBuffer.scala +++ b/javalib/src/main/scala/java/nio/TypedArrayShortBuffer.scala @@ -128,6 +128,6 @@ private[nio] object TypedArrayShortBuffer { def fromTypedArrayByteBuffer(byteBuffer: TypedArrayByteBuffer): ShortBuffer = GenTypedArrayBuffer.generic_fromTypedArrayByteBuffer(byteBuffer) - def wrap(array: Int16Array): ShortBuffer = + def wrapInt16Array(array: Int16Array): ShortBuffer = new TypedArrayShortBuffer(array, 0, array.length, false) } diff --git a/javalib/src/main/scala/java/nio/charset/Charset.scala b/javalib/src/main/scala/java/nio/charset/Charset.scala index 4e8fe7bb6f..2c5ac9e42c 100644 --- a/javalib/src/main/scala/java/nio/charset/Charset.scala +++ b/javalib/src/main/scala/java/nio/charset/Charset.scala @@ -12,6 +12,7 @@ package java.nio.charset +import java.lang.Utils._ import java.nio.{ByteBuffer, CharBuffer} import java.util.{Collections, HashSet, Arrays} import java.util.ScalaOps._ @@ -30,16 +31,16 @@ abstract class Charset protected (canonicalName: String, final def aliases(): java.util.Set[String] = aliasesSet override final def equals(that: Any): Boolean = that match { - case that: Charset => this.name == that.name + case that: Charset => this.name() == that.name() case _ => false } override final def toString(): String = name() - override final def hashCode(): Int = name.## + override final def hashCode(): Int = name().hashCode() override final def compareTo(that: Charset): Int = - name.compareToIgnoreCase(that.name) + name().compareToIgnoreCase(that.name()) def contains(cs: Charset): Boolean @@ -69,7 +70,7 @@ abstract class Charset protected (canonicalName: String, final def encode(str: String): ByteBuffer = encode(CharBuffer.wrap(str)) - def displayName(): String = name + def displayName(): String = name() } object Charset { @@ -78,20 +79,22 @@ object Charset { def defaultCharset(): Charset = UTF_8 - def forName(charsetName: String): Charset = - CharsetMap.getOrElse(charsetName.toLowerCase, - throw new UnsupportedCharsetException(charsetName)) + def forName(charsetName: String): Charset = { + dictGetOrElse(CharsetMap, charsetName.toLowerCase()) { + throw new UnsupportedCharsetException(charsetName) + } + } def isSupported(charsetName: String): Boolean = - CharsetMap.contains(charsetName.toLowerCase) + dictContains(CharsetMap, charsetName.toLowerCase()) private lazy val CharsetMap = { - val m = js.Dictionary.empty[Charset] - for (c <- js.Array(US_ASCII, ISO_8859_1, UTF_8, UTF_16BE, UTF_16LE, UTF_16)) { - m(c.name.toLowerCase) = c + val m = dictEmpty[Charset]() + forArrayElems(js.Array(US_ASCII, ISO_8859_1, UTF_8, UTF_16BE, UTF_16LE, UTF_16)) { c => + dictSet(m, c.name().toLowerCase(), c) val aliases = c._aliases for (i <- 0 until aliases.length) - m(aliases(i).toLowerCase) = c + dictSet(m, aliases(i).toLowerCase(), c) } m } diff --git a/javalib/src/main/scala/java/nio/charset/CharsetDecoder.scala b/javalib/src/main/scala/java/nio/charset/CharsetDecoder.scala index b8ab57270d..3268cbc98b 100644 --- a/javalib/src/main/scala/java/nio/charset/CharsetDecoder.scala +++ b/javalib/src/main/scala/java/nio/charset/CharsetDecoder.scala @@ -42,7 +42,7 @@ abstract class CharsetDecoder protected (cs: Charset, final def replaceWith(newReplacement: String): CharsetDecoder = { if (newReplacement == null || newReplacement == "") throw new IllegalArgumentException("Invalid replacement: "+newReplacement) - if (newReplacement.length > maxCharsPerByte) + if (newReplacement.length() > maxCharsPerByte()) throw new IllegalArgumentException( "Replacement string cannot be longer than maxCharsPerByte") _replacement = newReplacement @@ -99,8 +99,8 @@ abstract class CharsetDecoder protected (cs: Charset, throw new CoderMalfunctionError(ex) } - val result2 = if (result1.isUnderflow) { - val remaining = in.remaining + val result2 = if (result1.isUnderflow()) { + val remaining = in.remaining() if (endOfInput && remaining > 0) CoderResult.malformedForLength(remaining) else @@ -109,26 +109,26 @@ abstract class CharsetDecoder protected (cs: Charset, result1 } - if (result2.isUnderflow || result2.isOverflow) { + if (result2.isUnderflow() || result2.isOverflow()) { result2 } else { val action = - if (result2.isUnmappable) unmappableCharacterAction - else malformedInputAction + if (result2.isUnmappable()) unmappableCharacterAction() + else malformedInputAction() action match { case CodingErrorAction.REPLACE => - if (out.remaining < replacement.length) { + if (out.remaining() < replacement().length) { CoderResult.OVERFLOW } else { - out.put(replacement) - in.position(in.position() + result2.length) + out.put(replacement()) + in.position(in.position() + result2.length()) loop() } case CodingErrorAction.REPORT => result2 case CodingErrorAction.IGNORE => - in.position(in.position() + result2.length) + in.position(in.position() + result2.length()) loop() } } @@ -141,7 +141,7 @@ abstract class CharsetDecoder protected (cs: Charset, (status: @switch) match { case END => val result = implFlush(out) - if (result.isUnderflow) + if (result.isUnderflow()) status = FLUSHED result case FLUSHED => @@ -166,10 +166,10 @@ abstract class CharsetDecoder protected (cs: Charset, final def decode(in: ByteBuffer): CharBuffer = { def grow(out: CharBuffer): CharBuffer = { - if (out.capacity == 0) { + if (out.capacity() == 0) { CharBuffer.allocate(1) } else { - val result = CharBuffer.allocate(out.capacity*2) + val result = CharBuffer.allocate(out.capacity() * 2) out.flip() result.put(out) result @@ -180,11 +180,11 @@ abstract class CharsetDecoder protected (cs: Charset, @tailrec def loopDecode(out: CharBuffer): CharBuffer = { val result = decode(in, out, endOfInput = true) - if (result.isUnderflow) { - if (in.hasRemaining) + if (result.isUnderflow()) { + if (in.hasRemaining()) throw new AssertionError out - } else if (result.isOverflow) { + } else if (result.isOverflow()) { loopDecode(grow(out)) } else { result.throwException() @@ -196,9 +196,9 @@ abstract class CharsetDecoder protected (cs: Charset, @tailrec def loopFlush(out: CharBuffer): CharBuffer = { val result = flush(out) - if (result.isUnderflow) { + if (result.isUnderflow()) { out - } else if (result.isOverflow) { + } else if (result.isOverflow()) { loopFlush(grow(out)) } else { result.throwException() @@ -207,7 +207,7 @@ abstract class CharsetDecoder protected (cs: Charset, } reset() - val initLength = (in.remaining.toDouble * averageCharsPerByte).toInt + val initLength = (in.remaining().toDouble * averageCharsPerByte()).toInt val out = loopFlush(loopDecode(CharBuffer.allocate(initLength))) out.flip() out diff --git a/javalib/src/main/scala/java/nio/charset/CharsetEncoder.scala b/javalib/src/main/scala/java/nio/charset/CharsetEncoder.scala index df992fb1f0..dffade7a1f 100644 --- a/javalib/src/main/scala/java/nio/charset/CharsetEncoder.scala +++ b/javalib/src/main/scala/java/nio/charset/CharsetEncoder.scala @@ -46,7 +46,7 @@ abstract class CharsetEncoder protected (cs: Charset, final def replaceWith(newReplacement: Array[Byte]): CharsetEncoder = { if (newReplacement == null || newReplacement.length == 0 || - newReplacement.length > maxBytesPerChar || + newReplacement.length > maxBytesPerChar() || !isLegalReplacement(newReplacement)) throw new IllegalArgumentException @@ -58,17 +58,17 @@ abstract class CharsetEncoder protected (cs: Charset, protected def implReplaceWith(newReplacement: Array[Byte]): Unit = () def isLegalReplacement(repl: Array[Byte]): Boolean = { - val decoder = charset.newDecoder + val decoder = charset().newDecoder() val replBuf = ByteBuffer.wrap(repl) @inline @tailrec def loop(outBufSize: Int): Boolean = { val result = decoder.decode(replBuf, CharBuffer.allocate(outBufSize), true) - if (result.isOverflow) { + if (result.isOverflow()) { loop(outBufSize * 2) } else { - !replBuf.hasRemaining + !replBuf.hasRemaining() } } @@ -122,8 +122,8 @@ abstract class CharsetEncoder protected (cs: Charset, throw new CoderMalfunctionError(ex) } - val result2 = if (result1.isUnderflow) { - val remaining = in.remaining + val result2 = if (result1.isUnderflow()) { + val remaining = in.remaining() if (endOfInput && remaining > 0) CoderResult.malformedForLength(remaining) else @@ -132,26 +132,26 @@ abstract class CharsetEncoder protected (cs: Charset, result1 } - if (result2.isUnderflow || result2.isOverflow) { + if (result2.isUnderflow() || result2.isOverflow()) { result2 } else { val action = - if (result2.isUnmappable) unmappableCharacterAction - else malformedInputAction + if (result2.isUnmappable()) unmappableCharacterAction() + else malformedInputAction() action match { case CodingErrorAction.REPLACE => - if (out.remaining < replacement.length) { + if (out.remaining() < replacement().length) { CoderResult.OVERFLOW } else { - out.put(replacement) - in.position(in.position() + result2.length) + out.put(replacement()) + in.position(in.position() + result2.length()) loop() } case CodingErrorAction.REPORT => result2 case CodingErrorAction.IGNORE => - in.position(in.position() + result2.length) + in.position(in.position() + result2.length()) loop() } } @@ -164,7 +164,7 @@ abstract class CharsetEncoder protected (cs: Charset, (status: @switch) match { case END => val result = implFlush(out) - if (result.isUnderflow) + if (result.isUnderflow()) status = FLUSHED result case FLUSHED => @@ -189,28 +189,28 @@ abstract class CharsetEncoder protected (cs: Charset, final def encode(in: CharBuffer): ByteBuffer = { def grow(out: ByteBuffer): ByteBuffer = { - if (out.capacity == 0) { + if (out.capacity() == 0) { ByteBuffer.allocate(1) } else { - val result = ByteBuffer.allocate(out.capacity*2) + val result = ByteBuffer.allocate(out.capacity() * 2) out.flip() result.put(out) result } } - if (in.remaining == 0) { + if (in.remaining() == 0) { ByteBuffer.allocate(0) } else { @inline @tailrec def loopEncode(out: ByteBuffer): ByteBuffer = { val result = encode(in, out, endOfInput = true) - if (result.isUnderflow) { - if (in.hasRemaining) + if (result.isUnderflow()) { + if (in.hasRemaining()) throw new AssertionError out - } else if (result.isOverflow) { + } else if (result.isOverflow()) { loopEncode(grow(out)) } else { result.throwException() @@ -222,9 +222,9 @@ abstract class CharsetEncoder protected (cs: Charset, @tailrec def loopFlush(out: ByteBuffer): ByteBuffer = { val result = flush(out) - if (result.isUnderflow) { + if (result.isUnderflow()) { out - } else if (result.isOverflow) { + } else if (result.isOverflow()) { loopFlush(grow(out)) } else { result.throwException() @@ -233,7 +233,7 @@ abstract class CharsetEncoder protected (cs: Charset, } reset() - val initLength = (in.remaining * averageBytesPerChar).toInt + val initLength = (in.remaining() * averageBytesPerChar()).toInt val out = loopFlush(loopEncode(ByteBuffer.allocate(initLength))) out.flip() out diff --git a/javalib/src/main/scala/java/nio/charset/CoderResult.scala b/javalib/src/main/scala/java/nio/charset/CoderResult.scala index 0721da1988..4cbb5a9fd0 100644 --- a/javalib/src/main/scala/java/nio/charset/CoderResult.scala +++ b/javalib/src/main/scala/java/nio/charset/CoderResult.scala @@ -14,6 +14,7 @@ package java.nio.charset import scala.annotation.switch +import java.lang.Utils._ import java.nio._ import scala.scalajs.js @@ -26,7 +27,7 @@ class CoderResult private (kind: Int, _length: Int) { @inline def isMalformed(): Boolean = kind == Malformed @inline def isUnmappable(): Boolean = kind == Unmappable - @inline def isError(): Boolean = isMalformed || isUnmappable + @inline def isError(): Boolean = isMalformed() || isUnmappable() @inline def length(): Int = { val l = _length @@ -77,7 +78,7 @@ object CoderResult { } private def malformedForLengthImpl(length: Int): CoderResult = { - uniqueMalformed(length).fold { + undefOrFold(uniqueMalformed(length)) { val result = new CoderResult(Malformed, length) uniqueMalformed(length) = result result @@ -95,7 +96,7 @@ object CoderResult { } private def unmappableForLengthImpl(length: Int): CoderResult = { - uniqueUnmappable(length).fold { + undefOrFold(uniqueUnmappable(length)) { val result = new CoderResult(Unmappable, length) uniqueUnmappable(length) = result result diff --git a/javalib/src/main/scala/java/nio/charset/ISO_8859_1_And_US_ASCII_Common.scala b/javalib/src/main/scala/java/nio/charset/ISO_8859_1_And_US_ASCII_Common.scala index 92549b7273..f8689e7411 100644 --- a/javalib/src/main/scala/java/nio/charset/ISO_8859_1_And_US_ASCII_Common.scala +++ b/javalib/src/main/scala/java/nio/charset/ISO_8859_1_And_US_ASCII_Common.scala @@ -39,22 +39,22 @@ private[charset] abstract class ISO_8859_1_And_US_ASCII_Common protected ( def decodeLoop(in: ByteBuffer, out: CharBuffer): CoderResult = { // scalastyle:off return val maxValue = ISO_8859_1_And_US_ASCII_Common.this.maxValue - val inRemaining = in.remaining + val inRemaining = in.remaining() if (inRemaining == 0) { CoderResult.UNDERFLOW } else { - val outRemaining = out.remaining + val outRemaining = out.remaining() val overflow = outRemaining < inRemaining val rem = if (overflow) outRemaining else inRemaining - if (in.hasArray && out.hasArray) { - val inArr = in.array - val inOffset = in.arrayOffset + if (in.hasArray() && out.hasArray()) { + val inArr = in.array() + val inOffset = in.arrayOffset() val inStart = in.position() + inOffset val inEnd = inStart + rem - val outArr = out.array - val outOffset = out.arrayOffset + val outArr = out.array() + val outOffset = out.arrayOffset() val outStart = out.position() + outOffset var inPos = inStart @@ -105,22 +105,22 @@ private[charset] abstract class ISO_8859_1_And_US_ASCII_Common protected ( import java.lang.Character.{MIN_SURROGATE, MAX_SURROGATE} val maxValue = ISO_8859_1_And_US_ASCII_Common.this.maxValue - val inRemaining = in.remaining + val inRemaining = in.remaining() if (inRemaining == 0) { CoderResult.UNDERFLOW } else { - if (in.hasArray && out.hasArray) { - val outRemaining = out.remaining + if (in.hasArray() && out.hasArray()) { + val outRemaining = out.remaining() val overflow = outRemaining < inRemaining val rem = if (overflow) outRemaining else inRemaining - val inArr = in.array - val inOffset = in.arrayOffset + val inArr = in.array() + val inOffset = in.arrayOffset() val inStart = in.position() + inOffset val inEnd = inStart + rem - val outArr = out.array - val outOffset = out.arrayOffset + val outArr = out.array() + val outOffset = out.arrayOffset() val outStart = out.position() + outOffset @inline @@ -171,9 +171,9 @@ private[charset] abstract class ISO_8859_1_And_US_ASCII_Common protected ( @inline @tailrec def loop(): CoderResult = { - if (!in.hasRemaining) { + if (!in.hasRemaining()) { CoderResult.UNDERFLOW - } else if (!out.hasRemaining) { + } else if (!out.hasRemaining()) { CoderResult.OVERFLOW } else { val c = in.get() @@ -185,7 +185,7 @@ private[charset] abstract class ISO_8859_1_And_US_ASCII_Common protected ( in.position(in.position() - 1) CoderResult.malformedForLength(1) } else if (Character.isHighSurrogate(c)) { - if (in.hasRemaining) { + if (in.hasRemaining()) { val c2 = in.get() in.position(in.position() - 2) if (Character.isLowSurrogate(c2)) { diff --git a/javalib/src/main/scala/java/nio/charset/UTF_16_Common.scala b/javalib/src/main/scala/java/nio/charset/UTF_16_Common.scala index 5e49ccd795..be95d536e3 100644 --- a/javalib/src/main/scala/java/nio/charset/UTF_16_Common.scala +++ b/javalib/src/main/scala/java/nio/charset/UTF_16_Common.scala @@ -42,7 +42,7 @@ private[charset] abstract class UTF_16_Common protected ( @inline @tailrec def loop(): CoderResult = { - if (in.remaining < 2) CoderResult.UNDERFLOW + if (in.remaining() < 2) CoderResult.UNDERFLOW else { val b1 = in.get() & 0xff val b2 = in.get() & 0xff @@ -76,7 +76,7 @@ private[charset] abstract class UTF_16_Common protected ( in.position(in.position() - 2) CoderResult.malformedForLength(2) } else if (!Character.isHighSurrogate(c1)) { - if (out.remaining == 0) { + if (out.remaining() == 0) { in.position(in.position() - 2) CoderResult.OVERFLOW } else { @@ -84,7 +84,7 @@ private[charset] abstract class UTF_16_Common protected ( loop() } } else { - if (in.remaining < 2) { + if (in.remaining() < 2) { in.position(in.position() - 2) CoderResult.UNDERFLOW } else { @@ -96,7 +96,7 @@ private[charset] abstract class UTF_16_Common protected ( in.position(in.position() - 4) CoderResult.malformedForLength(4) } else { - if (out.remaining < 2) { + if (out.remaining() < 2) { in.position(in.position() - 4) CoderResult.OVERFLOW } else { @@ -119,7 +119,7 @@ private[charset] abstract class UTF_16_Common protected ( UTF_16_Common.this, 2.0f, if (endianness == AutoEndian) 4.0f else 2.0f, // Character 0xfffd - if (endianness == LittleEndian) Array(-3, -1) else Array(-1, -3)) { + if (endianness == LittleEndian) Array(-3.toByte, -1.toByte) else Array(-1.toByte, -3.toByte)) { private var needToWriteBOM: Boolean = endianness == AutoEndian @@ -130,7 +130,7 @@ private[charset] abstract class UTF_16_Common protected ( def encodeLoop(in: CharBuffer, out: ByteBuffer): CoderResult = { if (needToWriteBOM) { - if (out.remaining < 2) { + if (out.remaining() < 2) { return CoderResult.OVERFLOW // scalastyle:ignore } else { // Always encode in big endian @@ -156,7 +156,7 @@ private[charset] abstract class UTF_16_Common protected ( @inline @tailrec def loop(): CoderResult = { - if (in.remaining == 0) CoderResult.UNDERFLOW + if (in.remaining() == 0) CoderResult.UNDERFLOW else { val c1 = in.get() @@ -164,7 +164,7 @@ private[charset] abstract class UTF_16_Common protected ( in.position(in.position() - 1) CoderResult.malformedForLength(1) } else if (!Character.isHighSurrogate(c1)) { - if (out.remaining < 2) { + if (out.remaining() < 2) { in.position(in.position() - 1) CoderResult.OVERFLOW } else { @@ -172,7 +172,7 @@ private[charset] abstract class UTF_16_Common protected ( loop() } } else { - if (in.remaining < 1) { + if (in.remaining() < 1) { in.position(in.position() - 1) CoderResult.UNDERFLOW } else { @@ -182,7 +182,7 @@ private[charset] abstract class UTF_16_Common protected ( in.position(in.position() - 2) CoderResult.malformedForLength(1) } else { - if (out.remaining < 4) { + if (out.remaining() < 4) { in.position(in.position() - 2) CoderResult.OVERFLOW } else { diff --git a/javalib/src/main/scala/java/nio/charset/UTF_8.scala b/javalib/src/main/scala/java/nio/charset/UTF_8.scala index 345c76f197..9e155bfb4a 100644 --- a/javalib/src/main/scala/java/nio/charset/UTF_8.scala +++ b/javalib/src/main/scala/java/nio/charset/UTF_8.scala @@ -73,20 +73,20 @@ private[charset] object UTF_8 extends Charset("UTF-8", Array( private class Decoder extends CharsetDecoder(UTF_8, 1.0f, 1.0f) { def decodeLoop(in: ByteBuffer, out: CharBuffer): CoderResult = { - if (in.hasArray && out.hasArray) + if (in.hasArray() && out.hasArray()) decodeLoopArray(in, out) else decodeLoopNoArray(in, out) } private def decodeLoopArray(in: ByteBuffer, out: CharBuffer): CoderResult = { - val inArray = in.array - val inOffset = in.arrayOffset + val inArray = in.array() + val inOffset = in.arrayOffset() val inStart = in.position() + inOffset val inEnd = in.limit() + inOffset - val outArray = out.array - val outOffset = out.arrayOffset + val outArray = out.array() + val outOffset = out.arrayOffset() val outStart = out.position() + outOffset val outEnd = out.limit() + outOffset @@ -189,13 +189,13 @@ private[charset] object UTF_8 extends Charset("UTF-8", Array( result } - if (!in.hasRemaining) { + if (!in.hasRemaining()) { CoderResult.UNDERFLOW } else { val leading = in.get().toInt if (leading >= 0) { // US-ASCII repertoire - if (!out.hasRemaining) { + if (!out.hasRemaining()) { fail(CoderResult.OVERFLOW) } else { out.put(leading.toChar) @@ -208,19 +208,19 @@ private[charset] object UTF_8 extends Charset("UTF-8", Array( fail(CoderResult.malformedForLength(1)) } else { val decoded = { - if (in.hasRemaining) { + if (in.hasRemaining()) { val b2 = in.get() if (isInvalidNextByte(b2)) { DecodedMultiByte(CoderResult.malformedForLength(1)) } else if (length == 2) { decode2(leading, b2) - } else if (in.hasRemaining) { + } else if (in.hasRemaining()) { val b3 = in.get() if (isInvalidNextByte(b3)) { DecodedMultiByte(CoderResult.malformedForLength(2)) } else if (length == 3) { decode3(leading, b2, b3) - } else if (in.hasRemaining) { + } else if (in.hasRemaining()) { val b4 = in.get() if (isInvalidNextByte(b4)) DecodedMultiByte(CoderResult.malformedForLength(3)) @@ -241,7 +241,7 @@ private[charset] object UTF_8 extends Charset("UTF-8", Array( fail(decoded.failure) } else if (decoded.low == 0) { // not a surrogate pair - if (!out.hasRemaining) + if (!out.hasRemaining()) fail(CoderResult.OVERFLOW) else { out.put(decoded.high) @@ -249,7 +249,7 @@ private[charset] object UTF_8 extends Charset("UTF-8", Array( } } else { // a surrogate pair - if (out.remaining < 2) + if (out.remaining() < 2) fail(CoderResult.OVERFLOW) else { out.put(decoded.high) @@ -317,20 +317,20 @@ private[charset] object UTF_8 extends Charset("UTF-8", Array( private class Encoder extends CharsetEncoder(UTF_8, 1.1f, 3.0f) { def encodeLoop(in: CharBuffer, out: ByteBuffer): CoderResult = { - if (in.hasArray && out.hasArray) + if (in.hasArray() && out.hasArray()) encodeLoopArray(in, out) else encodeLoopNoArray(in, out) } private def encodeLoopArray(in: CharBuffer, out: ByteBuffer): CoderResult = { - val inArray = in.array - val inOffset = in.arrayOffset + val inArray = in.array() + val inOffset = in.arrayOffset() val inStart = in.position() + inOffset val inEnd = in.limit() + inOffset - val outArray = out.array - val outOffset = out.arrayOffset + val outArray = out.array() + val outOffset = out.arrayOffset() val outStart = out.position() + outOffset val outEnd = out.limit() + outOffset @@ -417,14 +417,14 @@ private[charset] object UTF_8 extends Charset("UTF-8", Array( result } - if (!in.hasRemaining) { + if (!in.hasRemaining()) { CoderResult.UNDERFLOW } else { val c1 = in.get() if (c1 < 0x80) { // Encoding in one byte - if (!out.hasRemaining) + if (!out.hasRemaining()) finalize(1, CoderResult.OVERFLOW) else { out.put(c1.toByte) @@ -432,7 +432,7 @@ private[charset] object UTF_8 extends Charset("UTF-8", Array( } } else if (c1 < 0x800) { // Encoding in 2 bytes (by construction, not a surrogate) - if (out.remaining < 2) + if (out.remaining() < 2) finalize(1, CoderResult.OVERFLOW) else { out.put(((c1 >> 6) | 0xc0).toByte) @@ -441,7 +441,7 @@ private[charset] object UTF_8 extends Charset("UTF-8", Array( } } else if (!isSurrogate(c1)) { // Not a surrogate, encoding in 3 bytes - if (out.remaining < 3) + if (out.remaining() < 3) finalize(1, CoderResult.OVERFLOW) else { out.put(((c1 >> 12) | 0xe0).toByte) @@ -451,7 +451,7 @@ private[charset] object UTF_8 extends Charset("UTF-8", Array( } } else if (isHighSurrogate(c1)) { // Should have a low surrogate that follows - if (!in.hasRemaining) + if (!in.hasRemaining()) finalize(1, CoderResult.UNDERFLOW) else { val c2 = in.get() @@ -459,7 +459,7 @@ private[charset] object UTF_8 extends Charset("UTF-8", Array( finalize(2, CoderResult.malformedForLength(1)) } else { // Surrogate pair, encoding in 4 bytes - if (out.remaining < 4) + if (out.remaining() < 4) finalize(2, CoderResult.OVERFLOW) else { val cp = toCodePoint(c1, c2) diff --git a/javalib/src/main/scala/java/security/Permission.scala b/javalib/src/main/scala/java/security/Permission.scala index 8cc6a1e9d5..2e765da0b6 100644 --- a/javalib/src/main/scala/java/security/Permission.scala +++ b/javalib/src/main/scala/java/security/Permission.scala @@ -21,5 +21,5 @@ abstract class Permission(name: String) extends Guard with Serializable { def getActions(): String //def newPermissionCollection(): PermissionCollection override def toString(): String = - s"ClassName ${this.getClass.getName} ${getActions}" + s"ClassName ${this.getClass().getName()} ${getActions()}" } diff --git a/javalib/src/main/scala/java/util/AbstractCollection.scala b/javalib/src/main/scala/java/util/AbstractCollection.scala index ff168a2470..8385d981da 100644 --- a/javalib/src/main/scala/java/util/AbstractCollection.scala +++ b/javalib/src/main/scala/java/util/AbstractCollection.scala @@ -22,24 +22,24 @@ abstract class AbstractCollection[E] protected () extends Collection[E] { def iterator(): Iterator[E] def size(): Int - def isEmpty(): Boolean = size == 0 + def isEmpty(): Boolean = size() == 0 def contains(o: Any): Boolean = this.scalaOps.exists(Objects.equals(o, _)) def toArray(): Array[AnyRef] = - toArray(new Array[AnyRef](size)) + toArray(new Array[AnyRef](size())) def toArray[T <: AnyRef](a: Array[T]): Array[T] = { val toFill: Array[T] = - if (a.length >= size) a - else jlr.Array.newInstance(a.getClass.getComponentType, size).asInstanceOf[Array[T]] + if (a.length >= size()) a + else jlr.Array.newInstance(a.getClass().getComponentType(), size()).asInstanceOf[Array[T]] - val iter = iterator - for (i <- 0 until size) + val iter = iterator() + for (i <- 0 until size()) toFill(i) = iter.next().asInstanceOf[T] - if (toFill.length > size) - toFill(size) = null.asInstanceOf[T] + if (toFill.length > size()) + toFill(size()) = null.asInstanceOf[T] toFill } @@ -49,7 +49,7 @@ abstract class AbstractCollection[E] protected () extends Collection[E] { def remove(o: Any): Boolean = { @tailrec def findAndRemove(iter: Iterator[E]): Boolean = { - if (iter.hasNext) { + if (iter.hasNext()) { if (Objects.equals(iter.next(), o)) { iter.remove() true @@ -81,7 +81,7 @@ abstract class AbstractCollection[E] protected () extends Collection[E] { private def removeWhere(p: Any => Boolean): Boolean = { val iter = iterator() var changed = false - while (iter.hasNext) { + while (iter.hasNext()) { if (p(iter.next())) { iter.remove() changed = true diff --git a/javalib/src/main/scala/java/util/AbstractList.scala b/javalib/src/main/scala/java/util/AbstractList.scala index 848a8d441c..4bf33805e2 100644 --- a/javalib/src/main/scala/java/util/AbstractList.scala +++ b/javalib/src/main/scala/java/util/AbstractList.scala @@ -21,7 +21,7 @@ abstract class AbstractList[E] protected () extends AbstractCollection[E] self => override def add(element: E): Boolean = { - add(size, element) + add(size(), element) true } @@ -40,15 +40,15 @@ abstract class AbstractList[E] protected () extends AbstractCollection[E] def lastIndexOf(o: Any): Int = { @tailrec def findIndex(iter: ListIterator[E]): Int = { - if (!iter.hasPrevious) -1 - else if (Objects.equals(iter.previous(), o)) iter.nextIndex + if (!iter.hasPrevious()) -1 + else if (Objects.equals(iter.previous(), o)) iter.nextIndex() else findIndex(iter) } - findIndex(listIterator(size)) + findIndex(listIterator(size())) } override def clear(): Unit = - removeRange(0, size) + removeRange(0, size()) def addAll(index: Int, c: Collection[_ <: E]): Boolean = { checkIndexOnBounds(index) @@ -58,7 +58,7 @@ abstract class AbstractList[E] protected () extends AbstractCollection[E] add(i, iter.next()) i += 1 } - !c.isEmpty + !c.isEmpty() } def iterator(): Iterator[E] = @@ -72,13 +72,13 @@ abstract class AbstractList[E] protected () extends AbstractCollection[E] // By default we use RandomAccessListIterator because we only have access to // the get(index) operation in the API. Subclasses override this if needs // using their knowledge of the structure instead. - new RandomAccessListIterator(self, index, 0, size) + new RandomAccessListIterator(self, index, 0, size()) } def subList(fromIndex: Int, toIndex: Int): List[E] = { if (fromIndex < 0) throw new IndexOutOfBoundsException(fromIndex.toString) - else if (toIndex > size) + else if (toIndex > size()) throw new IndexOutOfBoundsException(toIndex.toString) else if (fromIndex > toIndex) throw new IllegalArgumentException @@ -114,8 +114,8 @@ abstract class AbstractList[E] protected () extends AbstractCollection[E] } else { o match { case o: List[_] => - val oIter = o.listIterator - this.scalaOps.forall(oIter.hasNext && Objects.equals(_, oIter.next())) && !oIter.hasNext + val oIter = o.listIterator() + this.scalaOps.forall(oIter.hasNext() && Objects.equals(_, oIter.next())) && !oIter.hasNext() case _ => false } } @@ -136,12 +136,12 @@ abstract class AbstractList[E] protected () extends AbstractCollection[E] } protected[this] def checkIndexInBounds(index: Int): Unit = { - if (index < 0 || index >= size) + if (index < 0 || index >= size()) throw new IndexOutOfBoundsException(index.toString) } protected[this] def checkIndexOnBounds(index: Int): Unit = { - if (index < 0 || index > size) + if (index < 0 || index > size()) throw new IndexOutOfBoundsException(index.toString) } } @@ -158,13 +158,13 @@ private abstract class AbstractListView[E](protected val list: List[E], override def addAll(index: Int, c: Collection[_ <: E]): Boolean = { checkIndexOnBounds(index) list.addAll(fromIndex + index, c) - val elementsAdded = c.size + val elementsAdded = c.size() toIndex += elementsAdded elementsAdded != 0 } override def addAll(c: Collection[_ <: E]): Boolean = - addAll(size, c) + addAll(size(), c) def get(index: Int): E = { checkIndexInBounds(index) @@ -215,7 +215,7 @@ private class BackedUpListIterator[E](innerIterator: ListIterator[E], fromIndex: def previousIndex(): Int = i - 1 - def remove(): Unit = { + override def remove(): Unit = { innerIterator.remove() changeSize(-1) } @@ -229,7 +229,7 @@ private class BackedUpListIterator[E](innerIterator: ListIterator[E], fromIndex: } private def i: Int = - innerIterator.nextIndex - fromIndex + innerIterator.nextIndex() - fromIndex } /* RandomAccessListIterator implementation assumes that the has an efficient diff --git a/javalib/src/main/scala/java/util/AbstractMap.scala b/javalib/src/main/scala/java/util/AbstractMap.scala index 5ffff72791..df75f5ba67 100644 --- a/javalib/src/main/scala/java/util/AbstractMap.scala +++ b/javalib/src/main/scala/java/util/AbstractMap.scala @@ -21,20 +21,20 @@ object AbstractMap { private def entryEquals[K, V](entry: Map.Entry[K, V], other: Any): Boolean = { other match { case other: Map.Entry[_, _] => - Objects.equals(entry.getKey, other.getKey) && - Objects.equals(entry.getValue, other.getValue) + Objects.equals(entry.getKey(), other.getKey()) && + Objects.equals(entry.getValue(), other.getValue()) case _ => false } } private def entryHashCode[K, V](entry: Map.Entry[K, V]): Int = - Objects.hashCode(entry.getKey) ^ Objects.hashCode(entry.getValue) + Objects.hashCode(entry.getKey()) ^ Objects.hashCode(entry.getValue()) class SimpleEntry[K, V](private var key: K, private var value: V) extends Map.Entry[K, V] with Serializable { def this(entry: Map.Entry[_ <: K, _ <: V]) = - this(entry.getKey, entry.getValue) + this(entry.getKey(), entry.getValue()) def getKey(): K = key @@ -53,14 +53,14 @@ object AbstractMap { entryHashCode(this) override def toString(): String = - "" + getKey + "=" + getValue + "" + getKey() + "=" + getValue() } class SimpleImmutableEntry[K, V](key: K, value: V) extends Map.Entry[K, V] with Serializable { def this(entry: Map.Entry[_ <: K, _ <: V]) = - this(entry.getKey, entry.getValue) + this(entry.getKey(), entry.getValue()) def getKey(): K = key @@ -76,28 +76,28 @@ object AbstractMap { entryHashCode(this) override def toString(): String = - "" + getKey + "=" + getValue + "" + getKey() + "=" + getValue() } } abstract class AbstractMap[K, V] protected () extends java.util.Map[K, V] { self => - def size(): Int = entrySet.size + def size(): Int = entrySet().size() - def isEmpty(): Boolean = size == 0 + def isEmpty(): Boolean = size() == 0 def containsValue(value: Any): Boolean = - entrySet.scalaOps.exists(entry => Objects.equals(value, entry.getValue)) + entrySet().scalaOps.exists(entry => Objects.equals(value, entry.getValue())) def containsKey(key: Any): Boolean = - entrySet.scalaOps.exists(entry => Objects.equals(key, entry.getKey)) + entrySet().scalaOps.exists(entry => Objects.equals(key, entry.getKey())) def get(key: Any): V = { - entrySet.scalaOps.find(entry => Objects.equals(key, entry.getKey)).fold[V] { + entrySet().scalaOps.findFold(entry => Objects.equals(key, entry.getKey())) { null.asInstanceOf[V] } { entry => - entry.getValue + entry.getValue() } } @@ -107,38 +107,38 @@ abstract class AbstractMap[K, V] protected () extends java.util.Map[K, V] { def remove(key: Any): V = { @tailrec def findAndRemove(iter: Iterator[Map.Entry[K, V]]): V = { - if (iter.hasNext) { + if (iter.hasNext()) { val item = iter.next() - if (Objects.equals(key, item.getKey)) { + if (Objects.equals(key, item.getKey())) { iter.remove() - item.getValue + item.getValue() } else findAndRemove(iter) } else null.asInstanceOf[V] } - findAndRemove(entrySet.iterator) + findAndRemove(entrySet().iterator()) } def putAll(m: Map[_ <: K, _ <: V]): Unit = - m.entrySet.scalaOps.foreach(e => put(e.getKey, e.getValue)) + m.entrySet().scalaOps.foreach(e => put(e.getKey(), e.getValue())) def clear(): Unit = - entrySet.clear() + entrySet().clear() def keySet(): Set[K] = { new AbstractSet[K] { - override def size(): Int = self.size + override def size(): Int = self.size() def iterator(): Iterator[K] = { new Iterator[K] { - val iter = entrySet.iterator() + val iter = entrySet().iterator() def hasNext(): Boolean = iter.hasNext() def next(): K = iter.next().getKey() - def remove(): Unit = iter.remove() + override def remove(): Unit = iter.remove() } } } @@ -146,17 +146,17 @@ abstract class AbstractMap[K, V] protected () extends java.util.Map[K, V] { def values(): Collection[V] = { new AbstractCollection[V] { - override def size(): Int = self.size + override def size(): Int = self.size() def iterator(): Iterator[V] = { new Iterator[V] { - val iter = entrySet.iterator() + val iter = entrySet().iterator() def hasNext(): Boolean = iter.hasNext() def next(): V = iter.next().getValue() - def remove(): Unit = iter.remove() + override def remove(): Unit = iter.remove() } } } @@ -169,15 +169,15 @@ abstract class AbstractMap[K, V] protected () extends java.util.Map[K, V] { else { o match { case m: Map[_, _] => - self.size == m.size && - entrySet.scalaOps.forall(item => Objects.equals(m.get(item.getKey), item.getValue)) + self.size() == m.size() && + entrySet().scalaOps.forall(item => Objects.equals(m.get(item.getKey()), item.getValue())) case _ => false } } } override def hashCode(): Int = - entrySet.scalaOps.foldLeft(0)((prev, item) => item.hashCode + prev) + entrySet().scalaOps.foldLeft(0)((prev, item) => item.hashCode + prev) override def toString(): String = { var result = "{" diff --git a/javalib/src/main/scala/java/util/AbstractQueue.scala b/javalib/src/main/scala/java/util/AbstractQueue.scala index e1eb450d20..913779d91e 100644 --- a/javalib/src/main/scala/java/util/AbstractQueue.scala +++ b/javalib/src/main/scala/java/util/AbstractQueue.scala @@ -32,7 +32,7 @@ abstract class AbstractQueue[E] protected () } override def addAll(c: Collection[_ <: E]): Boolean = { - val iter = c.iterator + val iter = c.iterator() var changed = false while (iter.hasNext()) changed = add(iter.next()) || changed diff --git a/javalib/src/main/scala/java/util/AbstractRandomAccessListIterator.scala b/javalib/src/main/scala/java/util/AbstractRandomAccessListIterator.scala index 24b9c853e7..98b674f4c5 100644 --- a/javalib/src/main/scala/java/util/AbstractRandomAccessListIterator.scala +++ b/javalib/src/main/scala/java/util/AbstractRandomAccessListIterator.scala @@ -21,6 +21,9 @@ abstract private[util] class AbstractRandomAccessListIterator[E](private var i: i < end def next(): E = { + if (!hasNext()) + throw new NoSuchElementException() + last = i i += 1 get(last) @@ -30,6 +33,9 @@ abstract private[util] class AbstractRandomAccessListIterator[E](private var i: start < i def previous(): E = { + if (!hasPrevious()) + throw new NoSuchElementException() + i -= 1 last = i get(last) @@ -39,7 +45,7 @@ abstract private[util] class AbstractRandomAccessListIterator[E](private var i: def previousIndex(): Int = i - 1 - def remove(): Unit = { + override def remove(): Unit = { checkThatHasLast() remove(last) if (last < i) diff --git a/javalib/src/main/scala/java/util/AbstractSequentialList.scala b/javalib/src/main/scala/java/util/AbstractSequentialList.scala index 37015ecade..5d28753c6d 100644 --- a/javalib/src/main/scala/java/util/AbstractSequentialList.scala +++ b/javalib/src/main/scala/java/util/AbstractSequentialList.scala @@ -17,13 +17,13 @@ abstract class AbstractSequentialList[E] protected () def get(index: Int): E = { val iter = listIterator(index) - if (iter.hasNext) iter.next() + if (iter.hasNext()) iter.next() else throw new IndexOutOfBoundsException(index.toString) } override def set(index: Int, element: E): E = { val iter = listIterator(index) - if (!iter.hasNext) + if (!iter.hasNext()) throw new IndexOutOfBoundsException val ret = iter.next() iter.set(element) @@ -35,10 +35,10 @@ abstract class AbstractSequentialList[E] protected () override def remove(index: Int): E = { val iter = listIterator(index) - if (!iter.hasNext) + if (!iter.hasNext()) throw new IndexOutOfBoundsException val ret = iter.next() - iter.remove + iter.remove() ret } diff --git a/javalib/src/main/scala/java/util/AbstractSet.scala b/javalib/src/main/scala/java/util/AbstractSet.scala index fd3487bfc9..d67514446b 100644 --- a/javalib/src/main/scala/java/util/AbstractSet.scala +++ b/javalib/src/main/scala/java/util/AbstractSet.scala @@ -22,7 +22,7 @@ abstract class AbstractSet[E] protected () extends AbstractCollection[E] if (that.asInstanceOf[AnyRef] eq this) true else { that match { - case that: Collection[_] => that.size == this.size && containsAll(that) + case that: Collection[_] => that.size() == this.size() && containsAll(that) case _ => false } } @@ -32,12 +32,12 @@ abstract class AbstractSet[E] protected () extends AbstractCollection[E] this.scalaOps.foldLeft(0)((prev, item) => item.hashCode + prev) override def removeAll(c: Collection[_]): Boolean = { - if (size > c.size) { + if (size() > c.size()) { c.scalaOps.foldLeft(false)((prev, elem) => this.remove(elem) || prev) } else { @tailrec def removeAll(iter: Iterator[E], modified: Boolean): Boolean = { - if (iter.hasNext) { + if (iter.hasNext()) { if (c.contains(iter.next())) { iter.remove() removeAll(iter, true) @@ -48,7 +48,7 @@ abstract class AbstractSet[E] protected () extends AbstractCollection[E] modified } } - removeAll(this.iterator, false) + removeAll(this.iterator(), false) } } } diff --git a/javalib/src/main/scala/java/util/ArrayDeque.scala b/javalib/src/main/scala/java/util/ArrayDeque.scala index 05c43d4b5e..b45e075d03 100644 --- a/javalib/src/main/scala/java/util/ArrayDeque.scala +++ b/javalib/src/main/scala/java/util/ArrayDeque.scala @@ -12,29 +12,36 @@ package java.util +import java.lang.Cloneable +import java.lang.Utils._ + +import java.util.ScalaOps._ + import scala.scalajs.js -class ArrayDeque[E] private (private var inner: js.Array[E]) +class ArrayDeque[E] private (initialCapacity: Int) extends AbstractCollection[E] with Deque[E] with Cloneable with Serializable { self => - private var status = 0 + private val inner: js.Array[E] = new js.Array[E](Math.max(initialCapacity, 16)) - def this(initialCapacity: Int) = { - this(new js.Array[E]) + fillNulls(0, inner.length) - if (initialCapacity < 0) - throw new IllegalArgumentException - } + private var status = 0 + private var startIndex = 0 // inclusive, 0 <= startIndex < inner.length + private var endIndex = inner.length // exclusive, 0 < endIndex <= inner.length + private var empty = true - def this() = - this(16) + def this() = this(16) def this(c: Collection[_ <: E]) = { - this() + this(c.size()) addAll(c) } + @inline + override def isEmpty(): Boolean = empty + def addFirst(e: E): Unit = offerFirst(e) @@ -45,8 +52,13 @@ class ArrayDeque[E] private (private var inner: js.Array[E]) if (e == null) { throw new NullPointerException() } else { - inner = e +: inner + ensureCapacityForAdd() + startIndex -= 1 + if (startIndex < 0) + startIndex = inner.length - 1 + inner(startIndex) = e status += 1 + empty = false true } } @@ -55,82 +67,104 @@ class ArrayDeque[E] private (private var inner: js.Array[E]) if (e == null) { throw new NullPointerException() } else { - inner += e + ensureCapacityForAdd() + endIndex += 1 + if (endIndex > inner.length) + endIndex = 1 + inner(endIndex - 1) = e status += 1 + empty = false true } } def removeFirst(): E = { - if (inner.isEmpty) + if (isEmpty()) throw new NoSuchElementException() else pollFirst() } def removeLast(): E = { - if (inner.isEmpty) + if (isEmpty()) throw new NoSuchElementException() else pollLast() } def pollFirst(): E = { - if (inner.isEmpty) null.asInstanceOf[E] + if (isEmpty()) null.asInstanceOf[E] else { - val res = inner.remove(0) + val res = inner(startIndex) + inner(startIndex) = null.asInstanceOf[E] // free reference for GC + startIndex += 1 + if (startIndex == endIndex) + empty = true + if (startIndex >= inner.length) + startIndex = 0 status += 1 res } } def pollLast(): E = { - if (inner.isEmpty) null.asInstanceOf[E] - else inner.pop() + if (isEmpty()) { + null.asInstanceOf[E] + } else { + val res = inner(endIndex - 1) + inner(endIndex - 1) = null.asInstanceOf[E] // free reference for GC + endIndex -= 1 + if (startIndex == endIndex) + empty = true + if (endIndex <= 0) + endIndex = inner.length + status += 1 + res + } } def getFirst(): E = { - if (inner.isEmpty) + if (isEmpty()) throw new NoSuchElementException() else peekFirst() } def getLast(): E = { - if (inner.isEmpty) + if (isEmpty()) throw new NoSuchElementException() else peekLast() } def peekFirst(): E = { - if (inner.isEmpty) null.asInstanceOf[E] - else inner.head + if (isEmpty()) null.asInstanceOf[E] + else inner(startIndex) } def peekLast(): E = { - if (inner.isEmpty) null.asInstanceOf[E] - else inner.last + if (isEmpty()) null.asInstanceOf[E] + else inner(endIndex - 1) } def removeFirstOccurrence(o: Any): Boolean = { - val index = inner.indexWhere(Objects.equals(_, o)) - if (index >= 0) { - inner.remove(index) - status += 1 - true - } else + val i = firstIndexOf(o) + if (i == -1) { false + } else { + removeAt(i) + true + } } def removeLastOccurrence(o: Any): Boolean = { - val index = inner.lastIndexWhere(Objects.equals(_, o)) - if (index >= 0) { - inner.remove(index) - status += 1 - true - } else + val i = lastIndexOf(o) + if (i == -1) { false + } else { + removeAt(i) + true + } } override def add(e: E): Boolean = { @@ -152,53 +186,274 @@ class ArrayDeque[E] private (private var inner: js.Array[E]) def pop(): E = removeFirst() - def size(): Int = inner.size + def size(): Int = { + if (isEmpty()) 0 + else if (endIndex > startIndex) endIndex - startIndex + else (endIndex + inner.length) - startIndex + } + + def iterator(): Iterator[E] = new Iterator[E] { + private def checkStatus() = { + if (self.status != expectedStatus) + throw new ConcurrentModificationException() + } + + private var expectedStatus = self.status + + private var lastIndex: Int = -1 + private var nextIndex: Int = + if (isEmpty()) -1 + else startIndex + + def hasNext(): Boolean = { + checkStatus() + nextIndex != -1 + } + + def next(): E = { + if (!hasNext()) // also checks status + throw new NoSuchElementException() - private def failFastIterator(startIndex: Int, nex: (Int) => Int) = { - new Iterator[E] { - private def checkStatus() = - if (self.status != actualStatus) - throw new ConcurrentModificationException() + lastIndex = nextIndex - private val actualStatus = self.status + nextIndex += 1 + if (nextIndex == endIndex) + nextIndex = -1 + else if (nextIndex >= inner.length) + nextIndex = 0 - private var index: Int = startIndex + inner(lastIndex) + } - def hasNext(): Boolean = { - checkStatus() - val n = nex(index) - (n >= 0) && (n < inner.size) + override def remove(): Unit = { + checkStatus() + if (lastIndex == -1) + throw new IllegalStateException() + + val laterShifted = removeAt(lastIndex) + lastIndex = -1 + expectedStatus = self.status + + if (laterShifted && nextIndex != -1) { + /* assert(nextIndex != 0) + * Why? Assume nextIndex == 0, that means the element we just removed + * was at the end of the ring-buffer. But in this case, removeAt shifts + * forward to avoid copying over the buffer boundary. + * Therefore, laterShifted cannot be true. + */ + nextIndex -= 1 } + } + } + + def descendingIterator(): Iterator[E] = new Iterator[E] { + private def checkStatus() = { + if (self.status != expectedStatus) + throw new ConcurrentModificationException() + } + + private var expectedStatus = self.status + + private var lastIndex: Int = -1 + private var nextIndex: Int = + if (isEmpty()) -1 + else endIndex - 1 + + def hasNext(): Boolean = { + checkStatus() + nextIndex != -1 + } - def next(): E = { - checkStatus() - index = nex(index) - inner(index) + def next(): E = { + if (!hasNext()) // also checks status + throw new NoSuchElementException() + + lastIndex = nextIndex + + if (nextIndex == startIndex) { + nextIndex = -1 + } else { + nextIndex -= 1 + if (nextIndex < 0) + nextIndex = inner.length - 1 } - def remove(): Unit = { - checkStatus() - if (index < 0 || index >= inner.size) { + inner(lastIndex) + } + + override def remove(): Unit = { + checkStatus() + if (lastIndex == -1) throw new IllegalStateException() - } else { - inner.remove(index) - } + + + val laterShifted = removeAt(lastIndex) + expectedStatus = self.status + lastIndex = -1 + + if (!laterShifted && nextIndex != -1) { + /* assert(nextIndex < inner.length - 1) + * Why? Assume nextIndex == inner.length - 1, that means the element we + * just removed was at the beginning of the ring buffer (recall, this is + * a backwards iterator). However, in this case, removeAt would shift + * the next elements (in forward iteration order) backwards. + * That implies laterShifted, so we would not hit this branch. + */ + nextIndex += 1 } } } - def iterator(): Iterator[E] = - failFastIterator(-1, x => (x + 1)) - - def descendingIterator(): Iterator[E] = - failFastIterator(inner.size, x => (x - 1)) - - override def contains(o: Any): Boolean = inner.exists(Objects.equals(_, o)) + override def contains(o: Any): Boolean = firstIndexOf(o) != -1 override def remove(o: Any): Boolean = removeFirstOccurrence(o) override def clear(): Unit = { - if (!inner.isEmpty) status += 1 - inner.clear() + if (!isEmpty()) + status += 1 + empty = true + startIndex = 0 + endIndex = inner.length + } + + private def firstIndexOf(o: Any): Int = { + // scalastyle:off return + if (isEmpty()) + return -1 + val inner = this.inner // local copy + val capacity = inner.length // local copy + val endIndex = this.endIndex // local copy + var i = startIndex + do { + if (i >= capacity) + i = 0 + if (Objects.equals(inner(i), o)) + return i + i += 1 // let i overrun so we catch endIndex == capacity + } while (i != endIndex) + -1 + // scalastyle:on return + } + + private def lastIndexOf(o: Any): Int = { + // scalastyle:off return + if (isEmpty()) + return -1 + val inner = this.inner // local copy + val startIndex = this.startIndex // local copy + var i = endIndex + do { + i -= 1 + if (i < 0) + i = inner.length - 1 + if (Objects.equals(inner(i), o)) + return i + } while (i != startIndex) + -1 + // scalastyle:on return + } + + private def ensureCapacityForAdd(): Unit = { + if (isEmpty()) { + // Nothing to do (constructor ensures capacity is always non-zero). + } else if (startIndex == 0 && endIndex == inner.length) { + val oldCapacity = inner.length + inner.length *= 2 + // no copying required: We just keep adding to the end. + // However, ensure array is dense. + fillNulls(oldCapacity, inner.length) + } else if (startIndex == endIndex) { + val oldCapacity = inner.length + inner.length *= 2 + // move beginning of array to end + for (i <- 0 until endIndex) { + inner(i + oldCapacity) = inner(i) + inner(i) = null.asInstanceOf[E] // free old reference for GC + } + // ensure rest of array is dense + fillNulls(endIndex + oldCapacity, inner.length) + endIndex += oldCapacity + } + } + + /* Removes the element at index [[target]] + * + * The return value indicates which end of the queue was shifted onto the + * element to be removed. + * + * @returns true if elements after target were shifted onto target or target + * was the last element. Returns false, if elements before target were + * shifted onto target or target was the first element. + */ + private def removeAt(target: Int): Boolean = { + /* Note that if size == 1, we always take the first branch. + * Therefore, we need not handle the empty flag in this method. + */ + + if (target == startIndex) { + pollFirst() + false + } else if (target == endIndex - 1) { + pollLast() + true + } else if (target < endIndex) { + // Shift elements from endIndex towards target + for (i <- target until endIndex - 1) + inner(i) = inner(i + 1) + inner(endIndex - 1) = null.asInstanceOf[E] // free reference for GC + status += 1 + + /* Note that endIndex >= 2: + * By previous if: target < endIndex + * ==> target <= endIndex - 1 + * By previous if: target < endIndex - 1 (non-equality) + * ==> target <= endIndex - 2 + * By precondition: target >= 0 + * ==> 0 <= endIndex - 2 + * ==> endIndex >= 2 + * + * Therefore we do not need to perform an underflow check. + */ + endIndex -= 1 + + true + } else { + // Shift elements from startIndex towards target + + /* Note that target > startIndex. + * Why? Assume by contradiction: target <= startIndex + * By previous if: target >= endIndex. + * By previous if: target < startIndex (non-equality) + * ==> endIndex <= target < startIndex. + * ==> target is not in the active region of the ringbuffer. + * ==> contradiction. + */ + + // for (i <- target until startIndex by -1) + var i = target + while (i != startIndex) { + inner(i) = inner(i - 1) + i -= 1 + } + inner(startIndex) = null.asInstanceOf[E] // free reference for GC + + status += 1 + + /* Note that startIndex <= inner.length - 2: + * By previous proof: target > startIndex + * By precondition: target <= inner.length - 1 + * ==> startIndex < inner.length - 1 + * ==> startIndex <= inner.length - 2 + * + * Therefore we do not need to perform an overflow check. + */ + startIndex += 1 + false + } + } + + private def fillNulls(from: Int, until: Int): Unit = { + for (i <- from until until) + inner(i) = null.asInstanceOf[E] } } diff --git a/javalib/src/main/scala/java/util/ArrayList.scala b/javalib/src/main/scala/java/util/ArrayList.scala index fbb682736b..68b9705f62 100644 --- a/javalib/src/main/scala/java/util/ArrayList.scala +++ b/javalib/src/main/scala/java/util/ArrayList.scala @@ -12,6 +12,9 @@ package java.util +import java.lang.Cloneable +import java.lang.Utils._ + import scala.scalajs._ class ArrayList[E] private (private[ArrayList] val inner: js.Array[E]) @@ -58,28 +61,28 @@ class ArrayList[E] private (private[ArrayList] val inner: js.Array[E]) } override def add(e: E): Boolean = { - inner += e + inner.push(e) true } override def add(index: Int, element: E): Unit = { checkIndexOnBounds(index) - inner.insert(index, element) + inner.splice(index, 0, element) } override def remove(index: Int): E = { checkIndexInBounds(index) - inner.remove(index) + arrayRemoveAndGet(inner, index) } override def clear(): Unit = - inner.clear() + inner.length = 0 override def addAll(index: Int, c: Collection[_ <: E]): Boolean = { c match { case other: ArrayList[_] => inner.splice(index, 0, other.inner.toSeq: _*) - other.size > 0 + other.size() > 0 case _ => super.addAll(index, c) } } diff --git a/javalib/src/main/scala/java/util/Arrays.scala b/javalib/src/main/scala/java/util/Arrays.scala index c1bfc71922..b4eb10b6b2 100644 --- a/javalib/src/main/scala/java/util/Arrays.scala +++ b/javalib/src/main/scala/java/util/Arrays.scala @@ -13,279 +13,189 @@ package java.util import scala.scalajs.js -import scala.scalajs.runtime.SemanticsUtils import scala.annotation.tailrec -import scala.reflect.ClassTag +import java.util.internal.GenericArrayOps._ import ScalaOps._ object Arrays { - @inline - private final implicit def naturalOrdering[T <: AnyRef]: Ordering[T] = { - new Ordering[T] { - def compare(x: T, y: T): Int = x.asInstanceOf[Comparable[T]].compareTo(y) - } + private object NaturalComparator extends Comparator[AnyRef] { + @inline + def compare(o1: AnyRef, o2: AnyRef): Int = + o1.asInstanceOf[Comparable[AnyRef]].compareTo(o2) } - // Impose the total ordering of java.lang.Float.compare in Arrays - private implicit object FloatTotalOrdering extends Ordering[Float] { - def compare(x: Float, y: Float): Int = java.lang.Float.compare(x, y) - } + @inline def ifNullUseNaturalComparator[T <: AnyRef](comparator: Comparator[_ >: T]): Comparator[_ >: T] = + if (comparator == null) NaturalComparator + else comparator - // Impose the total ordering of java.lang.Double.compare in Arrays - private implicit object DoubleTotalOrdering extends Ordering[Double] { - def compare(x: Double, y: Double): Int = java.lang.Double.compare(x, y) - } + // Implementation of the API @noinline def sort(a: Array[Int]): Unit = - sortImpl(a) + sortImpl(a)(IntArrayOps) @noinline def sort(a: Array[Int], fromIndex: Int, toIndex: Int): Unit = - sortRangeImpl[Int](a, fromIndex, toIndex) + sortRangeImpl(a, fromIndex, toIndex)(IntArrayOps) @noinline def sort(a: Array[Long]): Unit = - sortImpl(a) + sortImpl(a)(LongArrayOps) @noinline def sort(a: Array[Long], fromIndex: Int, toIndex: Int): Unit = - sortRangeImpl[Long](a, fromIndex, toIndex) + sortRangeImpl(a, fromIndex, toIndex)(LongArrayOps) @noinline def sort(a: Array[Short]): Unit = - sortImpl(a) + sortImpl(a)(ShortArrayOps) @noinline def sort(a: Array[Short], fromIndex: Int, toIndex: Int): Unit = - sortRangeImpl[Short](a, fromIndex, toIndex) + sortRangeImpl(a, fromIndex, toIndex)(ShortArrayOps) @noinline def sort(a: Array[Char]): Unit = - sortImpl(a) + sortImpl(a)(CharArrayOps) @noinline def sort(a: Array[Char], fromIndex: Int, toIndex: Int): Unit = - sortRangeImpl[Char](a, fromIndex, toIndex) + sortRangeImpl(a, fromIndex, toIndex)(CharArrayOps) @noinline def sort(a: Array[Byte]): Unit = - sortImpl(a) + sortImpl(a)(ByteArrayOps) @noinline def sort(a: Array[Byte], fromIndex: Int, toIndex: Int): Unit = - sortRangeImpl[Byte](a, fromIndex, toIndex) + sortRangeImpl(a, fromIndex, toIndex)(ByteArrayOps) @noinline def sort(a: Array[Float]): Unit = - sortImpl(a) + sortImpl(a)(FloatArrayOps) @noinline def sort(a: Array[Float], fromIndex: Int, toIndex: Int): Unit = - sortRangeImpl[Float](a, fromIndex, toIndex) + sortRangeImpl(a, fromIndex, toIndex)(FloatArrayOps) @noinline def sort(a: Array[Double]): Unit = - sortImpl(a) + sortImpl(a)(DoubleArrayOps) @noinline def sort(a: Array[Double], fromIndex: Int, toIndex: Int): Unit = - sortRangeImpl[Double](a, fromIndex, toIndex) + sortRangeImpl(a, fromIndex, toIndex)(DoubleArrayOps) @noinline def sort(a: Array[AnyRef]): Unit = - sortAnyRefImpl(a) + sortImpl(a)(NaturalComparator) @noinline def sort(a: Array[AnyRef], fromIndex: Int, toIndex: Int): Unit = - sortRangeAnyRefImpl(a, fromIndex, toIndex) + sortRangeImpl(a, fromIndex, toIndex)(NaturalComparator) @noinline def sort[T <: AnyRef](array: Array[T], comparator: Comparator[_ >: T]): Unit = { - implicit val ord = toOrdering(comparator).asInstanceOf[Ordering[AnyRef]] - sortAnyRefImpl(array.asInstanceOf[Array[AnyRef]]) + implicit val createOps = new TemplateArrayOps(array) + sortImpl(array)(ifNullUseNaturalComparator(comparator)) } @noinline def sort[T <: AnyRef](array: Array[T], fromIndex: Int, toIndex: Int, comparator: Comparator[_ >: T]): Unit = { - implicit val ord = toOrdering(comparator).asInstanceOf[Ordering[AnyRef]] - sortRangeAnyRefImpl(array.asInstanceOf[Array[AnyRef]], fromIndex, toIndex) + implicit val createOps = new TemplateArrayOps(array) + sortRangeImpl(array, fromIndex, toIndex)(ifNullUseNaturalComparator(comparator)) } @inline - private def sortRangeImpl[@specialized T: ClassTag]( - a: Array[T], fromIndex: Int, toIndex: Int)(implicit ord: Ordering[T]): Unit = { - checkIndicesForCopyOfRange(a.length, fromIndex, toIndex) - stableMergeSort[T](a, fromIndex, toIndex) + private def sortRangeImpl[T](a: Array[T], fromIndex: Int, toIndex: Int)( + comparator: Comparator[_ >: T])( + implicit ops: ArrayOps[T], createOps: ArrayCreateOps[T]): Unit = { + checkRangeIndices(a, fromIndex, toIndex)(ops) + stableMergeSort[T](a, fromIndex, toIndex)(comparator) } @inline - private def sortRangeAnyRefImpl(a: Array[AnyRef], fromIndex: Int, toIndex: Int)( - implicit ord: Ordering[AnyRef]): Unit = { - checkIndicesForCopyOfRange(a.length, fromIndex, toIndex) - stableMergeSortAnyRef(a, fromIndex, toIndex) + private def sortImpl[T](a: Array[T])(comparator: Comparator[_ >: T])( + implicit ops: ArrayOps[T], createOps: ArrayCreateOps[T]): Unit = { + stableMergeSort[T](a, 0, ops.length(a))(comparator) } - @inline - private def sortImpl[@specialized T: ClassTag: Ordering](a: Array[T]): Unit = - stableMergeSort[T](a, 0, a.length) - - @inline - private def sortAnyRefImpl(a: Array[AnyRef])(implicit ord: Ordering[AnyRef]): Unit = - stableMergeSortAnyRef(a, 0, a.length) - private final val inPlaceSortThreshold = 16 - /** Sort array `a` with merge sort and insertion sort, - * using the Ordering on its elements. - */ + /** Sort array `a` with merge sort and insertion sort. */ @inline - private def stableMergeSort[@specialized K: ClassTag](a: Array[K], - start: Int, end: Int)(implicit ord: Ordering[K]): Unit = { + private def stableMergeSort[T](a: Array[T], start: Int, end: Int)( + comparator: Comparator[_ >: T])( + implicit ops: ArrayOps[T], createOps: ArrayCreateOps[T]): Unit = { if (end - start > inPlaceSortThreshold) - stableSplitMerge(a, new Array[K](a.length), start, end) + stableSplitMerge(a, createOps.create(ops.length(a)), start, end)(comparator) else - insertionSort(a, start, end) + insertionSort(a, start, end)(comparator) } @noinline - private def stableSplitMerge[@specialized K](a: Array[K], temp: Array[K], - start: Int, end: Int)(implicit ord: Ordering[K]): Unit = { + private def stableSplitMerge[T](a: Array[T], temp: Array[T], start: Int, + end: Int)( + comparator: Comparator[_ >: T])( + implicit ops: ArrayOps[T]): Unit = { val length = end - start if (length > inPlaceSortThreshold) { val middle = start + (length / 2) - stableSplitMerge(a, temp, start, middle) - stableSplitMerge(a, temp, middle, end) - stableMerge(a, temp, start, middle, end) + stableSplitMerge(a, temp, start, middle)(comparator) + stableSplitMerge(a, temp, middle, end)(comparator) + stableMerge(a, temp, start, middle, end)(comparator) System.arraycopy(temp, start, a, start, length) } else { - insertionSort(a, start, end) + insertionSort(a, start, end)(comparator) } } @inline - private def stableMerge[@specialized K](a: Array[K], temp: Array[K], - start: Int, middle: Int, end: Int)(implicit ord: Ordering[K]): Unit = { + private def stableMerge[T](a: Array[T], temp: Array[T], start: Int, + middle: Int, end: Int)( + comparator: Comparator[_ >: T])( + implicit ops: ArrayOps[T]): Unit = { var outIndex = start var leftInIndex = start var rightInIndex = middle while (outIndex < end) { if (leftInIndex < middle && - (rightInIndex >= end || ord.lteq(a(leftInIndex), a(rightInIndex)))) { - temp(outIndex) = a(leftInIndex) + (rightInIndex >= end || comparator.compare(ops.get(a, leftInIndex), ops.get(a, rightInIndex)) <= 0)) { + ops.set(temp, outIndex, ops.get(a, leftInIndex)) leftInIndex += 1 } else { - temp(outIndex) = a(rightInIndex) + ops.set(temp, outIndex, ops.get(a, rightInIndex)) rightInIndex += 1 } outIndex += 1 } } - // Ordering[T] might be slow especially for boxed primitives, so use binary - // search variant of insertion sort - // Caller must pass end >= start or math will fail. Also, start >= 0. - @noinline - private final def insertionSort[@specialized T](a: Array[T], start: Int, - end: Int)(implicit ord: Ordering[T]): Unit = { - val n = end - start - if (n >= 2) { - if (ord.compare(a(start), a(start + 1)) > 0) { - val temp = a(start) - a(start) = a(start + 1) - a(start + 1) = temp - } - var m = 2 - while (m < n) { - // Speed up already-sorted case by checking last element first - val next = a(start + m) - if (ord.compare(next, a(start + m - 1)) < 0) { - var iA = start - var iB = start + m - 1 - while (iB - iA > 1) { - val ix = (iA + iB) >>> 1 // Use bit shift to get unsigned div by 2 - if (ord.compare(next, a(ix)) < 0) - iB = ix - else - iA = ix - } - val ix = iA + (if (ord.compare(next, a(iA)) < 0) 0 else 1) - var i = start + m - while (i > ix) { - a(i) = a(i - 1) - i -= 1 - } - a(ix) = next - } - m += 1 - } - } - } - - /** Sort array `a` with merge sort and insertion sort, - * using the Ordering on its elements. + /* ArrayOps[T] and Comparator[T] might be slow especially for boxed + * primitives, so use a binary search variant of insertion sort. + * The caller must pass end >= start or math will fail. Also, start >= 0. */ - @inline - private def stableMergeSortAnyRef(a: Array[AnyRef], start: Int, end: Int)( - implicit ord: Ordering[AnyRef]): Unit = { - if (end - start > inPlaceSortThreshold) - stableSplitMergeAnyRef(a, new Array(a.length), start, end) - else - insertionSortAnyRef(a, start, end) - } - - @noinline - private def stableSplitMergeAnyRef(a: Array[AnyRef], temp: Array[AnyRef], - start: Int, end: Int)(implicit ord: Ordering[AnyRef]): Unit = { - val length = end - start - if (length > inPlaceSortThreshold) { - val middle = start + (length / 2) - stableSplitMergeAnyRef(a, temp, start, middle) - stableSplitMergeAnyRef(a, temp, middle, end) - stableMergeAnyRef(a, temp, start, middle, end) - System.arraycopy(temp, start, a, start, length) - } else { - insertionSortAnyRef(a, start, end) - } - } - - @inline - private def stableMergeAnyRef(a: Array[AnyRef], temp: Array[AnyRef], - start: Int, middle: Int, end: Int)(implicit ord: Ordering[AnyRef]): Unit = { - var outIndex = start - var leftInIndex = start - var rightInIndex = middle - while (outIndex < end) { - if (leftInIndex < middle && - (rightInIndex >= end || ord.lteq(a(leftInIndex), a(rightInIndex)))) { - temp(outIndex) = a(leftInIndex) - leftInIndex += 1 - } else { - temp(outIndex) = a(rightInIndex) - rightInIndex += 1 - } - outIndex += 1 - } - } - @noinline - private final def insertionSortAnyRef(a: Array[AnyRef], start: Int, end: Int)( - implicit ord: Ordering[AnyRef]): Unit = { + private final def insertionSort[T](a: Array[T], start: Int, end: Int)( + comparator: Comparator[_ >: T])( + implicit ops: ArrayOps[T]): Unit = { val n = end - start if (n >= 2) { - if (ord.compare(a(start), a(start + 1)) > 0) { - val temp = a(start) - a(start) = a(start + 1) - a(start + 1) = temp + val aStart = ops.get(a, start) + val aStartPlusOne = ops.get(a, start + 1) + if (comparator.compare(aStart, aStartPlusOne) > 0) { + ops.set(a, start, aStartPlusOne) + ops.set(a, start + 1, aStart) } + var m = 2 while (m < n) { // Speed up already-sorted case by checking last element first - val next = a(start + m) - if (ord.compare(next, a(start + m - 1)) < 0) { + val next = ops.get(a, start + m) + if (comparator.compare(next, ops.get(a, start + m - 1)) < 0) { var iA = start var iB = start + m - 1 while (iB - iA > 1) { val ix = (iA + iB) >>> 1 // Use bit shift to get unsigned div by 2 - if (ord.compare(next, a(ix)) < 0) + if (comparator.compare(next, ops.get(a, ix)) < 0) iB = ix else iA = ix } - val ix = iA + (if (ord.compare(next, a(iA)) < 0) 0 else 1) + val ix = iA + (if (comparator.compare(next, ops.get(a, iA)) < 0) 0 else 1) var i = start + m while (i > ix) { - a(i) = a(i - 1) + ops.set(a, i, ops.get(a, i - 1)) i -= 1 } - a(ix) = next + ops.set(a, ix, next) } m += 1 } @@ -293,118 +203,99 @@ object Arrays { } @noinline def binarySearch(a: Array[Long], key: Long): Int = - binarySearchImpl[Long](a, 0, a.length, key, _ < _) + binarySearchImpl(a, 0, a.length, key)(LongArrayOps) @noinline def binarySearch(a: Array[Long], startIndex: Int, endIndex: Int, key: Long): Int = { - checkRangeIndices(a.length, startIndex, endIndex) - binarySearchImpl[Long](a, startIndex, endIndex, key, _ < _) + checkRangeIndices(a, startIndex, endIndex) + binarySearchImpl(a, startIndex, endIndex, key)(LongArrayOps) } @noinline def binarySearch(a: Array[Int], key: Int): Int = - binarySearchImpl[Int](a, 0, a.length, key, _ < _) + binarySearchImpl(a, 0, a.length, key)(IntArrayOps) @noinline def binarySearch(a: Array[Int], startIndex: Int, endIndex: Int, key: Int): Int = { - checkRangeIndices(a.length, startIndex, endIndex) - binarySearchImpl[Int](a, startIndex, endIndex, key, _ < _) + checkRangeIndices(a, startIndex, endIndex) + binarySearchImpl(a, startIndex, endIndex, key)(IntArrayOps) } @noinline def binarySearch(a: Array[Short], key: Short): Int = - binarySearchImpl[Short](a, 0, a.length, key, _ < _) + binarySearchImpl(a, 0, a.length, key)(ShortArrayOps) @noinline def binarySearch(a: Array[Short], startIndex: Int, endIndex: Int, key: Short): Int = { - checkRangeIndices(a.length, startIndex, endIndex) - binarySearchImpl[Short](a, startIndex, endIndex, key, _ < _) + checkRangeIndices(a, startIndex, endIndex) + binarySearchImpl(a, startIndex, endIndex, key)(ShortArrayOps) } @noinline def binarySearch(a: Array[Char], key: Char): Int = - binarySearchImpl[Char](a, 0, a.length, key, _ < _) + binarySearchImpl(a, 0, a.length, key)(CharArrayOps) @noinline def binarySearch(a: Array[Char], startIndex: Int, endIndex: Int, key: Char): Int = { - checkRangeIndices(a.length, startIndex, endIndex) - binarySearchImpl[Char](a, startIndex, endIndex, key, _ < _) + checkRangeIndices(a, startIndex, endIndex) + binarySearchImpl(a, startIndex, endIndex, key)(CharArrayOps) } @noinline def binarySearch(a: Array[Byte], key: Byte): Int = - binarySearchImpl[Byte](a, 0, a.length, key, _ < _) + binarySearchImpl(a, 0, a.length, key)(ByteArrayOps) @noinline def binarySearch(a: Array[Byte], startIndex: Int, endIndex: Int, key: Byte): Int = { - checkRangeIndices(a.length, startIndex, endIndex) - binarySearchImpl[Byte](a, startIndex, endIndex, key, _ < _) + checkRangeIndices(a, startIndex, endIndex) + binarySearchImpl(a, startIndex, endIndex, key)(ByteArrayOps) } @noinline def binarySearch(a: Array[Double], key: Double): Int = - binarySearchImpl[Double](a, 0, a.length, key, _ < _) + binarySearchImpl(a, 0, a.length, key)(DoubleArrayOps) @noinline def binarySearch(a: Array[Double], startIndex: Int, endIndex: Int, key: Double): Int = { - checkRangeIndices(a.length, startIndex, endIndex) - binarySearchImpl[Double](a, startIndex, endIndex, key, _ < _) + checkRangeIndices(a, startIndex, endIndex) + binarySearchImpl(a, startIndex, endIndex, key)(DoubleArrayOps) } @noinline def binarySearch(a: Array[Float], key: Float): Int = - binarySearchImpl[Float](a, 0, a.length, key, _ < _) + binarySearchImpl(a, 0, a.length, key)(FloatArrayOps) @noinline def binarySearch(a: Array[Float], startIndex: Int, endIndex: Int, key: Float): Int = { - checkRangeIndices(a.length, startIndex, endIndex) - binarySearchImpl[Float](a, startIndex, endIndex, key, _ < _) + checkRangeIndices(a, startIndex, endIndex) + binarySearchImpl(a, startIndex, endIndex, key)(FloatArrayOps) } @noinline def binarySearch(a: Array[AnyRef], key: AnyRef): Int = - binarySearchImplRef(a, 0, a.length, key) + binarySearchImpl(a, 0, a.length, key)(NaturalComparator) @noinline def binarySearch(a: Array[AnyRef], startIndex: Int, endIndex: Int, key: AnyRef): Int = { - checkRangeIndices(a.length, startIndex, endIndex) - binarySearchImplRef(a, startIndex, endIndex, key) + checkRangeIndices(a, startIndex, endIndex) + binarySearchImpl(a, startIndex, endIndex, key)(NaturalComparator) } - @noinline def binarySearch[T](a: Array[T], key: T, c: Comparator[_ >: T]): Int = - binarySearchImpl[T](a, 0, a.length, key, (a, b) => c.compare(a, b) < 0) + @noinline def binarySearch[T <: AnyRef](a: Array[T], key: T, c: Comparator[_ >: T]): Int = + binarySearchImpl[T](a, 0, a.length, key)(ifNullUseNaturalComparator(c)) - @noinline def binarySearch[T](a: Array[T], startIndex: Int, endIndex: Int, key: T, + @noinline def binarySearch[T <: AnyRef](a: Array[T], startIndex: Int, endIndex: Int, key: T, c: Comparator[_ >: T]): Int = { - checkRangeIndices(a.length, startIndex, endIndex) - binarySearchImpl[T](a, startIndex, endIndex, key, (a, b) => c.compare(a, b) < 0) + checkRangeIndices(a, startIndex, endIndex) + binarySearchImpl[T](a, startIndex, endIndex, key)(ifNullUseNaturalComparator(c)) } @inline @tailrec - private def binarySearchImpl[T](a: Array[T], - startIndex: Int, endIndex: Int, key: T, lt: (T, T) => Boolean): Int = { + private def binarySearchImpl[T](a: Array[T], startIndex: Int, endIndex: Int, + key: T)( + comparator: Comparator[_ >: T])( + implicit ops: ArrayOps[T]): Int = { if (startIndex == endIndex) { // Not found -startIndex - 1 } else { // Indices are unsigned 31-bit integer, so this does not overflow val mid = (startIndex + endIndex) >>> 1 - val elem = a(mid) - if (lt(key, elem)) { - binarySearchImpl(a, startIndex, mid, key, lt) - } else if (key == elem) { - // Found - mid - } else { - binarySearchImpl(a, mid + 1, endIndex, key, lt) - } - } - } - - @inline - @tailrec - def binarySearchImplRef(a: Array[AnyRef], - startIndex: Int, endIndex: Int, key: AnyRef): Int = { - if (startIndex == endIndex) { - // Not found - -startIndex - 1 - } else { - // Indices are unsigned 31-bit integer, so this does not overflow - val mid = (startIndex + endIndex) >>> 1 - val cmp = key.asInstanceOf[Comparable[AnyRef]].compareTo(a(mid)) + val elem = ops.get(a, mid) + val cmp = comparator.compare(key, elem) if (cmp < 0) { - binarySearchImplRef(a, startIndex, mid, key) + binarySearchImpl(a, startIndex, mid, key)(comparator) } else if (cmp == 0) { // Found mid } else { - binarySearchImplRef(a, mid + 1, endIndex, key) + binarySearchImpl(a, mid + 1, endIndex, key)(comparator) } } } @@ -437,18 +328,19 @@ object Arrays { equalsImpl(a, b) @inline - private def equalsImpl[T](a: Array[T], b: Array[T]): Boolean = { + private def equalsImpl[T](a: Array[T], b: Array[T])( + implicit ops: ArrayOps[T]): Boolean = { // scalastyle:off return if (a eq b) return true if (a == null || b == null) return false - val len = a.length - if (b.length != len) + val len = ops.length(a) + if (ops.length(b) != len) return false var i = 0 while (i != len) { - if (a(i) != b(i)) + if (!Objects.equals(ops.get(a, i), ops.get(b, i))) return false i += 1 } @@ -512,24 +404,25 @@ object Arrays { @inline private def fillImpl[T](a: Array[T], fromIndex: Int, toIndex: Int, - value: T, checkIndices: Boolean = true): Unit = { + value: T, checkIndices: Boolean = true)( + implicit ops: ArrayOps[T]): Unit = { if (checkIndices) - checkRangeIndices(a.length, fromIndex, toIndex) + checkRangeIndices(a, fromIndex, toIndex) var i = fromIndex while (i != toIndex) { - a(i) = value + ops.set(a, i, value) i += 1 } } @noinline def copyOf[T <: AnyRef](original: Array[T], newLength: Int): Array[T] = { - implicit val tagT = ClassTag[T](original.getClass.getComponentType) + implicit val tops = new TemplateArrayOps(original) copyOfImpl(original, newLength) } @noinline def copyOf[T <: AnyRef, U <: AnyRef](original: Array[U], newLength: Int, newType: Class[_ <: Array[T]]): Array[T] = { - implicit val tag = ClassTag[T](newType.getComponentType) + implicit val tops = new ClassArrayOps(newType) copyOfImpl(original, newLength) } @@ -558,26 +451,28 @@ object Arrays { copyOfImpl(original, newLength) @inline - private def copyOfImpl[U, T: ClassTag](original: Array[U], newLength: Int): Array[T] = { + private def copyOfImpl[U, T](original: Array[U], newLength: Int)( + implicit uops: ArrayOps[U], tops: ArrayCreateOps[T]): Array[T] = { checkArrayLength(newLength) - val copyLength = Math.min(newLength, original.length) - val ret = new Array[T](newLength) + val copyLength = Math.min(newLength, uops.length(original)) + val ret = tops.create(newLength) System.arraycopy(original, 0, ret, 0, copyLength) ret } @noinline def copyOfRange[T <: AnyRef](original: Array[T], from: Int, to: Int): Array[T] = { - copyOfRangeImpl[T](original, from, to)(ClassTag(original.getClass.getComponentType)).asInstanceOf[Array[T]] + implicit val tops = new TemplateArrayOps(original) + copyOfRangeImpl(original, from, to) } - @noinline def copyOfRange[T <: AnyRef, U <: AnyRef](original: Array[U], from: Int, to: Int, - newType: Class[_ <: Array[T]]): Array[T] = { - copyOfRangeImpl[AnyRef](original.asInstanceOf[Array[AnyRef]], from, to)( - ClassTag(newType.getComponentType)).asInstanceOf[Array[T]] + @noinline def copyOfRange[T <: AnyRef, U <: AnyRef](original: Array[U], + from: Int, to: Int, newType: Class[_ <: Array[T]]): Array[T] = { + implicit val tops = new ClassArrayOps(newType) + copyOfRangeImpl(original, from, to) } @noinline def copyOfRange(original: Array[Byte], start: Int, end: Int): Array[Byte] = - copyOfRangeImpl[Byte](original, start, end) + copyOfRangeImpl(original, start, end) @noinline def copyOfRange(original: Array[Short], start: Int, end: Int): Array[Short] = copyOfRangeImpl(original, start, end) @@ -601,12 +496,15 @@ object Arrays { copyOfRangeImpl(original, start, end) @inline - private def copyOfRangeImpl[T: ClassTag](original: Array[T], - start: Int, end: Int): Array[T] = { - checkIndicesForCopyOfRange(original.length, start, end) + private def copyOfRangeImpl[T, U](original: Array[U], start: Int, end: Int)( + implicit uops: ArrayOps[U], tops: ArrayCreateOps[T]): Array[T] = { + if (start > end) + throw new IllegalArgumentException("" + start + " > " + end) + + val len = uops.length(original) val retLength = end - start - val copyLength = Math.min(retLength, original.length - start) - val ret = new Array[T](retLength) + val copyLength = Math.min(retLength, len - start) + val ret = tops.create(retLength) System.arraycopy(original, start, ret, 0, copyLength) ret } @@ -616,14 +514,6 @@ object Arrays { throw new NegativeArraySizeException } - @inline private def checkIndicesForCopyOfRange( - len: Int, start: Int, end: Int): Unit = { - if (start > end) - throw new IllegalArgumentException("" + start + " > " + end) - SemanticsUtils.arrayIndexOutOfBoundsCheck(start < 0 || start > len, - new ArrayIndexOutOfBoundsException) - } - @noinline def asList[T <: AnyRef](a: Array[T]): List[T] = { new AbstractList[T] with RandomAccess { def size(): Int = @@ -641,61 +531,73 @@ object Arrays { } @noinline def hashCode(a: Array[Long]): Int = - hashCodeImpl[Long](a, _.hashCode()) + hashCodeImpl(a) @noinline def hashCode(a: Array[Int]): Int = - hashCodeImpl[Int](a, _.hashCode()) + hashCodeImpl(a) @noinline def hashCode(a: Array[Short]): Int = - hashCodeImpl[Short](a, _.hashCode()) + hashCodeImpl(a) @noinline def hashCode(a: Array[Char]): Int = - hashCodeImpl[Char](a, _.hashCode()) + hashCodeImpl(a) @noinline def hashCode(a: Array[Byte]): Int = - hashCodeImpl[Byte](a, _.hashCode()) + hashCodeImpl(a) @noinline def hashCode(a: Array[Boolean]): Int = - hashCodeImpl[Boolean](a, _.hashCode()) + hashCodeImpl(a) @noinline def hashCode(a: Array[Float]): Int = - hashCodeImpl[Float](a, _.hashCode()) + hashCodeImpl(a) @noinline def hashCode(a: Array[Double]): Int = - hashCodeImpl[Double](a, _.hashCode()) + hashCodeImpl(a) @noinline def hashCode(a: Array[AnyRef]): Int = - hashCodeImpl[AnyRef](a, Objects.hashCode(_)) + hashCodeImpl(a) @inline - private def hashCodeImpl[T](a: Array[T], elementHashCode: T => Int): Int = { + private def hashCodeImpl[T](a: Array[T])(implicit ops: ArrayOps[T]): Int = { if (a == null) { 0 } else { var acc = 1 - for (i <- 0 until a.length) - acc = 31 * acc + elementHashCode(a(i)) + val len = ops.length(a) + var i = 0 + while (i != len) { + acc = 31 * acc + Objects.hashCode(ops.get(a, i)) + i += 1 + } acc } } @noinline def deepHashCode(a: Array[AnyRef]): Int = { - @inline - def getHash(elem: AnyRef): Int = { - elem match { - case elem: Array[AnyRef] => deepHashCode(elem) - case elem: Array[Long] => hashCode(elem) - case elem: Array[Int] => hashCode(elem) - case elem: Array[Short] => hashCode(elem) - case elem: Array[Char] => hashCode(elem) - case elem: Array[Byte] => hashCode(elem) - case elem: Array[Boolean] => hashCode(elem) - case elem: Array[Float] => hashCode(elem) - case elem: Array[Double] => hashCode(elem) - case _ => Objects.hashCode(elem) + def rec(a: Array[AnyRef]): Int = { + var acc = 1 + val len = a.length + var i = 0 + while (i != len) { + acc = 31 * acc + (a(i) match { + case elem: Array[AnyRef] => rec(elem) + case elem: Array[Long] => hashCode(elem) + case elem: Array[Int] => hashCode(elem) + case elem: Array[Short] => hashCode(elem) + case elem: Array[Char] => hashCode(elem) + case elem: Array[Byte] => hashCode(elem) + case elem: Array[Boolean] => hashCode(elem) + case elem: Array[Float] => hashCode(elem) + case elem: Array[Double] => hashCode(elem) + case elem => Objects.hashCode(elem) + }) + i += 1 } + acc } - hashCodeImpl(a, getHash) + + if (a == null) 0 + else rec(a) } @noinline def deepEquals(a1: Array[AnyRef], a2: Array[AnyRef]): Boolean = { @@ -745,17 +647,17 @@ object Arrays { toStringImpl[AnyRef](a) @inline - private def toStringImpl[T](a: Array[T]): String = { + private def toStringImpl[T](a: Array[T])(implicit ops: ArrayOps[T]): String = { if (a == null) { "null" } else { var result = "[" - val len = a.length + val len = ops.length(a) var i = 0 while (i != len) { if (i != 0) result += ", " - result += a(i) + result += ops.get(a, i) i += 1 } result + "]" @@ -815,19 +717,16 @@ object Arrays { } @inline - private def checkRangeIndices(length: Int, start: Int, end: Int): Unit = { + private def checkRangeIndices[T](a: Array[T], start: Int, end: Int)( + implicit ops: ArrayOps[T]): Unit = { if (start > end) throw new IllegalArgumentException("fromIndex(" + start + ") > toIndex(" + end + ")") - SemanticsUtils.arrayIndexOutOfBoundsCheck(start < 0, - new ArrayIndexOutOfBoundsException("Array index out of range: " + start)) - SemanticsUtils.arrayIndexOutOfBoundsCheck(end > length, - new ArrayIndexOutOfBoundsException("Array index out of range: " + end)) - } - @inline - private def toOrdering[T](cmp: Comparator[T]): Ordering[T] = { - new Ordering[T] { - def compare(x: T, y: T): Int = cmp.compare(x, y) - } + // bounds checks + if (start < 0) + ops.get(a, start) + + if (end > 0) + ops.get(a, end - 1) } } diff --git a/javalib/src/main/scala/java/util/Base64.scala b/javalib/src/main/scala/java/util/Base64.scala index f9ea87b9d6..a88333d294 100644 --- a/javalib/src/main/scala/java/util/Base64.scala +++ b/javalib/src/main/scala/java/util/Base64.scala @@ -389,7 +389,8 @@ object Base64 { -1 } else { iterate() - written + if (written == 0 && eof) -1 + else written } } @@ -402,7 +403,7 @@ object Base64 { // -------------------------------------------------------------------------- class Encoder private[Base64] (table: Array[Byte], lineLength: Int = 0, - lineSeparator: Array[Byte] = Array.empty, withPadding: Boolean = true) { + lineSeparator: Array[Byte] = new Array[Byte](0), withPadding: Boolean = true) { def encode(src: Array[Byte]): Array[Byte] = { val dst = new Array[Byte](dstLength(src.length)) diff --git a/javalib/src/main/scala/java/util/BitSet.scala b/javalib/src/main/scala/java/util/BitSet.scala new file mode 100644 index 0000000000..171ed1a629 --- /dev/null +++ b/javalib/src/main/scala/java/util/BitSet.scala @@ -0,0 +1,694 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util + +import java.io.Serializable +import java.lang.Cloneable +import java.lang.Integer.bitCount +import java.lang.Integer.toUnsignedLong +import java.nio.{ByteBuffer, LongBuffer} +import java.util +import java.util.ScalaOps.IntScalaOps + +private object BitSet { + private final val AddressBitsPerWord = 5 // Int Based 2^5 = 32 + private final val ElementSize = 1 << AddressBitsPerWord + private final val RightBits = ElementSize - 1 + + def valueOf(longs: Array[Long]): util.BitSet = { + val bs = new util.BitSet + + for (i <- 0 until longs.length * 64) { + val idx = i / 64 + if ((longs(idx) & (1L << (i % 64))) != 0) + bs.set(i) + } + + bs + } + + def valueOf(lb: LongBuffer): BitSet = { + val arr = new Array[Long](lb.remaining()) + lb.get(arr) + lb.position(lb.position() - arr.length) // Restores the buffer position + valueOf(arr) + } + + def valueOf(bytes: Array[Byte]): BitSet = { + val bs = new BitSet + + for (i <- 0 until bytes.length * 8) { + val idx = i / 8 + if ((bytes(idx) & (1 << (i % 8))) != 0) + bs.set(i) + } + + bs + } + + def valueOf(bb: ByteBuffer): BitSet = { + val arr = new Array[Byte](bb.remaining()) + bb.get(arr) + bb.position(bb.position() - arr.length) // Restores the buffer position + valueOf(arr) + } +} + +class BitSet private (private var bits: Array[Int]) extends Serializable with Cloneable { + import BitSet.{AddressBitsPerWord, ElementSize, RightBits} + + def this(nbits: Int) = { + this( + bits = { + if (nbits < 0) + throw new NegativeArraySizeException + + val length = (nbits + BitSet.RightBits) >> BitSet.AddressBitsPerWord + + new Array[Int](length) + } + ) + } + + def this() = { + this(64) + } + + def toByteArray(): Array[Byte] = { + if (isEmpty()) { + new Array[Byte](0) + } else { + val l = (length() + 7) / 8 + val array = new Array[Byte](l) + + for (i <- 0 until length()) { + if (get(i)) + array(i / 8) = (array(i / 8) | (1 << (i % 8))).toByte + } + + array + } + } + + def toLongArray(): Array[Long] = { + if (isEmpty()) { + new Array[Long](0) + } else { + val l = (length() + 63) / 64 + val array = new Array[Long](l) + + for (i <- 0 until length()) { + if (get(i)) + array(i / 64) |= 1L << (i % 64) + } + + array + } + } + + def flip(bitIndex: Int): Unit = { + checkBitIndex(bitIndex) + + val len = (bitIndex >> AddressBitsPerWord) + 1 + ensureLength(len) + + bits(len - 1) ^= 1 << (bitIndex & RightBits) + } + + def flip(fromIndex: Int, toIndex: Int): Unit = { + checkToAndFromIndex(fromIndex, toIndex) + + if (fromIndex != toIndex) { + val len2 = ((toIndex - 1) >> AddressBitsPerWord) + 1 + ensureLength(len2) + val idx1 = fromIndex >> AddressBitsPerWord + val idx2 = (toIndex - 1) >> AddressBitsPerWord + val mask1 = (~0) << (fromIndex & RightBits) + val mask2 = (~0) >>> (ElementSize - (toIndex & RightBits)) + + if (idx1 == idx2) { + bits(idx1) ^= (mask1 & mask2) + } else { + bits(idx1) ^= mask1 + bits(idx2) ^= mask2 + for (i <- idx1 + 1 until idx2) + bits(i) ^= (~0) + } + } + } + + def set(bitIndex: Int): Unit = { + checkBitIndex(bitIndex) + + val len = (bitIndex >> AddressBitsPerWord) + 1 + ensureLength(len) + + bits(len - 1) |= 1 << (bitIndex & RightBits) + } + + def set(bitIndex: Int, value: Boolean): Unit = + if (value) set(bitIndex) + else clear(bitIndex) + + // fromIndex is inclusive, toIndex is exclusive + def set(fromIndex: Int, toIndex: Int): Unit = { + checkToAndFromIndex(fromIndex, toIndex) + + if (fromIndex != toIndex) { + val len2 = ((toIndex - 1) >> AddressBitsPerWord) + 1 + ensureLength(len2) + + val idx1 = fromIndex >> AddressBitsPerWord + val idx2 = (toIndex - 1) >> AddressBitsPerWord + val mask1 = (~0) << (fromIndex & RightBits) + val mask2 = (~0) >>> (ElementSize - (toIndex & RightBits)) + + if (idx1 == idx2) { + bits(idx1) |= (mask1 & mask2) + } else { + bits(idx1) |= mask1 + bits(idx2) |= mask2 + + for (i <- idx1 + 1 until idx2) + bits(i) |= (~0) + } + } + } + + def set(fromIndex: Int, toIndex: Int, value: Boolean): Unit = + if (value) set(fromIndex, toIndex) + else clear(fromIndex, toIndex) + + def clear(bitIndex: Int): Unit = { + checkBitIndex(bitIndex) + + val arrayPos = bitIndex >> AddressBitsPerWord + + if (arrayPos < bits.length) { + bits(arrayPos) &= ~(1 << (bitIndex & RightBits)) + } + } + + def clear(fromIndex: Int, toIndex: Int): Unit = { + checkToAndFromIndex(fromIndex, toIndex) + + val last = bits.length << AddressBitsPerWord + if (fromIndex >= last || fromIndex == toIndex) + return // scalastyle:ignore + + val toIndexOrLast = + if (toIndex > last) last + else toIndex + + val idx1 = fromIndex >> AddressBitsPerWord + val idx2 = (toIndexOrLast - 1) >> AddressBitsPerWord + val mask1 = (~0) << (fromIndex & RightBits) + val mask2 = (~0) >>> (ElementSize - (toIndexOrLast & RightBits)) + + if (idx1 == idx2) { + bits(idx1) &= ~(mask1 & mask2) + } else { + bits(idx1) &= ~mask1 + bits(idx2) &= ~mask2 + + for (i <- idx1 + 1 until idx2) + bits(i) = 0 + } + } + + def clear(): Unit = { + for (i <- 0 until bits.length) + bits(i) = 0 + } + + def get(bitIndex: Int): Boolean = { + checkBitIndex(bitIndex) + + val arrayPos = bitIndex >> AddressBitsPerWord + + if (arrayPos < bits.length) + (bits(arrayPos) & (1 << (bitIndex & RightBits))) != 0 + else + false + } + + def get(fromIndex: Int, toIndex: Int): BitSet = { + // scalastyle:off return + checkToAndFromIndex(fromIndex, toIndex) + + val last = bits.length << AddressBitsPerWord + if (fromIndex >= last || fromIndex == toIndex) + return new BitSet(0) + + val toIndexOrLast = + if (toIndex > last) last + else toIndex + + val idx1 = fromIndex >> AddressBitsPerWord + val idx2 = (toIndexOrLast - 1) >> AddressBitsPerWord + val mask1 = (~0) << (fromIndex & RightBits) + val mask2 = (~0) >>> (ElementSize - (toIndexOrLast & RightBits)) + + if (idx1 == idx2) { + val result = (bits(idx1) & (mask1 & mask2)) >>> (fromIndex % ElementSize) + if (result == 0) + return new BitSet(0) + + new BitSet(Array(result)) + } else { + val newbits = new Array[Int](idx2 - idx1 + 1) + // first fill in the first and last indexes in the new bitset + newbits(0) = bits(idx1) & mask1 + newbits(newbits.length - 1) = bits(idx2) & mask2 + // fill in the in between elements of the new bitset + for (i <- 1 until idx2 - idx1) + newbits(i) = bits(idx1 + i) + + val numBitsToShift = fromIndex & RightBits + + if (numBitsToShift != 0) { + for (i <- 0 until newbits.length) { + // shift the current element to the right + newbits(i) = newbits(i) >>> numBitsToShift + // apply the last x bits of newbits[i+1] to the current + // element + if (i != newbits.length - 1) + newbits(i) |= newbits(i + 1) << (ElementSize - numBitsToShift) + } + } + + new BitSet(newbits) + } + // scalastyle:on return + } + + def nextSetBit(fromIndex: Int): Int = { + // scalastyle:off return + checkFromIndex(fromIndex) + + if (fromIndex >= (bits.length << AddressBitsPerWord)) + return -1 + + var idx = fromIndex >> AddressBitsPerWord + + // first check in the same bit set element + if (bits(idx) != 0) { + var j = fromIndex & RightBits + while (j < ElementSize) { + if ((bits(idx) & (1 << j)) != 0) + return (idx << AddressBitsPerWord) + j + j += 1 + } + } + + idx += 1 + + while (idx < bits.length && bits(idx) == 0) + idx += 1 + + if (idx == bits.length) + return -1 + + // we know for sure there is a bit set to true in this element + // since the bitset value is not 0 + var j = 0 + while (j < ElementSize) { + if ((bits(idx) & (1 << j)) != 0) + return (idx << AddressBitsPerWord) + j + j += 1 + } + + -1 + // scalastyle:on return + } + + def nextClearBit(fromIndex: Int): Int = { + // scalastyle:off return + checkFromIndex(fromIndex) + + val length = bits.length + val bssize = length << AddressBitsPerWord + + if (fromIndex >= bssize) + return fromIndex + + var idx = fromIndex >> AddressBitsPerWord + + if (bits(idx) != (~0)) { + var j = fromIndex % ElementSize + while (j < ElementSize) { + if ((bits(idx) & (1 << j)) == 0) + return idx * ElementSize + j + j += 1 + } + } + + idx += 1 + + while (idx < length && bits(idx) == (~0)) + idx += 1 + + if (idx == length) + return bssize + + var j = 0 + while (j < ElementSize) { + if ((bits(idx) & (1 << j)) == 0) + return (idx << AddressBitsPerWord) + j + j += 1 + } + + bssize + // scalastyle:on return + } + + def previousSetBit(fromIndex: Int): Int = { + // scalastyle:off return + if (fromIndex == -1) + return -1 + + checkFromIndex(fromIndex) + + val bssize = bits.length << AddressBitsPerWord + var idx = Math.min(bits.length - 1, fromIndex >> AddressBitsPerWord) + + if (bits(idx) != 0) { + if (idx == bssize) + return idx + + var j: Int = fromIndex % ElementSize + while (j >= 0) { + if ((bits(idx) & (1 << j)) != 0) + return idx * ElementSize + j + + j -= 1 + } + } + + idx -= 1 + + while (idx >= 0 && bits(idx) == 0) + idx -= 1 + + if (idx == -1) + return -1 + + var j: Int = ElementSize - 1 + while (j >= 0) { + if ((bits(idx) & (1 << j)) != 0) + return (idx << AddressBitsPerWord) + j + + j -= 1 + } + + bssize + // scalastyle:on return + } + + def previousClearBit(fromIndex: Int): Int = { + // scalastyle:off return + if (fromIndex == -1) + return -1 + + checkFromIndex(fromIndex) + + val length = bits.length + val bssize = length << AddressBitsPerWord + + if (fromIndex >= bssize) + return fromIndex + + var idx = Math.min(bits.length - 1, fromIndex >> AddressBitsPerWord) + + if (bits(idx) != (~0)) { + var j: Int = fromIndex % ElementSize + while (j >= 0) { + if ((bits(idx) & (1 << j)) == 0) + return idx * ElementSize + j + + j -= 1 + } + } + + idx -= 1 + + while (idx >= 0 && bits(idx) == (~0)) + idx -= 1 + + if (idx == -1) + return -1 + + var j: Int = ElementSize - 1 + while (j >= 0) { + if ((bits(idx) & (1 << j)) == 0) + return (idx << AddressBitsPerWord) + j + + j -= 1 + } + + bssize + // scalastyle:on return + } + + def length(): Int = { + val len = getActualArrayLength() + if (len == 0) + 0 + else + (len << AddressBitsPerWord) - Integer.numberOfLeadingZeros(bits(len - 1)) + } + + def isEmpty(): Boolean = getActualArrayLength() == 0 + + def intersects(set: BitSet): Boolean = { + // scalastyle:off return + val bsBits = set.bits + val length1 = bits.length + val length2 = set.bits.length + + if (length1 <= length2) { + var i: Int = 0 + while (i < length1) { + if ((bits(i) & bsBits(i)) != 0) + return true + + i += 1 + } + } else { + var i: Int = 0 + while (i < length2) { + if ((bits(i) & bsBits(i)) != 0) + return true + + i += 1 + } + } + + false + // scalastyle:on return + } + + def cardinality(): Int = { + var count = 0 + + val length = getActualArrayLength() + + for (idx <- 0 until length) { + count += bitCount(bits(idx)) + } + + count + } + + def and(set: BitSet): Unit = { + val bsBits = set.bits + val length1 = bits.length + val length2 = set.bits.length + + if (length1 <= length2) { + for (i <- 0 until length1) + bits(i) &= bsBits(i) + } else { + for (i <- 0 until length2) + bits(i) &= bsBits(i) + + for (i <- length2 until length1) + bits(i) = 0 + } + } + + def or(set: BitSet): Unit = { + val bsActualLen = set.getActualArrayLength() + + if (bsActualLen > bits.length) { + val tempBits = Arrays.copyOf(set.bits, bsActualLen) + + for (i <- 0 until bits.length) + tempBits(i) |= bits(i) + + bits = tempBits + } else { + val bsBits = set.bits + + for (i <- 0 until bsActualLen) + bits(i) |= bsBits(i) + } + } + + def xor(set: BitSet): Unit = { + val bsActualLen = set.getActualArrayLength() + + if (bsActualLen > bits.length) { + val tempBits = Arrays.copyOf(set.bits, bsActualLen) + + for (i <- 0 until bits.length) + tempBits(i) ^= bits(i) + + bits = tempBits + } else { + val bsBits = set.bits + + for (i <- 0 until bsActualLen) + bits(i) ^= bsBits(i) + } + } + + def andNot(set: BitSet): Unit = { + if (bits.length != 0) { + val bsBits = set.bits + + val minLength = Math.min(bits.length, set.bits.length) + + for (i <- 0 until minLength) + bits(i) &= ~bsBits(i) + } + } + + override def hashCode(): Int = { + var x: Long = 1234L + var i: Int = 0 + + while (i < bits.length) { + x ^= toUnsignedLong(bits(i)) * toUnsignedLong(i + 1) + i += 1 + } + + ((x >> 32) ^ x).toInt + } + + def size(): Int = bits.length << AddressBitsPerWord + + /** + * If one of the BitSets is larger than the other, check to see if + * any of its extra bits are set. If so return false. + */ + private def equalsImpl(other: BitSet): Boolean = { + // scalastyle:off return + val length1 = bits.length + val length2 = other.bits.length + + val smallerBS: BitSet = if (length1 <= length2) this else other + val smallerLength: Int = if (length1 <= length2) length1 else length2 + + val largerBS: BitSet = if (length1 > length2) this else other + val largerLength: Int = if (length1 > length2) length1 else length2 + + var i: Int = 0 + while (i < smallerLength) { + if (smallerBS.bits(i) != largerBS.bits(i)) + return false + + i += 1 + } + + // Check remainder bits, if they are zero these are equal + while (i < largerLength) { + if (largerBS.bits(i) != 0) + return false + + i += 1 + } + // scalastyle:on return + + true + } + + override def equals(obj: Any): Boolean = { + obj match { + case bs: BitSet => equalsImpl(bs) + case _ => false + } + } + + override def clone(): AnyRef = + new BitSet(bits.clone()) + + override def toString(): String = { + var result: String = "{" + var comma: Boolean = false + + // Work around Scala 2.11 limitation with the IR cleaner ; should be double-for over i and j + for { + i <- 0 until getActualArrayLength() + } { + var j = 0 + while (j < ElementSize) { + if ((bits(i) & (1 << j)) != 0) { + if (comma) + result += ", " + else + comma = true + result += (i << AddressBitsPerWord) + j + } + j += 1 + } + } + + result += "}" + result + } + + final private def ensureLength(len: Int): Unit = { + if (len > bits.length) + bits = Arrays.copyOf(bits, Math.max(len, bits.length * 2)) + } + + final private def getActualArrayLength(): Int = { + var idx = bits.length - 1 + while (idx >= 0 && bits(idx) == 0) + idx -= 1 + + idx + 1 + } + + private def checkToAndFromIndex(fromIndex: Int, toIndex: Int): Unit = { + if (fromIndex < 0) + throw new IndexOutOfBoundsException(s"fromIndex < 0: $fromIndex") + + if (toIndex < 0) + throw new IndexOutOfBoundsException(s"toIndex < 0: $toIndex") + + if (toIndex < fromIndex) + throw new IndexOutOfBoundsException(s"fromIndex: $fromIndex > toIndex: $toIndex") + } + + private def checkFromIndex(fromIndex: Int): Unit = { + if (fromIndex < 0) + throw new IndexOutOfBoundsException(s"fromIndex < 0: $fromIndex") + } + + private def checkBitIndex(bitIndex: Int): Unit = { + if (bitIndex < 0) + throw new IndexOutOfBoundsException(s"bitIndex < 0: $bitIndex") + } +} diff --git a/javalib/src/main/scala/java/util/Collections.scala b/javalib/src/main/scala/java/util/Collections.scala index 6245ffe992..e27b526a86 100644 --- a/javalib/src/main/scala/java/util/Collections.scala +++ b/javalib/src/main/scala/java/util/Collections.scala @@ -28,7 +28,7 @@ object Collections { new AbstractSet[Any] with Serializable { override def size(): Int = 0 - override def iterator(): Iterator[Any] = emptyIterator[Any] + override def iterator(): Iterator[Any] = emptyIterator[Any]() }) } @@ -58,7 +58,7 @@ object Collections { private lazy val EMPTY_ENUMERATION: Enumeration[_] = { new Enumeration[Any] { - def hasMoreElements: Boolean = false + def hasMoreElements(): Boolean = false def nextElement(): Any = throw new NoSuchElementException @@ -67,20 +67,10 @@ object Collections { // Differs from original type definition, original: [T <: jl.Comparable[_ >: T]] def sort[T <: jl.Comparable[T]](list: List[T]): Unit = - sort(list, naturalComparator[T]) + list.sort(null) - def sort[T](list: List[T], c: Comparator[_ >: T]): Unit = { - val arrayBuf = list.toArray() - Arrays.sort[AnyRef with T](arrayBuf.asInstanceOf[Array[AnyRef with T]], c) - - // The spec of `Arrays.asList()` guarantees that its result implements RandomAccess - val sortedList = Arrays.asList(arrayBuf).asInstanceOf[List[T] with RandomAccess] - - list match { - case list: RandomAccess => copyImpl(sortedList, list) - case _ => copyImpl(sortedList, list.listIterator) - } - } + def sort[T](list: List[T], c: Comparator[_ >: T]): Unit = + list.sort(c) def binarySearch[T](list: List[_ <: jl.Comparable[_ >: T]], key: T): Int = binarySearchImpl(list, (elem: Comparable[_ >: T]) => elem.compareTo(key)) @@ -109,18 +99,18 @@ object Collections { list match { case _: RandomAccess => - binarySearch(0, list.size, list.get(_)) + binarySearch(0, list.size(), list.get(_)) case _ => def getFrom(iter: ListIterator[E])(index: Int): E = { - val shift = index - iter.nextIndex + val shift = index - iter.nextIndex() if (shift > 0) (0 until shift).foreach(_ => iter.next()) else (0 until -shift).foreach(_ => iter.previous()) iter.next() } - binarySearch(0, list.size, getFrom(list.listIterator)) + binarySearch(0, list.size(), getFrom(list.listIterator())) } } @@ -129,7 +119,7 @@ object Collections { @inline def reverseImpl[T](list: List[T]): Unit = { - val size = list.size + val size = list.size() list match { case list: RandomAccess => for (i <- 0 until size / 2) { @@ -180,7 +170,7 @@ object Collections { case _ => val buffer = new ArrayList[T](list) shuffleInPlace(buffer) - copyImpl(buffer, list.listIterator) + copyImpl(buffer, list.listIterator()) } } @@ -198,7 +188,7 @@ object Collections { case _ => val it1 = list.listIterator(i) val it2 = list.listIterator(j) - if (!it1.hasNext || !it2.hasNext) + if (!it1.hasNext() || !it2.hasNext()) throw new IndexOutOfBoundsException val tmp = it1.next() it1.set(it2.next()) @@ -209,11 +199,11 @@ object Collections { def fill[T](list: List[_ >: T], obj: T): Unit = { list match { case list: RandomAccess => - (0 until list.size).foreach(list.set(_, obj)) + (0 until list.size()).foreach(list.set(_, obj)) case _ => - val iter = list.listIterator - while (iter.hasNext) { + val iter = list.listIterator() + while (iter.hasNext()) { iter.next() iter.set(obj) } @@ -223,21 +213,21 @@ object Collections { def copy[T](dest: List[_ >: T], src: List[_ <: T]): Unit = { (dest, src) match { case (dest: RandomAccess, src: RandomAccess) => copyImpl(src, dest) - case (dest: RandomAccess, _) => copyImpl(src.iterator, dest) - case (_, src: RandomAccess) => copyImpl(src, dest.listIterator) - case (_, _) => copyImpl(src.iterator, dest.listIterator) + case (dest: RandomAccess, _) => copyImpl(src.iterator(), dest) + case (_, src: RandomAccess) => copyImpl(src, dest.listIterator()) + case (_, _) => copyImpl(src.iterator(), dest.listIterator()) } } private def copyImpl[T](source: List[_ <: T] with RandomAccess, dest: List[T] with RandomAccess): Unit = { - (0 until source.size).foreach(i => dest.set(i, source.get(i))) + (0 until source.size()).foreach(i => dest.set(i, source.get(i))) } private def copyImpl[T](source: Iterator[_ <: T], dest: List[T] with RandomAccess): Unit = { val destEnd = dest.size() var i = 0 - while (source.hasNext) { + while (source.hasNext()) { if (i < destEnd) dest.set(i, source.next()) else @@ -247,8 +237,8 @@ object Collections { } private def copyImpl[T](source: List[_ <: T] with RandomAccess, dest: ListIterator[T]): Unit = { - for (i <- 0 until source.size) { - if (dest.hasNext) { + for (i <- 0 until source.size()) { + if (dest.hasNext()) { dest.next() dest.set(source.get(i)) } else { @@ -258,8 +248,8 @@ object Collections { } private def copyImpl[T](source: Iterator[_ <: T], dest: ListIterator[T]): Unit = { - while (source.hasNext) { - if (dest.hasNext) { + while (source.hasNext()) { + if (dest.hasNext()) { dest.next() dest.set(source.next()) } else { @@ -268,15 +258,15 @@ object Collections { } } - // Differs from original type definition, original: [T <: jl.Comparable[_ >: T]] - def min[T <: AnyRef with jl.Comparable[T]](coll: Collection[_ <: T]): T = + // Differs from original type definition, original: [T <: jl.Comparable[_ >: T]], returning T + def min[T <: AnyRef with jl.Comparable[T]](coll: Collection[_ <: T]): AnyRef = min(coll, naturalComparator[T]) def min[T](coll: Collection[_ <: T], comp: Comparator[_ >: T]): T = coll.scalaOps.reduceLeft((a, b) => if (comp.compare(a, b) <= 0) a else b) - // Differs from original type definition, original: [T <: jl.Comparable[_ >: T]] - def max[T <: AnyRef with jl.Comparable[T]](coll: Collection[_ <: T]): T = + // Differs from original type definition, original: [T <: jl.Comparable[_ >: T]], returning T + def max[T <: AnyRef with jl.Comparable[T]](coll: Collection[_ <: T]): AnyRef = max(coll, naturalComparator[T]) def max[T](coll: Collection[_ <: T], comp: Comparator[_ >: T]): T = @@ -286,7 +276,7 @@ object Collections { rotateImpl(list, distance) private def rotateImpl[T](list: List[T], distance: Int): Unit = { - val listSize = list.size + val listSize = list.size() if (listSize > 1 && distance % listSize != 0) { def exchangeRotation(): Unit = { def indexModulo(i: Int): Int = modulo(i, listSize) @@ -326,7 +316,7 @@ object Collections { list match { case _: RandomAccess => var modified = false - for (i <- 0 until list.size) { + for (i <- 0 until list.size()) { if (Objects.equals(list.get(i), oldVal)) { list.set(i, newVal) modified = true @@ -337,7 +327,7 @@ object Collections { case _ => @tailrec def replaceAll(iter: ListIterator[T], mod: Boolean): Boolean = { - if (iter.hasNext) { + if (iter.hasNext()) { val isEqual = Objects.equals(iter.next(), oldVal) if (isEqual) iter.set(newVal) @@ -499,9 +489,6 @@ object Collections { _hasNext = false o } - - def remove(): Unit = - throw new UnsupportedOperationException } } }) @@ -557,10 +544,10 @@ object Collections { } def enumeration[T](c: Collection[T]): Enumeration[T] = { - val it = c.iterator + val it = c.iterator() new Enumeration[T] { - override def hasMoreElements: Boolean = - it.hasNext + override def hasMoreElements(): Boolean = + it.hasNext() override def nextElement(): T = it.next() @@ -577,7 +564,7 @@ object Collections { c.scalaOps.count(Objects.equals(_, o)) def disjoint(c1: Collection[_], c2: Collection[_]): Boolean = { - if (c1.size < c2.size) + if (c1.size() < c2.size()) !c1.scalaOps.exists(elem => c2.contains(elem)) else !c2.scalaOps.exists(elem => c1.contains(elem)) @@ -596,12 +583,12 @@ object Collections { } def newSetFromMap[E](map: Map[E, java.lang.Boolean]): Set[E] = { - if (!map.isEmpty) + if (!map.isEmpty()) throw new IllegalArgumentException new WrappedSet[E, Set[E]] { override protected val inner: Set[E] = - map.keySet + map.keySet() override def add(e: E): Boolean = map.put(e, java.lang.Boolean.TRUE) == null @@ -624,13 +611,6 @@ object Collections { } } - @inline - private implicit def comparatorToOrdering[E](cmp: Comparator[E]): Ordering[E] = { - new Ordering[E] { - final def compare(x: E, y: E): Int = cmp.compare(x, y) - } - } - private trait WrappedEquals { protected def inner: AnyRef @@ -647,18 +627,18 @@ object Collections { protected def inner: Coll def size(): Int = - inner.size + inner.size() - def isEmpty: Boolean = - inner.isEmpty + def isEmpty(): Boolean = + inner.isEmpty() def contains(o: Any): Boolean = inner.contains(o) def iterator(): Iterator[E] = - inner.iterator + inner.iterator() - def toArray: Array[AnyRef] = + def toArray(): Array[AnyRef] = inner.toArray() def toArray[T <: AnyRef](a: Array[T]): Array[T] = @@ -708,10 +688,10 @@ object Collections { inner.headSet(toElement) def first(): E = - inner.first + inner.first() def last(): E = - inner.last + inner.last() } private trait WrappedList[E] @@ -756,8 +736,8 @@ object Collections { def size(): Int = inner.size() - def isEmpty: Boolean = - inner.isEmpty + def isEmpty(): Boolean = + inner.isEmpty() def containsKey(key: scala.Any): Boolean = inner.containsKey(key) @@ -781,13 +761,13 @@ object Collections { inner.clear() def keySet(): Set[K] = - inner.keySet + inner.keySet() def values(): Collection[V] = - inner.values + inner.values() def entrySet(): Set[Map.Entry[K, V]] = - inner.entrySet.asInstanceOf[Set[Map.Entry[K, V]]] + inner.entrySet().asInstanceOf[Set[Map.Entry[K, V]]] override def toString(): String = inner.toString @@ -796,7 +776,7 @@ object Collections { private trait WrappedSortedMap[K, V] extends WrappedMap[K, V, SortedMap[K, V]] with SortedMap[K, V] { def comparator(): Comparator[_ >: K] = - inner.comparator + inner.comparator() def subMap(fromKey: K, toKey: K): SortedMap[K, V] = inner.subMap(fromKey, toKey) @@ -808,38 +788,38 @@ object Collections { inner.tailMap(fromKey) def firstKey(): K = - inner.firstKey + inner.firstKey() def lastKey(): K = - inner.lastKey + inner.lastKey() } private trait WrappedIterator[E, Iter <: Iterator[E]] extends Iterator[E] { protected def inner: Iter def hasNext(): Boolean = - inner.hasNext + inner.hasNext() def next(): E = inner.next() - def remove(): Unit = + override def remove(): Unit = inner.remove() } private trait WrappedListIterator[E] extends WrappedIterator[E, ListIterator[E]] with ListIterator[E] { def hasPrevious(): Boolean = - inner.hasPrevious + inner.hasPrevious() def previous(): E = inner.previous() def nextIndex(): Int = - inner.nextIndex + inner.nextIndex() def previousIndex(): Int = - inner.previousIndex + inner.previousIndex() def set(e: E): Unit = inner.set(e) @@ -854,12 +834,12 @@ object Collections { protected val eagerThrow: Boolean = true override def clear(): Unit = { - if (eagerThrow || !isEmpty) + if (eagerThrow || !isEmpty()) throw new UnsupportedOperationException } override def iterator(): Iterator[E] = - new UnmodifiableIterator(inner.iterator) + new UnmodifiableIterator(inner.iterator()) override def add(e: E): Boolean = throw new UnsupportedOperationException @@ -869,7 +849,7 @@ object Collections { else false override def addAll(c: Collection[_ <: E]): Boolean = - if (eagerThrow || !c.isEmpty) throw new UnsupportedOperationException + if (eagerThrow || !c.isEmpty()) throw new UnsupportedOperationException else false override def removeAll(c: Collection[_]): Boolean = { @@ -912,7 +892,7 @@ object Collections { extends UnmodifiableCollection[E, List[E]](inner) with WrappedList[E] { override def addAll(index: Int, c: Collection[_ <: E]): Boolean = - if (eagerThrow || !c.isEmpty) throw new UnsupportedOperationException + if (eagerThrow || !c.isEmpty()) throw new UnsupportedOperationException else false override def set(index: Int, element: E): E = @@ -953,23 +933,23 @@ object Collections { } override def putAll(m: Map[_ <: K, _ <: V]): Unit = { - if (eagerThrow || !m.isEmpty) + if (eagerThrow || !m.isEmpty()) throw new UnsupportedOperationException } override def clear(): Unit = { - if (eagerThrow || !isEmpty) + if (eagerThrow || !isEmpty()) throw new UnsupportedOperationException } override def keySet(): Set[K] = - unmodifiableSet(super.keySet) + unmodifiableSet(super.keySet()) override def values(): Collection[V] = - unmodifiableCollection(super.values) + unmodifiableCollection(super.values()) override def entrySet(): Set[Map.Entry[K, V]] = - unmodifiableSet(super.entrySet) + unmodifiableSet(super.entrySet()) } private class ImmutableMap[K, V]( @@ -1077,7 +1057,7 @@ object Collections { override def putAll(m: Map[_ <: K, _ <: V]): Unit = { m.entrySet().scalaOps.foreach { - entry => checkKeyAndValue(entry.getKey, entry.getValue) + entry => checkKeyAndValue(entry.getKey(), entry.getValue()) } super.putAll(m) } @@ -1162,7 +1142,7 @@ object Collections { def next(): Any = throw new NoSuchElementException - def remove(): Unit = + override def remove(): Unit = throw new IllegalStateException } diff --git a/javalib/src/main/scala/java/util/Date.scala b/javalib/src/main/scala/java/util/Date.scala index 13733d7529..170d5829d2 100644 --- a/javalib/src/main/scala/java/util/Date.scala +++ b/javalib/src/main/scala/java/util/Date.scala @@ -12,21 +12,26 @@ package java.util +import java.lang.Cloneable +import java.time.Instant + import scalajs.js -class Date private (private val date: js.Date) extends Object +class Date(private var millis: Long) extends Object with Serializable with Cloneable with Comparable[Date] { import Date._ - def this() = this(new js.Date()) + def this() = { + /* No need to check for overflow. If SJS lives that long (~year 275760), + * it's OK to have a bug ;-) + */ + this(js.Date.now().toLong) + } @Deprecated - def this(year: Int, month: Int, date: Int, hrs: Int, min: Int, sec: Int) = { - this(new js.Date()) - this.date.setFullYear(1900 + year, month, date) - this.date.setHours(hrs, min, sec, 0) - } + def this(year: Int, month: Int, date: Int, hrs: Int, min: Int, sec: Int) = + this(Date.safeGetTime(new js.Date(1900 + year, month, date, hrs, min, sec, 0))) @Deprecated def this(year: Int, month: Int, date: Int, hrs: Int, min: Int) = @@ -36,101 +41,132 @@ class Date private (private val date: js.Date) extends Object def this(year: Int, month: Int, date: Int) = this(year, month, date, 0, 0, 0) - def this(date: Long) = this(new js.Date(date.toDouble)) - @Deprecated - def this(date: String) = this(new js.Date(date)) + def this(date: String) = this(Date.parse(date)) - def after(when: Date): Boolean = date.getTime() > when.date.getTime() + def after(when: Date): Boolean = millis > when.millis - def before(when: Date): Boolean = date.getTime() < when.date.getTime() + def before(when: Date): Boolean = millis < when.millis - override def clone(): Object = new Date(new js.Date(date.getTime())) + override def clone(): Object = new Date(millis) override def compareTo(anotherDate: Date): Int = - java.lang.Double.compare(date.getTime(), anotherDate.date.getTime()) + java.lang.Long.compare(millis, anotherDate.millis) override def equals(obj: Any): Boolean = obj match { - case d: Date => d.date.getTime() == date.getTime() + case d: Date => d.millis == millis case _ => false } - override def hashCode(): Int = date.getTime().hashCode() + override def hashCode(): Int = millis.hashCode() + + private def asDate(): js.Date = { + if (!isSafeJSDate()) { + throw new IllegalArgumentException( + s"cannot convert this java.util.Date ($millis millis) to a js.Date") + } + new js.Date(millis.toDouble) + } + + @inline + private def mutDate(mutator: js.Date => Unit): Unit = { + val date = asDate() + mutator(date) + millis = safeGetTime(date) + } @Deprecated - def getDate(): Int = date.getDate() + def getDate(): Int = asDate().getDate().toInt @Deprecated - def getDay(): Int = date.getDay() + def getDay(): Int = asDate().getDay().toInt @Deprecated - def getHours(): Int = date.getHours() + def getHours(): Int = asDate().getHours().toInt @Deprecated - def getMinutes(): Int = date.getMinutes() + def getMinutes(): Int = asDate().getMinutes().toInt @Deprecated - def getMonth(): Int = date.getMonth() + def getMonth(): Int = asDate().getMonth().toInt @Deprecated - def getSeconds(): Int = date.getSeconds() + def getSeconds(): Int = asDate().getSeconds().toInt - def getTime(): Long = date.getTime().toLong + def getTime(): Long = millis @Deprecated - def getTimezoneOffset(): Int = date.getTimezoneOffset() + def getTimezoneOffset(): Int = new js.Date().getTimezoneOffset().toInt @Deprecated - def getYear(): Int = date.getFullYear() - 1900 + def getYear(): Int = asDate().getFullYear().toInt - 1900 @Deprecated - def setDate(date: Int): Unit = this.date.setDate(date) + def setDate(date: Int): Unit = mutDate(_.setDate(date)) @Deprecated - def setHours(hours: Int): Unit = date.setHours(hours) + def setHours(hours: Int): Unit = mutDate(_.setHours(hours)) @Deprecated - def setMinutes(minutes: Int): Unit = date.setMinutes(minutes) + def setMinutes(minutes: Int): Unit = mutDate(_.setMinutes(minutes)) @Deprecated - def setMonth(month: Int): Unit = date.setMonth(month) + def setMonth(month: Int): Unit = mutDate(_.setMonth(month)) @Deprecated - def setSeconds(seconds: Int): Unit = date.setSeconds(seconds) + def setSeconds(seconds: Int): Unit = mutDate(_.setSeconds(seconds)) - def setTime(time: Long): Unit = date.setTime(time.toDouble) + def setTime(time: Long): Unit = millis = time @Deprecated - def setYear(year: Int): Unit = date.setFullYear(1900 + year) + def setYear(year: Int): Unit = mutDate(_.setFullYear(1900 + year)) @Deprecated def toGMTString(): String = { - "" + date.getUTCDate() + " " + Months(date.getUTCMonth()) + " " + - date.getUTCFullYear() + " " + pad0(date.getUTCHours()) + ":" + - pad0(date.getUTCMinutes()) + ":" + - pad0(date.getUTCSeconds()) +" GMT" + val date = asDate() + "" + date.getUTCDate().toInt + " " + Months(date.getUTCMonth().toInt) + " " + + date.getUTCFullYear().toInt + " " + pad0(date.getUTCHours().toInt) + ":" + + pad0(date.getUTCMinutes().toInt) + ":" + + pad0(date.getUTCSeconds().toInt) +" GMT" } + def toInstant(): Instant = Instant.ofEpochMilli(getTime()) + @Deprecated def toLocaleString(): String = { - "" + date.getDate() + "-" + Months(date.getMonth()) + "-" + - date.getFullYear() + "-" + pad0(date.getHours()) + ":" + - pad0(date.getMinutes()) + ":" + pad0(date.getSeconds()) + val date = asDate() + "" + date.getDate().toInt + "-" + Months(date.getMonth().toInt) + "-" + + date.getFullYear().toInt + "-" + pad0(date.getHours().toInt) + ":" + + pad0(date.getMinutes().toInt) + ":" + pad0(date.getSeconds().toInt) } override def toString(): String = { - val offset = -date.getTimezoneOffset() - val sign = if (offset < 0) "-" else "+" - val hours = pad0(Math.abs(offset) / 60) - val mins = pad0(Math.abs(offset) % 60) - Days(date.getDay()) + " "+ Months(date.getMonth()) + " " + - pad0(date.getDate()) + " " + pad0(date.getHours()) + ":" + - pad0(date.getMinutes()) + ":" + pad0(date.getSeconds()) + " GMT" + " " + - date.getFullYear() + if (isSafeJSDate()) { + val date = asDate() + val offset = -date.getTimezoneOffset().toInt + val sign = if (offset < 0) "-" else "+" + val hours = pad0(Math.abs(offset) / 60) + val mins = pad0(Math.abs(offset) % 60) + Days(date.getDay().toInt) + " "+ Months(date.getMonth().toInt) + " " + + pad0(date.getDate().toInt) + " " + pad0(date.getHours().toInt) + ":" + + pad0(date.getMinutes().toInt) + ":" + pad0(date.getSeconds().toInt) + + " GMT" + " " + date.getFullYear().toInt + } else { + s"java.util.Date($millis)" + } } + + @inline + private def isSafeJSDate(): Boolean = + -MaxMillis <= millis && millis <= MaxMillis } object Date { + /* Maximum amount of milliseconds supported in a js.Date. + * See https://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.14 + */ + private final val MaxMillis = 8640000000000000L + private val Days = Array( "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat") @@ -143,12 +179,27 @@ object Date { if (str.length < 2) "0" + str else str } + def from(instant: Instant): Date = { + try { + new Date(instant.toEpochMilli()) + } catch { + case ex: ArithmeticException => + throw new IllegalArgumentException(ex) + } + } + @Deprecated def UTC(year: Int, month: Int, date: Int, hrs: Int, min: Int, sec: Int): Long = js.Date.UTC(year + 1900, month, date, hrs, min, sec).toLong @Deprecated - def parse(string: String): Long = - new Date(new js.Date(string)).getTime.toLong + def parse(string: String): Long = safeGetTime(new js.Date(string)) + + private def safeGetTime(date: js.Date): Long = { + val time = date.getTime() + if (java.lang.Double.isNaN(time)) + throw new IllegalArgumentException + time.toLong + } } diff --git a/javalib/src/main/scala/java/util/EventObject.scala b/javalib/src/main/scala/java/util/EventObject.scala index dfed2519ea..f792217e04 100644 --- a/javalib/src/main/scala/java/util/EventObject.scala +++ b/javalib/src/main/scala/java/util/EventObject.scala @@ -16,5 +16,5 @@ class EventObject(protected var source: AnyRef) { def getSource(): AnyRef = source override def toString(): String = - s"${getClass.getSimpleName}[source=$source]" + s"${getClass().getSimpleName()}[source=$source]" } diff --git a/javalib/src/main/scala/java/util/Formatter.scala b/javalib/src/main/scala/java/util/Formatter.scala index 988e9382f4..b70237c115 100644 --- a/javalib/src/main/scala/java/util/Formatter.scala +++ b/javalib/src/main/scala/java/util/Formatter.scala @@ -16,9 +16,12 @@ import scala.annotation.switch import scala.scalajs.js import java.lang.{Double => JDouble} +import java.lang.Utils._ import java.io._ +import java.math.{BigDecimal, BigInteger} -final class Formatter(private[this] var dest: Appendable) +final class Formatter private (private[this] var dest: Appendable, + formatterLocaleInfo: Formatter.LocaleInfo) extends Closeable with Flushable { import Formatter._ @@ -39,7 +42,13 @@ final class Formatter(private[this] var dest: Appendable) private[this] var closed: Boolean = false private[this] var lastIOException: IOException = null - def this() = this(null: Appendable) + def this() = this(null: Appendable, Formatter.RootLocaleInfo) + + def this(a: Appendable) = this(a, Formatter.RootLocaleInfo) + + def this(l: Locale) = this(null: Appendable, new Formatter.LocaleLocaleInfo(l)) + + def this(a: Appendable, l: Locale) = this(a, new Formatter.LocaleLocaleInfo(l)) @inline private def trapIOExceptions(body: => Unit): Unit = { @@ -74,8 +83,12 @@ final class Formatter(private[this] var dest: Appendable) @noinline private def sendToDestSlowPath(ss: js.Array[String]): Unit = { + // Workaround Scala 2.11 limitation: cannot nest anonymous functions for the IR cleaner + @inline def body(): Unit = + forArrayElems(ss)(dest.append(_)) + trapIOExceptions { - ss.foreach(dest.append(_)) + body() } } @@ -105,7 +118,14 @@ final class Formatter(private[this] var dest: Appendable) } } - def format(format: String, args: Array[AnyRef]): Formatter = { + def format(format: String, args: Array[AnyRef]): Formatter = + this.format(formatterLocaleInfo, format, args) + + def format(l: Locale, format: String, args: Array[AnyRef]): Formatter = + this.format(new LocaleLocaleInfo(l), format, args) + + private def format(localeInfo: LocaleInfo, format: String, + args: Array[AnyRef]): Formatter = { // scalastyle:off return checkNotClosed() @@ -126,7 +146,7 @@ final class Formatter(private[this] var dest: Appendable) } sendToDest(format.substring(fmtIndex, nextPercentIndex)) - // Process one '%' + // Parse the format specifier val formatSpecifierIndex = nextPercentIndex + 1 val re = FormatSpecifier @@ -140,38 +160,117 @@ final class Formatter(private[this] var dest: Appendable) * JVM. */ val conversion = - if (formatSpecifierIndex == fmtLength) "%" - else format.substring(formatSpecifierIndex, formatSpecifierIndex + 1) - throw new UnknownFormatConversionException(conversion) + if (formatSpecifierIndex == fmtLength) '%' + else format.charAt(formatSpecifierIndex) + throwUnknownFormatConversionException(conversion) } fmtIndex = re.lastIndex // position at the end of the match + // For error reporting + def fullFormatSpecifier: String = "%" + execResult(0) + + /* Extract values from the match result + * + * 1. DuplicateFormatFlagsException (in parseFlags) + */ + val conversion = format.charAt(fmtIndex - 1) val flags = parseFlags(execResult(2).asInstanceOf[String], conversion) - val width = parsePositiveIntSilent(execResult(3), default = -1) - val precision = parsePositiveIntSilent(execResult(4), default = -1) + val width = parsePositiveInt(execResult(3)) + val precision = parsePositiveInt(execResult(4)) + + if (width == -2) + throwIllegalFormatWidthException(Int.MinValue) // Int.MinValue mimics the JVM + if (precision == -2) + throwIllegalFormatPrecisionException(Int.MinValue) // Int.MinValue mimics the JVM + + /* At this point, we need to branch off for 'n', because it has a + * completely different error reporting spec. In particular, it must + * throw an IllegalFormatFlagsException if any flag is specified, + * although the regular mechanism would throw a + * FormatFlagsConversionMismatchException. + * + * It is also the only conversion that throws + * IllegalFormatWidthException, so we use this forced special path to + * also take care of that one. + * + * We also treat '%' specially. Although its spec suggests that its + * validation could be done in the generic way, experimentation suggests + * that it behaves differently. Anyway, once 'n' has its special path, + * '%' becomes the only one that does not take an argument, and so it + * would need a special path later. So we handle it here and get it out + * of the way. This further allows the generic path to only deal with + * ASCII letters, which is convenient. + */ - val arg = if (conversion == '%' || conversion == 'n') { - /* No argument. Make sure not to bump `lastImplicitArgIndex` nor to - * affect `lastArgIndex`. - */ - null + if (conversion == 'n') { + if (precision != -1) + throwIllegalFormatPrecisionException(precision) + if (width != -1) + throwIllegalFormatWidthException(width) + if (flags.bits != 0) + throwIllegalFormatFlagsException(flags) + + sendToDest("\n") + } else if (conversion == '%') { + if (precision != -1) + throwIllegalFormatPrecisionException(precision) + checkIllegalFormatFlags(flags) + if (flags.leftAlign && width == -1) + throwMissingFormatWidthException(fullFormatSpecifier) + checkFlagsConversionMismatch('%', flags, ~LeftAlign) + + padAndSendToDestNoZeroPad(flags, width, "%") } else { - if (flags.leftAlign && width < 0) - throw new MissingFormatWidthException("%" + execResult(0)) + // 2. UnknownFormatConversionException + + // Because of the RegExp that we use, we know that `conversion` is an ASCII letter + val conversionLower = + if (flags.upperCase) (conversion + ('a' - 'A')).toChar + else conversion + val illegalFlags = ConversionsIllegalFlags(conversionLower - 'a') + if (illegalFlags == -1 || (flags.bits & UpperCase & illegalFlags) != 0) + throwUnknownFormatConversionException(conversion) + + // 3. MissingFormatWidthException + + if (flags.hasAnyOf(LeftAlign | ZeroPad) && width == -1) + throwMissingFormatWidthException(fullFormatSpecifier) + + // 4. IllegalFormatFlagsException + + checkIllegalFormatFlags(flags) + + // 5. IllegalFormatPrecisionException + + if (precision != -1 && (illegalFlags & Precision) != 0) + throwIllegalFormatPrecisionException(precision) + + // 6. FormatFlagsConversionMismatchException + + checkFlagsConversionMismatch(conversionLower, flags, illegalFlags) + + /* Finally, get the argument and format it. + * + * 7. MissingFormatArgumentException | IllegalFormatConversionException | IllegalFormatCodePointException + * + * The first one is handled here, while we extract the argument. + * The other two are handled in formatArg(). + */ val argIndex = if (flags.useLastIndex) { // Explicitly use the last index lastArgIndex } else { - val i = parsePositiveIntSilent(execResult(1), default = 0) - if (i == 0) { - // Either there is no explicit index, or the explicit index is 0 + val i = parsePositiveInt(execResult(1)) + if (i == -1) { + // No explicit index lastImplicitArgIndex += 1 lastImplicitArgIndex - } else if (i < 0) { - // Cannot be parsed, same as useLastIndex + } else if (i <= 0) { + // Out of range + throwIllegalFormatArgumentIndexException(i) lastArgIndex } else { // Could be parsed, this is the index @@ -179,19 +278,23 @@ final class Formatter(private[this] var dest: Appendable) } } - if (argIndex <= 0 || argIndex > args.length) { - val conversionStr = conversion.toString - if ("bBhHsHcCdoxXeEgGfn%".indexOf(conversionStr) < 0) - throw new UnknownFormatConversionException(conversionStr) - else - throw new MissingFormatArgumentException("%" + execResult(0)) - } + if (argIndex <= 0 || argIndex > args.length) + throwMissingFormatArgumentException(fullFormatSpecifier) lastArgIndex = argIndex - args(argIndex - 1) - } + val arg = args(argIndex - 1) + + /* Format the arg. We handle `null` in a generic way, except for 'b' + * and 's'. 'b' because it actually gives specific semantics to it. + * 's' because it needs to reject the '#' flag for `null`, and '#' is + * accepted for Formattable instances. + */ - formatArg(arg, conversion, flags, width, precision) + if (arg == null && conversionLower != 'b' && conversionLower != 's') + formatNonNumericString(RootLocaleInfo, flags, width, precision, "null") + else + formatArg(localeInfo, arg, conversionLower, flags, width, precision) + } } this @@ -203,7 +306,7 @@ final class Formatter(private[this] var dest: Appendable) * object about why we keep it here. */ private def parseFlags(flags: String, conversion: Char): Flags = { - var bits = if (conversion <= 'Z') UpperCase else 0 + var bits = if (conversion >= 'A' && conversion <= 'Z') UpperCase else 0 val len = flags.length var i = 0 @@ -221,7 +324,7 @@ final class Formatter(private[this] var dest: Appendable) } if ((bits & bit) != 0) - throw new DuplicateFormatFlagsException(f.toString) + throwDuplicateFormatFlagsException(f) bits |= bit i += 1 @@ -230,77 +333,43 @@ final class Formatter(private[this] var dest: Appendable) new Flags(bits) } - private def parsePositiveIntSilent(capture: js.UndefOr[String], - default: Int): Int = { - capture.fold { - default + /** Parses an optional integer argument. + * + * Returns -1 if it was not specified, and -2 if it was out of the + * Int range. + */ + private def parsePositiveInt(capture: js.UndefOr[String]): Int = { + undefOrFold(capture) { + -1 } { s => val x = js.Dynamic.global.parseInt(s, 10).asInstanceOf[Double] if (x <= Int.MaxValue) x.toInt else - -1 // Silently ignore and return -1 + -2 } } - private def formatArg(arg: Any, conversion: Char, flags: Flags, width: Int, - precision: Int): Unit = { - - @inline def rejectPrecision(): Unit = { - if (precision >= 0) - throw new IllegalFormatPrecisionException(precision) - } - - def formatNullOrThrowIllegalFormatConversion(): Unit = { - if (arg == null) - formatNonNumericString(flags, width, precision, "null") - else - throw new IllegalFormatConversionException(conversion, arg.getClass) - } - - @inline def precisionWithDefault = - if (precision >= 0) precision - else 6 + private def formatArg(localeInfo: LocaleInfo, arg: Any, conversionLower: Char, + flags: Flags, width: Int, precision: Int): Unit = { - @inline def efgCommon(notation: (Double, Int, Boolean) => String): Unit = { - arg match { - case arg: Double => - if (JDouble.isNaN(arg) || JDouble.isInfinite(arg)) { - formatNaNOrInfinite(flags, width, arg) - } else { - /* The alternative format # of 'e', 'f' and 'g' is to force a - * decimal separator. - */ - val forceDecimalSep = flags.altFormat - formatNumericString(flags, width, - notation(arg, precisionWithDefault, forceDecimalSep)) - } - case _ => - formatNullOrThrowIllegalFormatConversion() - } - } + @inline def illegalFormatConversion(): Nothing = + throwIllegalFormatConversionException(conversionLower, arg) - (conversion: @switch) match { - case 'b' | 'B' => - validateFlags(flags, conversion, - invalidFlags = NumericOnlyFlags | AltFormat) + (conversionLower: @switch) match { + case 'b' => val str = if ((arg.asInstanceOf[AnyRef] eq false.asInstanceOf[AnyRef]) || arg == null) "false" else "true" - formatNonNumericString(flags, width, precision, str) + formatNonNumericString(RootLocaleInfo, flags, width, precision, str) - case 'h' | 'H' => - validateFlags(flags, conversion, - invalidFlags = NumericOnlyFlags | AltFormat) - val str = - if (arg == null) "null" - else Integer.toHexString(arg.hashCode) - formatNonNumericString(flags, width, precision, str) + case 'h' => + val str = Integer.toHexString(arg.hashCode) + formatNonNumericString(RootLocaleInfo, flags, width, precision, str) - case 's' | 'S' => + case 's' => arg match { case formattable: Formattable => - validateFlags(flags, conversion, invalidFlags = NumericOnlyFlags) val formattableFlags = { (if (flags.leftAlign) FormattableFlags.LEFT_JUSTIFY else 0) | (if (flags.altFormat) FormattableFlags.ALTERNATE else 0) | @@ -309,152 +378,139 @@ final class Formatter(private[this] var dest: Appendable) formattable.formatTo(this, formattableFlags, width, precision) case _ => - validateFlags(flags, conversion, - invalidFlags = NumericOnlyFlags | AltFormat) + /* The Formattable case accepts AltFormat, therefore it is not + * present in the generic `ConversionsIllegalFlags` table. However, + * it is illegal for any other value, so we must check it now. + */ + checkFlagsConversionMismatch(conversionLower, flags, AltFormat) + val str = String.valueOf(arg) - formatNonNumericString(flags, width, precision, str) + formatNonNumericString(localeInfo, flags, width, precision, str) } - case 'c' | 'C' => - validateFlags(flags, conversion, - invalidFlags = NumericOnlyFlags | AltFormat) - rejectPrecision() - arg match { + case 'c' => + val str = arg match { case arg: Char => - formatNonNumericString(flags, width, -1, arg.toString) + arg.toString() case arg: Int => if (!Character.isValidCodePoint(arg)) - throw new IllegalFormatCodePointException(arg) - val str = if (arg < Character.MIN_SUPPLEMENTARY_CODE_POINT) { - js.Dynamic.global.String.fromCharCode(arg) + throwIllegalFormatCodePointException(arg) + if (arg < Character.MIN_SUPPLEMENTARY_CODE_POINT) { + js.Dynamic.global.String.fromCharCode(arg).asInstanceOf[String] } else { - js.Dynamic.global.String.fromCharCode( - 0xd800 | ((arg >> 10) - (0x10000 >> 10)), - 0xdc00 | (arg & 0x3ff)) + js.Dynamic.global.String + .fromCharCode(0xd800 | ((arg >> 10) - (0x10000 >> 10)), 0xdc00 | (arg & 0x3ff)) + .asInstanceOf[String] } - formatNonNumericString(flags, width, -1, str.asInstanceOf[String]) case _ => - formatNullOrThrowIllegalFormatConversion() + illegalFormatConversion() } + formatNonNumericString(localeInfo, flags, width, -1, str) case 'd' => - validateFlags(flags, conversion, invalidFlags = AltFormat) - rejectPrecision() - arg match { - case arg: Int => - formatNumericString(flags, width, arg.toString()) - case arg: Long => - formatNumericString(flags, width, arg.toString()) - case _ => - formatNullOrThrowIllegalFormatConversion() + val str = arg match { + case arg: Int => arg.toString() + case arg: Long => arg.toString() + case arg: BigInteger => arg.toString() + case _ => illegalFormatConversion() } + formatNumericString(localeInfo, flags, width, str) - case 'o' => - validateFlags(flags, conversion, - invalidFlags = InvalidFlagsForOctalAndHex) - rejectPrecision() - val prefix = - if (flags.altFormat) "0" - else "" - arg match { - case arg: Int => - padAndSendToDest(flags, width, prefix, - java.lang.Integer.toOctalString(arg)) - case arg: Long => - padAndSendToDest(flags, width, prefix, - java.lang.Long.toOctalString(arg)) - case _ => - formatNullOrThrowIllegalFormatConversion() - } + case 'o' | 'x' => + // Octal/hex formatting is not localized - case 'x' | 'X' => - validateFlags(flags, conversion, - invalidFlags = InvalidFlagsForOctalAndHex) - rejectPrecision() + val isOctal = conversionLower == 'o' val prefix = { if (!flags.altFormat) "" + else if (isOctal) "0" else if (flags.upperCase) "0X" else "0x" } + arg match { - case arg: Int => - padAndSendToDest(flags, width, prefix, - applyUpperCase(flags, java.lang.Integer.toHexString(arg))) - case arg: Long => - padAndSendToDest(flags, width, prefix, - applyUpperCase(flags, java.lang.Long.toHexString(arg))) + case arg: BigInteger => + val radix = if (isOctal) 8 else 16 + formatNumericString(RootLocaleInfo, flags, width, + arg.toString(radix), prefix) + case _ => - formatNullOrThrowIllegalFormatConversion() - } + val str = arg match { + case arg: Int => + if (isOctal) java.lang.Integer.toOctalString(arg) + else java.lang.Integer.toHexString(arg) + case arg: Long => + if (isOctal) java.lang.Long.toOctalString(arg) + else java.lang.Long.toHexString(arg) + case _ => + illegalFormatConversion() + } - case 'e' | 'E' => - validateFlags(flags, conversion, invalidFlags = UseGroupingSeps) - efgCommon(computerizedScientificNotation _) + /* The Int and Long conversions have extra illegal flags, which are + * not in the `ConversionsIllegalFlags` table because they are + * legal for BigIntegers. We must check them now. + */ + checkFlagsConversionMismatch(conversionLower, flags, + PositivePlus | PositiveSpace | NegativeParen) - case 'g' | 'G' => - validateFlags(flags, conversion, invalidFlags = AltFormat) - efgCommon(generalScientificNotation _) + padAndSendToDest(RootLocaleInfo, flags, width, prefix, + applyNumberUpperCase(flags, str)) + } - case 'f' => - validateFlags(flags, conversion, invalidFlags = 0) - efgCommon(decimalNotation _) + case 'e' | 'f' | 'g' => + def formatDecimal(x: Decimal): Unit = { + /* The alternative format # of 'e', 'f' and 'g' is to force a + * decimal separator. + */ + val forceDecimalSep = flags.altFormat + val actualPrecision = + if (precision >= 0) precision + else 6 + + val notation = conversionLower match { + case 'e' => computerizedScientificNotation(x, digitsAfterDot = actualPrecision, forceDecimalSep) + case 'f' => decimalNotation(x, scale = actualPrecision, forceDecimalSep) + case _ => generalScientificNotation(x, precision = actualPrecision, forceDecimalSep) + } + formatNumericString(localeInfo, flags, width, notation) + } - case '%' => - validateFlagsForPercentAndNewline(flags, conversion, - invalidFlags = AllWrittenFlags & ~LeftAlign) - rejectPrecision() - if (flags.leftAlign && width < 0) - throw new MissingFormatWidthException("%-%") - padAndSendToDestNoZeroPad(flags, width, "%") + arg match { + case arg: Double => + if (JDouble.isNaN(arg) || JDouble.isInfinite(arg)) + formatNaNOrInfinite(flags, width, arg) + else + formatDecimal(numberToDecimal(arg)) + case arg: BigDecimal => + formatDecimal(bigDecimalToDecimal(arg)) + case _ => + illegalFormatConversion() + } - case 'n' => - validateFlagsForPercentAndNewline(flags, conversion, - invalidFlags = AllWrittenFlags) - rejectPrecision() - if (width >= 0) - throw new IllegalFormatWidthException(width) - sendToDest("\n") + case 'a' => + // Floating point hex formatting is not localized + arg match { + case arg: Double => + formatHexFloatingPoint(flags, width, precision, arg) + case _ => + illegalFormatConversion() + } case _ => - throw new UnknownFormatConversionException(conversion.toString) + throw new AssertionError( + "Unknown conversion '" + conversionLower + "' was not rejected earlier") } } - @inline private def validateFlags(flags: Flags, conversion: Char, - invalidFlags: Int): Unit = { - - @noinline def flagsConversionMismatch(): Nothing = { - throw new FormatFlagsConversionMismatchException( - flagsToString(new Flags(flags.bits & invalidFlags)), conversion) - } - - if ((flags.bits & invalidFlags) != 0) - flagsConversionMismatch() - - @noinline def illegalFlags(): Nothing = - throw new IllegalFormatFlagsException(flagsToString(flags)) - - /* The test `(invalidFlags & BadCombo) == 0` is redundant, but is - * constant-folded away at called site, and if false it allows to dce the - * test after the `&&`. If both tests are eliminated, the entire `if` - * disappears. - */ - val BadCombo1 = LeftAlign | ZeroPad - val BadCombo2 = PositivePlus | PositiveSpace - if (((invalidFlags & BadCombo1) == 0 && (flags.bits & BadCombo1) == BadCombo1) || - ((invalidFlags & BadCombo2) == 0 && (flags.bits & BadCombo2) == BadCombo2)) { - illegalFlags() - } + @inline private def checkIllegalFormatFlags(flags: Flags): Unit = { + if (flags.hasAllOf(LeftAlign | ZeroPad) || flags.hasAllOf(PositivePlus | PositiveSpace)) + throwIllegalFormatFlagsException(flags) } - @inline private def validateFlagsForPercentAndNewline(flags: Flags, - conversion: Char, invalidFlags: Int): Unit = { + @inline private def checkFlagsConversionMismatch(conversionLower: Char, + flags: Flags, illegalFlags: Int): Unit = { - @noinline def illegalFlags(): Nothing = - throw new IllegalFormatFlagsException(flagsToString(flags)) - - if ((flags.bits & invalidFlags) != 0) - illegalFlags() + if (flags.hasAnyOf(illegalFlags)) + throwFormatFlagsConversionMismatchException(conversionLower, flags, illegalFlags) } /* Should in theory be a method of `Flags`. See the comment on that class @@ -471,89 +527,239 @@ final class Formatter(private[this] var dest: Appendable) (if (flags.useLastIndex) "<" else "") } - private def computerizedScientificNotation(x: Double, precision: Int, + private def computerizedScientificNotation(x: Decimal, digitsAfterDot: Int, forceDecimalSep: Boolean): String = { - import js.JSNumberOps._ - // First use JavaScript's native toExponential conversion - val s1 = x.toExponential(precision) + val rounded = x.round(precision = 1 + digitsAfterDot) - // -0.0 should have a leading '-' - val s2 = - if (x == 0.0 && 1 / x < 0) "-" + s1 - else s1 + val signStr = if (rounded.negative) "-" else "" - // Then make sure the exponent has at least 2 digits for the JDK spec - val len = s2.length - val s3 = - if ('e' != s2.charAt(len - 3)) s2 - else s2.substring(0, len - 1) + "0" + s2.substring(len - 1) + val intStr = rounded.unscaledValue + val dotPos = 1 + val fractionalDigitCount = intStr.length() - dotPos + val missingZeros = digitsAfterDot - fractionalDigitCount - // Finally, force the decimal separator, if requested - if (!forceDecimalSep || s3.indexOf(".") >= 0) { - s3 - } else { - val pos = s3.indexOf("e") - s3.substring(0, pos) + "." + s3.substring(pos) + val significandStr = { + val integerPart = intStr.substring(0, dotPos) + val fractionalPart = intStr.substring(dotPos) + strOfZeros(missingZeros) + if (fractionalPart == "" && !forceDecimalSep) + integerPart + else + integerPart + "." + fractionalPart } + + val exponent = fractionalDigitCount - rounded.scale + val exponentSign = if (exponent < 0) "-" else "+" + val exponentAbsStr0 = Math.abs(exponent).toString() + val exponentAbsStr = + if (exponentAbsStr0.length() == 1) "0" + exponentAbsStr0 + else exponentAbsStr0 + + signStr + significandStr + "e" + exponentSign + exponentAbsStr + } + + private def decimalNotation(x: Decimal, scale: Int, + forceDecimalSep: Boolean): String = { + + val rounded = x.setScale(scale) + + val signStr = if (rounded.negative) "-" else "" + + val intStr = rounded.unscaledValue + val intStrLen = intStr.length() + + val minDigits = 1 + scale // 1 before the '.' plus `scale` after it + val expandedIntStr = + if (intStrLen >= minDigits) intStr + else strOfZeros(minDigits - intStrLen) + intStr + val dotPos = expandedIntStr.length() - scale + + val integerPart = signStr + expandedIntStr.substring(0, dotPos) + if (scale == 0 && !forceDecimalSep) + integerPart + else + integerPart + "." + expandedIntStr.substring(dotPos) } - private def generalScientificNotation(x: Double, precision: Int, + private def generalScientificNotation(x: Decimal, precision: Int, forceDecimalSep: Boolean): String = { - val m = Math.abs(x) val p = if (precision == 0) 1 else precision - // between 1e-4 and 10e(p): display as fixed - if (m >= 1e-4 && m < Math.pow(10, p)) { - /* First approximation of the smallest power of 10 that is >= m. - * Due to rounding errors in the event of an imprecise `log10` - * function, sig0 could actually be the smallest power of 10 - * that is > m. - */ - val sig0 = Math.ceil(Math.log10(m)).toInt - /* Increment sig0 so that it is always the first power of 10 - * that is > m. - */ - val sig = if (Math.pow(10, sig0) <= m) sig0 + 1 else sig0 - decimalNotation(x, Math.max(p - sig, 0), forceDecimalSep) - } else { - computerizedScientificNotation(x, p - 1, forceDecimalSep) - } + /* The JavaDoc says: + * + * > After rounding for the precision, the formatting of the resulting + * > magnitude m depends on its value. + * + * so we first round to `p` significant digits before deciding which + * notation to use, based on the order of magnitude of the result. The + * order of magnitude is an integer `n` such that + * + * 10^n <= abs(x) < 10^(n+1) + * + * (except if x is a zero value, in which case it is 0). + * + * We also pass `rounded` to the dedicated notation function. Both + * functions perform rounding of their own, but the rounding methods will + * detect that no further rounding is necessary, so it is worth it. + */ + val rounded = x.round(p) + val orderOfMagnitude = (rounded.precision - 1) - rounded.scale + if (orderOfMagnitude >= -4 && orderOfMagnitude < p) + decimalNotation(rounded, scale = Math.max(0, p - orderOfMagnitude - 1), forceDecimalSep) + else + computerizedScientificNotation(rounded, digitsAfterDot = p - 1, forceDecimalSep) } - private def decimalNotation(x: Double, precision: Int, - forceDecimalSep: Boolean): String = { + /** Format an argument for the 'a' conversion. + * + * This conversion requires quite some code, compared to the others, and is + * therefore extracted into separate functions. + * + * There is some logic that is duplicated from + * `java.lang.Double.toHexString()`. It cannot be factored out because: + * + * - the javalanglib and javalib do not see each other's custom method + * (could be solved if we merged them), + * - this method deals with subnormals in a very weird way when the + * precision is set and is <= 12, and + * - the handling of padding is fairly specific to `Formatter`, and would + * not lend itself well to be factored with the more straightforward code + * in `Double.toHexString()`. + */ + private def formatHexFloatingPoint(flags: Flags, width: Int, precision: Int, + arg: Double): Unit = { + + if (JDouble.isNaN(arg) || JDouble.isInfinite(arg)) { + formatNaNOrInfinite(flags, width, arg) + } else { + // Extract the raw bits from the argument - import js.JSNumberOps._ + val ebits = 11 // exponent size + val mbits = 52 // mantissa size + val mbitsMask = ((1L << mbits) - 1L) + val bias = (1 << (ebits - 1)) - 1 - // First use JavaScript's native toFixed conversion - val s1 = x.toFixed(precision) + val bits = JDouble.doubleToLongBits(arg) + val negative = bits < 0 + val explicitMBits = bits & mbitsMask + val biasedExponent = (bits >>> mbits).toInt & ((1 << ebits) - 1) - // -0.0 should have a leading '-' - val s2 = - if (x == 0.0 && 1 / x < 0) "-" + s1 - else s1 + // Compute the actual precision - // Finally, force the decimal separator, if requested - if (forceDecimalSep && s2.indexOf(".") < 0) - s2 + "." - else - s2 + val actualPrecision = { + if (precision == 0) 1 // apparently, this is how it behaves on the JVM + else if (precision > 12) -1 // important for subnormals + else precision + } + + // Sign string + + val signStr = { + if (negative) "-" + else if (flags.positivePlus) "+" + else if (flags.positiveSpace) " " + else "" + } + + /* Extract the implicit bit, the mantissa, and the exponent. + * Also apply the artificial normalization of subnormals when the + * actualPrecision is in the interval [1, 12]. + */ + + val (implicitBitStr, mantissa, exponent) = if (biasedExponent == 0) { + if (explicitMBits == 0L) { + // Zero + ("0", 0L, 0) + } else { + // Subnormal + if (actualPrecision == -1) { + ("0", explicitMBits, -1022) + } else { + // Artificial normalization, required by the 'a' conversion spec + val leadingZeros = java.lang.Long.numberOfLeadingZeros(explicitMBits) + val shift = (leadingZeros + 1) - (64 - mbits) + val normalizedMantissa = (explicitMBits << shift) & mbitsMask + val normalizedExponent = -1022 - shift + ("1", normalizedMantissa, normalizedExponent) + } + } + } else { + // Normalized + ("1", explicitMBits, biasedExponent - bias) + } + + // Apply the rounding mandated by the precision + + val roundedMantissa = if (actualPrecision == -1) { + mantissa + } else { + val roundingUnit = 1L << (mbits - (actualPrecision * 4)) // 4 bits per hex character + val droppedPartMask = roundingUnit - 1 + val halfRoundingUnit = roundingUnit >> 1 + + val truncated = mantissa & ~droppedPartMask + val droppedPart = mantissa & droppedPartMask + + /* The JavaDoc is not clear about what flavor of rounding should be + * used. We use round-half-to-even to mimic the behavior of the JVM. + */ + if (droppedPart < halfRoundingUnit) + truncated + else if (droppedPart > halfRoundingUnit) + truncated + roundingUnit + else if ((truncated & roundingUnit) == 0L) // truncated is even + truncated + else + truncated + roundingUnit + } + + // Mantissa string + + val mantissaStr = { + val baseStr = java.lang.Long.toHexString(roundedMantissa) + val padded = "0000000000000".substring(baseStr.length()) + baseStr // 13 zeros + + assert(padded.length() == 13 && (13 * 4 == mbits), + "padded mantissa does not have the right number of bits") + + // ~ padded.dropRightWhile(_ == '0') but keep at least minLength chars + val minLength = Math.max(1, actualPrecision) + var len = padded.length + while (len > minLength && padded.charAt(len - 1) == '0') + len -= 1 + padded.substring(0, len) + } + + // Exponent string + + val exponentStr = Integer.toString(exponent) + + // Assemble, pad and send to dest + + val prefix = signStr + (if (flags.upperCase) "0X" else "0x") + val rest = implicitBitStr + "." + mantissaStr + "p" + exponentStr + + padAndSendToDest(RootLocaleInfo, flags, width, prefix, + applyNumberUpperCase(flags, rest)) + } } - private def formatNonNumericString(flags: Flags, width: Int, precision: Int, - str: String): Unit = { + private def formatNonNumericString(localeInfo: LocaleInfo, flags: Flags, + width: Int, precision: Int, str: String): Unit = { val truncatedStr = - if (precision < 0) str + if (precision < 0 || precision >= str.length()) str else str.substring(0, precision) - padAndSendToDestNoZeroPad(flags, width, applyUpperCase(flags, truncatedStr)) + padAndSendToDestNoZeroPad(flags, width, + applyUpperCase(localeInfo, flags, truncatedStr)) } private def formatNaNOrInfinite(flags: Flags, width: Int, x: Double): Unit = { + // NaN and Infinite formatting are not localized + val str = if (JDouble.isNaN(x)) { "NaN" } else if (x > 0.0) { @@ -565,26 +771,27 @@ final class Formatter(private[this] var dest: Appendable) else "-Infinity" } - padAndSendToDestNoZeroPad(flags, width, applyUpperCase(flags, str)) + padAndSendToDestNoZeroPad(flags, width, applyNumberUpperCase(flags, str)) } - private def formatNumericString(flags: Flags, width: Int, str: String): Unit = { + private def formatNumericString(localeInfo: LocaleInfo, flags: Flags, + width: Int, str: String, basePrefix: String = ""): Unit = { /* Flags for which a numeric string needs to be decomposed and transformed, * not just padded and/or uppercased. We can write fast-paths in this * method if none of them are present. */ val TransformativeFlags = - PositivePlus | PositiveSpace | UseGroupingSeps | NegativeParen + PositivePlus | PositiveSpace | UseGroupingSeps | NegativeParen | AltFormat if (str.length >= width && !flags.hasAnyOf(TransformativeFlags)) { // Super-fast-path - sendToDest(applyUpperCase(flags, str)) + sendToDest(localeInfo.localizeNumber(applyNumberUpperCase(flags, str))) } else if (!flags.hasAnyOf(TransformativeFlags | ZeroPad)) { // Fast-path that does not need to inspect the string - formatNonNumericString(flags, width, -1, str) + padAndSendToDestNoZeroPad(flags, width, applyNumberUpperCase(flags, str)) } else { // Extract prefix and rest, based on flags and the presence of a sign - val (prefix, rest0) = if (str.charAt(0) != '-') { + val (numberPrefix, rest0) = if (str.charAt(0) != '-') { if (flags.positivePlus) ("+", str) else if (flags.positiveSpace) @@ -598,31 +805,45 @@ final class Formatter(private[this] var dest: Appendable) ("-", str.substring(1)) } + val prefix = numberPrefix + basePrefix + // Insert grouping separators, if required val rest = - if (flags.useGroupingSeps) insertGroupingSeps(rest0) + if (flags.useGroupingSeps) insertGroupingCommas(localeInfo, rest0) else rest0 - // Apply uppercase, pad and send - padAndSendToDest(flags, width, prefix, applyUpperCase(flags, rest)) + // Apply uppercase, localization, pad and send + padAndSendToDest(localeInfo, flags, width, prefix, + localeInfo.localizeNumber(applyNumberUpperCase(flags, rest))) } } - private def insertGroupingSeps(s: String): String = { + /** Inserts grouping commas at the right positions for the locale. + * + * We already insert the ',' character, regardless of the locale. That is + * fixed later by `localeInfo.localizeNumber`. The only locale-sensitive + * behavior in this method is the grouping size. + * + * The reason is that we do not want to insert a character that would + * collide with another meaning (such as '.') at this point. + */ + private def insertGroupingCommas(localeInfo: LocaleInfo, s: String): String = { + val groupingSize = localeInfo.groupingSize + val len = s.length var index = 0 while (index != len && { val c = s.charAt(index); c >= '0' && c <= '9' }) { index += 1 } - index -= 3 + index -= groupingSize if (index <= 0) { s } else { var result = s.substring(index) - while (index > 3) { - val next = index - 3 + while (index > groupingSize) { + val next = index - groupingSize result = s.substring(next, index) + "," + result index = next } @@ -630,8 +851,12 @@ final class Formatter(private[this] var dest: Appendable) } } - private def applyUpperCase(flags: Flags, str: String): String = - if (flags.upperCase) str.toUpperCase + private def applyNumberUpperCase(flags: Flags, str: String): String = + if (flags.upperCase) str.toUpperCase() // uppercasing is not localized for numbers + else str + + private def applyUpperCase(localeInfo: LocaleInfo, flags: Flags, str: String): String = + if (flags.upperCase) localeInfo.toUpperCase(str) else str /** This method ignores `flags.zeroPad` and `flags.upperCase`. */ @@ -649,15 +874,15 @@ final class Formatter(private[this] var dest: Appendable) } /** This method ignores `flags.upperCase`. */ - private def padAndSendToDest(flags: Flags, width: Int, prefix: String, - str: String): Unit = { + private def padAndSendToDest(localeInfo: LocaleInfo, flags: Flags, + width: Int, prefix: String, str: String): Unit = { val len = prefix.length + str.length if (len >= width) sendToDest(prefix, str) else if (flags.zeroPad) - sendToDest(prefix, strRepeat("0", width - len), str) + sendToDest(prefix, strRepeat(localeInfo.zeroDigitString, width - len), str) else if (flags.leftAlign) sendToDest(prefix, str, strRepeat(" ", width - len)) else @@ -678,7 +903,7 @@ final class Formatter(private[this] var dest: Appendable) def locale(): Locale = { checkNotClosed() - null + formatterLocaleInfo.locale } def out(): Appendable = { @@ -703,6 +928,52 @@ final class Formatter(private[this] var dest: Appendable) throw new FormatterClosedException() } + /* Helpers to throw exceptions with all the right arguments. + * + * Some are direct forwarders, like `IllegalFormatPrecisionException`; they + * are here for consistency. + */ + + private def throwDuplicateFormatFlagsException(flag: Char): Nothing = + throw new DuplicateFormatFlagsException(flag.toString()) + + private def throwUnknownFormatConversionException(conversion: Char): Nothing = + throw new UnknownFormatConversionException(conversion.toString()) + + private def throwIllegalFormatPrecisionException(precision: Int): Nothing = + throw new IllegalFormatPrecisionException(precision) + + private def throwIllegalFormatWidthException(width: Int): Nothing = + throw new IllegalFormatWidthException(width) + + private def throwIllegalFormatArgumentIndexException(index: Int): Nothing = { + val msg = + if (index == 0) "Illegal format argument index = 0" + else "Format argument index: (not representable as int)" + throw new IllegalFormatArgumentIndexException(msg) + } + + private def throwIllegalFormatFlagsException(flags: Flags): Nothing = + throw new IllegalFormatFlagsException(flagsToString(flags)) + + private def throwMissingFormatWidthException(fullFormatSpecifier: String): Nothing = + throw new MissingFormatWidthException(fullFormatSpecifier) + + private def throwFormatFlagsConversionMismatchException(conversionLower: Char, + flags: Flags, illegalFlags: Int): Nothing = { + throw new FormatFlagsConversionMismatchException( + flagsToString(new Flags(flags.bits & illegalFlags)), conversionLower) + } + + private def throwMissingFormatArgumentException(fullFormatSpecifier: String): Nothing = + throw new MissingFormatArgumentException(fullFormatSpecifier) + + private def throwIllegalFormatConversionException(conversionLower: Char, arg: Any): Nothing = + throw new IllegalFormatConversionException(conversionLower, arg.getClass) + + private def throwIllegalFormatCodePointException(arg: Int): Nothing = + throw new IllegalFormatCodePointException(arg) + } object Formatter { @@ -710,6 +981,27 @@ object Formatter { private val FormatSpecifier = new js.RegExp( """(?:(\d+)\$)?([-#+ 0,\(<]*)(\d+)?(?:\.(\d+))?[%A-Za-z]""", "g") + private def strOfZeros(count: Int): String = { + val twentyZeros = "00000000000000000000" + if (count <= 20) { + twentyZeros.substring(0, count) + } else { + var result = "" + var remaining = count + while (remaining > 20) { + result += twentyZeros + remaining -= 20 + } + result + twentyZeros.substring(0, remaining) + } + } + + @inline + private def assert(condition: Boolean, msg: => String): Unit = { + if (!condition) + throw new AssertionError(msg) + } + /* This class is never used in a place where it would box, so it will * completely disappear at link-time. Make sure to keep it that way. * @@ -731,6 +1023,8 @@ object Formatter { @inline def upperCase: Boolean = (bits & UpperCase) != 0 @inline def hasAnyOf(testBits: Int): Boolean = (bits & testBits) != 0 + + @inline def hasAllOf(testBits: Int): Boolean = (bits & testBits) == testBits } /* This object only contains `final val`s and (synthetic) `@inline` @@ -747,14 +1041,307 @@ object Formatter { final val NegativeParen = 0x040 final val UseLastIndex = 0x080 final val UpperCase = 0x100 + final val Precision = 0x200 // used in ConversionsIllegalFlags + } - final val InvalidFlagsForOctalAndHex = - PositivePlus | PositiveSpace | UseGroupingSeps | NegativeParen + private val ConversionsIllegalFlags: Array[Int] = { + import Flags._ - final val NumericOnlyFlags = + val NumericOnlyFlags = PositivePlus | PositiveSpace | ZeroPad | UseGroupingSeps | NegativeParen - final val AllWrittenFlags = - LeftAlign | AltFormat | NumericOnlyFlags | UseLastIndex + // 'n' and '%' are not here because they have special paths in `format` + + Array( + UseGroupingSeps | NegativeParen, // a + NumericOnlyFlags | AltFormat, // b + NumericOnlyFlags | AltFormat | Precision, // c + AltFormat | UpperCase | Precision, // d + UseGroupingSeps, // e + UpperCase, // f + AltFormat, // g + NumericOnlyFlags | AltFormat, // h + -1, -1, -1, -1, -1, -1, // i -> n + UseGroupingSeps | UpperCase | Precision, // o + -1, -1, -1, // p -> r + NumericOnlyFlags, // s + -1, -1, -1, -1, // t -> w + UseGroupingSeps | Precision, // x + -1, -1 // y -> z + ) + } + + /** Converts a `Double` into a `Decimal` that has as few digits as possible + * while still uniquely identifying `x`. + * + * We do this by converting the absolute value of the number into a string + * using its built-in `toString()` conversion. By ECMAScript's spec, this + * yields a decimal representation with as few significant digits as + * possible, although it can be in fixed notation or in computerized + * scientific notation. + * + * We then parse that string to recover the integer part, the factional part + * and the exponent; the latter two being optional. + * + * From the parts, we construct a `Decimal`, making sure to create one that + * does not have leading 0's (as it is forbidden by `Decimal`'s invariants). + */ + private def numberToDecimal(x: Double): Decimal = { + if (x == 0.0) { + val negative = 1.0 / x < 0.0 + Decimal.zero(negative) + } else { + val negative = x < 0.0 + val s = JDouble.toString(if (negative) -x else x) + + val ePos = s.indexOf('e') + val e = + if (ePos < 0) 0 + else js.Dynamic.global.parseInt(s.substring(ePos + 1)).asInstanceOf[Int] + val significandEnd = if (ePos < 0) s.length() else ePos + + val dotPos = s.indexOf('.') + if (dotPos < 0) { + // No '.'; there cannot be leading 0's (x == 0.0 was handled before) + val unscaledValue = s.substring(0, significandEnd) + val scale = -e + new Decimal(negative, unscaledValue, scale) + } else { + // There is a '.'; there can be leading 0's, which we must remove + val digits = s.substring(0, dotPos) + s.substring(dotPos + 1, significandEnd) + val digitsLen = digits.length() + var i = 0 + while (i < digitsLen && digits.charAt(i) == '0') + i += 1 + val unscaledValue = digits.substring(i) + val scale = -e + (significandEnd - (dotPos + 1)) + new Decimal(negative, unscaledValue, scale) + } + } + } + + /** Converts a `BigDecimal` into a `Decimal`. + * + * Zero values are considered positive for the conversion. + * + * All other values keep their sign, unscaled value and scale. + */ + private def bigDecimalToDecimal(x: BigDecimal): Decimal = { + val unscaledValueWithSign = x.unscaledValue().toString() + + if (unscaledValueWithSign == "0") { + Decimal.zero(negative = false) + } else { + val negative = unscaledValueWithSign.charAt(0) == '-' + val unscaledValue = + if (negative) unscaledValueWithSign.substring(1) + else unscaledValueWithSign + val scale = x.scale() + new Decimal(negative, unscaledValue, scale) + } + } + + /** A decimal representation of a number. + * + * An instance of this class represents the number whose absolute value is + * `unscaledValue × 10^(-scale)`, and that is negative iff `negative` is + * true. + * + * The `unscaledValue` is stored as a String of decimal digits, i.e., + * characters in the range ['0', '9'], expressed in base 10. Leading 0's are + * *not* valid. + * + * As an exception, a zero value is represented by an `unscaledValue` of + * `"0"`. The scale of zero value is always 0. + * + * `Decimal` is similar to `BigDecimal`, with some differences: + * + * - `Decimal` distinguishes +0 from -0. + * - The unscaled value of `Decimal` is stored in base 10. + * + * The methods it exposes have the same meaning as for BigDecimal, with the + * only rounding mode being HALF_UP. + */ + private final class Decimal(val negative: Boolean, val unscaledValue: String, + val scale: Int) { + + def isZero: Boolean = unscaledValue == "0" + + /** The number of digits in the unscaled value. + * + * The precision of a zero value is 1. + */ + def precision: Int = unscaledValue.length() + + /** Rounds the number so that it has at most the given precision, i.e., at + * most the given number of digits in its `unscaledValue`. + * + * The given `precision` must be greater than 0. + */ + def round(precision: Int): Decimal = { + assert(precision > 0, "Decimal.round() called with non-positive precision") + + roundAtPos(roundingPos = precision) + } + + /** Returns a new Decimal instance with the same value, possibly rounded, + * with the given scale. + * + * If this is a zero value, the same value is returned (a zero value must + * always have a 0 scale). Rounding may also cause the result to be a zero + * value, in which case its scale must be 0 as well. Otherwise, the result + * is non-zero and is guaranteed to have exactly the given new scale. + */ + def setScale(newScale: Int): Decimal = { + val roundingPos = unscaledValue.length() + newScale - scale + val rounded = roundAtPos(roundingPos) + assert(rounded.isZero || rounded.scale <= newScale, + "roundAtPos returned a non-zero value with a scale too large") + + if (rounded.isZero || rounded.scale == newScale) + rounded + else + new Decimal(negative, rounded.unscaledValue + strOfZeros(newScale - rounded.scale), newScale) + } + + /** Rounds the number at the given position in its `unscaledValue`. + * + * The `roundingPos` may be any integer value. + * + * - If it is < 0, the result is always a zero value. + * - If it is >= `unscaledValue.lenght()`, the result is always the same + * value. + * - Otherwise, the `unscaledValue` will be truncated at `roundingPos`, + * and rounded up iff `unscaledValue.charAt(roundingPos) >= '5'`. + * + * The value of `negative` is always preserved. + * + * Unless the result is a zero value, the following guarantees apply: + * + * - its scale is guaranteed to be at most + * `scale - (unscaledValue.length() - roundingPos)`. + * - its precision is guaranteed to be at most + * `max(1, roundingPos)`. + */ + private def roundAtPos(roundingPos: Int): Decimal = { + val digits = this.unscaledValue // local copy + val digitsLen = digits.length() + + if (roundingPos < 0) { + Decimal.zero(negative) + } else if (roundingPos >= digitsLen) { + this // no rounding necessary + } else { + @inline def scaleAtPos(pos: Int): Int = scale - (digitsLen - pos) + + if (digits.charAt(roundingPos) < '5') { + // Truncate at roundingPos + if (roundingPos == 0) + Decimal.zero(negative) + else + new Decimal(negative, digits.substring(0, roundingPos), scaleAtPos(roundingPos)) + } else { + // Truncate and increment at roundingPos + + // Find the position of the last non-9 digit in the truncated digits (can be -1) + var lastNonNinePos = roundingPos - 1 + while (lastNonNinePos >= 0 && digits.charAt(lastNonNinePos) == '9') + lastNonNinePos -= 1 + + val newUnscaledValue = + if (lastNonNinePos < 0) "1" + else digits.substring(0, lastNonNinePos) + (digits.charAt(lastNonNinePos) + 1).toChar + + val newScale = scaleAtPos(lastNonNinePos + 1) + + new Decimal(negative, newUnscaledValue, newScale) + } + } + } + + // for debugging only + override def toString(): String = + s"Decimal($negative, $unscaledValue, $scale)" + } + + private object Decimal { + @inline def zero(negative: Boolean): Decimal = + new Decimal(negative, "0", 0) + } + + /** A proxy for a `java.util.Locale` or for the root locale that provides + * the info required by `Formatter`. + * + * The purpose of this abstraction is to allow `java.util.Formatter` to link + * when `java.util.Locale` and `java.text.*` are not on the classpath, as + * long as only methods that do not take an explicit `Locale` are used. + * + * While the `LocaleLocaleInfo` subclass actually delegates to a `Locale` + * (and hence cannot link without `Locale`), the object `RootLocaleInfo` + * hard-codes the required information about the Root locale. + * + * We use object-oriented method calls so that the reachability analysis + * never reaches the `Locale`-dependent code if `LocaleLocaleInfo` is never + * instantiated, which is the case as long the methods and constructors + * taking an explicit `Locale` are not called. + * + * When `LocaleLocaleInfo` can be dead-code-eliminated, the optimizer can + * even inline and constant-fold all the methods of `RootLocaleInfo`, + * resulting in top efficiency. + */ + private sealed abstract class LocaleInfo { + def locale: Locale + def groupingSize: Int + def zeroDigitString: String + def localizeNumber(str: String): String + def toUpperCase(str: String): String + } + + private object RootLocaleInfo extends LocaleInfo { + def locale: Locale = Locale.ROOT + def groupingSize: Int = 3 + def zeroDigitString: String = "0" + def localizeNumber(str: String): String = str + def toUpperCase(str: String): String = str.toUpperCase() + } + + private final class LocaleLocaleInfo(val locale: Locale) extends LocaleInfo { + import java.text._ + + private def actualLocale: Locale = + if (locale == null) Locale.ROOT + else locale + + private lazy val decimalFormatSymbols: DecimalFormatSymbols = + DecimalFormatSymbols.getInstance(actualLocale) + + lazy val groupingSize: Int = { + NumberFormat.getNumberInstance(actualLocale) match { + case decimalFormat: DecimalFormat => decimalFormat.getGroupingSize() + case _ => 3 + } + } + + def zeroDigitString: String = decimalFormatSymbols.getZeroDigit().toString() + + def localizeNumber(str: String): String = { + val formatSymbols = decimalFormatSymbols + val digitOffset = formatSymbols.getZeroDigit() - '0' + var result = "" + val len = str.length() + var i = 0 + while (i != len) { + result += (str.charAt(i) match { + case c if c >= '0' && c <= '9' => (c + digitOffset).toChar + case '.' => formatSymbols.getDecimalSeparator() + case ',' => formatSymbols.getGroupingSeparator() + case c => c + }) + i += 1 + } + result + } + + def toUpperCase(str: String): String = str.toUpperCase(actualLocale) } } diff --git a/javalib/src/main/scala/java/util/HashMap.scala b/javalib/src/main/scala/java/util/HashMap.scala index 8968bbb738..63aeff2881 100644 --- a/javalib/src/main/scala/java/util/HashMap.scala +++ b/javalib/src/main/scala/java/util/HashMap.scala @@ -14,11 +14,13 @@ package java.util import scala.annotation.tailrec +import java.lang.Cloneable import java.{util => ju} +import java.util.function.{BiConsumer, BiFunction, Function} import ScalaOps._ -class HashMap[K, V](initialCapacity: Int, loadFactor: Double) +class HashMap[K, V](initialCapacity: Int, loadFactor: Float) extends AbstractMap[K, V] with Serializable with Cloneable { self => @@ -26,7 +28,7 @@ class HashMap[K, V](initialCapacity: Int, loadFactor: Double) if (initialCapacity < 0) throw new IllegalArgumentException("initialCapacity < 0") - if (loadFactor <= 0.0) + if (loadFactor <= 0.0f) throw new IllegalArgumentException("loadFactor <= 0.0") def this() = @@ -80,21 +82,14 @@ class HashMap[K, V](initialCapacity: Int, loadFactor: Double) override def isEmpty(): Boolean = contentSize == 0 - override def get(key: Any): V = { - val node = findNode(key) - if (node eq null) { - null.asInstanceOf[V] - } else { - nodeWasAccessed(node) - node.value - } - } + override def get(key: Any): V = + getOrDefaultImpl(key, null.asInstanceOf[V]) override def containsKey(key: Any): Boolean = findNode(key) ne null override def put(key: K, value: V): V = - put0(key, value) + put0(key, value, ifAbsent = false) override def putAll(m: Map[_ <: K, _ <: V]): Unit = { m match { @@ -102,7 +97,7 @@ class HashMap[K, V](initialCapacity: Int, loadFactor: Double) val iter = m.nodeIterator() while (iter.hasNext()) { val next = iter.next() - put0(next.key, next.value, next.hash) + put0(next.key, next.value, next.hash, ifAbsent = false) } case _ => super.putAll(m) @@ -132,6 +127,111 @@ class HashMap[K, V](initialCapacity: Int, loadFactor: Double) def entrySet(): ju.Set[ju.Map.Entry[K, V]] = new EntrySet + override def getOrDefault(key: Any, defaultValue: V): V = + getOrDefaultImpl(key, defaultValue) + + /** Common implementation for get() and getOrDefault(). + * + * It is not directly inside the body of getOrDefault(), because subclasses + * could override getOrDefault() to re-rely on get(). + */ + private def getOrDefaultImpl(key: Any, defaultValue: V): V = { + val node = findNode(key) + if (node eq null) { + defaultValue + } else { + nodeWasAccessed(node) + node.value + } + } + + override def putIfAbsent(key: K, value: V): V = + put0(key, value, ifAbsent = true) + + override def remove(key: Any, value: Any): Boolean = { + val (node, idx) = findNodeAndIndexForRemoval(key) + if ((node ne null) && Objects.equals(node.value, value)) { + remove0(node, idx) + true + } else { + false + } + } + + override def replace(key: K, oldValue: V, newValue: V): Boolean = { + val node = findNode(key) + if ((node ne null) && Objects.equals(node.value, oldValue)) { + node.value = newValue + nodeWasAccessed(node) + true + } else { + false + } + } + + override def replace(key: K, value: V): V = { + val node = findNode(key) + if (node ne null) { + val old = node.value + node.value = value + nodeWasAccessed(node) + old + } else { + null.asInstanceOf[V] + } + } + + override def computeIfAbsent(key: K, mappingFunction: Function[_ >: K, _ <: V]): V = { + val (node, hash, idx, oldValue) = getNode0(key) + if (oldValue != null) { + oldValue + } else { + val newValue = mappingFunction.apply(key) + if (newValue != null) + put0(key, newValue, hash, node) + newValue + } + } + + override def computeIfPresent(key: K, remappingFunction: BiFunction[_ >: K, _ >: V, _ <: V]): V = { + val (node, hash, idx, oldValue) = getNode0(key) + if (oldValue == null) { + oldValue + } else { + val newValue = remappingFunction.apply(key, oldValue) + putOrRemove0(key, hash, idx, node, newValue) + } + } + + override def compute(key: K, remappingFunction: BiFunction[_ >: K, _ >: V, _ <: V]): V = { + val (node, hash, idx, oldValue) = getNode0(key) + val newValue = remappingFunction.apply(key, oldValue) + putOrRemove0(key, hash, idx, node, newValue) + } + + override def merge(key: K, value: V, remappingFunction: BiFunction[_ >: V, _ >: V, _ <: V]): V = { + Objects.requireNonNull(value) + + val (node, hash, idx, oldValue) = getNode0(key) + val newValue = + if (oldValue == null) value + else remappingFunction.apply(oldValue, value) + putOrRemove0(key, hash, idx, node, newValue) + } + + override def forEach(action: BiConsumer[_ >: K, _ >: V]): Unit = { + val len = table.length + var i = 0 + while (i != len) { + var node = table(i) + while (node ne null) { + action.accept(node.key, node.value) + node = node.next + } + i += 1 + } + } + override def clone(): AnyRef = new HashMap[K, V](this) @@ -166,42 +266,70 @@ class HashMap[K, V](initialCapacity: Int, loadFactor: Double) loop(table(idx)) } + // Helpers for compute-like methods + + @inline + private def getNode0(key: Any): (Node[K, V], Int, Int, V) = { + val hash = computeHash(key) + val idx = index(hash) + val node = findNode0(key, hash, idx) + val value = if (node eq null) { + null.asInstanceOf[V] + } else { + nodeWasAccessed(node) + node.value + } + (node, hash, idx, value) + } + + private def putOrRemove0(key: K, hash: Int, idx: Int, node: Node[K, V], + newValue: V): V = { + if (newValue != null) + put0(key, newValue, hash, node) + else if (node ne null) + remove0(node, idx) + newValue + } + // Heavy lifting: modifications - /** Adds a key-value pair to this map + /** Puts a key-value pair into this map. * - * @param key the key to add - * @param value the value to add + * If an entry already exists for the given key, `nodeWasAccessed` is + * called, and, unless `ifAbsent` is true, its value is updated. + * + * If no entry existed for the given key, a new entry is created with the + * given value, and `nodeWasAdded` is called. + * + * @param key the key to put + * @param value the value to put + * @param ifAbsent if true, do not override an existing mapping * @return the old value associated with `key`, or `null` if there was none */ @inline - private[this] def put0(key: K, value: V): V = - put0(key, value, computeHash(key)) + private[this] def put0(key: K, value: V, ifAbsent: Boolean): V = + put0(key, value, computeHash(key), ifAbsent) - /** Adds a key-value pair to this map + /** Puts a key-value pair into this map. * - * @param key the key to add - * @param value the value to add - * @param hash the **improved** hashcode of `key` (see computeHash) - * @return the old value associated with `key`, or `null` if there was none - */ - private[this] def put0(key: K, value: V, hash: Int): V = { - if (contentSize + 1 >= threshold) - growTable() - val idx = index(hash) - put0(key, value, hash, idx) - } - - /** Adds a key-value pair to this map + * If an entry already exists for the given key, `nodeWasAccessed` is + * called, and, unless `ifAbsent` is true, its value is updated. * - * @param key the key to add - * @param value the value to add + * If no entry existed for the given key, a new entry is created with the + * given value, and `nodeWasAdded` is called. + * + * @param key the key to put + * @param value the value to put * @param hash the **improved** hashcode of `key` (see computeHash) - * @param idx the index in the `table` corresponding to the `hash` + * @param ifAbsent if true, do not override an existing mapping * @return the old value associated with `key`, or `null` if there was none */ - private[this] def put0(key: K, value: V, hash: Int, idx: Int): V = { + private[this] def put0(key: K, value: V, hash: Int, ifAbsent: Boolean): V = { // scalastyle:off return + val newContentSize = contentSize + 1 + if (newContentSize >= threshold) + growTable() + val idx = index(hash) val newNode = table(idx) match { case null => val newNode = this.newNode(key, hash, value, null, null) @@ -214,7 +342,8 @@ class HashMap[K, V](initialCapacity: Int, loadFactor: Double) if (n.hash == hash && Objects.equals(key, n.key)) { nodeWasAccessed(n) val old = n.value - n.value = value + if (!ifAbsent || (old == null)) + n.value = value return old } prev = n @@ -229,12 +358,64 @@ class HashMap[K, V](initialCapacity: Int, loadFactor: Double) n.previous = newNode newNode } - contentSize += 1 + contentSize = newContentSize nodeWasAdded(newNode) null.asInstanceOf[V] // scalastyle:on return } + /** Puts a key-value pair into this map, given the result of an existing + * lookup. + * + * The parameter `node` must be the result of a lookup for the given key. + * If null, this method assumes that there is no entry for the given key in + * the map. + * + * `nodeWasAccessed` is NOT called by this method, since it must already + * have been called by the prerequisite lookup. + * + * If no entry existed for the given key, a new entry is created with the + * given value, and `nodeWasAdded` is called. + * + * @param key the key to add + * @param value the value to add + * @param hash the **improved** hashcode of `key` (see computeHash) + * @param node the entry for the given `key`, or `null` if there is no such entry + */ + private[this] def put0(key: K, value: V, hash: Int, node: Node[K, V]): Unit = { + if (node ne null) { + node.value = value + } else { + val newContentSize = contentSize + 1 + if (newContentSize >= threshold) + growTable() + val idx = index(hash) + val newNode = table(idx) match { + case null => + val newNode = this.newNode(key, hash, value, null, null) + table(idx) = newNode + newNode + case first => + var prev: Node[K, V] = null + var n = first + while ((n ne null) && n.hash < hash) { + prev = n + n = n.next + } + val newNode = this.newNode(key, hash, value, prev, n) + if (prev eq null) + table(idx) = newNode + else + prev.next = newNode + if (n ne null) + n.previous = newNode + newNode + } + contentSize = newContentSize + nodeWasAdded(newNode) + } + } + /** Removes a key from this map if it exists. * * @param key the key to remove @@ -315,7 +496,7 @@ class HashMap[K, V](initialCapacity: Int, loadFactor: Double) Math.min(Integer.highestOneBit(Math.max(capacity - 1, 4)) * 2, 1 << 30) @inline private[this] def newThreshold(size: Int): Int = - (size.toDouble * loadFactor).toInt + (size.toDouble * loadFactor.toDouble).toInt // Iterators @@ -386,7 +567,7 @@ class HashMap[K, V](initialCapacity: Int, loadFactor: Double) extract(node) } - def remove(): Unit = { + override def remove(): Unit = { val last = lastNode if (last eq null) throw new IllegalStateException("next must be called at least once before remove") @@ -518,6 +699,6 @@ object HashMap { unimproveHash(hash) ^ Objects.hashCode(value) override def toString(): String = - "" + getKey + "=" + getValue + "" + getKey() + "=" + getValue() } } diff --git a/javalib/src/main/scala/java/util/HashSet.scala b/javalib/src/main/scala/java/util/HashSet.scala index c05ea35794..f09868f25b 100644 --- a/javalib/src/main/scala/java/util/HashSet.scala +++ b/javalib/src/main/scala/java/util/HashSet.scala @@ -12,6 +12,8 @@ package java.util +import java.lang.Cloneable + class HashSet[E] private[util] (inner: HashMap[E, Any]) extends AbstractSet[E] with Set[E] with Cloneable with Serializable { @@ -57,7 +59,7 @@ class HashSet[E] private[util] (inner: HashMap[E, Any]) override def addAll(c: Collection[_ <: E]): Boolean = { val iter = c.iterator() var changed = false - while (iter.hasNext) + while (iter.hasNext()) changed = add(iter.next()) || changed changed } diff --git a/javalib/src/main/scala/java/util/Hashtable.scala b/javalib/src/main/scala/java/util/Hashtable.scala index 9b353b1866..9667c74811 100644 --- a/javalib/src/main/scala/java/util/Hashtable.scala +++ b/javalib/src/main/scala/java/util/Hashtable.scala @@ -12,6 +12,7 @@ package java.util +import java.lang.Cloneable import java.{util => ju} /* This implementation allows `null` keys and values, although the JavaDoc diff --git a/javalib/src/main/scala/java/util/IdentityHashMap.scala b/javalib/src/main/scala/java/util/IdentityHashMap.scala index 1682e6c99c..cb236bf263 100644 --- a/javalib/src/main/scala/java/util/IdentityHashMap.scala +++ b/javalib/src/main/scala/java/util/IdentityHashMap.scala @@ -12,6 +12,7 @@ package java.util +import java.lang.Cloneable import java.{util => ju} import scala.annotation.tailrec @@ -49,21 +50,21 @@ class IdentityHashMap[K, V] private ( } override def containsKey(key: Any): Boolean = - inner.containsKey(IdentityBox(key)) + inner.containsKey(new IdentityBox(key)) override def containsValue(value: Any): Boolean = inner.valueIterator().scalaOps.exists(same(_, value)) override def get(key: Any): V = - inner.get(IdentityBox(key)) + inner.get(new IdentityBox(key)) override def isEmpty(): Boolean = inner.isEmpty() override def put(key: K, value: V): V = - inner.put(IdentityBox(key), value) + inner.put(new IdentityBox(key), value) override def remove(key: Any): V = - inner.remove(IdentityBox(key)) + inner.remove(new IdentityBox(key)) override def size(): Int = inner.size() @@ -88,7 +89,7 @@ class IdentityHashMap[K, V] private ( override def remove(o: Any): Boolean = { @tailrec def findAndRemove(iter: Iterator[V]): Boolean = { - if (iter.hasNext) { + if (iter.hasNext()) { if (same(iter.next(), o)) { iter.remove() true @@ -108,7 +109,7 @@ class IdentityHashMap[K, V] private ( override def retainAll(c: Collection[_]): Boolean = { val iter = iterator() var changed = false - while (iter.hasNext) { + while (iter.hasNext()) { val elem = iter.next() if (!findSame(elem, c)) { iter.remove() @@ -133,7 +134,7 @@ class IdentityHashMap[K, V] private ( def next(): K = iter.next().inner - def remove(): Unit = + override def remove(): Unit = iter.remove() } } @@ -152,12 +153,12 @@ class IdentityHashMap[K, V] private ( } override def removeAll(c: Collection[_]): Boolean = { - if (size > c.size) { + if (size() > c.size()) { c.scalaOps.foldLeft(false)((prev, elem) => this.remove(elem) || prev) } else { @tailrec def removeAll(iter: Iterator[K], modified: Boolean): Boolean = { - if (iter.hasNext) { + if (iter.hasNext()) { if (findSame(iter.next(), c)) { iter.remove() removeAll(iter, true) @@ -168,14 +169,14 @@ class IdentityHashMap[K, V] private ( modified } } - removeAll(this.iterator, false) + removeAll(this.iterator(), false) } } override def retainAll(c: Collection[_]): Boolean = { val iter = iterator() var changed = false - while (iter.hasNext) { + while (iter.hasNext()) { val elem = iter.next() if (!findSame(elem, c)) { iter.remove() @@ -200,7 +201,7 @@ class IdentityHashMap[K, V] private ( def next(): Map.Entry[K, V] = new MapEntry(iter.next()) - def remove(): Unit = + override def remove(): Unit = iter.remove() } } @@ -240,7 +241,7 @@ class IdentityHashMap[K, V] private ( } object IdentityHashMap { - private final case class IdentityBox[+K](inner: K) { + private final class IdentityBox[+K](val inner: K) { override def equals(o: Any): Boolean = { o match { case o: IdentityBox[_] => @@ -254,24 +255,13 @@ object IdentityHashMap { System.identityHashCode(inner) } - @inline private def same(v1: Any, v2: Any): Boolean = { - // v1.asInstanceOf[AnyRef] eq v2.asInstanceOf[AnyRef] - // Use the following until 1.0.0 - // See https://github.com/scala-js/scala-js/pull/3747 - val v1Ref = v1.asInstanceOf[AnyRef] - val v2Ref = v2.asInstanceOf[AnyRef] - if (v1Ref eq v2Ref) { - (v1Ref ne java.lang.Double.valueOf(0.0)) || - (1.0 / v1Ref.asInstanceOf[Double] == 1.0 / v2Ref.asInstanceOf[Double]) // +0.0 v -0.0 - } else { - (v1Ref ne v1Ref) && (v2Ref ne v2Ref) // NaN - } - } + @inline private def same(v1: Any, v2: Any): Boolean = + v1.asInstanceOf[AnyRef] eq v2.asInstanceOf[AnyRef] private def findSame[K](elem: K, c: Collection[_]): Boolean = { // scalastyle:off return val iter = c.iterator() - while (iter.hasNext) { + while (iter.hasNext()) { if (same(elem, iter.next())) return true } diff --git a/javalib/src/main/scala/java/util/Iterator.scala b/javalib/src/main/scala/java/util/Iterator.scala index 4bfbacf46d..f6f2943a44 100644 --- a/javalib/src/main/scala/java/util/Iterator.scala +++ b/javalib/src/main/scala/java/util/Iterator.scala @@ -12,8 +12,21 @@ package java.util +import scala.scalajs.js.annotation.JavaDefaultMethod + +import java.util.function.Consumer + trait Iterator[E] { def hasNext(): Boolean def next(): E - def remove(): Unit + + @JavaDefaultMethod + def remove(): Unit = + throw new UnsupportedOperationException("remove") + + @JavaDefaultMethod + def forEachRemaining(action: Consumer[_ >: E]): Unit = { + while (hasNext()) + action.accept(next()) + } } diff --git a/javalib/src/main/scala/java/util/LinkedHashMap.scala b/javalib/src/main/scala/java/util/LinkedHashMap.scala index 6faebf55f1..ba46ffc844 100644 --- a/javalib/src/main/scala/java/util/LinkedHashMap.scala +++ b/javalib/src/main/scala/java/util/LinkedHashMap.scala @@ -13,6 +13,7 @@ package java.util import java.{util => ju} +import java.util.function.BiConsumer class LinkedHashMap[K, V](initialCapacity: Int, loadFactor: Float, accessOrder: Boolean) @@ -93,8 +94,27 @@ class LinkedHashMap[K, V](initialCapacity: Int, loadFactor: Float, younger.older = older } + override def clear(): Unit = { + super.clear() + + /* #4195 HashMap.clear() won't call `nodeWasRemoved` for every node, which + * would be inefficient, so `eldest` and `yougest` are not automatically + * updated. We must explicitly set them to `null` here. + */ + eldest = null + youngest = null + } + protected def removeEldestEntry(eldest: Map.Entry[K, V]): Boolean = false + override def forEach(action: BiConsumer[_ >: K, _ >: V]): Unit = { + var node = eldest + while (node ne null) { + action.accept(node.key, node.value) + node = node.younger + } + } + private[util] override def nodeIterator(): ju.Iterator[HashMap.Node[K, V]] = new NodeIterator @@ -135,7 +155,7 @@ class LinkedHashMap[K, V](initialCapacity: Int, loadFactor: Float, extract(node) } - def remove(): Unit = { + override def remove(): Unit = { val last = lastNode if (last eq null) throw new IllegalStateException("next must be called at least once before remove") diff --git a/javalib/src/main/scala/java/util/LinkedHashSet.scala b/javalib/src/main/scala/java/util/LinkedHashSet.scala index b67e126d8d..6133d013d9 100644 --- a/javalib/src/main/scala/java/util/LinkedHashSet.scala +++ b/javalib/src/main/scala/java/util/LinkedHashSet.scala @@ -12,6 +12,8 @@ package java.util +import java.lang.Cloneable + class LinkedHashSet[E] private[util] (inner: LinkedHashMap[E, Any]) extends HashSet[E](inner) with Set[E] with Cloneable with Serializable { diff --git a/javalib/src/main/scala/java/util/LinkedList.scala b/javalib/src/main/scala/java/util/LinkedList.scala index f6699068b5..cd0f205b8d 100644 --- a/javalib/src/main/scala/java/util/LinkedList.scala +++ b/javalib/src/main/scala/java/util/LinkedList.scala @@ -12,7 +12,7 @@ package java.util -import scala.annotation.tailrec +import java.lang.Cloneable import ScalaOps._ @@ -120,10 +120,10 @@ class LinkedList[E]() extends AbstractSequentialList[E] } override def remove(o: Any): Boolean = - _removeOccurrence(listIterator, o) + _removeOccurrence(listIterator(), o) override def addAll(c: Collection[_ <: E]): Boolean = { - val iter = c.iterator + val iter = c.iterator() val changed = iter.hasNext() while (iter.hasNext()) addLast(iter.next()) @@ -139,16 +139,16 @@ class LinkedList[E]() extends AbstractSequentialList[E] private def getNodeAt(index: Int): Node[E] = { if (index == 0) head - else if (index == size - 1) last + else if (index == size() - 1) last else { var current: Node[E] = null - if (index <= size/2) { + if (index <= size() / 2) { current = head for (_ <- 0 until index) current = current.next } else { current = last - for (_ <- index until (size - 1)) + for (_ <- index until (size() - 1)) current = current.prev } current @@ -241,7 +241,7 @@ class LinkedList[E]() extends AbstractSequentialList[E] else removeFirst() def pollLast(): E = - if (isEmpty) null.asInstanceOf[E] + if (isEmpty()) null.asInstanceOf[E] else removeLast() def push(e: E): Unit = @@ -276,7 +276,7 @@ class LinkedList[E]() extends AbstractSequentialList[E] private var i: Double = index private var currentNode: Node[E] = - if (index == size) null else + if (index == size()) null else getNodeAt(index) private var lastNode: Node[E] = @@ -284,10 +284,10 @@ class LinkedList[E]() extends AbstractSequentialList[E] LinkedList.this.last def hasNext(): Boolean = - i < size + i < size() def next(): E = { - if (i >= size) + if (i >= size()) throw new NoSuchElementException() last = i @@ -303,7 +303,7 @@ class LinkedList[E]() extends AbstractSequentialList[E] i > 0 def previous(): E = { - if (!hasPrevious) + if (!hasPrevious()) throw new NoSuchElementException() i -= 1 @@ -323,7 +323,7 @@ class LinkedList[E]() extends AbstractSequentialList[E] def previousIndex(): Int = (i - 1).toInt - def remove(): Unit = { + override def remove(): Unit = { checkThatHasLast() if (currentNode eq null) { @@ -384,7 +384,7 @@ class LinkedList[E]() extends AbstractSequentialList[E] ret.value } - def remove(): Unit = { + override def remove(): Unit = { if (!removeEnabled) throw new IllegalStateException() diff --git a/javalib/src/main/scala/java/util/List.scala b/javalib/src/main/scala/java/util/List.scala index eb53d13173..33d219303a 100644 --- a/javalib/src/main/scala/java/util/List.scala +++ b/javalib/src/main/scala/java/util/List.scala @@ -12,7 +12,42 @@ package java.util +import java.util.function.UnaryOperator + +import scala.scalajs.js.annotation.JavaDefaultMethod + trait List[E] extends Collection[E] { + @JavaDefaultMethod + def replaceAll(operator: UnaryOperator[E]): Unit = { + val iter = listIterator() + while (iter.hasNext()) + iter.set(operator.apply(iter.next())) + } + + @JavaDefaultMethod + def sort(c: Comparator[_ >: E]): Unit = { + val arrayBuf = toArray() + Arrays.sort[AnyRef with E](arrayBuf.asInstanceOf[Array[AnyRef with E]], c) + + val len = arrayBuf.length + + if (this.isInstanceOf[RandomAccess]) { + var i = 0 + while (i != len) { + set(i, arrayBuf(i).asInstanceOf[E]) + i += 1 + } + } else { + var i = 0 + val iter = listIterator() + while (i != len) { + iter.next() + iter.set(arrayBuf(i).asInstanceOf[E]) + i += 1 + } + } + } + def get(index: Int): E def set(index: Int, element: E): E def add(index: Int, element: E): Unit diff --git a/javalib/src/main/scala/java/util/ListIterator.scala b/javalib/src/main/scala/java/util/ListIterator.scala index 88c573583b..9788598e04 100644 --- a/javalib/src/main/scala/java/util/ListIterator.scala +++ b/javalib/src/main/scala/java/util/ListIterator.scala @@ -18,5 +18,6 @@ trait ListIterator[E] extends Iterator[E] { def previous(): E def previousIndex(): Int def nextIndex(): Int + def remove(): Unit def set(e: E): Unit } diff --git a/javalib/src/main/scala/java/util/Map.scala b/javalib/src/main/scala/java/util/Map.scala index 8d02265fd0..260bd05a92 100644 --- a/javalib/src/main/scala/java/util/Map.scala +++ b/javalib/src/main/scala/java/util/Map.scala @@ -12,6 +12,12 @@ package java.util +import java.util.function.{BiConsumer, BiFunction, Function} + +import scala.scalajs.js.annotation.JavaDefaultMethod + +import ScalaOps._ + trait Map[K, V] { def size(): Int def isEmpty(): Boolean @@ -27,6 +33,122 @@ trait Map[K, V] { def entrySet(): Set[Map.Entry[K, V]] def equals(o: Any): Boolean def hashCode(): Int + + @JavaDefaultMethod + def getOrDefault(key: Any, defaultValue: V): V = + if (containsKey(key)) get(key) + else defaultValue + + @JavaDefaultMethod + def forEach(action: BiConsumer[_ >: K, _ >: V]): Unit = { + for (entry <- entrySet().scalaOps) + action.accept(entry.getKey(), entry.getValue()) + } + + @JavaDefaultMethod + def replaceAll(function: BiFunction[_ >: K, _ >: V, _ <: V]): Unit = { + for (entry <- entrySet().scalaOps) + entry.setValue(function.apply(entry.getKey(), entry.getValue())) + } + + @JavaDefaultMethod + def putIfAbsent(key: K, value: V): V = { + val prevValue = get(key) + if (prevValue == null) + put(key, value) // will return null + else + prevValue + } + + @JavaDefaultMethod + def remove(key: Any, value: Any): Boolean = { + if (containsKey(key) && Objects.equals(get(key), value)) { + remove(key) + true + } else { + false + } + } + + @JavaDefaultMethod + def replace(key: K, oldValue: V, newValue: V): Boolean = { + if (containsKey(key) && Objects.equals(get(key), oldValue)) { + put(key, newValue) + true + } else { + false + } + } + + @JavaDefaultMethod + def replace(key: K, value: V): V = + if (containsKey(key)) put(key, value) + else null.asInstanceOf[V] + + @JavaDefaultMethod + def computeIfAbsent(key: K, mappingFunction: Function[_ >: K, _ <: V]): V = { + val oldValue = get(key) + if (oldValue != null) { + oldValue + } else { + val newValue = mappingFunction.apply(key) + if (newValue != null) + put(key, newValue) + newValue + } + } + + @JavaDefaultMethod + def computeIfPresent(key: K, remappingFunction: BiFunction[_ >: K, _ >: V, _ <: V]): V = { + val oldValue = get(key) + if (oldValue == null) { + oldValue + } else { + val newValue = remappingFunction.apply(key, oldValue) + putOrRemove(key, newValue) + newValue + } + } + + @JavaDefaultMethod + def compute(key: K, remappingFunction: BiFunction[_ >: K, _ >: V, _ <: V]): V = { + val oldValue = get(key) + val newValue = remappingFunction.apply(key, oldValue) + + /* The "Implementation Requirements" section of the JavaDoc for this method + * does not correspond to the textual specification in the case where both + * a) there was a null mapping, and + * b) the remapping function returned null. + * + * The Implementation Requirements would leave the null mapping, whereas + * the specification says to remove it. + * + * We implement the specification, as it appears that the actual Map + * implementations on the JVM behave like the spec. + */ + putOrRemove(key, newValue) + + newValue + } + + @JavaDefaultMethod + def merge(key: K, value: V, remappingFunction: BiFunction[_ >: V, _ >: V, _ <: V]): V = { + Objects.requireNonNull(value) + + val oldValue = get(key) + val newValue = + if (oldValue == null) value + else remappingFunction.apply(oldValue, value) + putOrRemove(key, newValue) + newValue + } + + private def putOrRemove(key: K, value: V): Unit = { + if (value != null) + put(key, value) + else + remove(key) + } } object Map { diff --git a/javalib/src/main/scala/java/util/NullRejectingHashMap.scala b/javalib/src/main/scala/java/util/NullRejectingHashMap.scala index 786a44a7d3..d10c1fb326 100644 --- a/javalib/src/main/scala/java/util/NullRejectingHashMap.scala +++ b/javalib/src/main/scala/java/util/NullRejectingHashMap.scala @@ -19,7 +19,7 @@ package java.util * their specifications. */ private[util] class NullRejectingHashMap[K, V]( - initialCapacity: Int, loadFactor: Double) + initialCapacity: Int, loadFactor: Float) extends HashMap[K, V](initialCapacity, loadFactor) { def this() = @@ -57,6 +57,15 @@ private[util] class NullRejectingHashMap[K, V]( super.put(key, value) } + override def putIfAbsent(key: K, value: V): V = { + if (value == null) + throw new NullPointerException() + val old = get(key) // throws if `key` is null + if (old == null) + super.put(key, value) + old + } + @noinline override def putAll(m: Map[_ <: K, _ <: V]): Unit = { /* The only purpose of `impl` is to capture the wildcards as named types, @@ -80,6 +89,37 @@ private[util] class NullRejectingHashMap[K, V]( super.remove(key) } + override def remove(key: Any, value: Any): Boolean = { + val old = get(key) // throws if `key` is null + if (old != null && old.equals(value)) { // false if `value` is null + super.remove(key) + true + } else { + false + } + } + + override def replace(key: K, oldValue: V, newValue: V): Boolean = { + if (oldValue == null || newValue == null) + throw new NullPointerException() + val old = get(key) // throws if `key` is null + if (oldValue.equals(old)) { // false if `old` is null + super.put(key, newValue) + true + } else { + false + } + } + + override def replace(key: K, value: V): V = { + if (value == null) + throw new NullPointerException() + val old = get(key) // throws if `key` is null + if (old != null) + super.put(key, value) + old + } + override def containsValue(value: Any): Boolean = { if (value == null) throw new NullPointerException() diff --git a/javalib/src/main/scala/java/util/Objects.scala b/javalib/src/main/scala/java/util/Objects.scala index ae960094e1..0f54da6f52 100644 --- a/javalib/src/main/scala/java/util/Objects.scala +++ b/javalib/src/main/scala/java/util/Objects.scala @@ -12,6 +12,8 @@ package java.util +import java.util.function.Supplier + import scala.reflect.ClassTag object Objects { @@ -82,9 +84,8 @@ object Objects { def nonNull(obj: Any): Boolean = obj != null - // Requires the implementation of java.util.function - // @inline - // def requireNonNull[T](obj: T, messageSupplier: Supplier[String]): T = - // if (obj == null) throw new NullPointerException(messageSupplier.get()) - // else obj + @inline + def requireNonNull[T](obj: T, messageSupplier: Supplier[String]): T = + if (obj == null) throw new NullPointerException(messageSupplier.get()) + else obj } diff --git a/javalib/src/main/scala/java/util/Optional.scala b/javalib/src/main/scala/java/util/Optional.scala index c1ca0cd04a..7507c2f93a 100644 --- a/javalib/src/main/scala/java/util/Optional.scala +++ b/javalib/src/main/scala/java/util/Optional.scala @@ -12,7 +12,10 @@ package java.util +import java.util.function._ + final class Optional[T] private (value: T) { + import Optional._ def get(): T = { if (!isPresent()) @@ -21,20 +24,53 @@ final class Optional[T] private (value: T) { value } - def isPresent(): Boolean = value != null + @inline def isPresent(): Boolean = value != null - //def ifPresent(consumer: Consumer[_ >: T]): Unit - //def filter(predicate: Predicate[_ >: T]): Optional[U] - //def map[U](mapper: Function[_ >: T, _ <: U]): Optional[U] - //def flatMap[U](mapper: Function[_ >: T, Optional[U]]): Optional[U] + @inline def isEmpty(): Boolean = value == null - def orElse(other: T): T = { - if (isPresent) value - else other + def ifPresent(action: Consumer[_ >: T]): Unit = { + if (isPresent()) + action.accept(value) + } + + def ifPresentOrElse(action: Consumer[_ >: T], emptyAction: Runnable): Unit = { + if (isPresent()) + action.accept(value) + else + emptyAction.run() } - //def orElseGet(other: Supplier[_ <: T]): T - //def orElseThrow[X](exceptionSupplier: Supplier[_ <: X]): T + def filter(predicate: Predicate[_ >: T]): Optional[T] = + if (isEmpty() || predicate.test(value)) this + else Optional.empty() + + def map[U](mapper: Function[_ >: T, _ <: U]): Optional[U] = + if (isEmpty()) emptyCast[U](this) + else Optional.ofNullable(mapper(value)) + + def flatMap[U](mapper: Function[_ >: T, Optional[_ <: U]]): Optional[U] = + if (isEmpty()) emptyCast[U](this) + else upcast[U](mapper(value)) + + def or(supplier: Supplier[_ <: Optional[_ <: T]]): Optional[T] = + if (isPresent()) this + else upcast[T](supplier.get()) + + def orElse(other: T): T = + if (isPresent()) value + else other + + def orElseGet(supplier: Supplier[_ <: T]): T = + if (isPresent()) value + else supplier.get() + + def orElseThrow(): T = + if (isPresent()) value + else throw new NoSuchElementException() + + def orElseThrow[X <: Throwable](exceptionSupplier: Supplier[_ <: X]): T = + if (isPresent()) value + else throw exceptionSupplier.get() override def equals(obj: Any): Boolean = { obj match { @@ -67,4 +103,12 @@ object Optional { } def ofNullable[T](value: T): Optional[T] = new Optional[T](value) + + @inline + private def upcast[T](optional: Optional[_ <: T]): Optional[T] = + optional.asInstanceOf[Optional[T]] + + @inline + private def emptyCast[T](empty: Optional[_]): Optional[T] = + empty.asInstanceOf[Optional[T]] } diff --git a/javalib/src/main/scala/java/util/PriorityQueue.scala b/javalib/src/main/scala/java/util/PriorityQueue.scala index 9de0a50ccc..9fc348472f 100644 --- a/javalib/src/main/scala/java/util/PriorityQueue.scala +++ b/javalib/src/main/scala/java/util/PriorityQueue.scala @@ -103,23 +103,9 @@ class PriorityQueue[E] private ( private def removeExact(o: Any): Unit = { val len = inner.length var i = 1 - - /* This is tricky. We must use reference equality to find the exact object - * to remove, but if `o` is a positive or negative 0.0 or NaN, we must use - * `equals` to delete the correct element (i.e., not confuse +0.0 and -0.0, - * and considering `NaN` equal to itself). - */ - o match { - case o: Double if o == 0.0 || java.lang.Double.isNaN(o) => - while (i != len && !o.equals(inner(i))) { - i += 1 - } - case _ => - while (i != len && (o.asInstanceOf[AnyRef] ne inner(i).asInstanceOf[AnyRef])) { - i += 1 - } + while (i != len && (o.asInstanceOf[AnyRef] ne inner(i).asInstanceOf[AnyRef])) { + i += 1 } - if (i == len) throw new ConcurrentModificationException() removeAt(i) @@ -165,7 +151,7 @@ class PriorityQueue[E] private ( last } - def remove(): Unit = { + override def remove(): Unit = { /* Once we start removing elements, the inner array of the enclosing * PriorityQueue will be modified in arbitrary ways. In particular, * entries yet to be iterated can be moved before `nextIdx` if the diff --git a/javalib/src/main/scala/java/util/Properties.scala b/javalib/src/main/scala/java/util/Properties.scala index baf1b8f11d..d75d89e601 100644 --- a/javalib/src/main/scala/java/util/Properties.scala +++ b/javalib/src/main/scala/java/util/Properties.scala @@ -12,9 +12,13 @@ package java.util +import scala.annotation.switch import scala.annotation.tailrec +import java.{lang => jl} import java.{util => ju} +import java.io._ +import java.nio.charset.StandardCharsets import scala.scalajs.js @@ -28,11 +32,46 @@ class Properties(protected val defaults: Properties) def setProperty(key: String, value: String): AnyRef = put(key, value) - // def load(reader: Reader): Unit - // def load(inStream: InputStream): Unit - // @deprecated("", "") def save(out: OutputStream, comments: String): Unit - // def store(writer: Writer, comments: String): Unit - // def store(out: OutputStream, comments: String): Unit + def load(reader: Reader): Unit = + loadImpl(reader) + + def load(inStream: InputStream): Unit = { + loadImpl(new InputStreamReader(inStream, StandardCharsets.ISO_8859_1)) + } + + @Deprecated + def save(out: OutputStream, comments: String): Unit = + store(out, comments) + + def store(writer: Writer, comments: String): Unit = + storeImpl(writer, comments, toHex = false) + + def store(out: OutputStream, comments: String): Unit = { + val writer = new OutputStreamWriter(out, StandardCharsets.ISO_8859_1) + storeImpl(writer, comments, toHex = true) + } + + private def storeImpl(writer: Writer, comments: String, + toHex: Boolean): Unit = { + if (comments != null) { + writeComments(writer, comments, toHex) + } + + writer.write('#') + writer.write(new Date().toString) + writer.write(System.lineSeparator()) + + entrySet().scalaOps.foreach { entry => + writer.write(encodeString(entry.getKey().asInstanceOf[String], + isKey = true, toHex)) + writer.write('=') + writer.write(encodeString(entry.getValue().asInstanceOf[String], + isKey = false, toHex)) + writer.write(System.lineSeparator()) + } + writer.flush() + } + // def loadFromXML(in: InputStream): Unit // def storeToXML(os: OutputStream, comment: String): Unit // def storeToXML(os: OutputStream, comment: String, encoding: String): Unit @@ -65,7 +104,7 @@ class Properties(protected val defaults: Properties) val set = new ju.HashSet[String] foreachAncestor { ancestor => ancestor.entrySet().scalaOps.foreach { entry => - (entry.getKey, entry.getValue) match { + (entry.getKey(), entry.getValue()) match { case (key: String, _: String) => set.add(key) case _ => // Ignore key } @@ -81,6 +120,263 @@ class Properties(protected val defaults: Properties) defaults.foreachAncestor(f) } - // def list(out: PrintStream): Unit - // def list(out: PrintWriter): Unit + private final val listStr = "-- listing properties --" + + private def format(entry: ju.Map.Entry[AnyRef, AnyRef]): String = { + def format(s: String): String = + if (s.length > 40) s"${s.substring(0, 37)}..." else s + + val key: String = entry.getKey().asInstanceOf[String] + val value: String = entry.getValue().asInstanceOf[String] + + s"${key}=${format(value)}" + } + + def list(out: PrintStream): Unit = { + out.println(listStr) + entrySet().scalaOps.foreach { entry => out.println(format(entry)) } + } + + def list(out: PrintWriter): Unit = { + out.println(listStr) + entrySet().scalaOps.foreach { entry => out.println(format(entry)) } + } + + private def loadImpl(reader: Reader): Unit = { + val br = new BufferedReader(reader) + val valBuf = new jl.StringBuilder() + var prevValueContinue = false + var isKeyParsed = false + var key: String = null + var line: String = null + + while ({ line = br.readLine(); line != null }) { + var i: Int = -1 + var ch: Char = Char.MinValue + + def getNextChar(): Char = { + i += 1 + // avoid out of bounds if value is empty + if (i < line.length()) + line.charAt(i) + else + ch + } + + def parseUnicodeEscape(): Char = { + val hexStr = line.substring(i, i + 4) + // don't advance past the last char used + i += 3 + Integer.parseInt(hexStr, 16).toChar + } + + def isWhitespace(char: Char): Boolean = + char == ' ' || char == '\t' || char == '\f' + + def isTokenKeySeparator(char: Char): Boolean = + char == '=' || char == ':' + + def isKeySeparator(char: Char): Boolean = + isTokenKeySeparator(char) || isWhitespace(char) + + def isEmpty(): Boolean = + line.isEmpty() + + def isComment(): Boolean = + line.startsWith("#") || line.startsWith("!") + + def oddBackslash(): Boolean = { + var i = line.length() + while (i > 0 && line.charAt(i - 1) == '\\') + i -= 1 + (line.length() - i) % 2 != 0 + } + + def valueContinues(): Boolean = oddBackslash() + + def processChar(buf: jl.StringBuilder): Unit = + if (ch == '\\') { + ch = getNextChar() + ch match { + case 'u' => + getNextChar() // advance + val uch = parseUnicodeEscape() + buf.append(uch) + case 't' => buf.append('\t') + case 'f' => buf.append('\f') + case 'r' => buf.append('\r') + case 'n' => buf.append('\n') + case _ => buf.append(ch) + } + } else { + buf.append(ch) + } + + def parseKey(): String = { + val buf = new jl.StringBuilder() + // ignore leading whitespace + while (i < line.length && isWhitespace(ch)) { + ch = getNextChar() + } + // key sep or empty value + while (!isKeySeparator(ch) && i < line.length()) { + processChar(buf) + ch = getNextChar() + } + // ignore trailing whitespace + while (i < line.length && isWhitespace(ch)) { + ch = getNextChar() + } + // ignore non-space key separator + if (i < line.length && isTokenKeySeparator(ch)) { + ch = getNextChar() + } + isKeyParsed = true + buf.toString() + } + + def parseValue(): String = { + // ignore leading whitespace + while (i < line.length && isWhitespace(ch)) { + ch = getNextChar() + } + + // nothing but line continuation + if (valueContinues() && i == line.length() - 1) { + // ignore the final backslash + ch = getNextChar() + } + + while (i < line.length) { + if (valueContinues() && i == line.length() - 1) { + // ignore the final backslash + ch = getNextChar() + } else { + processChar(valBuf) + ch = getNextChar() + } + } + valBuf.toString() + } + + // run the parsing + if (!(isComment() || isEmpty())) { + ch = getNextChar() + if (!isKeyParsed) { + valBuf.setLength(0) + key = parseKey() + val value = parseValue() + prevValueContinue = valueContinues() + if (!prevValueContinue) { + setProperty(key, value) + isKeyParsed = false + } + } else if (prevValueContinue && valueContinues()) { + val value = parseValue() + prevValueContinue = valueContinues() + } else { + val value = parseValue() + setProperty(key, value) + isKeyParsed = false + prevValueContinue = false + } + } + } + } + + private def writeComments(writer: Writer, comments: String, + toHex: Boolean): Unit = { + writer.write('#') + val chars = comments.toCharArray + var index = 0 + while (index < chars.length) { + val ch = chars(index) + if (ch <= 0xff) { + if (ch == '\r' || ch == '\n') { + def isCrlf = + ch == '\r' && index + 1 < chars.length && chars(index + 1) == '\n' + + if (isCrlf) { + index += 1 + } + writer.write(System.lineSeparator()) + + def noExplicitComment = { + index + 1 < chars.length && + (chars(index + 1) != '#' && chars(index + 1) != '!') + } + + if (noExplicitComment) { + writer.write('#') + } + } else { + writer.write(ch) + } + } else { + if (toHex) { + writer.write(unicodeToHexaDecimal(ch)) + } else { + writer.write(ch) + } + } + index += 1 + } + writer.write(System.lineSeparator()) + } + + private def encodeString(string: String, isKey: Boolean, + toHex: Boolean): String = { + val buffer = new jl.StringBuilder(200) + var index = 0 + val length = string.length + // leading element (value) spaces are escaped + if (!isKey) { + while (index < length && string.charAt(index) == ' ') { + buffer.append("\\ ") + index += 1 + } + } + + while (index < length) { + val ch = string.charAt(index) + (ch: @switch) match { + case '\t' => + buffer.append("\\t") + case '\n' => + buffer.append("\\n") + case '\f' => + buffer.append("\\f") + case '\r' => + buffer.append("\\r") + case '\\' | '#' | '!' | '=' | ':' => + buffer.append('\\') + buffer.append(ch) + case ' ' if isKey => + buffer.append("\\ ") + case _ => + if (toHex && (ch < 0x20 || ch > 0x7e)) { + buffer.append(unicodeToHexaDecimal(ch)) + } else { + buffer.append(ch) + } + } + index += 1 + } + buffer.toString() + } + + private def unicodeToHexaDecimal(ch: Int): Array[Char] = { + def hexChar(x: Int): Char = + if (x > 9) (x - 10 + 'A').toChar + else (x + '0').toChar + + Array( + '\\', + 'u', + hexChar((ch >>> 12) & 15), + hexChar((ch >>> 8) & 15), + hexChar((ch >>> 4) & 15), + hexChar(ch & 15) + ) + } } diff --git a/javalib/src/main/scala/java/util/Random.scala b/javalib/src/main/scala/java/util/Random.scala index 1a4a1610ed..a2ae2eb3f6 100644 --- a/javalib/src/main/scala/java/util/Random.scala +++ b/javalib/src/main/scala/java/util/Random.scala @@ -58,8 +58,6 @@ class Random(seed_in: Long) extends AnyRef with java.io.Serializable { // seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1) - val twoPow24 = (1 << 24).toDouble - val oldSeedHi = seedHi val oldSeedLo = seedLo diff --git a/javalib/src/main/scala/java/util/RedBlackTree.scala b/javalib/src/main/scala/java/util/RedBlackTree.scala index ba8d614235..336df6d2c4 100644 --- a/javalib/src/main/scala/java/util/RedBlackTree.scala +++ b/javalib/src/main/scala/java/util/RedBlackTree.scala @@ -134,7 +134,7 @@ private[util] object RedBlackTree { Objects.hashCode(key) ^ Objects.hashCode(value) override def toString(): String = - "" + getKey + "=" + getValue + "" + getKey() + "=" + getValue() @inline private[RedBlackTree] def isRoot: Boolean = parent eq null @@ -495,7 +495,7 @@ private[util] object RedBlackTree { * `node` before deleting `node`. We can do this because we know that * `succ` has a null `left` child. * - * In fact we transplant the `onlyChildOfSucc` (orignally at + * In fact we transplant the `onlyChildOfSucc` (originally at * `succ.right`) in place of `succ`, then transplant `succ` in place of * `node` (also acquiring its color), and finally fixing up the tree * around `onlyChildOfSucc`. @@ -748,7 +748,7 @@ private[util] object RedBlackTree { nextResult(node) } - def remove(): Unit = { + override def remove(): Unit = { val node = lastNode if (node eq null) throw new IllegalStateException() diff --git a/javalib/src/main/scala/java/util/ScalaOps.scala b/javalib/src/main/scala/java/util/ScalaOps.scala index 4362f77fa8..32023f2ab7 100644 --- a/javalib/src/main/scala/java/util/ScalaOps.scala +++ b/javalib/src/main/scala/java/util/ScalaOps.scala @@ -18,6 +18,9 @@ private[java] object ScalaOps { implicit class IntScalaOps private[ScalaOps] (val __self: Int) extends AnyVal { @inline def until(end: Int): SimpleRange = new SimpleRange(__self, end) + + @inline def to(end: Int): SimpleInclusiveRange = + new SimpleInclusiveRange(__self, end) } @inline @@ -32,6 +35,18 @@ private[java] object ScalaOps { } } + @inline + final class SimpleInclusiveRange(start: Int, end: Int) { + @inline + def foreach[U](f: Int => U): Unit = { + var i = start + while (i <= end) { + f(i) + i += 1 + } + } + } + implicit class ToJavaIterableOps[A] private[ScalaOps] ( val __self: java.lang.Iterable[A]) extends AnyVal { @@ -57,8 +72,8 @@ private[java] object ScalaOps { @inline def indexWhere(f: A => Boolean): Int = __self.iterator().scalaOps.indexWhere(f) - @inline def find(f: A => Boolean): Option[A] = - __self.iterator().scalaOps.find(f) + @inline def findFold[B](f: A => Boolean)(default: => B)(g: A => B): B = + __self.iterator().scalaOps.findFold(f)(default)(g) @inline def foldLeft[B](z: B)(f: (B, A) => B): B = __self.iterator().scalaOps.foldLeft(z)(f) @@ -112,14 +127,14 @@ private[java] object ScalaOps { // scalastyle:on return } - @inline def find(f: A => Boolean): Option[A] = { + @inline def findFold[B](f: A => Boolean)(default: => B)(g: A => B): B = { // scalastyle:off return while (__self.hasNext()) { val x = __self.next() if (f(x)) - return Some(x) + return g(x) } - None + default // scalastyle:on return } diff --git a/javalib/src/main/scala/java/util/SplittableRandom.scala b/javalib/src/main/scala/java/util/SplittableRandom.scala index 3713eb8807..9d394b909c 100644 --- a/javalib/src/main/scala/java/util/SplittableRandom.scala +++ b/javalib/src/main/scala/java/util/SplittableRandom.scala @@ -127,6 +127,6 @@ final class SplittableRandom private (private var seed: Long, gamma: Long) { // this should be properly tested // looks to work but just by chance maybe - def nextBoolean(): Boolean = nextInt < 0 + def nextBoolean(): Boolean = nextInt() < 0 } diff --git a/javalib/src/main/scala/java/util/StringTokenizer.scala b/javalib/src/main/scala/java/util/StringTokenizer.scala new file mode 100644 index 0000000000..9cf13dd76f --- /dev/null +++ b/javalib/src/main/scala/java/util/StringTokenizer.scala @@ -0,0 +1,111 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util + +class StringTokenizer( + str: String, + private var delim: String, + returnDelims: Boolean +) extends java.util.Enumeration[Object] { + + def this(str: String) = this(str, " \t\n\r\f", false) + def this(str: String, delim: String) = this(str, delim, false) + + private var position: Int = 0 + private val length: Int = str.length + + def hasMoreTokens(): Boolean = { + position < length && (returnDelims || !remainingAreDelims()) + } + + def nextToken(): String = { + @inline def nextIsDelim: Boolean = isDelim(currentChar) + @inline def currentChar: Char = str.charAt(position) + + ensureAvailable() + + if (returnDelims && nextIsDelim) { + val ret = String.valueOf(currentChar) + position += 1 + ret + } else { + // Skip consecutive delims + while (position < length && nextIsDelim) + position += 1 + + ensureAvailable() + + val start = position + while (position < length && !nextIsDelim) + position += 1 + str.substring(start, position) + } + } + + def nextToken(delim: String): String = { + this.delim = delim + nextToken() + } + + def hasMoreElements(): Boolean = hasMoreTokens() + + def nextElement(): Object = nextToken() + + def countTokens(): Int = { + var count = 0 + var inToken = false + var i = position + + while (i < length) { + if (isDelim(str.charAt(i))) { + if (returnDelims) + count += 1 + + if (inToken) { + count += 1 + inToken = false + } + } else { + inToken = true + } + + i += 1 + } + + if (inToken) + count += 1 + + count + } + + private def ensureAvailable(): Unit = { + if (position >= length) + throw new NoSuchElementException() + } + + @inline private def isDelim(ch: Char): Boolean = delim.indexOf(ch, 0) >= 0 + + private def remainingAreDelims(): Boolean = { + var i = position + var restAreDelims = true + + while (i < length && restAreDelims) { + if (!isDelim(str.charAt(i))) + restAreDelims = false + i += 1 + } + + restAreDelims + } +} + diff --git a/javalib/src/main/scala/java/util/Throwables.scala b/javalib/src/main/scala/java/util/Throwables.scala index 44582c9ecd..f5535afc7b 100644 --- a/javalib/src/main/scala/java/util/Throwables.scala +++ b/javalib/src/main/scala/java/util/Throwables.scala @@ -80,6 +80,12 @@ class IllegalFormatWidthException(w: Int) extends IllegalFormatException { override def getMessage(): String = Integer.toString(w) } +// See https://bugs.openjdk.java.net/browse/JDK-8253875 +private[util] class IllegalFormatArgumentIndexException(msg: String) + extends IllegalFormatException { + override def getMessage(): String = msg +} + class IllformedLocaleException(s: String, errorIndex: Int) extends RuntimeException(s + (if (errorIndex < 0) "" else " [at index " + errorIndex + "]")) { def this() = this(null, -1) diff --git a/javalib/src/main/scala/java/util/Timer.scala b/javalib/src/main/scala/java/util/Timer.scala index fd28fe69d2..b377b5a33f 100644 --- a/javalib/src/main/scala/java/util/Timer.scala +++ b/javalib/src/main/scala/java/util/Timer.scala @@ -12,8 +12,6 @@ package java.util -import scala.concurrent.duration._ - class Timer() { private[util] var canceled: Boolean = false @@ -33,12 +31,12 @@ class Timer() { } private def checkDelay(delay: Long): Unit = { - if (delay < 0 || (delay + System.currentTimeMillis) < 0) + if (delay < 0 || (delay + System.currentTimeMillis()) < 0) throw new IllegalArgumentException("Negative delay.") } private def checkTime(time: Date): Unit = { - if (time.getTime < 0) + if (time.getTime() < 0) throw new IllegalArgumentException(s"Negative time: $time.") } @@ -49,14 +47,14 @@ class Timer() { private def scheduleOnce(task: TimerTask, delay: Long): Unit = { acquire(task) - task.timeout(delay.millis) { + task.timeout(delay) { task.scheduledOnceAndStarted = true task.doRun() } } private def getMillisUntil(time: Date): Long = - math.max(0L, time.getTime - System.currentTimeMillis()) + Math.max(0L, time.getTime() - System.currentTimeMillis()) def schedule(task: TimerTask, delay: Long): Unit = { checkDelay(delay) @@ -72,16 +70,18 @@ class Timer() { private def schedulePeriodically( task: TimerTask, delay: Long, period: Long): Unit = { acquire(task) - task.timeout(delay.millis) { - def loop(): Unit = { - val startTime = System.nanoTime() - task.doRun() - val endTime = System.nanoTime() - val duration = (endTime - startTime) / 1000000 - task.timeout((period - duration).millis) { - loop() - } + + def loop(): Unit = { + val startTime = System.nanoTime() + task.doRun() + val endTime = System.nanoTime() + val duration = (endTime - startTime) / 1000000 + task.timeout(period - duration) { + loop() } + } + + task.timeout(delay) { loop() } } @@ -102,22 +102,24 @@ class Timer() { private def scheduleFixed( task: TimerTask, delay: Long, period: Long): Unit = { acquire(task) - task.timeout(delay.millis) { - def loop(scheduledTime: Long): Unit = { - task.doRun() - val nextScheduledTime = scheduledTime + period - val nowTime = System.nanoTime / 1000000L - if (nowTime >= nextScheduledTime) { - // Re-run immediately. + + def loop(scheduledTime: Long): Unit = { + task.doRun() + val nextScheduledTime = scheduledTime + period + val nowTime = System.nanoTime() / 1000000L + if (nowTime >= nextScheduledTime) { + // Re-run immediately. + loop(nextScheduledTime) + } else { + // Re-run after a timeout. + task.timeout(nextScheduledTime - nowTime) { loop(nextScheduledTime) - } else { - // Re-run after a timeout. - task.timeout((nextScheduledTime - nowTime).millis) { - loop(nextScheduledTime) - } } } - loop(System.nanoTime / 1000000L + period) + } + + task.timeout(delay) { + loop(System.nanoTime() / 1000000L + period) } } diff --git a/javalib/src/main/scala/java/util/TimerTask.scala b/javalib/src/main/scala/java/util/TimerTask.scala index c775afa4fe..4299157e89 100644 --- a/javalib/src/main/scala/java/util/TimerTask.scala +++ b/javalib/src/main/scala/java/util/TimerTask.scala @@ -12,8 +12,8 @@ package java.util -import scala.concurrent.duration.FiniteDuration -import scala.scalajs.js.timers._ +import scala.scalajs.js +import scala.scalajs.js.timers.RawTimers._ import scala.scalajs.js.timers.SetTimeoutHandle abstract class TimerTask { @@ -41,9 +41,9 @@ abstract class TimerTask { def scheduledExecutionTime(): Long = lastScheduled - private[util] def timeout(delay: FiniteDuration)(body: => Unit): Unit = { + private[util] def timeout(delay: Long)(body: => Unit): Unit = { if (!canceled) { - handle = setTimeout(delay)(body) + handle = setTimeout(() => body, delay.toDouble) } } diff --git a/javalib/src/main/scala/java/util/TreeSet.scala b/javalib/src/main/scala/java/util/TreeSet.scala index 723e8ed2d4..5a5924dbf1 100644 --- a/javalib/src/main/scala/java/util/TreeSet.scala +++ b/javalib/src/main/scala/java/util/TreeSet.scala @@ -12,6 +12,7 @@ package java.util +import java.lang.Cloneable import java.util.{RedBlackTree => RB} class TreeSet[E] private (tree: RB.Tree[E, Any])( diff --git a/javalib/src/main/scala/java/util/UUID.scala b/javalib/src/main/scala/java/util/UUID.scala index 9daedcd2b9..bc8d02f782 100644 --- a/javalib/src/main/scala/java/util/UUID.scala +++ b/javalib/src/main/scala/java/util/UUID.scala @@ -47,13 +47,13 @@ final class UUID private ( def getLeastSignificantBits(): Long = { if (l2 eq null) l2 = JLong.valueOf((i3.toLong << 32) | (i4.toLong & 0xffffffffL)) - l2.longValue + l2.longValue() } def getMostSignificantBits(): Long = { if (l1 eq null) l1 = JLong.valueOf((i1.toLong << 32) | (i2.toLong & 0xffffffffL)) - l1.longValue + l1.longValue() } def version(): Int = @@ -136,13 +136,26 @@ object UUID { private final val NameBased = 3 private final val Random = 4 - private lazy val rng = new Random() // TODO Use java.security.SecureRandom + // Typed as `Random` so that the IR typechecks when SecureRandom is not available + private lazy val csprng: Random = new java.security.SecureRandom() + private lazy val randomUUIDBuffer: Array[Byte] = new Array[Byte](16) def randomUUID(): UUID = { - val i1 = rng.nextInt() - val i2 = (rng.nextInt() & ~0x0000f000) | 0x00004000 - val i3 = (rng.nextInt() & ~0xc0000000) | 0x80000000 - val i4 = rng.nextInt() + val buffer = randomUUIDBuffer // local copy + + /* We use nextBytes() because that is the primitive of most secure RNGs, + * and therefore it allows to perform a unique call to the underlying + * secure RNG. + */ + csprng.nextBytes(randomUUIDBuffer) + + @inline def intFromBuffer(i: Int): Int = + (buffer(i) << 24) | ((buffer(i + 1) & 0xff) << 16) | ((buffer(i + 2) & 0xff) << 8) | (buffer(i + 3) & 0xff) + + val i1 = intFromBuffer(0) + val i2 = (intFromBuffer(4) & ~0x0000f000) | 0x00004000 + val i3 = (intFromBuffer(8) & ~0xc0000000) | 0x80000000 + val i4 = intFromBuffer(12) new UUID(i1, i2, i3, i4, null, null) } diff --git a/javalib/src/main/scala/java/util/concurrent/ConcurrentHashMap.scala b/javalib/src/main/scala/java/util/concurrent/ConcurrentHashMap.scala index 787408406c..29847a2acb 100644 --- a/javalib/src/main/scala/java/util/concurrent/ConcurrentHashMap.scala +++ b/javalib/src/main/scala/java/util/concurrent/ConcurrentHashMap.scala @@ -61,8 +61,16 @@ class ConcurrentHashMap[K, V] private (initialCapacity: Int, loadFactor: Float) override def clear(): Unit = inner.clear() - override def keySet(): ConcurrentHashMap.KeySetView[K, V] = - new ConcurrentHashMap.KeySetView[K, V](inner.keySet()) + override def keySet(): ConcurrentHashMap.KeySetView[K, V] = { + // Allow null as sentinel + new ConcurrentHashMap.KeySetView[K, V](this.inner, null.asInstanceOf[V]) + } + + def keySet(mappedValue: V): ConcurrentHashMap.KeySetView[K, V] = { + if (mappedValue == null) + throw new NullPointerException() + new ConcurrentHashMap.KeySetView[K, V](this.inner, mappedValue) + } override def values(): Collection[V] = inner.values() @@ -79,47 +87,17 @@ class ConcurrentHashMap[K, V] private (initialCapacity: Int, loadFactor: Float) override def equals(o: Any): Boolean = inner.equals(o) - def putIfAbsent(key: K, value: V): V = { - if (value == null) - throw new NullPointerException() - val old = inner.get(key) // throws if `key` is null - if (old == null) - inner.put(key, value) - old - } + override def putIfAbsent(key: K, value: V): V = + inner.putIfAbsent(key, value) - def remove(key: Any, value: Any): Boolean = { - if (value == null) - throw new NullPointerException() - val old = inner.get(key) // throws if `key` is null - if (value.equals(old)) { // false if `old` is null - inner.remove(key) - true - } else { - false - } - } + override def remove(key: Any, value: Any): Boolean = + inner.remove(key, value) - override def replace(key: K, oldValue: V, newValue: V): Boolean = { - if (oldValue == null || newValue == null) - throw new NullPointerException() - val old = inner.get(key) // throws if `key` is null - if (oldValue.equals(old)) { // false if `old` is null - inner.put(key, newValue) - true - } else { - false - } - } + override def replace(key: K, oldValue: V, newValue: V): Boolean = + inner.replace(key, oldValue, newValue) - override def replace(key: K, value: V): V = { - if (value == null) - throw new NullPointerException() - val old = inner.get(key) // throws if `key` is null - if (old != null) - inner.put(key, value) - old - } + override def replace(key: K, value: V): V = + inner.replace(key, value) def contains(value: Any): Boolean = containsValue(value) @@ -190,7 +168,7 @@ object ConcurrentHashMap { extract(node) } - def remove(): Unit = { + override def remove(): Unit = { val last = lastNode if (last eq null) throw new IllegalStateException("next must be called at least once before remove") @@ -200,39 +178,58 @@ object ConcurrentHashMap { } } - /* `KeySetView` is a public class in the JDK API. The result of - * `ConcurrentHashMap.keySet()` must be statically typed as a `KeySetView`, - * hence the existence of this class, although it forwards all its operations - * to the inner key set. - */ - class KeySetView[K, V] private[ConcurrentHashMap] (inner: Set[K]) + class KeySetView[K, V] private[ConcurrentHashMap] (innerMap: InnerHashMap[K, V], defaultValue: V) extends Set[K] with Serializable { - def contains(o: Any): Boolean = inner.contains(o) + def getMappedValue(): V = defaultValue - def remove(o: Any): Boolean = inner.remove(o) + def contains(o: Any): Boolean = innerMap.containsKey(o) - def iterator(): Iterator[K] = inner.iterator() + def remove(o: Any): Boolean = innerMap.remove(o) != null - def size(): Int = inner.size() + def iterator(): Iterator[K] = innerMap.keySet().iterator() - def isEmpty(): Boolean = inner.isEmpty() + def size(): Int = innerMap.size() - def toArray(): Array[AnyRef] = inner.toArray() + def isEmpty(): Boolean = innerMap.isEmpty() - def toArray[T <: AnyRef](a: Array[T]): Array[T] = inner.toArray[T](a) + def toArray(): Array[AnyRef] = innerMap.keySet().toArray() + + def toArray[T <: AnyRef](a: Array[T]): Array[T] = innerMap.keySet().toArray(a) + + def add(e: K): Boolean = { + if (defaultValue == null) { + throw new UnsupportedOperationException() + } + innerMap.putIfAbsent(e, defaultValue) == null + } - def add(e: K): Boolean = inner.add(e) + override def toString(): String = innerMap.keySet().toString - def containsAll(c: Collection[_]): Boolean = inner.containsAll(c) + def containsAll(c: Collection[_]): Boolean = innerMap.keySet().containsAll(c) - def addAll(c: Collection[_ <: K]): Boolean = inner.addAll(c) + def addAll(c: Collection[_ <: K]): Boolean = { + if (defaultValue == null) { + throw new UnsupportedOperationException() + } + val iter = c.iterator() + var changed = false + while (iter.hasNext()) + changed = innerMap.putIfAbsent(iter.next(), defaultValue) == null || changed + changed + } - def removeAll(c: Collection[_]): Boolean = inner.removeAll(c) + def removeAll(c: Collection[_]): Boolean = innerMap.keySet().removeAll(c) - def retainAll(c: Collection[_]): Boolean = inner.retainAll(c) + def retainAll(c: Collection[_]): Boolean = innerMap.keySet().retainAll(c) - def clear(): Unit = inner.clear() + def clear(): Unit = innerMap.clear() } + def newKeySet[K](): KeySetView[K, Boolean] = newKeySet[K](HashMap.DEFAULT_INITIAL_CAPACITY) + + def newKeySet[K](initialCapacity: Int): KeySetView[K, Boolean] = { + val inner = new InnerHashMap[K, Boolean](initialCapacity, HashMap.DEFAULT_LOAD_FACTOR) + new KeySetView[K, Boolean](inner, true) + } } diff --git a/javalib/src/main/scala/java/util/concurrent/ConcurrentLinkedQueue.scala b/javalib/src/main/scala/java/util/concurrent/ConcurrentLinkedQueue.scala index 15790d1764..b05b3e92f2 100644 --- a/javalib/src/main/scala/java/util/concurrent/ConcurrentLinkedQueue.scala +++ b/javalib/src/main/scala/java/util/concurrent/ConcurrentLinkedQueue.scala @@ -143,7 +143,7 @@ class ConcurrentLinkedQueue[E]() lastNode.value.value } - def remove(): Unit = { + override def remove(): Unit = { if (lastNode eq null) throw new IllegalStateException() diff --git a/javalib/src/main/scala/java/util/concurrent/ConcurrentSkipListSet.scala b/javalib/src/main/scala/java/util/concurrent/ConcurrentSkipListSet.scala index c668e577c4..5aee358012 100644 --- a/javalib/src/main/scala/java/util/concurrent/ConcurrentSkipListSet.scala +++ b/javalib/src/main/scala/java/util/concurrent/ConcurrentSkipListSet.scala @@ -12,6 +12,7 @@ package java.util.concurrent +import java.lang.Cloneable import java.util._ class ConcurrentSkipListSet[E] private (inner: TreeSet[E]) @@ -36,10 +37,10 @@ class ConcurrentSkipListSet[E] private (inner: TreeSet[E]) new ConcurrentSkipListSet(this) def size(): Int = - inner.size + inner.size() override def isEmpty(): Boolean = - inner.isEmpty + inner.isEmpty() override def contains(o: Any): Boolean = if (o == null) false @@ -87,10 +88,10 @@ class ConcurrentSkipListSet[E] private (inner: TreeSet[E]) inner.comparator() def first(): E = - inner.first + inner.first() def last(): E = - inner.last + inner.last() def subSet(fromElement: E, fromInclusive: Boolean, toElement: E, toInclusive: Boolean): NavigableSet[E] = diff --git a/javalib/src/main/scala/java/util/concurrent/CopyOnWriteArrayList.scala b/javalib/src/main/scala/java/util/concurrent/CopyOnWriteArrayList.scala index edecefdfcd..fb8cb030a5 100644 --- a/javalib/src/main/scala/java/util/concurrent/CopyOnWriteArrayList.scala +++ b/javalib/src/main/scala/java/util/concurrent/CopyOnWriteArrayList.scala @@ -12,9 +12,11 @@ package java.util.concurrent +import java.lang.Cloneable +import java.lang.Utils._ import java.lang.{reflect => jlr} import java.util._ -import java.util.function.Predicate +import java.util.function.{Predicate, UnaryOperator} import scala.annotation.tailrec @@ -46,13 +48,13 @@ class CopyOnWriteArrayList[E <: AnyRef] private (private var inner: js.Array[E]) } def size(): Int = - inner.size + inner.length - def isEmpty: Boolean = - size == 0 + def isEmpty(): Boolean = + size() == 0 def contains(o: scala.Any): Boolean = - iterator.scalaOps.exists(Objects.equals(o, _)) + iterator().scalaOps.exists(Objects.equals(o, _)) def indexOf(o: scala.Any): Int = indexOf(o.asInstanceOf[E], 0) @@ -68,30 +70,30 @@ class CopyOnWriteArrayList[E <: AnyRef] private (private var inner: js.Array[E]) def lastIndexOf(e: E, index: Int): Int = { @tailrec def findIndex(iter: ListIterator[E]): Int = { - if (!iter.hasPrevious) -1 - else if (Objects.equals(iter.previous(), e)) iter.nextIndex + if (!iter.hasPrevious()) -1 + else if (Objects.equals(iter.previous(), e)) iter.nextIndex() else findIndex(iter) } - findIndex(listIterator(size)) + findIndex(listIterator(size())) } override def clone(): AnyRef = new CopyOnWriteArrayList[E](this) def toArray(): Array[AnyRef] = - toArray(new Array[AnyRef](size)) + toArray(new Array[AnyRef](size())) - def toArray[T](a: Array[T]): Array[T] = { - val componentType = a.getClass.getComponentType + def toArray[T <: AnyRef](a: Array[T]): Array[T] = { + val componentType = a.getClass().getComponentType() val toFill: Array[T] = - if (a.length >= size) a - else jlr.Array.newInstance(componentType, size).asInstanceOf[Array[T]] + if (a.length >= size()) a + else jlr.Array.newInstance(componentType, size()).asInstanceOf[Array[T]] - val iter = iterator - for (i <- 0 until size) + val iter = iterator() + for (i <- 0 until size()) toFill(i) = iter.next().asInstanceOf[T] - if (toFill.length > size) - toFill(size) = null.asInstanceOf[T] + if (toFill.length > size()) + toFill(size()) = null.asInstanceOf[T] toFill } @@ -143,7 +145,7 @@ class CopyOnWriteArrayList[E <: AnyRef] private (private var inner: js.Array[E]) } def containsAll(c: Collection[_]): Boolean = - c.iterator.scalaOps.forall(this.contains(_)) + c.iterator().scalaOps.forall(this.contains(_)) def removeAll(c: Collection[_]): Boolean = { copyIfNeeded() @@ -178,13 +180,13 @@ class CopyOnWriteArrayList[E <: AnyRef] private (private var inner: js.Array[E]) } def addAll(c: Collection[_ <: E]): Boolean = - addAll(size, c) + addAll(size(), c) def addAll(index: Int, c: Collection[_ <: E]): Boolean = { checkIndexOnBounds(index) copyIfNeeded() innerInsertMany(index, c) - !c.isEmpty + !c.isEmpty() } /* Override Collection.removeIf() because our iterators do not support @@ -220,6 +222,18 @@ class CopyOnWriteArrayList[E <: AnyRef] private (private var inner: js.Array[E]) // scalastyle:on return } + override def replaceAll(operator: UnaryOperator[E]): Unit = { + val size = this.size() + if (size != 0) { + copyIfNeeded() + var i = 0 + while (i != size) { + innerSet(i, operator.apply(innerGet(i))) + i += 1 + } + } + } + override def toString: String = iterator().scalaOps.mkString("[", ", ", "]") @@ -229,8 +243,8 @@ class CopyOnWriteArrayList[E <: AnyRef] private (private var inner: js.Array[E]) } else { obj match { case obj: List[_] => - val oIter = obj.listIterator - this.scalaOps.forall(elem => oIter.hasNext && Objects.equals(elem, oIter.next())) && !oIter.hasNext + val oIter = obj.listIterator() + this.scalaOps.forall(elem => oIter.hasNext() && Objects.equals(elem, oIter.next())) && !oIter.hasNext() case _ => false } } @@ -250,11 +264,11 @@ class CopyOnWriteArrayList[E <: AnyRef] private (private var inner: js.Array[E]) def listIterator(index: Int): ListIterator[E] = { checkIndexOnBounds(index) - new CopyOnWriteArrayListIterator[E](innerSnapshot(), index, 0, size) + new CopyOnWriteArrayListIterator[E](innerSnapshot(), index, 0, size()) } def subList(fromIndex: Int, toIndex: Int): List[E] = { - if (fromIndex < 0 || fromIndex > toIndex || toIndex > size) + if (fromIndex < 0 || fromIndex > toIndex || toIndex > size()) throw new IndexOutOfBoundsException new CopyOnWriteArrayListView(fromIndex, toIndex) } @@ -278,7 +292,7 @@ class CopyOnWriteArrayList[E <: AnyRef] private (private var inner: js.Array[E]) } protected def innerRemove(index: Int): E = - inner.splice(index, 1)(0) + arrayRemoveAndGet(inner, index) protected def innerRemoveMany(index: Int, count: Int): Unit = inner.splice(index, count) @@ -304,8 +318,8 @@ class CopyOnWriteArrayList[E <: AnyRef] private (private var inner: js.Array[E]) override def clear(): Unit = { copyIfNeeded() - self.innerRemoveMany(fromIndex, size) - changeSize(-size) + self.innerRemoveMany(fromIndex, size()) + changeSize(-size()) } override def listIterator(index: Int): ListIterator[E] = { @@ -317,7 +331,7 @@ class CopyOnWriteArrayList[E <: AnyRef] private (private var inner: js.Array[E]) } override def subList(fromIndex: Int, toIndex: Int): List[E] = { - if (fromIndex < 0 || fromIndex > toIndex || toIndex > size) + if (fromIndex < 0 || fromIndex > toIndex || toIndex > size()) throw new IndexOutOfBoundsException new CopyOnWriteArrayListView(viewSelf.fromIndex + fromIndex, @@ -375,12 +389,12 @@ class CopyOnWriteArrayList[E <: AnyRef] private (private var inner: js.Array[E]) } protected def checkIndexInBounds(index: Int): Unit = { - if (index < 0 || index >= size) + if (index < 0 || index >= size()) throw new IndexOutOfBoundsException(index.toString) } protected def checkIndexOnBounds(index: Int): Unit = { - if (index < 0 || index > size) + if (index < 0 || index > size()) throw new IndexOutOfBoundsException(index.toString) } } diff --git a/javalib/src/main/scala/java/util/concurrent/Semaphore.scala b/javalib/src/main/scala/java/util/concurrent/Semaphore.scala new file mode 100644 index 0000000000..68efab26fe --- /dev/null +++ b/javalib/src/main/scala/java/util/concurrent/Semaphore.scala @@ -0,0 +1,84 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.concurrent + +import java.util.{Collection, Collections} + +class Semaphore(private[this] var permits: Int, fairness: Boolean) extends java.io.Serializable { + + def this(permits: Int) = this(permits, false) + + // These methods can’t be implemented because they block + // def acquire(): Unit + // def acquire(permits: Int): Unit + // def acquireUninterruptibly(): Unit + // def acquireUninterruptibly(permits: Int): Unit + // def tryAcquire(permits: Int, timeout: Long, unit: TimeUnit): Boolean + // def tryAcquire(timeout: Long, unit: TimeUnit): Boolean + + def availablePermits(): Int = permits + + def drainPermits(): Int = { + val old = permits + permits = 0 + old + } + + /* One would expect that the accessor methods delegate to `getQueuedThreads`, + * but that is not the JDK behavior. In the absence of a specification, we + * replicate the JDK behavior. Notably, because the documentation of + * `getQueuedThreads` mentions that it is intended for extensive monitoring, + * not overriding. The fact that the method is not final is hence likely an + * oversight. + */ + + protected def getQueuedThreads(): Collection[Thread] = Collections.emptySet() + + final def getQueueLength(): Int = 0 + + final def hasQueuedThreads(): Boolean = false + + def isFair(): Boolean = fairness + + protected def reducePermits(reduction: Int): Unit = { + requireNonNegative(reduction) + permits -= reduction + } + + def release(): Unit = release(1) + + def release(permits: Int): Unit = { + requireNonNegative(permits) + this.permits += permits + } + + override def toString: String = + s"${super.toString}[Permits = ${permits}]" + + def tryAcquire(): Boolean = tryAcquire(1) + + def tryAcquire(permits: Int): Boolean = { + requireNonNegative(permits) + if (this.permits >= permits) { + this.permits -= permits + true + } else { + false + } + } + + @inline private def requireNonNegative(n: Int): Unit = { + if (n < 0) + throw new IllegalArgumentException + } +} diff --git a/javalib/src/main/scala/java/util/concurrent/TimeUnit.scala b/javalib/src/main/scala/java/util/concurrent/TimeUnit.scala index e1054d84a1..c308bf1b97 100644 --- a/javalib/src/main/scala/java/util/concurrent/TimeUnit.scala +++ b/javalib/src/main/scala/java/util/concurrent/TimeUnit.scala @@ -134,7 +134,7 @@ object TimeUnit { var i = 0 while (i != len) { val value = values(i) - if (value.name == name) + if (value.name() == name) return value i += 1 } diff --git a/javalib/src/main/scala/java/util/concurrent/atomic/LongAdder.scala b/javalib/src/main/scala/java/util/concurrent/atomic/LongAdder.scala new file mode 100644 index 0000000000..1bb246ae8e --- /dev/null +++ b/javalib/src/main/scala/java/util/concurrent/atomic/LongAdder.scala @@ -0,0 +1,55 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.concurrent.atomic + +import java.io.Serializable + +class LongAdder extends Number with Serializable { + private[this] var value: Long = 0L + + final def add(x: Long): Unit = + value = value + x + + final def increment(): Unit = + value = value + 1 + + final def decrement(): Unit = + value = value - 1 + + final def sum(): Long = + value + + final def reset(): Unit = + value = 0 + + final def sumThenReset(): Long = { + val result = value + reset() + result + } + + override def toString(): String = + String.valueOf(value) + + final def longValue(): Long = + value + + final def intValue(): Int = + value.toInt + + final def floatValue(): Float = + value.toFloat + + final def doubleValue(): Double = + value.toDouble +} diff --git a/javalib/src/main/scala/java/util/concurrent/locks/ReentrantLock.scala b/javalib/src/main/scala/java/util/concurrent/locks/ReentrantLock.scala index 3aebcd7d85..c7ae10e413 100644 --- a/javalib/src/main/scala/java/util/concurrent/locks/ReentrantLock.scala +++ b/javalib/src/main/scala/java/util/concurrent/locks/ReentrantLock.scala @@ -62,7 +62,7 @@ class ReentrantLock(fair: Boolean) extends Lock with Serializable { final def isFair(): Boolean = fair protected def getOwner(): Thread = { - if (isLocked) + if (isLocked()) Thread.currentThread() else null @@ -74,7 +74,7 @@ class ReentrantLock(fair: Boolean) extends Lock with Serializable { //Not Implemented //final def hasQueuedThread(thread: Thread): Boolean - //Not Imolemented + //Not Implemented //final def getQueueLength(): Int //Not Implemented diff --git a/javalib/src/main/scala/java/util/function/BiConsumer.scala b/javalib/src/main/scala/java/util/function/BiConsumer.scala new file mode 100644 index 0000000000..d39a9a3222 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/BiConsumer.scala @@ -0,0 +1,25 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +import scala.scalajs.js.annotation.JavaDefaultMethod + +trait BiConsumer[T, U] { + def accept(t: T, u: U): Unit + + @JavaDefaultMethod + def andThen(after: BiConsumer[T, U]): BiConsumer[T, U] = { (t: T, u: U) => + accept(t, u) + after.accept(t, u) + } +} diff --git a/javalib/src/main/scala/java/util/function/BiFunction.scala b/javalib/src/main/scala/java/util/function/BiFunction.scala new file mode 100644 index 0000000000..c6f1f75a8a --- /dev/null +++ b/javalib/src/main/scala/java/util/function/BiFunction.scala @@ -0,0 +1,24 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +import scala.scalajs.js.annotation.JavaDefaultMethod + +trait BiFunction[T, U, R] { + def apply(t: T, u: U): R + + @JavaDefaultMethod + def andThen[V](after: Function[_ >: R, _ <: V]): BiFunction[T, U, V] = { (t: T, u: U) => + after.apply(this.apply(t, u)) + } +} diff --git a/javalib/src/main/scala/java/util/function/BiPredicate.scala b/javalib/src/main/scala/java/util/function/BiPredicate.scala new file mode 100644 index 0000000000..24e9610343 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/BiPredicate.scala @@ -0,0 +1,32 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +import scala.scalajs.js.annotation.JavaDefaultMethod + +trait BiPredicate[T, U] { + def test(t: T, u: U): Boolean + + @JavaDefaultMethod + def and(other: BiPredicate[_ >: T, _ >: U]): BiPredicate[T, U] = { (t: T, u: U) => + test(t, u) && other.test(t, u) + } + + @JavaDefaultMethod + def negate(): BiPredicate[T, U] = (t: T, u: U) => !test(t, u) + + @JavaDefaultMethod + def or(other: BiPredicate[_ >: T, _ >: U]): BiPredicate[T, U] = { (t: T, u: U) => + test(t, u) || other.test(t, u) + } +} diff --git a/javalib/src/main/scala/java/util/function/BinaryOperator.scala b/javalib/src/main/scala/java/util/function/BinaryOperator.scala new file mode 100644 index 0000000000..2fe11ca0fe --- /dev/null +++ b/javalib/src/main/scala/java/util/function/BinaryOperator.scala @@ -0,0 +1,29 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +import java.util.Comparator + +trait BinaryOperator[T] extends BiFunction[T, T, T] + +object BinaryOperator { + def minBy[T](comparator: Comparator[_ >: T]): BinaryOperator[T] = { (a: T, b: T) => + if (comparator.compare(a, b) <= 0) a + else b + } + + def maxBy[T](comparator: Comparator[_ >: T]): BinaryOperator[T] = { (a: T, b: T) => + if (comparator.compare(a, b) >= 0) a + else b + } +} diff --git a/javalib/src/main/scala/java/util/function/BooleanSupplier.scala b/javalib/src/main/scala/java/util/function/BooleanSupplier.scala new file mode 100644 index 0000000000..d735e2c78f --- /dev/null +++ b/javalib/src/main/scala/java/util/function/BooleanSupplier.scala @@ -0,0 +1,18 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +@FunctionalInterface +trait BooleanSupplier { + def getAsBoolean(): Boolean +} diff --git a/javalib/src/main/scala/java/util/function/DoubleBinaryOperator.scala b/javalib/src/main/scala/java/util/function/DoubleBinaryOperator.scala new file mode 100644 index 0000000000..66cbe788e6 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/DoubleBinaryOperator.scala @@ -0,0 +1,18 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +@FunctionalInterface +trait DoubleBinaryOperator { + def applyAsDouble(left: Double, right: Double): Double +} diff --git a/javalib/src/main/scala/java/util/function/DoubleConsumer.scala b/javalib/src/main/scala/java/util/function/DoubleConsumer.scala new file mode 100644 index 0000000000..32efd4d086 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/DoubleConsumer.scala @@ -0,0 +1,26 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +import scala.scalajs.js.annotation.JavaDefaultMethod + +@FunctionalInterface +trait DoubleConsumer { + def accept(value: Double): Unit + + @JavaDefaultMethod + def andThen(after: DoubleConsumer): DoubleConsumer = { (value: Double) => + this.accept(value) + after.accept(value) + } +} diff --git a/javalib/src/main/scala/java/util/function/DoubleFunction.scala b/javalib/src/main/scala/java/util/function/DoubleFunction.scala new file mode 100644 index 0000000000..822ec79c70 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/DoubleFunction.scala @@ -0,0 +1,18 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +@FunctionalInterface +trait DoubleFunction[R] { + def apply(value: Double): R +} diff --git a/javalib/src/main/scala/java/util/function/DoublePredicate.scala b/javalib/src/main/scala/java/util/function/DoublePredicate.scala new file mode 100755 index 0000000000..b327f1ce2d --- /dev/null +++ b/javalib/src/main/scala/java/util/function/DoublePredicate.scala @@ -0,0 +1,44 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +import scala.scalajs.js.annotation.JavaDefaultMethod + +@FunctionalInterface +trait DoublePredicate { self => + def test(t: Double): Boolean + + @JavaDefaultMethod + def and(other: DoublePredicate): DoublePredicate = { + new DoublePredicate { + def test(value: Double): Boolean = + self.test(value) && other.test(value) // the order and short-circuit are by-spec + } + } + + @JavaDefaultMethod + def negate(): DoublePredicate = { + new DoublePredicate { + def test(value: Double): Boolean = + !self.test(value) + } + } + + @JavaDefaultMethod + def or(other: DoublePredicate): DoublePredicate = { + new DoublePredicate { + def test(value: Double): Boolean = + self.test(value) || other.test(value) // the order and short-circuit are by-spec + } + } +} diff --git a/javalib/src/main/scala/java/util/function/DoubleSupplier.scala b/javalib/src/main/scala/java/util/function/DoubleSupplier.scala new file mode 100644 index 0000000000..bf0e6dc308 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/DoubleSupplier.scala @@ -0,0 +1,18 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +@FunctionalInterface +trait DoubleSupplier { + def getAsDouble(): Double +} diff --git a/javalib/src/main/scala/java/util/function/DoubleToIntFunction.scala b/javalib/src/main/scala/java/util/function/DoubleToIntFunction.scala new file mode 100644 index 0000000000..d8bdc70ef1 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/DoubleToIntFunction.scala @@ -0,0 +1,18 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +@FunctionalInterface +trait DoubleToIntFunction { + def applyAsInt(value: Double): Int +} diff --git a/javalib/src/main/scala/java/util/function/DoubleToLongFunction.scala b/javalib/src/main/scala/java/util/function/DoubleToLongFunction.scala new file mode 100644 index 0000000000..5e2e1504a9 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/DoubleToLongFunction.scala @@ -0,0 +1,18 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +@FunctionalInterface +trait DoubleToLongFunction { + def applyAsLong(value: Double): Long +} diff --git a/javalib/src/main/scala/java/util/function/DoubleUnaryOperator.scala b/javalib/src/main/scala/java/util/function/DoubleUnaryOperator.scala new file mode 100644 index 0000000000..53efb491f4 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/DoubleUnaryOperator.scala @@ -0,0 +1,34 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +import scala.scalajs.js.annotation.JavaDefaultMethod + +@FunctionalInterface +trait DoubleUnaryOperator { + def applyAsDouble(operand: Double): Double + + @JavaDefaultMethod + def andThen(after: DoubleUnaryOperator): DoubleUnaryOperator = { (d: Double) => + after.applyAsDouble(applyAsDouble(d)) + } + + @JavaDefaultMethod + def compose(before: DoubleUnaryOperator): DoubleUnaryOperator = { (d: Double) => + applyAsDouble(before.applyAsDouble(d)) + } +} + +object DoubleUnaryOperator { + def identity(): DoubleUnaryOperator = (d: Double) => d +} diff --git a/javalib/src/main/scala/java/util/function/Function.scala b/javalib/src/main/scala/java/util/function/Function.scala new file mode 100644 index 0000000000..f01c853527 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/Function.scala @@ -0,0 +1,33 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +import scala.scalajs.js.annotation.JavaDefaultMethod + +trait Function[T, R] { + def apply(t: T): R + + @JavaDefaultMethod + def andThen[V](after: Function[_ >: R, _ <: V]): Function[T, V] = { (t: T) => + after.apply(apply(t)) + } + + @JavaDefaultMethod + def compose[V](before: Function[_ >: V, _ <: T]): Function[V, R] = { (v: V) => + apply(before.apply(v)) + } +} + +object Function { + def identity[T](): Function[T, T] = (t: T) => t +} diff --git a/javalib/src/main/scala/java/util/function/IntBinaryOperator.scala b/javalib/src/main/scala/java/util/function/IntBinaryOperator.scala new file mode 100644 index 0000000000..68ca23060e --- /dev/null +++ b/javalib/src/main/scala/java/util/function/IntBinaryOperator.scala @@ -0,0 +1,18 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +@FunctionalInterface +trait IntBinaryOperator { + def applyAsInt(left: Int, right: Int): Int +} diff --git a/javalib/src/main/scala/java/util/function/IntConsumer.scala b/javalib/src/main/scala/java/util/function/IntConsumer.scala new file mode 100644 index 0000000000..5e54e7a101 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/IntConsumer.scala @@ -0,0 +1,26 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +import scala.scalajs.js.annotation.JavaDefaultMethod + +@FunctionalInterface +trait IntConsumer { + def accept(value: Int): Unit + + @JavaDefaultMethod + def andThen(after: IntConsumer): IntConsumer = { (value: Int) => + this.accept(value) + after.accept(value) + } +} diff --git a/javalib/src/main/scala/java/util/function/IntFunction.scala b/javalib/src/main/scala/java/util/function/IntFunction.scala new file mode 100644 index 0000000000..19d2a6c853 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/IntFunction.scala @@ -0,0 +1,18 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +@FunctionalInterface +trait IntFunction[R] { + def apply(value: Int): R +} diff --git a/javalib/src/main/scala/java/util/function/IntPredicate.scala b/javalib/src/main/scala/java/util/function/IntPredicate.scala new file mode 100755 index 0000000000..c6cfc6c7fc --- /dev/null +++ b/javalib/src/main/scala/java/util/function/IntPredicate.scala @@ -0,0 +1,44 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +import scala.scalajs.js.annotation.JavaDefaultMethod + +@FunctionalInterface +trait IntPredicate { self => + def test(t: Int): Boolean + + @JavaDefaultMethod + def and(other: IntPredicate): IntPredicate = { + new IntPredicate { + def test(value: Int): Boolean = + self.test(value) && other.test(value) // the order and short-circuit are by-spec + } + } + + @JavaDefaultMethod + def negate(): IntPredicate = { + new IntPredicate { + def test(value: Int): Boolean = + !self.test(value) + } + } + + @JavaDefaultMethod + def or(other: IntPredicate): IntPredicate = { + new IntPredicate { + def test(value: Int): Boolean = + self.test(value) || other.test(value) // the order and short-circuit are by-spec + } + } +} diff --git a/javalib/src/main/scala/java/util/function/IntSupplier.scala b/javalib/src/main/scala/java/util/function/IntSupplier.scala new file mode 100644 index 0000000000..a0a69e0e16 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/IntSupplier.scala @@ -0,0 +1,18 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +@FunctionalInterface +trait IntSupplier { + def getAsInt(): Int +} diff --git a/javalib/src/main/scala/java/util/function/IntToDoubleFunction.scala b/javalib/src/main/scala/java/util/function/IntToDoubleFunction.scala new file mode 100644 index 0000000000..02355bc759 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/IntToDoubleFunction.scala @@ -0,0 +1,18 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +@FunctionalInterface +trait IntToDoubleFunction { + def applyAsDouble(value: Int): Double +} diff --git a/javalib/src/main/scala/java/util/function/IntToLongFunction.scala b/javalib/src/main/scala/java/util/function/IntToLongFunction.scala new file mode 100644 index 0000000000..a40feceff4 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/IntToLongFunction.scala @@ -0,0 +1,18 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +@FunctionalInterface +trait IntToLongFunction { + def applyAsLong(value: Int): Long +} diff --git a/javalib/src/main/scala/java/util/function/IntUnaryOperator.scala b/javalib/src/main/scala/java/util/function/IntUnaryOperator.scala new file mode 100644 index 0000000000..826ab9fc37 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/IntUnaryOperator.scala @@ -0,0 +1,34 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +import scala.scalajs.js.annotation.JavaDefaultMethod + +@FunctionalInterface +trait IntUnaryOperator { + def applyAsInt(operand: Int): Int + + @JavaDefaultMethod + def andThen(after: IntUnaryOperator): IntUnaryOperator = { (i: Int) => + after.applyAsInt(applyAsInt(i)) + } + + @JavaDefaultMethod + def compose(before: IntUnaryOperator): IntUnaryOperator = { (i: Int) => + applyAsInt(before.applyAsInt(i)) + } +} + +object IntUnaryOperator { + def identity(): IntUnaryOperator = (i: Int) => i +} diff --git a/javalib/src/main/scala/java/util/function/LongBinaryOperator.scala b/javalib/src/main/scala/java/util/function/LongBinaryOperator.scala new file mode 100644 index 0000000000..a7b4981564 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/LongBinaryOperator.scala @@ -0,0 +1,18 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +@FunctionalInterface +trait LongBinaryOperator { + def applyAsLong(left: Long, right: Long): Long +} diff --git a/javalib/src/main/scala/java/util/function/LongConsumer.scala b/javalib/src/main/scala/java/util/function/LongConsumer.scala new file mode 100644 index 0000000000..4603d80376 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/LongConsumer.scala @@ -0,0 +1,26 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +import scala.scalajs.js.annotation.JavaDefaultMethod + +@FunctionalInterface +trait LongConsumer { + def accept(value: Long): Unit + + @JavaDefaultMethod + def andThen(after: LongConsumer): LongConsumer = { (value: Long) => + this.accept(value) + after.accept(value) + } +} diff --git a/javalib/src/main/scala/java/util/function/LongFunction.scala b/javalib/src/main/scala/java/util/function/LongFunction.scala new file mode 100644 index 0000000000..6fc9e7bce1 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/LongFunction.scala @@ -0,0 +1,18 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +@FunctionalInterface +trait LongFunction[R] { + def apply(value: Long): R +} diff --git a/javalib/src/main/scala/java/util/function/LongPredicate.scala b/javalib/src/main/scala/java/util/function/LongPredicate.scala new file mode 100755 index 0000000000..0b3693e6fc --- /dev/null +++ b/javalib/src/main/scala/java/util/function/LongPredicate.scala @@ -0,0 +1,44 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +import scala.scalajs.js.annotation.JavaDefaultMethod + +@FunctionalInterface +trait LongPredicate { self => + def test(t: Long): Boolean + + @JavaDefaultMethod + def and(other: LongPredicate): LongPredicate = { + new LongPredicate { + def test(value: Long): Boolean = + self.test(value) && other.test(value) // the order and short-circuit are by-spec + } + } + + @JavaDefaultMethod + def negate(): LongPredicate = { + new LongPredicate { + def test(value: Long): Boolean = + !self.test(value) + } + } + + @JavaDefaultMethod + def or(other: LongPredicate): LongPredicate = { + new LongPredicate { + def test(value: Long): Boolean = + self.test(value) || other.test(value) // the order and short-circuit are by-spec + } + } +} diff --git a/javalib/src/main/scala/java/util/function/LongSupplier.scala b/javalib/src/main/scala/java/util/function/LongSupplier.scala new file mode 100644 index 0000000000..cff6322e96 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/LongSupplier.scala @@ -0,0 +1,18 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +@FunctionalInterface +trait LongSupplier { + def getAsLong(): Long +} diff --git a/javalib/src/main/scala/java/util/function/LongToDoubleFunction.scala b/javalib/src/main/scala/java/util/function/LongToDoubleFunction.scala new file mode 100644 index 0000000000..d229934270 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/LongToDoubleFunction.scala @@ -0,0 +1,18 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +@FunctionalInterface +trait LongToDoubleFunction { + def applyAsDouble(value: Long): Double +} diff --git a/javalib/src/main/scala/java/util/function/LongToIntFunction.scala b/javalib/src/main/scala/java/util/function/LongToIntFunction.scala new file mode 100644 index 0000000000..60f3309385 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/LongToIntFunction.scala @@ -0,0 +1,18 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +@FunctionalInterface +trait LongToIntFunction { + def applyAsInt(value: Long): Int +} diff --git a/javalib/src/main/scala/java/util/function/LongUnaryOperator.scala b/javalib/src/main/scala/java/util/function/LongUnaryOperator.scala new file mode 100644 index 0000000000..0b84f242d9 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/LongUnaryOperator.scala @@ -0,0 +1,34 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +import scala.scalajs.js.annotation.JavaDefaultMethod + +@FunctionalInterface +trait LongUnaryOperator { + def applyAsLong(operand: Long): Long + + @JavaDefaultMethod + def andThen(after: LongUnaryOperator): LongUnaryOperator = { (l: Long) => + after.applyAsLong(applyAsLong(l)) + } + + @JavaDefaultMethod + def compose(before: LongUnaryOperator): LongUnaryOperator = { (l: Long) => + applyAsLong(before.applyAsLong(l)) + } +} + +object LongUnaryOperator { + def identity(): LongUnaryOperator = (l: Long) => l +} diff --git a/javalib/src/main/scala/java/util/function/ObjDoubleConsumer.scala b/javalib/src/main/scala/java/util/function/ObjDoubleConsumer.scala new file mode 100644 index 0000000000..4831fdbbd9 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/ObjDoubleConsumer.scala @@ -0,0 +1,18 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +@FunctionalInterface +trait ObjDoubleConsumer[T] { + def accept(t: T, value: Double): Unit +} diff --git a/javalib/src/main/scala/java/util/function/ObjIntConsumer.scala b/javalib/src/main/scala/java/util/function/ObjIntConsumer.scala new file mode 100644 index 0000000000..f1ffd65da7 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/ObjIntConsumer.scala @@ -0,0 +1,18 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +@FunctionalInterface +trait ObjIntConsumer[T] { + def accept(t: T, value: Int): Unit +} diff --git a/javalib/src/main/scala/java/util/function/ObjLongConsumer.scala b/javalib/src/main/scala/java/util/function/ObjLongConsumer.scala new file mode 100644 index 0000000000..f9919bd60c --- /dev/null +++ b/javalib/src/main/scala/java/util/function/ObjLongConsumer.scala @@ -0,0 +1,18 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +@FunctionalInterface +trait ObjLongConsumer[T] { + def accept(t: T, value: Long): Unit +} diff --git a/javalib/src/main/scala/java/util/function/Supplier.scala b/javalib/src/main/scala/java/util/function/Supplier.scala new file mode 100644 index 0000000000..41a1e0e341 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/Supplier.scala @@ -0,0 +1,17 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +trait Supplier[T] { + def get(): T +} diff --git a/javalib/src/main/scala/java/util/function/ToDoubleBiFunction.scala b/javalib/src/main/scala/java/util/function/ToDoubleBiFunction.scala new file mode 100644 index 0000000000..28eee69064 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/ToDoubleBiFunction.scala @@ -0,0 +1,18 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +@FunctionalInterface +trait ToDoubleBiFunction[T, U] { + def applyAsDouble(t: T, u: U): Double +} diff --git a/javalib/src/main/scala/java/util/function/ToDoubleFunction.scala b/javalib/src/main/scala/java/util/function/ToDoubleFunction.scala new file mode 100644 index 0000000000..1c72226668 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/ToDoubleFunction.scala @@ -0,0 +1,18 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +@FunctionalInterface +trait ToDoubleFunction[T] { + def applyAsDouble(t: T): Double +} diff --git a/javalib/src/main/scala/java/util/function/ToIntBiFunction.scala b/javalib/src/main/scala/java/util/function/ToIntBiFunction.scala new file mode 100644 index 0000000000..5e9751d650 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/ToIntBiFunction.scala @@ -0,0 +1,18 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +@FunctionalInterface +trait ToIntBiFunction[T, U] { + def applyAsInt(t: T, u: U): Int +} diff --git a/javalib/src/main/scala/java/util/function/ToIntFunction.scala b/javalib/src/main/scala/java/util/function/ToIntFunction.scala new file mode 100644 index 0000000000..7f9fc5e206 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/ToIntFunction.scala @@ -0,0 +1,18 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +@FunctionalInterface +trait ToIntFunction[T] { + def applyAsInt(t: T): Int +} diff --git a/javalib/src/main/scala/java/util/function/ToLongBiFunction.scala b/javalib/src/main/scala/java/util/function/ToLongBiFunction.scala new file mode 100644 index 0000000000..2e2b52fb36 --- /dev/null +++ b/javalib/src/main/scala/java/util/function/ToLongBiFunction.scala @@ -0,0 +1,18 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +@FunctionalInterface +trait ToLongBiFunction[T, U] { + def applyAsLong(t: T, u: U): Long +} diff --git a/javalib/src/main/scala/java/util/function/ToLongFunction.scala b/javalib/src/main/scala/java/util/function/ToLongFunction.scala new file mode 100644 index 0000000000..fef9a920ed --- /dev/null +++ b/javalib/src/main/scala/java/util/function/ToLongFunction.scala @@ -0,0 +1,18 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +@FunctionalInterface +trait ToLongFunction[T] { + def applyAsLong(t: T): Long +} diff --git a/javalib/src/main/scala/java/util/function/UnaryOperator.scala b/javalib/src/main/scala/java/util/function/UnaryOperator.scala new file mode 100644 index 0000000000..de49f0869a --- /dev/null +++ b/javalib/src/main/scala/java/util/function/UnaryOperator.scala @@ -0,0 +1,19 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.function + +trait UnaryOperator[T] extends Function[T, T] + +object UnaryOperator { + def identity[T](): UnaryOperator[T] = (t: T) => t +} diff --git a/javalib/src/main/scala/java/util/internal/GenericArrayOps.scala b/javalib/src/main/scala/java/util/internal/GenericArrayOps.scala new file mode 100644 index 0000000000..e25c786845 --- /dev/null +++ b/javalib/src/main/scala/java/util/internal/GenericArrayOps.scala @@ -0,0 +1,146 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.internal + +import java.lang.{reflect => jlr} +import java.util.Comparator + +/** Typeclasses for generic operations on `Array`s. */ +object GenericArrayOps { + + /** A typeclass for operations to manipulate existing arrays. */ + sealed trait ArrayOps[A] { + def length(a: Array[A]): Int + def get(a: Array[A], i: Int): A + def set(a: Array[A], i: Int, v: A): Unit + } + + /** A typeclass for the ability to create arrays of a given type. */ + sealed trait ArrayCreateOps[A] { + def create(length: Int): Array[A] + } + + // ArrayOps and ArrayCreateOps instances for reference types + + private object ReusableAnyRefArrayOps extends ArrayOps[AnyRef] { + @inline def length(a: Array[AnyRef]): Int = a.length + @inline def get(a: Array[AnyRef], i: Int): AnyRef = a(i) + @inline def set(a: Array[AnyRef], i: Int, v: AnyRef): Unit = a(i) = v + } + + @inline + implicit def specificAnyRefArrayOps[A <: AnyRef]: ArrayOps[A] = + ReusableAnyRefArrayOps.asInstanceOf[ArrayOps[A]] + + @inline + final class ClassArrayOps[A <: AnyRef](clazz: Class[_ <: Array[A]]) + extends ArrayCreateOps[A] { + @inline def create(length: Int): Array[A] = + createArrayOfClass(clazz, length) + } + + @inline + final class TemplateArrayOps[A <: AnyRef](template: Array[A]) + extends ArrayCreateOps[A] { + @inline def create(length: Int): Array[A] = + createArrayOfClass(template.getClass(), length) + } + + @inline + def createArrayOfClass[A <: AnyRef](clazz: Class[_ <: Array[A]], length: Int): Array[A] = + jlr.Array.newInstance(clazz.getComponentType(), length).asInstanceOf[Array[A]] + + implicit object AnyRefArrayCreateOps extends ArrayCreateOps[AnyRef] { + @inline def create(length: Int): Array[AnyRef] = new Array[AnyRef](length) + } + + /* ArrayOps and ArrayCreateOps instances for primitive types. + * + * With the exception of the one for Boolean, they also implement + * `java.util.Comparator` for the same element type. In a perfect design, we + * would define separate objects for that, but it would result in more + * generated code for no good reason. + */ + + implicit object BooleanArrayOps + extends ArrayOps[Boolean] with ArrayCreateOps[Boolean] { + @inline def length(a: Array[Boolean]): Int = a.length + @inline def get(a: Array[Boolean], i: Int): Boolean = a(i) + @inline def set(a: Array[Boolean], i: Int, v: Boolean): Unit = a(i) = v + @inline def create(length: Int): Array[Boolean] = new Array[Boolean](length) + } + + implicit object CharArrayOps + extends ArrayOps[Char] with ArrayCreateOps[Char] with Comparator[Char] { + @inline def length(a: Array[Char]): Int = a.length + @inline def get(a: Array[Char], i: Int): Char = a(i) + @inline def set(a: Array[Char], i: Int, v: Char): Unit = a(i) = v + @inline def create(length: Int): Array[Char] = new Array[Char](length) + @inline def compare(x: Char, y: Char): Int = java.lang.Character.compare(x, y) + } + + implicit object ByteArrayOps + extends ArrayOps[Byte] with ArrayCreateOps[Byte] with Comparator[Byte] { + @inline def length(a: Array[Byte]): Int = a.length + @inline def get(a: Array[Byte], i: Int): Byte = a(i) + @inline def set(a: Array[Byte], i: Int, v: Byte): Unit = a(i) = v + @inline def create(length: Int): Array[Byte] = new Array[Byte](length) + @inline def compare(x: Byte, y: Byte): Int = java.lang.Byte.compare(x, y) + } + + implicit object ShortArrayOps + extends ArrayOps[Short] with ArrayCreateOps[Short] with Comparator[Short] { + @inline def length(a: Array[Short]): Int = a.length + @inline def get(a: Array[Short], i: Int): Short = a(i) + @inline def set(a: Array[Short], i: Int, v: Short): Unit = a(i) = v + @inline def create(length: Int): Array[Short] = new Array[Short](length) + @inline def compare(x: Short, y: Short): Int = java.lang.Short.compare(x, y) + } + + implicit object IntArrayOps + extends ArrayOps[Int] with ArrayCreateOps[Int] with Comparator[Int] { + @inline def length(a: Array[Int]): Int = a.length + @inline def get(a: Array[Int], i: Int): Int = a(i) + @inline def set(a: Array[Int], i: Int, v: Int): Unit = a(i) = v + @inline def create(length: Int): Array[Int] = new Array[Int](length) + @inline def compare(x: Int, y: Int): Int = java.lang.Integer.compare(x, y) + } + + implicit object LongArrayOps + extends ArrayOps[Long] with ArrayCreateOps[Long] with Comparator[Long] { + @inline def length(a: Array[Long]): Int = a.length + @inline def get(a: Array[Long], i: Int): Long = a(i) + @inline def set(a: Array[Long], i: Int, v: Long): Unit = a(i) = v + @inline def create(length: Int): Array[Long] = new Array[Long](length) + @inline def compare(x: Long, y: Long): Int = java.lang.Long.compare(x, y) + } + + implicit object FloatArrayOps + extends ArrayOps[Float] with ArrayCreateOps[Float] with Comparator[Float] { + @inline def length(a: Array[Float]): Int = a.length + @inline def get(a: Array[Float], i: Int): Float = a(i) + @inline def set(a: Array[Float], i: Int, v: Float): Unit = a(i) = v + @inline def create(length: Int): Array[Float] = new Array[Float](length) + @inline def compare(x: Float, y: Float): Int = java.lang.Float.compare(x, y) + } + + implicit object DoubleArrayOps + extends ArrayOps[Double] with ArrayCreateOps[Double] with Comparator[Double] { + @inline def length(a: Array[Double]): Int = a.length + @inline def get(a: Array[Double], i: Int): Double = a(i) + @inline def set(a: Array[Double], i: Int, v: Double): Unit = a(i) = v + @inline def create(length: Int): Array[Double] = new Array[Double](length) + @inline def compare(x: Double, y: Double): Int = java.lang.Double.compare(x, y) + } + +} diff --git a/javalib/src/main/scala/java/util/internal/MurmurHash3.scala b/javalib/src/main/scala/java/util/internal/MurmurHash3.scala new file mode 100644 index 0000000000..bcf438f131 --- /dev/null +++ b/javalib/src/main/scala/java/util/internal/MurmurHash3.scala @@ -0,0 +1,61 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.internal + +import java.lang.Integer.{rotateLeft => rotl} + +/** Primitives to implement MurmurHash3 hashes in data structures. + * + * This is copy of parts of `scala.util.hashing.MurmurHash3`. + */ +private[java] object MurmurHash3 { + /** Mix in a block of data into an intermediate hash value. */ + final def mix(hash: Int, data: Int): Int = { + var h = mixLast(hash, data) + h = rotl(h, 13) + h * 5 + 0xe6546b64 + } + + /** May optionally be used as the last mixing step. + * + * Is a little bit faster than mix, as it does no further mixing of the + * resulting hash. For the last element this is not necessary as the hash is + * thoroughly mixed during finalization anyway. + */ + final def mixLast(hash: Int, data: Int): Int = { + var k = data + + k *= 0xcc9e2d51 + k = rotl(k, 15) + k *= 0x1b873593 + + hash ^ k + } + + /** Finalize a hash to incorporate the length and make sure all bits avalanche. */ + @noinline final def finalizeHash(hash: Int, length: Int): Int = + avalanche(hash ^ length) + + /** Force all bits of the hash to avalanche. Used for finalizing the hash. */ + @inline private final def avalanche(hash: Int): Int = { + var h = hash + + h ^= h >>> 16 + h *= 0x85ebca6b + h ^= h >>> 13 + h *= 0xc2b2ae35 + h ^= h >>> 16 + + h + } +} diff --git a/javalib/src/main/scala/java/util/internal/RefTypes.scala b/javalib/src/main/scala/java/util/internal/RefTypes.scala new file mode 100644 index 0000000000..d02cf33d8d --- /dev/null +++ b/javalib/src/main/scala/java/util/internal/RefTypes.scala @@ -0,0 +1,94 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.internal + +@inline +private[java] class BooleanRef(var elem: Boolean) extends Serializable { + override def toString(): String = String.valueOf(elem) +} +private[java] object BooleanRef { + def create(elem: Boolean): BooleanRef = new BooleanRef(elem) + def zero(): BooleanRef = new BooleanRef(false) +} + +@inline +private[java] class CharRef(var elem: Char) extends Serializable { + override def toString(): String = String.valueOf(elem) +} +private[java] object CharRef { + def create(elem: Char): CharRef = new CharRef(elem) + def zero(): CharRef = new CharRef(0.toChar) +} + +@inline +private[java] class ByteRef(var elem: Byte) extends Serializable { + override def toString(): String = String.valueOf(elem) +} +private[java] object ByteRef { + def create(elem: Byte): ByteRef = new ByteRef(elem) + def zero(): ByteRef = new ByteRef(0) +} + +@inline +private[java] class ShortRef(var elem: Short) extends Serializable { + override def toString(): String = String.valueOf(elem) +} +private[java] object ShortRef { + def create(elem: Short): ShortRef = new ShortRef(elem) + def zero(): ShortRef = new ShortRef(0) +} + +@inline +private[java] class IntRef(var elem: Int) extends Serializable { + override def toString(): String = String.valueOf(elem) +} +private[java] object IntRef { + def create(elem: Int): IntRef = new IntRef(elem) + def zero(): IntRef = new IntRef(0) +} + +@inline +private[java] class LongRef(var elem: Long) extends Serializable { + override def toString(): String = String.valueOf(elem) +} +private[java] object LongRef { + def create(elem: Long): LongRef = new LongRef(elem) + def zero(): LongRef = new LongRef(0) +} + +@inline +private[java] class FloatRef(var elem: Float) extends Serializable { + override def toString(): String = String.valueOf(elem) +} +private[java] object FloatRef { + def create(elem: Float): FloatRef = new FloatRef(elem) + def zero(): FloatRef = new FloatRef(0) +} + +@inline +private[java] class DoubleRef(var elem: Double) extends Serializable { + override def toString(): String = String.valueOf(elem) +} +private[java] object DoubleRef { + def create(elem: Double): DoubleRef = new DoubleRef(elem) + def zero(): DoubleRef = new DoubleRef(0) +} + +@inline +private[java] class ObjectRef[A](var elem: A) extends Serializable { + override def toString(): String = String.valueOf(elem) +} +private[java] object ObjectRef { + def create[A](elem: A): ObjectRef[A] = new ObjectRef(elem) + def zero(): ObjectRef[Object] = new ObjectRef(null) +} diff --git a/javalib/src/main/scala/java/util/internal/Tuples.scala b/javalib/src/main/scala/java/util/internal/Tuples.scala new file mode 100644 index 0000000000..d476cd74a9 --- /dev/null +++ b/javalib/src/main/scala/java/util/internal/Tuples.scala @@ -0,0 +1,26 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.internal + +@inline +final class Tuple2[+T1, +T2](val _1: T1, val _2: T2) + +@inline +final class Tuple3[+T1, +T2, +T3](val _1: T1, val _2: T2, val _3: T3) + +@inline +final class Tuple4[+T1, +T2, +T3, +T4](val _1: T1, val _2: T2, val _3: T3, val _4: T4) + +@inline +final class Tuple8[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8]( + val _1: T1, val _2: T2, val _3: T3, val _4: T4, val _5: T5, val _6: T6, val _7: T7, val _8: T8) diff --git a/javalib/src/main/scala/java/util/regex/GroupStartMapper.scala b/javalib/src/main/scala/java/util/regex/GroupStartMapper.scala deleted file mode 100644 index d9abb9417f..0000000000 --- a/javalib/src/main/scala/java/util/regex/GroupStartMapper.scala +++ /dev/null @@ -1,487 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package java.util.regex - -import scala.annotation.{tailrec, switch} - -import java.util.HashMap - -import scala.scalajs.js - -/** The goal of a `GroupStartMapper` is to retrieve the start position of each - * group of a matching regular expression where only the strings of the - * matched groups are known. - * For that, we use the following observation: - * If the regex /A(B)\1/ matches a string at a given index, - * then /(A)(B)\2/ matches the same string at the same index. - * However, in the second regex, we can use the length of the first group (A) - * to retrieve the start position of the second group (B). - * Note that the back-references in the second regex are shifted, but this - * does not change the matched strings. - * - * Implementation details: - * - It parses the regular expression into a tree of type `Node` - * - It converts this Node to a regex string, such that every sub-part of the - * regex which was not yet in a group now belongs to a group - * - The new regex matches the original string at the original position - * - It propagates the matched strings of all groups into the Node - * - It computes the start of every group thanks to the groups before it - * - It builds and returns the mapping of previous group number -> start - * - * @author Mikaël Mayer - */ -private[regex] class GroupStartMapper private (pattern: String, flags: String, - node: GroupStartMapper.Node, groupCount: Int, - allMatchingRegex: js.RegExp) { - - import GroupStartMapper._ - - def apply(string: String, start: Int): js.Array[Int] = { - allMatchingRegex.lastIndex = start - val allMatchResult = allMatchingRegex.exec(string) - if (allMatchResult == null) { - throw new AssertionError( - s"[Internal error] Executed '$allMatchingRegex' on " + - s"'$string' at position $start, got an error.\n" + - s"Original pattern '$pattern' with flags '$flags' did match however.") - } - - // Prepare a `groupStartMap` array with the correct length filled with -1 - val len = groupCount + 1 // index 0 is not used - val groupStartMap = new js.Array[Int](len) - var i = 0 - while (i != len) { - groupStartMap(i) = -1 - i += 1 - } - - node.propagateFromStart(allMatchResult, groupStartMap, start) - - groupStartMap - } -} - -private[regex] object GroupStartMapper { - def apply(pattern: String, flags: String): GroupStartMapper = { - val parser = new Parser(pattern) - val node = parser.parseTopLevel() - node.setNewGroup(1) - val allMatchingRegex = - new js.RegExp(node.buildRegex(parser.groupNodeMap), flags) - new GroupStartMapper(pattern, flags, node, parser.parsedGroupCount, - allMatchingRegex) - } - - /** Node of the regex tree. */ - private abstract class Node { - var newGroup: Int = _ // Assigned later after the tree of nodes is built - - /** Assigns consecutive group numbers starting from newGroupIndex to the - * nodes in this subtree, in a pre-order walk. - * - * @return 1 plus the largest assigned group number. - */ - def setNewGroup(newGroupIndex: Int): Int = { - newGroup = newGroupIndex - newGroupIndex + 1 - } - - def buildRegex(groupNodeMap: js.Array[Node]): String - - /* When assigning group positions. I could not choose between assigning - * group numbers from left to right or from right to left, because there - * both failed in one case each. Normally, both directions give the same - * result. But there are corner cases. - * - * Consider the following regex matching `abbbbbbc` - * - * (?=ab*(c))ab - * - * After conversion, this becomes: - * - * (?=(ab*)(c))(ab) - * - * To recover the position of the group (c), we cannot do anything but - * compute it from the length of (ab*), that is, propagate the start, - * compute the length, and return the end, and this, recursively. This is - * what we need to do in a forward-matching regex. - * - * However, consider the following regex matching `abcbdbe` - * - * a(b.)* - * - * After conversion, it is transformed to: - * - * (a)((b.)*) - * - * The semantics of group matching under a star are that the last match is - * kept. Therefore, we cannot obtain the start position of (b.) from - * propagating lengths from left to right. What we first do is to get the - * start, then the end, of the group `((b.)*)`, and then we propagate this - * end to the inner group. - * - * Note that when JavaScript will support back-matching `(?<= )` and - * `(? end - matched.length) - propagate(matchResult, groupStartMap, start, end) - start - } - - /** Propagates the appropriate positions to the descendants of this node - * from its start position. - * - * @return the end position of this node - */ - final def propagateFromStart(matchResult: js.RegExp.ExecResult, - groupStartMap: js.Array[Int], start: Int): Int = { - - val end = matchResult(newGroup).fold(-1)(matched => start + matched.length) - propagate(matchResult, groupStartMap, start, end) - end - } - } - - /** A numbered group. */ - private final class GroupNode(val number: Int, val inner: Node) extends Node { - override def setNewGroup(newGroupIndex: Int): Int = - inner.setNewGroup(super.setNewGroup(newGroupIndex)) - - def buildRegex(groupNodeMap: js.Array[Node]): String = - "(" + inner.buildRegex(groupNodeMap) + ")" - - def propagate(matchResult: js.RegExp.ExecResult, - groupStartMap: js.Array[Int], start: Int, end: Int): Unit = { - /* #3901: A GroupNode within a negative look-ahead node may receive - * `start != -1` from above, yet not match anything itself. We must - * always keep the default `-1` if this group node does not match - * anything. - */ - if (matchResult(newGroup).isDefined) - groupStartMap(number) = start - inner.propagateFromStart(matchResult, groupStartMap, start) - } - } - - /** A zero-length test of the form `(?= )` or `(?! )`. */ - private final class ZeroLengthTestNode(val indicator: String, val inner: Node) - extends Node { - - override def setNewGroup(newGroupIndex: Int): Int = - inner.setNewGroup(super.setNewGroup(newGroupIndex)) - - def buildRegex(groupNodeMap: js.Array[Node]): String = - "((" + indicator + inner.buildRegex(groupNodeMap) + "))" - - def propagate(matchResult: js.RegExp.ExecResult, - groupStartMap: js.Array[Int], start: Int, end: Int): Unit = { - inner.propagateFromStart(matchResult, groupStartMap, start) - } - } - - /** A repeated node. */ - private final class RepeatedNode(val inner: Node, val repeater: String) - extends Node { - - override def setNewGroup(newGroupIndex: Int): Int = - inner.setNewGroup(super.setNewGroup(newGroupIndex)) - - def buildRegex(groupNodeMap: js.Array[Node]): String = - "(" + inner.buildRegex(groupNodeMap) + repeater + ")" - - def propagate(matchResult: js.RegExp.ExecResult, - groupStartMap: js.Array[Int], start: Int, end: Int): Unit = { - inner.propagateFromEnd(matchResult, groupStartMap, end) - } - } - - /** A leaf regex, without any subgroups. */ - private final class LeafRegexNode(val regex: String) extends Node { - def buildRegex(groupNodeMap: js.Array[Node]): String = - "(" + regex + ")" - - def propagate(matchResult: js.RegExp.ExecResult, - groupStartMap: js.Array[Int], start: Int, end: Int): Unit = { - // nothing to do - } - } - - /** A back reference. */ - private final class BackReferenceNode(val groupNumber: Int) extends Node { - def buildRegex(groupNodeMap: js.Array[Node]): String = { - val newGroupNumber = - if (groupNumber >= groupNodeMap.length) 0 - else groupNodeMap(groupNumber).newGroup - "(\\" + newGroupNumber + ")" - } - - def propagate(matchResult: js.RegExp.ExecResult, - groupStartMap: js.Array[Int], start: Int, end: Int): Unit = { - // nothing to do - } - } - - /** A sequence of consecutive nodes. */ - private final class SequenceNode(val sequence: js.Array[Node]) extends Node { - override def setNewGroup(newGroupIndex: Int): Int = { - var nextIndex = super.setNewGroup(newGroupIndex) - val len = sequence.length - var i = 0 - while (i != len) { - nextIndex = sequence(i).setNewGroup(nextIndex) - i += 1 - } - nextIndex - } - - def buildRegex(groupNodeMap: js.Array[Node]): String = { - var result = "(" - val len = sequence.length - var i = 0 - while (i != len) { - result += sequence(i).buildRegex(groupNodeMap) - i += 1 - } - result + ")" - } - - def propagate(matchResult: js.RegExp.ExecResult, - groupStartMap: js.Array[Int], start: Int, end: Int): Unit = { - val len = sequence.length - var i = 0 - var nextStart = start - while (i != len) { - nextStart = - sequence(i).propagateFromStart(matchResult, groupStartMap, nextStart) - i += 1 - } - } - } - - /** An alternatives node such as `ab|cd`. */ - private final class AlternativesNode(val alternatives: js.Array[Node]) - extends Node { - - override def setNewGroup(newGroupIndex: Int): Int = { - var nextIndex = super.setNewGroup(newGroupIndex) - val len = alternatives.length - var i = 0 - while (i != len) { - nextIndex = alternatives(i).setNewGroup(nextIndex) - i += 1 - } - nextIndex - } - - def buildRegex(groupNodeMap: js.Array[Node]): String = { - var result = "(" - val len = alternatives.length - var i = 0 - while (i != len) { - if (i != 0) - result += "|" - result += alternatives(i).buildRegex(groupNodeMap) - i += 1 - } - result + ")" - } - - def propagate(matchResult: js.RegExp.ExecResult, - groupStartMap: js.Array[Int], start: Int, end: Int): Unit = { - val len = alternatives.length - var i = 0 - while (i != len) { - alternatives(i).propagateFromStart(matchResult, groupStartMap, start) - i += 1 - } - } - } - - private final class Parser(pattern0: String) { - /* Use a null-terminated string so that we don't have to check - * `pIndex < pattern.length` all the time. - */ - private[this] val pattern: String = pattern0 + ')' - - private[this] var pIndex: Int = 0 - - val groupNodeMap = js.Array[Node](null) // index 0 is not used - - def parsedGroupCount: Int = groupNodeMap.length - 1 - - def parseTopLevel(): Node = - parseInsideParensAndClosingParen() - - private def parseInsideParensAndClosingParen(): Node = { - // scalastyle:off return - val alternatives = js.Array[Node]() // completed alternatives - var sequence = js.Array[Node]() // current sequence - - // Explicitly take the sequence, otherwise we capture a `var` - def completeSequence(sequence: js.Array[Node]): Node = { - sequence.length match { - case 0 => new LeafRegexNode("") - case 1 => sequence(0) - case _ => new SequenceNode(sequence) - } - } - - while (true) { - val baseNode = (pattern.charAt(pIndex): @switch) match { - case '|' => - // Complete one alternative - alternatives.push(completeSequence(sequence)) - sequence = js.Array[Node]() - pIndex += 1 - null - - case ')' => - // Complete the last alternative - pIndex += 1 // go past the closing paren - val lastAlternative = completeSequence(sequence) - if (alternatives.length == 0) { - return lastAlternative - } else { - alternatives.push(lastAlternative) - return new AlternativesNode(alternatives) - } - - case '(' => - val indicator = pattern.substring(pIndex + 1, pIndex + 3) - if (indicator == "?=" || indicator == "?!") { - // Non-capturing test group - pIndex += 3 - val inner = parseInsideParensAndClosingParen() - new ZeroLengthTestNode(indicator, inner) - } else if (indicator == "?:") { - // Non-capturing group - pIndex += 3 - val inner = parseInsideParensAndClosingParen() - inner - } else { - // Capturing group - pIndex += 1 - val groupIndex = groupNodeMap.length - groupNodeMap.push(null) // reserve slot before parsing inner - val inner = parseInsideParensAndClosingParen() - val groupNode = new GroupNode(groupIndex, inner) - groupNodeMap(groupIndex) = groupNode - groupNode - } - - case '\\' => - @inline - def isDigit(c: Char): Boolean = c >= '0' && c <= '9' - - if (isDigit(pattern.charAt(pIndex + 1))) { - // it is a back reference; parse all following digits - val startIndex = pIndex - pIndex += 2 - while (isDigit(pattern.charAt(pIndex))) - pIndex += 1 - new BackReferenceNode( - Integer.parseInt(pattern.substring(startIndex + 1, pIndex))) - } else { - // it is a character escape - val e = pattern.substring(pIndex, pIndex + 2) - pIndex += 2 - new LeafRegexNode(e) - } - - case '[' => - // parse until the corresponding ']' - @tailrec def loop(pIndex: Int): Int = { - pattern.charAt(pIndex) match { - case '\\' => loop(pIndex + 2) - case ']' => pIndex + 1 - case _ => loop(pIndex + 1) - } - } - - val startIndex = pIndex - pIndex = loop(startIndex + 1) - val regex = pattern.substring(startIndex, pIndex) - new LeafRegexNode(regex) - - case _ => - val e = pattern.substring(pIndex, pIndex + 1) - pIndex += 1 - new LeafRegexNode(e) - } - - if (baseNode ne null) { // null if we just completed an alternative - (pattern.charAt(pIndex): @switch) match { - case '+' | '*' | '?' => - val startIndex = pIndex - if (pattern.charAt(startIndex + 1) == '?') // non-greedy mark - pIndex += 2 - else - pIndex += 1 - - val repeater = pattern.substring(startIndex, pIndex) - sequence.push(new RepeatedNode(baseNode, repeater)) - - case '{' => - // parse until end of occurrence - val startIndex = pIndex - pIndex = pattern.indexOf("}", startIndex + 1) + 1 - if (pattern.charAt(pIndex) == '?') // non-greedy mark - pIndex += 1 - val repeater = pattern.substring(startIndex, pIndex) - sequence.push(new RepeatedNode(baseNode, repeater)) - - case _ => - val sequenceLen = sequence.length - if (sequenceLen != 0 && baseNode.isInstanceOf[LeafRegexNode] && - sequence(sequenceLen - 1).isInstanceOf[LeafRegexNode]) { - val fused = new LeafRegexNode( - sequence(sequenceLen - 1).asInstanceOf[LeafRegexNode].regex + - baseNode.asInstanceOf[LeafRegexNode].regex) - sequence(sequenceLen - 1) = fused - } else { - sequence.push(baseNode) - } - } - } - } - - throw null // unreachable - // scalastyle:on return - } - } -} diff --git a/javalib/src/main/scala/java/util/regex/IndicesBuilder.scala b/javalib/src/main/scala/java/util/regex/IndicesBuilder.scala new file mode 100644 index 0000000000..85216af945 --- /dev/null +++ b/javalib/src/main/scala/java/util/regex/IndicesBuilder.scala @@ -0,0 +1,540 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.regex + +import scala.annotation.{tailrec, switch} + +import java.lang.Utils._ + +import scala.scalajs.js +import scala.scalajs.js.JSStringOps._ + +import Pattern.IndicesArray + +/** The goal of an `IndicesBuilder` is to retrieve the start and end positions + * of each group of a matching regular expression. + * + * This is essentially a polyfill for the 'd' flag of `js.RegExp`, which is + * a Stage 4 proposal scheduled for inclusion in ECMAScript 2022. Without that + * flag, `js.RegExp` only provides the substrings matched by capturing groups, + * but not their positions. We implement the positions on top of that. + * + * For that, we use the following observation: + * If the regex /A(B)\1/ matches a string at a given index, + * then /(A)(B)\2/ matches the same string at the same index. + * However, in the second regex, we can use the length of the first group (A) + * to retrieve the start position of the second group (B). + * Note that the back-references in the second regex are shifted, but this + * does not change the matched strings. + * + * Implementation details: + * - It parses the regular expression into a tree of type `Node` + * - It converts this Node to a regex string, such that every sub-part of the + * regex which was not yet in a group now belongs to a group + * - The new regex matches the original string at the original position + * - It propagates the matched strings of all groups into the Node + * - It computes the start of every group thanks to the groups before it + * - It builds and returns the mapping of previous group number -> start + * + * The `pattern` that is parsed by `IndicesBuilder` is the *compiled* JS + * pattern produced by `PatternCompiler`, not the original Java pattern. This + * means that we can simplify a number of things with the knowledge that: + * + * - the pattern is well-formed, + * - it contains no named group or named back references, and + * - a '\' is always followed by an ASCII character that is: + * - a digit, for a back reference, + * - one of `^ $ \ . * + ? ( ) [ ] { } |`, for an escape, + * - 'b' or 'B' for a word boundary, + * - 'd' or 'D' for a digit character class (used in `[\d\D]` for any code point), or + * - 'p' or 'P' followed by a `{}`-enclosed name that contains only ASCII word characters. + * + * @author Mikaël Mayer + */ +private[regex] class IndicesBuilder private (pattern: String, flags: String, + node: IndicesBuilder.Node, groupCount: Int, + jsRegExpForFind: js.RegExp, jsRegExpForMatches: js.RegExp) { + + import IndicesBuilder._ + + def apply(forMatches: Boolean, string: String, index: Int): IndicesArray = { + val regExp = + if (forMatches) jsRegExpForMatches + else jsRegExpForFind + + regExp.lastIndex = index + val allMatchResult = regExp.exec(string) + if (allMatchResult == null || allMatchResult.index != index) { + throw new AssertionError( + s"[Internal error] Executed '$regExp' on " + + s"'$string' at position $index, got an error.\n" + + s"Original pattern '$pattern' with flags '$flags' did match however.") + } + + val start = index // by definition + val end = start + undefOrForceGet(allMatchResult(0)).length() + + /* Initialize the `indices` array with: + * - `[start, end]` at index 0, which represents the whole match, and + * - `undefined` in the other slots. + * + * We explicitly store `undefined` in the other slots to prevent the array + * from containing *empty* slots. That would make it a sparse array, which + * is less efficient. + */ + val len = groupCount + 1 + val indices = new IndicesArray(len) + indices(0) = js.Array(start, end).asInstanceOf[js.Tuple2[Int, Int]] + var i = 1 + while (i != len) { + indices(i) = undefined + i += 1 + } + + node.propagate(allMatchResult, indices, start, end) + + indices + } +} + +private[regex] object IndicesBuilder { + def apply(pattern: String, flags: String): IndicesBuilder = { + val parser = new Parser(pattern) + val node = parser.parseTopLevel() + node.setNewGroup(1) + val allMatchingPattern = node.buildRegex(parser.groupNodeMap) + val jsRegExpForFind = new js.RegExp(allMatchingPattern, flags + "g") + val jsRegExpForMatches = + new js.RegExp(Pattern.wrapJSPatternForMatches(allMatchingPattern), flags) + new IndicesBuilder(pattern, flags, node, parser.parsedGroupCount, + jsRegExpForFind, jsRegExpForMatches) + } + + /** Node of the regex tree. */ + private abstract class Node { + var newGroup: Int = _ // Assigned later after the tree of nodes is built + + /** Assigns consecutive group numbers starting from newGroupIndex to the + * nodes in this subtree, in a pre-order walk. + * + * @return 1 plus the largest assigned group number. + */ + def setNewGroup(newGroupIndex: Int): Int = { + newGroup = newGroupIndex + newGroupIndex + 1 + } + + def buildRegex(groupNodeMap: js.Array[Node]): String + + /* The overall algorithm consists in, given known start and end positions + * of a parent node, determine the positions of its children. This is done + * in the main polymorphic method `propagate`, which each node implements. + * + * For some kinds of parent nodes, even when we know both their start and + * end positions, we can only determine one side of their children. + * Obvious examples are look-around nodes. Since they are zero-length, + * their start and end are always equal, but correspond to different sides + * of their children: + * + * - For look-ahead nodes (?=X) and (?!X), they correspond to the *start* of X. + * - For look-behind nodes (?<=X) and (? end - matched.length) + propagate(matchResult, indices, start, end) + } + + /** Propagates the appropriate positions to the descendants of this node + * from its start position. + * + * @return the end position of this node, as a convenience for `SequenceNode.propagate` + */ + final def propagateFromStart(matchResult: js.RegExp.ExecResult, + indices: IndicesArray, start: Int): Int = { + + val end = undefOrFold(matchResult(newGroup))(-1)(matched => start + matched.length) + propagate(matchResult, indices, start, end) + end + } + } + + /** A numbered group. */ + private final class GroupNode(val number: Int, val inner: Node) extends Node { + override def setNewGroup(newGroupIndex: Int): Int = + inner.setNewGroup(super.setNewGroup(newGroupIndex)) + + def buildRegex(groupNodeMap: js.Array[Node]): String = + "(" + inner.buildRegex(groupNodeMap) + ")" + + def propagate(matchResult: js.RegExp.ExecResult, + indices: IndicesArray, start: Int, end: Int): Unit = { + /* #3901: A GroupNode within a negative look-ahead node may receive + * `start != -1` from above, yet not match anything itself. We must + * always keep the default `-1` if this group node does not match + * anything. + */ + if (undefOrIsDefined(matchResult(newGroup))) + indices(number) = js.Array(start, end).asInstanceOf[js.Tuple2[Int, Int]] + inner.propagate(matchResult, indices, start, end) + } + } + + /** A look-around group of the form `(?= )`, `(?! )`, `(?<= )` or `(?= groupNodeMap.length) 0 + else groupNodeMap(groupNumber).newGroup + "(\\" + newGroupNumber + ")" + } + + def propagate(matchResult: js.RegExp.ExecResult, + indices: IndicesArray, start: Int, end: Int): Unit = { + // nothing to do + } + } + + /** A sequence of consecutive nodes. */ + private final class SequenceNode(val sequence: js.Array[Node]) extends Node { + override def setNewGroup(newGroupIndex: Int): Int = { + var nextIndex = super.setNewGroup(newGroupIndex) + val len = sequence.length + var i = 0 + while (i != len) { + nextIndex = sequence(i).setNewGroup(nextIndex) + i += 1 + } + nextIndex + } + + def buildRegex(groupNodeMap: js.Array[Node]): String = { + var result = "(" + val len = sequence.length + var i = 0 + while (i != len) { + result += sequence(i).buildRegex(groupNodeMap) + i += 1 + } + result + ")" + } + + def propagate(matchResult: js.RegExp.ExecResult, + indices: IndicesArray, start: Int, end: Int): Unit = { + val len = sequence.length + var i = 0 + var nextStart = start + while (i != len) { + nextStart = + sequence(i).propagateFromStart(matchResult, indices, nextStart) + i += 1 + } + } + } + + /** An alternatives node such as `ab|cd`. */ + private final class AlternativesNode(val alternatives: js.Array[Node]) + extends Node { + + override def setNewGroup(newGroupIndex: Int): Int = { + var nextIndex = super.setNewGroup(newGroupIndex) + val len = alternatives.length + var i = 0 + while (i != len) { + nextIndex = alternatives(i).setNewGroup(nextIndex) + i += 1 + } + nextIndex + } + + def buildRegex(groupNodeMap: js.Array[Node]): String = { + var result = "(" + val len = alternatives.length + var i = 0 + while (i != len) { + if (i != 0) + result += "|" + result += alternatives(i).buildRegex(groupNodeMap) + i += 1 + } + result + ")" + } + + def propagate(matchResult: js.RegExp.ExecResult, + indices: IndicesArray, start: Int, end: Int): Unit = { + val len = alternatives.length + var i = 0 + while (i != len) { + alternatives(i).propagate(matchResult, indices, start, end) + i += 1 + } + } + } + + private final class Parser(pattern0: String) { + /* Use a null-terminated string so that we don't have to check + * `pIndex < pattern.length` all the time. + */ + private[this] val pattern: String = pattern0 + ')' + + private[this] var pIndex: Int = 0 + + val groupNodeMap = js.Array[Node](null) // index 0 is not used + + def parsedGroupCount: Int = groupNodeMap.length - 1 + + def parseTopLevel(): Node = + parseInsideParensAndClosingParen() + + private def parseInsideParensAndClosingParen(): Node = { + // scalastyle:off return + val alternatives = js.Array[Node]() // completed alternatives + var sequence = js.Array[Node]() // current sequence + + // Explicitly take the sequence, otherwise we capture a `var` + def completeSequence(sequence: js.Array[Node]): Node = { + sequence.length match { + case 0 => new LeafRegexNode("") + case 1 => sequence(0) + case _ => new SequenceNode(sequence) + } + } + + while (true) { + /* Parse the pattern by code points if RegExp supports the 'u' flag, + * in which case PatternCompiler always uses it, or by chars if it + * doesn't. This distinction is important for repeated surrogate pairs. + */ + val dispatchCP = + if (PatternCompiler.Support.supportsUnicode) pattern.codePointAt(pIndex) + else pattern.charAt(pIndex).toInt + + val baseNode = (dispatchCP: @switch) match { + case '|' => + // Complete one alternative + alternatives.push(completeSequence(sequence)) + sequence = js.Array[Node]() + pIndex += 1 + null + + case ')' => + // Complete the last alternative + pIndex += 1 // go past the closing paren + val lastAlternative = completeSequence(sequence) + if (alternatives.length == 0) { + return lastAlternative + } else { + alternatives.push(lastAlternative) + return new AlternativesNode(alternatives) + } + + case '(' => + val indicator = pattern.jsSubstring(pIndex + 1, pIndex + 3) + if (indicator == "?=" || indicator == "?!") { + // Look-ahead group + pIndex += 3 + val inner = parseInsideParensAndClosingParen() + new LookAroundNode(isLookBehind = false, indicator, inner) + } else if (indicator == "?<") { + // Look-behind group, which must be ?<= or ? + @inline + def isDigit(c: Char): Boolean = c >= '0' && c <= '9' + + val startIndex = pIndex + val c = pattern.charAt(startIndex + 1) + pIndex += 2 + + if (isDigit(c)) { + // it is a back reference; parse all following digits + while (isDigit(pattern.charAt(pIndex))) + pIndex += 1 + new BackReferenceNode( + Integer.parseInt(pattern.jsSubstring(startIndex + 1, pIndex))) + } else { + // it is a character escape, or one of \b, \B, \d, \D, \p{...} or \P{...} + if (c == 'p' || c == 'P') { + while (pattern.charAt(pIndex) != '}') + pIndex += 1 + pIndex += 1 + } + new LeafRegexNode(pattern.jsSubstring(startIndex, pIndex)) + } + + case '[' => + // parse until the corresponding ']' (here surrogate pairs don't matter) + @tailrec def loop(pIndex: Int): Int = { + pattern.charAt(pIndex) match { + case '\\' => loop(pIndex + 2) // this is also fine for \p{...} and \P{...} + case ']' => pIndex + 1 + case _ => loop(pIndex + 1) + } + } + + val startIndex = pIndex + pIndex = loop(startIndex + 1) + val regex = pattern.jsSubstring(startIndex, pIndex) + new LeafRegexNode(regex) + + case _ => + val start = pIndex + pIndex += Character.charCount(dispatchCP) + new LeafRegexNode(pattern.jsSubstring(start, pIndex)) + } + + if (baseNode ne null) { // null if we just completed an alternative + (pattern.charAt(pIndex): @switch) match { + case '+' | '*' | '?' => + val startIndex = pIndex + if (pattern.charAt(startIndex + 1) == '?') // non-greedy mark + pIndex += 2 + else + pIndex += 1 + + val repeater = pattern.jsSubstring(startIndex, pIndex) + sequence.push(new RepeatedNode(baseNode, repeater)) + + case '{' => + // parse until end of occurrence + val startIndex = pIndex + pIndex = pattern.indexOf("}", startIndex + 1) + 1 + if (pattern.charAt(pIndex) == '?') // non-greedy mark + pIndex += 1 + val repeater = pattern.jsSubstring(startIndex, pIndex) + sequence.push(new RepeatedNode(baseNode, repeater)) + + case _ => + val sequenceLen = sequence.length + if (sequenceLen != 0 && baseNode.isInstanceOf[LeafRegexNode] && + sequence(sequenceLen - 1).isInstanceOf[LeafRegexNode]) { + val fused = new LeafRegexNode( + sequence(sequenceLen - 1).asInstanceOf[LeafRegexNode].regex + + baseNode.asInstanceOf[LeafRegexNode].regex) + sequence(sequenceLen - 1) = fused + } else { + sequence.push(baseNode) + } + } + } + } + + throw null // unreachable + // scalastyle:on return + } + } +} diff --git a/javalib/src/main/scala/java/util/regex/Matcher.scala b/javalib/src/main/scala/java/util/regex/Matcher.scala index 48bda1aac9..07f94a8076 100644 --- a/javalib/src/main/scala/java/util/regex/Matcher.scala +++ b/javalib/src/main/scala/java/util/regex/Matcher.scala @@ -12,29 +12,31 @@ package java.util.regex -import scala.language.implicitConversions +import java.lang.Utils._ import scala.annotation.switch import scala.scalajs.js +import Pattern.IndicesArray + final class Matcher private[regex] ( - private var pattern0: Pattern, private var input0: CharSequence, - private var regionStart0: Int, private var regionEnd0: Int) + private var pattern0: Pattern, private var input0: String) extends AnyRef with MatchResult { import Matcher._ def pattern(): Pattern = pattern0 - // Configuration (updated manually) - private var regexp = pattern0.newJSRegExp() - private var inputstr = input0.subSequence(regionStart0, regionEnd0).toString + // Region configuration (updated by reset() and region()) + private var regionStart0 = 0 + private var regionEnd0 = input0.length() + private var inputstr = input0 // Match result (updated by successful matches) + private var position: Int = 0 // within `inputstr`, not `input0` private var lastMatch: js.RegExp.ExecResult = null - private var lastMatchIsValid = false - private var canStillFind = true + private var lastMatchIsForMatches = false // Append state (updated by replacement methods) private var appendPos: Int = 0 @@ -42,48 +44,41 @@ final class Matcher private[regex] ( // Lookup methods def matches(): Boolean = { - reset() - find() - // TODO this check is wrong with non-greedy patterns - // Further, it might be wrong to just use ^$ delimiters for two reasons: - // - They might already be there - // - They might not behave as expected when newline characters are present - if ((lastMatch ne null) && (start != 0 || end != inputstr.length)) - reset() + resetMatch() + + lastMatch = pattern().execMatches(inputstr) + lastMatchIsForMatches = true lastMatch ne null } def lookingAt(): Boolean = { - reset() + resetMatch() find() - if ((lastMatch ne null) && (start != 0)) - reset() + if ((lastMatch ne null) && (ensureLastMatch.index != 0)) + resetMatch() lastMatch ne null } - def find(): Boolean = if (canStillFind) { - lastMatchIsValid = true - lastMatch = regexp.exec(inputstr) - if (lastMatch ne null) { - if (lastMatch(0).get.isEmpty) - regexp.lastIndex += 1 - } else { - canStillFind = false - } - startOfGroupCache = null - lastMatch ne null - } else false + def find(): Boolean = { + val (mtch, end) = pattern().execFind(inputstr, position) + position = + if (mtch ne null) (if (end == mtch.index) end + 1 else end) + else inputstr.length() + 1 // cannot find anymore + lastMatch = mtch + lastMatchIsForMatches = false + mtch ne null + } def find(start: Int): Boolean = { reset() - regexp.lastIndex = start + position = start find() } // Replace methods def appendReplacement(sb: StringBuffer, replacement: String): Matcher = { - sb.append(inputstr.substring(appendPos, start)) + sb.append(inputstr.substring(appendPos, start())) @inline def isDigit(c: Char) = c >= '0' && c <= '9' @@ -97,7 +92,9 @@ final class Matcher private[regex] ( while (i < len && isDigit(replacement.charAt(i))) i += 1 val group = Integer.parseInt(replacement.substring(j, i)) - sb.append(this.group(group)) + val replaced = this.group(group) + if (replaced != null) + sb.append(replaced) case '\\' => i += 1 @@ -111,7 +108,7 @@ final class Matcher private[regex] ( } } - appendPos = end + appendPos = end() this } @@ -148,31 +145,30 @@ final class Matcher private[regex] ( // Reset methods - def reset(): Matcher = { - regexp.lastIndex = 0 + private def resetMatch(): Matcher = { + position = 0 lastMatch = null - lastMatchIsValid = false - canStillFind = true appendPos = 0 - startOfGroupCache = null this } - def reset(input: CharSequence): Matcher = { + def reset(): Matcher = { regionStart0 = 0 - regionEnd0 = input.length() - input0 = input - inputstr = input0.toString + regionEnd0 = input0.length() + inputstr = input0 + resetMatch() + } + + @inline // `input` is almost certainly a String at call site + def reset(input: CharSequence): Matcher = { + input0 = input.toString() reset() } def usePattern(pattern: Pattern): Matcher = { - val prevLastIndex = regexp.lastIndex + // note that `position` and `appendPos` are left unchanged pattern0 = pattern - regexp = pattern.newJSRegExp() - regexp.lastIndex = prevLastIndex lastMatch = null - startOfGroupCache = null this } @@ -184,64 +180,69 @@ final class Matcher private[regex] ( lastMatch } - def groupCount(): Int = Matcher.getGroupCount(lastMatch, pattern()) + def groupCount(): Int = pattern().groupCount - def start(): Int = ensureLastMatch.index + def start(): Int = ensureLastMatch.index + regionStart() def end(): Int = start() + group().length - def group(): String = ensureLastMatch(0).get + def group(): String = undefOrForceGet(ensureLastMatch(0)) - def start(group: Int): Int = { - if (group == 0) start() - else startOfGroup(group) - } + private def indices: IndicesArray = + pattern().getIndices(ensureLastMatch, lastMatchIsForMatches) - def end(group: Int): Int = { - val s = start(group) - if (s == -1) -1 - else s + this.group(group).length - } + private def startInternal(compiledGroup: Int): Int = + undefOrFold(indices(compiledGroup))(-1)(_._1 + regionStart()) - def group(group: Int): String = ensureLastMatch(group).orNull + def start(group: Int): Int = + startInternal(pattern().numberedGroup(group)) - def group(name: String): String = { - ensureLastMatch - throw new IllegalArgumentException - } + def start(name: String): Int = + startInternal(pattern().namedGroup(name)) + + private def endInternal(compiledGroup: Int): Int = + undefOrFold(indices(compiledGroup))(-1)(_._2 + regionStart()) + + def end(group: Int): Int = + endInternal(pattern().numberedGroup(group)) + + def end(name: String): Int = + endInternal(pattern().namedGroup(name)) + + def group(group: Int): String = + undefOrGetOrNull(ensureLastMatch(pattern().numberedGroup(group))) + + def group(name: String): String = + undefOrGetOrNull(ensureLastMatch(pattern().namedGroup(name))) // Seal the state def toMatchResult(): MatchResult = - new SealedResult(inputstr, lastMatch, pattern(), startOfGroupCache) + new SealedResult(lastMatch, lastMatchIsForMatches, pattern(), regionStart()) // Other query state methods - def hitEnd(): Boolean = - lastMatchIsValid && (lastMatch == null || end() == inputstr.length) + // Cannot be implemented (see #3454) + //def hitEnd(): Boolean - //def requireEnd(): Boolean // I don't understand the spec + // Similar difficulties as with hitEnd() + //def requireEnd(): Boolean - // Stub methods for region management + // Region management def regionStart(): Int = regionStart0 def regionEnd(): Int = regionEnd0 - def region(start: Int, end: Int): Matcher = - new Matcher(pattern0, input0, start, end) + + def region(start: Int, end: Int): Matcher = { + regionStart0 = start + regionEnd0 = end + inputstr = input0.substring(start, end) + resetMatch() + } def hasTransparentBounds(): Boolean = false //def useTransparentBounds(b: Boolean): Matcher def hasAnchoringBounds(): Boolean = true //def useAnchoringBounds(b: Boolean): Matcher - - // Lazily computed by `startOfGroup`, reset every time `lastMatch` changes - private var startOfGroupCache: js.Array[Int] = _ - - /** Returns a mapping from the group number to the respective start position. */ - private def startOfGroup: js.Array[Int] = { - if (startOfGroupCache eq null) - startOfGroupCache = pattern0.groupStartMapper(inputstr, start()) - startOfGroupCache - } } object Matcher { @@ -259,44 +260,31 @@ object Matcher { result } - private def getGroupCount(lastMatch: js.RegExp.ExecResult, - pattern: Pattern): Int = { - /* `pattern.groupCount` has the answer, but it can require some - * computation to get it, so try and use lastMatch's group count if we can. - */ - if (lastMatch != null) lastMatch.length - 1 - else pattern.groupCount - } - - private final class SealedResult(inputstr: String, - lastMatch: js.RegExp.ExecResult, pattern: Pattern, - private var startOfGroupCache: js.Array[Int]) + private final class SealedResult(lastMatch: js.RegExp.ExecResult, + lastMatchIsForMatches: Boolean, pattern: Pattern, regionStart: Int) extends MatchResult { - def groupCount(): Int = getGroupCount(lastMatch, pattern) + def groupCount(): Int = pattern.groupCount - def start(): Int = ensureLastMatch.index + def start(): Int = ensureLastMatch.index + regionStart def end(): Int = start() + group().length - def group(): String = ensureLastMatch(0).get + def group(): String = undefOrForceGet(ensureLastMatch(0)) - private def startOfGroup: js.Array[Int] = { - if (startOfGroupCache eq null) - startOfGroupCache = pattern.groupStartMapper(inputstr, start()) - startOfGroupCache - } + private def indices: IndicesArray = + pattern.getIndices(ensureLastMatch, lastMatchIsForMatches) - def start(group: Int): Int = { - if (group == 0) start() - else startOfGroup(group) - } + /* Note that MatchResult does *not* define the named versions of `group`, + * `start` and `end`, so we don't have them here either. + */ - def end(group: Int): Int = { - val s = start(group) - if (s == -1) -1 - else s + this.group(group).length - } + def start(group: Int): Int = + undefOrFold(indices(pattern.numberedGroup(group)))(-1)(_._1 + regionStart) + + def end(group: Int): Int = + undefOrFold(indices(pattern.numberedGroup(group)))(-1)(_._2 + regionStart) - def group(group: Int): String = ensureLastMatch(group).orNull + def group(group: Int): String = + undefOrGetOrNull(ensureLastMatch(pattern.numberedGroup(group))) private def ensureLastMatch: js.RegExp.ExecResult = { if (lastMatch == null) diff --git a/javalib/src/main/scala/java/util/regex/Pattern.scala b/javalib/src/main/scala/java/util/regex/Pattern.scala index 5ff459105e..05ee30db58 100644 --- a/javalib/src/main/scala/java/util/regex/Pattern.scala +++ b/javalib/src/main/scala/java/util/regex/Pattern.scala @@ -12,61 +12,171 @@ package java.util.regex -import scala.annotation.switch +import scala.annotation.tailrec + +import java.lang.Utils._ +import java.util.ScalaOps._ import scala.scalajs.js -import java.util.ScalaOps._ +import PatternCompiler.Support._ -final class Pattern private (jsRegExp: js.RegExp, _pattern: String, _flags: Int) - extends Serializable { +final class Pattern private[regex] ( + _pattern: String, + _flags: Int, + jsPattern: String, + jsFlags: String, + sticky: Boolean, + private[regex] val groupCount: Int, + groupNumberMap: js.Array[Int], + namedGroups: js.Dictionary[Int] +) extends Serializable { import Pattern._ - def pattern(): String = _pattern - def flags(): Int = _flags + @inline private def jsFlagsForFind: String = + jsFlags + (if (sticky && supportsSticky) "gy" else "g") + + /** Whether we already added the 'd' flag to the native RegExp's. */ + private var enabledNativeIndices: Boolean = false + + /** The RegExp that is used for `Matcher.find()`. + * + * It receives the 'g' flag so that `lastIndex` is taken into acount. + * + * It also receives the 'y' flag if this pattern is sticky and it is + * supported. If it is not supported, its behavior is polyfilled in + * `execFind()`. + * + * Since that RegExp is only used locally within `execFind()`, we can + * always reuse the same instance. + */ + private[this] var jsRegExpForFind = + new js.RegExp(jsPattern, jsFlagsForFind) + + /** Another version of the RegExp that is used by `Matcher.matches()`. + * + * It forces `^` and `$` at the beginning and end of the pattern so that + * only entire inputs are matched. In addition, it does not have the 'g' + * flag, so that it can be repeatedly used without managing `lastIndex`. + * + * Since that RegExp is only used locally within `execMatches()`, we can + * always reuse the same instance. + */ + private[this] var jsRegExpForMatches: js.RegExp = + new js.RegExp(wrapJSPatternForMatches(jsPattern), jsFlags) - private def jsPattern: String = jsRegExp.source + private lazy val indicesBuilder: IndicesBuilder = + IndicesBuilder(jsPattern, jsFlags) - private def jsFlags: String = { - (if (jsRegExp.global) "g" else "") + - (if (jsRegExp.ignoreCase) "i" else "") + - (if (jsRegExp.multiline) "m" else "") + private[regex] def execMatches(input: String): js.RegExp.ExecResult = + jsRegExpForMatches.exec(input) + + @inline // to stack-allocate the tuple + private[regex] def execFind(input: String, start: Int): (js.RegExp.ExecResult, Int) = { + val mtch = execFindInternal(input, start) + val end = jsRegExpForFind.lastIndex + (mtch, end) } - private[regex] lazy val groupCount: Int = - new js.RegExp("|" + jsPattern).exec("").length - 1 + private def execFindInternal(input: String, start: Int): js.RegExp.ExecResult = { + val regexp = jsRegExpForFind + + if (!supportsSticky && sticky) { + regexp.lastIndex = start + val mtch = regexp.exec(input) + if (mtch == null || mtch.index > start) + null + else + mtch + } else if (supportsUnicode) { + regexp.lastIndex = start + regexp.exec(input) + } else { + /* When the native RegExp does not support the 'u' flag (introduced in + * ECMAScript 2015), it can find a match starting in the middle of a + * surrogate pair. This can happen if the pattern can match a substring + * starting with a lone low surrogate. However, that is not valid, + * because surrogate pairs must always stick together. + * + * In all the other situations, the `PatternCompiler` makes sure that + * surrogate pairs are always matched together or not at all, but it + * cannot avoid this specific situation because there is no look-behind + * support in that case either. So we take care of it now by skipping + * matches that start in the middle of a surrogate pair. + */ + @tailrec + def loop(start: Int): js.RegExp.ExecResult = { + regexp.lastIndex = start + val mtch = regexp.exec(input) + if (mtch == null) { + null + } else { + val index = mtch.index + if (index > start && index < input.length() && + Character.isLowSurrogate(input.charAt(index)) && + Character.isHighSurrogate(input.charAt(index - 1))) { + loop(index + 1) + } else { + mtch + } + } + } + loop(start) + } + } - private[regex] lazy val groupStartMapper: GroupStartMapper = - GroupStartMapper(jsPattern, jsFlags) + private[regex] def numberedGroup(group: Int): Int = { + if (group < 0 || group > groupCount) + throw new IndexOutOfBoundsException(group.toString()) + groupNumberMap(group) + } - override def toString(): String = pattern + private[regex] def namedGroup(name: String): Int = { + groupNumberMap(dictGetOrElse(namedGroups, name) { + throw new IllegalArgumentException(s"No group with name <$name>") + }) + } - private[regex] def newJSRegExp(): js.RegExp = { - val r = new js.RegExp(jsRegExp) - if (r ne jsRegExp) { - r - } else { - /* Workaround for the PhantomJS 1.x bug - * https://github.com/ariya/phantomjs/issues/11494 - * which causes new js.RegExp(jsRegExp) to return the same object, - * rather than a new one. - * We therefore reconstruct the pattern and flags used to create - * jsRegExp and create a new one from there. - */ - new js.RegExp(jsPattern, jsFlags) + private[regex] def getIndices(lastMatch: js.RegExp.ExecResult, forMatches: Boolean): IndicesArray = { + val lastMatchDyn = lastMatch.asInstanceOf[js.Dynamic] + if (isUndefined(lastMatchDyn.indices)) { + if (supportsIndices) { + if (!enabledNativeIndices) { + jsRegExpForFind = new js.RegExp(jsPattern, jsFlagsForFind + "d") + jsRegExpForMatches = new js.RegExp(wrapJSPatternForMatches(jsPattern), jsFlags + "d") + enabledNativeIndices = true + } + val regexp = if (forMatches) jsRegExpForMatches else jsRegExpForFind + regexp.lastIndex = lastMatch.index + lastMatchDyn.indices = regexp.exec(lastMatch.input).asInstanceOf[js.Dynamic].indices + } else { + lastMatchDyn.indices = indicesBuilder(forMatches, lastMatch.input, lastMatch.index) + } } + lastMatchDyn.indices.asInstanceOf[IndicesArray] } + // Public API --------------------------------------------------------------- + + def pattern(): String = _pattern + def flags(): Int = _flags + + override def toString(): String = pattern() + + @inline // `input` is almost certainly a String at call site def matcher(input: CharSequence): Matcher = - new Matcher(this, input, 0, input.length) + new Matcher(this, input.toString()) + @inline // `input` is almost certainly a String at call site def split(input: CharSequence): Array[String] = split(input, 0) - def split(input: CharSequence, limit: Int): Array[String] = { - val inputStr = input.toString + @inline // `input` is almost certainly a String at call site + def split(input: CharSequence, limit: Int): Array[String] = + split(input.toString(), limit) + private def split(inputStr: String, limit: Int): Array[String] = { // If the input string is empty, always return Array("") - #987, #2592 if (inputStr == "") { Array("") @@ -74,45 +184,40 @@ final class Pattern private (jsRegExp: js.RegExp, _pattern: String, _flags: Int) // Actually split original string val lim = if (limit > 0) limit else Int.MaxValue val matcher = this.matcher(inputStr) - val builder = Array.newBuilder[String] + val result = js.Array[String]() var prevEnd = 0 - var size = 0 - while ((size < lim-1) && matcher.find()) { - if (matcher.end == 0) { + while ((result.length < lim - 1) && matcher.find()) { + if (matcher.end() == 0) { /* If there is a zero-width match at the beginning of the string, * ignore it, i.e., omit the resulting empty string at the beginning * of the array. */ } else { - builder += inputStr.substring(prevEnd, matcher.start) - size += 1 + result.push(inputStr.substring(prevEnd, matcher.start())) } - prevEnd = matcher.end + prevEnd = matcher.end() } - builder += inputStr.substring(prevEnd) - val result = builder.result() + result.push(inputStr.substring(prevEnd)) // With `limit == 0`, remove trailing empty strings. - if (limit != 0) { - result - } else { - var actualLength = result.length + var actualLength = result.length + if (limit == 0) { while (actualLength != 0 && result(actualLength - 1) == "") actualLength -= 1 - - if (actualLength == result.length) { - result - } else { - val actualResult = new Array[String](actualLength) - System.arraycopy(result, 0, actualResult, 0, actualLength) - actualResult - } } + + // Build result array + val r = new Array[String](actualLength) + for (i <- 0 until actualLength) + r(i) = result(i) + r } } } object Pattern { + private[regex] type IndicesArray = js.Array[js.UndefOr[js.Tuple2[Int, Int]]] + final val UNIX_LINES = 0x01 final val CASE_INSENSITIVE = 0x02 final val COMMENTS = 0x04 @@ -123,95 +228,32 @@ object Pattern { final val CANON_EQ = 0x80 final val UNICODE_CHARACTER_CLASS = 0x100 - def compile(regex: String, flags: Int): Pattern = { - val (jsPattern, flags1) = { - if ((flags & LITERAL) != 0) { - (quote(regex), flags) - } else { - trySplitHack(regex, flags) orElse - tryFlagHack(regex, flags) getOrElse - (regex, flags) - } - } - - val jsFlags = { - "g" + - (if ((flags1 & CASE_INSENSITIVE) != 0) "i" else "") + - (if ((flags1 & MULTILINE) != 0) "m" else "") - } - - val jsRegExp = new js.RegExp(jsPattern, jsFlags) - - new Pattern(jsRegExp, regex, flags1) - } + def compile(regex: String, flags: Int): Pattern = + PatternCompiler.compile(regex, flags) def compile(regex: String): Pattern = compile(regex, 0) + @inline // `input` is almost certainly a String at call site def matches(regex: String, input: CharSequence): Boolean = + matches(regex, input.toString()) + + private def matches(regex: String, input: String): Boolean = compile(regex).matcher(input).matches() def quote(s: String): String = { - var result = "" - var i = 0 - while (i < s.length) { - val c = s.charAt(i) - result += ((c: @switch) match { - case '\\' | '.' | '(' | ')' | '[' | ']' | '{' | '}' | '|' - | '?' | '*' | '+' | '^' | '$' => "\\"+c - case _ => c - }) - i += 1 + var result = "\\Q" + var start = 0 + var end = s.indexOf("\\E", start) + while (end >= 0) { + result += s.substring(start, end) + "\\E\\\\E\\Q" + start = end + 2 + end = s.indexOf("\\E", start) } - result + result + s.substring(start) + "\\E" } - /** This is a hack to support StringLike.split(). - * It replaces occurrences of \Q\E by quoted() - */ @inline - private def trySplitHack(pat: String, flags: Int) = { - val m = splitHackPat.exec(pat) - if (m != null) - Some((quote(m(1).get), flags)) - else - None - } - - @inline - private def tryFlagHack(pat: String, flags0: Int) = { - val m = flagHackPat.exec(pat) - if (m != null) { - val newPat = pat.substring(m(0).get.length) // cut off the flag specifiers - var flags = flags0 - for (chars <- m(1)) { - for (i <- 0 until chars.length()) - flags |= charToFlag(chars.charAt(i)) - } - for (chars <- m(2)) { - for (i <- 0 until chars.length()) - flags &= ~charToFlag(chars.charAt(i)) - } - Some((newPat, flags)) - } else - None - } - - private def charToFlag(c: Char) = (c: @switch) match { - case 'i' => CASE_INSENSITIVE - case 'd' => UNIX_LINES - case 'm' => MULTILINE - case 's' => DOTALL - case 'u' => UNICODE_CASE - case 'x' => COMMENTS - case 'U' => UNICODE_CHARACTER_CLASS - case _ => throw new IllegalArgumentException("bad in-pattern flag") - } - - /** matches \Q\E to support StringLike.split */ - private val splitHackPat = new js.RegExp("^\\\\Q(.|\\n|\\r)\\\\E$") - - /** regex to match flag specifiers in regex. E.g. (?u), (?-i), (?U-i) */ - private val flagHackPat = - new js.RegExp("^\\(\\?([idmsuxU]*)(?:-([idmsuxU]*))?\\)") + private[regex] def wrapJSPatternForMatches(jsPattern: String): String = + "^(?:" + jsPattern + ")$" // the group is needed if there is a top-level | in jsPattern } diff --git a/javalib/src/main/scala/java/util/regex/PatternCompiler.scala b/javalib/src/main/scala/java/util/regex/PatternCompiler.scala new file mode 100644 index 0000000000..cb9974f382 --- /dev/null +++ b/javalib/src/main/scala/java/util/regex/PatternCompiler.scala @@ -0,0 +1,1854 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.regex + +import scala.annotation.{switch, tailrec} + +import java.lang.Character.{ + charCount, + isBmpCodePoint, + highSurrogate, + lowSurrogate, + MIN_HIGH_SURROGATE, + MAX_HIGH_SURROGATE, + MIN_LOW_SURROGATE, + MAX_LOW_SURROGATE +} + +import java.lang.Utils._ +import java.util.ScalaOps._ + +import scala.scalajs.js +import scala.scalajs.js.JSStringOps.enableJSStringOps +import scala.scalajs.runtime.linkingInfo +import scala.scalajs.LinkingInfo.ESVersion + +/** Compiler from Java regular expressions to JavaScript regular expressions. + * + * See `README.md` in this directory for the design. + * + * !!! PLEASE (re-)read the README before modifying this class. !!! + * + * There are very intricate concerns that are cross-cutting all over the + * class, and assumptions are not local! + */ +private[regex] object PatternCompiler { + import Pattern._ + + def compile(regex: String, flags: Int): Pattern = + new PatternCompiler(regex, flags).compile() + + /** RegExp to match leading embedded flag specifiers in a pattern. + * + * E.g. (?u), (?-i), (?U-i) + */ + private val leadingEmbeddedFlagSpecifierRegExp = + new js.RegExp("^\\(\\?([idmsuxU]*)(?:-([idmsuxU]*))?\\)") + + /** RegExp to renumber backreferences (used for possessive quantifiers). */ + private val renumberingRegExp = + new js.RegExp("(\\\\+)(\\d+)", "g") + + /** Returns the flag that corresponds to an embedded flag specifier. */ + private def charToFlag(c: Char): Int = (c: @switch) match { + case 'i' => CASE_INSENSITIVE + case 'd' => UNIX_LINES + case 'm' => MULTILINE + case 's' => DOTALL + case 'u' => UNICODE_CASE + case 'x' => COMMENTS + case 'U' => UNICODE_CHARACTER_CLASS + case _ => throw new IllegalArgumentException("bad in-pattern flag") + } + + private def featureTest(flags: String): Boolean = { + try { + new js.RegExp("", flags) + true + } catch { + case _: Throwable => + false + } + } + + /** Cache for `Support.supportsUnicode`. */ + private val _supportsUnicode = + (linkingInfo.esVersion >= ESVersion.ES2015) || featureTest("u") + + /** Cache for `Support.supportsSticky`. */ + private val _supportsSticky = + (linkingInfo.esVersion >= ESVersion.ES2015) || featureTest("y") + + /** Cache for `Support.supportsDotAll`. */ + private val _supportsDotAll = + (linkingInfo.esVersion >= ESVersion.ES2018) || featureTest("us") + + /** Cache for `Support.supportsIndices`. */ + private val _supportsIndices = + featureTest("d") + + /** Feature-test methods. + * + * They are located in a separate object so that the methods can be fully + * inlined and optimized away, without leaving a `LoadModule` of the + * enclosing object behind, depending on the target ES version. + */ + private[regex] object Support { + /** Tests whether the underlying JS RegExp supports the 'u' flag. */ + @inline + def supportsUnicode: Boolean = + (linkingInfo.esVersion >= ESVersion.ES2015) || _supportsUnicode + + /** Tests whether the underlying JS RegExp supports the 'y' flag. */ + @inline + def supportsSticky: Boolean = + (linkingInfo.esVersion >= ESVersion.ES2015) || _supportsSticky + + /** Tests whether the underlying JS RegExp supports the 's' flag. */ + @inline + def supportsDotAll: Boolean = + (linkingInfo.esVersion >= ESVersion.ES2018) || _supportsDotAll + + /** Tests whether the underlying JS RegExp supports the 'd' flag. */ + @inline + def supportsIndices: Boolean = + _supportsIndices + + /** Tests whether features requiring support for the 'u' flag are enabled. + * + * They are enabled if and only if the project is configured to rely on + * ECMAScript 2015 features. + */ + @inline + def enableUnicodeCaseInsensitive: Boolean = + linkingInfo.esVersion >= ESVersion.ES2015 + + /** Tests whether features requiring \p{} and/or look-behind assertions are enabled. + * + * They are enabled if and only if the project is configured to rely on + * ECMAScript 2018 features. + */ + @inline + def enableUnicodeCharacterClassesAndLookBehinds: Boolean = + linkingInfo.esVersion >= ESVersion.ES2018 + } + + import Support._ + + // Helpers to deal with surrogate pairs when the 'u' flag is not supported + + private def codePointNotAmong(characters: String): String = { + if (supportsUnicode) { + if (characters != "") + "[^" + characters + "]" + else if (supportsDotAll) + "." // we always add the 's' flag when it is supported, so we can use "." here + else + "[\\d\\D]" // In theory, "[^]" works, but XRegExp does not trust JS engines on that, so we don't either + } else { + val highCharRange = s"$MIN_HIGH_SURROGATE-$MAX_HIGH_SURROGATE" + val lowCharRange = s"$MIN_LOW_SURROGATE-$MAX_LOW_SURROGATE" + val highCPOrSupplementaryCP = s"[$highCharRange](?:[$lowCharRange]|(?![$lowCharRange]))" + s"(?:[^$characters$highCharRange]|$highCPOrSupplementaryCP)" + } + } + + // Other helpers + + /** Helpers that are always inlined; kept in a separate object so that they + * can be inlined without cost. + */ + private object InlinedHelpers { + /* isHighSurrogateCP, isLowSurrogateCP and toCodePointCP are like the + * non-CP equivalents in Character, but they take Int code point + * parameters. The implementation strategy is the same as the methods for + * Chars. The magical constants are copied from Character and extended to + * 32 bits. + */ + + private final val HighSurrogateCPMask = 0xfffffc00 // ffff 111111 00 00000000 + private final val HighSurrogateCPID = 0x0000d800 // 0000 110110 00 00000000 + private final val LowSurrogateCPMask = 0xfffffc00 // ffff 111111 00 00000000 + private final val LowSurrogateCPID = 0x0000dc00 // 0000 110111 00 00000000 + private final val SurrogateUsefulPartMask = 0x000003ff // 0000 000000 11 11111111 + + private final val HighSurrogateShift = 10 + private final val HighSurrogateAddValue = 0x10000 >> HighSurrogateShift + + @inline def isHighSurrogateCP(cp: Int): Boolean = + (cp & HighSurrogateCPMask) == HighSurrogateCPID + + @inline def isLowSurrogateCP(cp: Int): Boolean = + (cp & LowSurrogateCPMask) == LowSurrogateCPID + + @inline def toCodePointCP(high: Int, low: Int): Int = { + (((high & SurrogateUsefulPartMask) + HighSurrogateAddValue) << HighSurrogateShift) | + (low & SurrogateUsefulPartMask) + } + + @inline def isLetter(c: Char): Boolean = + (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') + + @inline def isDigit(c: Char): Boolean = + c >= '0' && c <= '9' + + @inline def isLetterOrDigit(c: Char): Boolean = + isLetter(c) || isDigit(c) + + @inline def isHexDigit(c: Char): Boolean = + isDigit(c) || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f') + + @inline def parseInt(s: String, radix: Int): Int = + js.Dynamic.global.parseInt(s, radix).asInstanceOf[Int] + } + + import InlinedHelpers._ + + private def codePointToString(codePoint: Int): String = { + if (linkingInfo.esVersion >= ESVersion.ES2015) { + js.Dynamic.global.String.fromCodePoint(codePoint).asInstanceOf[String] + } else { + if (isBmpCodePoint(codePoint)) { + js.Dynamic.global.String.fromCharCode(codePoint).asInstanceOf[String] + } else { + js.Dynamic.global.String + .fromCharCode(highSurrogate(codePoint).toInt, lowSurrogate(codePoint).toInt) + .asInstanceOf[String] + } + } + } + + // Everything for compiling character classes + + /* This should be a sealed class with subclasses that we pattern-match on. + * However, to cut costs in terms of code size, we use a single class with a + * `kind` field. + */ + private final class CompiledCharClass(val kind: Int, val data: String) { + import CompiledCharClass._ + + lazy val negated: CompiledCharClass = + new CompiledCharClass(kind ^ 1, data) + } + + // This object is entirely inlined and DCE'ed. Keep it that way. + private object CompiledCharClass { + /** Represents `\p{data}`. */ + final val PosP = 0 + + /** Represents `\P{data}`. */ + final val NegP = 1 + + /** Represents `[data]`. */ + final val PosClass = 2 + + /** Represents `[^data]`. */ + final val NegClass = 3 + + @inline def posP(name: String): CompiledCharClass = + new CompiledCharClass(PosP, name) + + @inline def negP(name: String): CompiledCharClass = + new CompiledCharClass(NegP, name) + + @inline def posClass(content: String): CompiledCharClass = + new CompiledCharClass(PosClass, content) + + @inline def negClass(content: String): CompiledCharClass = + new CompiledCharClass(NegClass, content) + } + + private val ASCIIDigit = CompiledCharClass.posClass("0-9") + private val UnicodeDigit = CompiledCharClass.posP("Nd") + + private val UniversalHorizontalWhiteSpace = + CompiledCharClass.posClass("\t \u00A0\u1680\u180E\u2000-\u200A\u202F\u205F\u3000") + + private val ASCIIWhiteSpace = CompiledCharClass.posClass("\t-\r ") + private val UnicodeWhitespace = CompiledCharClass.posP("White_Space") + + private val UniversalVerticalWhiteSpace = CompiledCharClass.posClass("\n-\r\u0085\u2028\u2029") + + private val ASCIIWordChar = CompiledCharClass.posClass("a-zA-Z_0-9") + private val UnicodeWordChar = + CompiledCharClass.posClass("\\p{Alphabetic}\\p{Mn}\\p{Me}\\p{Mc}\\p{Nd}\\p{Pc}\\p{Join_Control}") + + /** Mapping from POSIX character class to the character set to use when + * `UNICODE_CHARACTER_CLASSES` is *not* set. + * + * This is a `js.Dictionary` because it can be used even when compiling to + * ECMAScript 5.1. + */ + private val asciiPOSIXCharacterClasses: js.Dictionary[CompiledCharClass] = { + import CompiledCharClass._ + + val r = dictEmpty[CompiledCharClass]() + dictSet(r, "Lower", posClass("a-z")) + dictSet(r, "Upper", posClass("A-Z")) + dictSet(r, "ASCII", posClass("\u0000-\u007f")) + dictSet(r, "Alpha", posClass("A-Za-z")) // [\p{Lower}\p{Upper}] + dictSet(r, "Digit", posClass("0-9")) + dictSet(r, "Alnum", posClass("0-9A-Za-z")) // [\p{Alpha}\p{Digit}] + dictSet(r, "Punct", posClass("!-/:-@[-`{-~")) // One of !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ + dictSet(r, "Graph", posClass("!-~")) // [\p{Alnum}\p{Punct}] + dictSet(r, "Print", posClass(" -~")) // [\p{Graph}\x20] + dictSet(r, "Blank", posClass("\t ")) + dictSet(r, "Cntrl", posClass("\u0000-\u001f\u007f")) + dictSet(r, "XDigit", posClass("0-9A-Fa-f")) + dictSet(r, "Space", posClass("\t-\r ")) // [ \t\n\x0B\f\r] + r + } + + /** Mapping of predefined character classes to the corresponding character + * set. + * + * Mappings that also exist in `asciiPOSIXCharacterClasses` must be + * preferred when `UNICODE_CHARACTER_CLASSES` is not set. + * + * This is a `js.Map` (and a lazy val) because it is only used when `\\p` is + * already known to be supported by the underlying `js.RegExp` (ES 2018), + * and we assume that that implies that `js.Map` is supported (ES 2015). + */ + private lazy val predefinedPCharacterClasses: js.Map[String, CompiledCharClass] = { + import CompiledCharClass._ + + val result = new js.Map[String, CompiledCharClass]() + + // General categories + + val generalCategories = js.Array( + "Lu", "Ll", "Lt", "LC", "Lm", "Lo", "L", + "Mn", "Mc", "Me", "M", + "Nd", "Nl", "No", "N", + "Pc", "Pd", "Ps", "Pe", "Pi", "Pf", "Po", "P", + "Sm", "Sc", "Sk", "So", "S", + "Zs", "Zl", "Zp", "Z", + "Cc", "Cf", "Cs", "Co", "Cn", "C" + ) + + forArrayElems(generalCategories) { gc => + val compiled = posP(gc) + mapSet(result, gc, compiled) + mapSet(result, "Is" + gc, compiled) + mapSet(result, "general_category=" + gc, compiled) + mapSet(result, "gc=" + gc, compiled) + } + + // Binary properties + + mapSet(result, "IsAlphabetic", posP("Alphabetic")) + mapSet(result, "IsIdeographic", posP("Ideographic")) + mapSet(result, "IsLetter", posP("Letter")) + mapSet(result, "IsLowercase", posP("Lowercase")) + mapSet(result, "IsUppercase", posP("Uppercase")) + mapSet(result, "IsTitlecase", posP("Lt")) + mapSet(result, "IsPunctuation", posP("Punctuation")) + mapSet(result, "IsControl", posP("Control")) + mapSet(result, "IsWhite_Space", posP("White_Space")) + mapSet(result, "IsDigit", posP("Nd")) + mapSet(result, "IsHex_Digit", posP("Hex_Digit")) + mapSet(result, "IsJoin_Control", posP("Join_Control")) + mapSet(result, "IsNoncharacter_Code_Point", posP("Noncharacter_Code_Point")) + mapSet(result, "IsAssigned", posP("Assigned")) + + // java.lang.Character classes + + mapSet(result, "javaAlphabetic", posP("Alphabetic")) + mapSet(result, "javaDefined", negP("Cn")) + mapSet(result, "javaDigit", posP("Nd")) + mapSet(result, "javaIdentifierIgnorable", posClass("\u0000-\u0008\u000E-\u001B\u007F-\u009F\\p{Cf}")) + mapSet(result, "javaIdeographic", posP("Ideographic")) + mapSet(result, "javaISOControl", posClass("\u0000-\u001F\u007F-\u009F")) + mapSet(result, "javaJavaIdentifierPart", + posClass("\\p{L}\\p{Sc}\\p{Pc}\\p{Nd}\\p{Nl}\\p{Mn}\\p{Mc}\u0000-\u0008\u000E-\u001B\u007F-\u009F\\p{Cf}")) + mapSet(result, "javaJavaIdentifierStart", posClass("\\p{L}\\p{Sc}\\p{Pc}\\p{Nl}")) + mapSet(result, "javaLetterOrDigit", posClass("\\p{L}\\p{Nd}")) + mapSet(result, "javaLowerCase", posP("Lowercase")) + mapSet(result, "javaMirrored", posP("Bidi_Mirrored")) + mapSet(result, "javaSpaceChar", posP("Z")) + mapSet(result, "javaTitleCase", posP("Lt")) + mapSet(result, "javaUnicodeIdentifierPart", + posClass("\\p{ID_Continue}\u2E2F\u0000-\u0008\u000E-\u001B\u007F-\u009F\\p{Cf}")) + mapSet(result, "javaUnicodeIdentifierStart", posClass("\\p{ID_Start}\u2E2F")) + mapSet(result, "javaUpperCase", posP("Uppercase")) + + // [\t-\r\u001C-\u001F\\p{Z}&&[^\u00A0\u2007\u202F]] + mapSet(result, "javaWhitespace", + posClass("\t-\r\u001C-\u001F \u1680\u2000-\u2006\u2008-\u200A\u205F\u3000\\p{Zl}\\p{Zp}")) + + /* POSIX character classes with Unicode compatibility + * (resolved from the original definitions, which are in comments) + */ + + mapSet(result, "Lower", posP("Lower")) // \p{IsLowercase} + mapSet(result, "Upper", posP("Upper")) // \p{IsUppercase} + mapSet(result, "ASCII", posClass("\u0000-\u007f")) + mapSet(result, "Alpha", posP("Alpha")) // \p{IsAlphabetic} + mapSet(result, "Digit", posP("Nd")) // \p{IsDigit} + mapSet(result, "Alnum", posClass("\\p{Alpha}\\p{Nd}")) // [\p{IsAlphabetic}\p{IsDigit}] + mapSet(result, "Punct", posP("P")) // \p{IsPunctuation} + + // [^\p{IsWhite_Space}\p{gc=Cc}\p{gc=Cs}\p{gc=Cn}] + mapSet(result, "Graph", negClass("\\p{White_Space}\\p{Cc}\\p{Cs}\\p{Cn}")) + + /* [\p{Graph}\p{Blank}&&[^\p{Cntrl}]] + * === (by definition of Cntrl) + * [\p{Graph}\p{Blank}&&[^\p{Cc}]] + * === (because Graph already excludes anything in the Cc category) + * [\p{Graph}[\p{Blank}&&[^\p{Cc}]]] + * === (by the resolved definition of Blank below) + * [\p{Graph}[\t\p{Zs}&&[^\p{Cc}]]] + * === (by the fact that \t is a Cc, and general categories are disjoint) + * [\p{Graph}\p{Zs}] + * === (by definition of Graph) + * [[^\p{IsWhite_Space}\p{Cc}\p{Cs}\p{Cn}]\p{Zs}] + * === (see the excerpt from PropList.txt below) + * [[^\x09-\x0d\x85\p{Zs}\p{Zl}\p{Zp}\p{Cc}\p{Cs}\p{Cn}]\p{Zs}] + * === (canceling \p{Zs}) + * [^\x09-\x0d\x85\p{Zl}\p{Zp}\p{Cc}\p{Cs}\p{Cn}] + * === (because \x09-\x0d and \x85 are all in the Cc category) + * [^\p{Zl}\p{Zp}\p{Cc}\p{Cs}\p{Cn}] + */ + mapSet(result, "Print", negClass("\\p{Zl}\\p{Zp}\\p{Cc}\\p{Cs}\\p{Cn}")) + + /* [\p{IsWhite_Space}&&[^\p{gc=Zl}\p{gc=Zp}\x0a\x0b\x0c\x0d\x85]] + * === (see the excerpt from PropList.txt below) + * [[\x09-\x0d\x85\p{gc=Zs}\p{gc=Zl}\p{gc=Zp}]&&[^\p{gc=Zl}\p{gc=Zp}\x0a\x0b\x0c\x0d\x85]] + * === (by simplification) + * [\x09\p{gc=Zs}] + */ + mapSet(result, "Blank", posClass("\t\\p{Zs}")) + + mapSet(result, "Cntrl", posP("Cc")) // \p{gc=Cc} + mapSet(result, "XDigit", posClass("\\p{Nd}\\p{Hex}")) // [\p{gc=Nd}\p{IsHex_Digit}] + mapSet(result, "Space", posP("White_Space")) // \p{IsWhite_Space} + + result + } + + /* Excerpt from PropList.txt v13.0.0: + * + * 0009..000D ; White_Space # Cc [5] .. + * 0020 ; White_Space # Zs SPACE + * 0085 ; White_Space # Cc + * 00A0 ; White_Space # Zs NO-BREAK SPACE + * 1680 ; White_Space # Zs OGHAM SPACE MARK + * 2000..200A ; White_Space # Zs [11] EN QUAD..HAIR SPACE + * 2028 ; White_Space # Zl LINE SEPARATOR + * 2029 ; White_Space # Zp PARAGRAPH SEPARATOR + * 202F ; White_Space # Zs NARROW NO-BREAK SPACE + * 205F ; White_Space # Zs MEDIUM MATHEMATICAL SPACE + * 3000 ; White_Space # Zs IDEOGRAPHIC SPACE + * + * Note that *all* the code points with general category Zs, Zl or Zp are + * listed here. In addition, we have 0009-000D and 0085 from the Cc category. + * Therefore, the following equivalence holds: + * + * \p{IsWhite_Space} === [\x09-\x0d\x85\p{gc=Zs}\p{gc=Zl}\p{gc=Zp}] + * + * That equivalence is known to be true as of Unicode 13.0.0, and seems to + * have been true for a number of past versions as well. We rely on it to + * define \p{Print} and \p{Blank} above. Those would become buggy if a future + * version of Unicode invalidates that assumption. + */ + + private val scriptCanonicalizeRegExp = new js.RegExp("(?:^|_)[a-z]", "g") + + /** A cache for verified and canonicalized script names. + * + * This is a `js.Map` (and a lazy val) because it is only used when `\\p` is + * already known to be supported by the underlying `js.RegExp` (ES 2018), + * and we assume that that implies that `js.Map` is supported (ES 2015). + */ + private lazy val canonicalizedScriptNameCache: js.Map[String, String] = { + val result = new js.Map[String, String]() + + /* SignWriting is an exception. It has an uppercase 'W' even though it is + * not after '_'. We add the exception to the map immediately. + */ + mapSet(result, "signwriting", "SignWriting") + + result + } + + @inline + private final class CodePointRange(val start: Int, val end: Int) { + def isEmpty: Boolean = start > end + def nonEmpty: Boolean = start <= end + + /** Computes the intersection of two *non-empty* ranges. + * + * This method makes no guarantee about its result if either or both input + * ranges are empty. + * + * The result range may be empty. + */ + def intersect(that: CodePointRange): CodePointRange = + CodePointRange(Math.max(this.start, that.start), Math.min(this.end, that.end)) + + def shift(offset: Int): CodePointRange = + CodePointRange(start + offset, end + offset) + } + + private object CodePointRange { + @inline + def apply(start: Int, end: Int): CodePointRange = + new CodePointRange(start, end) + + @inline + def BmpBelowHighSurrogates: CodePointRange = + CodePointRange(0, Character.MIN_HIGH_SURROGATE - 1) + + @inline + def HighSurrogates: CodePointRange = + CodePointRange(Character.MIN_HIGH_SURROGATE, Character.MAX_HIGH_SURROGATE) + + @inline + def BmpAboveHighSurrogates: CodePointRange = + CodePointRange(Character.MAX_HIGH_SURROGATE + 1, Character.MAX_VALUE) + + @inline + def Supplementaries: CodePointRange = + CodePointRange(Character.MIN_SUPPLEMENTARY_CODE_POINT, Character.MAX_CODE_POINT) + } + + private final class CharacterClassBuilder(asciiCaseInsensitive: Boolean, isNegated: Boolean) { + private var conjunction = "" + private var thisConjunct = "" + private var thisSegment = "" + + def finish(): String = { + val conjunct = conjunctResult() + if (conjunction == "") conjunct else s"(?:$conjunction$conjunct)" + } + + def startNewConjunct(): Unit = { + val conjunct = conjunctResult() + conjunction += (if (isNegated) conjunct + "|" else s"(?=$conjunct)") + thisConjunct = "" + thisSegment = "" + } + + private def addAlternative(alt: String): Unit = { + if (thisConjunct == "") + thisConjunct = alt + else + thisConjunct += "|" + alt + } + + private def conjunctResult(): String = { + if (isNegated) { + val negThisSegment = codePointNotAmong(thisSegment) + if (thisConjunct == "") + negThisSegment + else + s"(?:(?!$thisConjunct)$negThisSegment)" + } else if (thisSegment == "") { + if (thisConjunct == "") + "[^\\d\\D]" // impossible to satisfy + else + s"(?:$thisConjunct)" + } else { + if (thisConjunct == "") + s"[$thisSegment]" + else + s"(?:$thisConjunct|[$thisSegment])" + } + } + + private def literalCodePoint(codePoint: Int): String = { + val s = codePointToString(codePoint) + if (codePoint == ']' || codePoint == '\\' || codePoint == '-' || codePoint == '^') + "\\" + s + else + s + } + + def addCharacterClass(cls: String): Unit = + addAlternative(cls) + + def addCharacterClass(cls: CompiledCharClass): Unit = { + cls.kind match { + case CompiledCharClass.PosP => + thisSegment += "\\p{" + cls.data + "}" + case CompiledCharClass.NegP => + thisSegment += "\\P{" + cls.data + "}" + case CompiledCharClass.PosClass => + thisSegment += cls.data + case CompiledCharClass.NegClass => + addAlternative(codePointNotAmong(cls.data)) + } + } + + def addCodePointsInString(str: String, start: Int, end: Int): Unit = { + var i = start + while (i != end) { + val codePoint = str.codePointAt(i) + addSingleCodePoint(codePoint) + i += charCount(codePoint) + } + } + + def addSingleCodePoint(codePoint: Int): Unit = { + val s = literalCodePoint(codePoint) + + if (supportsUnicode || (isBmpCodePoint(codePoint) && !isHighSurrogateCP(codePoint))) { + if (isLowSurrogateCP(codePoint)) { + // Put low surrogates at the beginning so that they do not merge with high surrogates + thisSegment = s + thisSegment + } else { + thisSegment += s + } + } else { + if (isBmpCodePoint(codePoint)) { + // It is a high surrogate + addAlternative(s"(?:$s(?![$MIN_LOW_SURROGATE-$MAX_LOW_SURROGATE]))") + } else { + // It is a supplementary code point + addAlternative(s) + } + } + + if (asciiCaseInsensitive) { + if (codePoint >= 'A' && codePoint <= 'Z') + thisSegment += codePointToString(codePoint - 'A' + 'a') + else if (codePoint >= 'a' && codePoint <= 'z') + thisSegment += codePointToString(codePoint - 'a' + 'A') + } + } + + def addCodePointRange(startCodePoint: Int, endCodePoint: Int): Unit = { + def literalRange(range: CodePointRange): String = + literalCodePoint(range.start) + "-" + literalCodePoint(range.end) + + val range = CodePointRange(startCodePoint, endCodePoint) + + if (supportsUnicode || range.end < MIN_HIGH_SURROGATE) { + val s = literalRange(range) + + if (isLowSurrogateCP(range.start)) { + /* Put ranges whose start code point is a low surrogate at the + * beginning, so that they cannot merge with a high surrogate. Since + * the numeric values of high surrogates is *less than* that of low + * surrogates, the `range.end` cannot be a high surrogate here, and + * so there is no danger of it merging with a low surrogate already + * present at the beginning of `thisSegment`. + */ + thisSegment = s + thisSegment + } else { + thisSegment += s + } + } else { + /* Here be dragons. We need to split the range into several ranges that + * we can separately compile. + * + * Since the 'u' flag is not used when we get here, the RegExp engine + * treats surrogate chars as individual chars in all cases. Therefore, + * we do not need to protect low surrogates. + */ + + val bmpBelowHighSurrogates = range.intersect(CodePointRange.BmpBelowHighSurrogates) + if (bmpBelowHighSurrogates.nonEmpty) + thisSegment += literalRange(bmpBelowHighSurrogates) + + val highSurrogates = range.intersect(CodePointRange.HighSurrogates) + if (highSurrogates.nonEmpty) + addAlternative("[" + literalRange(highSurrogates) + "]" + s"(?![$MIN_LOW_SURROGATE-$MAX_LOW_SURROGATE])") + + val bmpAboveHighSurrogates = range.intersect(CodePointRange.BmpAboveHighSurrogates) + if (bmpAboveHighSurrogates.nonEmpty) + thisSegment += literalRange(bmpAboveHighSurrogates) + + val supplementaries = range.intersect(CodePointRange.Supplementaries) + if (supplementaries.nonEmpty) { + val startHigh = highSurrogate(supplementaries.start) + val startLow = lowSurrogate(supplementaries.start) + + val endHigh = highSurrogate(supplementaries.end) + val endLow = lowSurrogate(supplementaries.end) + + if (startHigh == endHigh) { + addAlternative( + codePointToString(startHigh) + "[" + literalRange(CodePointRange(startLow, endLow)) + "]") + } else { + addAlternative( + codePointToString(startHigh) + "[" + literalRange(CodePointRange(startLow, MAX_LOW_SURROGATE)) + "]") + + val middleHighs = CodePointRange(startHigh + 1, endHigh - 1) + if (middleHighs.nonEmpty) + addAlternative(s"[${literalRange(middleHighs)}][$MIN_LOW_SURROGATE-$MAX_LOW_SURROGATE]") + + addAlternative( + codePointToString(endHigh) + "[" + literalRange(CodePointRange(MIN_LOW_SURROGATE, endLow)) + "]") + } + } + } + + if (asciiCaseInsensitive) { + val uppercases = range.intersect(CodePointRange('A', 'Z')) + if (uppercases.nonEmpty) + thisSegment += literalRange(uppercases.shift('a' - 'A')) + + val lowercases = range.intersect(CodePointRange('a', 'z')) + if (lowercases.nonEmpty) + thisSegment += literalRange(lowercases.shift('A' - 'a')) + } + } + } +} + +private final class PatternCompiler(private val pattern: String, private var flags: Int) { + import PatternCompiler._ + import PatternCompiler.Support._ + import PatternCompiler.InlinedHelpers._ + import Pattern._ + + /** Whether the result `Pattern` must be sticky. */ + private var sticky: Boolean = false + + /** The parse index, within `pattern`. */ + private var pIndex: Int = 0 + + /** The number of capturing groups in the compiled pattern. + * + * This is different than `originalGroupCount` when there are atomic groups + * (or possessive quantifiers, which are sugar for atomic groups). + */ + private var compiledGroupCount: Int = 0 + + /** Map from original group number to compiled group number. + * + * It contains a mapping for the entire match, which is group 0. + */ + private val groupNumberMap = js.Array[Int](0) + + /** The number of capturing groups found so far in the original pattern. + * + * This is `groupNumberMap.length - 1`, because `groupNumberMap` contains + * the mapping for the entire match, which is group 0. + */ + @inline private def originalGroupCount = groupNumberMap.length - 1 + + /** Map from group name to original group number. + * + * We store *original* group numbers, rather than compiled group numbers, + * in order to make the renumbering caused by possessive quantifiers easier. + */ + private val namedGroups = dictEmpty[Int]() + + @inline private def hasFlag(flag: Int): Boolean = (flags & flag) != 0 + + @inline private def unixLines: Boolean = hasFlag(UNIX_LINES) + @inline private def comments: Boolean = hasFlag(COMMENTS) + @inline private def dotAll: Boolean = hasFlag(DOTALL) + + @inline + private def asciiCaseInsensitive: Boolean = + (flags & (CASE_INSENSITIVE | UNICODE_CASE)) == CASE_INSENSITIVE + + @inline + private def unicodeCaseInsensitive: Boolean = { + enableUnicodeCaseInsensitive && // for dead code elimination + (flags & (CASE_INSENSITIVE | UNICODE_CASE)) == (CASE_INSENSITIVE | UNICODE_CASE) + } + + @inline + private def unicodeCaseOrUnicodeCharacterClass: Boolean = { + enableUnicodeCaseInsensitive && // for dead code elimination + (flags & (UNICODE_CASE | UNICODE_CHARACTER_CLASS)) != 0 + } + + @inline + private def multiline: Boolean = { + enableUnicodeCharacterClassesAndLookBehinds && // for dead code elimination + hasFlag(MULTILINE) + } + + @inline + private def unicodeCharacterClass: Boolean = { + enableUnicodeCharacterClassesAndLookBehinds && // for dead code elimination + hasFlag(UNICODE_CHARACTER_CLASS) + } + + def compile(): Pattern = { + // UNICODE_CHARACTER_CLASS implies UNICODE_CASE, even for LITERAL + if (hasFlag(UNICODE_CHARACTER_CLASS)) + flags |= UNICODE_CASE + + val isLiteral = hasFlag(LITERAL) + + if (!isLiteral) + processLeadingEmbeddedFlags() + + if (hasFlag(CANON_EQ)) + parseError("CANON_EQ is not supported") + + if (!enableUnicodeCharacterClassesAndLookBehinds) { + if (hasFlag(MULTILINE)) + parseErrorRequireESVersion("MULTILINE", "2018") + if (hasFlag(UNICODE_CHARACTER_CLASS)) + parseErrorRequireESVersion("UNICODE_CHARACTER_CLASS", "2018") + } + + if (!enableUnicodeCaseInsensitive) { + if (hasFlag(UNICODE_CASE)) + parseErrorRequireESVersion("UNICODE_CASE", "2015") + } + + val jsPattern = if (isLiteral) { + literal(pattern) + } else { + if (pattern.jsSubstring(pIndex, pIndex + 2) == "\\G") { + sticky = true + pIndex += 2 + } + compileTopLevel() + } + + val jsFlags = { + // We always use the 'u' and 's' flags when they are supported. + val baseJSFlags = { + if (supportsDotAll) "us" + else if (supportsUnicode) "u" + else "" + } + + // We add the 'i' flag when using Unicode-aware case insensitive matching. + if (unicodeCaseInsensitive) baseJSFlags + "i" + else baseJSFlags + } + + new Pattern(pattern, flags, jsPattern, jsFlags, sticky, originalGroupCount, + groupNumberMap, namedGroups) + } + + private def parseError(desc: String): Nothing = + throw new PatternSyntaxException(desc, pattern, pIndex) + + @inline + private def requireES2018Features(purpose: String): Unit = { + if (!enableUnicodeCharacterClassesAndLookBehinds) + parseErrorRequireESVersion(purpose, "2018") + } + + @noinline + private def parseErrorRequireESVersion(purpose: String, es: String): Nothing = { + parseError( + s"$purpose is not supported because it requires RegExp features of ECMAScript $es.\n" + + s"If you only target environments with ES$es+, you can enable ES$es features with\n" + + s" scalaJSLinkerConfig ~= { _.withESFeatures(_.withESVersion(ESVersion.ES$es)) }\n" + + "or an equivalent configuration depending on your build tool.") + } + + private def processLeadingEmbeddedFlags(): Unit = { + val m = leadingEmbeddedFlagSpecifierRegExp.exec(pattern) + if (m != null) { + undefOrForeach(m(1)) { chars => + for (i <- 0 until chars.length()) + flags |= charToFlag(chars.charAt(i)) + } + + // If U was in the flags, we need to enable UNICODE_CASE as well + if (hasFlag(UNICODE_CHARACTER_CLASS)) + flags |= UNICODE_CASE + + undefOrForeach(m(2)) { chars => + for (i <- 0 until chars.length()) + flags &= ~charToFlag(chars.charAt(i)) + } + + /* The way things are done here, it is possible to *remove* + * `UNICODE_CASE` from the set of flags while leaving + * `UNICODE_CHARACTER_CLASS` in. This creates a somewhat inconsistent + * state, but it matches what the JVM does, as illustrated in the test + * `RegexPatternTest.flags()`. + */ + + // Advance past the embedded flags + pIndex += undefOrForceGet(m(0)).length() + } + } + + // The predefined character class for \w, depending on the UNICODE_CHARACTER_CLASS flag + + @inline + private def wordCharClass: CompiledCharClass = + if (unicodeCharacterClass) UnicodeWordChar + else ASCIIWordChar + + // Meat of the compilation + + private def literal(s: String): String = { + var result = "" + val len = s.length() + var i = 0 + while (i != len) { + val cp = s.codePointAt(i) + result += literal(cp) + i += charCount(cp) + } + result + } + + private def literal(cp: Int): String = { + val s = codePointToString(cp) + + if (cp < 0x80) { + /* SyntaxCharacter :: one of + * ^ $ \ . * + ? ( ) [ ] { } | + */ + (cp: @switch) match { + case '^' | '$' | '\\' | '.' | '*' | '+' | '?' | '(' | ')' | '[' | ']' | '{' | '}' | '|' => + "\\" + s + case _ => + if (!asciiCaseInsensitive) + s + else if (cp >= 'A' && cp <= 'Z') + "[" + s + codePointToString(cp + ('a' - 'A')) + "]" + else if (cp >= 'a' && cp <= 'z') + "[" + codePointToString(cp + ('A' - 'a')) + s + "]" + else + s + } + } else { + if (supportsUnicode) { + /* We wrap low surrogates with `(?:x)` to ensure that we do not + * artificially create a surrogate pair in the compiled pattern where + * none existed in the source pattern. + * Consider the source pattern `\x{D834}\x{DD1E}`, for example. + * If low surrogates were not wrapped, it would be compiled to a + * surrogate pair, which would match the input string `"𝄞"` although it + * is not supposed to. + */ + if (isLowSurrogateCP(cp)) + s"(?:$s)" + else + s + } else { + if (isHighSurrogateCP(cp)) + s"(?:$s(?![$MIN_LOW_SURROGATE-$MAX_LOW_SURROGATE]))" + else if (isBmpCodePoint(cp)) + s + else + s"(?:$s)" // group a surrogate pair so that it is repeated as a whole + } + } + } + + @inline + private def compileTopLevel(): String = + compileTopLevelOrInsideGroup(insideGroup = false) + + @inline + private def compileInsideGroup(): String = + compileTopLevelOrInsideGroup(insideGroup = true) + + /** The main parsing method. + * + * It follows a recursive descent approach. It is recursive for any + * `(...)`-enclosed subpattern, and flat for other kinds of patterns. + */ + private def compileTopLevelOrInsideGroup(insideGroup: Boolean): String = { + // scalastyle:off return + // the 'return' is in the case ')' + + val pattern = this.pattern // local copy + val len = pattern.length() + + var result = "" + + while (pIndex != len) { + val dispatchCP = pattern.codePointAt(pIndex) + (dispatchCP: @switch) match { + // Cases that mess with the control flow and/or that cannot be repeated + + case ')' => + if (!insideGroup) + parseError("Unmatched closing ')'") + pIndex += 1 + return result + + case '|' => + if (sticky && !insideGroup) + parseError("\\G is not supported when there is an alternative at the top level") + pIndex += 1 + result += "|" + + // experimentally, this is the set of chars considered as whitespace for comments + case ' ' | '\t' | '\n' | '\u000B' | '\f' | '\r' if comments => + pIndex += 1 + + case '#' if comments => + skipSharpComment() + + case '?' | '*' | '+' | '{' => + parseError("Dangling meta character '" + codePointToString(dispatchCP) + "'") + + // Regular cases, which can be repeated + + case _ => + // Record the current compiledGroupCount, for possessive quantifiers + val compiledGroupCountBeforeThisToken = compiledGroupCount + + val compiledToken = (dispatchCP: @switch) match { + case '\\' => compileEscape() + case '[' => compileCharacterClass() + case '(' => compileGroup() + case '^' => compileCaret() + case '$' => compileDollar() + case '.' => compileDot() + + case _ => + pIndex += charCount(dispatchCP) + literal(dispatchCP) + } + + result += compileRepeater(compiledGroupCountBeforeThisToken, compiledToken) + } + } + + if (insideGroup) + parseError("Unclosed group") + + result + // scalastyle:on return + } + + /** Skip a '#' comment. + * + * Pre-condition: `comments && pattern.charAt(pIndex) == '#'` is true + */ + private def skipSharpComment(): Unit = { + val pattern = this.pattern // local copy + val len = pattern.length() + + @inline def isEOL(c: Char): Boolean = + c == '\n' || c == '\r' || c == '\u0085' || c == '\u2028' || c == '\u2029' + + while (pIndex != len && !isEOL(pattern.charAt(pIndex))) + pIndex += 1 + } + + /** Skip all comments. + * + * Pre-condition: `comments` is true + */ + @noinline + private def skipComments(): Unit = { + val pattern = this.pattern // local copy + val len = pattern.length() + + @inline @tailrec + def loop(): Unit = { + if (pIndex != len) { + (pattern.charAt(pIndex): @switch) match { + case ' ' | '\t' | '\n' | '\u000B' | '\f' | '\r' => + pIndex += 1 + loop() + case '#' => + skipSharpComment() + loop() + case _ => + () + } + } + } + + loop() + } + + private def compileRepeater(compiledGroupCountBeforeThisToken: Int, compiledToken: String): String = { + val pattern = this.pattern // local copy + val len = pattern.length() + + val startOfRepeater = pIndex + val repeaterDispatchChar = + if (startOfRepeater == len) '.' + else pattern.charAt(startOfRepeater) + + @inline def hasRepeater: Boolean = { + repeaterDispatchChar == '?' || repeaterDispatchChar == '*' || + repeaterDispatchChar == '+' || repeaterDispatchChar == '{' + } + + if (hasRepeater) { + // There is a repeater + val baseRepeater = parseBaseRepeater(repeaterDispatchChar) + + if (pIndex != len) { + pattern.charAt(pIndex) match { + case '+' => + // Possessive quantifier + pIndex += 1 + buildPossessiveQuantifier(compiledGroupCountBeforeThisToken, compiledToken, baseRepeater) + case '?' => + // Lazy quantifier + pIndex += 1 + compiledToken + baseRepeater + "?" + case _ => + // Greedy quantifier + compiledToken + baseRepeater + } + } else { + // Greedy quantifier + compiledToken + baseRepeater + } + } else { + // No repeater + compiledToken + } + } + + private def parseBaseRepeater(repeaterDispatchChar: Char): String = { + val pattern = this.pattern // local copy + val startOfRepeater = pIndex + + pIndex += 1 + + if (repeaterDispatchChar == '{') { + val len = pattern.length() + + if (pIndex == len || !isDigit(pattern.charAt(pIndex))) + parseError("Illegal repetition") + while (pIndex != len && isDigit(pattern.charAt(pIndex))) + pIndex += 1 + if (pIndex == len) + parseError("Illegal repetition") + if (pattern.charAt(pIndex) == ',') { + pIndex += 1 + while (pIndex != len && isDigit(pattern.charAt(pIndex))) + pIndex += 1 + } + if (pIndex == len || pattern.charAt(pIndex) != '}') + parseError("Illegal repetition") + pIndex += 1 + } + + pattern.jsSubstring(startOfRepeater, pIndex) + } + + /** Builds a possessive quantifier, which is sugar for an atomic group over + * a greedy quantifier. + */ + private def buildPossessiveQuantifier(compiledGroupCountBeforeThisToken: Int, + compiledToken: String, baseRepeater: String): String = { + + /* This is very intricate. Not only do we need to surround a posteriori the + * previous token, we are introducing a new capturing group in between. + * This means that we need to renumber all backreferences contained in the + * compiled token. + */ + + // Remap group numbers + for (i <- 0 until groupNumberMap.length) { + val mapped = groupNumberMap(i) + if (mapped > compiledGroupCountBeforeThisToken) + groupNumberMap(i) = mapped + 1 + } + + // Renumber all backreferences contained in the compiled token + import js.JSStringOps._ + val amendedToken = compiledToken.jsReplace(renumberingRegExp, { + (str, backslashes, groupString) => + if (backslashes.length() % 2 == 0) { // poor man's negative look-behind + str + } else { + val groupNumber = parseInt(groupString, 10) + if (groupNumber > compiledGroupCountBeforeThisToken) + backslashes + (groupNumber + 1) + else + str + } + }: js.Function3[String, String, String, String]) + + // Plan the future remapping + compiledGroupCount += 1 + + // Finally, the encoding of the atomic group over the greedy quantifier + val myGroupNumber = compiledGroupCountBeforeThisToken + 1 + s"(?:(?=($amendedToken$baseRepeater))\\$myGroupNumber)" + } + + @inline + private def compileCaret(): String = { + pIndex += 1 + if (multiline) { + /* `multiline` implies ES2018, so we can use look-behind assertions. + * We cannot use the 'm' flag of JavaScript RegExps because its semantics + * differ from the Java ones (either with or without `UNIX_LINES`). + */ + if (unixLines) + "(?<=^|\n)" + else + "(?<=^|\r(?!\n)|[\n\u0085\u2028\u2029])" + } else { + /* Wrap as (?:^) in case it ends up being repeated, for example `^+` + * becomes `(?:^)+`. This is necessary because `^+` is not syntactically + * valid in JS, although it is valid once wrapped in a group. + * (Not that repeating ^ has any useful purpose, but the spec does not + * prevent it.) + */ + "(?:^)" + } + } + + @inline + private def compileDollar(): String = { + pIndex += 1 + if (multiline) { + /* `multiline` implies ES2018, so we can use look-behind assertions. + * We cannot use the 'm' flag of JavaScript RegExps (see ^ above). + */ + if (unixLines) + "(?=$|\n)" + else + "(?=$|(? + val cls = parsePredefinedCharacterClass(dispatchChar) + cls.kind match { + case CompiledCharClass.PosP => + "\\p{" + cls.data + "}" + case CompiledCharClass.NegP => + "\\P{" + cls.data + "}" + case CompiledCharClass.PosClass => + "[" + cls.data + "]" + case CompiledCharClass.NegClass => + codePointNotAmong(cls.data) + } + + // Boundary matchers + + case 'b' => + if (pattern.jsSubstring(pIndex, pIndex + 4) == "b{g}") { + parseError("\\b{g} is not supported") + } else { + /* Compile as is if both `UNICODE_CASE` and `UNICODE_CHARACTER_CLASS` are false. + * This is correct because: + * - since `UNICODE_CHARACTER_CLASS` is false, word chars are + * considered to be `[a-zA-Z_0-9]` for Java semantics, and + * - since `UNICODE_CASE` is false, we do not use the 'i' flag in the + * JS RegExp, and so word chars are considered to be `[a-zA-Z_0-9]` + * for the JS semantics as well. + * + * In all other cases, we determine the compiled form of `\w` and use + * a custom look-around-based implementation. + * This requires ES2018+, hence why we go to the trouble of trying to + * reuse `\b` if we can. + */ + if (unicodeCaseOrUnicodeCharacterClass) { + requireES2018Features("\\b with UNICODE_CASE") // UNICODE_CHARACTER_CLASS would have been rejected earlier + pIndex += 1 + val w = wordCharClass.data + s"(?:(?<=[$w])(?![$w])|(? + // Same strategy as for \b above + if (unicodeCaseOrUnicodeCharacterClass) { + requireES2018Features("\\B with UNICODE_CASE") // UNICODE_CHARACTER_CLASS would have been rejected earlier + pIndex += 1 + val w = wordCharClass.data + s"(?:(?<=[$w])(?=[$w])|(? + // We can always use ^ for start-of-text because we never use the 'm' flag in the JS RegExp + pIndex += 1 + "(?:^)" // wrap in case it is quantified (see compilation of '^') + case 'G' => + parseError("\\G in the middle of a pattern is not supported") + case 'Z' => + // We can always use $ for end-of-text because we never use the 'm' flag in the JS RegExp + pIndex += 1 + val lineTerminator = + if (unixLines) "\n" + else "(?:\r\n?|[\n\u0085\u2028\u2029])" + "(?=" + lineTerminator + "?$)" + case 'z' => + // We can always use $ for end-of-text because we never use the 'm' flag in the JS RegExp + pIndex += 1 + "(?:$)" // wrap in case it is quantified (see compilation of '$') + + // Linebreak matcher + + case 'R' => + pIndex += 1 + "(?:\r\n|[\n-\r\u0085\u2028\u2029])" + + // Unicode Extended Grapheme matcher + + case 'X' => + parseError("\\X is not supported") + + // Back references + + case '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' => + /* From the JavaDoc: + * + * > In this class, \1 through \9 are always interpreted as back + * > references, and a larger number is accepted as a back reference if + * > at least that many subexpressions exist at that point in the + * > regular expression, otherwise the parser will drop digits until + * > the number is smaller or equal to the existing number of groups or + * > it is one digit. + */ + val start = pIndex + var end = start + 1 + + // In most cases, one of the first two conditions is immediately false + while (end != len && isDigit(pattern.charAt(end)) && + parseInt(pattern.jsSubstring(start, end + 1), 10) <= originalGroupCount) { + end += 1 + } + + val groupString = pattern.jsSubstring(start, end) + val groupNumber = parseInt(groupString, 10) + if (groupNumber > originalGroupCount) + parseError(s"numbered capturing group <$groupNumber> does not exist") + val compiledGroupNumber = groupNumberMap(groupNumber) + pIndex = end + // Wrap in a non-capturing group in case it's followed by a (de-escaped) digit + "(?:\\" + compiledGroupNumber + ")" + + case 'k' => + pIndex += 1 + if (pIndex == len || pattern.charAt(pIndex) != '<') + parseError("\\k is not followed by '<' for named capturing group") + pIndex += 1 + val groupName = parseGroupName() + val groupNumber = dictGetOrElse(namedGroups, groupName) { + parseError(s"named capturing group <$groupName> does not exit") + } + val compiledGroupNumber = groupNumberMap(groupNumber) + pIndex += 1 + // Wrap in a non-capturing group in case it's followed by a (de-escaped) digit + "(?:\\" + compiledGroupNumber + ")" + + // Quotes + + case 'Q' => + val start = pIndex + 1 + val end = pattern.indexOf("\\E", start) + if (end < 0) { + pIndex = pattern.length() + literal(pattern.jsSubstring(start)) + } else { + pIndex = end + 2 + literal(pattern.jsSubstring(start, end)) + } + + // Other + + case c => + literal(parseSingleCodePointEscape()) + } + } + + private def parseSingleCodePointEscape(): Int = { + val pattern = this.pattern // local copy + + (pattern.codePointAt(pIndex): @switch) match { + case '0' => + parseOctalEscape() + case 'x' => + parseHexEscape() + case 'u' => + parseUnicodeHexEscape() + case 'N' => + parseError("\\N is not supported") + case 'a' => + pIndex += 1 + 0x0007 + case 't' => + pIndex += 1 + 0x0009 + case 'n' => + pIndex += 1 + 0x000a + case 'f' => + pIndex += 1 + 0x000c + case 'r' => + pIndex += 1 + 0x000d + case 'e' => + pIndex += 1 + 0x001b + case 'c' => + pIndex += 1 + if (pIndex == pattern.length()) + parseError("Illegal control escape sequence") + val cp = pattern.codePointAt(pIndex) + pIndex += charCount(cp) + // https://stackoverflow.com/questions/35208570/java-regular-expression-cx-control-characters + cp ^ 0x40 + + case cp => + // Other letters are forbidden / reserved for future use + if ((cp >= 'A' && cp <= 'Z') || (cp >= 'a' && cp <= 'z')) + parseError("Illegal/unsupported escape sequence") + + // But everything else is accepted and quoted as is + pIndex += charCount(cp) + cp + } + } + + private def parseOctalEscape(): Int = { + /* \0n The character with octal value 0n (0 <= n <= 7) + * \0nn The character with octal value 0nn (0 <= n <= 7) + * \0mnn The character with octal value 0mnn (0 <= m <= 3, 0 <= n <= 7) + */ + + val pattern = this.pattern // local copy + val len = pattern.length() + val start = pIndex + + val d1 = + if (start + 1 < len) pattern.charAt(start + 1) - '0' + else -1 + if (d1 < 0 || d1 > 7) + parseError("Illegal octal escape sequence") + + val d2 = + if (start + 2 < len) pattern.charAt(start + 2) - '0' + else -1 + + if (d2 < 0 || d2 > 7) { + pIndex += 2 + d1 + } else if (d1 > 3) { + pIndex += 3 + d1 * 8 + d2 + } else { + val d3 = + if (start + 3 < len) pattern.charAt(start + 3) - '0' + else -1 + + if (d3 < 0 || d3 > 7) { + pIndex += 3 + d1 * 8 + d2 + } else { + pIndex += 4 + d1 * 64 + d2 * 8 + d3 + } + } + } + + private def parseHexEscape(): Int = { + /* \xhh The character with hexadecimal value 0xhh + * \x{h...h} The character with hexadecimal value 0xh...h + * (Character.MIN_CODE_POINT <= 0xh...h <= Character.MAX_CODE_POINT) + */ + + val pattern = this.pattern // local copy + val len = pattern.length() + + val start = pIndex + 1 + + if (start != len && pattern.charAt(start) == '{') { + val innerStart = start + 1 + val innerEnd = pattern.indexOf("}", innerStart) + if (innerEnd < 0) + parseError("Unclosed hexadecimal escape sequence") + val cp = parseHexCodePoint(innerStart, innerEnd, "hexadecimal") + pIndex = innerEnd + 1 + cp + } else { + val cp = parseHexCodePoint(start, start + 2, "hexadecimal") + pIndex = start + 2 + cp + } + } + + private def parseUnicodeHexEscape(): Int = { + /* \ uhhhh The character with hexadecimal value 0xhhhh + * + * An escaped high surrogate followed by an escaped low surrogate form a + * unique escaped code point. This is important in character classes. + */ + + val pattern = this.pattern // local copy + + val start = pIndex + 1 + val end = start + 4 + val codeUnit = parseHexCodePoint(start, end, "Unicode") + + pIndex = end + + val lowStart = end + 2 + val lowEnd = lowStart + 4 + + if (isHighSurrogateCP(codeUnit) && pattern.jsSubstring(end, lowStart) == "\\u") { + val low = parseHexCodePoint(lowStart, lowEnd, "Unicode") + if (isLowSurrogateCP(low)) { + pIndex = lowEnd + toCodePointCP(codeUnit, low) + } else { + codeUnit + } + } else { + codeUnit + } + } + + private def parseHexCodePoint(start: Int, end: Int, nameForError: String): Int = { + val pattern = this.pattern // local copy + val len = pattern.length() + + if (start == end || end > len) + parseError(s"Illegal $nameForError escape sequence") + + for (i <- start until end) { + if (!isHexDigit(pattern.charAt(i))) + parseError(s"Illegal $nameForError escape sequence") + } + + val cp = + if (end - start > 6) Character.MAX_CODE_POINT + 1 + else parseInt(pattern.jsSubstring(start, end), 16) + if (cp > Character.MAX_CODE_POINT) + parseError("Hexadecimal codepoint is too big") + + cp + } + + /** Parses and returns a translated version of a pre-defined character class. */ + private def parsePredefinedCharacterClass(dispatchChar: Char): CompiledCharClass = { + import CompiledCharClass._ + + pIndex += 1 + + val positive = (dispatchChar: @switch) match { + case 'd' | 'D' => + if (unicodeCharacterClass) UnicodeDigit + else ASCIIDigit + case 'h' | 'H' => + UniversalHorizontalWhiteSpace + case 's' | 'S' => + if (unicodeCharacterClass) UnicodeWhitespace + else ASCIIWhiteSpace + case 'v' | 'V' => + UniversalVerticalWhiteSpace + case 'w' | 'W' => + wordCharClass + case 'p' | 'P' => + parsePCharacterClass() + } + + if (dispatchChar >= 'a') // cheap isLower + positive + else + positive.negated + } + + /** Parses and returns a translated version of a `\p` character class. */ + private def parsePCharacterClass(): CompiledCharClass = { + val pattern = this.pattern // local copy + val len = pattern.length() + + val start = pIndex + val property = if (start == len) { + "?" // mimics the behavior of the JVM + } else if (pattern.charAt(start) == '{') { + val innerStart = start + 1 + val innerEnd = pattern.indexOf("}", innerStart) + if (innerEnd < 0) + parseError("Unclosed character family") + pIndex = innerEnd + pattern.jsSubstring(innerStart, innerEnd) + } else { + pattern.jsSubstring(start, start + 1) + } + + val result = if (!unicodeCharacterClass && dictContains(asciiPOSIXCharacterClasses, property)) { + val property2 = + if (asciiCaseInsensitive && (property == "Lower" || property == "Upper")) "Alpha" + else property + dictRawApply(asciiPOSIXCharacterClasses, property2) + } else { + // For anything else, we need built-in support for \p + requireES2018Features("Unicode character family") + + mapGetOrElse(predefinedPCharacterClasses, property) { + val scriptPrefixLen = if (property.startsWith("Is")) { + 2 + } else if (property.startsWith("sc=")) { + 3 + } else if (property.startsWith("script=")) { + 7 + } else if (property.startsWith("In") || property.startsWith("blk=") || property.startsWith("block=")) { + parseError("Blocks are not supported in \\p Unicode character families") + } else { + // Error + parseError(s"Unknown Unicode character class '$property'") + } + CompiledCharClass.posP("sc=" + canonicalizeScriptName(property.jsSubstring(scriptPrefixLen))) + } + } + + pIndex += 1 + + result + } + + /** Validates a script name and canonicalizes its casing. + * + * The JDK regexps compare script names while ignoring case, but JavaScript + * requires the canonical name. + * + * After canonicalizing the script name, we try to create a `js.RegExp` that + * uses it. If that fails, we report the (original) script name as unknown. + */ + private def canonicalizeScriptName(scriptName: String): String = { + import js.JSStringOps._ + + val lowercase = scriptName.toLowerCase() + + mapGetOrElseUpdate(canonicalizedScriptNameCache, lowercase) { + val canonical = lowercase.jsReplace(scriptCanonicalizeRegExp, + ((s: String) => s.toUpperCase()): js.Function1[String, String]) + + try { + new js.RegExp(s"\\p{sc=$canonical}", "u") + } catch { + case _: Throwable => + parseError(s"Unknown character script name {$scriptName}") + } + + canonical + } + } + + private def compileCharacterClass(): String = { + // scalastyle:off return + // the 'return' is in the case ']' + + val pattern = PatternCompiler.this.pattern // local copy + val len = pattern.length() + + pIndex += 1 // skip '[' + + /* If there is a leading '^' right after the '[', the whole class is + * negated. In a sense, '^' is the operator with the lowest precedence. + */ + val isNegated = pIndex != len && pattern.charAt(pIndex) == '^' + if (isNegated) + pIndex += 1 + + val builder = new CharacterClassBuilder(asciiCaseInsensitive, isNegated) + + while (pIndex != len) { + def processRangeOrSingleCodePoint(startCodePoint: Int): Unit = { + if (comments) + skipComments() + + if (pIndex != len && pattern.charAt(pIndex) == '-') { + // Perhaps a range of code points, unless the '-' is followed by '[' or ']' + pIndex += 1 + if (comments) + skipComments() + + if (pIndex == len) + parseError("Unclosed character class") + + val cpEnd = pattern.codePointAt(pIndex) + + if (cpEnd == '[' || cpEnd == ']') { + // Oops, it wasn't a range after all + builder.addSingleCodePoint(startCodePoint) + builder.addSingleCodePoint('-') + } else { + // Range of code points + pIndex += charCount(cpEnd) + val endCodePoint = + if (cpEnd == '\\') parseSingleCodePointEscape() + else cpEnd + if (endCodePoint < startCodePoint) + parseError("Illegal character range") + builder.addCodePointRange(startCodePoint, endCodePoint) + } + } else { + // Single code point + builder.addSingleCodePoint(startCodePoint) + } + } + + (pattern.codePointAt(pIndex): @switch) match { + case ']' => + pIndex += 1 + return builder.finish() + + case '&' => + pIndex += 1 + if (pIndex != len && pattern.charAt(pIndex) == '&') { + pIndex += 1 + builder.startNewConjunct() + } else { + processRangeOrSingleCodePoint('&') + } + + case '[' => + builder.addCharacterClass(compileCharacterClass()) + + case '\\' => + pIndex += 1 + if (pIndex == len) + parseError("Illegal escape sequence") + val c2 = pattern.charAt(pIndex) + (c2: @switch) match { + case 'd' | 'D' | 'h' | 'H' | 's' | 'S' | 'v' | 'V' | 'w' | 'W' | 'p' | 'P' => + builder.addCharacterClass(parsePredefinedCharacterClass(c2)) + + case 'Q' => + pIndex += 1 + val end = pattern.indexOf("\\E", pIndex) + if (end < 0) + parseError("Unclosed character class") + builder.addCodePointsInString(pattern, pIndex, end) + pIndex = end + 2 // for the \E + + case _ => + processRangeOrSingleCodePoint(parseSingleCodePointEscape()) + } + + case ' ' | '\t' | '\n' | '\u000B' | '\f' | '\r' if comments => + pIndex += 1 + case '#' if comments => + skipSharpComment() + + case codePoint => + pIndex += charCount(codePoint) + processRangeOrSingleCodePoint(codePoint) + } + } + + parseError("Unclosed character class") + // scalastyle:on return + } + + private def compileGroup(): String = { + val pattern = this.pattern // local copy + val len = pattern.length() + + val start = pIndex + + if (start + 1 == len || pattern.charAt(start + 1) != '?') { + // Numbered capturing group + pIndex = start + 1 + compiledGroupCount += 1 + groupNumberMap.push(compiledGroupCount) + "(" + compileInsideGroup() + ")" + } else { + if (start + 2 == len) + parseError("Unclosed group") + + val c1 = pattern.charAt(start + 2) + + if (c1 == ':' || c1 == '=' || c1 == '!') { + // Non-capturing group or look-ahead + pIndex = start + 3 + pattern.jsSubstring(start, start + 3) + compileInsideGroup() + ")" + } else if (c1 == '<') { + if (start + 3 == len) + parseError("Unclosed group") + + val c2 = pattern.charAt(start + 3) + + if (isLetter(c2)) { + // Named capturing group + pIndex = start + 3 + val name = parseGroupName() + if (dictContains(namedGroups, name)) + parseError(s"named capturing group <$name> is already defined") + compiledGroupCount += 1 + groupNumberMap.push(compiledGroupCount) // this changes originalGroupCount + dictSet(namedGroups, name, originalGroupCount) + pIndex += 1 + "(" + compileInsideGroup() + ")" + } else { + // Look-behind group + if (c2 != '=' && c2 != '!') + parseError("Unknown look-behind group") + requireES2018Features("Look-behind group") + pIndex = start + 4 + pattern.jsSubstring(start, start + 4) + compileInsideGroup() + ")" + } + } else if (c1 == '>') { + // Atomic group + pIndex = start + 3 + compiledGroupCount += 1 + val groupNumber = compiledGroupCount + s"(?:(?=(${compileInsideGroup()}))\\$groupNumber)" + } else { + parseError("Embedded flag expression in the middle of a pattern is not supported") + } + } + } + + /** Parses a group name. + * + * Pre: `pIndex` should point right after the opening '<'. + * + * Post: `pIndex` points right before the closing '>' (it is guaranteed to be a '>'). + */ + private def parseGroupName(): String = { + val pattern = this.pattern // local copy + val len = pattern.length() + val start = pIndex + while (pIndex != len && isLetterOrDigit(pattern.charAt(pIndex))) + pIndex += 1 + if (pIndex == len || pattern.charAt(pIndex) != '>') + parseError("named capturing group is missing trailing '>'") + pattern.jsSubstring(start, pIndex) + } +} diff --git a/javalib/src/main/scala/java/util/regex/PatternSyntaxException.scala b/javalib/src/main/scala/java/util/regex/PatternSyntaxException.scala new file mode 100644 index 0000000000..945753d91b --- /dev/null +++ b/javalib/src/main/scala/java/util/regex/PatternSyntaxException.scala @@ -0,0 +1,41 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package java.util.regex + +import scala.scalajs.js +import scala.scalajs.runtime.linkingInfo +import scala.scalajs.LinkingInfo + +class PatternSyntaxException(desc: String, regex: String, index: Int) + extends IllegalArgumentException { + + def getIndex(): Int = index + + def getDescription(): String = desc + + def getPattern(): String = regex + + override def getMessage(): String = { + // local copies, for code size + val idx = index + val re = regex + + val indexHint = if (idx < 0) "" else " near index " + idx + val base = desc + indexHint + "\n" + re + + if (idx >= 0 && re != null && idx < re.length()) + base + "\n" + " ".asInstanceOf[java.lang._String].repeat(idx) + "^" + else + base + } +} diff --git a/javalib/src/main/scala/java/util/regex/README.md b/javalib/src/main/scala/java/util/regex/README.md new file mode 100644 index 0000000000..e14742347f --- /dev/null +++ b/javalib/src/main/scala/java/util/regex/README.md @@ -0,0 +1,324 @@ +# Design document for the implementation of `j.u.regex.*` + +Java and JavaScript have different support for regular expressions. +In addition to Java having many more features, they also *differ* in the specifics of most of the features they have in common. + +For performance and code size reasons, we still want to use the native JavaScript `RegExp` class. +Modern JavaScript engines JIT-compile `RegExp`s to native code, so it is impossible to compete with that using a user-space engine. +For example, see [V8 talking about its Irregexp library](https://blog.chromium.org/2009/02/irregexp-google-chromes-new-regexp.html) and [SpiderMonkey talking about their latest integration of Irregexp](https://hacks.mozilla.org/2020/06/a-new-regexp-engine-in-spidermonkey/). + +Therefore, our strategy for `java.util.regex` is to *compile* Java regexes down to JavaScript regexes that behave in the same way. +The compiler is in the file `PatternCompiler.scala`, and is invoked at the time of `Pattern.compile()`. + +We can deal with most features in a compliant way using that strategy, while retaining performance, and without sacrificing code size too much compared to directly passing regexes through without caring about the discrepancies. +There are however a few features that are either never supported, or only supported when targeting a recent enough version of ECMAScript. + +## Support + +The set of supported features depends on the target ECMAScript version, specified in `ESFeatures.esVersion`. + +The following features are never supported: + +* the `CANON_EQ` flag, +* the `\X`, `\b{g}` and `\N{...}` expressions, +* `\p{In𝘯𝘢𝘮𝘦}` character classes representing Unicode *blocks*, +* the `\G` boundary matcher, *except* if it appears at the very beginning of the regex (e.g., `\Gfoo`), +* embedded flag expressions with inner groups, i.e., constructs of the form `(?idmsuxU-idmsuxU:𝑋)`, +* embedded flag expressions without inner groups, i.e., constructs of the form `(?idmsuxU-idmsuxU)`, *except* if they appear at the very beginning of the regex (e.g., `(?i)abc` is accepted, but `ab(?i)c` is not), and +* numeric "back" references to groups that are defined later in the pattern (note that even Java does not support *named* back references like that). + +The following features require `esVersion >= ESVersion.ES2015`: + +* the `UNICODE_CASE` flag. + +The following features require `esVersion >= ESVersion.ES2018`: + +* the `MULTILINE` and `UNICODE_CHARACTER_CLASS` flags, +* look-behind assertions `(?<=𝑋)` and `(?𝑋)`, +* possessive quantifiers `𝑋*+`, `𝑋++` and `𝑋?+`, +* the `\A`, `\Z` and `\z` boundary matchers, +* the `\R` expression, +* embedded quotations with `\Q` and `\E`, both outside and inside character classes. + +All the supported features have the correct semantics from Java. +This is even true for features that exist in JavaScript but with different semantics, among which: + +* the `^` and `$` boundary matchers with the `MULTILINE` flag (when the latter is supported), +* the predefined character classes `\h`, `\s`, `\v`, `\w` and their negated variants, respecting the `UNICODE_CHARACTER_CLASS` flag, +* the `\b` and `\B` boundary matchers, respecting the `UNICODE_CHARACTER_CLASS` flag, +* the internal format of `\p{𝘯𝘢𝘮𝘦}` character classes, including the `\p{java𝘔𝘦𝘵𝘩𝘰𝘥𝘕𝘢𝘮𝘦}` classes, +* octal escapes and control escapes. + +### Guarantees + +If a feature is not supported, a `PatternSyntaxException` is thrown at the time of `Pattern.compile()`. + +If `Pattern.compile()` succeeds, the regex is guaranteed to behave exactly like on the JVM, *except* for capturing groups within repeated segments (both for their back references and subsequent calls to `group`, `start` and `end`): + +* on the JVM, a capturing group always captures whatever substring was successfully matched last by *that* group during the processing of the regex: + - even if it was in a previous iteration of a repeated segment and the last iteration did not have a match for that group, or + - if it was during a later iteration of a repeated segment that was subsequently backtracked; +* in JS, capturing groups within repeated segments always capture what was matched (or not) during the last iteration that was eventually kept. + +The behavior of JavaScript is more "functional", whereas that of the JVM is more "imperative". +This imperative nature is also reflected in the `hitEnd()` and `requireEnd()` methods of `Matcher`, which we do not support (they don't link). + +The behavior of the JVM does not appear to be specified, and is questionable. +There are several open issues that argue it is buggy: + +* https://bugs.openjdk.java.net/browse/JDK-8027747 +* https://bugs.openjdk.java.net/browse/JDK-8187083 +* https://bugs.openjdk.java.net/browse/JDK-8187080 +* https://bugs.openjdk.java.net/browse/JDK-8187082 + +Therefore, it seems wise to keep the JavaScript behavior, and not try to replicate the JVM behavior at great cost (if that is even possible within our constrains). + +## Implementation strategy + +Java regexes are compiled to JS regexes in one pass, using a recursive descent approach. +There is a state variable `pIndex` which indicates the position inside the original `pattern`. +Compilation methods parse a subexpression at `pIndex`, advance `pIndex` past what they parsed, and return the result of the compilation. + +Parsing is always done at the code point level, and not at the individual `Char` level, using the [WTF-16 encoding](https://simonsapin.github.io/wtf-8/#wtf-16). +See [Handling surrogate pairs without support for the 'u' flag](#handling-surrogate-pairs-without-support-for-the-u-flag) for details about the behavior of lone surrogates. + +We first describe the compilation with the assumption that the underlying `RegExp`s support the `u` flag. +This is always true in ES 2015+, and dynamically determined at run-time in ES 5.1. +We will cover later what happens when it is not supported. + +### JS RegExp flags and case sensitivity + +Irrespective of the Java flags, we always use the following JS flags when they are supported (including through dynamic detection): + +- 'u' for correct handling of surrogate pairs and Unicode rules for case folding (introduced in ES2015), +- 's' for the dotAll behavior, i.e., `.` matches any code point (introduced in ES2018). + +In addition, we use the 'i' JS flag when both `CASE_INSENSITIVE` and `UNICODE_CASE` are on. +Since `UNICODE_CASE` is only supported in ES 2015+, this implies that 'u' is supported, and hence that we can leave all the handling of case insensitivity to the native RegExp. + +When `CASE_INSENSITIVE` is on but `UNICODE_CASE` is off, we must apply ASCII case insensitivity. +This is not supported by JS RegExps, so we implement it ourselves during compilation. +This is represented by the property `asciiCaseInsensitive`. +When it is true: + +* any single code point that is an ASCII letter, such as 'g', is compiled to a character class with the uppercase and lowercase variants (e.g., `[Gg]`), in subexpressions or in character classes, and +* any character range in a character class that intersects with the range `A-Z` and/or `a-z` is compiled with additional range(s) to cover the uppercase and lowercase variants. + +`PatternCompiler` never uses any other JS RegExp flag. +`Pattern` adds the 'g' flag for its general-purpose instance of `RegExp` (the one used for everything except `Matcher.matches()`), as well as the 'y' flag if the regex is sticky and it is supported. + +### Capturing groups + +Usually, there is a 1-to-1 relationship between original group numbers and compiled groups numbers. +However, differences are introduced when compiling atomic groups and possessive quantifiers. +Therefore, we maintain a mapping from original group numbers to the corresponding group numbers in the compiled pattern. +We use it for the following purposes: + +* when compiling back references of the form `\𝑁`, and +* when using the `Matcher` API to retrieve the groups' contents, start and end positions. + +Named capturing groups are always compiled as numbered capturing groups, even in ES 2018+. +We record an additional map of names to the corresponding original group numbers, and use it + +* when compiling named back references of the form `\k<𝘯𝘢𝘮𝘦>` (as numbered back references), and +* when using the `Matcher` API with group names. + +### Other main "control structures" + +The following constructs are translated as is: + +* Sequences and alternatives, +* Greedy quantifiers of the form `𝑋*`, `𝑋+` and `𝑋?`, +* Lazy quantifiers of the form `𝑋*?`, `𝑋+?` and `𝑋??`, +* Non-capturing groups of the form `(?:𝑋)`, +* Look-ahead groups of the form `(?=𝑋)` and `(?!𝑋)`, +* Look-behind groups of the form `(?<=𝑋)` and `(?𝑋)`, and +* Possessive quantifiers, for example of the form `𝑋*+`. + +### Single code points + +Subexpressions that represent a single code point are parsed and normalized as the code point that they represent. +For example, both `a` and `\x65` are compiled as `a`. +Code points that are metacharacters in JS regexes (i.e., `^ $ \ . * + ? ( ) [ ] { } |`) are escaped with a `\`, for example `\$`. +This is implemented in `def literal(cp: Int)`. + +Note that a double escape of the form `\uℎℎℎℎ\uℎℎℎℎ` representing a high surrogate and a low surrogate is treated as a single escape for a single supplementary code point. +For example, `\uD834\uDD1E` is considered as a single escape for the code point `𝄞` (U+1D11E Musical Symbol G Clef). + +This behavior only applies to `\u` escapes. +A would-be double-escape `\x{D834}\x{DD1E}` constitutes two separate code points. +In practice, such a sequence can never match anything in the input; if the input contained that sequence of code units, it would be considered as a single code point `𝄞`, which is not matched by a pattern meant to match two separate code points U+D834 and U+DD1E. + +### Quotes + +A quote starts with `\Q`, and ends at the first occurrence of `\E` or the end of the string. +The full string in between is taken as a sequence of code points. + +Each code point is compiled as described in "Single code points" for `def literal(cp: Int)`, and the compiled patterns are concatenated in a sequence. +This is implemented in `def literal(s: String)`. + +### Predefined character classes + +Predefined character classes represent a set of code points that matches a single code point in the input string. +The set typically depends on the value of `UNICODE_CHARACTER_CLASS`. + +Since virtually none of them has a corresponding predefined character class in JS RegExps, they are all compiled as custom `[...]` character classes, according to their definition. + +### Atomic groups + +Atomic groups are not well documented in the JavaDoc, but they are well covered in outside documentation such as [on Regular-Expressions.info](https://www.regular-expressions.info/atomic.html). +They have the form `(?>𝑋)`. +An atomic group matches whatever `𝑋` matches, but once it has successfully matched a particular substring, it is considered as an atomic unit. +If backtracking is needed later on because the rest of the pattern failed to match, the atomic group is backtracked as a whole. + +JS does not support atomic groups. +However, there exists a trick to implement atomic groups on top of look-ahead groups and back references, including with the correct performance characterics. +It is well documented in the article [Mimicking Atomic Groups](https://blog.stevenlevithan.com/archives/mimic-atomic-groups). +In a nutshell, we compile `(?>𝑋)` to `(?:(?=(𝑋))\𝑁)` where `𝑁` is the allocated group number for the capturing group `(𝑋)`. + +This introduces a discrepancy between the original group numbers and the compiled group numbers for any subsequent capturing group. +This is why we maintain `groupNumberMap`. +Note that the discrepancy applies within `𝑋` as well, so we record it before compiling the subexpression `𝑋`. + +### Possessive quantifiers + +[Possessive quantifiers](https://www.regular-expressions.info/possessive.html) can be interpreted as sugar for atomic groups over greedy quantifiers. +For example, `𝑋*+` is equivalent to `(?>𝑋*)`. + +Since JS does not support possessive quantifiers any more than atomic groups, we compile them as that desugaring, followed by the compilation scheme of atomic groups. + +However, there is an additional problem. +For atomic groups, we know before parsing `𝑋` that we need to record a discrepancy in the group numbering. +For possessive quantifiers, we only know that *after* having parsed `𝑋`, but it should apply also *within* `𝑋`. +We do that with postprocessing. +Before compiling any token `𝑋`, we record the current `compiledGroupCount`, and when compiling a possessive quantifier, we increment the compiled group number of those greater than the recorded count. +We do this + +- in the values of `groupNumberMap`, and +- in the back references found in the compiled pattern for `𝑋`. + +The latter is pretty ugly, but is robust nevertheless. + +### Custom character classes + +Unlike JavaScript, Java regexes support intersections and unions of character classes. +We compile them away using the following equivalences: + +* Positive intersection: `[𝐴&&𝐵]` is equivalent to `(?=[𝐴])[𝐵]` +* Negative intersection: `[^𝐴&&𝐵]` is equivalent to `[^𝐴]|[^𝐵]` +* Positive union: `[𝐴𝐵]` is equivalent to `[𝐴]|[𝐵]` +* Negative union: `[^𝐴𝐵]` is equivalent to `(?![𝐴])[^𝐵]` + +For example, using the rule on positive intersection, we can compile the example from the JavaDoc `[a-z&&[^m-p]]` to `(?=[a-z])[^m-p]`. + +An alternative design would have been to resolve all the operations at compile-time to get to flat code point sets. +This would require to expand `\p{}` and `\P{}` Unicode property names into equivalent sets, which would need a significant chunk of the Unicode database to be available. +That strategy would have a huge cost in terms of code size, and likely in terms of execution time as well (for compilation and/or matching). + +### Handling surrogate pairs without support for the 'u' flag + +So far, we have assumed that the underlying RegExp supports the 'u' flag, which we test with `supportsUnicode`. +In this section, we cover how the compilation is affected when it is not supported. +This can only happen when we target ES 5.1. + +The ECMAScript specification is very precise about how patterns and strings are interpreted when the 'u' flag is enabled. +It boils down to: + +* First, the pattern and the input, which are strings of 16-bit UTF-16 code units, are decoded into a *list of code points*, using the WTF-16 encoding. + This means that surrogate pairs become single supplementary code points, while lone surrogates (and other code units) become themselves. +* Then, all the regular expressions operators work on these lists of code points, never taking individual code units into account. + +The documentation for Java regexes does not really say anything about what it considers "characters" to be. +However, experimentation and tests show that they behave exactly like ECMAScript with the 'u' flag. + +Without support for the 'u' flag, the JavaScript RegExp engine will parse the pattern and process the input with individual Chars rather than code points. +In other words, it will consider surrogate pairs as two separate (and therefore separable) code units. +If we do nothing against it, it can jeopardize the semantics of regexes in several ways: + +* a `.` will match only the high surrogate of a surrogate pair instead of the whole codepoint, +* same issue with any negative character class like `[^a]`, +* an unpaired high surrogate in the pattern may match the high surrogate of a surrogate pair in the input, although it must not, +* a surrogate pair in a character class will be interpreted as *either* the high surrogate or the low surrogate, instead of both together, +* etc. + +Even patterns that contain only ASCII characters (escaped or not) and use no flags can behave incorrectly on inputs that contain surrogate characters (paired or unpaired). +A possible design would have been to restrict the *inputs* to strings without surrogate code units when targeting ES 5.1. +However, that could lead to patterns that fail at matching-time, rather than at compile-time (during `Pattern.compile()`), unlike all the other features that are conditioned on the ES version. + +Therefore, we go to great lengths to implement the right semantics despite the lack of support for 'u'. + +#### Overall idea of the solution + +When `supportsUnicode` is false, we apply the following changes to the compilation scheme. +In general, we make sure that: + +* something that can match a high surrogate does not match one followed by a low surrogate, +* something that can match a supplementary code point or a high surrogate never selects the high surrogate if it could match the whole code point. + +We do nothing special for low surrogates, as all possible patterns go from left to right (we don't have look-behinds in this context) and we otherwise make sure that all code points from the input are either fully matched or not at all. +Therefore, the "cursor" of the engine can never stop in the middle of a code point, and so low surrogates are only visible if they were unpaired to begin with. +The only exception to this is when the cursor is at the beginning of the pattern, when using `find`. +In that case we cannot a priori prevent the JS engine from trying to find a match starting in the middle of a code point. +To address that, we have special a posteriori handling in `Pattern.execFind()`. + +#### Concretely + +A single code point that is a high surrogate `𝑥` is compiled to `(?:𝑥(?![ℒ]))`, where `ℒ` is `\uDC00-\uDFFF`, the range of all low surrogates. +The negative look-ahead group prevents a match from separating the high surrogate from a following low surrogate. + +A dot-all (in `codePointNotAmong("")`) is compiled to `(?:[^ℋ]|[ℋ](?:[ℒ]|(?![ℒ])))`, where `ℋ` is `\uD800-\uDBFF`, the range of all high surrogates. +This means either + +* any code unit that is not a high surrogate, or +* a high surrogate and a following low surrogate (taking a full code point is allowed), or +* a high surrogate that is not followed by a low surrogate (separating a surrogate pair is not allowed). + +We restrict the internal contract of `codePointNotAmong(𝑠)` to only take BMP code points that are not high surrogates, and compile it to the same as the dot-all but with the characters in `𝑠` excluded like the high surrogates: `(?:[^𝑠ℋ]|[ℋ](?:[ℒ]|(?![ℒ])))`. + +Since `UNICODE_CHARACTER_CLASS` is not supported, all but one call site of `codePointNotAmong` already respect that stricter contract. +The only one that does not is the call `codePointNotAmong(thisSegment)` inside `CharacterClassBuilder.conjunctResult()`. +To make that one compliant, we make sure not to add illegal code points in `thisSegment`. +To do that, we exploit the equivalences `[𝐴𝐵] = [𝐴]|[𝐵]` and `[^𝐴𝐵] = (?![𝐴])[𝐵]` where `𝐴` is an illegal code point to isolate it in a separate alternative, that we can compile as a single code point above. +For example, the character class `[k\uD834f]`, containing a high surrogate code point, is equivalent to `[\uD834]|[kf]`, which can be compiled as `(?:\uD834(?![ℒ]))|[kf])`. +That logic is implemented in `CharacterClassBuilder.addSingleCodePoint()`. + +Code point ranges that contain illegal code points are decomposed into the union of 4 (possibly empty) ranges: + +* one with only BMP code points below high surrogates, compiled as is +* one with high surrogates `𝑥-𝑦`, compiled to `(?:[𝑥-𝑦](?![ℒ]))` +* one with BMP code points above high surrogates, compiled as is +* one with supplementary code points `𝑥-𝑦`, where `𝑥` is the surrogate pair `𝑝𝑞` and `𝑦` is the pair `𝑠𝑡`, which is further decomposed into: + * the range `𝑝𝑞-𝑝\uDFFF`, compiled as `(?:𝑝[𝑞-\uDFFF])` + * the range `𝑝′\uDC00-𝑠′\uDFFF` where 𝑝′ = 𝑝+1 and 𝑠′ = 𝑠−1, compiled to `(?:[𝑝′-𝑠′][\uDC00-\uDFFF])` + * the range `𝑠\uDC00-𝑠𝑡`, compiled to `(?:𝑠[\uDC00-𝑡])` + +That logic is implemented in `CharacterClassBuilder.addCodePointRange()`. + +## About code size + +For historical reasons, code size is critical in this class. +Before Scala.js 1.7.0, `java.util.regex.Pattern` was just a wrapper over native `RegExp`s. +The patterns were passed through with minimal preprocessing, without caring about the proper semantics. +This created an expectation of small code size for this class. +When we fixed the semantics, we had to introduce this compiler, which is non-trivial. +In order not to regress too much on code size, we went to great lengths to minimize the code size impact of this class, in particular in the default ES 2015 configuration. + +When modifying this code, make sure to preserve as small a code size as possible. diff --git a/javalib/src/main/scala/org/scalajs/javalibintf/StackTraceElement.scala b/javalib/src/main/scala/org/scalajs/javalibintf/StackTraceElement.scala new file mode 100644 index 0000000000..5237986051 --- /dev/null +++ b/javalib/src/main/scala/org/scalajs/javalibintf/StackTraceElement.scala @@ -0,0 +1,26 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.javalibintf + +import java.{lang => jl} + +object StackTraceElement { + def createWithColumnNumber(declaringClass: String, methodName: String, + fileName: String, lineNumber: Int, columnNumber: Int): jl.StackTraceElement = { + new jl.StackTraceElement(declaringClass, methodName, fileName, + lineNumber, columnNumber) + } + + def getColumnNumber(stackTraceElement: jl.StackTraceElement): Int = + stackTraceElement.getColumnNumber() +} diff --git a/javalib/src/main/scala/org/scalajs/javalibintf/TypedArrayBuffer.scala b/javalib/src/main/scala/org/scalajs/javalibintf/TypedArrayBuffer.scala new file mode 100644 index 0000000000..7fbe4d23c6 --- /dev/null +++ b/javalib/src/main/scala/org/scalajs/javalibintf/TypedArrayBuffer.scala @@ -0,0 +1,56 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.javalibintf + +import java.nio._ + +import scala.scalajs.js.typedarray._ + +object TypedArrayBuffer { + + def wrapInt8Array(array: Any): ByteBuffer = + ByteBuffer.wrapInt8Array(array.asInstanceOf[Int8Array]) + + def wrapUint16Array(array: Any): CharBuffer = + CharBuffer.wrapUint16Array(array.asInstanceOf[Uint16Array]) + + def wrapInt16Array(array: Any): ShortBuffer = + ShortBuffer.wrapInt16Array(array.asInstanceOf[Int16Array]) + + def wrapInt32Array(array: Any): IntBuffer = + IntBuffer.wrapInt32Array(array.asInstanceOf[Int32Array]) + + def wrapFloat32Array(array: Any): FloatBuffer = + FloatBuffer.wrapFloat32Array(array.asInstanceOf[Float32Array]) + + def wrapFloat64Array(array: Any): DoubleBuffer = + DoubleBuffer.wrapFloat64Array(array.asInstanceOf[Float64Array]) + + def hasArrayBuffer(buffer: Buffer): Boolean = + buffer.hasArrayBuffer() + + def arrayBuffer(buffer: Buffer): Any = + buffer.arrayBuffer() + + def arrayBufferOffset(buffer: Buffer): Int = + buffer.arrayBufferOffset() + + def dataView(buffer: Buffer): Any = + buffer.dataView() + + def hasTypedArray(buffer: Buffer): Boolean = + buffer.hasTypedArray() + + def typedArray(buffer: Buffer): Any = + buffer.typedArray() +} diff --git a/javalib/src/main/scala/scala/scalajs/js/typedarray/TypedArrayBufferBridge.scala b/javalib/src/main/scala/scala/scalajs/js/typedarray/TypedArrayBufferBridge.scala deleted file mode 100644 index b8440a4c3a..0000000000 --- a/javalib/src/main/scala/scala/scalajs/js/typedarray/TypedArrayBufferBridge.scala +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -/* !!!!! - * THIS FILE IS ALMOST COPY-PASTED IN javalib/ AND library/. - * THEY MUST BE KEPT IN SYNC. - * - * This file acts as bridge for scala.scalajs.js.typedarray to be able to - * access the additional public API provided by java.nio, but which is not - * part of the JDK API. Because javalib/ does not export its .class files, - * we cannot call this additonal API directly from library/, even though the - * members are public. - * - * In library/, this file has only the signatures, with stub implementations. - * In javalib/, it has the proper the proper implementations. - * The build keeps the .class coming from library/ and the .sjsir file from - * javalib/. This way, we bridge the library and javalib. But that means the - * binary interface of TypedArrayBufferBridge must be strictly equivalent in - * the two copies. - * - * (Yes, this is a hack.) - * !!!!! - */ - -package scala.scalajs.js.typedarray - -import java.nio._ - -private[typedarray] object TypedArrayBufferBridge { - def wrap(array: ArrayBuffer): ByteBuffer = - ByteBuffer.wrap(array) - - def wrap(array: ArrayBuffer, byteOffset: Int, length: Int): ByteBuffer = - ByteBuffer.wrap(array, byteOffset, length) - - def wrap(array: Int8Array): ByteBuffer = - ByteBuffer.wrap(array) - - def wrap(array: Uint16Array): CharBuffer = - CharBuffer.wrap(array) - - def wrap(array: Int16Array): ShortBuffer = - ShortBuffer.wrap(array) - - def wrap(array: Int32Array): IntBuffer = - IntBuffer.wrap(array) - - def wrap(array: Float32Array): FloatBuffer = - FloatBuffer.wrap(array) - - def wrap(array: Float64Array): DoubleBuffer = - DoubleBuffer.wrap(array) - - def Buffer_hasArrayBuffer(buffer: Buffer): Boolean = - buffer.hasArrayBuffer() - - def Buffer_arrayBuffer(buffer: Buffer): ArrayBuffer = - buffer.arrayBuffer() - - def Buffer_arrayBufferOffset(buffer: Buffer): Int = - buffer.arrayBufferOffset() - - def Buffer_dataView(buffer: Buffer): DataView = - buffer.dataView() - - def Buffer_hasTypedArray(buffer: Buffer): Boolean = - buffer.hasTypedArray() - - def Buffer_typedArray(buffer: Buffer): TypedArray[_, _] = - buffer.typedArray() -} diff --git a/javalibintf/src/main/java/org/scalajs/javalibintf/StackTraceElement.java b/javalibintf/src/main/java/org/scalajs/javalibintf/StackTraceElement.java new file mode 100644 index 0000000000..b2cdb29b62 --- /dev/null +++ b/javalibintf/src/main/java/org/scalajs/javalibintf/StackTraceElement.java @@ -0,0 +1,74 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.javalibintf; + +/** + * Scala.js-specific extensions for {@link java.lang.StackTraceElement}. + * + *

In the JavaScript ecosystem, it is common practice for stack traces to + * mention column numbers in addition to line numbers. The official API of + * {@link java.lang.StackTraceElement} does not allow for representing column + * numbers, but Scala.js supports them. + * + *

This class offers methods to manipulate the extended information of + * {@link java.lang.StackTraceElement} for Scala.js. + * + *

This class only contains static methods. It cannot be instantiated. + * + * @see java.lang.StackTraceElement + */ +public final class StackTraceElement { + private StackTraceElement() {} + + /** + * Creates a {@link java.lang.StackTraceElement} that includes a column number. + * + * @param declaringClass + * the fully qualified name of the class containing the execution point + * represented by the stack trace element + * @param methodName + * the name of the method containing the execution point represented by the + * stack trace element + * @param fileName + * the name of the file containing the execution point represented by the + * stack trace element, or null if this information is unavailable + * @param lineNumber + * the line number of the source line containing the execution point + * represented by this stack trace element, or a negative number if this + * information is unavailable + * @param columnNumber + * the column number within the source line containing the execution point + * represented by this stack trace element, or a negative number if this + * information is unavailable + * + * @return + * a new {@link java.lang.StackTraceElement} containing the provided information + */ + public static final java.lang.StackTraceElement createWithColumnNumber( + String declaringClass, String methodName, String fileName, + int lineNumber, int columnNumber) { + throw new AssertionError("stub"); + } + + /** + * Returns the column number of the provided {@link java.lang.StackTraceElement}. + * + * @return + * the column number of the provided stackTraceElement, or a negative + * number if this information is unavailable + */ + public static final int getColumnNumber( + java.lang.StackTraceElement stackTraceElement) { + throw new AssertionError("stub"); + } +} diff --git a/javalibintf/src/main/java/org/scalajs/javalibintf/TypedArrayBuffer.java b/javalibintf/src/main/java/org/scalajs/javalibintf/TypedArrayBuffer.java new file mode 100644 index 0000000000..436b6d7fec --- /dev/null +++ b/javalibintf/src/main/java/org/scalajs/javalibintf/TypedArrayBuffer.java @@ -0,0 +1,315 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.javalibintf; + +import java.nio.*; + +/** + * Utilities to interface {@link java.nio.Buffer}s and JavaScript TypedArrays. + * + *

{@link java.nio.Buffer}s can be direct buffers or + * indirect buffers. Indirect buffers use an underlying array (like + * {@code int[]} in Java or {@code Array[Int]} in Scala). Direct buffers are + * supposed to use off-heap memory. + * + *

In a JavaScript environment, the equivalent of off-heap memory for + * buffers of primitive numeric types are TypedArrays. + * + *

This class provides methods to wrap TypedArrays as direct Buffers, and + * extract references to TypedArrays from direct Buffers. + */ +public final class TypedArrayBuffer { + private TypedArrayBuffer() {} + + /** + * Wraps a JavaScript {@code Int8Array} as a direct + * {@link java.nio.ByteBuffer}. + * + *

The provided {@code array} parameter must be a valid JavaScript + * {@code Int8Array}, otherwise the behavior of this method is not + * specified. + * + *

The returned {@link java.nio.ByteBuffer} has the following properties: + * + *

    + *
  • It has a {@code capacity()} equal to the {@code array.length}.
  • + *
  • Its initial {@code position()} is 0 and its {@code limit()} is its capacity.
  • + *
  • It is a direct buffer backed by the provided {@code Int8Array}: + * changes to one are reflected on the other.
  • + *
+ * + * @param array a JavaScript {@code Int8Array} + */ + public static final ByteBuffer wrapInt8Array(Object array) { + throw new AssertionError("stub"); + } + + /** + * Wraps a JavaScript {@code Uint16Array} as a direct + * {@link java.nio.CharBuffer}. + * + *

The provided {@code array} parameter must be a valid JavaScript + * {@code Uint16Array}, otherwise the behavior of this method is not + * specified. + * + *

The returned {@link java.nio.CharBuffer} has the following properties: + * + *

    + *
  • It has a {@code capacity()} equal to the {@code array.length}.
  • + *
  • Its initial {@code position()} is 0 and its {@code limit()} is its capacity.
  • + *
  • It is a direct buffer backed by the provided {@code Uint16Array}: + * changes to one are reflected on the other.
  • + *
+ * + * @param array a JavaScript {@code Uint16Array} + */ + public static final CharBuffer wrapUint16Array(Object array) { + throw new AssertionError("stub"); + } + + /** + * Wraps a JavaScript {@code Int16Array} as a direct + * {@link java.nio.ShortBuffer}. + * + *

The provided {@code array} parameter must be a valid JavaScript + * {@code Int16Array}, otherwise the behavior of this method is not + * specified. + * + *

The returned {@link java.nio.ShortBuffer} has the following properties: + * + *

    + *
  • It has a {@code capacity()} equal to the {@code array.length}.
  • + *
  • Its initial {@code position()} is 0 and its {@code limit()} is its capacity.
  • + *
  • It is a direct buffer backed by the provided {@code Int16Array}: + * changes to one are reflected on the other.
  • + *
+ * + * @param array a JavaScript {@code Int16Array} + */ + public static final ShortBuffer wrapInt16Array(Object array) { + throw new AssertionError("stub"); + } + + /** + * Wraps a JavaScript {@code Int32Array} as a direct + * {@link java.nio.IntBuffer}. + * + *

The provided {@code array} parameter must be a valid JavaScript + * {@code Int32Array}, otherwise the behavior of this method is not + * specified. + * + *

The returned {@link java.nio.IntBuffer} has the following properties: + * + *

    + *
  • It has a {@code capacity()} equal to the {@code array.length}.
  • + *
  • Its initial {@code position()} is 0 and its {@code limit()} is its capacity.
  • + *
  • It is a direct buffer backed by the provided {@code Int32Array}: + * changes to one are reflected on the other.
  • + *
+ * + * @param array a JavaScript {@code Int32Array} + */ + public static final IntBuffer wrapInt32Array(Object array) { + throw new AssertionError("stub"); + } + + /** + * Wraps a JavaScript {@code Float32Array} as a direct + * {@link java.nio.FloatBuffer}. + * + *

The provided {@code array} parameter must be a valid JavaScript + * {@code Float32Array}, otherwise the behavior of this method is not + * specified. + * + *

The returned {@link java.nio.FloatBuffer} has the following properties: + * + *

    + *
  • It has a {@code capacity()} equal to the {@code array.length}.
  • + *
  • Its initial {@code position()} is 0 and its {@code limit()} is its capacity.
  • + *
  • It is a direct buffer backed by the provided {@code Float32Array}: + * changes to one are reflected on the other.
  • + *
+ * + * @param array a JavaScript {@code Float32Array} + */ + public static final FloatBuffer wrapFloat32Array(Object array) { + throw new AssertionError("stub"); + } + + /** + * Wraps a JavaScript {@code Float64Array} as a direct + * {@link java.nio.DoubleBuffer}. + * + *

The provided {@code array} parameter must be a valid JavaScript + * {@code Float64Array}, otherwise the behavior of this method is not + * specified. + * + *

The returned {@link java.nio.DoubleBuffer} has the following properties: + * + *

    + *
  • It has a {@code capacity()} equal to the {@code array.length}.
  • + *
  • Its initial {@code position()} is 0 and its {@code limit()} is its capacity.
  • + *
  • It is a direct buffer backed by the provided {@code Float64Array}: + * changes to one are reflected on the other.
  • + *
+ * + * @param array a JavaScript {@code Float64Array} + */ + public static final DoubleBuffer wrapFloat64Array(Object array) { + throw new AssertionError("stub"); + } + + /** + * Tests whether the given {@link java.nio.Buffer} is backed by an accessible + * JavaScript {@code ArrayBuffer}. + * + *

This is true for all read-write direct buffers, in particular for those + * created with any of the {@code wrapX} methods of this class. + * + *

If this method returns {@code true}, then {@code arrayBuffer(buffer)}, + * {@code arrayBufferOffset(buffer)} and {@code dataView(buffer)} do not + * throw any {@link UnsupportedOperationException}. + * + * @return + * true if and only if the provided {@code buffer} is backed by an + * accessible JavaScript {@code ArrayBuffer} + * + * @see TypedArrayBuffer#arrayBuffer(Buffer) + * @see TypedArrayBuffer#arrayBufferOffset(Buffer) + * @see TypedArrayBuffer#dataView(Buffer) + */ + public static final boolean hasArrayBuffer(Buffer buffer) { + throw new AssertionError("stub"); + } + + /** + * Returns the JavaScript {@code ArrayBuffer} backing the provided + * {@link java.nio.Buffer}. + * + *

The {@code buffer} may represent a view of the returned + * {@code ArrayBuffer} that does not start at index 0. Use the method + * {@link TypedArrayBuffer#arrayBufferOffset(Buffer)} to retrieve the offset + * within the {@code ArrayBuffer}. + * + * @return + * the JavaScript {@code ArrayBuffer} backing the provided {@code buffer} + * + * @throws UnsupportedOperationException + * if the provided {@code buffer} is read-only or is not backed by a + * JavaScript {@code ArrayBuffer}, i.e., if {@code hasArrayBuffer(buffer)} + * returns {@code false} + * + * @see TypedArrayBuffer#hasArrayBuffer(Buffer) + * @see TypedArrayBuffer#arrayBufferOffset(Buffer) + */ + public static final Object arrayBuffer(Buffer buffer) throws UnsupportedOperationException { + throw new AssertionError("stub"); + } + + /** + * Returns the offset within the JavaScript {@code ArrayBuffer} backing the + * provided {@link java.nio.Buffer}. + * + * @return + * the offset within the JavaScript {@code ArrayBuffer} backing the + * provided {@code buffer} where the latter starts + * + * @throws UnsupportedOperationException + * if the provided {@code buffer} is read-only or is not backed by a + * JavaScript {@code ArrayBuffer}, i.e., if {@code hasArrayBuffer(buffer)} + * returns {@code false} + * + * @see TypedArrayBuffer#hasArrayBuffer(Buffer) + * @see TypedArrayBuffer#arrayBuffer(Buffer) + */ + public static final int arrayBufferOffset(Buffer buffer) throws UnsupportedOperationException { + throw new AssertionError("stub"); + } + + /** + * Returns a JavaScript {@code DataView} of the provided + * {@link java.nio.Buffer}. + * + * @return + * a JavaScript {@code DataView} of the provided {@code buffer} + * + * @throws UnsupportedOperationException + * if the provided {@code buffer} is read-only or is not backed by a + * JavaScript {@code ArrayBuffer}, i.e., if {@code hasArrayBuffer(buffer)} + * returns {@code false} + * + * @see TypedArrayBuffer#hasArrayBuffer(Buffer) + */ + public static final Object dataView(Buffer buffer) throws UnsupportedOperationException { + throw new AssertionError("stub"); + } + + /** + * Tests whether the given {@link java.nio.Buffer} is backed by an accessible + * JavaScript {@code TypedArray}. + * + *

This is true when all of the following conditions apply: + * + *

    + *
  • the buffer is a direct buffer,
  • + *
  • it is not read-only,
  • + *
  • its byte order corresponds to the native byte order of JavaScript + * {@code TypedArray}s, and
  • + *
  • it is not a {@link java.nio.LongBuffer}.
  • + *
+ * + *

In particular, it is true for all {@link java.nio.Buffer}s created with + * any of the {@code wrapXArray} methods of this class. + * + *

If this method returns {@code true}, then {@code typedArray(buffer)} + * does not throw any {@link UnsupportedOperationException}. + * + * @return + * true if and only if the provided {@code buffer} is backed by an + * accessible JavaScript {@code TypedArray} + * + * @see TypedArrayBuffer#typedArray(Buffer) + */ + public static final boolean hasTypedArray(Buffer buffer) { + throw new AssertionError("stub"); + } + + /** + * Returns a JavaScript {@code TypedArray} view of the provided + * {@link java.nio.Buffer}. + * + *

The particular type of {@code TypedArray} depends on the type of buffer: + * + *

    + *
  • an {@code Int8Array} for a {@link java.nio.ByteBuffer}
  • + *
  • a {@code Uint16Array} for a {@link java.nio.CharBuffer}
  • + *
  • an {@code Int16Array} for a {@link java.nio.ShortBuffer}
  • + *
  • an {@code Int32Array} for a {@link java.nio.IntBuffer}
  • + *
  • an {@code Float32Array} for a {@link java.nio.FloatBuffer}
  • + *
  • an {@code Float64Array} for a {@link java.nio.DoubleBuffer}
  • + *
+ * + * @return + * a JavaScript {@code TypedArray} view of the provided {@code buffer} + * + * @throws UnsupportedOperationException + * if the provided {@code buffer} is read-only or is not backed by a + * JavaScript {@code TypedArray}, i.e., if {@code hasTypedArray(buffer)} + * returns {@code false} + * + * @see TypedArrayBuffer#hasTypedArray(Buffer) + */ + public static final Object typedArray(Buffer buffer) throws UnsupportedOperationException { + throw new AssertionError("stub"); + } +} diff --git a/js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/AsyncTests.scala b/js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/AsyncTests.scala deleted file mode 100644 index 076f90f893..0000000000 --- a/js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/AsyncTests.scala +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv.test - -import org.scalajs.jsenv._ - -import org.scalajs.core.tools.io._ -import org.scalajs.core.tools.logging._ - -import org.junit.Test -import org.junit.Assert._ - -import scala.concurrent.{Future, Await} -import scala.concurrent.duration._ - -/** A couple of tests that test async runners for mix-in into a test suite */ -trait AsyncTests extends BasicJSEnvTests { - - protected final val DefaultTimeout: Duration = 10.seconds - - protected def newJSEnv: AsyncJSEnv - - protected def asyncRunner(code: String): AsyncJSRunner = { - val codeVF = new MemVirtualJSFile("testScript.js").withContent(code) - newJSEnv.asyncRunner(codeVF) - } - - protected def start(runner: AsyncJSRunner): Future[Unit] = { - runner.start(new ScalaConsoleLogger(Level.Warn), ConsoleJSConsole) - } - - @Test - def futureTest: Unit = { - val runner = asyncRunner("") - val fut = start(runner) - - Await.result(fut, DefaultTimeout) - - assertFalse("VM should be terminated", runner.isRunning) - } - - @Test - def stopAfterTerminatedTest: Unit = { - val runner = asyncRunner("") - val fut = start(runner) - - Await.result(fut, DefaultTimeout) - - runner.stop() // should do nothing, and not fail - } - -} diff --git a/js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/BasicJSEnvTests.scala b/js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/BasicJSEnvTests.scala deleted file mode 100644 index 46600b8996..0000000000 --- a/js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/BasicJSEnvTests.scala +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv.test - -import org.junit.Test -import org.junit.Assert._ - -/** Tests that should succeed on any JSEnv */ -trait BasicJSEnvTests extends JSEnvTest { - - @Test - def failureTest: Unit = { - - """ - var a = {}; - a.foo(); - """.fails() - - } - - @Test - def syntaxErrorTest: Unit = { - - """ - { - """.fails() - - } - - @Test // Failed in Phantom - #2053 - def utf8Test: Unit = { - - """ - console.log("\u1234"); - """ hasOutput "\u1234\n"; - - } - - @Test - def allowScriptTags: Unit = { - - """ - console.log(""); - """ hasOutput "\n"; - - } - -} diff --git a/js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/ComTests.scala b/js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/ComTests.scala deleted file mode 100644 index 45125ce2a7..0000000000 --- a/js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/ComTests.scala +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv.test - -import org.scalajs.jsenv._ - -import org.scalajs.core.tools.io._ - -import org.junit.Test -import org.junit.Assert._ - -import scala.concurrent.Await - -/** A couple of tests that test communication for mix-in into a test suite */ -trait ComTests extends AsyncTests { - - protected def newJSEnv: ComJSEnv - - protected def comRunner(code: String): ComJSRunner = { - val codeVF = new MemVirtualJSFile("testScript.js").withContent(code) - newJSEnv.comRunner(codeVF) - } - - private def assertThrowClosed(msg: String, body: => Unit): Unit = { - val thrown = try { - body - false - } catch { - case _: ComJSEnv.ComClosedException => - true - } - - assertTrue(msg, thrown) - } - - @Test - def comCloseJVMTest: Unit = { - val com = comRunner(s""" - scalajsCom.init(function(msg) { scalajsCom.send("received: " + msg); }); - scalajsCom.send("Hello World"); - """) - - start(com) - - assertEquals("Hello World", com.receive()) - - for (i <- 0 to 10) { - com.send(i.toString) - assertEquals(s"received: $i", com.receive()) - } - - com.close() - com.await(DefaultTimeout) - - com.stop() // should do nothing, and not fail - } - - def comCloseJSTestCommon(timeout: Long): Unit = { - val com = comRunner(s""" - scalajsCom.init(function(msg) {}); - for (var i = 0; i < 10; ++i) - scalajsCom.send("msg: " + i); - scalajsCom.close(); - """) - - start(com) - - Thread.sleep(timeout) - - for (i <- 0 until 10) - assertEquals(s"msg: $i", com.receive()) - - assertThrowClosed("Expect receive to throw after closing of channel", - com.receive()) - - com.close() - com.await(DefaultTimeout) - - com.stop() // should do nothing, and not fail - } - - @Test - def comCloseJSTest: Unit = comCloseJSTestCommon(0) - - @Test - def comCloseJSTestDelayed: Unit = comCloseJSTestCommon(1000) - - @Test - def doubleCloseTest: Unit = { - val n = 10 - val com = pingPongRunner(n) - - start(com) - - for (i <- 0 until n) { - com.send("ping") - assertEquals("pong", com.receive()) - } - - com.close() - com.await(DefaultTimeout) - } - - @Test - def multiEnvTest: Unit = { - val n = 10 - val envs = List.fill(5)(pingPongRunner(10)) - - envs.foreach(start) - - val ops = List[ComJSRunner => Unit]( - _.send("ping"), - com => assertEquals("pong", com.receive()) - ) - - for { - i <- 0 until n - env <- envs - op <- ops - } op(env) - - envs.foreach(_.close()) - envs.foreach(_.await(DefaultTimeout)) - } - - private def pingPongRunner(count: Int) = { - comRunner(s""" - var seen = 0; - scalajsCom.init(function(msg) { - scalajsCom.send("pong"); - if (++seen >= $count) - scalajsCom.close(); - }); - """) - } - - @Test - def largeMessageTest: Unit = { - // 1KB data - val baseMsg = new String(Array.tabulate(512)(_.toChar)) - val baseLen = baseMsg.length - - // Max message size: 1KB * 2^(2*iters+1) = 1MB - val iters = 4 - - val com = comRunner(""" - scalajsCom.init(function(msg) { - scalajsCom.send(msg + msg); - }); - """) - - start(com) - - com.send(baseMsg) - - def resultFactor(iters: Int) = Math.pow(2, 2 * iters + 1).toInt - - for (i <- 0 until iters) { - val reply = com.receive() - - val factor = resultFactor(i) - - assertEquals(baseLen * factor, reply.length) - - for (j <- 0 until factor) - assertEquals(baseMsg, reply.substring(j * baseLen, (j + 1) * baseLen)) - - com.send(reply + reply) - } - - val lastLen = com.receive().length - assertEquals(baseLen * resultFactor(iters), lastLen) - - com.close() - com.await(DefaultTimeout) - } - - @Test - def highCharTest: Unit = { // #1536 - val com = comRunner(""" - scalajsCom.init(scalajsCom.send); - """) - - start(com) - - val msg = "\uC421\u8F10\u0112\uFF32" - - com.send(msg) - assertEquals(msg, com.receive()) - - com.close() - com.await(DefaultTimeout) - } - - @Test - def noInitTest: Unit = { - val com = comRunner("") - - start(com) - com.send("Dummy") - com.close() - com.await(DefaultTimeout) - } - - @Test - def stopTestCom: Unit = { - val com = comRunner(s"""scalajsCom.init(function(msg) {});""") - - start(com) - - // Make sure the VM doesn't terminate. - Thread.sleep(1000) - - assertTrue("VM should still be running", com.isRunning) - - // Stop VM instead of closing channel - com.stop() - - try { - com.await(DefaultTimeout) - fail("Stopped VM should be in failure state") - } catch { - case _: Throwable => - } - } - - @Test - def futureStopTest: Unit = { - val com = comRunner(s"""scalajsCom.init(function(msg) {});""") - - val fut = start(com) - - // Make sure the VM doesn't terminate. - Thread.sleep(1000) - - assertTrue("VM should still be running", com.isRunning) - - // Stop VM instead of closing channel - com.stop() - - try { - Await.result(fut, DefaultTimeout) - fail("Stopped VM should be in failure state") - } catch { - case _: Throwable => - } - } - -} diff --git a/js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/CustomInitFilesTest.scala b/js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/CustomInitFilesTest.scala deleted file mode 100644 index be4ae138c2..0000000000 --- a/js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/CustomInitFilesTest.scala +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv.test - -import org.scalajs.core.tools.io._ - -import org.junit.Test - -abstract class CustomInitFilesTest extends JSEnvTest { - def makeCustomInitFiles(): Seq[VirtualJSFile] = { - Seq(new MemVirtualJSFile("custominit.js").withContent(""" - function customPrint(s) { - console.log("custom: " + s); - } - """)) - } - - @Test - def customInitFilesTest: Unit = { - """ - customPrint("hello"); - """ hasOutput - """|custom: hello - |""".stripMargin - } -} diff --git a/js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/JSEnvTest.scala b/js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/JSEnvTest.scala deleted file mode 100644 index ca26440833..0000000000 --- a/js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/JSEnvTest.scala +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv.test - -import org.scalajs.jsenv._ - -import org.scalajs.core.tools.io.MemVirtualJSFile -import org.scalajs.core.tools.logging._ - -import org.junit.Assert._ - -import StoreLogger._ - -abstract class JSEnvTest { - - protected def newJSEnv: JSEnv - - implicit class RunMatcher(codeStr: String) { - - val code = new MemVirtualJSFile("testScript.js").withContent(codeStr) - - def hasOutput(expectedOut: String): Unit = { - - val console = new StoreJSConsole() - val logger = new StoreLogger() - - newJSEnv.jsRunner(code).run(logger, console) - - val log = logger.getLog - val hasBadLog = log exists { - case Log(level, _) if level >= Level.Warn => true - case Trace(_) => true - case _ => false - } - - assertFalse("VM shouldn't log errors, warnings or traces. Log:\n" + - log.mkString("\n"), hasBadLog) - assertEquals("Output should match", expectedOut, console.getLog) - } - - def fails(): Unit = { - try { - newJSEnv.jsRunner(code).run(NullLogger, NullJSConsole) - assertTrue("Code snipped should fail", false) - } catch { - case e: Exception => - } - } - } - -} diff --git a/js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/StoreJSConsole.scala b/js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/StoreJSConsole.scala deleted file mode 100644 index 0de28ed63f..0000000000 --- a/js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/StoreJSConsole.scala +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv.test - -import org.scalajs.jsenv._ - -class StoreJSConsole extends JSConsole { - private[this] val buf = new StringBuilder() - - def log(msg: Any): Unit = { - buf.append(msg.toString) - buf.append('\n') - } - - def getLog: String = buf.toString -} diff --git a/js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/StoreLogger.scala b/js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/StoreLogger.scala deleted file mode 100644 index 9738c93e89..0000000000 --- a/js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/StoreLogger.scala +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv.test - -import org.scalajs.core.tools.logging._ - -import scala.collection.mutable.ListBuffer - -class StoreLogger extends Logger { - import StoreLogger._ - - private[this] val buf = new ListBuffer[LogElem] - - def log(level: Level, message: => String): Unit = - buf += Log(level, message) - def success(message: => String): Unit = - buf += Success(message) - def trace(t: => Throwable): Unit = - buf += Trace(t) - - def getLog: List[LogElem] = buf.toList -} - -object StoreLogger { - - sealed trait LogElem - final case class Log(level: Level, message: String) extends LogElem - final case class Success(message: String) extends LogElem - final case class Trace(t: Throwable) extends LogElem - -} diff --git a/js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/TimeoutComTests.scala b/js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/TimeoutComTests.scala deleted file mode 100644 index 1c2ce2f797..0000000000 --- a/js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/TimeoutComTests.scala +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv.test - -import org.junit.Test -import org.junit.Assert._ - -import scala.concurrent.TimeoutException -import scala.concurrent.duration._ - -trait TimeoutComTests extends TimeoutTests with ComTests { - - @Test - def delayedInitTest: Unit = { - - val com = comRunner(s""" - setTimeout(function() { - scalajsCom.init(function(msg) { - scalajsCom.send("Got: " + msg); - }); - }, 100); - """) - - val deadline = 100.millis.fromNow - - start(com) - - com.send("Hello World") - - assertEquals("Got: Hello World", com.receive()) - - assertTrue("Execution took too little time", deadline.isOverdue()) - - com.close() - com.await(DefaultTimeout) - - } - - @Test - def delayedReplyTest: Unit = { - - val com = comRunner(s""" - scalajsCom.init(function(msg) { - setTimeout(scalajsCom.send, 20, "Got: " + msg); - }); - """) - - start(com) - - for (i <- 1 to 10) { - val deadline = 19.millis.fromNow // give some slack - com.send(s"Hello World: $i") - assertEquals(s"Got: Hello World: $i", com.receive()) - assertTrue("Execution took too little time", deadline.isOverdue()) - } - - com.close() - com.await(DefaultTimeout) - - } - - @Test - def receiveTimeoutTest: Unit = { - - val com = comRunner(s""" - scalajsCom.init(function(msg) { - setTimeout(scalajsCom.send, 2000, "Got: " + msg); - }); - """) - - start(com) - - for (i <- 1 to 2) { - com.send(s"Hello World: $i") - try { - com.receive(900.millis) - fail("Expected TimeoutException to be thrown") - } catch { - case _: TimeoutException => - } - assertEquals(s"Got: Hello World: $i", com.receive(3000.millis)) - } - - com.close() - com.await(DefaultTimeout) - - } - - @Test - def intervalSendTest: Unit = { - - val com = comRunner(s""" - scalajsCom.init(function(msg) {}); - var interval = setInterval(scalajsCom.send, 50, "Hello"); - setTimeout(clearInterval, 295, interval); - """) - - val deadline = 245.millis.fromNow - - start(com) - - for (i <- 1 to 5) - assertEquals("Hello", com.receive()) - - com.close() - com.await(DefaultTimeout) - - assertTrue("Execution took too little time", deadline.isOverdue()) - - } - - @Test - def noMessageTest: Unit = { - val com = comRunner(s""" - // Make sure JVM has already closed when we init - setTimeout(scalajsCom.init, 1000, function(msg) {}); - """) - start(com) - com.close() - com.await(DefaultTimeout) - } - - @Test - def stopTestTimeout: Unit = { - - val async = asyncRunner(s""" - setInterval(function() {}, 0); - """) - - start(async) - async.stop() - - try { - async.await(DefaultTimeout) - fail("Expected await to fail") - } catch { - case t: Throwable => // all is well - } - - async.stop() // should do nothing, and not fail - - } - - @Test - def doubleStopTest: Unit = { - val async = asyncRunner(s""" - setInterval(function() {}, 0); - """) - - start(async) - async.stop() - async.stop() // should do nothing, and not fail - - try { - async.await(DefaultTimeout) - fail("Expected await to fail") - } catch { - case t: Throwable => // all is well - } - - async.stop() // should do nothing, and not fail - } - -} diff --git a/js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/TimeoutTests.scala b/js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/TimeoutTests.scala deleted file mode 100644 index 83c8b26241..0000000000 --- a/js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/TimeoutTests.scala +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv.test - -import org.junit.Test -import org.junit.Assert._ - -import scala.concurrent.duration._ - -trait TimeoutTests extends JSEnvTest { - - @Test - def basicTimeoutTest: Unit = { - - val deadline = 300.millis.fromNow - - """ - setTimeout(function() { console.log("1"); }, 200); - setTimeout(function() { console.log("2"); }, 100); - setTimeout(function() { console.log("3"); }, 300); - setTimeout(function() { console.log("4"); }, 0); - """ hasOutput - """|4 - |2 - |1 - |3 - |""".stripMargin - - assertTrue("Execution took too little time", deadline.isOverdue()) - - } - - @Test - def clearTimeoutTest: Unit = { - - val deadline = 300.millis.fromNow - - """ - var c = setTimeout(function() { console.log("1"); }, 200); - setTimeout(function() { - console.log("2"); - clearTimeout(c); - }, 100); - setTimeout(function() { console.log("3"); }, 300); - setTimeout(function() { console.log("4"); }, 0); - """ hasOutput - """|4 - |2 - |3 - |""".stripMargin - - assertTrue("Execution took too little time", deadline.isOverdue()) - - } - - @Test // #2368 - def timeoutSingleArgTest: Unit = { - """ - setTimeout(function() { console.log("ok"); }); - """ hasOutput "ok\n" - } - - @Test - def timeoutArgTest: Unit = { - - val deadline = 300.millis.fromNow - - """ - setTimeout(function(a, b) { console.log("1" + a + b); }, 200, "foo", "bar"); - setTimeout(function() { console.log("2"); }, 100); - setTimeout(function(msg) { console.log(msg); }, 300, "Hello World"); - setTimeout(function() { console.log("4"); }, 0); - """ hasOutput - """|4 - |2 - |1foobar - |Hello World - |""".stripMargin - - assertTrue("Execution took too little time", deadline.isOverdue()) - - } - - @Test - def intervalTest: Unit = { - - val deadline = 1.second.fromNow - - """ - var i1 = setInterval(function() { console.log("each 2200"); }, 2200); - var i2 = setInterval(function() { console.log("each 3100"); }, 3100); - var i3 = setInterval(function() { console.log("each 1300"); }, 1300); - - setTimeout(function() { - clearInterval(i1); - clearInterval(i2); - clearInterval(i3); - }, 10000); - """ hasOutput - """|each 1300 - |each 2200 - |each 1300 - |each 3100 - |each 1300 - |each 2200 - |each 1300 - |each 3100 - |each 1300 - |each 2200 - |each 1300 - |each 2200 - |each 1300 - |each 3100 - |""".stripMargin - - assertTrue("Execution took too little time", deadline.isOverdue()) - - } - - @Test - def intervalSelfClearTest: Unit = { - - val deadline = 100.millis.fromNow - - """ - var c = 0; - var i = setInterval(function() { - c++; - console.log(c.toString()); - if (c >= 10) - clearInterval(i); - }, 10); - """ hasOutput (1 to 10).mkString("", "\n", "\n") - - assertTrue("Execution took too little time", deadline.isOverdue()) - - } - -} diff --git a/js-envs-test-suite/src/test/scala/org/scalajs/jsenv/test/JSDOMNodeJSEnvTest.scala b/js-envs-test-suite/src/test/scala/org/scalajs/jsenv/test/JSDOMNodeJSEnvTest.scala deleted file mode 100644 index a47e41b5b9..0000000000 --- a/js-envs-test-suite/src/test/scala/org/scalajs/jsenv/test/JSDOMNodeJSEnvTest.scala +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv.test - -import org.scalajs.jsenv.jsdomnodejs.JSDOMNodeJSEnv - -import org.junit.Test -import org.junit.Assert._ - -class JSDOMNodeJSEnvTest extends TimeoutComTests { - - protected def newJSEnv: JSDOMNodeJSEnv = new JSDOMNodeJSEnv() - - @Test - def historyAPI: Unit = { - """|console.log(window.location.href); - |window.history.pushState({}, "", "/foo"); - |console.log(window.location.href); - """.stripMargin hasOutput - """|http://localhost/ - |http://localhost/foo - |""".stripMargin - } - -} diff --git a/js-envs-test-suite/src/test/scala/org/scalajs/jsenv/test/NodeJSTest.scala b/js-envs-test-suite/src/test/scala/org/scalajs/jsenv/test/NodeJSTest.scala deleted file mode 100644 index 73870a2b93..0000000000 --- a/js-envs-test-suite/src/test/scala/org/scalajs/jsenv/test/NodeJSTest.scala +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv.test - -import org.scalajs.jsenv.nodejs.NodeJSEnv - -import org.junit.Test -import org.junit.Assert._ - -class NodeJSTest extends TimeoutComTests { - - protected def newJSEnv: NodeJSEnv = new NodeJSEnv - - /** Node.js strips double percentage signs - #500 */ - @Test - def percentageTest: Unit = { - val counts = 1 to 15 - val argcs = 1 to 3 - val strings = counts.map("%" * _) - - val strlists = for { - count <- argcs - string <- strings - } yield List.fill(count)(string) - - val codes = for { - strlist <- strlists - } yield { - val args = strlist.map(s => s""""$s"""").mkString(", ") - s"console.log($args);\n" - } - - val result = strlists.map(_.mkString(" ") + "\n").mkString("") - - codes.mkString("").hasOutput(result) - } - - /** Node.js console.log hack didn't allow to log non-Strings - #561 */ - @Test - def nonStringTest: Unit = { - - """ - console.log(1); - console.log(undefined); - console.log(null); - console.log({}); - console.log([1,2]); - """ hasOutput - """|1 - |undefined - |null - |[object Object] - |1,2 - |""".stripMargin - } - - @Test - def slowJSEnvTest: Unit = { - val com = comRunner(""" - setTimeout(function() { - scalajsCom.init(function(msg) { - scalajsCom.send("pong: " + msg); - }); - }, 1000); - """) - - val n = 20 - - start(com) - - for (_ <- 1 to n) - com.send("ping") - - for (_ <- 1 to n) - assertEquals(com.receive(), "pong: ping") - - com.close() - com.await(DefaultTimeout) - } - - @Test - def testConcurrentSendReceive_issue3408: Unit = { - for (_ <- 0 until 50) { - val com = comRunner(""" - scalajsCom.init(function(msg) { - scalajsCom.send("pong: " + msg); - }); - """) - - start(com) - - // Try very hard to send and receive at the same time - val lock = new AnyRef - val threadSend = new Thread { - override def run(): Unit = { - lock.synchronized(lock.wait()) - com.send("ping") - } - } - threadSend.start() - - Thread.sleep(200L) - lock.synchronized(lock.notifyAll()) - assertEquals(com.receive(), "pong: ping") - - threadSend.join() - com.close() - com.await(DefaultTimeout) - } - } - -} diff --git a/js-envs-test-suite/src/test/scala/org/scalajs/jsenv/test/NodeJSWithCustomInitFilesTest.scala b/js-envs-test-suite/src/test/scala/org/scalajs/jsenv/test/NodeJSWithCustomInitFilesTest.scala deleted file mode 100644 index 4ad2c68861..0000000000 --- a/js-envs-test-suite/src/test/scala/org/scalajs/jsenv/test/NodeJSWithCustomInitFilesTest.scala +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv.test - -import org.scalajs.jsenv.nodejs.NodeJSEnv - -class NodeJSWithCustomInitFilesTest extends CustomInitFilesTest { - protected def newJSEnv: NodeJSEnv = new NodeJSEnv { - override def customInitFiles() = makeCustomInitFiles() - } -} diff --git a/js-envs-test-suite/src/test/scala/org/scalajs/jsenv/test/PhantomJSTest.scala b/js-envs-test-suite/src/test/scala/org/scalajs/jsenv/test/PhantomJSTest.scala deleted file mode 100644 index 5736183ac4..0000000000 --- a/js-envs-test-suite/src/test/scala/org/scalajs/jsenv/test/PhantomJSTest.scala +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv.test - -import org.scalajs.jsenv.phantomjs.PhantomJSEnv - -class PhantomJSTest extends JSEnvTest with ComTests { - protected def newJSEnv: PhantomJSEnv = new PhantomJSEnv -} diff --git a/js-envs-test-suite/src/test/scala/org/scalajs/jsenv/test/PhantomJSWithCustomInitFilesTest.scala b/js-envs-test-suite/src/test/scala/org/scalajs/jsenv/test/PhantomJSWithCustomInitFilesTest.scala deleted file mode 100644 index b6f7924b5c..0000000000 --- a/js-envs-test-suite/src/test/scala/org/scalajs/jsenv/test/PhantomJSWithCustomInitFilesTest.scala +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv.test - -import org.scalajs.jsenv.phantomjs.PhantomJSEnv - -class PhantomJSWithCustomInitFilesTest extends CustomInitFilesTest { - protected def newJSEnv: PhantomJSEnv = new PhantomJSEnv { - override def customInitFiles() = makeCustomInitFiles() - } -} diff --git a/js-envs-test-suite/src/test/scala/org/scalajs/jsenv/test/RetryingComJSEnvTest.scala b/js-envs-test-suite/src/test/scala/org/scalajs/jsenv/test/RetryingComJSEnvTest.scala deleted file mode 100644 index 2aacb198de..0000000000 --- a/js-envs-test-suite/src/test/scala/org/scalajs/jsenv/test/RetryingComJSEnvTest.scala +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv.test - -import org.scalajs.core.tools.io.VirtualJSFile -import org.scalajs.core.tools.jsdep.ResolvedJSDependency -import org.scalajs.core.tools.logging._ -import org.scalajs.jsenv.nodejs.NodeJSEnv -import org.scalajs.jsenv.{ComJSRunner, JSConsole, _} - -import scala.concurrent.Future -import scala.concurrent.duration.Duration - -class RetryingComJSEnvTest extends JSEnvTest with ComTests { - - private final val maxFails = 5 - - // Don't log anything here - override protected def start(runner: AsyncJSRunner): Future[Unit] = { - runner.start(NullLogger, ConsoleJSConsole) - } - - protected def newJSEnv: RetryingComJSEnv = - new RetryingComJSEnv(new FailingEnv(new NodeJSEnv), maxFails) - - private final class FailingEnv(baseEnv: ComJSEnv) extends ComJSEnv { - def name: String = s"FailingJSEnv of ${baseEnv.name}" - - private[this] var fails = 0 - private[this] var failedReceive = false - - def jsRunner(libs: Seq[ResolvedJSDependency], - code: VirtualJSFile): JSRunner = { - baseEnv.jsRunner(libs, code) - } - - def asyncRunner(libs: Seq[ResolvedJSDependency], - code: VirtualJSFile): AsyncJSRunner = { - baseEnv.asyncRunner(libs, code) - } - - def comRunner(libs: Seq[ResolvedJSDependency], - code: VirtualJSFile): ComJSRunner = { - new FailingComJSRunner(baseEnv.comRunner(libs, code)) - } - - /** Hack to work around abstract override in ComJSRunner */ - private trait DummyJSRunner { - def stop(): Unit = () - } - - private class FailingComJSRunner(baseRunner: ComJSRunner) - extends DummyJSRunner with ComJSRunner { - - def future: Future[Unit] = baseRunner.future - - def send(msg: String): Unit = { - maybeFail() - baseRunner.send(msg) - } - - def receive(timeout: Duration): String = { - if (shouldFail) { - failedReceive = true - fail() - } - baseRunner.receive(timeout) - } - - def start(logger: Logger, console: JSConsole): Future[Unit] = { - maybeFail() - baseRunner.start(logger, console) - } - - override def stop(): Unit = { - maybeFail() - baseRunner.stop() - } - - def close(): Unit = { - maybeFail() - baseRunner.close() - } - - private def shouldFail = !failedReceive && fails < maxFails - - private def maybeFail() = { - if (shouldFail) - fail() - } - - private def fail() = { - fails += 1 - throw new Exception("Dummy fail for testing purposes") - } - } - } - -} diff --git a/js-envs-test-suite/src/test/scala/org/scalajs/jsenv/test/RhinoJSEnvTest.scala b/js-envs-test-suite/src/test/scala/org/scalajs/jsenv/test/RhinoJSEnvTest.scala deleted file mode 100644 index c098f64c75..0000000000 --- a/js-envs-test-suite/src/test/scala/org/scalajs/jsenv/test/RhinoJSEnvTest.scala +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv.test - -import org.scalajs.core.tools.sem.Semantics - -import org.scalajs.jsenv.rhino._ - -class RhinoJSEnvTest extends TimeoutComTests { - protected def newJSEnv: RhinoJSEnv = - new RhinoJSEnv(Semantics.Defaults, withDOM = false, internal = ()) -} diff --git a/js-envs/src/main/scala/org/scalajs/jsenv/AsyncJSEnv.scala b/js-envs/src/main/scala/org/scalajs/jsenv/AsyncJSEnv.scala deleted file mode 100644 index 08214d23ce..0000000000 --- a/js-envs/src/main/scala/org/scalajs/jsenv/AsyncJSEnv.scala +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv - -import org.scalajs.core.tools.io.VirtualJSFile -import org.scalajs.core.tools.jsdep.ResolvedJSDependency - -trait AsyncJSEnv extends JSEnv { - def asyncRunner(libs: Seq[ResolvedJSDependency], code: VirtualJSFile): AsyncJSRunner - - final def asyncRunner(code: VirtualJSFile): AsyncJSRunner = - asyncRunner(Nil, code) - - override def loadLibs(libs: Seq[ResolvedJSDependency]): AsyncJSEnv = - new AsyncLoadedLibs { val loadedLibs = libs } - - private[jsenv] trait AsyncLoadedLibs extends LoadedLibs with AsyncJSEnv { - def asyncRunner(libs: Seq[ResolvedJSDependency], - code: VirtualJSFile): AsyncJSRunner = { - AsyncJSEnv.this.asyncRunner(loadedLibs ++ libs, code) - } - } -} diff --git a/js-envs/src/main/scala/org/scalajs/jsenv/AsyncJSRunner.scala b/js-envs/src/main/scala/org/scalajs/jsenv/AsyncJSRunner.scala deleted file mode 100644 index 14779fb32b..0000000000 --- a/js-envs/src/main/scala/org/scalajs/jsenv/AsyncJSRunner.scala +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv - -import scala.concurrent.{Future, Await} -import scala.concurrent.duration.Duration - -import org.scalajs.core.tools.logging.Logger - -trait AsyncJSRunner { - - /** A future that completes when the associated run has terminated. */ - def future: Future[Unit] - - /** - * Start the associated run and returns a Future that completes - * when the run terminates. The returned Future is equivalent to - * the one returned by [[future]]. - */ - def start(logger: Logger, console: JSConsole): Future[Unit] - - /** Aborts the associated run. - * - * There is no guarantee that the runner will be effectively terminated - * by the time this method returns. If necessary, this call can be followed - * by a call to `await()`. - * - * If the run has already completed, this does nothing. Similarly, - * subsequent calls to `stop()` will do nothing. - * - * This method cannot be called before `start()` has been called. - */ - def stop(): Unit - - /** - * Checks whether this async runner is still running. Strictly - * equivalent to - * - * {{{ - * !future.isCompleted - * }}} - */ - final def isRunning(): Boolean = !future.isCompleted - - /** Await completion of the started Run. Strictly equivalent to - * - * {{{ - * Await.result(future, Duration.Inf) - * }}} - */ - final def await(): Unit = Await.result(future, Duration.Inf) - - /** Await completion of the started Run for the duration specified - * by `atMost`. Strictly equivalent to: - * - * {{{ - * Await.result(future, atMost) - * }}} - * - */ - final def await(atMost: Duration): Unit = Await.result(future, atMost) - - /** Awaits completion of the started Run for the duration specified by - * `atMost`, or force it to stop. - * - * If any exception is thrown while awaiting completion (including a - * [[scala.concurrent.TimeoutException TimeoutException]]), forces the runner - * to stop by calling `stop()` before rethrowing the exception. - * - * Strictly equivalent to: - * - * {{{ - * try await(atMost) - * finally stop() - * }}} - */ - final def awaitOrStop(atMost: Duration): Unit = { - try await(atMost) - finally stop() - } - -} diff --git a/js-envs/src/main/scala/org/scalajs/jsenv/ComJSEnv.scala b/js-envs/src/main/scala/org/scalajs/jsenv/ComJSEnv.scala deleted file mode 100644 index c8688dce0d..0000000000 --- a/js-envs/src/main/scala/org/scalajs/jsenv/ComJSEnv.scala +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv - -import org.scalajs.core.tools.io.VirtualJSFile -import org.scalajs.core.tools.jsdep.ResolvedJSDependency - -/** An [[AsyncJSEnv]] that provides communication to and from the JS VM. - * - * Inside the VM there is a global JavaScript object named `scalajsCom` that - * can be used to control the message channel. It's operations are: - * {{{ - * // initialize com (with callback) - * scalajsCom.init(function(msg) { console.log("Received: " + msg); }); - * - * // send a message to host system - * scalajsCom.send("my message"); - * - * // close com (releases callback, allowing VM to terminate) - * scalajsCom.close(); - * }}} - */ -trait ComJSEnv extends AsyncJSEnv { - def comRunner(libs: Seq[ResolvedJSDependency], code: VirtualJSFile): ComJSRunner - - final def comRunner(code: VirtualJSFile): ComJSRunner = comRunner(Nil, code) - - override def loadLibs(libs: Seq[ResolvedJSDependency]): ComJSEnv = - new ComLoadedLibs { val loadedLibs = libs } - - private[jsenv] trait ComLoadedLibs extends AsyncLoadedLibs with ComJSEnv { - def comRunner(libs: Seq[ResolvedJSDependency], - code: VirtualJSFile): ComJSRunner = { - ComJSEnv.this.comRunner(loadedLibs ++ libs, code) - } - } -} - -object ComJSEnv { - private final val defaultMsg = "JSCom has been closed" - - class ComClosedException(msg: String, - cause: Throwable) extends Exception(msg, cause) { - def this() = this(defaultMsg, null) - def this(cause: Throwable) = this(defaultMsg, cause) - def this(msg: String) = this(msg, null) - } -} diff --git a/js-envs/src/main/scala/org/scalajs/jsenv/ComJSRunner.scala b/js-envs/src/main/scala/org/scalajs/jsenv/ComJSRunner.scala deleted file mode 100644 index 14954db5f8..0000000000 --- a/js-envs/src/main/scala/org/scalajs/jsenv/ComJSRunner.scala +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv - -import scala.concurrent.duration.Duration - -trait ComJSRunner extends AsyncJSRunner { - - /** Send a message to the JS VM. Throws if the message cannot be sent. */ - def send(msg: String): Unit - - /** Blocks until a message is received and returns it. - * - * @throws ComJSEnv.ComClosedException if the channel is closed before a - * message is received - */ - final def receive(): String = receive(Duration.Inf) - - /** Blocks until a message is received and returns it. - * - * @throws ComJSEnv.ComClosedException if the channel is closed before a - * message is received - * @throws scala.concurrent.TimeoutException if the timeout expires - * before a message is received and the channel is still open - */ - def receive(timeout: Duration): String - - /** Close the communication channel. Allows the VM to terminate if it is - * still waiting for callback. The JVM side **must** call close in - * order to be able to expect termination of the VM. - * - * Calling [[stop]] on a [ComJSRunner]] automatically closes the - * channel. - */ - def close(): Unit - - /** Abort the associated run. Also closes the communication channel. */ - abstract override def stop(): Unit = { - close() - super.stop() - } - -} diff --git a/js-envs/src/main/scala/org/scalajs/jsenv/ConsoleJSConsole.scala b/js-envs/src/main/scala/org/scalajs/jsenv/ConsoleJSConsole.scala deleted file mode 100644 index 4185fe09f6..0000000000 --- a/js-envs/src/main/scala/org/scalajs/jsenv/ConsoleJSConsole.scala +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv - -/** A JS console that prints on the console */ -object ConsoleJSConsole extends JSConsole { - override def log(msg: Any): Unit = { - Console.println(msg) - } -} diff --git a/js-envs/src/main/scala/org/scalajs/jsenv/ExternalJSEnv.scala b/js-envs/src/main/scala/org/scalajs/jsenv/ExternalJSEnv.scala deleted file mode 100644 index 0c2d73fe76..0000000000 --- a/js-envs/src/main/scala/org/scalajs/jsenv/ExternalJSEnv.scala +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv - -import org.scalajs.core.tools.io._ -import org.scalajs.core.tools.logging.Logger -import org.scalajs.core.tools.jsdep.ResolvedJSDependency - -import java.io.{ Console => _, _ } -import scala.io.Source - -import scala.concurrent.{Future, Promise} -import scala.util.Try - -abstract class ExternalJSEnv( - final protected val args: Seq[String], - final protected val env: Map[String, String]) - extends AsyncJSEnv { - - import ExternalJSEnv._ - - def name: String = s"ExternalJSEnv for $vmName" - - /** Printable name of this VM */ - protected def vmName: String - - /** Command to execute (on shell) for this VM */ - protected def executable: String - - @deprecated("Use `args` instead.", "0.6.16") - final protected def additionalArgs: Seq[String] = args - - @deprecated("Use `env` instead.", "0.6.16") - final protected def additionalEnv: Map[String, String] = env - - /** Custom initialization scripts. */ - protected def customInitFiles(): Seq[VirtualJSFile] = Nil - - protected class AbstractExtRunner( - protected val libs: Seq[ResolvedJSDependency], - protected val code: VirtualJSFile) extends JSInitFiles { - - private[this] var _logger: Logger = _ - private[this] var _console: JSConsole = _ - - protected def logger: Logger = _logger - protected def console: JSConsole = _console - - protected def setupLoggerAndConsole(logger: Logger, console: JSConsole) = { - require(_logger == null && _console == null) - _logger = logger - _console = console - } - - /** Custom initialization scripts, defined by the environment. */ - final protected def customInitFiles(): Seq[VirtualJSFile] = - ExternalJSEnv.this.customInitFiles() - - /** Sends required data to VM Stdin (can throw) */ - protected def sendVMStdin(out: OutputStream): Unit = {} - - /** VM arguments excluding executable. Override to adapt. - * - * The default value in `ExternalJSEnv` is `args`. - */ - protected def getVMArgs(): Seq[String] = args - - /** VM environment. Override to adapt. - * - * The default value in `ExternalJSEnv` is - * `System.getenv().asScala.toMap ++ env`. - */ - protected def getVMEnv(): Map[String, String] = { - /* We use Java's `forEach` not to depend on Scala's JavaConverters, which - * are very difficult to cross-compile across 2.12- and 2.13+. - */ - val builder = Map.newBuilder[String, String] - System.getenv().forEach(new java.util.function.BiConsumer[String, String] { - def accept(key: String, value: String): Unit = - builder += key -> value - }) - builder ++= env - builder.result() - } - - /** Get files that are a library (i.e. that do not run anything) */ - protected def getLibJSFiles(): Seq[VirtualJSFile] = - initFiles() ++ customInitFiles() ++ libs.map(_.lib) - - /** Get all files that are passed to VM (libraries and code) */ - protected def getJSFiles(): Seq[VirtualJSFile] = - getLibJSFiles() :+ code - - /** write a single JS file to a writer using an include fct if appropriate */ - protected def writeJSFile(file: VirtualJSFile, writer: Writer): Unit = { - // The only platform-independent way to do this in JS is to dump the file. - writer.write(file.content) - writer.write('\n') - } - - /** Pipe stdin and stdout from/to VM */ - final protected def pipeVMData(vmInst: Process): Unit = { - // Send stdin to VM. - val out = vmInst.getOutputStream() - try { sendVMStdin(out) } - finally { out.close() } - - // Pipe stdout (and stderr which is merged into it) to console - pipeToConsole(vmInst.getInputStream(), console) - } - - /** Wait for the VM to terminate, verify exit code - * - * @throws ExternalJSEnv.NonZeroExitException if VM returned a non-zero code - */ - final protected def waitForVM(vmInst: Process): Unit = { - // Make sure we are done. - vmInst.waitFor() - - // Get return value and return - val retVal = vmInst.exitValue - if (retVal != 0) - throw new NonZeroExitException(vmName, retVal) - } - - protected def startVM(): Process = { - val vmArgs = getVMArgs() - val vmEnv = getVMEnv() - - val allArgs = executable +: vmArgs - val pBuilder = new ProcessBuilder(allArgs: _*) - pBuilder.redirectErrorStream(true) // merge stderr into stdout - - pBuilder.environment().clear() - for ((name, value) <- vmEnv) - pBuilder.environment().put(name, value) - - logger.debug("Starting process: " + allArgs.mkString(" ")) - - pBuilder.start() - } - - /** send a bunch of JS files to an output stream */ - final protected def sendJS(files: Seq[VirtualJSFile], - out: OutputStream): Unit = { - val writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8")) - try sendJS(files, writer) - finally writer.close() - } - - /** send a bunch of JS files to a writer */ - final protected def sendJS(files: Seq[VirtualJSFile], out: Writer): Unit = - files.foreach { writeJSFile(_, out) } - - /** pipe lines from input stream to JSConsole */ - final protected def pipeToConsole(in: InputStream, console: JSConsole) = { - val source = Source.fromInputStream(in, "UTF-8") - try { source.getLines.foreach(console.log _) } - finally { source.close() } - } - - } - - protected class ExtRunner(libs: Seq[ResolvedJSDependency], code: VirtualJSFile) - extends AbstractExtRunner(libs, code) with JSRunner { - - def run(logger: Logger, console: JSConsole): Unit = { - setupLoggerAndConsole(logger, console) - - val vmInst = startVM() - - pipeVMData(vmInst) - waitForVM(vmInst) - } - } - - protected class AsyncExtRunner(libs: Seq[ResolvedJSDependency], code: VirtualJSFile) - extends AbstractExtRunner(libs, code) with AsyncJSRunner { - - private[this] var vmInst: Process = null - private[this] var ioThreadEx: Throwable = null - private[this] val promise = Promise[Unit] - - private[this] val thread = new Thread { - override def run(): Unit = { - // This thread should not be interrupted, so it is safe to use Trys - val pipeResult = Try(pipeVMData(vmInst)) - val vmComplete = Try(waitForVM(vmInst)) - - // Store IO exception - pipeResult recover { - case e => ioThreadEx = e - } - - /* We want the VM failure to take precedence if there was one, - * otherwise the IO failure if there is one. We complete with a - * successful () only when both vmComplete and pipeResult were successful. - */ - promise.complete(vmComplete.flatMap(_ => pipeResult)) - } - } - - def future: Future[Unit] = promise.future - - def start(logger: Logger, console: JSConsole): Future[Unit] = { - setupLoggerAndConsole(logger, console) - startExternalJSEnv() - future - } - - /** Core functionality of [[start]]. - * - * Same as [[start]] but without a call to [[setupLoggerAndConsole]] and - * not returning [[future]]. - * Useful to be called in overrides of [[start]]. - */ - protected def startExternalJSEnv(): Unit = { - require(vmInst == null, "start() may only be called once") - vmInst = startVM() - thread.start() - } - - def stop(): Unit = { - require(vmInst != null, "start() must have been called") - vmInst.destroy() - } - } - -} - -object ExternalJSEnv { - final case class NonZeroExitException(vmName: String, retVal: Int) - extends Exception(s"$vmName exited with code $retVal") -} diff --git a/js-envs/src/main/scala/org/scalajs/jsenv/JSConsole.scala b/js-envs/src/main/scala/org/scalajs/jsenv/JSConsole.scala deleted file mode 100644 index b7f98b9b61..0000000000 --- a/js-envs/src/main/scala/org/scalajs/jsenv/JSConsole.scala +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv - -/** Trait representing a JS console */ -trait JSConsole { - def log(msg: Any): Unit -} diff --git a/js-envs/src/main/scala/org/scalajs/jsenv/JSEnv.scala b/js-envs/src/main/scala/org/scalajs/jsenv/JSEnv.scala deleted file mode 100644 index 52870daa09..0000000000 --- a/js-envs/src/main/scala/org/scalajs/jsenv/JSEnv.scala +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv - -import org.scalajs.core.tools.io.VirtualJSFile -import org.scalajs.core.tools.jsdep.ResolvedJSDependency - -trait JSEnv { - /** Human-readable name for this [[JSEnv]] */ - def name: String - - /** Prepare a runner for the code in the virtual file. */ - def jsRunner(libs: Seq[ResolvedJSDependency], code: VirtualJSFile): JSRunner - - /** Prepare a runner without any libraries. - * - * Strictly equivalent to: - * {{{ - * this.jsRunner(Nil, code) - * }}} - */ - final def jsRunner(code: VirtualJSFile): JSRunner = jsRunner(Nil, code) - - /** Return this [[JSEnv]] with the given libraries already loaded. - * - * The following two are equivalent: - * {{{ - * jsEnv.loadLibs(a).jsRunner(b, c) - * jsEnv.jsRunner(a ++ b, c) - * }}} - */ - def loadLibs(libs: Seq[ResolvedJSDependency]): JSEnv = - new LoadedLibs { val loadedLibs = libs } - - private[jsenv] trait LoadedLibs extends JSEnv { - val loadedLibs: Seq[ResolvedJSDependency] - - def name: String = JSEnv.this.name - - def jsRunner(libs: Seq[ResolvedJSDependency], code: VirtualJSFile): JSRunner = - JSEnv.this.jsRunner(loadedLibs ++ libs, code) - } -} diff --git a/js-envs/src/main/scala/org/scalajs/jsenv/JSInitFiles.scala b/js-envs/src/main/scala/org/scalajs/jsenv/JSInitFiles.scala deleted file mode 100644 index 7ff78d1ec6..0000000000 --- a/js-envs/src/main/scala/org/scalajs/jsenv/JSInitFiles.scala +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv - -import org.scalajs.core.tools.io.VirtualJSFile - -trait JSInitFiles { - /** JS files used to setup VM */ - protected def initFiles(): Seq[VirtualJSFile] = Nil -} diff --git a/js-envs/src/main/scala/org/scalajs/jsenv/JSRunner.scala b/js-envs/src/main/scala/org/scalajs/jsenv/JSRunner.scala deleted file mode 100644 index 5c9400e89b..0000000000 --- a/js-envs/src/main/scala/org/scalajs/jsenv/JSRunner.scala +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv - -import org.scalajs.core.tools.logging.Logger - -trait JSRunner { - /** Run the associated JS code. Throw if an error occurs. */ - def run(logger: Logger, console: JSConsole): Unit -} diff --git a/js-envs/src/main/scala/org/scalajs/jsenv/LinkingUnitAsyncJSEnv.scala b/js-envs/src/main/scala/org/scalajs/jsenv/LinkingUnitAsyncJSEnv.scala deleted file mode 100644 index e26ec3f1a4..0000000000 --- a/js-envs/src/main/scala/org/scalajs/jsenv/LinkingUnitAsyncJSEnv.scala +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv - -import org.scalajs.core.tools.io.VirtualJSFile -import org.scalajs.core.tools.jsdep.ResolvedJSDependency -import org.scalajs.core.tools.linker.LinkingUnit - -trait LinkingUnitAsyncJSEnv extends LinkingUnitJSEnv with AsyncJSEnv { - def asyncRunner(preLibs: Seq[ResolvedJSDependency], linkingUnit: LinkingUnit, - postLibs: Seq[ResolvedJSDependency], code: VirtualJSFile): AsyncJSRunner - - override def loadLibs(libs: Seq[ResolvedJSDependency]): LinkingUnitAsyncJSEnv = - new LinkingUnitAsyncLoadedLibs { val loadedLibs = libs } - - override def loadLinkingUnit(linkingUnit: LinkingUnit): AsyncJSEnv = - new AsyncLoadedUnit { val loadedUnit = linkingUnit } - - private[jsenv] trait LinkingUnitAsyncLoadedLibs extends LinkingUnitLoadedLibs - with AsyncLoadedLibs with LinkingUnitAsyncJSEnv { - def asyncRunner(preLibs: Seq[ResolvedJSDependency], linkingUnit: LinkingUnit, - postLibs: Seq[ResolvedJSDependency], - code: VirtualJSFile): AsyncJSRunner = { - LinkingUnitAsyncJSEnv.this.asyncRunner(loadedLibs ++ preLibs, linkingUnit, - postLibs, code) - } - } - - private[jsenv] trait AsyncLoadedUnit extends LoadedUnit with AsyncJSEnv { - def asyncRunner(libs: Seq[ResolvedJSDependency], - code: VirtualJSFile): AsyncJSRunner = { - LinkingUnitAsyncJSEnv.this.asyncRunner(Nil, loadedUnit, libs, code) - } - } -} diff --git a/js-envs/src/main/scala/org/scalajs/jsenv/LinkingUnitComJSEnv.scala b/js-envs/src/main/scala/org/scalajs/jsenv/LinkingUnitComJSEnv.scala deleted file mode 100644 index 5761e0e9ff..0000000000 --- a/js-envs/src/main/scala/org/scalajs/jsenv/LinkingUnitComJSEnv.scala +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv - -import org.scalajs.core.tools.io.VirtualJSFile -import org.scalajs.core.tools.jsdep.ResolvedJSDependency -import org.scalajs.core.tools.linker.LinkingUnit - -trait LinkingUnitComJSEnv extends LinkingUnitAsyncJSEnv with ComJSEnv { - def comRunner(preLibs: Seq[ResolvedJSDependency], linkingUnit: LinkingUnit, - postLibs: Seq[ResolvedJSDependency], code: VirtualJSFile): ComJSRunner - - override def loadLibs(libs: Seq[ResolvedJSDependency]): LinkingUnitComJSEnv = - new LinkingUnitComLoadedLibs { val loadedLibs = libs } - - override def loadLinkingUnit(linkingUnit: LinkingUnit): ComJSEnv = - new ComLoadedUnit { val loadedUnit = linkingUnit } - - private[jsenv] trait LinkingUnitComLoadedLibs - extends LinkingUnitAsyncLoadedLibs with ComLoadedLibs - with LinkingUnitComJSEnv { - def comRunner(preLibs: Seq[ResolvedJSDependency], linkingUnit: LinkingUnit, - postLibs: Seq[ResolvedJSDependency], - code: VirtualJSFile): ComJSRunner = { - LinkingUnitComJSEnv.this.comRunner(loadedLibs ++ preLibs, linkingUnit, - postLibs, code) - } - } - - private[jsenv] trait ComLoadedUnit extends AsyncLoadedUnit with ComJSEnv { - def comRunner(libs: Seq[ResolvedJSDependency], - code: VirtualJSFile): ComJSRunner = { - LinkingUnitComJSEnv.this.comRunner(Nil, loadedUnit, libs, code) - } - } -} diff --git a/js-envs/src/main/scala/org/scalajs/jsenv/LinkingUnitJSEnv.scala b/js-envs/src/main/scala/org/scalajs/jsenv/LinkingUnitJSEnv.scala deleted file mode 100644 index 46020ee7f8..0000000000 --- a/js-envs/src/main/scala/org/scalajs/jsenv/LinkingUnitJSEnv.scala +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv - -import org.scalajs.core.tools.io.VirtualJSFile -import org.scalajs.core.tools.jsdep.ResolvedJSDependency -import org.scalajs.core.tools.linker.LinkingUnit -import org.scalajs.core.tools.linker.analyzer.SymbolRequirement - -trait LinkingUnitJSEnv extends JSEnv { - /** Symbols this [[LinkingUnitJSEnv]] needs present in the - * [[org.scalajs.core.tools.linker.LinkingUnit LinkingUnit]] it receives. - */ - val symbolRequirements: SymbolRequirement - - /** Prepare a runner for the code in the virtual file. */ - def jsRunner(preLibs: Seq[ResolvedJSDependency], linkingUnit: LinkingUnit, - postLibs: Seq[ResolvedJSDependency], code: VirtualJSFile): JSRunner - - override def loadLibs(libs: Seq[ResolvedJSDependency]): LinkingUnitJSEnv = - new LinkingUnitLoadedLibs { val loadedLibs = libs } - - /** Returns a [[JSEnv]] with the given - * [[org.scalajs.core.tools.linker.LinkingUnit LinkingUnit]] already loaded. - * - * Note that any subsequent libraries will be inserted after the - * [[org.scalajs.core.tools.linker.LinkingUnit LinkingUnit]]. - * - * Hence, the following are equivalent: - * {{{ - * jsEnv.loadUnit(a).jsRunner(b, c) - * jsEnv.jsRunner(Nil, a, b, c) - * }}} - * - * If you need to load libraries before, you can use the [[loadLibs]] method: - * {{{ - * jsEnv.loadLibs(a).loadUnit(b).jsRunner(c, d) - * // equivalent to - * jsEnv.jsRunner(a, b, c, d) - * }}} - */ - def loadLinkingUnit(linkingUnit: LinkingUnit): JSEnv = - new LoadedUnit { val loadedUnit = linkingUnit } - - private[jsenv] trait LinkingUnitLoadedLibs - extends LoadedLibs with LinkingUnitJSEnv { - val symbolRequirements: SymbolRequirement = - LinkingUnitJSEnv.this.symbolRequirements - - def jsRunner(preLibs: Seq[ResolvedJSDependency], linkingUnit: LinkingUnit, - postLibs: Seq[ResolvedJSDependency], code: VirtualJSFile): JSRunner = { - LinkingUnitJSEnv.this.jsRunner(loadedLibs ++ preLibs, - linkingUnit, postLibs, code) - } - } - - private[jsenv] trait LoadedUnit extends JSEnv { - val loadedUnit: LinkingUnit - - def name: String = LinkingUnitJSEnv.this.name - - def jsRunner(libs: Seq[ResolvedJSDependency], code: VirtualJSFile): JSRunner = - LinkingUnitJSEnv.this.jsRunner(Nil, loadedUnit, libs, code) - } -} diff --git a/js-envs/src/main/scala/org/scalajs/jsenv/NullJSConsole.scala b/js-envs/src/main/scala/org/scalajs/jsenv/NullJSConsole.scala deleted file mode 100644 index 4dbbcf52ca..0000000000 --- a/js-envs/src/main/scala/org/scalajs/jsenv/NullJSConsole.scala +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv - -object NullJSConsole extends JSConsole { - def log(msg: Any): Unit = {} -} diff --git a/js-envs/src/main/scala/org/scalajs/jsenv/RetryingComJSEnv.scala b/js-envs/src/main/scala/org/scalajs/jsenv/RetryingComJSEnv.scala deleted file mode 100644 index 88fb340cda..0000000000 --- a/js-envs/src/main/scala/org/scalajs/jsenv/RetryingComJSEnv.scala +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv - -import org.scalajs.core.tools.io._ -import org.scalajs.core.tools.logging.Logger -import org.scalajs.core.tools.jsdep.ResolvedJSDependency - -import scala.concurrent.{Future, Promise, ExecutionContext} -import scala.concurrent.duration.Duration -import scala.collection.mutable -import scala.annotation.tailrec -import scala.util.control.NonFatal -import scala.util.{Try, Failure, Success} - -/** A RetryingComJSEnv allows to automatically retry if a call to the underlying - * ComJSRunner fails. - * - * While it protects the JVM side from observing state that differs inbetween - * runs that have been retried, it assumes that the executed JavaScript code - * does not have side-effects other than the ones visible through the channel - * (e.g. writing to a file). It is the users responsibility to ensure this - * property. - * - * No retrying is performed for synchronous, or normal asynchronous runs. - */ -final class RetryingComJSEnv(val baseEnv: ComJSEnv, - val maxRetries: Int) extends ComJSEnv { - - def this(baseEnv: ComJSEnv) = this(baseEnv, 5) - - def name: String = s"Retrying ${baseEnv.name}" - - def jsRunner(libs: Seq[ResolvedJSDependency], - code: VirtualJSFile): JSRunner = { - baseEnv.jsRunner(libs, code) - } - - def asyncRunner(libs: Seq[ResolvedJSDependency], - code: VirtualJSFile): AsyncJSRunner = { - baseEnv.asyncRunner(libs, code) - } - - def comRunner(libs: Seq[ResolvedJSDependency], - code: VirtualJSFile): ComJSRunner = { - new RetryingComJSRunner(libs, code) - } - - /** Hack to work around abstract override in ComJSRunner */ - private trait DummyJSRunner { - def stop(): Unit = () - } - - private class RetryingComJSRunner(libs: Seq[ResolvedJSDependency], - code: VirtualJSFile) extends DummyJSRunner with ComJSRunner { - - private[this] val promise = Promise[Unit] - - private[this] var curRunner = baseEnv.comRunner(libs, code) - - private[this] var hasReceived = false - private[this] var retryCount = 0 - - private[this] val log = mutable.Buffer.empty[LogItem] - - private[this] var _logger: Logger = _ - private[this] var _console: JSConsole = _ - - def future: Future[Unit] = promise.future - - def start(logger: Logger, console: JSConsole): Future[Unit] = { - require(log.isEmpty, "start() may only be called once") - - _logger = logger - _console = console - - logAndDo(Start) - future - } - - override def stop(): Unit = { - require(log.nonEmpty, "start() must have been called") - close() - logAndDo(Stop) - } - - def send(msg: String): Unit = { - require(log.nonEmpty, "start() must have been called") - logAndDo(Send(msg)) - } - - def receive(timeout: Duration): String = { - @tailrec - def recLoop(): String = { - // Need to use Try for tailrec - Try { - val result = curRunner.receive(timeout) - // At this point, we are sending state to the JVM, we cannot retry - // after this. - hasReceived = true - result - } match { - case Failure(t) => - retry(t) - recLoop() - case Success(v) => v - } - } - - recLoop() - } - - def close(): Unit = { - require(log.nonEmpty, "start() must have been called") - logAndDo(Close) - } - - @tailrec - private final def retry(cause: Throwable): Unit = { - retryCount += 1 - - // Accesses to promise and swaps in the curRunner must be synchronized - synchronized { - if (hasReceived || retryCount > maxRetries || promise.isCompleted) - throw cause - - _logger.warn("Retrying to launch a " + baseEnv.getClass.getName + - " after " + cause.toString) - - val oldRunner = curRunner - - curRunner = try { - baseEnv.comRunner(libs, code) - } catch { - case NonFatal(t) => - _logger.error("Could not retry: creating an new runner failed: " + - t.toString) - throw cause - } - - try oldRunner.stop() // just in case - catch { - case NonFatal(t) => // ignore - } - } - - // Replay the whole log - // Need to use Try for tailrec - Try(log.foreach(executeTask)) match { - case Failure(t) => retry(t) - case _ => - } - } - - private def logAndDo(task: LogItem) = { - log += task - try executeTask(task) - catch { - case NonFatal(t) => retry(t) - } - } - - private def executeTask(task: LogItem) = task match { - case Start => - import ExecutionContext.Implicits.global - val runner = curRunner - runner.start(_logger, _console) onComplete { result => - // access to curRunner and promise must be synchronized - synchronized { - if (curRunner eq runner) - promise.complete(result) - } - } - case Send(msg) => - curRunner.send(msg) - case Stop => - curRunner.stop() - case Close => - curRunner.close() - } - - private sealed trait LogItem - private case object Start extends LogItem - private case class Send(msg: String) extends LogItem - private case object Stop extends LogItem - private case object Close extends LogItem - - } - -} diff --git a/js-envs/src/main/scala/org/scalajs/jsenv/Utils.scala b/js-envs/src/main/scala/org/scalajs/jsenv/Utils.scala deleted file mode 100644 index b2d5ff9d12..0000000000 --- a/js-envs/src/main/scala/org/scalajs/jsenv/Utils.scala +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv - -import scala.concurrent.duration._ - -private[jsenv] object Utils { - final class OptDeadline private ( - val deadline: Deadline /* nullable */) extends AnyVal { // scalastyle:ignore - def millisLeft: Long = - if (deadline == null) 0 - else (deadline.timeLeft.toMillis max 1L) - - def isOverdue: Boolean = - if (deadline == null) false - else deadline.isOverdue - } - - object OptDeadline { - def apply(timeout: Duration): OptDeadline = { - new OptDeadline(timeout match { - case timeout: FiniteDuration => timeout.fromNow - case _ => null - }) - } - } -} diff --git a/js-envs/src/main/scala/org/scalajs/jsenv/VirtualFileMaterializer.scala b/js-envs/src/main/scala/org/scalajs/jsenv/VirtualFileMaterializer.scala deleted file mode 100644 index 455c0d9cc9..0000000000 --- a/js-envs/src/main/scala/org/scalajs/jsenv/VirtualFileMaterializer.scala +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv - -import scala.annotation.tailrec - -import org.scalajs.core.tools.io._ - -import java.io.File - -/** A helper class to temporarily store virtual files to the filesystem. - * - * Can be used with tools that require real files. - * @param singleDir if true, forces files to be copied into - * [[cacheDir]]. Useful to setup include directories for - * example. - */ -final class VirtualFileMaterializer(singleDir: Boolean = false) { - import VirtualFileMaterializer._ - - val cacheDir = { - val dir = createTempDir() - dir.deleteOnExit() - dir - } - - /** Create a target file to write/copy to. Will also call - * deleteOnExit on the file. - */ - private def trgFile(name: String): File = { - val f = new File(cacheDir, name) - f.deleteOnExit() - f - } - - def materialize(vf: VirtualTextFile): File = vf match { - case vf: FileVirtualFile if !singleDir => - vf.file - case _ => - val trg = trgFile(vf.name) - IO.copyTo(vf, WritableFileVirtualTextFile(trg)) - trg - } - - def materialize(vf: VirtualBinaryFile): File = vf match { - case vf: FileVirtualFile if !singleDir => - vf.file - case _ => - val trg = trgFile(vf.name) - IO.copyTo(vf, WritableFileVirtualBinaryFile(trg)) - trg - } - - /** Removes the cache directory. Any operation on this - * VirtualFileMaterializer is invalid after [[close]] has been - * called. - */ - def close(): Unit = { - cacheDir.listFiles().foreach(_.delete) - cacheDir.delete() - } - - // scalastyle:off line.size.limit - /* Taken from Guava: - * https://github.com/google/guava/blob/1c285fc8d289c43b46aa55e7f90ec0359be5b69a/guava/src/com/google/common/io/Files.java#L413-L426 - */ - // scalastyle:on line.size.limit - private def createTempDir(): File = { - val baseDir = new File(System.getProperty("java.io.tmpdir")) - val baseName = "" + System.currentTimeMillis() + "-" - - @tailrec - def loop(tries: Int): File = { - val tempDir = new File(baseDir, baseName + tries) - if (tempDir.mkdir()) - tempDir - else if (tries < TempDirAttempts) - loop(tries + 1) - else { - throw new IllegalStateException("Failed to create directory within " + - s"$TempDirAttempts attempts (tried ${baseName}0 to " + - s"${baseName}${TempDirAttempts - 1})") - } - } - - loop(0) - } - -} - -private object VirtualFileMaterializer { - private final val TempDirAttempts = 10000 -} diff --git a/js-envs/src/main/scala/org/scalajs/jsenv/jsdomnodejs/JSDOMNodeJSEnv.scala b/js-envs/src/main/scala/org/scalajs/jsenv/jsdomnodejs/JSDOMNodeJSEnv.scala deleted file mode 100644 index ab0caefd09..0000000000 --- a/js-envs/src/main/scala/org/scalajs/jsenv/jsdomnodejs/JSDOMNodeJSEnv.scala +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv.jsdomnodejs - -class JSDOMNodeJSEnv(config: JSDOMNodeJSEnv.Config) - extends org.scalajs.jsenv.nodejs.JSDOMNodeJSEnv(config.executable, - config.args, config.env, internal = ()) { - - def this() = this(JSDOMNodeJSEnv.Config()) -} - -object JSDOMNodeJSEnv { - final class Config private ( - val executable: String, - val args: List[String], - val env: Map[String, String] - ) { - private def this() = { - this( - executable = "node", - args = Nil, - env = Map.empty - ) - } - - def withExecutable(executable: String): Config = - copy(executable = executable) - - def withArgs(args: List[String]): Config = - copy(args = args) - - def withEnv(env: Map[String, String]): Config = - copy(env = env) - - private def copy( - executable: String = executable, - args: List[String] = args, - env: Map[String, String] = env - ): Config = { - new Config(executable, args, env) - } - } - - object Config { - /** Returns a default configuration for a [[JSDOMNodeJSEnv]]. - * - * The defaults are: - * - * - `executable`: `"node"` - * - `args`: `Nil` - * - `env`: `Map.empty` - */ - def apply(): Config = new Config() - } -} diff --git a/js-envs/src/main/scala/org/scalajs/jsenv/nodejs/AbstractNodeJSEnv.scala b/js-envs/src/main/scala/org/scalajs/jsenv/nodejs/AbstractNodeJSEnv.scala deleted file mode 100644 index 08b52870cd..0000000000 --- a/js-envs/src/main/scala/org/scalajs/jsenv/nodejs/AbstractNodeJSEnv.scala +++ /dev/null @@ -1,388 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv.nodejs - -import scala.annotation.tailrec - -import java.io.{Console => _, _} -import java.net._ - -import org.scalajs.core.ir.Utils.escapeJS -import org.scalajs.core.tools.io._ -import org.scalajs.core.tools.jsdep.ResolvedJSDependency -import org.scalajs.core.tools.logging.NullLogger -import org.scalajs.jsenv._ -import org.scalajs.jsenv.Utils.OptDeadline - -import scala.concurrent.TimeoutException -import scala.concurrent.duration._ - -abstract class AbstractNodeJSEnv( - protected val executable: String, - args: Seq[String], - env: Map[String, String], - val sourceMap: Boolean) - extends ExternalJSEnv(args, env) with ComJSEnv { - - /** True, if the installed node executable supports source mapping. - * - * Do `npm install source-map-support` if you need source maps. - */ - lazy val hasSourceMapSupport: Boolean = { - val code = new MemVirtualJSFile("source-map-support-probe.js") - .withContent("""require('source-map-support').install();""") - - try { - jsRunner(code).run(NullLogger, NullJSConsole) - true - } catch { - case t: ExternalJSEnv.NonZeroExitException => - false - } - } - - /** Retry-timeout to wait for the JS VM to connect */ - protected val acceptTimeout = 500 - - protected trait AbstractNodeRunner extends AbstractExtRunner with JSInitFiles { - - protected[this] val libCache = new VirtualFileMaterializer(true) - - /** File(s) to automatically install source-map-support. - * Is used by [[initFiles]], override to change/disable. - */ - protected def installSourceMap(): Seq[VirtualJSFile] = { - if (sourceMap) Seq( - new MemVirtualJSFile("sourceMapSupport.js").withContent( - """ - |try { - | require('source-map-support').install(); - |} catch (e) {} - """.stripMargin - ) - ) else Seq() - } - - /** File(s) to hack console.log to prevent if from changing `%%` to `%`. - * Is used by [[initFiles]], override to change/disable. - */ - protected def fixPercentConsole(): Seq[VirtualJSFile] = Seq( - new MemVirtualJSFile("nodeConsoleHack.js").withContent( - """ - |// Hack console log to duplicate double % signs - |(function() { - | function startsWithAnyOf(s, prefixes) { - | for (var i = 0; i < prefixes.length; i++) { - | // ES5 does not have .startsWith() on strings - | if (s.substring(0, prefixes[i].length) === prefixes[i]) - | return true; - | } - | return false; - | } - | var nodeWillDeduplicateEvenForOneArgument = startsWithAnyOf( - | process.version, ["v0.", "v1.", "v2.0."]); - | var oldLog = console.log; - | var newLog = function() { - | var args = arguments; - | if (args.length >= 1 && args[0] !== void 0 && args[0] !== null) { - | var argStr = args[0].toString(); - | if (args.length > 1 || nodeWillDeduplicateEvenForOneArgument) - | argStr = argStr.replace(/%/g, "%%"); - | args[0] = argStr; - | } - | oldLog.apply(console, args); - | }; - | console.log = newLog; - |})(); - """.stripMargin - ) - ) - - - /** File(s) to define `__ScalaJSEnv`. Defines `exitFunction`. - * Is used by [[initFiles]], override to change/disable. - */ - protected def runtimeEnv(): Seq[VirtualJSFile] = Seq( - new MemVirtualJSFile("scalaJSEnvInfo.js").withContent( - """ - |__ScalaJSEnv = { - | exitFunction: function(status) { process.exit(status); } - |}; - """.stripMargin - ) - ) - - override protected def initFiles(): Seq[VirtualJSFile] = - installSourceMap() ++ fixPercentConsole() ++ runtimeEnv() - - /** write a single JS file to a writer using an include fct if appropriate - * uses `require` if the file exists on the filesystem - */ - override protected def writeJSFile(file: VirtualJSFile, - writer: Writer): Unit = { - - def writeImport(file: File): Unit = { - val uri = file.toURI.toASCIIString - val importerFile = new MemVirtualJSFile("importer.js") - importerFile.content = { - s""" - |import("${escapeJS(uri)}").catch(e => { - | console.error(e); - | process.exit(1); - |}); - """.stripMargin - } - val f = libCache.materialize(importerFile) - writer.write(s"""require("${escapeJS(f.getAbsolutePath)}");\n""") - } - - file match { - case file: FileVirtualJSFile => - val fname = file.file.getAbsolutePath - if (fname.endsWith(".mjs")) - writeImport(file.file) - else - writer.write(s"""require("${escapeJS(fname)}");\n""") - case _ => - if (file.path.endsWith(".mjs")) - writeImport(libCache.materialize(file)) - else - super.writeJSFile(file, writer) - } - } - - // Node.js specific (system) environment - override protected def getVMEnv(): Map[String, String] = { - val baseNodePath = Option(System.getenv("NODE_PATH")).filter(_.nonEmpty) - val nodePath = libCache.cacheDir.getAbsolutePath + - baseNodePath.fold("")(p => File.pathSeparator + p) - - /* We use Java's `forEach` not to depend on Scala's JavaConverters, which - * are very difficult to cross-compile across 2.12- and 2.13+. - */ - val builder = Map.newBuilder[String, String] - System.getenv().forEach(new java.util.function.BiConsumer[String, String] { - def accept(key: String, value: String): Unit = - builder += key -> value - }) - builder += "NODE_MODULE_CONTEXTS" -> "0" - builder += "NODE_PATH" -> nodePath - builder ++= env - builder.result() - } - } - - protected trait NodeComJSRunner extends ComJSRunner with JSInitFiles { - - /* Manipulation of the socket must be protected by synchronized, except - * calls to `close()`. - */ - private[this] val serverSocket = - new ServerSocket(0, 0, InetAddress.getByName(null)) // Loopback address - - /* Those 3 fields are assigned *once* under synchronization in - * `awaitConnection()`. - * Read access must be protected by synchronized, or be done after a - * successful call to `awaitConnection()`. - */ - private var comSocket: Socket = _ - private var jvm2js: DataOutputStream = _ - private var js2jvm: DataInputStream = _ - - abstract override protected def initFiles(): Seq[VirtualJSFile] = - super.initFiles :+ comSetup - - private def comSetup(): VirtualJSFile = { - new MemVirtualJSFile("comSetup.js").withContent( - s""" - |(function() { - | // The socket for communication - | var socket = null; - | // The callback where received messages go - | var recvCallback = null; - | - | // Buffers received data - | var inBuffer = Buffer.alloc(0); - | - | function onData(data) { - | inBuffer = Buffer.concat([inBuffer, data]); - | tryReadMsg(); - | } - | - | function tryReadMsg() { - | while (inBuffer.length >= 4) { - | var msgLen = inBuffer.readInt32BE(0); - | var byteLen = 4 + msgLen * 2; - | - | if (inBuffer.length < byteLen) return; - | var res = ""; - | - | for (var i = 0; i < msgLen; ++i) - | res += String.fromCharCode(inBuffer.readInt16BE(4 + i * 2)); - | - | inBuffer = inBuffer.slice(byteLen); - | - | recvCallback(res); - | } - | } - | - | global.scalajsCom = { - | init: function(recvCB) { - | if (socket !== null) throw new Error("Com already open"); - | - | var net = require('net'); - | recvCallback = recvCB; - | socket = net.connect(${serverSocket.getLocalPort}); - | socket.on('data', onData); - | socket.on('error', function(err) { - | // Whatever happens, this closes the Com - | socket.end(); - | - | // Expected errors: - | // - EPIPE on write: JVM closes - | // - ECONNREFUSED on connect: JVM closes before JS opens - | var expected = ( - | err.syscall === "write" && err.code === "EPIPE" || - | err.syscall === "connect" && err.code === "ECONNREFUSED" - | ); - | - | if (!expected) { - | console.error("Scala.js Com failed: " + err); - | // We must terminate with an error - | process.exit(-1); - | } - | }); - | }, - | send: function(msg) { - | if (socket === null) throw new Error("Com not open"); - | - | var len = msg.length; - | var buf = Buffer.allocUnsafe(4 + len * 2); - | buf.writeInt32BE(len, 0); - | for (var i = 0; i < len; ++i) - | buf.writeUInt16BE(msg.charCodeAt(i), 4 + i * 2); - | socket.write(buf); - | }, - | close: function() { - | if (socket === null) throw new Error("Com not open"); - | socket.end(); - | } - | } - |}).call(this); - """.stripMargin) - } - - def send(msg: String): Unit = { - if (awaitConnection()) { - jvm2js.writeInt(msg.length) - jvm2js.writeChars(msg) - jvm2js.flush() - } - } - - def receive(timeout: Duration): String = { - if (!awaitConnection()) - throw new ComJSEnv.ComClosedException("Node.js isn't connected") - - js2jvm.mark(Int.MaxValue) - val savedSoTimeout = comSocket.getSoTimeout() - try { - val optDeadline = OptDeadline(timeout) - - comSocket.setSoTimeout((optDeadline.millisLeft min Int.MaxValue).toInt) - val len = js2jvm.readInt() - val carr = Array.fill(len) { - comSocket.setSoTimeout((optDeadline.millisLeft min Int.MaxValue).toInt) - js2jvm.readChar() - } - - js2jvm.mark(0) - String.valueOf(carr) - } catch { - case e: EOFException => - throw new ComJSEnv.ComClosedException(e) - case e: SocketTimeoutException => - js2jvm.reset() - throw new TimeoutException("Timeout expired") - } finally { - comSocket.setSoTimeout(savedSoTimeout) - } - } - - def close(): Unit = { - /* Close the socket first. This will cause any existing and upcoming - * calls to `awaitConnection()` to be canceled and throw a - * `SocketException` (unless it has already successfully completed the - * `accept()` call). - */ - serverSocket.close() - - /* Now wait for a possibly still-successful `awaitConnection()` to - * complete before closing the sockets. - */ - synchronized { - if (comSocket != null) { - jvm2js.close() - js2jvm.close() - comSocket.close() - } - } - } - - /** Waits until the JS VM has established a connection or terminates - * - * @return true if the connection was established - */ - private def awaitConnection(): Boolean = synchronized { - if (comSocket != null) { - true - } else { - @tailrec - def acceptLoop(): Option[Socket] = { - if (!isRunning) { - None - } else { - try { - Some(serverSocket.accept()) - } catch { - case to: SocketTimeoutException => acceptLoop() - } - } - } - - serverSocket.setSoTimeout(acceptTimeout) - val optComSocket = acceptLoop() - - optComSocket.fold { - false - } { comSocket0 => - val jvm2js0 = new DataOutputStream( - new BufferedOutputStream(comSocket0.getOutputStream())) - val js2jvm0 = new DataInputStream( - new BufferedInputStream(comSocket0.getInputStream())) - - /* Assign those three fields together, without the possibility of - * an exception happening in the middle (see #3408). - */ - comSocket = comSocket0 - jvm2js = jvm2js0 - js2jvm = js2jvm0 - - true - } - } - } - - override protected def finalize(): Unit = close() - } -} diff --git a/js-envs/src/main/scala/org/scalajs/jsenv/nodejs/JSDOMNodeJSEnv.scala b/js-envs/src/main/scala/org/scalajs/jsenv/nodejs/JSDOMNodeJSEnv.scala deleted file mode 100644 index 37c0ace3df..0000000000 --- a/js-envs/src/main/scala/org/scalajs/jsenv/nodejs/JSDOMNodeJSEnv.scala +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv.nodejs - -import java.io.{Console => _, _} - -import org.scalajs.core.tools.io._ -import org.scalajs.core.tools.jsdep.ResolvedJSDependency -import org.scalajs.jsenv._ - -import org.scalajs.core.ir.Utils.escapeJS - -class JSDOMNodeJSEnv private[jsenv] ( - executable: String, - args: Seq[String], - env: Map[String, String], - internal: Unit -) extends AbstractNodeJSEnv(executable, args, env, sourceMap = false) { - - @deprecated("Use org.scalajs.jsenv.jsdomnodejs.JSDOMNodeJSEnv.", "0.6.18") - def this( - executable: String = "node", - args: Seq[String] = Seq.empty, - env: Map[String, String] = Map.empty - ) = { - this(executable, args, env, internal = ()) - } - - protected def vmName: String = "Node.js with JSDOM" - - override def jsRunner(libs: Seq[ResolvedJSDependency], - code: VirtualJSFile): JSRunner = { - new DOMNodeRunner(libs, code) - } - - override def asyncRunner(libs: Seq[ResolvedJSDependency], - code: VirtualJSFile): AsyncJSRunner = { - new AsyncDOMNodeRunner(libs, code) - } - - override def comRunner(libs: Seq[ResolvedJSDependency], - code: VirtualJSFile): ComJSRunner = { - new ComDOMNodeRunner(libs, code) - } - - protected class DOMNodeRunner(libs: Seq[ResolvedJSDependency], code: VirtualJSFile) - extends ExtRunner(libs, code) with AbstractDOMNodeRunner - - protected class AsyncDOMNodeRunner(libs: Seq[ResolvedJSDependency], code: VirtualJSFile) - extends AsyncExtRunner(libs, code) with AbstractDOMNodeRunner - - protected class ComDOMNodeRunner(libs: Seq[ResolvedJSDependency], code: VirtualJSFile) - extends AsyncDOMNodeRunner(libs, code) with NodeComJSRunner - - protected trait AbstractDOMNodeRunner extends AbstractNodeRunner { - - protected def codeWithJSDOMContext(): Seq[VirtualJSFile] = { - val scriptsFiles = (getLibJSFiles() :+ code).map { - case file: FileVirtualFile => file.file - case file => libCache.materialize(file) - } - val scriptsURIsAsJSStrings = scriptsFiles.map { file => - "\"" + escapeJS(file.toURI.toASCIIString) + "\"" - } - val scriptsURIsJSArray = scriptsURIsAsJSStrings.mkString("[", ", ", "]") - - val jsDOMCode = { - s""" - |(function () { - | var jsdom = require("jsdom"); - | - | if (typeof jsdom.JSDOM === "function") { - | // jsdom >= 10.0.0 - | var virtualConsole = new jsdom.VirtualConsole() - | .sendTo(console, { omitJSDOMErrors: true }); - | virtualConsole.on("jsdomError", function (error) { - | /* #3458 Counter-hack the hack that React's development mode - | * uses to bypass browsers' debugging tools. If we detect - | * that we are called from that hack, we do nothing. - | */ - | var isWithinReactsInvokeGuardedCallbackDevHack_issue3458 = - | new Error("").stack.indexOf("invokeGuardedCallbackDev") >= 0; - | if (isWithinReactsInvokeGuardedCallbackDevHack_issue3458) - | return; - | - | try { - | // Display as much info about the error as possible - | if (error.detail && error.detail.stack) { - | console.error("" + error.detail); - | console.error(error.detail.stack); - | } else { - | console.error(error); - | } - | } finally { - | // Whatever happens, kill the process so that the run fails - | process.exit(1); - | } - | }); - | - | var dom = new jsdom.JSDOM("", { - | virtualConsole: virtualConsole, - | url: "http://localhost/", - | - | /* Allow unrestricted """ + "\n") - } - - /** - * PhantomJS doesn't support Function.prototype.bind. We polyfill it. - * https://github.com/ariya/phantomjs/issues/10522 - */ - override protected def initFiles(): Seq[VirtualJSFile] = Seq( - // scalastyle:off line.size.limit - new MemVirtualJSFile("bindPolyfill.js").withContent( - """ - |// Polyfill for Function.bind from Facebook react: - |// https://github.com/facebook/react/blob/3dc10749080a460e48bee46d769763ec7191ac76/src/test/phantomjs-shims.js - |// Originally licensed under Apache 2.0 - |(function() { - | - | var Ap = Array.prototype; - | var slice = Ap.slice; - | var Fp = Function.prototype; - | - | if (!Fp.bind) { - | // PhantomJS doesn't support Function.prototype.bind natively, so - | // polyfill it whenever this module is required. - | Fp.bind = function(context) { - | var func = this; - | var args = slice.call(arguments, 1); - | - | function bound() { - | var invokedAsConstructor = func.prototype && (this instanceof func); - | return func.apply( - | // Ignore the context parameter when invoking the bound function - | // as a constructor. Note that this includes not only constructor - | // invocations using the new keyword but also calls to base class - | // constructors such as BaseClass.call(this, ...) or super(...). - | !invokedAsConstructor && context || this, - | args.concat(slice.call(arguments)) - | ); - | } - | - | // The bound function must share the .prototype of the unbound - | // function so that any object created by one constructor will count - | // as an instance of both constructors. - | bound.prototype = func.prototype; - | - | return bound; - | }; - | } - | - |})(); - |""".stripMargin - ), - new MemVirtualJSFile("scalaJSEnvInfo.js").withContent( - """ - |__ScalaJSEnv = { - | exitFunction: function(status) { - | window.callPhantom({ - | action: 'exit', - | returnValue: status | 0 - | }); - | } - |}; - """.stripMargin - ) - // scalastyle:on line.size.limit - ) - - protected def writeWebpageLauncher(out: Writer): Unit = { - out.write(s""" - Phantom.js Launcher - """) - sendJS(getLibJSFiles(), out) - writeCodeLauncher(code, out) - out.write(s"\n\n\n") - } - - protected def createTmpLauncherFile(): File = { - val webF = createTmpWebpage() - - val launcherTmpF = File.createTempFile("phantomjs-launcher", ".js") - launcherTmpF.deleteOnExit() - - val out = new FileWriter(launcherTmpF) - - try { - out.write( - s"""// Scala.js Phantom.js launcher - |var page = require('webpage').create(); - |var url = "${escapeJS(fixFileURI(webF.toURI).toASCIIString)}"; - |var autoExit = $autoExit; - |page.onConsoleMessage = function(msg) { - | console.log(msg); - |}; - |page.onError = function(msg, trace) { - | console.error(msg); - | if (trace && trace.length) { - | console.error(''); - | trace.forEach(function(t) { - | console.error(' ' + t.file + ':' + t.line + - | (t.function ? ' (in function "' + t.function +'")' : '')); - | }); - | } - | - | phantom.exit(2); - |}; - |page.onCallback = function(data) { - | if (!data.action) { - | console.error('Called callback without action'); - | phantom.exit(3); - | } else if (data.action === 'exit') { - | phantom.exit(data.returnValue || 0); - | } else if (data.action === 'setAutoExit') { - | if (typeof(data.autoExit) === 'boolean') - | autoExit = data.autoExit; - | else - | autoExit = true; - | } else { - | console.error('Unknown callback action ' + data.action); - | phantom.exit(4); - | } - |}; - |page.open(url, function (status) { - | if (autoExit || status !== 'success') - | phantom.exit(status !== 'success'); - |}); - |""".stripMargin) - } finally { - out.close() - } - - logger.debug( - "PhantomJS using launcher at: " + launcherTmpF.getAbsolutePath()) - - launcherTmpF - } - - protected def createTmpWebpage(): File = { - val webTmpF = File.createTempFile("phantomjs-launcher-webpage", ".html") - webTmpF.deleteOnExit() - - val out = new BufferedWriter( - new OutputStreamWriter(new FileOutputStream(webTmpF), "UTF-8")) - - try { - writeWebpageLauncher(out) - } finally { - out.close() - } - - logger.debug( - "PhantomJS using webpage launcher at: " + webTmpF.getAbsolutePath()) - - webTmpF - } - - protected def writeCodeLauncher(code: VirtualJSFile, out: Writer): Unit = { - // Create a file with the launcher function. - val launcherFile = new MemVirtualJSFile("phantomjs-launcher.js") - launcherFile.content = s""" - // Phantom.js code launcher - // Origin: ${code.path} - function $launcherName() {${code.content}} - """ - writeJSFile(launcherFile, out) - } - } - - protected def htmlEscape(str: String): String = str.flatMap { - case '<' => "<" - case '>' => ">" - case '"' => """ - case '&' => "&" - case c => c.toString() - } - -} - -object PhantomJSEnv { - private final val MaxByteMessageSize = 32768 // 32 KB - private final val MaxCharMessageSize = MaxByteMessageSize / 2 // 2B per char - private final val MaxCharPayloadSize = MaxCharMessageSize - 1 // frag flag - - private final val launcherName = "scalaJSPhantomJSEnvLauncher" - - final class Config private ( - val executable: String, - val args: List[String], - val env: Map[String, String], - val autoExit: Boolean, - val jettyClassLoader: ClassLoader - ) { - private def this() = { - this( - executable = "phantomjs", - args = Nil, - env = Map.empty, - autoExit = true, - jettyClassLoader = null - ) - } - - def withExecutable(executable: String): Config = - copy(executable = executable) - - def withArgs(args: List[String]): Config = - copy(args = args) - - def withEnv(env: Map[String, String]): Config = - copy(env = env) - - def withAutoExit(autoExit: Boolean): Config = - copy(autoExit = autoExit) - - def withJettyClassLoader(jettyClassLoader: ClassLoader): Config = - copy(jettyClassLoader = jettyClassLoader) - - private def copy( - executable: String = executable, - args: List[String] = args, - env: Map[String, String] = env, - autoExit: Boolean = autoExit, - jettyClassLoader: ClassLoader = jettyClassLoader - ): Config = { - new Config(executable, args, env, autoExit, jettyClassLoader) - } - } - - object Config { - /** Returns a default configuration for a [[PhantomJSEnv]]. - * - * The defaults are: - * - * - `executable`: `"phantomjs"` - * - `args`: `Nil` - * - `env`: `Map.empty` - * - `autoExit`: `true` - * - `jettyClassLoader`: `null` (will use the current class loader) - */ - def apply(): Config = new Config() - } -} diff --git a/js-envs/src/main/scala/org/scalajs/jsenv/phantomjs/PhantomJettyClassLoader.scala b/js-envs/src/main/scala/org/scalajs/jsenv/phantomjs/PhantomJettyClassLoader.scala deleted file mode 100644 index 3fb0bed497..0000000000 --- a/js-envs/src/main/scala/org/scalajs/jsenv/phantomjs/PhantomJettyClassLoader.scala +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv.phantomjs - -import org.scalajs.core.tools.io.IO - -/** A special [[java.lang.ClassLoader]] to load the Jetty 8 dependency of - * [[PhantomJSEnv]] in a private space. - * - * It loads everything that belongs to `JettyWebsocketManager` itself (while - * retrieving the requested class file from its parent. - * For all other classes, it first tries to load them from `jettyLoader`, - * which should only contain the Jetty 8 classpath. - * If this fails, it delegates to its parent. - * - * The rationale is, that `JettyWebsocketManager` and its dependees can use - * the classes on the Jetty 8 classpath, while they remain hidden from the rest - * of the Java world. This allows to load another version of Jetty in the same - * JVM for the rest of the project. - */ -final class PhantomJettyClassLoader(jettyLoader: ClassLoader, - parent: ClassLoader) extends ClassLoader(parent) { - - def this(loader: ClassLoader) = - this(loader, ClassLoader.getSystemClassLoader()) - - /** Classes needed to bridge private jetty classpath and public PhantomJS - * Basically everything defined in JettyWebsocketManager. - */ - private val bridgeClasses = Set( - "org.scalajs.jsenv.phantomjs.JettyWebsocketManager", - "org.scalajs.jsenv.phantomjs.JettyWebsocketManager$WSLogger", - "org.scalajs.jsenv.phantomjs.JettyWebsocketManager$ComWebSocketListener", - "org.scalajs.jsenv.phantomjs.JettyWebsocketManager$$anon$1", - "org.scalajs.jsenv.phantomjs.JettyWebsocketManager$$anon$2" - ) - - override protected def loadClass(name: String, resolve: Boolean): Class[_] = { - if (bridgeClasses.contains(name)) { - // Load bridgeClasses manually since they must be associated to this - // class loader, rather than the parent class loader in order to find the - // jetty classes - - // First check if we have loaded it already - Option(findLoadedClass(name)) getOrElse { - val wsManager = - parent.getResourceAsStream(name.replace('.', '/') + ".class") - - if (wsManager == null) { - throw new ClassNotFoundException(name) - } else { - val buf = IO.readInputStreamToByteArray(wsManager) - defineClass(name, buf, 0, buf.length) - } - } - } else { - try { - jettyLoader.loadClass(name) - } catch { - case _: ClassNotFoundException => - super.loadClass(name, resolve) - } - } - } -} diff --git a/js-envs/src/main/scala/org/scalajs/jsenv/phantomjs/WebsocketListener.scala b/js-envs/src/main/scala/org/scalajs/jsenv/phantomjs/WebsocketListener.scala deleted file mode 100644 index adcad9a9e2..0000000000 --- a/js-envs/src/main/scala/org/scalajs/jsenv/phantomjs/WebsocketListener.scala +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv.phantomjs - -private[phantomjs] trait WebsocketListener { - def onRunning(): Unit - def onOpen(): Unit - def onClose(): Unit - def onMessage(msg: String): Unit - - def log(msg: String): Unit -} diff --git a/js-envs/src/main/scala/org/scalajs/jsenv/phantomjs/WebsocketManager.scala b/js-envs/src/main/scala/org/scalajs/jsenv/phantomjs/WebsocketManager.scala deleted file mode 100644 index 0f4dd90b7c..0000000000 --- a/js-envs/src/main/scala/org/scalajs/jsenv/phantomjs/WebsocketManager.scala +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv.phantomjs - -private[phantomjs] trait WebsocketManager { - def start(): Unit - def stop(): Unit - def sendMessage(msg: String): Unit - def localPort: Int - def isConnected: Boolean - def isClosed: Boolean -} diff --git a/js-envs/src/main/scala/org/scalajs/jsenv/rhino/LazyScalaJSScope.scala b/js-envs/src/main/scala/org/scalajs/jsenv/rhino/LazyScalaJSScope.scala deleted file mode 100644 index 11a68efa9b..0000000000 --- a/js-envs/src/main/scala/org/scalajs/jsenv/rhino/LazyScalaJSScope.scala +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv.rhino - -import scala.collection.mutable - -import org.mozilla.javascript.{Scriptable, Context} - -/** A proxy for a ScalaJS "scope" field that loads scripts lazily - * - * E.g., ScalaJS.c, which is a scope with the Scala.js classes, can be - * turned to a LazyScalaJSScope. Upon first access to a field of ScalaJS.c, - * say ScalaJS.c.scala_Option, the script defining that particular - * field will be loaded. - * This is possible because the relative path to the script can be derived - * from the name of the property being accessed. - * - * It is immensely useful, because it allows to load lazily only the scripts - * that are actually needed. - */ -private[rhino] class LazyScalaJSScope( - coreLib: ScalaJSCoreLib, - globalScope: Scriptable, - base: Scriptable, - isStatics: Boolean) extends Scriptable { - - private val fields = mutable.HashMap.empty[String, Any] - private var prototype: Scriptable = _ - private var parentScope: Scriptable = _ - - { - // Pre-fill fields with the properties of `base` - for (id <- base.getIds()) { - (id.asInstanceOf[Any]: @unchecked) match { - case name: String => put(name, this, base.get(name, base)) - case index: Int => put(index, this, base.get(index, base)) - } - } - } - - private def load(name: String): Unit = - coreLib.load(globalScope, propNameToEncodedName(name)) - - private def propNameToEncodedName(name: String): String = { - if (isStatics) name.split("__")(0) - else name - } - - override def getClassName(): String = "LazyScalaJSScope" - - override def get(name: String, start: Scriptable): AnyRef = { - if (name == "__noSuchMethod__") { - /* Automatically called by Rhino when trying to call a method fails. - * We don't want to throw a ClassNotFoundException for this case, but - * rather return a proper NOT_FOUND sentinel. Otherwise, this exception - * would "shadow" the real one containing the class name that could not - * be found on the classpath. - */ - Scriptable.NOT_FOUND - } else { - fields.getOrElse(name, { - try { - load(name) - fields.getOrElse(name, Scriptable.NOT_FOUND) - } catch { - // We need to re-throw the exception if `load` fails, otherwise the - // JavaScript runtime will not catch it. - case t: RhinoJSEnv.ClassNotFoundException => - throw Context.throwAsScriptRuntimeEx(t) - } - }).asInstanceOf[AnyRef] - } - } - - override def get(index: Int, start: Scriptable): AnyRef = - get(index.toString, start) - - override def has(name: String, start: Scriptable): Boolean = - fields.contains(name) - override def has(index: Int, start: Scriptable): Boolean = - has(index.toString, start) - - override def put(name: String, start: Scriptable, value: Any): Unit = - fields(name) = value - override def put(index: Int, start: Scriptable, value: Any): Unit = - put(index.toString, start, value) - - override def delete(name: String): Unit = () - override def delete(index: Int): Unit = () - - override def getPrototype(): Scriptable = prototype - override def setPrototype(value: Scriptable): Unit = prototype = value - - override def getParentScope(): Scriptable = parentScope - override def setParentScope(value: Scriptable): Unit = parentScope = value - - override def getIds(): Array[AnyRef] = fields.keys.toArray - - override def getDefaultValue(hint: java.lang.Class[_]): AnyRef = { - base.getDefaultValue(hint) - } - - override def hasInstance(instance: Scriptable): Boolean = false -} diff --git a/js-envs/src/main/scala/org/scalajs/jsenv/rhino/RhinoJSEnv.scala b/js-envs/src/main/scala/org/scalajs/jsenv/rhino/RhinoJSEnv.scala deleted file mode 100644 index 7f34ac6b13..0000000000 --- a/js-envs/src/main/scala/org/scalajs/jsenv/rhino/RhinoJSEnv.scala +++ /dev/null @@ -1,623 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv.rhino - -import org.scalajs.jsenv._ -import org.scalajs.jsenv.Utils.OptDeadline - -import org.scalajs.core.tools.sem.Semantics -import org.scalajs.core.tools.io._ -import org.scalajs.core.tools.jsdep.ResolvedJSDependency -import org.scalajs.core.tools.logging._ - -import org.scalajs.core.tools.linker.LinkingUnit -import org.scalajs.core.tools.linker.backend.OutputMode -import org.scalajs.core.tools.linker.backend.emitter.Emitter -import org.scalajs.core.tools.javascript.ESLevel - -import scala.annotation.tailrec - -import scala.io.Source - -import scala.collection.mutable - -import scala.concurrent.{Future, Promise, Await, TimeoutException} -import scala.concurrent.duration._ - -import scala.reflect.ClassTag - -import org.mozilla.javascript._ - -/** A JS environment using a modified Rhino interpreter (deprecated). - * - * As of Scala.js 0.6.13, `RhinoJSEnv` is deprecated. It will be removed in - * Scala.js 1.0.0. - */ -final class RhinoJSEnv private ( - semantics: Semantics, - withDOM: Boolean, - val sourceMap: Boolean -) extends LinkingUnitComJSEnv { - - import RhinoJSEnv._ - - @deprecated( - "The Rhino JS environment is being phased out. " + - "It will be removed in Scala.js 1.0.0. ", - "0.6.13") - def this(semantics: Semantics = Semantics.Defaults, withDOM: Boolean = false) = - this(semantics, withDOM, sourceMap = true) - - /** A non-deprecated constructor for internal use. */ - private[scalajs] def this(semantics: Semantics, withDOM: Boolean, - internal: Unit) = { - this(semantics, withDOM, sourceMap = true) - } - - def withSourceMap(sourceMap: Boolean): RhinoJSEnv = - new RhinoJSEnv(semantics, withDOM, sourceMap) - - /* Ask the Emitter, which we'll use in ScalaJSCoreLib to generate JS code, - * what are its requirements. - */ - val symbolRequirements = Emitter.symbolRequirements(semantics, ESLevel.ES5) - - def name: String = "RhinoJSEnv" - - override def loadLinkingUnit(linkingUnit: LinkingUnit): ComJSEnv = { - verifyUnit(linkingUnit) - super.loadLinkingUnit(linkingUnit) - } - - /** 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. - */ - override def jsRunner(libs: Seq[ResolvedJSDependency], - code: VirtualJSFile): JSRunner = { - new Runner(libs, None, Nil, code) - } - - override def jsRunner(preLibs: Seq[ResolvedJSDependency], - linkingUnit: LinkingUnit, postLibs: Seq[ResolvedJSDependency], - code: VirtualJSFile): JSRunner = { - verifyUnit(linkingUnit) - new Runner(preLibs, Some(linkingUnit), postLibs, code) - } - - private class Runner(preLibs: Seq[ResolvedJSDependency], - optLinkingUnit: Option[LinkingUnit], postLibs: Seq[ResolvedJSDependency], - code: VirtualJSFile) extends JSRunner { - def run(logger: Logger, console: JSConsole): Unit = - internalRunJS(preLibs, optLinkingUnit, postLibs, - code, logger, console, None) - } - - override def asyncRunner(libs: Seq[ResolvedJSDependency], - code: VirtualJSFile): AsyncJSRunner = { - new AsyncRunner(libs, None, Nil, code) - } - - override def asyncRunner(preLibs: Seq[ResolvedJSDependency], - linkingUnit: LinkingUnit, postLibs: Seq[ResolvedJSDependency], - code: VirtualJSFile): AsyncJSRunner = { - verifyUnit(linkingUnit) - new AsyncRunner(preLibs, Some(linkingUnit), postLibs, code) - } - - private class AsyncRunner(preLibs: Seq[ResolvedJSDependency], - optLinkingUnit: Option[LinkingUnit], postLibs: Seq[ResolvedJSDependency], - code: VirtualJSFile) extends AsyncJSRunner { - - private[this] val promise = Promise[Unit] - private[this] var _thread: Thread = _ - - def future: Future[Unit] = promise.future - - def start(logger: Logger, console: JSConsole): Future[Unit] = { - _thread = new Thread { - override def run(): Unit = { - try { - internalRunJS(preLibs, optLinkingUnit, postLibs, - code, logger, console, optChannel) - promise.success(()) - } catch { - case t: Throwable => - promise.failure(t) - } - } - } - - _thread.start() - future - } - - def stop(): Unit = _thread.interrupt() - - protected def optChannel(): Option[Channel] = None - } - - override def comRunner(libs: Seq[ResolvedJSDependency], - code: VirtualJSFile): ComJSRunner = { - new ComRunner(libs, None, Nil, code) - } - - override def comRunner(preLibs: Seq[ResolvedJSDependency], - linkingUnit: LinkingUnit, postLibs: Seq[ResolvedJSDependency], - code: VirtualJSFile): ComJSRunner = { - verifyUnit(linkingUnit) - new ComRunner(preLibs, Some(linkingUnit), postLibs, code) - } - - private class ComRunner(preLibs: Seq[ResolvedJSDependency], - optLinkingUnit: Option[LinkingUnit], postLibs: Seq[ResolvedJSDependency], - code: VirtualJSFile) - extends AsyncRunner(preLibs, optLinkingUnit, postLibs, code) - with ComJSRunner { - - private[this] val channel = new Channel - - override protected def optChannel(): Option[Channel] = Some(channel) - - def send(msg: String): Unit = channel.sendToJS(msg) - - def receive(timeout: Duration): String = { - try { - channel.recvJVM(timeout) - } catch { - case _: ChannelClosedException => - throw new ComJSEnv.ComClosedException - } - } - - def close(): Unit = channel.closeJVM() - - } - - private def internalRunJS(preLibs: Seq[ResolvedJSDependency], - optLinkingUnit: Option[LinkingUnit], postLibs: Seq[ResolvedJSDependency], - code: VirtualJSFile, logger: Logger, console: JSConsole, - optChannel: Option[Channel]): Unit = { - - val context = Context.enter() - try { - val scope = context.initStandardObjects() - - // Rhino has trouble optimizing some big things, e.g., env.js or ScalaTest - context.setOptimizationLevel(-1) - - if (withDOM) - setupDOM(context, scope) - - disableLiveConnect(context, scope) - setupConsole(context, scope, console) - - val taskQ = setupSetTimeout(context, scope) - - // Optionally setup scalaJSCom - var recvCallback: Option[String => Unit] = None - for (channel <- optChannel) { - setupCom(context, scope, channel, - setCallback = cb => recvCallback = Some(cb), - clrCallback = () => recvCallback = None) - } - - try { - // Evaluate pre JS libs - preLibs.foreach(lib => context.evaluateFile(scope, lib.lib)) - - // Load LinkingUnit (if present) - optLinkingUnit.foreach(loadLinkingUnit(context, scope, _)) - - // Evaluate post JS libs - postLibs.foreach(lib => context.evaluateFile(scope, lib.lib)) - - // Actually run the code - context.evaluateFile(scope, code) - - // Start the event loop - - for (channel <- optChannel) { - comEventLoop(taskQ, channel, - () => recvCallback.get, () => recvCallback.isDefined) - } - - // Channel is closed. Fall back to basic event loop - basicEventLoop(taskQ) - - } catch { - case e: RhinoException => - // Trace here, since we want to be in the context to trace. - logger.trace(e) - throw new Exception( - s"Exception while running JS code: ${e.getMessage}") - } - } finally { - // Ensure the channel is closed to release JVM side - optChannel.foreach(_.closeJS()) - - Context.exit() - } - } - - private def setupDOM(context: Context, scope: Scriptable): Unit = { - // 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") - - // 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) */ - private def disableLiveConnect(context: Context, scope: Scriptable): Unit = { - 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 - } - } - - private def setupConsole(context: Context, scope: Scriptable, - console: JSConsole): Unit = { - // Setup console.log - val jsconsole = context.newObject(scope) - jsconsole.addFunction("log", _.foreach(console.log _)) - ScriptableObject.putProperty(scope, "console", jsconsole) - } - - private def setupSetTimeout(context: Context, - scope: Scriptable): TaskQueue = { - - val ordering = Ordering.by[TimedTask, Deadline](_.deadline).reverse - val taskQ = mutable.PriorityQueue.empty(ordering) - - def ensure[T: ClassTag](v: AnyRef, errMsg: String): T = v match { - case v: T => v - case _ => throw new IllegalArgumentException(errMsg) - } - - scope.addFunction("setTimeout", args => { - val cb = ensure[Function](args(0), - "First argument to setTimeout must be a function") - - val deadline = - args.lift(1).fold(0)(n => Context.toNumber(n).toInt).millis.fromNow - - val task = new TimeoutTask(deadline, () => - cb.call(context, scope, scope, args.slice(2, args.length))) - - taskQ += task - - task - }) - - scope.addFunction("setInterval", args => { - val cb = ensure[Function](args(0), - "First argument to setInterval must be a function") - - val interval = Context.toNumber(args(1)).toInt.millis - val firstDeadline = interval.fromNow - - val task = new IntervalTask(firstDeadline, interval, () => - cb.call(context, scope, scope, args.slice(2, args.length))) - - taskQ += task - - task - }) - - scope.addFunction("clearTimeout", args => { - val task = ensure[TimeoutTask](args(0), "First argument to " + - "clearTimeout must be a value returned by setTimeout") - task.cancel() - }) - - scope.addFunction("clearInterval", args => { - val task = ensure[IntervalTask](args(0), "First argument to " + - "clearInterval must be a value returned by setInterval") - task.cancel() - }) - - taskQ - } - - private def setupCom(context: Context, scope: Scriptable, channel: Channel, - setCallback: (String => Unit) => Unit, clrCallback: () => Unit): Unit = { - - val comObj = context.newObject(scope) - - comObj.addFunction("send", s => - channel.sendToJVM(Context.toString(s(0)))) - - comObj.addFunction("init", s => s(0) match { - case f: Function => - val cb: String => Unit = - msg => f.call(context, scope, scope, Array(msg)) - setCallback(cb) - case _ => - throw new IllegalArgumentException( - "First argument to init must be a function") - }) - - comObj.addFunction("close", _ => { - // Tell JVM side we won't send anything - channel.closeJS() - // Internally register that we're done - clrCallback() - }) - - ScriptableObject.putProperty(scope, "scalajsCom", comObj) - } - - /** Loads a [[LinkingUnit]] with lazy loading of classes and source mapping. */ - private def loadLinkingUnit(context: Context, scope: Scriptable, - linkingUnit: LinkingUnit): Unit = { - - val loader = new ScalaJSCoreLib(linkingUnit) - - // Setup sourceMapper - if (sourceMap) { - val oldScalaJSenv = ScriptableObject.getProperty(scope, "__ScalaJSEnv") - val scalaJSenv = oldScalaJSenv match { - case Scriptable.NOT_FOUND => - val newScalaJSenv = context.newObject(scope) - ScriptableObject.putProperty(scope, "__ScalaJSEnv", newScalaJSenv) - newScalaJSenv - - case oldScalaJSenv: Scriptable => - oldScalaJSenv - } - - scalaJSenv.addFunction("sourceMapper", args => { - val trace = Context.toObject(args(0), scope) - loader.mapStackTrace(trace, context, scope) - }) - } - - loader.insertInto(context, scope) - } - - private def basicEventLoop(taskQ: TaskQueue): Unit = - eventLoopImpl(taskQ, sleepWait, () => true) - - private def comEventLoop(taskQ: TaskQueue, channel: Channel, - callback: () => String => Unit, isOpen: () => Boolean): Unit = { - - if (!isOpen()) - // The channel has not been opened yet. Wait for opening. - eventLoopImpl(taskQ, sleepWait, () => !isOpen()) - - // Once we reach this point, we either: - // - Are done - // - The channel is open - - // Guard call to `callback` - if (isOpen()) { - val cb = callback() - try { - @tailrec - def loop(): Unit = { - val loopResult = eventLoopImpl(taskQ, channel.recvJS _, isOpen) - - loopResult match { - case Some(msg) => - cb(msg) - loop() - case None if isOpen() => - assert(taskQ.isEmpty) - cb(channel.recvJS()) - loop() - case None => - // No tasks left, channel closed - } - } - loop() - } catch { - case _: ChannelClosedException => - // the JVM side closed the connection - } - } - } - - /** Run an event loop on [[taskQ]] using [[waitFct]] to wait - * - * If [[waitFct]] returns a Some, this method returns this value immediately - * If [[waitFct]] returns a None, we assume a sufficient amount has been - * waited for the Deadline to pass. The event loop then runs the task. - * - * Each iteration, [[continue]] is queried, whether to continue the loop. - * - * @returns A Some returned by [[waitFct]] or None if [[continue]] has - * returned false, or there are no more tasks (i.e. [[taskQ]] is empty) - * @throws InterruptedException if the thread was interrupted - */ - private def eventLoopImpl[T](taskQ: TaskQueue, - waitFct: Deadline => Option[T], continue: () => Boolean): Option[T] = { - - @tailrec - def loop(): Option[T] = { - if (Thread.interrupted()) - throw new InterruptedException() - - if (taskQ.isEmpty || !continue()) None - else { - val task = taskQ.head - if (task.canceled) { - taskQ.dequeue() - loop() - } else { - waitFct(task.deadline) match { - case result @ Some(_) => result - - case None => - // The time has actually expired - val task = taskQ.dequeue() - - // Perform task - task.task() - - if (task.reschedule()) - taskQ += task - - loop() - } - } - } - } - - loop() - } - - private val sleepWait = { (deadline: Deadline) => - val timeLeft = deadline.timeLeft.toMillis - if (timeLeft > 0) - Thread.sleep(timeLeft) - None - } - - private def verifyUnit(linkingUnit: LinkingUnit) = { - require(linkingUnit.semantics == semantics, - "RhinoJSEnv and LinkingUnit must agree on semantics") - require(linkingUnit.esLevel == ESLevel.ES5, "RhinoJSEnv only supports ES5") - } - -} - -object RhinoJSEnv { - - final class ClassNotFoundException(className: String) extends Exception( - s"Rhino was unable to load Scala.js class: $className") - - /** Communication channel between the Rhino thread and the rest of the JVM */ - private class Channel { - private[this] var _closedJS = false - private[this] var _closedJVM = false - private[this] val js2jvm = mutable.Queue.empty[String] - private[this] val jvm2js = mutable.Queue.empty[String] - - def sendToJS(msg: String): Unit = synchronized { - ensureOpen(_closedJVM) - jvm2js.enqueue(msg) - notifyAll() - } - - def sendToJVM(msg: String): Unit = synchronized { - ensureOpen(_closedJS) - js2jvm.enqueue(msg) - notifyAll() - } - - def recvJVM(timeout: Duration): String = synchronized { - val deadline = OptDeadline(timeout) - - while (js2jvm.isEmpty && ensureOpen(_closedJS) && !deadline.isOverdue) - wait(deadline.millisLeft) - - if (js2jvm.isEmpty) - throw new TimeoutException("Timeout expired") - js2jvm.dequeue() - } - - def recvJS(): String = synchronized { - while (jvm2js.isEmpty && ensureOpen(_closedJVM)) - wait() - - jvm2js.dequeue() - } - - def recvJS(deadline: Deadline): Option[String] = synchronized { - var expired = false - while (jvm2js.isEmpty && !expired && ensureOpen(_closedJVM)) { - val timeLeft = deadline.timeLeft.toMillis - if (timeLeft > 0) - wait(timeLeft) - else - expired = true - } - - if (expired) None - else Some(jvm2js.dequeue()) - } - - def closeJS(): Unit = synchronized { - _closedJS = true - notifyAll() - } - - def closeJVM(): Unit = synchronized { - _closedJVM = true - notifyAll() - } - - /** Throws if the channel is closed and returns true */ - private def ensureOpen(closed: Boolean): Boolean = { - if (closed) - throw new ChannelClosedException - true - } - } - - private class ChannelClosedException extends Exception - - private abstract class TimedTask(val task: () => Unit) { - private[this] var _canceled: Boolean = false - - def deadline: Deadline - def reschedule(): Boolean - - def canceled: Boolean = _canceled - def cancel(): Unit = _canceled = true - } - - private final class TimeoutTask(val deadline: Deadline, - task: () => Unit) extends TimedTask(task) { - def reschedule(): Boolean = false - - override def toString(): String = - s"TimeoutTask($deadline, canceled = $canceled)" - } - - private final class IntervalTask(firstDeadline: Deadline, - interval: FiniteDuration, task: () => Unit) extends TimedTask(task) { - - private[this] var _deadline = firstDeadline - - def deadline: Deadline = _deadline - - def reschedule(): Boolean = { - _deadline += interval - !canceled - } - - override def toString(): String = - s"IntervalTask($deadline, interval = $interval, canceled = $canceled)" - } - - private type TaskQueue = mutable.PriorityQueue[TimedTask] - -} diff --git a/js-envs/src/main/scala/org/scalajs/jsenv/rhino/ScalaJSCoreLib.scala b/js-envs/src/main/scala/org/scalajs/jsenv/rhino/ScalaJSCoreLib.scala deleted file mode 100644 index 9cb6f0d50f..0000000000 --- a/js-envs/src/main/scala/org/scalajs/jsenv/rhino/ScalaJSCoreLib.scala +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv.rhino - -import scala.collection.mutable - -import org.mozilla.javascript.{Context, Scriptable} - -import org.scalajs.core.ir - -import org.scalajs.core.tools.sem.Semantics -import org.scalajs.core.tools.linker.{LinkedClass, LinkingUnit} -import org.scalajs.core.tools.javascript._ -import org.scalajs.core.tools.io._ - -import org.scalajs.core.tools.linker.backend.ModuleKind.NoModule -import org.scalajs.core.tools.linker.backend.OutputMode.ECMAScript51Global -import org.scalajs.core.tools.linker.backend.emitter._ - -private[rhino] class ScalaJSCoreLib(linkingUnit: LinkingUnit) { - import ScalaJSCoreLib._ - - require(linkingUnit.esLevel == ESLevel.ES5, "RhinoJSEnv only supports ES5") - - private val emitter = - new Emitter(linkingUnit.semantics, ECMAScript51Global, NoModule) - - emitter.rhinoAPI.initialize(linkingUnit) - - private val (providers, exportedSymbols) = { - val providers = mutable.Map.empty[String, LinkedClass] - val exportedSymbols = mutable.ListBuffer.empty[String] - - for (linkedClass <- linkingUnit.classDefs) { - def hasStaticInitializer = { - linkedClass.staticMethods.exists { - _.tree.name.encodedName == ir.Definitions.StaticInitializerName - } - } - - providers += linkedClass.encodedName -> linkedClass - if (linkedClass.isExported || hasStaticInitializer) - exportedSymbols += linkedClass.encodedName - } - - (providers, exportedSymbols) - } - - def insertInto(context: Context, scope: Scriptable): Unit = { - val semantics = linkingUnit.semantics - context.evaluateFile(scope, emitter.rhinoAPI.getHeaderFile()) - lazifyScalaJSFields(scope) - - // Make sure exported symbols are loaded - val ScalaJS = Context.toObject(scope.get("ScalaJS", scope), scope) - val c = Context.toObject(ScalaJS.get("c", ScalaJS), scope) - for (encodedName <- exportedSymbols) - c.get(encodedName, c) - - // Execute the module initializers - evaluateJSTree(scope, emitter.rhinoAPI.genModuleInitializers(linkingUnit), - "ScalaJSEntryPoints.js") - } - - /** Source maps the given stack trace (where possible) */ - def mapStackTrace(stackTrace: Scriptable, - context: Context, scope: Scriptable): Scriptable = { - val count = Context.toNumber(stackTrace.get("length", stackTrace)).toInt - - // Maps file -> max line (0-based) - val neededMaps = mutable.Map.empty[String, Int] - - // Collect required line counts - for (i <- 0 until count) { - val elem = Context.toObject(stackTrace.get(i, stackTrace), scope) - val fileName = Context.toString(elem.get("fileName", elem)) - - if (fileName.endsWith(PseudoFileSuffix) && - providers.contains(fileName.stripSuffix(PseudoFileSuffix))) { - - val curMaxLine = neededMaps.getOrElse(fileName, -1) - val reqLine = Context.toNumber(elem.get("lineNumber", elem)).toInt - 1 - - if (reqLine > curMaxLine) - neededMaps.put(fileName, reqLine) - } - } - - // Map required files - val maps = - for ((fileName, maxLine) <- neededMaps) - yield (fileName, getSourceMapper(fileName, maxLine)) - - // Create new stack trace to return - val res = context.newArray(scope, count) - - for (i <- 0 until count) { - val elem = Context.toObject(stackTrace.get(i, stackTrace), scope) - val fileName = Context.toString(elem.get("fileName", elem)) - val line = Context.toNumber(elem.get("lineNumber", elem)).toInt - 1 - - val pos = maps.get(fileName).fold(ir.Position.NoPosition)(_(line)) - - val newElem = - if (pos.isDefined) newPosElem(scope, context, elem, pos) - else elem - - res.put(i, res, newElem) - } - - res - } - - private def getSourceMapper(fileName: String, untilLine: Int) = { - val linked = providers(fileName.stripSuffix(PseudoFileSuffix)) - val mapper = new Printers.ReverseSourceMapPrinter(untilLine) - val desugared = emitter.rhinoAPI.genClassDef(linked) - mapper.reverseSourceMap(desugared) - mapper - } - - private def newPosElem(scope: Scriptable, context: Context, - origElem: Scriptable, pos: ir.Position): Scriptable = { - assert(pos.isDefined) - - val elem = context.newObject(scope) - - elem.put("declaringClass", elem, origElem.get("declaringClass", origElem)) - elem.put("methodName", elem, origElem.get("methodName", origElem)) - elem.put("fileName", elem, pos.source.toString) - elem.put("lineNumber", elem, pos.line + 1) - elem.put("columnNumber", elem, pos.column + 1) - - elem - } - - private val scalaJSLazyFields = Seq( - Info("d"), - Info("a"), - Info("b"), - Info("c"), - Info("h"), - Info("s", isStatics = true), - Info("t", isStatics = true), - Info("f", isStatics = true), - Info("n"), - Info("m"), - Info("is"), - Info("as"), - Info("isArrayOf"), - Info("asArrayOf")) - - private def lazifyScalaJSFields(scope: Scriptable) = { - val ScalaJS = Context.toObject(scope.get("ScalaJS", scope), scope) - - def makeLazyScalaJSScope(base: Scriptable, isStatics: Boolean) = - new LazyScalaJSScope(this, scope, base, isStatics) - - for (Info(name, isStatics) <- scalaJSLazyFields) { - val base = ScalaJS.get(name, ScalaJS) - // Depending on the Semantics, some fields could be entirely absent - if (base != Scriptable.NOT_FOUND) { - val lazified = makeLazyScalaJSScope( - base.asInstanceOf[Scriptable], isStatics) - ScalaJS.put(name, ScalaJS, lazified) - } - } - } - - private[rhino] def load(scope: Scriptable, encodedName: String): Unit = { - val linkedClass = providers.getOrElse(encodedName, - throw new RhinoJSEnv.ClassNotFoundException(encodedName)) - - val desugared = emitter.rhinoAPI.genClassDef(linkedClass) - evaluateJSTree(scope, desugared, encodedName + PseudoFileSuffix) - } - - private def evaluateJSTree(scope: Scriptable, tree: Trees.Tree, - fakeFileName: String): Unit = { - val codeWriter = new java.io.StringWriter - val printer = new Printers.JSTreePrinter(codeWriter) - printer.printTopLevelTree(tree) - printer.complete() - val ctx = Context.getCurrentContext() - ctx.evaluateString(scope, codeWriter.toString(), - fakeFileName, 1, null) - } -} - -private[rhino] object ScalaJSCoreLib { - private case class Info(name: String, isStatics: Boolean = false) - - private final val PseudoFileSuffix = ".sjsir" -} diff --git a/js-envs/src/main/scala/org/scalajs/jsenv/rhino/package.scala b/js-envs/src/main/scala/org/scalajs/jsenv/rhino/package.scala deleted file mode 100644 index 9a5422e07a..0000000000 --- a/js-envs/src/main/scala/org/scalajs/jsenv/rhino/package.scala +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.jsenv - -import org.mozilla.javascript._ - -import org.scalajs.core.tools.io._ - -package object rhino { - - private[rhino] implicit class ContextOps(val self: Context) extends AnyVal { - def evaluateFile(scope: Scriptable, file: VirtualJSFile, - securityDomain: AnyRef = null): Any = { - self.evaluateString(scope, file.content, file.path, 1, securityDomain) - } - } - - private[rhino] implicit class ScriptableObjectOps(val self: Scriptable) { - def addFunction(name: String, function: Array[AnyRef] => Any): Unit = { - val rhinoFunction = - new BaseFunction { - ScriptRuntime.setFunctionProtoAndParent(this, self) - override def call(context: Context, scope: Scriptable, - thisObj: Scriptable, args: Array[AnyRef]): AnyRef = { - function(args) match { - case () => Undefined.instance - case r => r.asInstanceOf[AnyRef] - } - } - } - - ScriptableObject.putProperty(self, name, rhinoFunction) - } - } -} diff --git a/junit-async/js/src/main/scala/org/scalajs/junit/async/package.scala b/junit-async/js/src/main/scala/org/scalajs/junit/async/package.scala new file mode 100644 index 0000000000..5e6d312967 --- /dev/null +++ b/junit-async/js/src/main/scala/org/scalajs/junit/async/package.scala @@ -0,0 +1,28 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.junit + +import scala.concurrent.Future + +/* Use the queue execution context (based on JS promises) explicitly: + * We do not have anything better at our disposal and it is accceptable in + * terms of fairness: All we use it for is to map over a completed Future once. + */ +import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue + +import scala.util.{Try, Success} + +package object async { + type AsyncResult = Future[Try[Unit]] + def await(f: Future[_]): AsyncResult = f.map(_ => Success(())) +} diff --git a/junit-async/jvm/src/main/scala/org/scalajs/junit/async/package.scala b/junit-async/jvm/src/main/scala/org/scalajs/junit/async/package.scala new file mode 100644 index 0000000000..5fedec8444 --- /dev/null +++ b/junit-async/jvm/src/main/scala/org/scalajs/junit/async/package.scala @@ -0,0 +1,21 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.junit + +import scala.concurrent._ +import scala.concurrent.duration.Duration + +package object async { + type AsyncResult = Unit + def await(f: Future[_]): AsyncResult = Await.result(f, Duration.Inf) +} diff --git a/junit-plugin/src/main/scala/org/scalajs/junit/plugin/Compat210Component.scala b/junit-plugin/src/main/scala/org/scalajs/junit/plugin/Compat210Component.scala deleted file mode 100644 index ff23b72a44..0000000000 --- a/junit-plugin/src/main/scala/org/scalajs/junit/plugin/Compat210Component.scala +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.junit.plugin - -import scala.reflect.internal.Flags -import scala.tools.nsc._ - -/** Hacks to have our source code compatible with 2.10 and 2.11. - * It exposes 2.11 API in a 2.10 compiler. - * - * @author Nicolas Stucki - */ -trait Compat210Component { - - val global: Global - - import global._ - - def newValDef(sym: Symbol, rhs: Tree)( - mods: Modifiers = Modifiers(sym.flags), - name: TermName = sym.name.toTermName, - tpt: Tree = TypeTreeMemberType(sym)): ValDef = { - atPos(sym.pos)(ValDef(mods, name, tpt, rhs)) setSymbol sym - } - - def newDefDef(sym: Symbol, rhs: Tree)( - mods: Modifiers = Modifiers(sym.flags), - name: TermName = sym.name.toTermName, - tparams: List[TypeDef] = sym.typeParams.map(sym => - newTypeDef(sym, typeBoundsTree(sym))()), - vparamss: List[List[ValDef]] = mapParamss(sym)(sym => - newValDef(sym, EmptyTree)()), - tpt: Tree = TypeTreeMemberType(sym)): DefDef = { - atPos(sym.pos)(DefDef(mods, name, tparams, vparamss, tpt, rhs)).setSymbol(sym) - } - - def TypeTreeMemberType(sym: Symbol): TypeTree = { - val resType = { - if (sym.owner.isTerm) sym.tpe - else sym.owner.thisType.memberType(sym) - }.finalResultType - atPos(sym.pos.focus)(TypeTree(resType)) - } - - private def newTypeDef(sym: Symbol, rhs: Tree)( - mods: Modifiers = Modifiers(sym.flags), - name: TypeName = sym.name.toTypeName, - tparams: List[TypeDef] = sym.typeParams.map(sym => - newTypeDef(sym, typeBoundsTree(sym))())): TypeDef = { - atPos(sym.pos)(TypeDef(mods, name, tparams, rhs)) setSymbol sym - } - - private def typeBoundsTree(bounds: TypeBounds): TypeBoundsTree = - TypeBoundsTree(TypeTree(bounds.lo), TypeTree(bounds.hi)) - - private def typeBoundsTree(sym: Symbol): TypeBoundsTree = - atPos(sym.pos)(typeBoundsTree(sym.info.bounds)) - - implicit final class GenCompat(self: global.TreeGen) { - def mkClassDef(mods: Modifiers, name: TypeName, - tparams: List[TypeDef], templ: Template): ClassDef = { - val isInterface = - mods.isTrait && templ.body.forall(treeInfo.isInterfaceMember) - val mods1 = if (isInterface) mods | Flags.INTERFACE else mods - ClassDef(mods1, name, tparams, templ) - } - } - - implicit final class DefinitionsCompat( - self: Compat210Component.this.global.definitions.type) { - - lazy val StringTpe = definitions.StringClass.tpe - - def wrapVarargsArrayMethodName(elemtp: Type): TermName = - self.wrapArrayMethodName(elemtp) - - def wrapArrayMethodName(elemtp: Type): TermName = infiniteLoop() - } - - private def infiniteLoop(): Nothing = - throw new AssertionError("Infinite loop in Compat210Component") -} diff --git a/junit-plugin/src/main/scala/org/scalajs/junit/plugin/ScalaJSJUnitPlugin.scala b/junit-plugin/src/main/scala/org/scalajs/junit/plugin/ScalaJSJUnitPlugin.scala index c16e163aad..f274ad5843 100644 --- a/junit-plugin/src/main/scala/org/scalajs/junit/plugin/ScalaJSJUnitPlugin.scala +++ b/junit-plugin/src/main/scala/org/scalajs/junit/plugin/ScalaJSJUnitPlugin.scala @@ -12,83 +12,21 @@ package org.scalajs.junit.plugin -import scala.language.reflectiveCalls +import scala.annotation.tailrec -import scala.reflect.internal.Flags import scala.tools.nsc._ import scala.tools.nsc.plugins.{ Plugin => NscPlugin, PluginComponent => NscPluginComponent } -/** The Scala.js jUnit plugin is a way to overcome the lack of annotation - * information of any test class (usually accessed through reflection). - * This is all the information required by the Scala.js testing framework to - * execute the tests. +/** The Scala.js JUnit plugin replaces reflection based test lookup. * - * As an example we take the following test class: - * {{{ - * class Foo { - * @Before def before(): Unit = { - * // Initialize the instance before the tests - * } - * @Test def bar(): Unit = { - * // assert some stuff - * } - * @Ignore("baz not implemented yet") @Test def baz(): Unit = { - * // assert some other stuff - * } - * } + * For each JUnit test `my.pkg.X`, it generates a bootstrapper module/object + * `my.pkg.X\$scalajs\$junit\$bootstrapper` implementing + * `org.scalajs.junit.Bootstrapper`. * - * object Foo { - * @BeforeClass def beforeClass(): Unit = { - * // Initialize some global state for the tests. - * } - * } - * }}} - * - * Will generate the following bootstrapper module: - * - * {{{ - * object Foo\$scalajs\$junit\$bootstrapper extends org.scalajs.junit.JUnitTestBootstrapper { - * - * def metadata(): JUnitClassMetadata = { - * new JUnitClassMetadata( - * classAnnotations = List(), - * moduleAnnotations = List(), - * classMethods = List( - * new JUnitMethodMetadata(name = "before", - * annotations = List(new Before)), - * new JUnitMethodMetadata(name = "bar", - * annotations = List(new Test)), - * new JUnitMethodMetadata(name = "baz", - * annotations = List(new Test, new Ignore("baz not implemented yet"))) - * ), - * moduleMethods( - * new JUnitMethodMetadata(name = "beforeClass", - * annotations = List(new BeforeClass))) - * ) - * } - * - * def newInstance(): AnyRef = new Foo() - * - * def invoke(methodName: String): Unit = { - * if (methodName == "0") Foo.beforeClass() - * else throw new NoSuchMethodException(methodId) - * } - * - * def invoke(instance: AnyRef, methodName: String): Unit = { - * if (methodName == "before") instance.asInstanceOf[Foo].before() - * else if (methodName == "bar") instance.asInstanceOf[Foo].bar() - * else if (methodName == "baz") instance.asInstanceOf[Foo].baz() - * else throw new NoSuchMethodException(methodId) - * } - * } - * }}} - * The test framework will identify `Foo\$scalajs\$junit\$bootstrapper` as a test module - * because it extends `JUnitTestBootstrapper`. It will know which methods to run based - * on the info returned by Foo\$scalajs\$junit\$bootstrapper.metadata, - * it will create new test instances using `Foo\$scalajs\$junit\$bootstrapper.newInstance()` - * and it will invoke test methods using `invoke` on the bootstrapper. + * The test runner uses these objects to obtain test metadata and dispatch to + * relevant methods. */ class ScalaJSJUnitPlugin(val global: Global) extends NscPlugin { @@ -100,11 +38,12 @@ class ScalaJSJUnitPlugin(val global: Global) extends NscPlugin { val description: String = "Makes JUnit test classes invokable in Scala.js" object ScalaJSJUnitPluginComponent - extends plugins.PluginComponent with transform.Transform with Compat210Component { + extends plugins.PluginComponent with transform.Transform { val global: Global = ScalaJSJUnitPlugin.this.global import global._ - import definitions.ObjectClass + import definitions._ + import rootMirror.getRequiredClass val phaseName: String = "junit-inject" val runsAfter: List[String] = List("mixin") @@ -113,137 +52,97 @@ class ScalaJSJUnitPlugin(val global: Global) extends NscPlugin { protected def newTransformer(unit: CompilationUnit): Transformer = new ScalaJSJUnitPluginTransformer - class ScalaJSJUnitPluginTransformer extends Transformer { - - import rootMirror.getRequiredClass + private object JUnitAnnots { + val Test = getRequiredClass("org.junit.Test") + val Before = getRequiredClass("org.junit.Before") + val After = getRequiredClass("org.junit.After") + val BeforeClass = getRequiredClass("org.junit.BeforeClass") + val AfterClass = getRequiredClass("org.junit.AfterClass") + val Ignore = getRequiredClass("org.junit.Ignore") + } - private val TestClass = - getRequiredClass("org.junit.Test") + private object Names { + val beforeClass = newTermName("beforeClass") + val afterClass = newTermName("afterClass") + val before = newTermName("before") + val after = newTermName("after") + val tests = newTermName("tests") + val invokeTest = newTermName("invokeTest") + val newInstance = newTermName("newInstance") + + val instance = newTermName("instance") + val name = newTermName("name") + } - private val FixMethodOrderClass = - getRequiredClass("org.junit.FixMethodOrder") + private lazy val BootstrapperClass = + getRequiredClass("org.scalajs.junit.Bootstrapper") - private val annotationWhiteList = List( - TestClass, - getRequiredClass("org.junit.Before"), - getRequiredClass("org.junit.After"), - getRequiredClass("org.junit.BeforeClass"), - getRequiredClass("org.junit.AfterClass"), - getRequiredClass("org.junit.Ignore") - ) + private lazy val TestMetadataClass = + getRequiredClass("org.scalajs.junit.TestMetadata") - private val jUnitClassMetadataType = - getRequiredClass("org.scalajs.junit.JUnitClassMetadata").toType + private lazy val FutureClass = + getRequiredClass("scala.concurrent.Future") - private val jUnitTestMetadataType = - getRequiredClass("org.scalajs.junit.JUnitTestBootstrapper").toType + private lazy val FutureModule_successful = + getMemberMethod(FutureClass.companionModule, newTermName("successful")) - private def jUnitMethodMetadataTypeTree = - TypeTree(getRequiredClass("org.scalajs.junit.JUnitMethodMetadata").toType) + private lazy val SuccessModule_apply = + getMemberMethod(getRequiredClass("scala.util.Success").companionModule, nme.apply) + class ScalaJSJUnitPluginTransformer extends Transformer { override def transform(tree: Tree): Tree = tree match { case tree: PackageDef => - def isClassWithJUnitAnnotation(sym: Symbol): Boolean = sym match { - case _:ClassSymbol | _:ModuleSymbol => - val hasAnnotationInClass = sym.selfType.members.exists { - case mtdSym: MethodSymbol => hasAnnotation(mtdSym, TestClass) - case _ => false - } - if (hasAnnotationInClass) true - else sym.parentSymbols.headOption.fold(false)(isClassWithJUnitAnnotation) - - case _ => false + @tailrec + def hasTests(sym: Symbol): Boolean = { + sym.info.members.exists(m => m.isMethod && m.hasAnnotation(JUnitAnnots.Test)) || + sym.superClass.exists && hasTests(sym.superClass) } - val bootstrappers = tree.stats.groupBy { // Group the class with its module - case clDef: ClassDef => Some(clDef.name) - case _ => None - }.iterator.flatMap { - case (Some(_), xs) if xs.exists(x => isClassWithJUnitAnnotation(x.symbol)) => - def isModule(cDef: ClassDef): Boolean = - cDef.mods.hasFlag(Flags.MODULE) - def isTestClass(cDef: ClassDef): Boolean = { - !cDef.mods.hasFlag(Flags.MODULE) && - !cDef.mods.hasFlag(Flags.ABSTRACT) && - !cDef.mods.hasFlag(Flags.TRAIT) - } - // Get the class definition and do the transformation - xs.collectFirst { - case clDef: ClassDef if isTestClass(clDef) => - // Get the module definition - val modDefOption = xs collectFirst { - case clDef: ClassDef if isModule(clDef) => clDef - } - // Create a new module for the JUnit entry point. - mkBootstrapperClass(clDef, modDefOption) - } - - case (_, xs) => None + def isTest(sym: Symbol) = { + sym.isClass && + !sym.isModuleClass && + !sym.isAbstract && + !sym.isTrait && + hasTests(sym) } - val newStats = (tree.stats.map(transform).iterator ++ bootstrappers).toList + val bootstrappers = tree.stats.collect { + case clDef: ClassDef if isTest(clDef.symbol) => + genBootstrapper(clDef.symbol.asClass) + } - treeCopy.PackageDef(tree: Tree, tree.pid, newStats) + val newStats = tree.stats.map(transform) ++ bootstrappers + treeCopy.PackageDef(tree, tree.pid, newStats) - case _ => + case tree => super.transform(tree) } - def mkBootstrapperClass(clazz: ClassDef, modDefOption: Option[ClassDef]): ClassDef = { + def genBootstrapper(testClass: ClassSymbol): ClassDef = { // Create the module and its module class, and enter them in their owner's scope - val bootName = newTypeName(clazz.name.toString + "$scalajs$junit$bootstrapper") - val (moduleSym, bootSym) = clazz.symbol.owner.newModuleAndClassSymbol(bootName, clazz.pos, 0L) + val (moduleSym, bootSym) = testClass.owner.newModuleAndClassSymbol( + newTypeName(testClass.name.toString + "$scalajs$junit$bootstrapper"), + testClass.pos, 0L) val bootInfo = - ClassInfoType(List(definitions.ObjectTpe, jUnitTestMetadataType), newScope, bootSym) + ClassInfoType(List(ObjectTpe, BootstrapperClass.toType), newScope, bootSym) bootSym.setInfo(bootInfo) moduleSym.setInfoAndEnter(bootSym.toTypeConstructor) bootSym.owner.info.decls.enter(bootSym) - bootSym.sourceModule.info - - // Generate the Trees of the members - val constructorDef = genConstructor(bootSym) - val getJUnitMetadataDef = mkGetJUnitMetadataDef(clazz.symbol, - modDefOption.map(_.symbol)) - val newInstanceDef = genNewInstanceDef(clazz.symbol, bootSym) - val invokeJUnitMethodDef = { - val annotatedMethods = modDefOption.fold(List.empty[MethodSymbol]) { mod => - jUnitAnnotatedMethods(mod.symbol.asClass) - } - mkInvokeJUnitMethodOnModuleDef(annotatedMethods, bootSym, - modDefOption.map(_.symbol)) - } - val invokeJUnitMethodOnInstanceDef = { - val annotatedMethods = jUnitAnnotatedMethods(clazz.symbol.asClass) - mkInvokeJUnitMethodOnInstanceDef(annotatedMethods, bootSym, - clazz.symbol) - } - // Enter the member symbols into the module class' scope - val decls = bootSym.info.decls - decls.enter(getJUnitMetadataDef.symbol) - decls.enter(newInstanceDef.symbol) - decls.enter(invokeJUnitMethodDef.symbol) - decls.enter(invokeJUnitMethodOnInstanceDef.symbol) - - // Build the ClassDef - val bootBody = { - List(constructorDef, getJUnitMetadataDef, newInstanceDef, - invokeJUnitMethodDef, invokeJUnitMethodOnInstanceDef) - } - val bootParents = List( - TypeTree(definitions.ObjectTpe), - TypeTree(jUnitTestMetadataType) + val testMethods = annotatedMethods(testClass, JUnitAnnots.Test) + + val defs = List( + genConstructor(bootSym), + genCallOnModule(bootSym, Names.beforeClass, testClass.companionModule, JUnitAnnots.BeforeClass), + genCallOnModule(bootSym, Names.afterClass, testClass.companionModule, JUnitAnnots.AfterClass), + genCallOnParam(bootSym, Names.before, testClass, JUnitAnnots.Before), + genCallOnParam(bootSym, Names.after, testClass, JUnitAnnots.After), + genTests(bootSym, testMethods), + genInvokeTest(bootSym, testClass, testMethods), + genNewInstance(bootSym, testClass) ) - val bootImpl = - treeCopy.Template(clazz.impl, bootParents, clazz.impl.self, bootBody) - - val bootClazz = gen.mkClassDef(Modifiers(Flags.MODULE), - bootName, Nil, bootImpl) - bootClazz.setSymbol(bootSym) - - currentRun.symSource(bootSym) = clazz.symbol.sourceFile - bootClazz + ClassDef(bootSym, defs) } private def genConstructor(owner: ClassSymbol): DefDef = { @@ -258,244 +157,106 @@ class ScalaJSJUnitPlugin(val global: Global) extends NscPlugin { typer.typedDefDef(newDefDef(sym, rhs)()) } - def jUnitAnnotatedMethods(sym: Symbol): List[MethodSymbol] = { - sym.selfType.members.collect { - case m: MethodSymbol if hasJUnitMethodAnnotation(m) => m - }.toList - } - - /** This method generates a method that invokes a test method in the module - * given its name. These methods have no parameters. - * - * Example: - * {{{ - * object Foo { - * @BeforeClass def bar(): Unit - * @AfterClass def baz(): Unit - * } - * object Foo\$scalajs\$junit\$bootstrapper { - * // This is the method generated by mkInvokeJUnitMethodOnModuleDef - * def invoke(methodName: String): Unit = { - * if (methodName == "bar") Foo.bar() - * else if (methodName == "baz") Foo.baz() - * else throw new NoSuchMethodException(methodName + " not found") - * } - * } - * }}} - */ - def mkInvokeJUnitMethodOnModuleDef(methods: List[MethodSymbol], - bootSym: Symbol, modClassSym: Option[Symbol]): DefDef = { - val invokeJUnitMethodSym = bootSym.newMethod(newTermName("invoke")) - - val paramSyms = { - val params = List(("methodName", definitions.StringTpe)) - mkParamSymbols(invokeJUnitMethodSym, params) - } + private def genCallOnModule(owner: ClassSymbol, name: TermName, module: Symbol, annot: Symbol): DefDef = { + val sym = owner.newMethodSymbol(name) + sym.setInfoAndEnter(MethodType(Nil, definitions.UnitTpe)) - invokeJUnitMethodSym.setInfo(MethodType(paramSyms, definitions.UnitTpe)) - - def callLocally(methodSymbol: Symbol): Tree = { - val methodSymbolLocal = { - modClassSym.fold(methodSymbol) { sym => - methodSymbol.cloneSymbol(newOwner = sym) - } - } - gen.mkMethodCall(methodSymbolLocal, Nil) - } + val calls = annotatedMethods(module, annot) + .map(gen.mkMethodCall(Ident(module), _, Nil, Nil)) + .toList - val invokeJUnitMethodRhs = mkMethodResolutionAndCall(invokeJUnitMethodSym, - methods, paramSyms.head, callLocally) - - mkMethod(invokeJUnitMethodSym, invokeJUnitMethodRhs, paramSyms) + typer.typedDefDef(newDefDef(sym, Block(calls: _*))()) } - /** This method generates a method that invokes a test method in the class - * given its name. These methods have no parameters. - * - * Example: - * {{{ - * class Foo { - * @Test def bar(): Unit - * @Test def baz(): Unit - * } - * object Foo\$scalajs\$junit\$bootstrapper { - * // This is the method generated by mkInvokeJUnitMethodOnInstanceDef - * def invoke(instance: AnyRef, methodName: String): Unit = { - * if (methodName == "bar") instance.asInstanceOf[Foo].bar() - * else if (methodName == "baz") instance.asInstanceOf[Foo].baz() - * else throw new NoSuchMethodException(methodName + " not found") - * } - * } - * }}} - */ - def mkInvokeJUnitMethodOnInstanceDef(methods: List[MethodSymbol], - classSym: Symbol, refClassSym: Symbol): DefDef = { - val invokeJUnitMethodSym = classSym.newMethod(newTermName("invoke")) - - val paramSyms = { - val params = List(("instance", definitions.ObjectTpe), - ("methodName", definitions.StringTpe)) - mkParamSymbols(invokeJUnitMethodSym, params) - } - - val instanceParamSym :: idParamSym :: Nil = paramSyms + private def genCallOnParam(owner: ClassSymbol, name: TermName, testClass: Symbol, annot: Symbol): DefDef = { + val sym = owner.newMethodSymbol(name) - invokeJUnitMethodSym.setInfo(MethodType(paramSyms, definitions.UnitTpe)) + val instanceParam = sym.newValueParameter(Names.instance).setInfo(ObjectTpe) - def callLocally(methodSymbol: Symbol): Tree = { - val instance = gen.mkAttributedIdent(instanceParamSym) - val castedInstance = gen.mkAttributedCast(instance, refClassSym.tpe) - gen.mkMethodCall(castedInstance, methodSymbol, Nil, Nil) - } + sym.setInfoAndEnter(MethodType(List(instanceParam), definitions.UnitTpe)) - val invokeJUnitMethodRhs = mkMethodResolutionAndCall(invokeJUnitMethodSym, - methods, idParamSym, callLocally) + val instance = castParam(instanceParam, testClass) + val calls = annotatedMethods(testClass, annot) + .map(gen.mkMethodCall(instance, _, Nil, Nil)) + .toList - mkMethod(invokeJUnitMethodSym, invokeJUnitMethodRhs, paramSyms) + typer.typedDefDef(newDefDef(sym, Block(calls: _*))()) } - def mkGetJUnitMetadataDef(clSym: Symbol, - modSymOption: Option[Symbol]): DefDef = { - val methods = jUnitAnnotatedMethods(clSym) - val modMethods = modSymOption.map(jUnitAnnotatedMethods) - - def liftAnnotations(methodSymbol: Symbol): List[Tree] = { - val annotations = methodSymbol.annotations - - // Find and report unsupported JUnit annotations - annotations.foreach { - case ann if ann.atp.typeSymbol == TestClass && ann.original.isInstanceOf[Block] => - reporter.error(ann.pos, "@Test(timeout = ...) is not " + - "supported in Scala.js JUnit Framework") + private def genTests(owner: ClassSymbol, tests: Scope): DefDef = { + val sym = owner.newMethodSymbol(Names.tests) + sym.setInfoAndEnter(MethodType(Nil, + typeRef(NoType, ArrayClass, List(TestMetadataClass.tpe)))) - case ann if ann.atp.typeSymbol == FixMethodOrderClass => - reporter.error(ann.pos, "@FixMethodOrder(...) is not supported " + - "in Scala.js JUnit Framework") + val metadata = for (test <- tests) yield { + val reifiedAnnot = New( + JUnitAnnots.Test, test.getAnnotation(JUnitAnnots.Test).get.args: _*) - case _ => // all is well - } - - // Collect lifted representations of the JUnit annotations - annotations.collect { - case ann if annotationWhiteList.contains(ann.tpe.typeSymbol) => - val args = if (ann.args != null) ann.args else Nil - mkNewInstance(TypeTree(ann.tpe), args) - } - } + val name = Literal(Constant(test.name.toString)) + val ignored = Literal(Constant(test.hasAnnotation(JUnitAnnots.Ignore))) - def defaultMethodMetadata(tpe: TypeTree)(mtdSym: MethodSymbol): Tree = { - val annotations = liftAnnotations(mtdSym) - mkNewInstance(tpe, List( - Literal(Constant(mtdSym.name.toString)), - mkList(annotations))) + New(TestMetadataClass, name, ignored, reifiedAnnot) } - def mkList(elems: List[Tree]): Tree = { - val varargsModule = - if (hasNewCollections) definitions.ScalaRunTimeModule - else definitions.PredefModule - - val array = ArrayValue(TypeTree(definitions.ObjectTpe), elems) - val wrappedArray = gen.mkMethodCall( - varargsModule, - definitions.wrapVarargsArrayMethodName(definitions.ObjectTpe), - Nil, List(array)) - val listApply = typer.typed { - gen.mkMethodCall(definitions.ListModule, nme.apply, Nil, List(wrappedArray)) - } + val rhs = ArrayValue(TypeTree(TestMetadataClass.tpe), metadata.toList) - if (listApply.tpe.typeSymbol.isSubClass(definitions.ListClass)) - listApply - else - gen.mkCast(listApply, definitions.ListClass.toTypeConstructor) - } - - def mkMethodList(tpe: TypeTree)(testMethods: List[MethodSymbol]): Tree = - mkList(testMethods.map(defaultMethodMetadata(tpe))) - - val getJUnitMethodRhs = { - mkNewInstance( - TypeTree(jUnitClassMetadataType), - List( - mkList(liftAnnotations(clSym)), - gen.mkNil, - mkMethodList(jUnitMethodMetadataTypeTree)(methods), - modMethods.fold(gen.mkNil)(mkMethodList(jUnitMethodMetadataTypeTree)) - )) - } - - val getJUnitMetadataSym = clSym.newMethod(newTermName("metadata")) - getJUnitMetadataSym.setInfo(MethodType(Nil, jUnitClassMetadataType)) - - typer.typedDefDef(newDefDef(getJUnitMetadataSym, getJUnitMethodRhs)()) + typer.typedDefDef(newDefDef(sym, rhs)()) } - private def hasJUnitMethodAnnotation(mtd: MethodSymbol): Boolean = - annotationWhiteList.exists(hasAnnotation(mtd, _)) + private def genInvokeTest(owner: ClassSymbol, testClass: Symbol, tests: Scope): DefDef = { + val sym = owner.newMethodSymbol(Names.invokeTest) - private def hasAnnotation(mtd: MethodSymbol, tpe: TypeSymbol): Boolean = - mtd.annotations.exists(_.atp.typeSymbol == tpe) + val instanceParam = sym.newValueParameter(Names.instance).setInfo(ObjectTpe) + val nameParam = sym.newValueParameter(Names.name).setInfo(StringTpe) - private def mkNewInstance[T: TypeTag](params: List[Tree]): Apply = - mkNewInstance(TypeTree(typeOf[T]), params) + sym.setInfo(MethodType(List(instanceParam, nameParam), FutureClass.toTypeConstructor)) - private def mkNewInstance(tpe: TypeTree, params: List[Tree]): Apply = - Apply(Select(New(tpe), nme.CONSTRUCTOR), params) + val instance = castParam(instanceParam, testClass) + val rhs = tests.foldRight[Tree] { + Throw(New(typeOf[NoSuchMethodException], Ident(nameParam))) + } { (sym, next) => + val cond = gen.mkMethodCall(Ident(nameParam), Object_equals, Nil, + List(Literal(Constant(sym.name.toString)))) - /* Generate a method that creates a new instance of the test class, this - * method will be located in the bootstrapper class. - */ - private def genNewInstanceDef(classSym: Symbol, bootSymbol: Symbol): DefDef = { - val mkNewInstanceDefRhs = - mkNewInstance(TypeTree(classSym.typeConstructor), Nil) - val mkNewInstanceDefSym = bootSymbol.newMethodSymbol(newTermName("newInstance")) - mkNewInstanceDefSym.setInfo(MethodType(Nil, definitions.ObjectTpe)) + val call = genTestInvocation(sym, instance) - typer.typedDefDef(newDefDef(mkNewInstanceDefSym, mkNewInstanceDefRhs)()) - } - - private def mkParamSymbols(method: MethodSymbol, - params: List[(String, Type)]): List[Symbol] = { - params.map { - case (pName, tpe) => - val sym = method.newValueParameter(newTermName(pName)) - sym.setInfo(tpe) - sym + If(cond, call, next) } - } - private def mkMethod(methodSym: MethodSymbol, methodRhs: Tree, - paramSymbols: List[Symbol]): DefDef = { - val paramValDefs = List(paramSymbols.map(newValDef(_, EmptyTree)())) - typer.typedDefDef(newDefDef(methodSym, methodRhs)(vparamss = paramValDefs)) + typer.typedDefDef(newDefDef(sym, rhs)()) } - private def mkMethodResolutionAndCall(methodSym: MethodSymbol, - methods: List[Symbol], idParamSym: Symbol, genCall: Symbol => Tree): Tree = { - val tree = methods.foldRight[Tree](mkMethodNotFound(idParamSym)) { (methodSymbol, acc) => - val mName = Literal(Constant(methodSymbol.name.toString)) - val paramIdent = gen.mkAttributedIdent(idParamSym) - val cond = gen.mkMethodCall(paramIdent, definitions.Object_equals, Nil, List(mName)) - val call = genCall(methodSymbol) - If(cond, call, acc) + private def genTestInvocation(sym: Symbol, instance: Tree): Tree = { + sym.tpe.resultType.typeSymbol match { + case UnitClass => + val boxedUnit = gen.mkAttributedRef(definitions.BoxedUnit_UNIT) + val newSuccess = gen.mkMethodCall(SuccessModule_apply, List(boxedUnit)) + Block( + gen.mkMethodCall(instance, sym, Nil, Nil), + gen.mkMethodCall(FutureModule_successful, List(newSuccess)) + ) + + case FutureClass => + gen.mkMethodCall(instance, sym, Nil, Nil) + + case _ => + // We lie in the error message to not expose that we support async testing. + reporter.error(sym.pos, "JUnit test must have Unit return type") + EmptyTree } - atOwner(methodSym)(typer.typed(tree)) } - private def mkMethodNotFound(paramSym: Symbol) = { - val paramIdent = gen.mkAttributedIdent(paramSym) - val msg = gen.mkMethodCall(paramIdent, definitions.String_+, Nil, - List(Literal(Constant(" not found")))) - val exception = mkNewInstance[NoSuchMethodException](List(msg)) - Throw(exception) + private def genNewInstance(owner: ClassSymbol, testClass: ClassSymbol): DefDef = { + val sym = owner.newMethodSymbol(Names.newInstance) + sym.setInfoAndEnter(MethodType(Nil, ObjectTpe)) + typer.typedDefDef(newDefDef(sym, New(testClass))()) } - } - private lazy val hasNewCollections = { - val v = scala.util.Properties.versionNumberString - !v.startsWith("2.10.") && - !v.startsWith("2.11.") && - !v.startsWith("2.12.") + private def castParam(param: Symbol, clazz: Symbol): Tree = + gen.mkAsInstanceOf(Ident(param), clazz.tpe, any = false) + + private def annotatedMethods(owner: Symbol, annot: Symbol): Scope = + owner.info.members.filter(m => m.isMethod && m.hasAnnotation(annot)) } } } diff --git a/junit-runtime/src/main/scala/com/novocode/junit/Ansi.scala b/junit-runtime/src/main/scala/com/novocode/junit/Ansi.scala deleted file mode 100644 index c64973659f..0000000000 --- a/junit-runtime/src/main/scala/com/novocode/junit/Ansi.scala +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package com.novocode.junit - -object Ansi { - - private[this] final val NORMAL = "\u001B[0m" - - def c(s: String, colorSequence: String): String = - if (colorSequence == null) s - else colorSequence + s + NORMAL - - def filterAnsi(s: String): String = { - if (s == null) { - null - } else { - var r: String = "" - val len = s.length - var i = 0 - while (i < len) { - val c = s.charAt(i) - if (c == '\u001B') { - i += 1 - while (i < len && s.charAt(i) != 'm') - i += 1 - } else { - r += c - } - i += 1 - } - r - } - } - - final val INFO = "\u001B[34m" // BLUE - final val ERRCOUNT = "\u001B[31m" // RED - final val IGNCOUNT = "\u001B[33m" // YELLOW - final val ERRMSG = "\u001B[31m" // RED - final val NNAME1 = "\u001B[33m" // YELLOW - final val NNAME2 = "\u001B[36m" // CYAN - final val NNAME3 = "\u001B[33m" // YELLOW - final val ENAME1 = "\u001B[33m" // YELLOW - final val ENAME2 = "\u001B[31m" // RED - final val ENAME3 = "\u001B[33m" // YELLOW - final val TESTFILE1 = "\u001B[35m" // MAGENTA - final val TESTFILE2 = "\u001B[33m" // YELLOW -} diff --git a/junit-runtime/src/main/scala/com/novocode/junit/JUnitFramework.scala b/junit-runtime/src/main/scala/com/novocode/junit/JUnitFramework.scala index 2b110922bc..002f31251b 100644 --- a/junit-runtime/src/main/scala/com/novocode/junit/JUnitFramework.scala +++ b/junit-runtime/src/main/scala/com/novocode/junit/JUnitFramework.scala @@ -12,94 +12,27 @@ package com.novocode.junit -import org.scalajs.junit.{JUnitMasterRunner, JUnitSlaveRunner} import sbt.testing._ +/** Forwarder framework so no additional framework name is needed in sbt. + * + * Note that a type alias is not enough, since sbt looks at the runtime type. + */ final class JUnitFramework extends Framework { + private val f = new org.scalajs.junit.JUnitFramework - val name: String = "Scala.js JUnit test framework" + val name: String = f.name - private object JUnitFingerprint extends AnnotatedFingerprint { - override def annotationName(): String = "org.junit.Test" - - override def isModule(): Boolean = false - } - - def fingerprints(): Array[Fingerprint] = { - Array(JUnitFingerprint) - } + def fingerprints(): Array[Fingerprint] = f.fingerprints() def runner(args: Array[String], remoteArgs: Array[String], - testClassLoader: ClassLoader): JUnitMasterRunner = { - new JUnitMasterRunner(args, remoteArgs, testClassLoader, - parseRunSettings(args)) + testClassLoader: ClassLoader): Runner = { + f.runner(args, remoteArgs, testClassLoader) } + // Aka `workerRunner`; see the Scaladoc of `sbt.testing.Framework` about the name. def slaveRunner(args: Array[String], remoteArgs: Array[String], - testClassLoader: ClassLoader, send: String => Unit): JUnitSlaveRunner = { - new JUnitSlaveRunner(args, remoteArgs, testClassLoader, send, - parseRunSettings(args)) - } - - def arrayString(arr: Array[String]): String = arr.mkString("Array(", ", ", ")") - - def parseRunSettings(args: Array[String]): RunSettings = { - var quiet = false - var verbose = false - var noColor = false - var decodeScalaNames = false - var logAssert = false - var notLogExceptionClass = false - var ignoreRunners = "org.junit.runners.Suite" - var runListener: String = null - for (str <- args) { - str match { - case "-q" => quiet = true - case "-v" => verbose = true - case "-n" => noColor = true - case "-s" => decodeScalaNames = true - case "-a" => logAssert = true - case "-c" => notLogExceptionClass = true - - case s if s.startsWith("-tests=") => - throw new UnsupportedOperationException("-tests") - - case s if s.startsWith("--tests=") => - throw new UnsupportedOperationException("--tests") - - case s if s.startsWith("--ignore-runners=") => - ignoreRunners = s.substring(17) - - case s if s.startsWith("--run-listener=") => - runListener = s.substring(15) - - case s if s.startsWith("--include-categories=") => - throw new UnsupportedOperationException("--include-categories") - - case s if s.startsWith("--exclude-categories=") => - throw new UnsupportedOperationException("--exclude-categories") - - case s if s.startsWith("-D") && s.contains("=") => - throw new UnsupportedOperationException("-Dkey=value") - - case s if !s.startsWith("-") && !s.startsWith("+") => - throw new UnsupportedOperationException(s) - - case _ => - } - } - for (s <- args) { - s match { - case "+q" => quiet = false - case "+v" => verbose = false - case "+n" => noColor = false - case "+s" => decodeScalaNames = false - case "+a" => logAssert = false - case "+c" => notLogExceptionClass = false - case _ => - } - } - new RunSettings(!noColor, decodeScalaNames, quiet, verbose, logAssert, - ignoreRunners, notLogExceptionClass) + testClassLoader: ClassLoader, send: String => Unit): Runner = { + f.slaveRunner(args, remoteArgs, testClassLoader, send) } } diff --git a/junit-runtime/src/main/scala/com/novocode/junit/RichLogger.scala b/junit-runtime/src/main/scala/com/novocode/junit/RichLogger.scala deleted file mode 100644 index b6cec79069..0000000000 --- a/junit-runtime/src/main/scala/com/novocode/junit/RichLogger.scala +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package com.novocode.junit - -import sbt.testing._ - -import scala.collection.mutable - -import Ansi._ - -final class RichLogger private (loggers: Array[Logger], settings: RunSettings) { - - private[this] var currentTestClassName: List[String] = Nil - - def this(loggers: Array[Logger], settings: RunSettings, - testClassName: String) = { - this(loggers, settings) - currentTestClassName ::= testClassName - } - - def pushCurrentTestClassName(s: String): Unit = - currentTestClassName ::= s - - def popCurrentTestClassName(): Unit = { - if (!currentTestClassName.isEmpty && !currentTestClassName.tail.isEmpty) - currentTestClassName = currentTestClassName.tail - } - - def debug(s: String): Unit = { - for (l <- loggers) - l.debug(filterAnsiIfNeeded(l, s)) - } - - def error(s: String): Unit = { - for (l <- loggers) - l.error(filterAnsiIfNeeded(l, s)) - } - - def error(s: String, t: Throwable): Unit = { - error(s) - if (t != null && (settings.logAssert || !t.isInstanceOf[AssertionError])) - logStackTrace(t) - } - - def info(s: String): Unit = { - for (l <- loggers) - l.info(filterAnsiIfNeeded(l, s)) - } - - def warn(s: String): Unit = { - for (l <- loggers) - l.warn(filterAnsiIfNeeded(l, s)) - } - - private def filterAnsiIfNeeded(l: Logger, s: String): String = - if (l.ansiCodesSupported() && settings.color) s - else filterAnsi(s) - - private def logStackTrace(t: Throwable): Unit = { - val trace = t.getStackTrace.dropWhile { p => - p.getFileName != null && { - p.getFileName.contains("StackTrace.scala") || - p.getFileName.contains("Throwables.scala") - } - } - val testClassName = currentTestClassName.head - val testFileName = { - if (settings.color) findTestFileName(trace, testClassName) - else null - } - val i = trace.indexWhere { - p => p.getFileName != null && p.getFileName.contains("JUnitExecuteTest.scala") - } - 1 - val m = if (i > 0) i else trace.length - 1 - logStackTracePart(trace, m, trace.length - m - 1, t, testClassName, testFileName) - } - - private def logStackTracePart(trace: Array[StackTraceElement], m: Int, - framesInCommon: Int, t: Throwable, testClassName: String, - testFileName: String): Unit = { - val m0 = m - var m2 = m - var top = 0 - var i = top - while (i <= m2) { - if (trace(i).toString.startsWith("org.junit.") || - trace(i).toString.startsWith("org.hamcrest.")) { - if (i == top) { - top += 1 - } else { - m2 = i - 1 - var break = false - while (m2 > top && !break) { - val s = trace(m2).toString - if (!s.startsWith("java.lang.reflect.") && - !s.startsWith("sun.reflect.")) { - break = true - } else { - m2 -= 1 - } - } - i = m2 // break - } - } - i += 1 - } - - for (i <- top to m2) { - error(" at " + - stackTraceElementToString(trace(i), testClassName, testFileName)) - } - if (m0 != m2) { - // skip junit-related frames - error(" ...") - } else if (framesInCommon != 0) { - // skip frames that were in the previous trace too - error(" ... " + framesInCommon + " more") - } - logStackTraceAsCause(trace, t.getCause, testClassName, testFileName) - } - - private def logStackTraceAsCause(causedTrace: Array[StackTraceElement], - t: Throwable, testClassName: String, testFileName: String): Unit = { - if (t != null) { - val trace = t.getStackTrace - var m = trace.length - 1 - var n = causedTrace.length - 1 - while (m >= 0 && n >= 0 && trace(m) == causedTrace(n)) { - m -= 1 - n -= 1 - } - error("Caused by: " + t) - logStackTracePart(trace, m, trace.length - 1 - m, t, testClassName, testFileName) - } - } - - private def findTestFileName(trace: Array[StackTraceElement], testClassName: String): String = { - trace.collectFirst { - case e if testClassName.equals(e.getClassName) => e.getFileName - }.orNull - } - - private def stackTraceElementToString(e: StackTraceElement, - testClassName: String, testFileName: String): String = { - val highlight = settings.color && { - testClassName == e.getClassName || - (testFileName != null && testFileName == e.getFileName) - } - var r = "" - r += settings.decodeName(e.getClassName + '.' + e.getMethodName) - r += '(' - - if (e.isNativeMethod) { - r += c("Native Method", if (highlight) TESTFILE2 else null) - } else if (e.getFileName == null) { - r += c("Unknown Source", if (highlight) TESTFILE2 else null) - } else { - r += c(e.getFileName, if (highlight) TESTFILE1 else null) - if (e.getLineNumber >= 0) { - r += ':' - r += c(String.valueOf(e.getLineNumber), if (highlight) TESTFILE2 else null) - } - } - r += ')' - r - } -} diff --git a/junit-runtime/src/main/scala/com/novocode/junit/RunSettings.scala b/junit-runtime/src/main/scala/com/novocode/junit/RunSettings.scala deleted file mode 100644 index 2b6cb6f796..0000000000 --- a/junit-runtime/src/main/scala/com/novocode/junit/RunSettings.scala +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package com.novocode.junit - -import com.novocode.junit.Ansi._ - -import java.util.HashSet - -import scala.util.Try - -class RunSettings private (val color: Boolean, val decodeScalaNames: Boolean, - val quiet: Boolean, val verbose: Boolean, val logAssert: Boolean, - val notLogExceptionClass: Boolean) { - - private val ignoreRunnersSet = new HashSet[String] - - def this(color: Boolean, decodeScalaNames: Boolean, quiet: Boolean, - verbose: Boolean, logAssert: Boolean, ignoreRunners: String, - notLogExceptionClass: Boolean) = { - this(color, decodeScalaNames, quiet, verbose, logAssert, notLogExceptionClass) - for (s <- ignoreRunners.split(",")) - ignoreRunnersSet.add(s.trim) - } - - def decodeName(name: String): String = - if (decodeScalaNames) RunSettings.decodeScalaName(name) else name - - def buildColoredMessage(t: Throwable, c1: String): String = { - if (t == null) "null" else { - if (notLogExceptionClass || (!logAssert && t.isInstanceOf[AssertionError])) { - t.getMessage - } else { - val b = new StringBuilder() - val cn = decodeName(t.getClass.getName) - val pos1 = cn.indexOf('$') - val pos2 = { - if (pos1 == -1) cn.lastIndexOf('.') - else cn.lastIndexOf('.', pos1) - } - if (pos2 == -1) b.append(c(cn, c1)) - else { - b.append(cn.substring(0, pos2)) - b.append('.') - b.append(c(cn.substring(pos2 + 1), c1)) - } - b.append(": ").append(t.getMessage) - b.toString() - } - } - } - - def buildInfoMessage(t: Throwable): String = - buildColoredMessage(t, NNAME2) - - def buildErrorMessage(t: Throwable): String = - buildColoredMessage(t, ENAME2) -} - -object RunSettings { - private[RunSettings] def decodeScalaName(name: String): String = - Try(scala.reflect.NameTransformer.decode(name)).getOrElse(name) -} diff --git a/junit-runtime/src/main/scala/org/junit/Assert.scala b/junit-runtime/src/main/scala/org/junit/Assert.scala index d3c321b303..a52574dcdb 100644 --- a/junit-runtime/src/main/scala/org/junit/Assert.scala +++ b/junit-runtime/src/main/scala/org/junit/Assert.scala @@ -3,6 +3,9 @@ */ package org.junit +import java.util.Objects + +import org.junit.function.ThrowingRunnable import org.junit.internal.InexactComparisonCriteria import org.junit.internal.ExactComparisonCriteria import org.hamcrest.Matcher @@ -38,7 +41,7 @@ object Assert { @noinline def assertEquals(message: String, expected: Any, actual: Any): Unit = { - if (!equalsRegardingNull(expected, actual)) { + if (!Objects.equals(expected, actual)) { (expected, actual) match { case (expectedString: String, actualString: String) => val cleanMsg: String = if (message == null) "" else message @@ -50,22 +53,13 @@ object Assert { } } - @inline - private def equalsRegardingNull(expected: Any, actual: Any): Boolean = - if (expected == null) actual == null - else isEquals(expected, actual) - - @inline - private def isEquals(expected: Any, actual: Any): Boolean = - expected.equals(actual) - @noinline def assertEquals(expected: Any, actual: Any): Unit = assertEquals(null, expected, actual) @noinline def assertNotEquals(message: String, unexpected: Any, actual: Any): Unit = { - if (equalsRegardingNull(unexpected, actual)) + if (Objects.equals(unexpected, actual)) failEquals(message, actual) } @@ -81,6 +75,18 @@ object Assert { fail(s"$checkedMessage. Actual: $actual") } + // Not part of the JVM API: make sure to keep Ints instead of Longs + @noinline + def assertNotEquals(message: String, unexpected: Int, actual: Int): Unit = { + if (unexpected == actual) + failEquals(message, actual) + } + + // Not part of the JVM API: make sure to keep Ints instead of Longs + @noinline + def assertNotEquals(unexpected: Int, actual: Int): Unit = + assertNotEquals(null, unexpected, actual) + @noinline def assertNotEquals(message: String, unexpected: Long, actual: Long): Unit = { if (unexpected == actual) @@ -122,6 +128,16 @@ object Assert { "floating-point numbers") } + // Not part of the JVM API: make sure to keep Ints instead of Longs + @noinline + def assertEquals(expected: Int, actual: Int): Unit = + assertEquals(null, expected, actual) + + // Not part of the JVM API: make sure to keep Ints instead of Longs + @noinline + def assertEquals(message: String, expected: Int, actual: Int): Unit = + assertEquals(message, expected: Any, actual: Any) + @noinline def assertEquals(expected: Long, actual: Long): Unit = assertEquals(null, expected, actual) @@ -348,6 +364,9 @@ object Assert { } } + private def formatClass(value: Class[_]): String = + value.getName() + private def formatClassAndValue(value: Any, valueString: String): String = { val className = if (value == null) "null" else value.getClass.getName s"$className<$valueString>" @@ -361,41 +380,36 @@ object Assert { def assertThat[T](reason: String, actual: T, matcher: Matcher[T]): Unit = MatcherAssert.assertThat(reason, actual, matcher) - // The following methods will be available on JUnit 4.13, a backport implementation - // is being tested in JUnitAssertionTest until 4.13 is released. - - /* @noinline - def assertThrows(expectedThrowable: Class[_ <: Throwable], - runnable: ThrowingRunnable): Unit = { - expectThrows(expectedThrowable, runnable) - } + def assertThrows[T <: Throwable](expectedThrowable: Class[T], runnable: ThrowingRunnable): T = + assertThrows(null, expectedThrowable, runnable) @noinline - def expectThrows[T <: Throwable](expectedThrowable: Class[T], runnable: ThrowingRunnable): T = { + def assertThrows[T <: Throwable](message: String, expectedThrowable: Class[T], + runnable: ThrowingRunnable): T = { + // scalastyle:off return + + def buildPrefix: String = + if (message != null && !message.isEmpty()) message + ": " else "" + try { runnable.run() - val message = - s"expected ${expectedThrowable.getSimpleName} to be thrown," + - " but nothing was thrown" - throw new AssertionError(message) } catch { + case actualThrown: Throwable if expectedThrowable.isInstance(actualThrown) => + return actualThrown.asInstanceOf[T] + case actualThrown: Throwable => - if (expectedThrowable.isInstance(actualThrown)) { - actualThrown.asInstanceOf[T] - } else { - val mismatchMessage = format("unexpected exception type thrown;", - expectedThrowable.getSimpleName, actualThrown.getClass.getSimpleName) - - val assertionError = new AssertionError(mismatchMessage) - assertionError.initCause(actualThrown) - throw assertionError - } + val expected = formatClass(expectedThrowable) + val actual = formatClass(actualThrown.getClass()) + throw new AssertionError( + buildPrefix + format("unexpected exception type thrown;", expected, actual), + actualThrown) } - } - trait ThrowingRunnable { - def run(): Unit + throw new AssertionError( + buildPrefix + + String.format("expected %s to be thrown, but nothing was thrown", formatClass(expectedThrowable))) + + // scalastyle:on return } - */ } diff --git a/junit-runtime/src/main/scala/org/junit/FixMethodOrder.scala b/junit-runtime/src/main/scala/org/junit/FixMethodOrder.scala deleted file mode 100644 index 4096184fa4..0000000000 --- a/junit-runtime/src/main/scala/org/junit/FixMethodOrder.scala +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Ported from https://github.com/junit-team/junit - */ -package org.junit - -import java.lang.annotation._ - -import org.junit.runners.MethodSorters - -class FixMethodOrder(val value: MethodSorters) - extends Annotation { - - def this() = this(MethodSorters.DEFAULT) - - def annotationType(): Class[_ <: Annotation] = classOf[FixMethodOrder] -} diff --git a/junit-runtime/src/main/scala/org/junit/TestCouldNotBeSkippedException.scala b/junit-runtime/src/main/scala/org/junit/TestCouldNotBeSkippedException.scala new file mode 100644 index 0000000000..3b9981b54d --- /dev/null +++ b/junit-runtime/src/main/scala/org/junit/TestCouldNotBeSkippedException.scala @@ -0,0 +1,7 @@ +/* + * Ported from https://github.com/junit-team/junit + */ +package org.junit + +class TestCouldNotBeSkippedException(cause: internal.AssumptionViolatedException) + extends RuntimeException("Test could not be skipped due to other failures", cause) diff --git a/junit-runtime/src/main/scala/org/junit/function/ThrowingRunnable.scala b/junit-runtime/src/main/scala/org/junit/function/ThrowingRunnable.scala new file mode 100644 index 0000000000..2c09d4dd72 --- /dev/null +++ b/junit-runtime/src/main/scala/org/junit/function/ThrowingRunnable.scala @@ -0,0 +1,8 @@ +/* + * Ported from https://github.com/junit-team/junit + */ +package org.junit.function + +trait ThrowingRunnable { + def run(): Unit +} diff --git a/junit-runtime/src/main/scala/org/junit/runners/MethodSorters.scala b/junit-runtime/src/main/scala/org/junit/runners/MethodSorters.scala deleted file mode 100644 index 6b96a4caca..0000000000 --- a/junit-runtime/src/main/scala/org/junit/runners/MethodSorters.scala +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Ported from https://github.com/junit-team/junit - */ -package org.junit.runners - -object MethodSorters { - - private lazy val _NAME_ASCENDING = new MethodSorters((x, y) => x.compareTo(y)) - private lazy val _JVM = new MethodSorters((x, y) => 0) - private lazy val _DEFAULT = _NAME_ASCENDING - - def NAME_ASCENDING: MethodSorters = _NAME_ASCENDING - - def JVM: MethodSorters = _JVM - - def DEFAULT: MethodSorters = _DEFAULT -} - -class MethodSorters private (f: (String, String) => Int) { - lazy val comparator: Ordering[String] = { - new Ordering[String] { - def compare(x: String, y: String): Int = f(x, y) - } - } -} diff --git a/junit-runtime/src/main/scala/org/scalajs/junit/Ansi.scala b/junit-runtime/src/main/scala/org/scalajs/junit/Ansi.scala new file mode 100644 index 0000000000..40747c55ed --- /dev/null +++ b/junit-runtime/src/main/scala/org/scalajs/junit/Ansi.scala @@ -0,0 +1,50 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.junit + +private[junit] object Ansi { + + private[this] final val NORMAL = "\u001B[0m" + + def c(s: String, colorSequence: String): String = + if (colorSequence == null) s + else colorSequence + s + NORMAL + + def filterAnsi(s: String): String = { + if (s == null) { + null + } else { + var r: String = "" + val len = s.length + var i = 0 + while (i < len) { + val c = s.charAt(i) + if (c == '\u001B') { + i += 1 + while (i < len && s.charAt(i) != 'm') + i += 1 + } else { + r += c + } + i += 1 + } + r + } + } + + final val RED = "\u001B[31m" + final val YELLOW = "\u001B[33m" + final val BLUE = "\u001B[34m" + final val MAGENTA = "\u001B[35m" + final val CYAN = "\u001B[36m" +} diff --git a/junit-runtime/src/main/scala/org/scalajs/junit/Bootstrapper.scala b/junit-runtime/src/main/scala/org/scalajs/junit/Bootstrapper.scala new file mode 100644 index 0000000000..e965c0ed3a --- /dev/null +++ b/junit-runtime/src/main/scala/org/scalajs/junit/Bootstrapper.scala @@ -0,0 +1,51 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.junit + +import scala.concurrent.Future +import scala.util.Try + +import scala.scalajs.reflect.annotation._ + +/** Scala.js internal JUnit bootstrapper. + * + * This class is public due to implementation details. Only the junit compiler + * plugin may generate classes inheriting from it. + * + * Relying on this trait directly is unspecified behavior. + */ +@EnableReflectiveInstantiation +trait Bootstrapper { + def beforeClass(): Unit + def afterClass(): Unit + def before(instance: AnyRef): Unit + def after(instance: AnyRef): Unit + + def tests(): Array[TestMetadata] + def invokeTest(instance: AnyRef, name: String): Future[Try[Unit]] + + def newInstance(): AnyRef +} + +/** Scala.js internal JUnit test metadata + * + * This class is public due to implementation details. Only the junit compiler + * plugin may create instances of it. + * + * Relying on this class directly is unspecified behavior. + */ +final class TestMetadata( + val name: String, + val ignored: Boolean, + val annotation: org.junit.Test +) diff --git a/junit-runtime/src/main/scala/org/scalajs/junit/JUnitBaseRunner.scala b/junit-runtime/src/main/scala/org/scalajs/junit/JUnitBaseRunner.scala deleted file mode 100644 index 5d47de28c6..0000000000 --- a/junit-runtime/src/main/scala/org/scalajs/junit/JUnitBaseRunner.scala +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.junit - -import com.novocode.junit.RunSettings -import sbt.testing._ - -abstract class JUnitBaseRunner( - val args: Array[String], - val remoteArgs: Array[String], - private[junit] val testClassLoader: ClassLoader, - private[junit] val runSettings: RunSettings) extends Runner { - - protected def newTask(taskDef: TaskDef): Task = - new JUnitTask(taskDef, this) - - protected var doneCount = 0 - protected var passedCount = 0 - protected var failedCount = 0 - protected var ignoredCount = 0 - protected var skippedCount = 0 - protected var totalCount = 0 - - private[junit] def taskDoneCount: Int = doneCount - private[junit] def testPassedCount: Int = passedCount - private[junit] def testFailedCount: Int = failedCount - private[junit] def testIgnoredCount: Int = ignoredCount - private[junit] def testSkippedCount: Int = skippedCount - private[junit] def testTotalCount: Int = totalCount - - private[junit] def taskDone(): Unit = doneCount += 1 - private[junit] def testPassed(): Unit = passedCount += 1 - private[junit] def testFailed(): Unit = failedCount += 1 - private[junit] def testIgnored(): Unit = ignoredCount += 1 - private[junit] def testSkipped(): Unit = skippedCount += 1 - private[junit] def testRegisterTotal(count: Int = 1): Unit = totalCount += count - - def serializeTask(task: Task, serializer: TaskDef => String): String = - serializer(task.taskDef) - - def deserializeTask(task: String, deserializer: String => TaskDef): Task = - newTask(deserializer(task)) - - def resetTestCounts(): Unit = { - passedCount = 0 - failedCount = 0 - ignoredCount = 0 - skippedCount = 0 - totalCount = 0 - } -} - -object JUnitBaseRunner { - object Done { - def deserialize(str: String): Done = { - val split = str.split(':') - if (split.length != 6) { - throw new IllegalArgumentException(str) - } else { - Done(split(0).toInt, split(1).toInt, split(2).toInt, split(3).toInt, - split(4).toInt, split(5).toInt) - } - } - } - - case class Done(done: Int, passed: Int, failed: Int, ignored: Int, - skipped: Int, total: Int) { - def serialize(): String = - Seq(done, passed, failed, ignored, skipped, total).mkString(":") - } -} diff --git a/junit-runtime/src/main/scala/org/scalajs/junit/JUnitEvent.scala b/junit-runtime/src/main/scala/org/scalajs/junit/JUnitEvent.scala index d221c2b586..e07d7ab13b 100644 --- a/junit-runtime/src/main/scala/org/scalajs/junit/JUnitEvent.scala +++ b/junit-runtime/src/main/scala/org/scalajs/junit/JUnitEvent.scala @@ -14,9 +14,13 @@ package org.scalajs.junit import sbt.testing._ -final class JUnitEvent(taskDef: TaskDef, val status: Status, val selector: Selector, +private[junit] final class JUnitEvent( + taskDef: TaskDef, + val status: Status, + val selector: Selector, val throwable: OptionalThrowable = new OptionalThrowable, - val duration: Long = -1L) extends Event { - def fullyQualifiedName: String = taskDef.fullyQualifiedName - def fingerprint: Fingerprint = taskDef.fingerprint + val duration: Long = -1L +) extends Event { + def fullyQualifiedName(): String = taskDef.fullyQualifiedName() + def fingerprint(): Fingerprint = taskDef.fingerprint() } diff --git a/junit-runtime/src/main/scala/org/scalajs/junit/JUnitExecuteTest.scala b/junit-runtime/src/main/scala/org/scalajs/junit/JUnitExecuteTest.scala deleted file mode 100644 index 59fd68f086..0000000000 --- a/junit-runtime/src/main/scala/org/scalajs/junit/JUnitExecuteTest.scala +++ /dev/null @@ -1,294 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.junit - -import java.io.ByteArrayOutputStream - -import com.novocode.junit.Ansi._ -import com.novocode.junit.RichLogger -import org.junit._ -import sbt.testing._ - -import scala.util.matching.Regex - -final class JUnitExecuteTest(taskDef: TaskDef, runner: JUnitBaseRunner, - classMetadata: JUnitTestBootstrapper, richLogger: RichLogger, - eventHandler: EventHandler) { - - private val verbose = runner.runSettings.verbose - private val decodeScalaNames = runner.runSettings.decodeScalaNames - - lazy val packageName = fullyQualifiedName.split('.').init.mkString(".") - lazy val className = fullyQualifiedName.split('.').last - - def fullyQualifiedName: String = taskDef.fullyQualifiedName() - - def executeTests(): Unit = { - val jUnitMetadata = classMetadata.metadata() - - val assumptionViolated = try { - for (method <- jUnitMetadata.beforeClassMethod) - classMetadata.invoke(method.name) - false - } catch { - case _: AssumptionViolatedException | _:internal.AssumptionViolatedException => - true - } - - def logTestIgnored(name: String): Unit = { - logFormattedInfo(name, "ignored") - } - - if (assumptionViolated) { - logTestIgnored(null) - ignoreTestClass() - } else { - def runWithOrWithoutQuietMode[T](block: => T): T = { - if (runner.runSettings.quiet) { - scala.Console.withOut(new ByteArrayOutputStream()) { - block - } - } else { - block - } - } - - runWithOrWithoutQuietMode { - for (method <- jUnitMetadata.testMethods) { - method.getIgnoreAnnotation match { - case Some(ign) => - logTestIgnored(method.name) - ignoreTest(method.name) - - case None => - executeTestMethod(classMetadata, method) - } - } - } - - for (method <- jUnitMetadata.afterClassMethod) - classMetadata.invoke(method.name) - } - } - - private[this] def executeTestMethod(classMetadata: JUnitTestBootstrapper, - method: JUnitMethodMetadata) = { - val jUnitMetadata = classMetadata.metadata() - val methodName = method.name - val decodedMethodName = { - if (decodeScalaNames) runner.runSettings.decodeName(methodName) - else methodName - } - val testAnnotation = method.getTestAnnotation.get - - if (verbose) - logFormattedInfo(decodedMethodName, "started") - else - logFormattedDebug(decodedMethodName, "started") - - val t0 = System.nanoTime - def getTimeInSeconds(): Double = (System.nanoTime - t0).toDouble / 1000000000 - - var eventAlreadyEmitted: Boolean = false - - def emitTestFailed(): Unit = { - if (eventAlreadyEmitted) { - // Only add to the failed test count, don't emit an event - runner.testFailed() - } else { - testFailed(methodName) - eventAlreadyEmitted = true - } - } - - def execute(expectedException: Class[_] = classOf[org.junit.Test.None])( - body: => Unit): Boolean = { - - try { - body - - if (expectedException == classOf[org.junit.Test.None]) { - true - } else { - val msg = { - s"failed: Expected exception: " + expectedException + - s"took ${getTimeInSeconds()} sec" - } - logFormattedError(decodedMethodName, msg, None) - emitTestFailed() - false - } - } catch { - case ex: Throwable => - val timeInSeconds = getTimeInSeconds() - if (ex.isInstanceOf[AssumptionViolatedException] || - ex.isInstanceOf[internal.AssumptionViolatedException]) { - logAssertionWarning(decodedMethodName, ex, timeInSeconds) - testSkipped() - false - } else if (expectedException.isInstance(ex)) { - true - } else if (expectedException == classOf[org.junit.Test.None]) { - val isAssertion = ex.isInstanceOf[AssertionError] - val failedMsg = new StringBuilder - failedMsg ++= "failed: " - if (!runner.runSettings.notLogExceptionClass && - (!isAssertion || runner.runSettings.logAssert)) { - val classParts = ex.getClass.getName.split('.') - failedMsg ++= classParts.init.mkString(".") - failedMsg += '.' - failedMsg ++= c(classParts.last, ENAME2) - failedMsg ++= ": " - } - failedMsg ++= ex.getMessage - failedMsg += ',' - val msg = s"$failedMsg took $timeInSeconds sec" - val exOpt = { - if (!isAssertion || runner.runSettings.logAssert) Some(ex) - else None - } - logFormattedError(decodedMethodName, msg, exOpt) - emitTestFailed() - false - } else { - val msg = s"failed: ${ex.getClass}, took $timeInSeconds sec" - logFormattedError(decodedMethodName, msg, Some(ex)) - emitTestFailed() - false - } - } - } - - var testClassInstance: AnyRef = null - - val instantiationSucceeded = execute() { - testClassInstance = classMetadata.newInstance() - } - - val success = if (!instantiationSucceeded) { - false - } else { - val beforeSucceeded = execute() { - for (method <- jUnitMetadata.beforeMethod) - classMetadata.invoke(testClassInstance, method.name) - } - - val beforeAndTestSucceeded = if (!beforeSucceeded) { - false - } else { - execute(testAnnotation.expected) { - classMetadata.invoke(testClassInstance, method.name) - } - } - - // Whether before and/or test succeeded or not, run the after methods - val afterSucceeded = execute() { - for (method <- jUnitMetadata.afterMethod) - classMetadata.invoke(testClassInstance, method.name) - } - - beforeAndTestSucceeded && afterSucceeded - } - - logFormattedDebug(decodedMethodName, - s"finished, took ${getTimeInSeconds()} sec") - - // Scala.js-specific: timeouts are warnings only, after the fact - val timeInSeconds = getTimeInSeconds() - if (testAnnotation.timeout != 0 && testAnnotation.timeout <= timeInSeconds) { - richLogger.warn("Timeout: took " + timeInSeconds + " sec, expected " + - (testAnnotation.timeout.toDouble / 1000) + " sec") - } - - if (success) - testPassed(methodName) - - runner.testRegisterTotal() - } - - private def ignoreTest(methodName: String) = { - runner.testIgnored() - val selector = new NestedTestSelector(fullyQualifiedName, methodName) - eventHandler.handle(new JUnitEvent(taskDef, Status.Skipped, selector)) - } - - private def ignoreTestClass() = { - runner.testIgnored() - val selector = new TestSelector(fullyQualifiedName) - eventHandler.handle(new JUnitEvent(taskDef, Status.Skipped, selector)) - } - - private def testSkipped(): Unit = { - runner.testSkipped() - val selector = new TestSelector(fullyQualifiedName) - eventHandler.handle(new JUnitEvent(taskDef, Status.Skipped, selector)) - } - - private def testFailed(methodName: String): Unit = { - runner.testFailed() - val selector = new NestedTestSelector(fullyQualifiedName, methodName) - eventHandler.handle(new JUnitEvent(taskDef, Status.Failure, selector)) - } - - private def testPassed(methodName: String): Unit = { - runner.testPassed() - val selector = new NestedTestSelector(fullyQualifiedName, methodName) - eventHandler.handle(new JUnitEvent(taskDef, Status.Success, selector)) - } - - private[this] def logAssertionWarning(methodName: String, ex: Throwable, - timeInSeconds: Double): Unit = { - val exName = - if (runner.runSettings.notLogExceptionClass) "" - else "org.junit.internal." + c("AssumptionViolatedException", ERRMSG) + ": " - - val msg = s"failed: $exName${ex.getMessage}, took $timeInSeconds sec" - logFormattedWarn("Test assumption in test ", methodName, msg) - } - - private[this] def logFormattedInfo(method: String, msg: String): Unit = { - val fMethod = if (method != null) c(method, NNAME2) else null - richLogger.info( - formatLayout("Test ", packageName, c(className, NNAME1), fMethod, msg)) - } - - private[this] def logFormattedDebug(method: String, msg: String): Unit = { - val fMethod = if (method != null) c(method, NNAME2) else null - richLogger.debug( - formatLayout("Test ", packageName, c(className, NNAME1), fMethod, msg)) - } - - private[this] def logFormattedWarn(prefix: String, method: String, - msg: String): Unit = { - val fMethod = if (method != null) c(method, ERRMSG) else null - richLogger.warn( - formatLayout(prefix, packageName, c(className, NNAME1), fMethod, msg)) - } - - private[this] def logFormattedError(method: String, msg: String, - exOpt: Option[Throwable]): Unit = { - val fMethod = if (method != null) c(method, ERRMSG) else null - val formattedMsg = formatLayout("Test ", packageName, c(className, NNAME1), - fMethod, msg) - exOpt match { - case Some(ex) => richLogger.error(formattedMsg, ex) - case None => richLogger.error(formattedMsg) - } - } - - private[this] def formatLayout(prefix: String, packageName: String, - className: String, method: String, msg: String): String = { - if (method != null) s"$prefix$packageName.$className.$method $msg" - else s"$prefix$packageName.$className $msg" - } -} diff --git a/junit-runtime/src/main/scala/org/scalajs/junit/JUnitFramework.scala b/junit-runtime/src/main/scala/org/scalajs/junit/JUnitFramework.scala new file mode 100644 index 0000000000..e960402f61 --- /dev/null +++ b/junit-runtime/src/main/scala/org/scalajs/junit/JUnitFramework.scala @@ -0,0 +1,95 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.junit + +import sbt.testing._ + +final class JUnitFramework extends Framework { + + val name: String = "Scala.js JUnit test framework" + + private object JUnitFingerprint extends AnnotatedFingerprint { + override def annotationName(): String = "org.junit.Test" + + override def isModule(): Boolean = false + } + + def fingerprints(): Array[Fingerprint] = { + Array(JUnitFingerprint) + } + + def runner(args: Array[String], remoteArgs: Array[String], + testClassLoader: ClassLoader): Runner = { + new JUnitRunner(args, remoteArgs, parseRunSettings(args)) + } + + // Aka `workerRunner`; see the Scaladoc of `sbt.testing.Framework` about the name. + def slaveRunner(args: Array[String], remoteArgs: Array[String], + testClassLoader: ClassLoader, send: String => Unit): Runner = { + new JUnitRunner(args, remoteArgs, parseRunSettings(args)) + } + + private def parseRunSettings(args: Array[String]): RunSettings = { + var verbose = false + var noColor = false + var decodeScalaNames = false + var logAssert = false + var notLogExceptionClass = false + for (str <- args) { + str match { + case "-v" => verbose = true + case "-n" => noColor = true + case "-s" => decodeScalaNames = true + case "-a" => logAssert = true + case "-c" => notLogExceptionClass = true + + case s if s.startsWith("-tests=") => + throw new UnsupportedOperationException("-tests") + + case s if s.startsWith("--tests=") => + throw new UnsupportedOperationException("--tests") + + case s if s.startsWith("--ignore-runners=") => + throw new UnsupportedOperationException("--ignore-runners") + + case s if s.startsWith("--run-listener=") => + throw new UnsupportedOperationException("--run-listener") + + case s if s.startsWith("--include-categories=") => + throw new UnsupportedOperationException("--include-categories") + + case s if s.startsWith("--exclude-categories=") => + throw new UnsupportedOperationException("--exclude-categories") + + case s if s.startsWith("-D") && s.contains("=") => + throw new UnsupportedOperationException("-Dkey=value") + + case s if !s.startsWith("-") && !s.startsWith("+") => + throw new UnsupportedOperationException(s) + + case _ => + } + } + for (s <- args) { + s match { + case "+v" => verbose = false + case "+n" => noColor = false + case "+s" => decodeScalaNames = false + case "+a" => logAssert = false + case "+c" => notLogExceptionClass = false + case _ => + } + } + new RunSettings(!noColor, decodeScalaNames, verbose, logAssert, notLogExceptionClass) + } +} diff --git a/junit-runtime/src/main/scala/org/scalajs/junit/JUnitMasterRunner.scala b/junit-runtime/src/main/scala/org/scalajs/junit/JUnitMasterRunner.scala deleted file mode 100644 index f75f26cc13..0000000000 --- a/junit-runtime/src/main/scala/org/scalajs/junit/JUnitMasterRunner.scala +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.junit - -import com.novocode.junit.RunSettings -import sbt.testing._ -import java.util.concurrent.atomic.AtomicInteger - -final class JUnitMasterRunner( - args: Array[String], - remoteArgs: Array[String], - testClassLoader: ClassLoader, - runSettings: RunSettings) - extends JUnitBaseRunner(args, remoteArgs, testClassLoader, runSettings) { - - private[this] var registeredCount = 0 - private[this] var slaveCount = 0 - - def tasks(taskDefs: Array[TaskDef]): Array[Task] = { - registeredCount += taskDefs.length - taskDefs.map(newTask) - } - - def done(): String = { - val slaves = slaveCount - val registered = registeredCount - val done = doneCount - - if (slaves > 0) - throw new IllegalStateException(s"There are still $slaves slaves running") - - if (registered != done) { - val msg = s"$registered task(s) were registered, $done were executed" - throw new IllegalStateException(msg) - } else { - "" - } - } - - def receiveMessage(msg: String): Option[String] = msg(0) match { - case 'd' => - val slaveDone = JUnitBaseRunner.Done.deserialize(msg.tail) - doneCount += slaveDone.done - passedCount += slaveDone.passed - failedCount += slaveDone.failed - ignoredCount += slaveDone.skipped - skippedCount += slaveDone.skipped - totalCount += slaveDone.total - slaveCount -= 1 - None - } -} diff --git a/junit-runtime/src/main/scala/org/scalajs/junit/JUnitRunner.scala b/junit-runtime/src/main/scala/org/scalajs/junit/JUnitRunner.scala new file mode 100644 index 0000000000..92ee7dc85a --- /dev/null +++ b/junit-runtime/src/main/scala/org/scalajs/junit/JUnitRunner.scala @@ -0,0 +1,34 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.junit + +import sbt.testing._ + +private[junit] final class JUnitRunner( + val args: Array[String], + val remoteArgs: Array[String], + runSettings: RunSettings) extends Runner { + + def tasks(taskDefs: Array[TaskDef]): Array[Task] = + taskDefs.map(new JUnitTask(_, runSettings)) + + def done(): String = "" + + def serializeTask(task: Task, serializer: TaskDef => String): String = + serializer(task.taskDef()) + + def deserializeTask(task: String, deserializer: String => TaskDef): Task = + new JUnitTask(deserializer(task), runSettings) + + def receiveMessage(msg: String): Option[String] = None +} diff --git a/junit-runtime/src/main/scala/org/scalajs/junit/JUnitSlaveRunner.scala b/junit-runtime/src/main/scala/org/scalajs/junit/JUnitSlaveRunner.scala deleted file mode 100644 index 7f389f235d..0000000000 --- a/junit-runtime/src/main/scala/org/scalajs/junit/JUnitSlaveRunner.scala +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.junit - -import com.novocode.junit.RunSettings -import sbt.testing._ - -final class JUnitSlaveRunner( - args: Array[String], - remoteArgs: Array[String], - testClassLoader: ClassLoader, - send: String => Unit, - runSettings: RunSettings) - extends JUnitBaseRunner(args, remoteArgs, testClassLoader, runSettings) { - - def tasks(taskDefs: Array[TaskDef]): Array[Task] = { - taskDefs.map(newTask) - } - - def done(): String = { - send("d" + JUnitBaseRunner.Done(taskDoneCount, passedCount, failedCount, - ignoredCount, skippedCount, totalCount).serialize) - "" - } - - def receiveMessage(msg: String): Option[String] = { - None // <- ignored - } -} diff --git a/junit-runtime/src/main/scala/org/scalajs/junit/JUnitTask.scala b/junit-runtime/src/main/scala/org/scalajs/junit/JUnitTask.scala index 2ad9e97d7e..7c2dab2087 100644 --- a/junit-runtime/src/main/scala/org/scalajs/junit/JUnitTask.scala +++ b/junit-runtime/src/main/scala/org/scalajs/junit/JUnitTask.scala @@ -12,83 +12,234 @@ package org.scalajs.junit -import com.novocode.junit.{Ansi, RichLogger} -import Ansi._ -import sbt.testing._ -import scala.scalajs.reflect.Reflect +import scala.concurrent.Future + +/* Use the queue execution context (based on JS promises) explicitly: + * We do not have anything better at our disposal and it is accceptable in + * terms of fairness: We only use it for test dispatching and orchestation. + * The real async work is done in Bootstrapper#invokeTest which does not take + * an (implicit) ExecutionContext parameter. + */ +import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue + import scala.util.{Try, Success, Failure} -final class JUnitTask(val taskDef: TaskDef, runner: JUnitBaseRunner) - extends sbt.testing.Task { +import scala.scalajs.reflect.Reflect + +import sbt.testing._ + +/* Implementation note: In JUnitTask we use Future[Try[Unit]] instead of simply + * Future[Unit]. This is to prevent Scala's Future implementation to box/wrap + * fatal errors (most importantly AssertionError) in ExecutionExceptions. We + * need to prevent the wrapping in order to hide the fact that we use async + * under the hood and stay consistent with JVM JUnit. + */ +private[junit] final class JUnitTask(val taskDef: TaskDef, + runSettings: RunSettings) extends Task { - def tags: Array[String] = Array.empty + def tags(): Array[String] = Array.empty def execute(eventHandler: EventHandler, loggers: Array[Logger], continuation: Array[Task] => Unit): Unit = { - continuation(execute(eventHandler, loggers)) + val reporter = new Reporter(eventHandler, loggers, runSettings, taskDef) + + val result = loadBootstrapper(reporter).fold { + Future.successful(()) + } { bootstrapper => + executeTests(bootstrapper, reporter) + } + + result.foreach(_ => continuation(Array())) } - def execute(eventHandler: EventHandler, loggers: Array[Logger]): Array[Task] = { - val fullClassName = taskDef.fullyQualifiedName - val richLogger = new RichLogger(loggers, runner.runSettings, fullClassName) + private def executeTests(bootstrapper: Bootstrapper, reporter: Reporter): Future[Unit] = { + reporter.reportRunStarted() + + var failed = 0 + var ignored = 0 + var total = 0 + + def runTests(tests: List[TestMetadata]): Future[Try[Unit]] = { + val (nextIgnored, other) = tests.span(_.ignored) - def infoOrDebug(msg: String): Unit = { - if (runner.runSettings.verbose) - richLogger.info(msg) - else - richLogger.debug(msg) + nextIgnored.foreach(t => reporter.reportIgnored(Some(t.name))) + ignored += nextIgnored.size + + other match { + case t :: ts => + total += 1 + executeTestMethod(bootstrapper, t, reporter).flatMap { fc => + failed += fc + runTests(ts) + } + + case Nil => + Future.successful(Success(())) + } } - infoOrDebug(c("Test run started", INFO)) + val result = runTestLifecycle { + Success(()) + } { _ => + catchAll(bootstrapper.beforeClass()) + } { _ => + runTests(bootstrapper.tests().toList) + } { _ => + catchAll(bootstrapper.afterClass()) + } - val bootstrapperName = fullClassName + "$scalajs$junit$bootstrapper" + for { + (errors, timeInSeconds) <- result + } yield { + failed += reportExecutionErrors(reporter, None, timeInSeconds, errors) + reporter.reportRunFinished(failed, ignored, total, timeInSeconds) + } + } - val startTime = System.nanoTime + private[this] def executeTestMethod(bootstrapper: Bootstrapper, test: TestMetadata, + reporter: Reporter): Future[Int] = { + reporter.reportTestStarted(test.name) + + val result = runTestLifecycle { + catchAll(bootstrapper.newInstance()) + } { instance => + catchAll(bootstrapper.before(instance)) + } { instance => + handleExpected(test.annotation.expected) { + catchAll(bootstrapper.invokeTest(instance, test.name)) match { + case Success(f) => f.recover { case t => Failure(t) } + case Failure(t) => Future.successful(Failure(t)) + } + } + } { instance => + catchAll(bootstrapper.after(instance)) + } + + for { + (errors, timeInSeconds) <- result + } yield { + val failed = reportExecutionErrors(reporter, Some(test.name), timeInSeconds, errors) + reporter.reportTestFinished(test.name, errors.isEmpty, timeInSeconds) + + // Scala.js-specific: timeouts are warnings only, after the fact + val timeout = test.annotation.timeout + if (timeout != 0 && timeout <= timeInSeconds) { + reporter.log(_.warn, "Timeout: took " + timeInSeconds + " sec, expected " + + (timeout.toDouble / 1000) + " sec") + } + + failed + } + } - def errorWhileLoadingClass(t: Throwable): Unit = { - richLogger.error("Error while loading test class: " + fullClassName, t) - val selector = new TestSelector(fullClassName) - val optThrowable = new OptionalThrowable(t) - val ev = new JUnitEvent(taskDef, Status.Failure, selector, optThrowable) - eventHandler.handle(ev) + private def reportExecutionErrors(reporter: Reporter, method: Option[String], + timeInSeconds: Double, errors: List[Throwable]): Int = { + import org.junit.internal.AssumptionViolatedException + import org.junit.TestCouldNotBeSkippedException + + errors match { + case Nil => + // fast path + 0 + + case (e: AssumptionViolatedException) :: Nil => + reporter.reportAssumptionViolation(method, timeInSeconds, e) + 0 + + case _ => + val errorsPatchedForAssumptionViolations = errors.map { + case error: AssumptionViolatedException => + new TestCouldNotBeSkippedException(error) + case error => + error + } + reporter.reportErrors("Test ", method, timeInSeconds, + errorsPatchedForAssumptionViolations) + errorsPatchedForAssumptionViolations.size } + } - Try { - Reflect - .lookupLoadableModuleClass(bootstrapperName + "$") - .getOrElse(throw new ClassNotFoundException(s"Cannot find $bootstrapperName$$")) + private def loadBootstrapper(reporter: Reporter): Option[Bootstrapper] = { + val bootstrapperName = + taskDef.fullyQualifiedName() + "$scalajs$junit$bootstrapper$" + + try { + val b = Reflect + .lookupLoadableModuleClass(bootstrapperName) + .getOrElse(throw new ClassNotFoundException(s"Cannot find $bootstrapperName")) .loadModule() - } match { - case Success(classMetadata: JUnitTestBootstrapper) => - new JUnitExecuteTest(taskDef, runner, classMetadata, - richLogger, eventHandler).executeTests() - case Success(_) => - val msg = s"Expected $bootstrapperName to extend JUnitTestBootstrapper" - errorWhileLoadingClass(new Exception(msg)) + b match { + case b: Bootstrapper => Some(b) - case Failure(exception) => - errorWhileLoadingClass(exception) + case _ => + throw new ClassCastException(s"Expected $bootstrapperName to extend Bootstrapper") + } + } catch { + case t: Throwable => + reporter.reportErrors("Error while loading test class ", None, 0, List(t)) + None } + } - runner.taskDone() + private def handleExpected(expectedException: Class[_ <: Throwable])(body: => Future[Try[Unit]]) = { + val wantException = expectedException != classOf[org.junit.Test.None] + + if (wantException) { + for (r <- body) yield { + r match { + case Success(_) => + Failure(new AssertionError("Expected exception: " + expectedException.getName)) + + case Failure(t) if expectedException.isInstance(t) => + Success(()) + + case Failure(t) => + val expName = expectedException.getName + val gotName = t.getClass.getName + Failure(new Exception(s"Unexpected exception, expected<$expName> but was<$gotName>", t)) + } + } + } else { + body + } + } + + private def runTestLifecycle[T](build: => Try[T])(before: T => Try[Unit])( + body: T => Future[Try[Unit]])( + after: T => Try[Unit]): Future[(List[Throwable], Double)] = { + val startTime = System.nanoTime + + val exceptions: Future[List[Throwable]] = build match { + case Success(x) => + val bodyFuture = before(x) match { + case Success(()) => body(x) + case Failure(t) => Future.successful(Failure(t)) + } - val time = System.nanoTime - startTime - val failed = runner.testFailedCount - val ignored = runner.testIgnoredCount - val total = runner.testTotalCount + for (bodyResult <- bodyFuture) yield { + val afterException = after(x).failed.toOption + bodyResult.failed.toOption.toList ++ afterException.toList + } - val msg = { - c("Test run finished: ", INFO) + - c(s"$failed failed", if (failed == 0) INFO else ERRCOUNT) + - c(s", ", INFO) + - c(s"$ignored ignored", if (ignored == 0) INFO else IGNCOUNT) + - c(s", $total total, ${time.toDouble / 1000000000}s", INFO) + case Failure(t) => + Future.successful(List(t)) } - infoOrDebug(msg) - runner.resetTestCounts() + for (es <- exceptions) yield { + val timeInSeconds = (System.nanoTime - startTime).toDouble / 1000000000 + (es, timeInSeconds) + } + } - Array() + private def catchAll[T](body: => T): Try[T] = { + try { + Success(body) + } catch { + case t: Throwable => Failure(t) + } } + + def execute(eventHandler: EventHandler, loggers: Array[Logger]): Array[Task] = + throw new UnsupportedOperationException("Supports JS only") } diff --git a/junit-runtime/src/main/scala/org/scalajs/junit/JUnitTestBootstrapper.scala b/junit-runtime/src/main/scala/org/scalajs/junit/JUnitTestBootstrapper.scala deleted file mode 100644 index d61b22c9dc..0000000000 --- a/junit-runtime/src/main/scala/org/scalajs/junit/JUnitTestBootstrapper.scala +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Scala.js (https://www.scala-js.org/) - * - * Copyright EPFL. - * - * Licensed under Apache License 2.0 - * (https://www.apache.org/licenses/LICENSE-2.0). - * - * See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - */ - -package org.scalajs.junit - -import java.lang.annotation.Annotation - -import org.junit.FixMethodOrder - -import scala.scalajs.reflect.annotation._ - -@EnableReflectiveInstantiation -trait JUnitTestBootstrapper { - def metadata(): JUnitClassMetadata - def newInstance(): AnyRef - def invoke(methodName: String): Unit - def invoke(instance: AnyRef, methodName: String): Unit -} - -final class JUnitMethodMetadata(val name: String, annotations: List[Annotation]) { - - def hasTestAnnotation: Boolean = - annotations.exists(_.isInstanceOf[org.junit.Test]) - - def hasBeforeAnnotation: Boolean = - annotations.exists(_.isInstanceOf[org.junit.Before]) - - def hasAfterAnnotation: Boolean = - annotations.exists(_.isInstanceOf[org.junit.After]) - - def hasBeforeClassAnnotation: Boolean = - annotations.exists(_.isInstanceOf[org.junit.BeforeClass]) - - def hasAfterClassAnnotation: Boolean = - annotations.exists(_.isInstanceOf[org.junit.AfterClass]) - - def getTestAnnotation: Option[org.junit.Test] = - annotations.collectFirst { case test: org.junit.Test => test } - - def getIgnoreAnnotation: Option[org.junit.Ignore] = - annotations.collectFirst { case ign: org.junit.Ignore => ign } -} - -final class JUnitClassMetadata(classAnnotations: List[Annotation], - moduleAnnotations: List[Annotation], classMethods: List[JUnitMethodMetadata], - moduleMethods: List[JUnitMethodMetadata]) { - - def testMethods: List[JUnitMethodMetadata] = { - val fixMethodOrderAnnotation = getFixMethodOrderAnnotation - val methodSorter = fixMethodOrderAnnotation.value - val tests = classMethods.filter(_.hasTestAnnotation) - tests.sortWith((a, b) => methodSorter.comparator.lt(a.name, b.name)) - } - - def beforeMethod: List[JUnitMethodMetadata] = - classMethods.filter(_.hasBeforeAnnotation) - - def afterMethod: List[JUnitMethodMetadata] = - classMethods.filter(_.hasAfterAnnotation) - - def beforeClassMethod: List[JUnitMethodMetadata] = - moduleMethods.filter(_.hasBeforeClassAnnotation) - - def afterClassMethod: List[JUnitMethodMetadata] = - moduleMethods.filter(_.hasAfterClassAnnotation) - - def getFixMethodOrderAnnotation: FixMethodOrder = { - classAnnotations.collectFirst { - case fmo: FixMethodOrder => fmo - }.getOrElse(new FixMethodOrder) - } -} diff --git a/junit-runtime/src/main/scala/org/scalajs/junit/Reporter.scala b/junit-runtime/src/main/scala/org/scalajs/junit/Reporter.scala new file mode 100644 index 0000000000..4673a4cf9e --- /dev/null +++ b/junit-runtime/src/main/scala/org/scalajs/junit/Reporter.scala @@ -0,0 +1,239 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.junit + +import org.junit._ + +import sbt.testing._ + +private[junit] final class Reporter(eventHandler: EventHandler, + loggers: Array[Logger], settings: RunSettings, taskDef: TaskDef) { + + def reportRunStarted(): Unit = + log(infoOrDebug, Ansi.c("Test run started", Ansi.BLUE)) + + def reportRunFinished(failed: Int, ignored: Int, total: Int, + timeInSeconds: Double): Unit = { + val msg = { + Ansi.c("Test run finished: ", Ansi.BLUE) + + Ansi.c(s"$failed failed", if (failed == 0) Ansi.BLUE else Ansi.RED) + + Ansi.c(s", ", Ansi.BLUE) + + Ansi.c(s"$ignored ignored", if (ignored == 0) Ansi.BLUE else Ansi.YELLOW) + + Ansi.c(s", $total total, ${timeInSeconds}s", Ansi.BLUE) + } + + log(infoOrDebug, msg) + } + + def reportIgnored(method: Option[String]): Unit = { + logTestInfo(_.info, method, "ignored") + emitEvent(method, Status.Skipped) + } + + def reportTestStarted(method: String): Unit = + logTestInfo(infoOrDebug, Some(method), "started") + + def reportTestFinished(method: String, succeeded: Boolean, timeInSeconds: Double): Unit = { + logTestInfo(_.debug, Some(method), s"finished, took $timeInSeconds sec") + + if (succeeded) + emitEvent(Some(method), Status.Success) + } + + def reportErrors(prefix: String, method: Option[String], + timeInSeconds: Double, errors: List[Throwable]): Unit = { + def emit(t: Throwable) = { + logTestException(_.error, prefix, method, t, timeInSeconds) + trace(t) + } + + if (errors.nonEmpty) { + emit(errors.head) + emitEvent(method, Status.Failure) + errors.tail.foreach(emit) + } + } + + def reportAssumptionViolation(method: Option[String], timeInSeconds: Double, e: Throwable): Unit = { + logTestException(_.warn, "Test assumption in test ", method, e, + timeInSeconds) + emitEvent(method, Status.Skipped) + } + + private def logTestInfo(level: Reporter.Level, method: Option[String], msg: String): Unit = + log(level, s"Test ${formatTest(method, Ansi.CYAN)} $msg") + + private def logTestException(level: Reporter.Level, prefix: String, + method: Option[String], ex: Throwable, timeInSeconds: Double): Unit = { + val logException = { + !settings.notLogExceptionClass && + (settings.logAssert || !ex.isInstanceOf[AssertionError]) + } + + val fmtName = + if (logException) formatClass(ex.getClass.getName, Ansi.RED) + ": " + else "" + + val m = formatTest(method, Ansi.RED) + val msg = s"$prefix$m failed: $fmtName${ex.getMessage}, took $timeInSeconds sec" + log(level, msg) + } + + private def trace(t: Throwable): Unit = { + if (!t.isInstanceOf[AssertionError] || settings.logAssert) { + logTrace(t) + } + } + + private def infoOrDebug: Reporter.Level = + if (settings.verbose) _.info + else _.debug + + private def formatTest(method: Option[String], color: String): String = { + method.fold(formattedTestClass) { method => + val fmtMethod = Ansi.c(settings.decodeName(method), color) + s"$formattedTestClass.$fmtMethod" + } + } + + private lazy val formattedTestClass = + formatClass(taskDef.fullyQualifiedName(), Ansi.YELLOW) + + private def formatClass(fullName: String, color: String): String = { + val (prefix, name) = fullName.splitAt(fullName.lastIndexOf(".") + 1) + prefix + Ansi.c(name, color) + } + + private def emitEvent(method: Option[String], status: Status): Unit = { + val testName = method.fold(taskDef.fullyQualifiedName())(method => + taskDef.fullyQualifiedName() + "." + settings.decodeName(method)) + val selector = new TestSelector(testName) + eventHandler.handle(new JUnitEvent(taskDef, status, selector)) + } + + def log(level: Reporter.Level, s: String): Unit = { + for (l <- loggers) + level(l)(filterAnsiIfNeeded(l, s)) + } + + private def filterAnsiIfNeeded(l: Logger, s: String): String = + if (l.ansiCodesSupported() && settings.color) s + else Ansi.filterAnsi(s) + + private def logTrace(t: Throwable): Unit = { + val trace = t.getStackTrace.dropWhile { p => + p.getFileName() != null && { + p.getFileName().contains("StackTrace.scala") || + p.getFileName().contains("Throwables.scala") + } + } + val testFileName = { + if (settings.color) findTestFileName(trace) + else null + } + val i = trace.indexWhere { + p => p.getFileName() != null && p.getFileName().contains("JUnitExecuteTest.scala") + } - 1 + val m = if (i > 0) i else trace.length - 1 + logStackTracePart(trace, m, trace.length - m - 1, t, testFileName) + } + + private def logStackTracePart(trace: Array[StackTraceElement], m: Int, + framesInCommon: Int, t: Throwable, testFileName: String): Unit = { + val m0 = m + var m2 = m + var top = 0 + var i = top + while (i <= m2) { + if (trace(i).toString.startsWith("org.junit.") || + trace(i).toString.startsWith("org.hamcrest.")) { + if (i == top) { + top += 1 + } else { + m2 = i - 1 + var break = false + while (m2 > top && !break) { + val s = trace(m2).toString + if (!s.startsWith("java.lang.reflect.") && + !s.startsWith("sun.reflect.")) { + break = true + } else { + m2 -= 1 + } + } + i = m2 // break + } + } + i += 1 + } + + for (i <- top to m2) { + log(_.error, " at " + + stackTraceElementToString(trace(i), testFileName)) + } + if (m0 != m2) { + // skip junit-related frames + log(_.error, " ...") + } else if (framesInCommon != 0) { + // skip frames that were in the previous trace too + log(_.error, " ... " + framesInCommon + " more") + } + logStackTraceAsCause(trace, t.getCause, testFileName) + } + + private def logStackTraceAsCause(causedTrace: Array[StackTraceElement], + t: Throwable, testFileName: String): Unit = { + if (t != null) { + val trace = t.getStackTrace + var m = trace.length - 1 + var n = causedTrace.length - 1 + while (m >= 0 && n >= 0 && trace(m) == causedTrace(n)) { + m -= 1 + n -= 1 + } + log(_.error, "Caused by: " + t) + logStackTracePart(trace, m, trace.length - 1 - m, t, testFileName) + } + } + + private def findTestFileName(trace: Array[StackTraceElement]): String = + trace.find(_.getClassName() == taskDef.fullyQualifiedName()).map(_.getFileName()).orNull + + private def stackTraceElementToString(e: StackTraceElement, testFileName: String): String = { + val highlight = settings.color && { + taskDef.fullyQualifiedName() == e.getClassName() || + (testFileName != null && testFileName == e.getFileName()) + } + var r = "" + r += settings.decodeName(e.getClassName() + '.' + e.getMethodName()) + r += '(' + + if (e.isNativeMethod) { + r += Ansi.c("Native Method", if (highlight) Ansi.YELLOW else null) + } else if (e.getFileName() == null) { + r += Ansi.c("Unknown Source", if (highlight) Ansi.YELLOW else null) + } else { + r += Ansi.c(e.getFileName(), if (highlight) Ansi.MAGENTA else null) + if (e.getLineNumber() >= 0) { + r += ':' + r += Ansi.c(String.valueOf(e.getLineNumber()), if (highlight) Ansi.YELLOW else null) + } + } + r += ')' + r + } +} + +private[junit] object Reporter { + type Level = Logger => (String => Unit) +} diff --git a/junit-runtime/src/main/scala/org/scalajs/junit/RunSettings.scala b/junit-runtime/src/main/scala/org/scalajs/junit/RunSettings.scala new file mode 100644 index 0000000000..da461c73c7 --- /dev/null +++ b/junit-runtime/src/main/scala/org/scalajs/junit/RunSettings.scala @@ -0,0 +1,28 @@ +/* + * Scala.js (https://www.scala-js.org/) + * + * Copyright EPFL. + * + * Licensed under Apache License 2.0 + * (https://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package org.scalajs.junit + +import scala.util.Try + +private[junit] final class RunSettings ( + val color: Boolean, + decodeScalaNames: Boolean, + val verbose: Boolean, + val logAssert: Boolean, + val notLogExceptionClass: Boolean +) { + def decodeName(name: String): String = { + if (decodeScalaNames) Try(scala.reflect.NameTransformer.decode(name)).getOrElse(name) + else name + } +} diff --git a/junit-test/README.md b/junit-test/README.md new file mode 100644 index 0000000000..e9a6aa186b --- /dev/null +++ b/junit-test/README.md @@ -0,0 +1,8 @@ +JUnit tests compare the output of a JUnit test to a recording. + +The recordings lie in the `outputs` directory. To re-record all tests, set the +`org.scalajs.junit.utils.record` system property and run the JVM tests: + +``` +sbt -Dorg.scalajs.junit.utils.record jUnitTestOutputsJVM/test +``` diff --git a/junit-test/output-js/src/test/scala/org/scalajs/junit/utils/JUnitTestPlatformImpl.scala b/junit-test/output-js/src/test/scala/org/scalajs/junit/utils/JUnitTestPlatformImpl.scala index 0e9cb2d924..f2290ec9d3 100644 --- a/junit-test/output-js/src/test/scala/org/scalajs/junit/utils/JUnitTestPlatformImpl.scala +++ b/junit-test/output-js/src/test/scala/org/scalajs/junit/utils/JUnitTestPlatformImpl.scala @@ -12,28 +12,38 @@ package org.scalajs.junit.utils -import sbt.testing._ - import scala.scalajs.js +import scala.concurrent._ +import scala.concurrent.ExecutionContext.Implicits.global + +import sbt.testing._ + object JUnitTestPlatformImpl { - def getClassLoader: ClassLoader = - new org.scalajs.testinterface.ScalaJSClassLoader(js.Dynamic.global) - - def executeLoop(tasks: Array[Task], recorder: Logger with EventHandler): Unit = { - if (tasks.nonEmpty) { - executeLoop(tasks.flatMap { task => - /* This is a hack, assuming the asynchronous continuation will be called before - * the outer call returns. This is terrible in general, but we do not have - * another choice, since JUnit does not support async testing. - * However, since JUnit does not support async testing, this is a safe - * assumption to make (modulo JUnit implementation details, which we control). - * If JUnit ever were to support async testing, we could also change this here. - */ - task.execute(recorder, Array(recorder)) - Array.empty[Task] - }, recorder) + def getClassLoader: ClassLoader = null + + def executeLoop(tasks: Array[Task], recorder: Logger with EventHandler): Future[Unit] = { + if (tasks.isEmpty) { + Future.successful(()) + } else { + Future.traverse(tasks.toList)(executeTask(_, recorder)).flatMap( + newTasks => executeLoop(newTasks.flatten.toArray, recorder)) } } + + private def executeTask(task: Task, recorder: Logger with EventHandler): Future[Array[Task]] = { + val p = Promise[Array[Task]]() + task.execute(recorder, Array(recorder), p.success _) + p.future + } + + def writeLines(lines: List[String], file: String): Unit = + throw new UnsupportedOperationException("Writing is only supported on the JVM.") + + def readLines(file: String): List[String] = { + val fs = js.Dynamic.global.require("fs") + val c = fs.readFileSync(file, "utf8").asInstanceOf[String] + c.split('\n').toList + } } diff --git a/junit-test/output-jvm/src/test/scala/org/scalajs/junit/utils/JUnitTestPlatformImpl.scala b/junit-test/output-jvm/src/test/scala/org/scalajs/junit/utils/JUnitTestPlatformImpl.scala index f6c2fdcdd3..8857d8ca85 100644 --- a/junit-test/output-jvm/src/test/scala/org/scalajs/junit/utils/JUnitTestPlatformImpl.scala +++ b/junit-test/output-jvm/src/test/scala/org/scalajs/junit/utils/JUnitTestPlatformImpl.scala @@ -12,15 +12,33 @@ package org.scalajs.junit.utils +import scala.annotation.tailrec + +import scala.collection.JavaConverters._ + +import scala.concurrent.Future + +import java.nio.file._ +import java.nio.charset.StandardCharsets.UTF_8 + import sbt.testing._ object JUnitTestPlatformImpl { def getClassLoader: ClassLoader = getClass.getClassLoader - def executeLoop(tasks: Array[Task], recorder: Logger with EventHandler): Unit = { + @tailrec + def executeLoop(tasks: Array[Task], recorder: Logger with EventHandler): Future[Unit] = { if (tasks.nonEmpty) { executeLoop(tasks.flatMap(_.execute(recorder, Array(recorder))), recorder) + } else { + Future.successful(()) } } + + def writeLines(lines: List[String], file: String): Unit = + Files.write(Paths.get(file), (lines: Iterable[String]).asJava, UTF_8) + + def readLines(file: String): List[String] = + Files.readAllLines(Paths.get(file), UTF_8).asScala.toList } diff --git a/junit-test/outputs/org/scalajs/junit/AssertEquals2TestAssertions_.txt b/junit-test/outputs/org/scalajs/junit/AssertEquals2TestAssertions_.txt new file mode 100644 index 0000000000..2a161db9ae --- /dev/null +++ b/junit-test/outputs/org/scalajs/junit/AssertEquals2TestAssertions_.txt @@ -0,0 +1,7 @@ +ldTest run started +ldTest org.scalajs.junit.AssertEquals2Test.test started +leTest org.scalajs.junit.AssertEquals2Test.test failed: This is the message expected: but was:, took