diff --git a/.github/workflows/scala.yml b/.github/workflows/scala.yml index 42559c2da..6a70c6b3f 100644 --- a/.github/workflows/scala.yml +++ b/.github/workflows/scala.yml @@ -19,8 +19,8 @@ jobs: - uses: actions/setup-node@v3 with: node-version: '17.x' - - name: Install TypeScript - run: npm ci + - name: Prepare TypeScript + run: ./scripts/ts-prepare.sh - name: Run tests run: sbt -J-Xmx4096M -J-Xss4M test - name: Check no changes diff --git a/.gitignore b/.gitignore index 4a989b4c7..a9def9946 100644 --- a/.gitignore +++ b/.gitignore @@ -7,4 +7,8 @@ metals.sbt project/Dependencies.scala project/metals.sbt **.worksheet.sc +driver/js/src/test/cjsprojects/js/ts/ +driver/js/src/test/esprojects/js/my_ts_path/ +driver/npm/lib/index.js +driver/npm/lib/index.js.map .DS_Store diff --git a/README.md b/README.md index f0eeec956..d13b73ff3 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,18 @@ MLscript supports union, intersection, and complement (or negation) connectives, - The `ts2mls/js/src/test/diff` directory contains the declarations generated by ts2mls. +- The `driver/js/src/main` directory contains the sources of the driver module. + +- The `driver/js/src/test/scala/driver` directory contains the sources of the test infrastructure for the driver. + +- The `driver/js/src/test/cjsprojects` directory contains the tests using CommonJS module solution. + +- The `driver/js/src/test/esprojects` directory contains the tests using ES module solution. + +- The `driver/js/src/test/output` directory contains the test execution outputs. + +- The `driver/js/src/test/predefs` directory contains the MLscript type definitions that override those in `es5.d.ts`. + ### Prerequisites You need [JDK supported by Scala][supported-jdk-versions], [sbt][sbt], [Node.js][node.js], and TypeScript to compile the project and run the tests. @@ -49,8 +61,14 @@ We recommend you to install JDK and sbt via [coursier][coursier]. The versions o Running the main MLscript tests only requires the Scala Build Tool installed. In the terminal, run `sbt mlscriptJVM/test`. -Running the ts2mls MLscript tests requires NodeJS, and TypeScript in addition. -In the terminal, run `sbt ts2mlsTest/test`. +Running the driver MLscript tests(including ts2mls) requires NodeJS, TypeScript, and TypeScript libraries below: +- [json5](https://json5.org/) +- [lodash](https://lodash.com/) +- [fp-ts](https://gcanti.github.io/fp-ts/) + +To install these libraries and compile TypeScript codes automatically, run `./scripts/ts-prepare.sh`. + +In the terminal, run `sbt driverTest/test`. You can also run all tests simultaneously. In the terminal, run `sbt test`. @@ -70,15 +88,22 @@ You can also indicate the test you want in `shared/src/test/scala/mlscript/DiffT ).map(os.RelPath(_)) ``` -To run the tests in ts2mls sub-project individually, -you can indicate the test you want in `ts2mls/js/src/test/scala/ts2mls/TSTypeGenerationTests.scala`: +To run the tests in the driver sub-project individually, +you can indicate the test you want in `driver/js/src/test/scala/driver/DriverDiffTests.scala`: ```scala -private val testsData = List( - // Put all input files in the `Seq` - // Then indicate the output file's name - (Seq("Array.ts"), "Array.d.mls") - ) +private val ts2mlsCases = List( + ts2mlsEntry(/* ... */), + // ... +) +private val esCases = List( + esEntry(/* ... */), + // ... +) +private val cjsCases = List( + cjsEntry(/* ... */), + // ... +) ``` ### Running the web demo locally diff --git a/build.sbt b/build.sbt index 8f4ff503f..b508778c8 100644 --- a/build.sbt +++ b/build.sbt @@ -13,7 +13,7 @@ ThisBuild / scalacOptions ++= Seq( ) lazy val root = project.in(file(".")) - .aggregate(mlscriptJS, mlscriptJVM, ts2mlsTest, compilerJVM) + .aggregate(mlscriptJS, mlscriptJVM, driverTest, compilerJVM) .settings( publish := {}, publishLocal := {}, @@ -91,3 +91,27 @@ lazy val compiler = crossProject(JSPlatform, JVMPlatform).in(file("compiler")) lazy val compilerJVM = compiler.jvm lazy val compilerJS = compiler.js +lazy val driver = crossProject(JSPlatform, JVMPlatform).in(file("driver")) + .settings( + name := "mlscript-driver", + scalaVersion := "2.13.8", + scalacOptions ++= Seq( + "-deprecation" + ) + ) + .jvmSettings() + .jsSettings( + libraryDependencies += "org.scala-js" %%% "scalajs-dom" % "2.1.0", + libraryDependencies += "org.scalatest" %%% "scalatest" % "3.2.12" % "test", + Compile / fastOptJS / artifactPath := baseDirectory.value / ".." / ".." / "driver" / "npm" / "lib" / "index.js", + scalaJSLinkerConfig ~= { _.withModuleKind(ModuleKind.CommonJSModule) } + ) + .dependsOn(mlscript % "compile->compile;test->test") + .dependsOn(ts2mls % "compile->compile;test->test") + +lazy val driverJS = driver.js +lazy val driverTest = project.in(file("driver")) + .settings( + scalaVersion := "2.13.8", + Test / test := ((driverJS / Test / test) dependsOn (ts2mlsJS / Test / test)).value + ) diff --git a/compiler/shared/main/scala/mlscript/compiler/ClassLifter.scala b/compiler/shared/main/scala/mlscript/compiler/ClassLifter.scala index 559bc5957..217ac2e1e 100644 --- a/compiler/shared/main/scala/mlscript/compiler/ClassLifter.scala +++ b/compiler/shared/main/scala/mlscript/compiler/ClassLifter.scala @@ -299,7 +299,7 @@ class ClassLifter(logDebugMsg: Boolean = false) { } private def newLambObj(lhs: Term, rhs: Term) = - New(None, TypingUnit(List(NuFunDef(None, Var("apply"), None, Nil, Left(Lam(lhs, rhs)))(N, N, N, N, false)))) //TODO: Use Proper Arguments + New(None, TypingUnit(List(NuFunDef(None, Var("apply"), None, Nil, Left(Lam(lhs, rhs)))(N, N, N, N, N, false)))) //TODO: Use Proper Arguments private def liftTerm(target: Term)(using ctx: LocalContext, cache: ClassCache, globFuncs: Map[Var, (Var, LocalContext)], outer: Option[ClassInfoCache]): (Term, LocalContext) = log(s"liftTermNew $target in $ctx, $cache, $globFuncs, $outer") @@ -321,7 +321,7 @@ class ClassLifter(logDebugMsg: Boolean = false) { val nTpNm = TypeName(genAnoName("Lambda"+prmCnt)) val anoCls = NuTypeDef( Cls, nTpNm, Nil, S(Tup(Nil)), N, N, Nil, N, N, - TypingUnit(List(NuFunDef(None, Var("apply"), N, Nil, Left(Lam(lhs, rhs)))(N, N, N, N, false))))(N, N) //TODO: Use Proper Arguments + TypingUnit(List(NuFunDef(None, Var("apply"), N, Nil, Left(Lam(lhs, rhs)))(N, N, N, N, N, false))))(N, N, N) //TODO: Use Proper Arguments val nSta = New(Some((nTpNm, Tup(Nil))), TypingUnit(Nil)) val ret = liftEntities(List(anoCls, nSta)) (Blk(ret._1), ret._2) @@ -414,13 +414,13 @@ class ClassLifter(logDebugMsg: Boolean = false) { val cls = cache.get(t).get val supArgs = Tup(cls.body.params.fold(Nil)(t => t.fields).flatMap(tupleEntityToVar).map(toFldsEle)) val anoCls = NuTypeDef(Cls, nTpNm, Nil, cls.body.params, None, None, - List(App(Var(t.name), supArgs)), None, None, tu)(None, None) + List(App(Var(t.name), supArgs)), None, None, tu)(None, None, None) val nSta = New(Some((nTpNm, prm)), TypingUnit(Nil)) val ret = liftEntities(List(anoCls, nSta)) (Blk(ret._1), ret._2) case New(None, tu) => val nTpNm = TypeName(genAnoName()) - val anoCls = NuTypeDef(Cls, nTpNm, Nil, None, None, None, Nil, None, None, tu)(None, None) + val anoCls = NuTypeDef(Cls, nTpNm, Nil, None, None, None, Nil, None, None, tu)(None, None, None) val nSta = New(Some((nTpNm, Tup(Nil))), TypingUnit(Nil)) val ret = liftEntities(List(anoCls, nSta)) (Blk(ret._1), ret._2) @@ -582,18 +582,18 @@ class ClassLifter(logDebugMsg: Boolean = false) { val lctx = getFreeVars(lhs)(using emptyCtx, cache, globFuncs, None) val lret = liftTuple(lhs)(using ctx.addV(lctx.vSet)) val ret = liftTerm(rhs)(using ctx.addV(lctx.vSet).addT(tpVs)) - (func.copy(rhs = Left(Lam(lret._1, ret._1)))(func.declareLoc, func.virtualLoc, func.signature, func.outer, func.genField), ret._2 -+ lret._2) //TODO: Check correctness + (func.copy(rhs = Left(Lam(lret._1, ret._1)))(func.declareLoc, func.exportLoc, func.virtualLoc, func.signature, func.outer, func.genField), ret._2 -+ lret._2) //TODO: Check correctness case Left(value) => // will be treated as Lam(Tup(Nil), rhs) val ret = liftTerm(value)(using ctx.addT(tpVs)) - (func.copy(rhs = Left(Lam(Tup(Nil), ret._1)))(func.declareLoc, func.virtualLoc, func.signature, func.outer, func.genField), ret._2) //TODO: Check correctness + (func.copy(rhs = Left(Lam(Tup(Nil), ret._1)))(func.declareLoc, func.exportLoc, func.virtualLoc, func.signature, func.outer, func.genField), ret._2) //TODO: Check correctness case Right(PolyType(targs, body)) => val nBody = liftType(body)(using ctx.addT(tpVs)) val nTargs = targs.map { case L(tp) => liftTypeName(tp)(using ctx.addT(tpVs)).mapFirst(Left.apply) case R(tv) => R(tv) -> emptyCtx }.unzip - (func.copy(rhs = Right(PolyType(nTargs._1, nBody._1)))(func.declareLoc, func.virtualLoc, func.signature, func.outer, func.genField), + (func.copy(rhs = Right(PolyType(nTargs._1, nBody._1)))(func.declareLoc, func.exportLoc, func.virtualLoc, func.signature, func.outer, func.genField), nTargs._2.fold(nBody._2)(_ ++ _)) case _ => throw MonomorphError(s"Unimplemented liftMemberFunc: ${func}") // TODO } @@ -609,12 +609,12 @@ class ClassLifter(logDebugMsg: Boolean = false) { val lctx = getFreeVars(lhs)(using emptyCtx, cache, globFuncs, None) val lret = liftTuple(lhs)(using ctx.addV(lctx.vSet) ++ globFuncs.get(nm).get._2, cache, globFuncs) val ret = liftTerm(rhs)(using ctx.addV(lctx.vSet) ++ globFuncs.get(nm).get._2, cache, globFuncs) - NuFunDef(rec, globFuncs.get(nm).get._1, N, nTpVs, Left(Lam(Tup(lret._1.fields ++ tmp), ret._1)))(N, N, N, N, true) //TODO: Use proper arguments + NuFunDef(rec, globFuncs.get(nm).get._1, N, nTpVs, Left(Lam(Tup(lret._1.fields ++ tmp), ret._1)))(N, N, N, N, N, true) //TODO: Use proper arguments case Left(rhs) => // will be treated as Lam(Tup(Nil), rhs) val tmp = globFuncs.get(nm).get._2.vSet.toList.map(toFldsEle) val ret = liftTerm(rhs)(using ctx ++ globFuncs.get(nm).get._2, cache, globFuncs) - NuFunDef(rec, globFuncs.get(nm).get._1, N, nTpVs, Left(Lam(Tup(tmp), ret._1)))(N, N, N, N, true) //TODO: Use proper arguments + NuFunDef(rec, globFuncs.get(nm).get._1, N, nTpVs, Left(Lam(Tup(tmp), ret._1)))(N, N, N, N, N, true) //TODO: Use proper arguments // val ret = liftTermNew(value)(using ctx.addV(nm) ++ globFuncs.get(nm).get._2, cache, globFuncs) // NuFunDef(rec, globFuncs.get(nm).get._1, nTpVs, Left(ret._1)) case Right(PolyType(targs, body)) => @@ -624,7 +624,7 @@ class ClassLifter(logDebugMsg: Boolean = false) { liftTypeName(tn)(using ctx.addT(nTpVs), cache, globFuncs, None) match case (tn, ctx) => (L(tn), ctx) case R(tv) => R(tv) -> emptyCtx}).unzip - NuFunDef(rec, globFuncs.get(nm).get._1, N, nTpVs, Right(PolyType(nTargs._1, nBody._1)))(N, N, N, N, true) //TODO: Use proper arguments + NuFunDef(rec, globFuncs.get(nm).get._1, N, nTpVs, Right(PolyType(nTargs._1, nBody._1)))(N, N, N, N, N, true) //TODO: Use proper arguments case _ => throw MonomorphError(s"Unimplemented liftGlobalFunc: ${func}") }) } @@ -742,7 +742,7 @@ class ClassLifter(logDebugMsg: Boolean = false) { clsList.foreach(x => liftTypeDef(x)(using nCache, globFuncs, nOuter)) retSeq = retSeq.appended(NuTypeDef( kind, nName, nTps.map((None, _)), S(Tup(nParams)), None, None, nPars._1, - None, None, TypingUnit(nFuncs._1 ++ nTerms._1))(None, None)) + None, None, TypingUnit(nFuncs._1 ++ nTerms._1))(None, None, None)) } def liftTypingUnit(rawUnit: TypingUnit): TypingUnit = { diff --git a/compiler/shared/main/scala/mlscript/compiler/Helpers.scala b/compiler/shared/main/scala/mlscript/compiler/Helpers.scala index 41515a772..62462692b 100644 --- a/compiler/shared/main/scala/mlscript/compiler/Helpers.scala +++ b/compiler/shared/main/scala/mlscript/compiler/Helpers.scala @@ -73,6 +73,7 @@ object Helpers: case mlscript.Def(_, _, _, _) => throw MonomorphError("unsupported Def") case mlscript.LetS(_, _, _) => throw MonomorphError("unsupported LetS") case mlscript.Constructor(_, _) => throw MonomorphError("unsupported Constructor") + case _: mlscript.Import => throw MonomorphError("unsupported import") }) case Bra(rcd, term) => term2Expr(term) case Asc(term, ty) => Expr.As(term2Expr(term), ty) diff --git a/compiler/shared/test/scala/mlscript/compiler/Test.scala b/compiler/shared/test/scala/mlscript/compiler/Test.scala index 7f4c81698..b79daeae9 100644 --- a/compiler/shared/test/scala/mlscript/compiler/Test.scala +++ b/compiler/shared/test/scala/mlscript/compiler/Test.scala @@ -8,6 +8,7 @@ import mlscript.compiler.debug.TreeDebug import mlscript.compiler.mono.Monomorph import mlscript.compiler.printer.ExprPrinter import mlscript.compiler.mono.MonomorphError +import mlscript.JVMGitHelper class DiffTestCompiler extends DiffTests { import DiffTestCompiler.* @@ -41,10 +42,7 @@ class DiffTestCompiler extends DiffTests { } outputBuilder.toString().linesIterator.toList - override protected lazy val files = allFiles.filter { file => - val fileName = file.baseName - validExt(file.ext) && filter(file.relativeTo(pwd)) - } + override protected lazy val files = gitHelper.getFiles(allFiles) } object DiffTestCompiler { @@ -55,7 +53,5 @@ object DiffTestCompiler { private val allFiles = os.walk(dir).filter(_.toIO.isFile) private val validExt = Set("fun", "mls") - - private def filter(file: os.RelPath) = DiffTests.filter(file) - + private val gitHelper = JVMGitHelper(pwd, dir) } diff --git a/driver/js/src/main/scala/driver/Driver.scala b/driver/js/src/main/scala/driver/Driver.scala new file mode 100644 index 000000000..6ee14db94 --- /dev/null +++ b/driver/js/src/main/scala/driver/Driver.scala @@ -0,0 +1,393 @@ +package driver + +import scala.scalajs.js +import mlscript.utils._ +import mlscript._ +import mlscript.utils.shorthands._ +import scala.collection.mutable.{ListBuffer, Map => MutMap, Set => MutSet} +import mlscript.codegen._ +import mlscript.Message._ +import ts2mls.{TSProgram, TypeScript, TSPathResolver, JSFileSystem, JSWriter, FileInfo, JSGitHelper} + +class Driver(options: DriverOptions) { + import Driver._ + import JSFileSystem._ + import JSDriverBackend.ModuleType + + private val gitHelper = JSGitHelper(".", options.path, options.forceIfNoChange) + + private var totalErrors = 0 + private var totalTypeErrors = 0 + private var dbgWriter: Option[JSWriter] = None + private def printDbg(msg: String) = + dbgWriter.foreach(writer => writer.writeDbg(msg.replace("\t", " "))) + + private val typer = + new mlscript.Typer( + dbg = false, + verbose = false, + explainErrors = false, + newDefs = true + ) { + override def emitDbg(str: String): Unit = printDbg(str) + } + + import typer._ + + private object SimplifyPipeline extends typer.SimplifyPipeline { + def debugOutput(msg: => Str): Unit = + println(msg) + } + + // Errors in imported files should be printed in their own files to avoid redundancy + private val noRedundantRaise = (diag: Diagnostic) => () + private val noRedundantOutput = (s: String) => () + + private val importedModule = MutSet[String]() + private val dbgFiles = MutSet[String]() + private implicit val config = TypeScript.parseOption(options.path, options.tsconfig) + + import TSPathResolver.{normalize, isLocal, isMLScirpt, dirname} + + private def checkESModule(filename: String, from: String) = + if (isMLScirpt(filename)) None + else if (isLocal(filename)) // Local files: check tsconfig.json + Some(TypeScript.isESModule(config, false)) + else { // Files in node_modules: find package.json to get the module type + val fullname = TypeScript.resolveModuleName(filename, from, config) + def find(path: String): Boolean = { + val dir = dirname(path) + val pack = s"$dir/package.json" + if (JSFileSystem.exists(pack)) { + val config = TypeScript.parsePackage(pack) + TypeScript.isESModule(config, true) + } + else if (dir.isEmpty || dir === "." || dir === "/") false // Not found: default is commonjs + else find(dir) + } + Some(find(fullname)) + } + + import DriverResult._ + + def execute: DriverResult = + try { + totalErrors = 0 + totalTypeErrors = 0 + implicit var ctx: Ctx = Ctx.init + implicit val raise: Raise = (diag: Diagnostic) => report(diag, printErr) + implicit val extrCtx: Opt[typer.ExtrCtx] = N + implicit val vars: Map[Str, typer.SimpleType] = Map.empty + implicit val stack = List[String]() + initTyper + val res = compile(FileInfo(options.path, options.filename, options.interfaceDir), false) + if (!res) OK // Not changed. + else if (totalErrors > 0 && !options.expectError) Error + else if (totalErrors == 0 && options.expectError) ExpectError + else if (totalTypeErrors > 0 && !options.expectTypeError) TypeError + else if (totalErrors > 0 && !options.expectError) ExpectTypeError + else OK + } + catch { + case err: Diagnostic => // We can not find a file to store the error message. Print on the screen + report(err, printErr) + if (options.expectError) OK else Error + } + + def genPackageJson(): Unit = { + val content = // TODO: more settings? + if (!options.commonJS) + """{ "type": "module" }""" + "\n" + else + """{ "type": "commonjs" }""" + "\n" + saveToFile(s"${options.outputDir}/package.json", content) + } + + type ParseResult = (List[Statement], List[NuDecl], List[Import], Origin) + private def parse(filename: String, content: String): ParseResult = { + import fastparse._ + import fastparse.Parsed.{Success, Failure} + + val lines = content.splitSane('\n').toIndexedSeq + lines.headOption match { + case S(head) if (head.startsWith("//") && head.endsWith(":d")) => + dbgFiles.add(filename) + typer.dbg = true + case _ => () + } + val fph = new mlscript.FastParseHelpers(content, lines) + val origin = Origin(filename, 1, fph) + val lexer = new NewLexer(origin, throw _, dbg = false) + val tokens = lexer.bracketedTokens + + val parser = new NewParser(origin, tokens, true, throw _, dbg = false, None) { + def doPrintDbg(msg: => String): Unit = if (dbg) println(msg) + } + + val (tu, depList) = parser.parseAll(parser.tuWithImports) + val (definitions, declarations) = tu.entities.partitionMap { + case nt: NuTypeDef if (nt.isDecl) => Right(nt) + case nf: NuFunDef if nf.rhs.isRight => Right(nf) + case t => Left(t) + } + + (definitions, declarations, depList, origin) + } + + private def packTopModule(moduleName: Option[String], content: String) = + moduleName.fold(content)(moduleName => + s"export declare module $moduleName {\n" + + content.splitSane('\n').toIndexedSeq.filter(!_.isEmpty()).map(line => s" $line").reduceLeft(_ + "\n" + _) + + "\n}\n" + ) + + private def parseAndRun[Res](filename: String, f: (ParseResult) => Res): Res = readFile(filename) match { + case Some(content) => f(parse(filename, content)) + case _ => + throw + ErrorReport(msg"Cannot open file $filename" -> None :: Nil, true, Diagnostic.Compilation) + } + + private def extractSig(filename: String, moduleName: String): TypingUnit = + parseAndRun(filename, { + case (_, declarations, _, origin) => TypingUnit( + NuTypeDef(Mod, TypeName(moduleName), Nil, N, N, N, Nil, N, N, TypingUnit(declarations))(S(Loc(0, 1, origin)), N, N) :: Nil) + }) + + // If the current file is es5.mlsi, we allow overriding builtin type(like String and Object) + private def `type`(tu: TypingUnit, isES5: Boolean, errOutput: String => Unit)( + implicit ctx: Ctx, + raise: Raise, + extrCtx: Opt[typer.ExtrCtx], + vars: Map[Str, typer.SimpleType] + ) = try { + val tpd = typer.typeTypingUnit(tu, N, isES5) + val sim = SimplifyPipeline(tpd, pol = S(true))(ctx) + val r = typer.expandType(sim) + r + } catch { + case t: Throwable => + totalTypeErrors += 1 + errOutput(t.toString()) + mlscript.Bot + } + + private lazy val jsBuiltinDecs = Driver.jsBuiltinPaths.map(path => parseAndRun(s"${options.includePath}/$path", { + case (_, declarations, _, _) => declarations + })) + + // Check if generated ts interfaces are correct + private def checkTSInterface(file: FileInfo, writer: JSWriter): Unit = parse(file.filename, writer.getContent) match { + case (_, declarations, imports, origin) => + var ctx: Ctx = Ctx.init + val extrCtx: Opt[typer.ExtrCtx] = N + val vars: Map[Str, typer.SimpleType] = Map.empty + initTyper(ctx, noRedundantRaise, extrCtx, vars) + val reportRaise = (diag: Diagnostic) => report(diag, writer.writeErr) + val tu = TypingUnit(declarations) + imports.foreach(d => importModule(file.`import`(d.path))(ctx, extrCtx, vars)) + `type`(tu, false, writer.writeErr)(ctx, reportRaise, extrCtx, vars) + } + + private def initTyper( + implicit ctx: Ctx, + raise: Raise, + extrCtx: Opt[typer.ExtrCtx], + vars: Map[Str, typer.SimpleType] + ) = jsBuiltinDecs.foreach(lst => `type`(TypingUnit(lst), true, printErr)) + + // Translate mlscirpt import paths into js import paths + private def resolveJSPath(file: FileInfo, imp: String) = + if (isLocal(imp) && !isMLScirpt(imp)) { // Local ts files: locate by checking tsconfig.json + val tsPath = TypeScript.getOutputFileNames(s"${TSPathResolver.dirname(file.filename)}/$imp", config) + val outputBase = TSPathResolver.dirname(TSPathResolver.normalize(s"${options.outputDir}${file.jsFilename}")) + TSPathResolver.relative(outputBase, tsPath) + } + else imp // Otherwise(mlscript & node_module): use the original name + + private def importModule(file: FileInfo)( + implicit ctx: Ctx, + extrCtx: Opt[typer.ExtrCtx], + vars: Map[Str, typer.SimpleType] + ): List[NuDecl] = + try parseAndRun(s"${options.path}/${file.interfaceFilename}", { + case (_, declarations, imports, _) => + imports.foreach(d => importModule(file.`import`(d.path))) + `type`(TypingUnit(declarations), false, noRedundantOutput)(ctx, noRedundantRaise, extrCtx, vars) + declarations.filter(_.isExported) + }) + catch { // The generated interface code is not supported yet + case _: Throwable if JSFileSystem.exists(file.filename) => // Use the original file + parseAndRun(file.filename, { + case (definitions, declarations, imports, _) => + imports.foreach(d => importModule(file.`import`(d.path))) + val mod = + NuTypeDef(Mod, TypeName(file.moduleName), Nil, N, N, N, Nil, N, N, TypingUnit(definitions ++ declarations))(N, N, N) + `type`(TypingUnit(mod :: Nil), false, noRedundantOutput)(ctx, noRedundantRaise, extrCtx, vars) + mod :: Nil + }) + case _: Throwable => throw ErrorReport(msg"Cannot import file ${file.filename}" -> None :: Nil, true, Diagnostic.Compilation) + } + + private def compile( + file: FileInfo, + exported: Boolean + )( + implicit ctx: Ctx, + extrCtx: Opt[typer.ExtrCtx], + vars: Map[Str, typer.SimpleType], + stack: List[String] + ): Bool = { + if (!isMLScirpt(file.filename)) { // TypeScript + val tsprog = + TSProgram(file, true, options.tsconfig, checkTSInterface, S(gitHelper)) + return tsprog.generate + } + + val mlsiFile = normalize(s"${file.workDir}/${file.interfaceFilename}") + val jsFile = s"${options.outputDir}/${file.jsFilename}" + val mlsiWriter = JSWriter(mlsiFile) + implicit val raise: Raise = (diag: Diagnostic) => report(diag, mlsiWriter.writeErr) + parseAndRun(file.filename, { + case (definitions, declarations, imports, _) => { + val (cycleList, otherList) = imports.filter(dep => { + val depFile = file.`import`(dep.path) + if (depFile.filename === file.filename) { + totalErrors += 1 + mlsiWriter.writeErr(s"Cannot import ${file.filename} from itself") + false + } + else if (stack.contains(depFile.filename) && !dep.weak) { + totalErrors += 1 + mlsiWriter.writeErr(s"Use `weak import` to break the cycle dependency `import \"${dep.path}\"`") + false + } + else true + }).partitionMap { dep => { + val depFile = file.`import`(dep.path) + if (stack.contains(depFile.filename)) L(depFile) + else R(dep.path) + } } + + val cycleSigs = cycleList.foldLeft(Ls[TypingUnit]())((sigs, file) => { + importedModule += file.filename + sigs :+ extractSig(file.filename, file.moduleName) + }) + val cycleRecompile = cycleList.foldLeft(false)((r, f) => r || gitHelper.filter(f.filename)) + val dependentRecompile = otherList.foldLeft(cycleRecompile)((r, dp) => { + // We need to create another new context when compiling other files. + // e.g. A -> B, A -> C, B -> D, C -> D, where `->` means "depends on". + // If we forget to add `import "D.mls"` in C, we need to raise an error. + // Keeping using the same environment would not. + var newCtx: Ctx = Ctx.init + val newExtrCtx: Opt[typer.ExtrCtx] = N + val newVars: Map[Str, typer.SimpleType] = Map.empty + initTyper + val newFilename = file.`import`(dp) + importedModule += newFilename.filename + compile(newFilename, true)(newCtx, newExtrCtx, newVars, stack :+ file.filename) || r + }) + + if (!dependentRecompile && !gitHelper.filter(file.filename) && !gitHelper.filter(mlsiFile) && + JSFileSystem.exists(mlsiFile) && JSFileSystem.exists(jsFile)) return false + + System.out.println(s"compiling ${file.filename}...") + val importedSym = (try { otherList.map(d => importModule(file.`import`(d))) } + catch { + case t : Throwable => + totalTypeErrors += 1 + mlsiWriter.writeErr(t.toString()) + Nil + }) ++ cycleSigs.map(tu => tu.entities) + if (file.filename.endsWith(".mls")) { // Only generate js/mlsi files for mls files + val expStr = + cycleSigs.foldLeft("")((s, tu) => s"$s${`type`(tu, false, mlsiWriter.writeErr).show(true)}") + { + dbgWriter = Some(mlsiWriter) + val res = packTopModule(Some(file.moduleName), `type`(TypingUnit(definitions), false, mlsiWriter.writeErr).show(true)) + res + } + val interfaces = otherList.map(s => + Import(file.translateImportToInterface(s), false)).foldRight(expStr)((imp, itf) => s"""import "${imp.path}"\n$itf""") + + mlsiWriter.write(interfaces) + mlsiWriter.close() + if (totalErrors == 0) + generate(Pgrm(definitions), jsFile, file.moduleName, imports.map( + imp => new Import(resolveJSPath(file, imp.path), imp.weak) with ModuleType { + val isESModule = checkESModule(path, TSPathResolver.resolve(file.filename)) + } + ), jsBuiltinDecs ++ importedSym, exported || importedModule(file.filename)) + } + else + `type`(TypingUnit(declarations), false, mlsiWriter.writeErr) // For ts/mlsi files, we only check interface files + + if (dbgFiles.contains(file.filename)) { + typer.dbg = false + dbgFiles.remove(file.filename) + () + } + } + }) + + true + } + + private def generate( + program: Pgrm, + filename: String, + moduleName: String, + imports: Ls[Import with ModuleType], + predefs: Ls[Ls[Statement]], + exported: Boolean + ): Unit = try { + val backend = new JSDriverBackend() + predefs.foreach(pd => backend.declarePredef(Pgrm(pd))) + val lines = backend(program, moduleName, imports, exported, options.commonJS) + val code = lines.mkString("", "\n", "\n") + saveToFile(filename, code) + } catch { + case CodeGenError(err) => + totalErrors += 1 + saveToFile(filename, s"//| codegen error: $err\n") + case t : Throwable => + totalErrors += 1 + saveToFile(filename, s"//| unexpected error: ${t.toString()}\n") + } + + private def report(diag: Diagnostic, output: Str => Unit): Unit = { + diag match { + case ErrorReport(msg, loco, src) => + src match { + case Diagnostic.Lexing => + totalErrors += 1 + case Diagnostic.Parsing => + totalErrors += 1 + case _ => + totalTypeErrors += 1 + } + case WarningReport(msg, loco, src) => () + } + Diagnostic.report(diag, output, 0, false, true) + } +} + +object Driver { + def apply(options: DriverOptions) = new Driver(options) + + private val jsBuiltinPaths = List( + "./ES5.mlsi", + "./Dom.mlsi", + "./Predef.mlsi" + ) + + private def printErr(msg: String): Unit = + System.err.println(msg) + + + + private def saveToFile(filename: String, content: String) = { + val writer = JSWriter(filename) + writer.write(content) + writer.close() + } +} diff --git a/driver/js/src/main/scala/driver/DriverBackend.scala b/driver/js/src/main/scala/driver/DriverBackend.scala new file mode 100644 index 000000000..b3d5eb19b --- /dev/null +++ b/driver/js/src/main/scala/driver/DriverBackend.scala @@ -0,0 +1,77 @@ +package driver + +import mlscript._ +import mlscript.codegen._ +import mlscript.utils._, shorthands._, algorithms._ +import ts2mls.TSPathResolver + +class JSDriverBackend extends JSBackend(allowUnresolvedSymbols = false) { + def oldDefs = false + + def declarePredef(pgrm: Pgrm): Unit = { + val (typeDefs, otherStmts) = pgrm.tops.partitionMap { + case ot: Terms => R(ot) + case fd: NuFunDef => R(fd) + case nd: NuTypeDef => L(nd) + case _ => die + } + + declareNewTypeDefs(typeDefs, N)(topLevelScope) + otherStmts.foreach { + case NuFunDef(_, Var(name), sym, _, _) => + topLevelScope.declareStubValue(name, sym.flatMap(n => S(n.name)))(true) + case _ => () + } + } + + private def generateNewDef(pgrm: Pgrm, topModuleName: Str, exported: Bool, commonJS: Bool): Ls[Str] = { + val (typeDefs, otherStmts) = pgrm.tops.partitionMap { + case ot: Terms => R(ot) + case fd: NuFunDef => R(fd) + case nd: NuTypeDef => L(nd) + case _ => die + } + + val topModule = topLevelScope.declareTopModule(topModuleName, otherStmts, typeDefs, false) + val moduleDecl = translateTopModuleDeclaration(topModule, false, true)(topLevelScope) + val initMethod = moduleDecl.methods.lastOption match { + case Some(JSClassMethod(name, _, _)) => name + case _ => throw new CodeGenError(s"can not get $$init method of module $topModuleName.") + } + val invoke = JSInvoke(JSIdent(topModuleName).member(initMethod), Nil).stmt + val insDecl = JSConstDecl(topModuleName, JSNew(JSClassExpr(moduleDecl))) + + val ins = + if (exported) { + if (commonJS) insDecl :: invoke :: JSExport(R(JSIdent(topModuleName))) :: Nil + else JSExport(L(insDecl)) :: invoke :: Nil + } + else insDecl :: invoke :: Nil + + SourceCode.fromStmts(polyfill.emit() ++ ins).toLines + } + + import JSDriverBackend.ModuleType + + private def translateImport(imp: Import with ModuleType, commonJS: Bool) = { + val path = imp.path + val ext = TSPathResolver.extname(path) + JSImport( + TSPathResolver.basename(path), if (ext.isEmpty()) path else path.replace(ext, ".js"), + imp.isESModule, commonJS + ) + } + + def apply(pgrm: Pgrm, topModuleName: Str, imports: Ls[Import with ModuleType], exported: Bool, commonJS: Bool): Ls[Str] = { + imports.flatMap (imp => { + translateImport(imp, commonJS).toSourceCode.toLines + }) ::: generateNewDef(pgrm, topModuleName, exported, commonJS) + } +} + +object JSDriverBackend { + // N -> mls module, S(true) -> ES module, S(false) -> CommonJS module + trait ModuleType { + val isESModule: Opt[Bool] + } +} diff --git a/driver/js/src/main/scala/driver/DriverHelper.scala b/driver/js/src/main/scala/driver/DriverHelper.scala new file mode 100644 index 000000000..cb53f80a1 --- /dev/null +++ b/driver/js/src/main/scala/driver/DriverHelper.scala @@ -0,0 +1,67 @@ +package driver + +import scala.scalajs.js +import js.Dynamic.{global => g} +import js.DynamicImplicits._ +import js.JSConverters._ +import scala.scalajs.js.annotation._ +import mlscript.utils._ +import ts2mls.TypeScript + +object DriverHelper { + // Do not use fs.watch + // See https://github.com/paulmillr/chokidar + private val watcher = TypeScript.load("chokidar") + + private def run( + filename: String, + workDir: String, + outputDir: String, + tsconfig: Option[String], + commonJS: Boolean, + expectTypeError: Boolean + ): Unit = { + System.out.println(s"start watching $workDir") + val options = DriverOptions(filename, workDir, s"${g.__dirname}/predefs/", outputDir, tsconfig, ".interfaces", commonJS, expectTypeError, false, false) + def compile() = { + val driver = Driver(options) + driver.genPackageJson() + val res = driver.execute + + import DriverResult._ + res match { + case Error => System.err.println(s"Compiling error(s) found in $filename.") + case TypeError => System.err.println(s"Type error(s) found in $filename") + case ExpectError => System.err.println(s"Expect compiling error(s) in $filename") + case ExpectTypeError => System.err.println(s"Expect type error(s) in $filename") + case OK => System.out.println("Finished") + } + } + + compile() + watcher.watch(workDir, js.Dictionary("ignoreInitial" -> true)).on("all", (event: js.Dynamic, file: js.Dynamic) => { + val filename = file.toString() + if ((event.toString() === "change" || event.toString() === "add") && (filename.endsWith("ts") || filename.endsWith("mls"))) + compile() + }) + } + + @JSExportTopLevel("watch") + def watch( + filename: String, + workDir: String, + outputDir: String, + tsconfig: String, + commonJS: Boolean, + expectTypeError: Boolean + ): Unit = run(filename, workDir, outputDir, Some(tsconfig), commonJS, expectTypeError) + + @JSExportTopLevel("watch") + def watch( + filename: String, + workDir: String, + outputDir: String, + commonJS: Boolean, + expectTypeError: Boolean + ): Unit = run(filename, workDir, outputDir, None, commonJS, expectTypeError) +} diff --git a/driver/js/src/main/scala/driver/DriverOptions.scala b/driver/js/src/main/scala/driver/DriverOptions.scala new file mode 100644 index 000000000..5cfdd8d4e --- /dev/null +++ b/driver/js/src/main/scala/driver/DriverOptions.scala @@ -0,0 +1,24 @@ +package driver + +import scala.scalajs.js +import js.Dynamic.{global => g} +import js.DynamicImplicits._ +import js.JSConverters._ + +final case class DriverOptions( + filename: String, // The entry file's name + path: String, // Work path + includePath: String, // Where the predef is + outputDir: String, // JS output path + tsconfig: Option[String], // TS configuration filename (if applicable) + interfaceDir: String, // Interface file output path + commonJS: Boolean, // Generate common js or es5 + expectTypeError: Boolean, // Type errors are expected + expectError: Boolean, // Other errors(e.g., code generation errors) are expected + forceIfNoChange: Boolean // If it is true, recompile everything when there is no change +) + +object DriverResult extends Enumeration { + type DriverResult = Value + val OK, Error, TypeError, ExpectError, ExpectTypeError = Value +} diff --git a/driver/js/src/test/cjsprojects/.interfaces/mlscript/Bar.mlsi b/driver/js/src/test/cjsprojects/.interfaces/mlscript/Bar.mlsi new file mode 100644 index 000000000..c168ea016 --- /dev/null +++ b/driver/js/src/test/cjsprojects/.interfaces/mlscript/Bar.mlsi @@ -0,0 +1,9 @@ +import "../ts/Foo.mlsi" +export declare module Bar { + class Bar() extends Foo { + fun bar: "bar" + fun foo: () -> Str + } + let bf: Bar + unit +} diff --git a/driver/js/src/test/cjsprojects/.interfaces/mlscript/BazBaz.mlsi b/driver/js/src/test/cjsprojects/.interfaces/mlscript/BazBaz.mlsi new file mode 100644 index 000000000..ced6e1d75 --- /dev/null +++ b/driver/js/src/test/cjsprojects/.interfaces/mlscript/BazBaz.mlsi @@ -0,0 +1,12 @@ +import "../ts/Baz.mlsi" +export declare module BazBaz { + class BazBaz() + let bazbaz: BazBaz + error +} +//| ╔══[ERROR] Unsupported parent specification +//| ║ l.3: class BazBaz() extends Baz.Baz(2) +//| ╙── ^^^^^^^^^^ +//| ╔══[ERROR] Type `BazBaz` does not contain member `baz` +//| ║ l.6: bazbaz.baz() +//| ╙── ^^^^ diff --git a/driver/js/src/test/cjsprojects/.interfaces/mlscript/CJS1.mlsi b/driver/js/src/test/cjsprojects/.interfaces/mlscript/CJS1.mlsi new file mode 100644 index 000000000..f9d428e47 --- /dev/null +++ b/driver/js/src/test/cjsprojects/.interfaces/mlscript/CJS1.mlsi @@ -0,0 +1,4 @@ +import "./CJS2.mlsi" +export declare module CJS1 { + unit +} diff --git a/driver/js/src/test/cjsprojects/.interfaces/mlscript/CJS2.mlsi b/driver/js/src/test/cjsprojects/.interfaces/mlscript/CJS2.mlsi new file mode 100644 index 000000000..aaf544379 --- /dev/null +++ b/driver/js/src/test/cjsprojects/.interfaces/mlscript/CJS2.mlsi @@ -0,0 +1,3 @@ +export declare module CJS2 { + fun add: (x: Int, y: Int) -> Int +} diff --git a/driver/js/src/test/cjsprojects/.interfaces/mlscript/Call.mlsi b/driver/js/src/test/cjsprojects/.interfaces/mlscript/Call.mlsi new file mode 100644 index 000000000..7ee6ba4bc --- /dev/null +++ b/driver/js/src/test/cjsprojects/.interfaces/mlscript/Call.mlsi @@ -0,0 +1,4 @@ +import "../ts/Funs.mlsi" +export declare module Call { + unit +} diff --git a/driver/js/src/test/cjsprojects/.interfaces/mlscript/Lodash.mlsi b/driver/js/src/test/cjsprojects/.interfaces/mlscript/Lodash.mlsi new file mode 100644 index 000000000..5d9e47dce --- /dev/null +++ b/driver/js/src/test/cjsprojects/.interfaces/mlscript/Lodash.mlsi @@ -0,0 +1,5 @@ +import "lodash/fp.mlsi" +export declare module Lodash { + fun inc: (x: Int) -> Int + unit +} diff --git a/driver/js/src/test/cjsprojects/.interfaces/ts/Baz.mlsi b/driver/js/src/test/cjsprojects/.interfaces/ts/Baz.mlsi new file mode 100644 index 000000000..bf7bde4fc --- /dev/null +++ b/driver/js/src/test/cjsprojects/.interfaces/ts/Baz.mlsi @@ -0,0 +1,6 @@ +export declare module Baz { + export declare class Baz { + constructor(t: Num) + declare fun baz(): unit + } +} diff --git a/driver/js/src/test/cjsprojects/.interfaces/ts/Foo.mlsi b/driver/js/src/test/cjsprojects/.interfaces/ts/Foo.mlsi new file mode 100644 index 000000000..4e9366ee3 --- /dev/null +++ b/driver/js/src/test/cjsprojects/.interfaces/ts/Foo.mlsi @@ -0,0 +1,3 @@ +export declare class Foo { + declare fun foo(): Str +} diff --git a/driver/js/src/test/cjsprojects/.interfaces/ts/Funs.mlsi b/driver/js/src/test/cjsprojects/.interfaces/ts/Funs.mlsi new file mode 100644 index 000000000..ca2b2ba8f --- /dev/null +++ b/driver/js/src/test/cjsprojects/.interfaces/ts/Funs.mlsi @@ -0,0 +1,3 @@ +declare fun f(x: Num, y: Num): Num +declare fun g(x: Num): Num +export declare fun Funs(): Num diff --git a/driver/js/src/test/cjsprojects/js/mlscript/Bar.js b/driver/js/src/test/cjsprojects/js/mlscript/Bar.js new file mode 100644 index 000000000..f0ad163ad --- /dev/null +++ b/driver/js/src/test/cjsprojects/js/mlscript/Bar.js @@ -0,0 +1,35 @@ +const Foo = require("../ts/Foo.js") + +const Bar = new class Bar { + #Bar; + constructor() { + } + get Bar() { + const qualifier = this; + if (this.#Bar === undefined) { + class Bar extends Foo { + constructor() { + super(); + } + get bar() { + return "bar"; + } + static + unapply(x) { + return []; + } + }; + this.#Bar = (() => Object.freeze(new Bar())); + this.#Bar.class = Bar; + this.#Bar.unapply = Bar.unapply; + } + return this.#Bar; + } + $init() { + const qualifier = this; + const bf = qualifier.Bar(); + console.log(bf.bar); + console.log(bf.foo()); + } +}; +Bar.$init(); diff --git a/driver/js/src/test/cjsprojects/js/mlscript/BazBaz.js b/driver/js/src/test/cjsprojects/js/mlscript/BazBaz.js new file mode 100644 index 000000000..f9d70cfda --- /dev/null +++ b/driver/js/src/test/cjsprojects/js/mlscript/BazBaz.js @@ -0,0 +1,31 @@ +const Baz = require("../ts/Baz.js") + +const BazBaz = new class BazBaz { + #BazBaz; + constructor() { + } + get BazBaz() { + const qualifier = this; + if (this.#BazBaz === undefined) { + class BazBaz extends Baz.Baz { + constructor() { + super(2); + } + static + unapply(x) { + return []; + } + }; + this.#BazBaz = (() => Object.freeze(new BazBaz())); + this.#BazBaz.class = BazBaz; + this.#BazBaz.unapply = BazBaz.unapply; + } + return this.#BazBaz; + } + $init() { + const qualifier = this; + const bazbaz = qualifier.BazBaz(); + bazbaz.baz(); + } +}; +BazBaz.$init(); diff --git a/driver/js/src/test/cjsprojects/js/mlscript/CJS1.js b/driver/js/src/test/cjsprojects/js/mlscript/CJS1.js new file mode 100644 index 000000000..8da9c92f0 --- /dev/null +++ b/driver/js/src/test/cjsprojects/js/mlscript/CJS1.js @@ -0,0 +1,10 @@ +const CJS2 = require("./CJS2.js") + +const CJS1 = new class CJS1 { + constructor() { + } + $init() { + console.log(CJS2.add(42, 24)); + } +}; +CJS1.$init(); diff --git a/driver/js/src/test/cjsprojects/js/mlscript/CJS2.js b/driver/js/src/test/cjsprojects/js/mlscript/CJS2.js new file mode 100644 index 000000000..6cbf1b1ee --- /dev/null +++ b/driver/js/src/test/cjsprojects/js/mlscript/CJS2.js @@ -0,0 +1,10 @@ +const CJS2 = new class CJS2 { + constructor() { + } + add(x, y) { + return x + y; + } + $init() {} +}; +CJS2.$init(); +module.exports = CJS2; diff --git a/driver/js/src/test/cjsprojects/js/mlscript/Call.js b/driver/js/src/test/cjsprojects/js/mlscript/Call.js new file mode 100644 index 000000000..f03b0168f --- /dev/null +++ b/driver/js/src/test/cjsprojects/js/mlscript/Call.js @@ -0,0 +1 @@ +//| codegen error: unresolved symbol g diff --git a/driver/js/src/test/cjsprojects/js/mlscript/Lodash.js b/driver/js/src/test/cjsprojects/js/mlscript/Lodash.js new file mode 100644 index 000000000..bc30c2f4b --- /dev/null +++ b/driver/js/src/test/cjsprojects/js/mlscript/Lodash.js @@ -0,0 +1,18 @@ +const fp = require("lodash/fp") + +const Lodash = new class Lodash { + constructor() { + } + inc(x) { + return x + 1; + } + $init() { + const qualifier = this; + console.log(fp.map(qualifier.inc)([ + 1, + 2, + 3 + ])); + } +}; +Lodash.$init(); diff --git a/driver/js/src/test/cjsprojects/js/package.json b/driver/js/src/test/cjsprojects/js/package.json new file mode 100644 index 000000000..a3c15a7a6 --- /dev/null +++ b/driver/js/src/test/cjsprojects/js/package.json @@ -0,0 +1 @@ +{ "type": "commonjs" } diff --git a/driver/js/src/test/cjsprojects/mlscript/Bar.mls b/driver/js/src/test/cjsprojects/mlscript/Bar.mls new file mode 100644 index 000000000..c767f5021 --- /dev/null +++ b/driver/js/src/test/cjsprojects/mlscript/Bar.mls @@ -0,0 +1,9 @@ +import "../ts/Foo.ts" + +class Bar() extends Foo { + fun bar = "bar" +} + +let bf = Bar() +console.log(bf.bar) +console.log(bf.foo()) diff --git a/driver/js/src/test/cjsprojects/mlscript/BazBaz.mls b/driver/js/src/test/cjsprojects/mlscript/BazBaz.mls new file mode 100644 index 000000000..db1796717 --- /dev/null +++ b/driver/js/src/test/cjsprojects/mlscript/BazBaz.mls @@ -0,0 +1,6 @@ +import "../ts/Baz.ts" + +class BazBaz() extends Baz.Baz(2) + +let bazbaz = BazBaz() +bazbaz.baz() diff --git a/driver/js/src/test/cjsprojects/mlscript/CJS1.mls b/driver/js/src/test/cjsprojects/mlscript/CJS1.mls new file mode 100644 index 000000000..78c509802 --- /dev/null +++ b/driver/js/src/test/cjsprojects/mlscript/CJS1.mls @@ -0,0 +1,2 @@ +import "./CJS2.mls" +console.log(CJS2.add(42, 24)) diff --git a/driver/js/src/test/cjsprojects/mlscript/CJS2.mls b/driver/js/src/test/cjsprojects/mlscript/CJS2.mls new file mode 100644 index 000000000..53e75068d --- /dev/null +++ b/driver/js/src/test/cjsprojects/mlscript/CJS2.mls @@ -0,0 +1 @@ +export fun add(x: Int, y: Int) = x + y diff --git a/driver/js/src/test/cjsprojects/mlscript/Call.mls b/driver/js/src/test/cjsprojects/mlscript/Call.mls new file mode 100644 index 000000000..af4e0b343 --- /dev/null +++ b/driver/js/src/test/cjsprojects/mlscript/Call.mls @@ -0,0 +1,5 @@ +import "../ts/Funs.ts" + +console.log(Funs()) // ok +console.log(g(5)) // error: g is not exported +console.log(f(1, 2)) // error: f is not exported diff --git a/driver/js/src/test/cjsprojects/mlscript/Lodash.mls b/driver/js/src/test/cjsprojects/mlscript/Lodash.mls new file mode 100644 index 000000000..cac91136b --- /dev/null +++ b/driver/js/src/test/cjsprojects/mlscript/Lodash.mls @@ -0,0 +1,4 @@ +import "lodash/fp" + +fun inc(x: Int) = x + 1 +console.log(fp.map(inc)([1, 2, 3])) diff --git a/driver/js/src/test/cjsprojects/package-lock.json b/driver/js/src/test/cjsprojects/package-lock.json new file mode 100644 index 000000000..85f6be4c8 --- /dev/null +++ b/driver/js/src/test/cjsprojects/package-lock.json @@ -0,0 +1,35 @@ +{ + "name": "cjsprojects", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "dependencies": { + "@types/lodash": "^4.14.195", + "lodash": "^4.17.21" + } + }, + "node_modules/@types/lodash": { + "version": "4.14.195", + "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.195.tgz", + "integrity": "sha512-Hwx9EUgdwf2GLarOjQp5ZH8ZmblzcbTBC2wtQWNKARBSxM9ezRIAUpeDTgoQRAFB0+8CNWXVA9+MaSOzOF3nPg==" + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + } + }, + "dependencies": { + "@types/lodash": { + "version": "4.14.195", + "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.195.tgz", + "integrity": "sha512-Hwx9EUgdwf2GLarOjQp5ZH8ZmblzcbTBC2wtQWNKARBSxM9ezRIAUpeDTgoQRAFB0+8CNWXVA9+MaSOzOF3nPg==" + }, + "lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + } + } +} diff --git a/driver/js/src/test/cjsprojects/package.json b/driver/js/src/test/cjsprojects/package.json new file mode 100644 index 000000000..19f9fec2d --- /dev/null +++ b/driver/js/src/test/cjsprojects/package.json @@ -0,0 +1,7 @@ +{ + "dependencies": { + "@types/lodash": "^4.14.195", + "lodash": "^4.17.21" + }, + "module": "commonJS" +} diff --git a/driver/js/src/test/cjsprojects/ts/Baz.ts b/driver/js/src/test/cjsprojects/ts/Baz.ts new file mode 100644 index 000000000..16c5af51a --- /dev/null +++ b/driver/js/src/test/cjsprojects/ts/Baz.ts @@ -0,0 +1,16 @@ +class Baz { + #times + constructor(t: number) { + this.#times = t; + } + + baz() { + for (let i = 0; i < this.#times; ++i) { + console.log("baz") + } + } +} + +export = { + Baz: Baz +} diff --git a/driver/js/src/test/cjsprojects/ts/Foo.ts b/driver/js/src/test/cjsprojects/ts/Foo.ts new file mode 100644 index 000000000..9b47306cc --- /dev/null +++ b/driver/js/src/test/cjsprojects/ts/Foo.ts @@ -0,0 +1,7 @@ +class Foo { + foo() { + return "foo"; + } +} + +export = Foo diff --git a/driver/js/src/test/cjsprojects/ts/Funs.ts b/driver/js/src/test/cjsprojects/ts/Funs.ts new file mode 100644 index 000000000..126229d48 --- /dev/null +++ b/driver/js/src/test/cjsprojects/ts/Funs.ts @@ -0,0 +1,13 @@ +function f(x: number, y: number) { + return x + y; +} + +function g(x: number) { + return f(x, x); +} + +function h() { + return g(42); +} + +export = h; diff --git a/driver/js/src/test/cjsprojects/tsconfig.json b/driver/js/src/test/cjsprojects/tsconfig.json new file mode 100644 index 000000000..086094bd7 --- /dev/null +++ b/driver/js/src/test/cjsprojects/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "outDir": "js/ts", + "module": "CommonJS", + "target": "ES2015", + "moduleResolution": "node", + "allowJs": true, + "esModuleInterop": true + }, + "include": ["ts/*"], +} diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/A.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/A.mlsi new file mode 100644 index 000000000..88b035bb9 --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/A.mlsi @@ -0,0 +1,3 @@ +export declare module A { + class Foo(x: Int) +} diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/B.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/B.mlsi new file mode 100644 index 000000000..372f349d9 --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/B.mlsi @@ -0,0 +1,7 @@ +import "./A.mlsi" +export declare module B { + fun foo: error +} +//| ╔══[ERROR] Access to class member not yet supported +//| ║ l.4: export fun foo = A.Foo(12) +//| ╙── ^^^^ diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/Builtin.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/Builtin.mlsi new file mode 100644 index 000000000..647c21e71 --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/Builtin.mlsi @@ -0,0 +1,5 @@ +export declare module Builtin { + let s: "abc" + let n: Num + unit +} diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/C.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/C.mlsi new file mode 100644 index 000000000..52aeb7646 --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/C.mlsi @@ -0,0 +1,18 @@ +import "./B.mlsi" +export declare module C { + let a: error + let b: error + unit +} +//| ╔══[ERROR] Access to class member not yet supported +//| ║ l.4: let b = A.Foo(0) // not allowed, unless we import "A.mls" +//| ╙── ^^^^ +//| ╔══[ERROR] Type mismatch in field selection: +//| ║ l.5: console.log(a.x) +//| ║ ^^^ +//| ╟── type `error` does not have field 'x' +//| ║ l.3: fun foo: error +//| ║ ^^^^^ +//| ╟── but it flows into reference with expected type `{x: ?x}` +//| ║ l.5: console.log(a.x) +//| ╙── ^ diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/Child.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/Child.mlsi new file mode 100644 index 000000000..e4541216b --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/Child.mlsi @@ -0,0 +1,20 @@ +import "./Parent.mlsi" +export declare module Child { + class Child1(x: Int) + class Child2(y: Int) + let c1: Child1 + let c2: Child2 + unit +} +//| ╔══[ERROR] Unsupported parent specification +//| ║ l.3: class Child1(val x: Int) extends Parent.Parent1(x + 1) +//| ╙── ^^^^^^^^^^^^^^^^^^^^^ +//| ╔══[ERROR] Unsupported parent specification +//| ║ l.4: class Child2(val y: Int) extends Parent.Parent2 +//| ╙── ^^^^^^^^^^^^^^ +//| ╔══[ERROR] Type `Child1` does not contain member `inc` +//| ║ l.8: console.log(c1.inc) +//| ╙── ^^^^ +//| ╔══[ERROR] Type `Child2` does not contain member `x` +//| ║ l.9: console.log(c2.x) +//| ╙── ^^ diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/Cycle1.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/Cycle1.mlsi new file mode 100644 index 000000000..2321bfb1e --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/Cycle1.mlsi @@ -0,0 +1,6 @@ +declare module Cycle2 { + fun g: (x: Int) -> Int +} +export declare module Cycle1 { + fun f: (0 | Int & ~0) -> Int +} diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/Cycle2.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/Cycle2.mlsi new file mode 100644 index 000000000..14d08bb29 --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/Cycle2.mlsi @@ -0,0 +1,5 @@ +import "./Cycle1.mlsi" +export declare module Cycle2 { + fun g: (x: Int) -> Int + () +} diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/Cycle3.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/Cycle3.mlsi new file mode 100644 index 000000000..28b5202d0 --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/Cycle3.mlsi @@ -0,0 +1,7 @@ +export declare module Cycle3 { + fun f: (0 | Int & ~0) -> (114 | error) +} +//| Use `weak import` to break the cycle dependency `import "./Cycle4.mls"` +//| ╔══[ERROR] identifier not found: Cycle4 +//| ║ l.5: _ then Cycle4.g(x - 1) +//| ╙── ^^^^^^ diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/Cycle4.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/Cycle4.mlsi new file mode 100644 index 000000000..89276a837 --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/Cycle4.mlsi @@ -0,0 +1,17 @@ +import "./Cycle3.mlsi" +export declare module Cycle4 { + fun g: (x: Int) -> Int + () +} +//| ╔══[ERROR] Type mismatch in type ascription: +//| ║ l.4: export fun g(x: Int): Int = Cycle3.f(x) +//| ║ ^^^^^^^^^^^ +//| ╟── type `error` is not an instance of `Int` +//| ║ l.2: fun f: (0 | Int & ~0) -> (114 | error) +//| ║ ^^^^^ +//| ╟── but it flows into application with expected type `Int` +//| ║ l.4: export fun g(x: Int): Int = Cycle3.f(x) +//| ║ ^^^^^^^^^^^ +//| ╟── Note: constraint arises from type reference: +//| ║ l.4: export fun g(x: Int): Int = Cycle3.f(x) +//| ╙── ^^^ diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/Debug1.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/Debug1.mlsi new file mode 100644 index 000000000..0a4dee357 --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/Debug1.mlsi @@ -0,0 +1,5 @@ +import "./Debug2.mlsi" +import "./Debug4.mlsi" +export declare module Debug1 { + let x: 42 +} diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/Debug2.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/Debug2.mlsi new file mode 100644 index 000000000..5a687ad0b --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/Debug2.mlsi @@ -0,0 +1,93 @@ +import "./Debug3.mlsi" +export declare module Debug2 { + let y: 42 +} +//| 0. Typing TypingUnit(List(NuFunDef(Some(false),Var(y),None,List(),Left(IntLit(42))))) +//| | 0. Created lazy type info for NuFunDef(Some(false),Var(y),None,List(),Left(IntLit(42))) +//| | Completing let y = 42 +//| | | Type params +//| | | Params +//| | | 0. Typing term IntLit(42) +//| | | 0. : #42 +//| | | CONSTRAIN #42 ) where +//| | Typing unit statements +//| | : None +//| ⬤ Initial: TypedTypingUnit( +//| TypedNuFun(0,NuFunDef(Some(false),Var(y),None,List(),Left(IntLit(42))),#42) +//| None) +//| where: +//| allVarPols: +//| ⬤ Cleaned up: TypedTypingUnit( +//| TypedNuFun(0,NuFunDef(Some(false),Var(y),None,List(),Left(IntLit(42))),#42) +//| None) +//| where: +//| allVarPols: +//| consed: Map() +//| ⬤ Unskid: TypedTypingUnit( +//| TypedNuFun(0,NuFunDef(Some(false),Var(y),None,List(),Left(IntLit(42))),#42) +//| None) +//| where: +//| analyze1[+] #42 +//| [inv] +//| [nums] +//| analyze2[+] #42 +//| [occs] +//| [vars] TreeSet() +//| [rec] Set() +//| [sub] +//| [bounds] +//| [rec] Set() +//| transform[+] #42 () + None +//| ~> #42 +//| ⬤ Type after simplification: TypedTypingUnit( +//| TypedNuFun(0,NuFunDef(Some(false),Var(y),None,List(),Left(IntLit(42))),#42) +//| None) +//| where: +//| allVarPols: +//| normLike[+] TypedTypingUnit( +//| TypedNuFun(0,NuFunDef(Some(false),Var(y),None,List(),Left(IntLit(42))),#42) +//| None) +//| | norm[+] #42 +//| | | DNF: DNF(0, #42{}) +//| | ~> #42 +//| ⬤ Normalized: TypedTypingUnit( +//| TypedNuFun(0,NuFunDef(Some(false),Var(y),None,List(),Left(IntLit(42))),#42) +//| None) +//| where: +//| allVarPols: +//| ⬤ Cleaned up: TypedTypingUnit( +//| TypedNuFun(0,NuFunDef(Some(false),Var(y),None,List(),Left(IntLit(42))),#42) +//| None) +//| where: +//| allVarPols: +//| consed: Map() +//| ⬤ Unskid: TypedTypingUnit( +//| TypedNuFun(0,NuFunDef(Some(false),Var(y),None,List(),Left(IntLit(42))),#42) +//| None) +//| where: +//| analyze1[+] #42 +//| [inv] +//| [nums] +//| analyze2[+] #42 +//| [occs] +//| [vars] TreeSet() +//| [rec] Set() +//| [sub] +//| [bounds] +//| [rec] Set() +//| transform[+] #42 () + None +//| ~> #42 +//| ⬤ Resim: TypedTypingUnit( +//| TypedNuFun(0,NuFunDef(Some(false),Var(y),None,List(),Left(IntLit(42))),#42) +//| None) +//| where: +//| allVarPols: +//| [subs] HashMap() +//| ⬤ Factored: TypedTypingUnit( +//| TypedNuFun(0,NuFunDef(Some(false),Var(y),None,List(),Left(IntLit(42))),#42) +//| None) +//| where: diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/Debug3.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/Debug3.mlsi new file mode 100644 index 000000000..9f98c42c0 --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/Debug3.mlsi @@ -0,0 +1,92 @@ +export declare module Debug3 { + let z: 1 +} +//| 0. Typing TypingUnit(List(NuFunDef(Some(false),Var(z),None,List(),Left(IntLit(1))))) +//| | 0. Created lazy type info for NuFunDef(Some(false),Var(z),None,List(),Left(IntLit(1))) +//| | Completing let z = 1 +//| | | Type params +//| | | Params +//| | | 0. Typing term IntLit(1) +//| | | 0. : #1 +//| | | CONSTRAIN #1 ) where +//| | Typing unit statements +//| | : None +//| ⬤ Initial: TypedTypingUnit( +//| TypedNuFun(0,NuFunDef(Some(false),Var(z),None,List(),Left(IntLit(1))),#1) +//| None) +//| where: +//| allVarPols: +//| ⬤ Cleaned up: TypedTypingUnit( +//| TypedNuFun(0,NuFunDef(Some(false),Var(z),None,List(),Left(IntLit(1))),#1) +//| None) +//| where: +//| allVarPols: +//| consed: Map() +//| ⬤ Unskid: TypedTypingUnit( +//| TypedNuFun(0,NuFunDef(Some(false),Var(z),None,List(),Left(IntLit(1))),#1) +//| None) +//| where: +//| analyze1[+] #1 +//| [inv] +//| [nums] +//| analyze2[+] #1 +//| [occs] +//| [vars] TreeSet() +//| [rec] Set() +//| [sub] +//| [bounds] +//| [rec] Set() +//| transform[+] #1 () + None +//| ~> #1 +//| ⬤ Type after simplification: TypedTypingUnit( +//| TypedNuFun(0,NuFunDef(Some(false),Var(z),None,List(),Left(IntLit(1))),#1) +//| None) +//| where: +//| allVarPols: +//| normLike[+] TypedTypingUnit( +//| TypedNuFun(0,NuFunDef(Some(false),Var(z),None,List(),Left(IntLit(1))),#1) +//| None) +//| | norm[+] #1 +//| | | DNF: DNF(0, #1{}) +//| | ~> #1 +//| ⬤ Normalized: TypedTypingUnit( +//| TypedNuFun(0,NuFunDef(Some(false),Var(z),None,List(),Left(IntLit(1))),#1) +//| None) +//| where: +//| allVarPols: +//| ⬤ Cleaned up: TypedTypingUnit( +//| TypedNuFun(0,NuFunDef(Some(false),Var(z),None,List(),Left(IntLit(1))),#1) +//| None) +//| where: +//| allVarPols: +//| consed: Map() +//| ⬤ Unskid: TypedTypingUnit( +//| TypedNuFun(0,NuFunDef(Some(false),Var(z),None,List(),Left(IntLit(1))),#1) +//| None) +//| where: +//| analyze1[+] #1 +//| [inv] +//| [nums] +//| analyze2[+] #1 +//| [occs] +//| [vars] TreeSet() +//| [rec] Set() +//| [sub] +//| [bounds] +//| [rec] Set() +//| transform[+] #1 () + None +//| ~> #1 +//| ⬤ Resim: TypedTypingUnit( +//| TypedNuFun(0,NuFunDef(Some(false),Var(z),None,List(),Left(IntLit(1))),#1) +//| None) +//| where: +//| allVarPols: +//| [subs] HashMap() +//| ⬤ Factored: TypedTypingUnit( +//| TypedNuFun(0,NuFunDef(Some(false),Var(z),None,List(),Left(IntLit(1))),#1) +//| None) +//| where: diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/Debug4.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/Debug4.mlsi new file mode 100644 index 000000000..fc22a6a63 --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/Debug4.mlsi @@ -0,0 +1,3 @@ +export declare module Debug4 { + let w: "wuwuwu" +} diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/MLS2TheMax.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/MLS2TheMax.mlsi new file mode 100644 index 000000000..c72b45fa8 --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/MLS2TheMax.mlsi @@ -0,0 +1,53 @@ +import "../ts/ReadLine.mlsi" +import "./tools/Concat.mlsi" +export declare module MLS2TheMax { + fun ask: (question: Str) -> Str + class Some[A](value: A) + module None + fun parse: (s: Str) -> (None | Some[Num]) + class Game(name: Str) { + fun check: (x: Num) -> unit + fun loop: unit + let number: 4 + fun shouldContinue: unit + } + fun main: unit + unit +} +//| ╔══[WARNING] Expression in statement position should have type `unit`. +//| ╟── Use the `discard` function to discard non-unit values, making the intent clearer. +//| ╟── Type mismatch in application: +//| ║ l.5: console.log(question) +//| ║ ^^^^^^^^^^^^^^^^^^^^^ +//| ╟── type `unit` does not match type `()` +//| ║ l.20: declare fun log(args0: (anything) | (MutArray[anything])): unit +//| ║ ^^^^ +//| ╟── but it flows into application with expected type `()` +//| ║ l.5: console.log(question) +//| ╙── ^^^^^^^^^^^^^^^^^^^^^ +//| ╔══[WARNING] Expression in statement position should have type `unit`. +//| ╟── Use the `discard` function to discard non-unit values, making the intent clearer. +//| ╟── Type mismatch in if-else block: +//| ║ l.33: if parse(guess) is +//| ║ ^^^^^^^^^^^^^^^ +//| ║ l.34: Some(i) then check(i) +//| ║ ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +//| ║ l.35: _ then console.log("Not a number!") +//| ║ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +//| ╟── type `unit` does not match type `()` +//| ║ l.20: declare fun log(args0: (anything) | (MutArray[anything])): unit +//| ║ ^^^^ +//| ╟── but it flows into application with expected type `()` +//| ║ l.34: Some(i) then check(i) +//| ╙── ^^^^^^^^ +//| ╔══[WARNING] Expression in statement position should have type `unit`. +//| ╟── Use the `discard` function to discard non-unit values, making the intent clearer. +//| ╟── Type mismatch in application: +//| ║ l.41: console.log(Concat.concat3("Hello, ", name, " welcome to the game!")) +//| ║ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +//| ╟── type `unit` does not match type `()` +//| ║ l.20: declare fun log(args0: (anything) | (MutArray[anything])): unit +//| ║ ^^^^ +//| ╟── but it flows into application with expected type `()` +//| ║ l.41: console.log(Concat.concat3("Hello, ", name, " welcome to the game!")) +//| ╙── ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/Mixin1.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/Mixin1.mlsi new file mode 100644 index 000000000..9a7b7c7b9 --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/Mixin1.mlsi @@ -0,0 +1,40 @@ +import "./Mixin2.mlsi" +export declare module Mixin1 { + class Neg[A](expr: A) + mixin EvalNeg() { + super: {eval: 'a -> 'b} + this: {eval: 'c -> Int} + fun eval: (Neg['c] | Object & 'a & ~#Neg) -> (Int | 'b) + } + module MyLang { + fun eval: (Neg['d] | Object & ~#Neg) -> Int + } + fun show: unit + unit + where + 'd <: Neg['d] | Object & ~#Neg +} +//| ╔══[ERROR] Unsupported parent specification +//| ║ l.11: module MyLang extends Mixin2.EvalBase, EvalNeg +//| ╙── ^^^^^^^^^^^^^^^ +//| ╔══[ERROR] Type mismatch in type declaration: +//| ║ l.11: module MyLang extends Mixin2.EvalBase, EvalNeg +//| ║ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +//| ╟── Object of type `anything` does not have field 'eval' +//| ║ l.11: module MyLang extends Mixin2.EvalBase, EvalNeg +//| ║ ^ +//| ╟── Note: constraint arises from field selection: +//| ║ l.8: else super.eval(e) +//| ║ ^^^^^^^^^^ +//| ╟── from reference: +//| ║ l.8: else super.eval(e) +//| ╙── ^^^^^ +//| ╔══[ERROR] Access to class member not yet supported +//| ║ l.14: let program = Mixin2.Add(Mixin2.Lit(48), Neg(Mixin2.Lit(6))) +//| ╙── ^^^^ +//| ╔══[ERROR] Access to class member not yet supported +//| ║ l.14: let program = Mixin2.Add(Mixin2.Lit(48), Neg(Mixin2.Lit(6))) +//| ╙── ^^^^ +//| ╔══[ERROR] Access to class member not yet supported +//| ║ l.14: let program = Mixin2.Add(Mixin2.Lit(48), Neg(Mixin2.Lit(6))) +//| ╙── ^^^^ diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/Mixin2.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/Mixin2.mlsi new file mode 100644 index 000000000..504fcdcb1 --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/Mixin2.mlsi @@ -0,0 +1,11 @@ +export declare module Mixin2 { + class Add[E](lhs: E, rhs: E) + class Lit(n: Int) + fun eval: forall 'a. 'a -> Int + mixin EvalBase() { + this: {eval: 'b -> Int} + fun eval: (Add['b] | Lit) -> Int + } + where + 'a <: Add['a] | Lit +} diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/MyPartialOrder.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/MyPartialOrder.mlsi new file mode 100644 index 000000000..a6f6d6597 --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/MyPartialOrder.mlsi @@ -0,0 +1,10 @@ +import "fp-ts/BoundedMeetSemilattice.mlsi" +export declare module MyPartialOrder { + class MyPartialOrder { + constructor() + } + let order: MyPartialOrder +} +//| ╔══[ERROR] Unsupported parent specification +//| ║ l.3: class MyPartialOrder extends BoundedMeetSemilattice.BoundedMeetSemilattice { +//| ╙── ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/NewTSClass.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/NewTSClass.mlsi new file mode 100644 index 000000000..5571ce86b --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/NewTSClass.mlsi @@ -0,0 +1,11 @@ +import "../ts/MyClass.mlsi" +export declare module NewTSClass { + class Bar() + error +} +//| ╔══[ERROR] Unsupported parent specification +//| ║ l.3: class Bar() extends MyClass.FooClass +//| ╙── ^^^^^^^^^^^^^^^^ +//| ╔══[ERROR] Type `Bar` does not contain member `foo` +//| ║ l.4: Bar().foo() +//| ╙── ^^^^ diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/Opened.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/Opened.mlsi new file mode 100644 index 000000000..c0922ce00 --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/Opened.mlsi @@ -0,0 +1,5 @@ +import "./tools/Inc.mlsi" +export declare module Opened { + fun hello: (x: Int) -> () + () +} diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/Output.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/Output.mlsi new file mode 100644 index 000000000..777bcdc1b --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/Output.mlsi @@ -0,0 +1,5 @@ +import "../ts/ConfigGen.mlsi" +export declare module Output { + let res: Str + () +} diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/Output2.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/Output2.mlsi new file mode 100644 index 000000000..28ed42118 --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/Output2.mlsi @@ -0,0 +1,6 @@ +import "json5.mlsi" +export declare module Output2 { + fun createConfig: (path: Str) -> nothing + let config: nothing + () +} diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/Parent.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/Parent.mlsi new file mode 100644 index 000000000..efe9f31a6 --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/Parent.mlsi @@ -0,0 +1,9 @@ +export declare module Parent { + class Parent1(x: Int) { + fun inc: Int + } + class Parent2 { + constructor() + fun x: 42 + } +} diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/Self.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/Self.mlsi new file mode 100644 index 000000000..7aa505010 --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/Self.mlsi @@ -0,0 +1,4 @@ +export declare module Self { + class Foo() +} +//| Cannot import driver/js/src/test/esprojects/mlscript/Self.mls from itself diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/Simple.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/Simple.mlsi new file mode 100644 index 000000000..ab9238a55 --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/Simple.mlsi @@ -0,0 +1,15 @@ +import "./Opened.mlsi" +export declare module Simple { + mixin B() { + this: {n: 'n} + fun foo: 'n + } + class A(n: Int) { + fun foo: Int + } + let a: A + module C { + let b: 1 + } + () +} diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/TS.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/TS.mlsi new file mode 100644 index 000000000..3f96f47e3 --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/TS.mlsi @@ -0,0 +1,12 @@ +import "../ts/MyPrint.mlsi" +export declare module TS { + let tspt: error + let printer: error + error +} +//| ╔══[ERROR] Access to class member not yet supported +//| ║ l.3: let tspt = MyPrint.DatePrint +//| ╙── ^^^^^^^^^^ +//| ╔══[ERROR] type identifier not found: tspt +//| ║ l.4: let printer = new tspt("love from ts") +//| ╙── ^^^^ diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/TyperDebug.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/TyperDebug.mlsi new file mode 100644 index 000000000..fde3d545d --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/TyperDebug.mlsi @@ -0,0 +1,517 @@ +export declare module TyperDebug { + class A(x: Int) { + fun add: (y: Int) -> Int + } + let aa: A + unit +} +//| 0. Typing TypingUnit(List(NuTypeDef(Cls,TypeName(A),List(),Some(Tup(List((Some(Var(x)),Fld(_,Var(Int)))))),None,None,List(),None,None,TypingUnit(List(NuFunDef(None,Var(add),None,List(),Left(Lam(Tup(List((Some(Var(y)),Fld(_,Var(Int))))),App(Var(+),Tup(List((None,Fld(_,Var(x))), (None,Fld(_,Var(y)))))))))))), NuFunDef(Some(false),Var(aa),None,List(),Left(App(Var(A),Tup(List((None,Fld(_,IntLit(42)))))))), App(Sel(Var(console),Var(log)),Tup(List((None,Fld(_,App(Sel(Var(aa),Var(add)),Tup(List((None,Fld(_,IntLit(6))))))))))))) +//| | 0. Created lazy type info for NuTypeDef(Cls,TypeName(A),List(),Some(Tup(List((Some(Var(x)),Fld(_,Var(Int)))))),None,None,List(),None,None,TypingUnit(List(NuFunDef(None,Var(add),None,List(),Left(Lam(Tup(List((Some(Var(y)),Fld(_,Var(Int))))),App(Var(+),Tup(List((None,Fld(_,Var(x))), (None,Fld(_,Var(y)))))))))))) +//| | 0. Created lazy type info for NuFunDef(Some(false),Var(aa),None,List(),Left(App(Var(A),Tup(List((None,Fld(_,IntLit(42)))))))) +//| | Completing class A(x: Int,) {fun add = (y: Int,) => +(x, y,)} +//| | | Type params +//| | | Typing type TypeName(Int) +//| | | | vars=Map() newDefsInfo=Map() +//| | | | 1. type TypeName(Int) +//| | | | => Int +//| | | => Int ——— +//| | | Params List((Var(x),Int)) +//| | | Done inheriting: Pack({},List(NuParam(Var(x),Int,false)),None,List(),List(),Map()) +//| | | 1. Finalizing inheritance with ({} w/ {x: Int} & #A) <: a536' +//| | | | CONSTRAIN ({} w/ {x: Int} & #A) ) +(x, y,) +//| | | | | Type params +//| | | | | Params +//| | | | | 2. Typing term Lam(Tup(List((Some(Var(y)),Fld(_,Var(Int))))),App(Var(+),Tup(List((None,Fld(_,Var(x))), (None,Fld(_,Var(y))))))) +//| | | | | | 2. Typing pattern Tup(List((Some(Var(y)),Fld(_,Var(Int))))) +//| | | | | | | 2. Typing pattern Asc(Var(y),TypeName(Int)) +//| | | | | | | | Typing type TypeName(Int) +//| | | | | | | | | vars=Map() newDefsInfo=Map() +//| | | | | | | | | 2. type TypeName(Int) +//| | | | | | | | | => Int +//| | | | | | | | => Int ——— +//| | | | | | | 2. : Int +//| | | | | | 2. : (y: Int,) +//| | | | | | 2. Typing term App(Var(+),Tup(List((None,Fld(_,Var(x))), (None,Fld(_,Var(y)))))) +//| | | | | | | 2. Typing term Var(+) +//| | | | | | | 2. : ((Int, Int,) -> Int) +//| | | | | | | 2. Typing term Var(x) +//| | | | | | | 2. : Int +//| | | | | | | 2. Typing term Var(y) +//| | | | | | | 2. : Int +//| | | | | | | CONSTRAIN ((Int, Int,) -> Int) α537'') +//| | | | | | | where +//| | | | | | | 2. C ((Int, Int,) -> Int) α537'') (0) +//| | | | | | | | 2. C ((Int, Int,) -> Int) α537'') (0) +//| | | | | | | | | 2. C ((Int, Int,) -> Int) α537'') (0) +//| | | | | | | | | | 2. C (Int, Int,) α537'') +//| | | | | CONSTRAIN ((y: Int,) -> α537'') Int +//| | | | | 2. C ((y: Int,) -> α537'') α537'') α537'')) where +//| α537'' :> Int +//| | | | Typing unit statements +//| | | | : None +//| | | baseClsImplemMembers List() +//| | | Checking `this` accesses... +//| | | Checking base class implementations against inherited signatures... +//| | | Checking new implementations against inherited signatures... +//| | | | Checking overriding for TypedNuFun(1,NuFunDef(None,Var(add),None,List(),Left(Lam(Tup(List((Some(Var(y)),Fld(_,Var(Int))))),App(Var(+),Tup(List((None,Fld(_,Var(x))), (None,Fld(_,Var(y))))))))),((y: Int,) -> α537'')) against None... +//| | | | Checking overriding for NuParam(Var(x),Int,false) against None... +//| | | Checking new signatures against inherited signatures... +//| | | allMembers Map(add -> TypedNuFun(1,NuFunDef(None,Var(add),None,List(),Left(Lam(Tup(List((Some(Var(y)),Fld(_,Var(Int))))),App(Var(+),Tup(List((None,Fld(_,Var(x))), (None,Fld(_,Var(y))))))))),((y: Int,) -> α537'')), x -> NuParam(Var(x),Int,false)) +//| | | Computing variances of A +//| | | | Trav(+)(((y: Int,) -> α537'')) +//| | | | | Trav(+)(((y: Int,) -> α537'')) +//| | | | | | Trav(+;-)((y: Int,)) +//| | | | | | | Trav(+;-)(Int) +//| | | | | | Trav(+)(α537'') +//| | | | | | | Trav(+;@[+](0))(Int) +//| | | | | | | | Trav(+;@[+](0))(Int) +//| | | | | | | | | Trav(+;@[+](0))(Int) +//| | | | Trav(+)(Int) +//| | | = HashMap(α537'' -> +) +//| | Completed TypedNuCls(0, TypeName(A), +//| List(), +//| Some(List((Var(x),Int))), +//| this: ⊤, +//| (add,TypedNuFun(1,NuFunDef(None,Var(add),None,List(),Left(Lam(Tup(List((Some(Var(y)),Fld(_,Var(Int))))),App(Var(+),Tup(List((None,Fld(_,Var(x))), (None,Fld(_,Var(y))))))))),((y: Int,) -> α537''))) +//| (x,NuParam(Var(x),Int,false)), +//| : ⊤, Set(), Map()) where +//| α537'' :> Int +//| | Completing let aa = A(42,) +//| | | Type params +//| | | Params +//| | | 0. Typing term App(Var(A),Tup(List((None,Fld(_,IntLit(42)))))) +//| | | | 0. Typing term Var(A) +//| | | | | params: Some(List((Var(x),Int))) None +//| | | | 0. : ((x: Int,) -> #A) +//| | | | 0. Typing term IntLit(42) +//| | | | 0. : #42 +//| | | | CONSTRAIN ((x: Int,) -> #A) ,) -> α539) +//| | | | where +//| | | | 0. C ((x: Int,) -> #A) ,) -> α539) (0) +//| | | | | 0. C ((x: Int,) -> #A) ,) -> α539) (0) +//| | | | | | 0. C ((x: Int,) -> #A) ,) -> α539) (0) +//| | | | | | | 0. C (#42,) #A +//| | | 1. C α539 #A +//| | Typing unit statements +//| | | 0. Typing term App(Sel(Var(console),Var(log)),Tup(List((None,Fld(_,App(Sel(Var(aa),Var(add)),Tup(List((None,Fld(_,IntLit(6))))))))))) +//| | | | 0. Typing term Sel(Var(console),Var(log)) +//| | | | | 0. Typing term Var(console) +//| | | | | 0. : ‹∀ 0. Console› +//| | | | | CONSTRAIN ‹∀ 0. Console› ) <: DNF(0, {log: log541}) +//| | | | | | | | | Possible: List({log: log541}) +//| | | | | | | | | 0. A {}∧#Console<> % List() % List() % List() ) & {...} +//| | | | | | | | | | | | | Lookup Console.log : Some(((args0: (Anything | MutArray[Anything]),) -> Unit)) where +//| | | | | | | | | | | | | Fresh[0] Console.log : Some(((args0: (Anything | MutArray[Anything]),) -> Unit)) where Some() +//| | | | | | | | | | | | | & None (from refinement) +//| | | | | | | | | | | | 0. C ((args0: (Anything | MutArray[Anything]),) -> Unit) Unit) #A +//| | | | | | 0. C α539 α537'')›) where +//| α537'' :> Int +//| | | | | | | | | | | | Fresh[0] A.add : Some(‹∀ 1. ((y: Int,) -> α537'')›) where Some( +//| α537'' :> Int) +//| | | | | | | | | | | | & None (from refinement) +//| | | | | | | | | | | 0. C ‹∀ 1. ((y: Int,) -> α537'')› +//| | | | | CONSTRAIN add542 ,) -> α543) +//| | | | | where +//| α537'' :> Int +//| add542 :> ‹∀ 1. ((y: Int,) -> α537'')› +//| | | | | 0. C add542 ,) -> α543) (0) +//| | | | | | 0. C add542 ,) -> α543) (0) +//| | | | | | | NEW add542 UB (0) +//| | | | | | | 0. C ‹∀ 1. ((y: Int,) -> α537'')› ,) -> α543) (2) +//| | | | | | | | 0. C ‹∀ 1. ((y: Int,) -> α537'')› ,) -> α543) (2) +//| | | | | | | | | 0. C ‹∀ 1. ((y: Int,) -> α537'')› ,) -> α543) (2) +//| | | | | | | | | | INST [1] ‹∀ 1. ((y: Int,) -> α537'')› +//| | | | | | | | | | where +//| α537'' :> Int +//| | | | | | | | | | TO [0] ~> ((y: Int,) -> α537_544) +//| | | | | | | | | | where +//| α537_544 :> Int +//| | | | | | | | | | 0. C ((y: Int,) -> α537_544) ,) -> α543) (4) +//| | | | | | | | | | | 0. C ((y: Int,) -> α537_544) ,) -> α543) (4) +//| | | | | | | | | | | | 0. C (#6,) α545) +//| | | | where +//| log541 :> ((args0: (Anything | MutArray[Anything]),) -> Unit) +//| α543 :> Int +//| | | | 0. C log541 α545) (0) +//| | | | | 0. C log541 α545) (0) +//| | | | | | NEW log541 UB (0) +//| | | | | | 0. C ((args0: (Anything | MutArray[Anything]),) -> Unit) α545) (2) +//| | | | | | | 0. C ((args0: (Anything | MutArray[Anything]),) -> Unit) α545) (2) +//| | | | | | | | 0. C ((args0: (Anything | MutArray[Anything]),) -> Unit) α545) (2) +//| | | | | | | | | 0. C ((args0: (Anything | MutArray[Anything]),) -> Unit) α545) (2) +//| | | | | | | | | | 0. C (α543,) α537''))) +//| (x,NuParam(Var(x),Int,false)), +//| : ⊤, Set(), Map()) +//| TypedNuFun(0,NuFunDef(Some(false),Var(aa),None,List(),Left(App(Var(A),Tup(List((None,Fld(_,IntLit(42)))))))),α539) +//| Some(α545)) +//| where: +//| α537'' :> Int +//| α539 :> #A <: {add: add542} +//| add542 :> ‹∀ 1. ((y: Int,) -> α537'')› <: ((#6,) -> α543) +//| α543 :> Int <: (Anything | MutArray[Anything]) +//| α545 :> Unit +//| allVarPols: +α537'', +α539, +α545 +//| Renewed α537'' ~> α537_546'' +//| Renewed α539 ~> α539_547 +//| Renewed α545 ~> α545_548 +//| ⬤ Cleaned up: TypedTypingUnit( +//| TypedNuCls(0, TypeName(A), +//| List(), +//| Some(List((Var(x),Int))), +//| this: ⊤, +//| (add,TypedNuFun(1,NuFunDef(None,Var(add),None,List(),Left(Lam(Tup(List((Some(Var(y)),Fld(_,Var(Int))))),App(Var(+),Tup(List((None,Fld(_,Var(x))), (None,Fld(_,Var(y))))))))),((y: Int,) -> α537_546''))) +//| (x,NuParam(Var(x),Int,false)), +//| : ⊤, Set(), Map()) +//| TypedNuFun(0,NuFunDef(Some(false),Var(aa),None,List(),Left(App(Var(A),Tup(List((None,Fld(_,IntLit(42)))))))),α539_547) +//| Some(α545_548)) +//| where: +//| α537_546'' :> Int +//| α539_547 :> #A +//| α545_548 :> Unit +//| allVarPols: +α537_546'', +α539_547, +α545_548 +//| consed: Map() +//| ⬤ Unskid: TypedTypingUnit( +//| TypedNuCls(0, TypeName(A), +//| List(), +//| Some(List((Var(x),Int))), +//| this: ⊤, +//| (add,TypedNuFun(1,NuFunDef(None,Var(add),None,List(),Left(Lam(Tup(List((Some(Var(y)),Fld(_,Var(Int))))),App(Var(+),Tup(List((None,Fld(_,Var(x))), (None,Fld(_,Var(y))))))))),((y: Int,) -> α537_546''))) +//| (x,NuParam(Var(x),Int,false)), +//| : ⊤, Set(), Map()) +//| TypedNuFun(0,NuFunDef(Some(false),Var(aa),None,List(),Left(App(Var(A),Tup(List((None,Fld(_,IntLit(42)))))))),α539_547) +//| Some(α545_548)) +//| where: +//| α537_546'' :> Int +//| α539_547 :> #A +//| α545_548 :> Unit +//| analyze1[+] Int +//| analyze1[+] ((y: Int,) -> α537_546'') +//| | analyze1[+;-] (y: Int,) +//| | | analyze1[+;-] Int +//| | analyze1[+] α537_546'' +//| | | analyze1[+;@[+](0)] Int +//| analyze1[+] Int +//| analyze1[+;-] ⊤ +//| analyze1[+;-] ⊤ +//| analyze1[+] α539_547 +//| | analyze1[+;@[+](0)] #A +//| analyze1[+] α545_548 +//| | analyze1[+;@[+](0)] Unit +//| [inv] +//| [nums] +α537_546'' 1 ; +α539_547 1 ; +α545_548 1 +//| analyze2[+] Int +//| analyze2[+] ((y: Int,) -> α537_546'') +//| | analyze2[+;-] (y: Int,) +//| | | analyze2[+;-] Int +//| | analyze2[+] α537_546'' +//| | | >> Processing α537_546'' at [+] +//| | | go α537_546'' () +//| | | | go Int (α537_546'') +//| | | >> Occurrences HashSet(α537_546'', Int) +//| | | >>>> occs[+α537_546''] := HashSet(α537_546'', Int) <~ None +//| | | analyze2[+] Int +//| analyze2[+] Int +//| analyze2[+;-] ⊤ +//| analyze2[+;-] ⊤ +//| analyze2[+] α539_547 +//| | >> Processing α539_547 at [+] +//| | go α539_547 () +//| | | go #A (α539_547) +//| | >> Occurrences HashSet(α539_547, #A) +//| | >>>> occs[+α539_547] := HashSet(α539_547, #A) <~ None +//| | analyze2[+] #A +//| analyze2[+] α545_548 +//| | >> Processing α545_548 at [+] +//| | go α545_548 () +//| | | go Unit (α545_548) +//| | >> Occurrences HashSet(α545_548, Unit) +//| | >>>> occs[+α545_548] := HashSet(α545_548, Unit) <~ None +//| | analyze2[+] Unit +//| [occs] +α537_546'' {α537_546'',Int} ; +α539_547 {α539_547,#A} ; +α545_548 {α545_548,Unit} +//| [vars] TreeSet(α537_546'', α539_547, α545_548) +//| [rec] Set() +//| 0[1] α537_546'' +//| 0[1] α539_547 +//| 0[1] α545_548 +//| 1[!] α537_546'' +//| 1[!] α539_547 +//| 1[!] α545_548 +//| [sub] α537_546'' -> None, α539_547 -> None, α545_548 -> None +//| [bounds] +//| α537_546'' :> Int +//| α539_547 :> #A +//| α545_548 :> Unit +//| [rec] Set() +//| transform[+] Int () + None +//| ~> Int +//| transform[+] ((y: Int,) -> α537_546'') () + None +//| | transform[-] (y: Int,) () +;- None +//| | | transform[-] Int () +;- None +//| | | ~> Int +//| | ~> (y: Int,) +//| | transform[+] α537_546'' () + None +//| | | -> bound Some(true) +//| | | transform[+] Int (α537_546'') +;@[+](0) None +//| | | ~> Int +//| | ~> Int +//| ~> ((y: Int,) -> Int) +//| transform[+] Int () + None +//| ~> Int +//| transform[-] ⊤ () +;- None +//| ~> ⊤ +//| transform[+] ⊤ () + None +//| ~> ⊤ +//| transform[+] α539_547 () + None +//| | -> bound Some(true) +//| | transform[+] #A (α539_547) +;@[+](0) None +//| | ~> #A +//| ~> #A +//| transform[+] α545_548 () + None +//| | -> bound Some(true) +//| | transform[+] Unit (α545_548) +;@[+](0) None +//| | ~> Unit +//| ~> Unit +//| ⬤ Type after simplification: TypedTypingUnit( +//| TypedNuCls(0, TypeName(A), +//| List(), +//| Some(List((Var(x),Int))), +//| this: ⊤, +//| (add,TypedNuFun(1,NuFunDef(None,Var(add),None,List(),Left(Lam(Tup(List((Some(Var(y)),Fld(_,Var(Int))))),App(Var(+),Tup(List((None,Fld(_,Var(x))), (None,Fld(_,Var(y))))))))),((y: Int,) -> Int))) +//| (x,NuParam(Var(x),Int,false)), +//| : ⊤, Set(), Map()) +//| TypedNuFun(0,NuFunDef(Some(false),Var(aa),None,List(),Left(App(Var(A),Tup(List((None,Fld(_,IntLit(42)))))))),#A) +//| Some(Unit)) +//| where: +//| allVarPols: +//| normLike[+] TypedTypingUnit( +//| TypedNuCls(0, TypeName(A), +//| List(), +//| Some(List((Var(x),Int))), +//| this: ⊤, +//| (add,TypedNuFun(1,NuFunDef(None,Var(add),None,List(),Left(Lam(Tup(List((Some(Var(y)),Fld(_,Var(Int))))),App(Var(+),Tup(List((None,Fld(_,Var(x))), (None,Fld(_,Var(y))))))))),((y: Int,) -> Int))) +//| (x,NuParam(Var(x),Int,false)), +//| : ⊤, Set(), Map()) +//| TypedNuFun(0,NuFunDef(Some(false),Var(aa),None,List(),Left(App(Var(A),Tup(List((None,Fld(_,IntLit(42)))))))),#A) +//| Some(Unit)) +//| | norm[+] Int +//| | | DNF: DNF(0, #Int{}) +//| | ~> #Int +//| | norm[+] ((y: Int,) -> Int) +//| | | DNF: DNF(0, ((y: Int,) -> Int){}) +//| | | norm[-] (y: Int,) +//| | | | DNF: DNF(0, (y: Int,){}) +//| | | | norm[-] Int +//| | | | | DNF: DNF(0, #Int{}) +//| | | | ~> #Int +//| | | ~> (y: #Int,) +//| | | norm[+] Int +//| | | | DNF: DNF(0, #Int{}) +//| | | ~> #Int +//| | ~> ((y: #Int,) -> #Int) +//| | norm[+] Int +//| | | DNF: DNF(0, #Int{}) +//| | ~> #Int +//| | norm[-] ⊤ +//| | | DNF: DNF(0, ) +//| | ~> ⊤ +//| | norm[+] ⊤ +//| | | DNF: DNF(0, ) +//| | ~> ⊤ +//| | norm[+] #A +//| | | DNF: DNF(0, #A{}) +//| | | rcd2 {} +//| | | typeRef A +//| | | clsFields +//| | ~> A +//| | norm[+] Unit +//| | | DNF: DNF(0, #unit<>{}) +//| | ~> #unit<> +//| ⬤ Normalized: TypedTypingUnit( +//| TypedNuCls(0, TypeName(A), +//| List(), +//| Some(List((Var(x),#Int))), +//| this: ⊤, +//| (add,TypedNuFun(1,NuFunDef(None,Var(add),None,List(),Left(Lam(Tup(List((Some(Var(y)),Fld(_,Var(Int))))),App(Var(+),Tup(List((None,Fld(_,Var(x))), (None,Fld(_,Var(y))))))))),((y: #Int,) -> #Int))) +//| (x,NuParam(Var(x),#Int,false)), +//| : ⊤, Set(), Map()) +//| TypedNuFun(0,NuFunDef(Some(false),Var(aa),None,List(),Left(App(Var(A),Tup(List((None,Fld(_,IntLit(42)))))))),A) +//| Some(#unit<>)) +//| where: +//| allVarPols: +//| ⬤ Cleaned up: TypedTypingUnit( +//| TypedNuCls(0, TypeName(A), +//| List(), +//| Some(List((Var(x),#Int))), +//| this: ⊤, +//| (add,TypedNuFun(1,NuFunDef(None,Var(add),None,List(),Left(Lam(Tup(List((Some(Var(y)),Fld(_,Var(Int))))),App(Var(+),Tup(List((None,Fld(_,Var(x))), (None,Fld(_,Var(y))))))))),((y: #Int,) -> #Int))) +//| (x,NuParam(Var(x),#Int,false)), +//| : ⊤, Set(), Map()) +//| TypedNuFun(0,NuFunDef(Some(false),Var(aa),None,List(),Left(App(Var(A),Tup(List((None,Fld(_,IntLit(42)))))))),A) +//| Some(#unit<>)) +//| where: +//| allVarPols: +//| consed: Map() +//| ⬤ Unskid: TypedTypingUnit( +//| TypedNuCls(0, TypeName(A), +//| List(), +//| Some(List((Var(x),#Int))), +//| this: ⊤, +//| (add,TypedNuFun(1,NuFunDef(None,Var(add),None,List(),Left(Lam(Tup(List((Some(Var(y)),Fld(_,Var(Int))))),App(Var(+),Tup(List((None,Fld(_,Var(x))), (None,Fld(_,Var(y))))))))),((y: #Int,) -> #Int))) +//| (x,NuParam(Var(x),#Int,false)), +//| : ⊤, Set(), Map()) +//| TypedNuFun(0,NuFunDef(Some(false),Var(aa),None,List(),Left(App(Var(A),Tup(List((None,Fld(_,IntLit(42)))))))),A) +//| Some(#unit<>)) +//| where: +//| analyze1[+] #Int +//| analyze1[+] ((y: #Int,) -> #Int) +//| | analyze1[+;-] (y: #Int,) +//| | | analyze1[+;-] #Int +//| | analyze1[+] #Int +//| analyze1[+] #Int +//| analyze1[+;-] ⊤ +//| analyze1[+;-] ⊤ +//| analyze1[+] A +//| analyze1[+] #unit<> +//| [inv] +//| [nums] +//| analyze2[+] #Int +//| analyze2[+] ((y: #Int,) -> #Int) +//| | analyze2[+;-] (y: #Int,) +//| | | analyze2[+;-] #Int +//| | analyze2[+] #Int +//| analyze2[+] #Int +//| analyze2[+;-] ⊤ +//| analyze2[+;-] ⊤ +//| analyze2[+] A +//| analyze2[+] #unit<> +//| [occs] +//| [vars] TreeSet() +//| [rec] Set() +//| [sub] +//| [bounds] +//| [rec] Set() +//| transform[+] #Int () + None +//| ~> #Int +//| transform[+] ((y: #Int,) -> #Int) () + None +//| | transform[-] (y: #Int,) () +;- None +//| | | transform[-] #Int () +;- None +//| | | ~> #Int +//| | ~> (y: #Int,) +//| | transform[+] #Int () + None +//| | ~> #Int +//| ~> ((y: #Int,) -> #Int) +//| transform[+] #Int () + None +//| ~> #Int +//| transform[-] ⊤ () +;- None +//| ~> ⊤ +//| transform[+] ⊤ () + None +//| ~> ⊤ +//| transform[+] A () + None +//| ~> A +//| transform[+] #unit<> () + None +//| ~> #unit<> +//| ⬤ Resim: TypedTypingUnit( +//| TypedNuCls(0, TypeName(A), +//| List(), +//| Some(List((Var(x),#Int))), +//| this: ⊤, +//| (add,TypedNuFun(1,NuFunDef(None,Var(add),None,List(),Left(Lam(Tup(List((Some(Var(y)),Fld(_,Var(Int))))),App(Var(+),Tup(List((None,Fld(_,Var(x))), (None,Fld(_,Var(y))))))))),((y: #Int,) -> #Int))) +//| (x,NuParam(Var(x),#Int,false)), +//| : ⊤, Set(), Map()) +//| TypedNuFun(0,NuFunDef(Some(false),Var(aa),None,List(),Left(App(Var(A),Tup(List((None,Fld(_,IntLit(42)))))))),A) +//| Some(#unit<>)) +//| where: +//| allVarPols: +//| [subs] HashMap() +//| ⬤ Factored: TypedTypingUnit( +//| TypedNuCls(0, TypeName(A), +//| List(), +//| Some(List((Var(x),#Int))), +//| this: ⊤, +//| (add,TypedNuFun(1,NuFunDef(None,Var(add),None,List(),Left(Lam(Tup(List((Some(Var(y)),Fld(_,Var(Int))))),App(Var(+),Tup(List((None,Fld(_,Var(x))), (None,Fld(_,Var(y))))))))),((y: #Int,) -> #Int))) +//| (x,NuParam(Var(x),#Int,false)), +//| : ⊤, Set(), Map()) +//| TypedNuFun(0,NuFunDef(Some(false),Var(aa),None,List(),Left(App(Var(A),Tup(List((None,Fld(_,IntLit(42)))))))),A) +//| Some(#unit<>)) +//| where: diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/tools/Concat.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/tools/Concat.mlsi new file mode 100644 index 000000000..67833f4fa --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/tools/Concat.mlsi @@ -0,0 +1,4 @@ +export declare module Concat { + fun concat2: (Str, Str) -> Str + fun concat3: (Str, Str, Str) -> Str +} diff --git a/driver/js/src/test/esprojects/.interfaces/mlscript/tools/Inc.mlsi b/driver/js/src/test/esprojects/.interfaces/mlscript/tools/Inc.mlsi new file mode 100644 index 000000000..942e575fa --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/mlscript/tools/Inc.mlsi @@ -0,0 +1,3 @@ +export declare module Inc { + fun inc: (x: Int) -> Int +} diff --git a/driver/js/src/test/esprojects/.interfaces/ts/ConfigGen.mlsi b/driver/js/src/test/esprojects/.interfaces/ts/ConfigGen.mlsi new file mode 100644 index 000000000..5826e23f2 --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/ts/ConfigGen.mlsi @@ -0,0 +1,4 @@ +import "json5.mlsi" +export declare module ConfigGen { + export declare fun generate(outDir: Str): Str +} diff --git a/driver/js/src/test/esprojects/.interfaces/ts/MyClass.mlsi b/driver/js/src/test/esprojects/.interfaces/ts/MyClass.mlsi new file mode 100644 index 000000000..bae9f9256 --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/ts/MyClass.mlsi @@ -0,0 +1,5 @@ +export declare module MyClass { + export declare class FooClass { + declare fun foo(): unit + } +} diff --git a/driver/js/src/test/esprojects/.interfaces/ts/MyPrint.mlsi b/driver/js/src/test/esprojects/.interfaces/ts/MyPrint.mlsi new file mode 100644 index 000000000..5cd0a5a98 --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/ts/MyPrint.mlsi @@ -0,0 +1,6 @@ +export declare module MyPrint { + export declare class DatePrint { + constructor(p: Str) + declare fun print(args0: Str): unit + } +} diff --git a/driver/js/src/test/esprojects/.interfaces/ts/ReadLine.mlsi b/driver/js/src/test/esprojects/.interfaces/ts/ReadLine.mlsi new file mode 100644 index 000000000..1288af2b5 --- /dev/null +++ b/driver/js/src/test/esprojects/.interfaces/ts/ReadLine.mlsi @@ -0,0 +1,5 @@ +export declare module ReadLine { + val lines: MutArray[Str] + val i: Num + export declare fun getStrLn(): Str +} diff --git a/driver/js/src/test/esprojects/js/mlscript/A.js b/driver/js/src/test/esprojects/js/mlscript/A.js new file mode 100644 index 000000000..4dad80370 --- /dev/null +++ b/driver/js/src/test/esprojects/js/mlscript/A.js @@ -0,0 +1,27 @@ +export const A = new class A { + #Foo; + constructor() { + } + get Foo() { + const qualifier = this; + if (this.#Foo === undefined) { + class Foo { + #x; + get x() { return this.#x; } + constructor(x) { + this.#x = x; + } + static + unapply(x) { + return [x.#x]; + } + }; + this.#Foo = ((x) => Object.freeze(new Foo(x))); + this.#Foo.class = Foo; + this.#Foo.unapply = Foo.unapply; + } + return this.#Foo; + } + $init() {} +}; +A.$init(); diff --git a/driver/js/src/test/esprojects/js/mlscript/B.js b/driver/js/src/test/esprojects/js/mlscript/B.js new file mode 100644 index 000000000..187ec80d9 --- /dev/null +++ b/driver/js/src/test/esprojects/js/mlscript/B.js @@ -0,0 +1,11 @@ +import { A } from "./A.js" + +export const B = new class B { + constructor() { + } + get foo() { + return A.Foo(12); + } + $init() {} +}; +B.$init(); diff --git a/driver/js/src/test/esprojects/js/mlscript/Builtin.js b/driver/js/src/test/esprojects/js/mlscript/Builtin.js new file mode 100644 index 000000000..74293ca67 --- /dev/null +++ b/driver/js/src/test/esprojects/js/mlscript/Builtin.js @@ -0,0 +1,16 @@ +const Builtin = new class Builtin { + constructor() { + } + $init() { + const s = "abc"; + const n = 42; + console.log(s.charAt(1)); + console.log(s.indexOf("c", undefined)); + console.log(String.fromCharCode(64)); + console.log(n.toString(8)); + console.log(Number["MAX_VALUE"]); + console.log(s.hasOwnProperty("foo")); + console.log(Math.PI); + } +}; +Builtin.$init(); diff --git a/driver/js/src/test/esprojects/js/mlscript/C.js b/driver/js/src/test/esprojects/js/mlscript/C.js new file mode 100644 index 000000000..d1a6e66e9 --- /dev/null +++ b/driver/js/src/test/esprojects/js/mlscript/C.js @@ -0,0 +1 @@ +//| codegen error: unresolved symbol A diff --git a/driver/js/src/test/esprojects/js/mlscript/Child.js b/driver/js/src/test/esprojects/js/mlscript/Child.js new file mode 100644 index 000000000..50eae9c37 --- /dev/null +++ b/driver/js/src/test/esprojects/js/mlscript/Child.js @@ -0,0 +1,58 @@ +import { Parent } from "./Parent.js" + +const Child = new class Child { + #Child1; + #Child2; + constructor() { + } + get Child1() { + const qualifier = this; + if (this.#Child1 === undefined) { + class Child1 extends Parent.Parent1.class { + #x; + get x() { return this.#x; } + constructor(x) { + super(x + 1); + this.#x = x; + } + static + unapply(x) { + return [x.#x]; + } + }; + this.#Child1 = ((x) => Object.freeze(new Child1(x))); + this.#Child1.class = Child1; + this.#Child1.unapply = Child1.unapply; + } + return this.#Child1; + } + get Child2() { + const qualifier = this; + if (this.#Child2 === undefined) { + class Child2 extends Parent.Parent2 { + #y; + get y() { return this.#y; } + constructor(y) { + super(); + this.#y = y; + } + static + unapply(x) { + return [x.#y]; + } + }; + this.#Child2 = ((y) => Object.freeze(new Child2(y))); + this.#Child2.class = Child2; + this.#Child2.unapply = Child2.unapply; + } + return this.#Child2; + } + $init() { + const qualifier = this; + const c1 = qualifier.Child1(2); + const c2 = qualifier.Child2(3); + console.log(c1.inc); + console.log(c2.x); + } +}; +Child.$init(); diff --git a/driver/js/src/test/esprojects/js/mlscript/Cycle1.js b/driver/js/src/test/esprojects/js/mlscript/Cycle1.js new file mode 100644 index 000000000..fec5e0dc2 --- /dev/null +++ b/driver/js/src/test/esprojects/js/mlscript/Cycle1.js @@ -0,0 +1,11 @@ +import { Cycle2 } from "./Cycle2.js" + +export const Cycle1 = new class Cycle1 { + constructor() { + } + f(x) { + return x === 0 ? 114 : Cycle2.g(x - 1); + } + $init() {} +}; +Cycle1.$init(); diff --git a/driver/js/src/test/esprojects/js/mlscript/Cycle2.js b/driver/js/src/test/esprojects/js/mlscript/Cycle2.js new file mode 100644 index 000000000..ef8bda225 --- /dev/null +++ b/driver/js/src/test/esprojects/js/mlscript/Cycle2.js @@ -0,0 +1,17 @@ +import { Cycle1 } from "./Cycle1.js" + +function log(x) { + return console.info(x); +} +export const Cycle2 = new class Cycle2 { + constructor() { + } + g(x) { + return Cycle1.f(x); + } + $init() { + const qualifier = this; + log(qualifier.g(42)); + } +}; +Cycle2.$init(); diff --git a/driver/js/src/test/esprojects/js/mlscript/Cycle3.js b/driver/js/src/test/esprojects/js/mlscript/Cycle3.js new file mode 100644 index 000000000..4841153f9 --- /dev/null +++ b/driver/js/src/test/esprojects/js/mlscript/Cycle3.js @@ -0,0 +1,11 @@ +import { Cycle4 } from "./Cycle4.js" + +export const Cycle3 = new class Cycle3 { + constructor() { + } + f(x) { + return x === 0 ? 114 : Cycle4.g(x - 1); + } + $init() {} +}; +Cycle3.$init(); diff --git a/driver/js/src/test/esprojects/js/mlscript/Cycle4.js b/driver/js/src/test/esprojects/js/mlscript/Cycle4.js new file mode 100644 index 000000000..2809242d2 --- /dev/null +++ b/driver/js/src/test/esprojects/js/mlscript/Cycle4.js @@ -0,0 +1,17 @@ +import { Cycle3 } from "./Cycle3.js" + +function log(x) { + return console.info(x); +} +export const Cycle4 = new class Cycle4 { + constructor() { + } + g(x) { + return Cycle3.f(x); + } + $init() { + const qualifier = this; + log(qualifier.g(42)); + } +}; +Cycle4.$init(); diff --git a/driver/js/src/test/esprojects/js/mlscript/Debug1.js b/driver/js/src/test/esprojects/js/mlscript/Debug1.js new file mode 100644 index 000000000..3ec43241a --- /dev/null +++ b/driver/js/src/test/esprojects/js/mlscript/Debug1.js @@ -0,0 +1,12 @@ +import { Debug2 } from "./Debug2.js" + +import { Debug4 } from "./Debug4.js" + +const Debug1 = new class Debug1 { + constructor() { + } + $init() { + const x = 42; + } +}; +Debug1.$init(); diff --git a/driver/js/src/test/esprojects/js/mlscript/Debug2.js b/driver/js/src/test/esprojects/js/mlscript/Debug2.js new file mode 100644 index 000000000..75a819b3a --- /dev/null +++ b/driver/js/src/test/esprojects/js/mlscript/Debug2.js @@ -0,0 +1,10 @@ +import { Debug3 } from "./Debug3.js" + +export const Debug2 = new class Debug2 { + constructor() { + } + $init() { + const y = 42; + } +}; +Debug2.$init(); diff --git a/driver/js/src/test/esprojects/js/mlscript/Debug3.js b/driver/js/src/test/esprojects/js/mlscript/Debug3.js new file mode 100644 index 000000000..41443207b --- /dev/null +++ b/driver/js/src/test/esprojects/js/mlscript/Debug3.js @@ -0,0 +1,8 @@ +export const Debug3 = new class Debug3 { + constructor() { + } + $init() { + const z = 1; + } +}; +Debug3.$init(); diff --git a/driver/js/src/test/esprojects/js/mlscript/Debug4.js b/driver/js/src/test/esprojects/js/mlscript/Debug4.js new file mode 100644 index 000000000..e01bc3633 --- /dev/null +++ b/driver/js/src/test/esprojects/js/mlscript/Debug4.js @@ -0,0 +1,8 @@ +export const Debug4 = new class Debug4 { + constructor() { + } + $init() { + const w = "wuwuwu"; + } +}; +Debug4.$init(); diff --git a/driver/js/src/test/esprojects/js/mlscript/MLS2TheMax.js b/driver/js/src/test/esprojects/js/mlscript/MLS2TheMax.js new file mode 100644 index 000000000..9c0a70d18 --- /dev/null +++ b/driver/js/src/test/esprojects/js/mlscript/MLS2TheMax.js @@ -0,0 +1,111 @@ +import * as ReadLine from "../my_ts_path/ReadLine.js" + +import { Concat } from "./tools/Concat.js" + +const MLS2TheMax = new class MLS2TheMax { + #Some; + #Game; + #None; + constructor() { + } + ask(question) { + return ((() => { + console.log(question); + return ReadLine.getStrLn(); + })()); + } + parse(s) { + const qualifier = this; + return ((() => { + let i = parseInt(s, undefined); + return isNaN(i) === true ? qualifier.None : qualifier.Some(i); + })()); + } + get main() { + const qualifier = this; + return ((() => { + let name = qualifier.ask("What is your name?"); + console.log(Concat.concat3("Hello, ", name, " welcome to the game!")); + return qualifier.Game(name).loop; + })()); + } + get None() { + const qualifier = this; + if (this.#None === undefined) { + class None {} + this.#None = new None(); + this.#None.class = None; + } + return this.#None; + } + get Some() { + const qualifier = this; + if (this.#Some === undefined) { + class Some { + #value; + constructor(value) { + this.#value = value; + } + static + unapply(x) { + return [x.#value]; + } + }; + this.#Some = ((value) => Object.freeze(new Some(value))); + this.#Some.class = Some; + this.#Some.unapply = Some.unapply; + } + return this.#Some; + } + get Game() { + const qualifier = this; + if (this.#Game === undefined) { + class Game { + #number; + #name; + constructor(name) { + this.#name = name; + this.#number = 4; + const number = this.#number; + } + get shouldContinue() { + const name = this.#name; + const qualifier1 = this; + return ((() => { + let ans = qualifier.ask("Do you want to continue?"); + return ans === "y" === true ? qualifier1.loop : console.log("Bye!"); + })()); + } + check(x) { + const name = this.#name; + const qualifier1 = this; + return ((() => { + return x == qualifier1.#number === true ? console.log(Concat.concat2("You guessed right, ", name)) : console.log(Concat.concat2("You guessed wrong, ", name)); + })()); + } + get loop() { + const name = this.#name; + const qualifier1 = this; + return ((() => { + let guess = qualifier.ask(Concat.concat3("Dear ", name, ", please guess a number from 1 to 5")); + ((tmp0) => tmp0 instanceof qualifier.Some.class ? (([i]) => qualifier1.check(i))(qualifier.Some.unapply(tmp0)) : console.log("Not a number!"))(qualifier.parse(guess)); + return qualifier1.shouldContinue; + })()); + } + static + unapply(x) { + return [x.#name]; + } + }; + this.#Game = ((name) => Object.freeze(new Game(name))); + this.#Game.class = Game; + this.#Game.unapply = Game.unapply; + } + return this.#Game; + } + $init() { + const qualifier = this; + qualifier.main; + } +}; +MLS2TheMax.$init(); diff --git a/driver/js/src/test/esprojects/js/mlscript/Mixin1.js b/driver/js/src/test/esprojects/js/mlscript/Mixin1.js new file mode 100644 index 000000000..dab0a577d --- /dev/null +++ b/driver/js/src/test/esprojects/js/mlscript/Mixin1.js @@ -0,0 +1,66 @@ +import { Mixin2 } from "./Mixin2.js" + +const Mixin1 = new class Mixin1 { + #Neg; + #MyLang; + constructor() { + } + get show() { + const qualifier = this; + return ((() => { + let program = Mixin2.Add(Mixin2.Lit(48), qualifier.Neg(Mixin2.Lit(6))); + return console.log(qualifier.MyLang.eval(program)); + })()); + } + EvalNeg(base) { + const qualifier = this; + return (class EvalNeg extends base { + constructor(...rest) { + super(...rest); + } + eval(e) { + const qualifier1 = this; + return ((() => { + return e instanceof qualifier.Neg.class ? (([d]) => 0 - qualifier1.eval(d))(qualifier.Neg.unapply(e)) : super.eval(e); + })()); + } + }); + } + get MyLang() { + const qualifier = this; + if (this.#MyLang === undefined) { + class MyLang extends qualifier.EvalNeg(Mixin2.EvalBase(Object)) { + constructor() { + super(); + } + } + this.#MyLang = new MyLang(); + this.#MyLang.class = MyLang; + } + return this.#MyLang; + } + get Neg() { + const qualifier = this; + if (this.#Neg === undefined) { + class Neg { + #expr; + constructor(expr) { + this.#expr = expr; + } + static + unapply(x) { + return [x.#expr]; + } + }; + this.#Neg = ((expr) => Object.freeze(new Neg(expr))); + this.#Neg.class = Neg; + this.#Neg.unapply = Neg.unapply; + } + return this.#Neg; + } + $init() { + const qualifier = this; + qualifier.show; + } +}; +Mixin1.$init(); diff --git a/driver/js/src/test/esprojects/js/mlscript/Mixin2.js b/driver/js/src/test/esprojects/js/mlscript/Mixin2.js new file mode 100644 index 000000000..c7c707ffb --- /dev/null +++ b/driver/js/src/test/esprojects/js/mlscript/Mixin2.js @@ -0,0 +1,83 @@ +export const Mixin2 = new class Mixin2 { + #Add; + #Lit; + constructor() { + } + eval(e) { + const qualifier = this; + return ((() => { + let a; + return (a = e, a instanceof qualifier.Lit.class ? (([n]) => n)(qualifier.Lit.unapply(e)) : a instanceof qualifier.Add.class ? (([ + l, + r + ]) => qualifier.eval(l) + qualifier.eval(r))(qualifier.Add.unapply(e)) : (() => { + throw new Error("non-exhaustive case expression"); + })()); + })()); + } + EvalBase(base) { + const qualifier = this; + return (class EvalBase extends base { + constructor(...rest) { + super(...rest); + } + eval(e) { + const qualifier1 = this; + return ((() => { + let a; + return (a = e, a instanceof qualifier.Lit.class ? (([n]) => n)(qualifier.Lit.unapply(e)) : a instanceof qualifier.Add.class ? (([ + l, + r + ]) => qualifier1.eval(l) + qualifier1.eval(r))(qualifier.Add.unapply(e)) : (() => { + throw new Error("non-exhaustive case expression"); + })()); + })()); + } + }); + } + get Add() { + const qualifier = this; + if (this.#Add === undefined) { + class Add { + #lhs; + #rhs; + constructor(lhs, rhs) { + this.#lhs = lhs; + this.#rhs = rhs; + } + static + unapply(x) { + return ([ + x.#lhs, + x.#rhs + ]); + } + }; + this.#Add = ((lhs, rhs) => Object.freeze(new Add(lhs, rhs))); + this.#Add.class = Add; + this.#Add.unapply = Add.unapply; + } + return this.#Add; + } + get Lit() { + const qualifier = this; + if (this.#Lit === undefined) { + class Lit { + #n; + constructor(n) { + this.#n = n; + } + static + unapply(x) { + return [x.#n]; + } + }; + this.#Lit = ((n) => Object.freeze(new Lit(n))); + this.#Lit.class = Lit; + this.#Lit.unapply = Lit.unapply; + } + return this.#Lit; + } + $init() {} +}; +Mixin2.$init(); diff --git a/driver/js/src/test/esprojects/js/mlscript/MyPartialOrder.js b/driver/js/src/test/esprojects/js/mlscript/MyPartialOrder.js new file mode 100644 index 000000000..d0f503cbe --- /dev/null +++ b/driver/js/src/test/esprojects/js/mlscript/MyPartialOrder.js @@ -0,0 +1 @@ +//| codegen error: parent BoundedMeetSemilattice not found. diff --git a/driver/js/src/test/esprojects/js/mlscript/NewTSClass.js b/driver/js/src/test/esprojects/js/mlscript/NewTSClass.js new file mode 100644 index 000000000..f13a60738 --- /dev/null +++ b/driver/js/src/test/esprojects/js/mlscript/NewTSClass.js @@ -0,0 +1,30 @@ +import * as MyClass from "../my_ts_path/MyClass.js" + +const NewTSClass = new class NewTSClass { + #Bar; + constructor() { + } + get Bar() { + const qualifier = this; + if (this.#Bar === undefined) { + class Bar extends MyClass.FooClass { + constructor() { + super(); + } + static + unapply(x) { + return []; + } + }; + this.#Bar = (() => Object.freeze(new Bar())); + this.#Bar.class = Bar; + this.#Bar.unapply = Bar.unapply; + } + return this.#Bar; + } + $init() { + const qualifier = this; + qualifier.Bar().foo(); + } +}; +NewTSClass.$init(); diff --git a/driver/js/src/test/esprojects/js/mlscript/Opened.js b/driver/js/src/test/esprojects/js/mlscript/Opened.js new file mode 100644 index 000000000..2e60b26c8 --- /dev/null +++ b/driver/js/src/test/esprojects/js/mlscript/Opened.js @@ -0,0 +1,20 @@ +import { Inc } from "./tools/Inc.js" + +function log(x) { + return console.info(x); +} +export const Opened = new class Opened { + constructor() { + } + hello(x) { + return (log([ + "hello!", + Inc.inc(x) + ])); + } + $init() { + const qualifier = this; + qualifier.hello(114513); + } +}; +Opened.$init(); diff --git a/driver/js/src/test/esprojects/js/mlscript/Output.js b/driver/js/src/test/esprojects/js/mlscript/Output.js new file mode 100644 index 000000000..4e2ed3ad9 --- /dev/null +++ b/driver/js/src/test/esprojects/js/mlscript/Output.js @@ -0,0 +1,14 @@ +import * as ConfigGen from "../my_ts_path/ConfigGen.js" + +function log(x) { + return console.info(x); +} +const Output = new class Output { + constructor() { + } + $init() { + const res = ConfigGen.generate("foo"); + log(res); + } +}; +Output.$init(); diff --git a/driver/js/src/test/esprojects/js/mlscript/Output2.js b/driver/js/src/test/esprojects/js/mlscript/Output2.js new file mode 100644 index 000000000..baf8dc5fa --- /dev/null +++ b/driver/js/src/test/esprojects/js/mlscript/Output2.js @@ -0,0 +1,22 @@ +import json5 from "json5" + +function log(x) { + return console.info(x); +} +const Output2 = new class Output2 { + constructor() { + } + createConfig(path) { + return ((() => { + let options = { outDir: path }; + let config = { compilerOptions: options }; + return json5.stringify(config); + })()); + } + $init() { + const qualifier = this; + const config = qualifier.createConfig("bar"); + log(config); + } +}; +Output2.$init(); diff --git a/driver/js/src/test/esprojects/js/mlscript/Parent.js b/driver/js/src/test/esprojects/js/mlscript/Parent.js new file mode 100644 index 000000000..ac847068d --- /dev/null +++ b/driver/js/src/test/esprojects/js/mlscript/Parent.js @@ -0,0 +1,46 @@ +export const Parent = new class Parent { + #Parent1; + #Parent2; + constructor() { + } + get Parent1() { + const qualifier = this; + if (this.#Parent1 === undefined) { + class Parent1 { + #x; + get x() { return this.#x; } + constructor(x) { + this.#x = x; + } + get inc() { + const x = this.#x; + return x + 1; + } + static + unapply(x) { + return [x.#x]; + } + }; + this.#Parent1 = ((x) => Object.freeze(new Parent1(x))); + this.#Parent1.class = Parent1; + this.#Parent1.unapply = Parent1.unapply; + } + return this.#Parent1; + } + get Parent2() { + const qualifier = this; + if (this.#Parent2 === undefined) { + class Parent2 { + constructor() { + } + get x() { + return 42; + } + }; + this.#Parent2 = Parent2; + } + return this.#Parent2; + } + $init() {} +}; +Parent.$init(); diff --git a/driver/js/src/test/esprojects/js/mlscript/Simple.js b/driver/js/src/test/esprojects/js/mlscript/Simple.js new file mode 100644 index 000000000..cd0551cfb --- /dev/null +++ b/driver/js/src/test/esprojects/js/mlscript/Simple.js @@ -0,0 +1,64 @@ +import { Opened } from "./Opened.js" + +function log(x) { + return console.info(x); +} +const Simple = new class Simple { + #A; + #C; + constructor() { + } + B(base) { + const qualifier = this; + return (class B extends base { + constructor(...rest) { + super(...rest); + } + get foo() { + const qualifier1 = this; + return qualifier1.n; + } + }); + } + get C() { + const qualifier = this; + if (this.#C === undefined) { + class C { + constructor() { + const b = 1; + } + } + this.#C = new C(); + this.#C.class = C; + } + return this.#C; + } + get A() { + const qualifier = this; + if (this.#A === undefined) { + class A extends qualifier.B(Object) { + #n; + get n() { return this.#n; } + constructor(n) { + super(); + this.#n = n; + } + static + unapply(x) { + return [x.#n]; + } + }; + this.#A = ((n) => Object.freeze(new A(n))); + this.#A.class = A; + this.#A.unapply = A.unapply; + } + return this.#A; + } + $init() { + const qualifier = this; + const a = qualifier.A(42); + log(a.foo); + Opened.hello(a.n); + } +}; +Simple.$init(); diff --git a/driver/js/src/test/esprojects/js/mlscript/TS.js b/driver/js/src/test/esprojects/js/mlscript/TS.js new file mode 100644 index 000000000..31358ae1e --- /dev/null +++ b/driver/js/src/test/esprojects/js/mlscript/TS.js @@ -0,0 +1,12 @@ +import * as MyPrint from "../my_ts_path/MyPrint.js" + +const TS = new class TS { + constructor() { + } + $init() { + const tspt = MyPrint.DatePrint; + const printer = new tspt("love from ts"); + printer.print("hello world!"); + } +}; +TS.$init(); diff --git a/driver/js/src/test/esprojects/js/mlscript/TyperDebug.js b/driver/js/src/test/esprojects/js/mlscript/TyperDebug.js new file mode 100644 index 000000000..8f3256318 --- /dev/null +++ b/driver/js/src/test/esprojects/js/mlscript/TyperDebug.js @@ -0,0 +1,34 @@ +const TyperDebug = new class TyperDebug { + #A; + constructor() { + } + get A() { + const qualifier = this; + if (this.#A === undefined) { + class A { + #x; + constructor(x) { + this.#x = x; + } + add(y) { + const x = this.#x; + return x + y; + } + static + unapply(x) { + return [x.#x]; + } + }; + this.#A = ((x) => Object.freeze(new A(x))); + this.#A.class = A; + this.#A.unapply = A.unapply; + } + return this.#A; + } + $init() { + const qualifier = this; + const aa = qualifier.A(42); + console.log(aa.add(6)); + } +}; +TyperDebug.$init(); diff --git a/driver/js/src/test/esprojects/js/mlscript/tools/Concat.js b/driver/js/src/test/esprojects/js/mlscript/tools/Concat.js new file mode 100644 index 000000000..b919e039b --- /dev/null +++ b/driver/js/src/test/esprojects/js/mlscript/tools/Concat.js @@ -0,0 +1,20 @@ +function concat(x, y) { + if (arguments.length === 2) { + return x + y; + } else { + return (y) => x + y; + } +} +export const Concat = new class Concat { + constructor() { + } + concat2(s1, s2) { + return concat(s1)(s2); + } + concat3(s1, s2, s3) { + const qualifier = this; + return qualifier.concat2(qualifier.concat2(s1, s2), s3); + } + $init() {} +}; +Concat.$init(); diff --git a/driver/js/src/test/esprojects/js/mlscript/tools/Inc.js b/driver/js/src/test/esprojects/js/mlscript/tools/Inc.js new file mode 100644 index 000000000..02fd1ff82 --- /dev/null +++ b/driver/js/src/test/esprojects/js/mlscript/tools/Inc.js @@ -0,0 +1,9 @@ +export const Inc = new class Inc { + constructor() { + } + inc(x) { + return x + 1; + } + $init() {} +}; +Inc.$init(); diff --git a/driver/js/src/test/esprojects/js/package.json b/driver/js/src/test/esprojects/js/package.json new file mode 100644 index 000000000..5ffd9800b --- /dev/null +++ b/driver/js/src/test/esprojects/js/package.json @@ -0,0 +1 @@ +{ "type": "module" } diff --git a/driver/js/src/test/esprojects/mlscript/A.mls b/driver/js/src/test/esprojects/mlscript/A.mls new file mode 100644 index 000000000..6dab6149f --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/A.mls @@ -0,0 +1 @@ +export class Foo(val x: Int) {} diff --git a/driver/js/src/test/esprojects/mlscript/B.mls b/driver/js/src/test/esprojects/mlscript/B.mls new file mode 100644 index 000000000..51c99d11a --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/B.mls @@ -0,0 +1,4 @@ +import "./A.mls" + +// FIXME: access to class member not yet supported +export fun foo = A.Foo(12) diff --git a/driver/js/src/test/esprojects/mlscript/Builtin.mls b/driver/js/src/test/esprojects/mlscript/Builtin.mls new file mode 100644 index 000000000..a0cbe8986 --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/Builtin.mls @@ -0,0 +1,10 @@ +let s = "abc" +let n: Num = 42 + +console.log(s.charAt(1)) +console.log(s.indexOf("c", undefined)) +console.log(String.fromCharCode(64)) +console.log(n.toString(8)) +console.log(Number.MAX_VALUE) +console.log(s.hasOwnProperty("foo")) +console.log(Math.PI) diff --git a/driver/js/src/test/esprojects/mlscript/C.mls b/driver/js/src/test/esprojects/mlscript/C.mls new file mode 100644 index 000000000..207de4e8c --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/C.mls @@ -0,0 +1,5 @@ +import "./B.mls" + +let a = B.foo +let b = A.Foo(0) // not allowed, unless we import "A.mls" +console.log(a.x) diff --git a/driver/js/src/test/esprojects/mlscript/Child.mls b/driver/js/src/test/esprojects/mlscript/Child.mls new file mode 100644 index 000000000..7af292ace --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/Child.mls @@ -0,0 +1,9 @@ +import "./Parent.mls" + +class Child1(val x: Int) extends Parent.Parent1(x + 1) +class Child2(val y: Int) extends Parent.Parent2 + +let c1 = Child1(2) +let c2 = Child2(3) +console.log(c1.inc) +console.log(c2.x) diff --git a/driver/js/src/test/esprojects/mlscript/Cycle1.mls b/driver/js/src/test/esprojects/mlscript/Cycle1.mls new file mode 100644 index 000000000..29e843ee0 --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/Cycle1.mls @@ -0,0 +1,5 @@ +weak import "./Cycle2.mls" + +export fun f(x) = if x is + 0 then 114 + _ then Cycle2.g(x - 1) diff --git a/driver/js/src/test/esprojects/mlscript/Cycle2.mls b/driver/js/src/test/esprojects/mlscript/Cycle2.mls new file mode 100644 index 000000000..c45f4adc8 --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/Cycle2.mls @@ -0,0 +1,6 @@ +import "./Cycle1.mls" + +export fun g(x: Int): Int +export fun g(x: Int): Int = Cycle1.f(x) + +log(g(42)) diff --git a/driver/js/src/test/esprojects/mlscript/Cycle3.mls b/driver/js/src/test/esprojects/mlscript/Cycle3.mls new file mode 100644 index 000000000..8f003642e --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/Cycle3.mls @@ -0,0 +1,5 @@ +import "./Cycle4.mls" + +export fun f(x) = if x is + 0 then 114 + _ then Cycle4.g(x - 1) diff --git a/driver/js/src/test/esprojects/mlscript/Cycle4.mls b/driver/js/src/test/esprojects/mlscript/Cycle4.mls new file mode 100644 index 000000000..d8b32f4b2 --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/Cycle4.mls @@ -0,0 +1,6 @@ +import "./Cycle3.mls" + +export fun g(x: Int): Int +export fun g(x: Int): Int = Cycle3.f(x) + +log(g(42)) diff --git a/driver/js/src/test/esprojects/mlscript/Debug1.mls b/driver/js/src/test/esprojects/mlscript/Debug1.mls new file mode 100644 index 000000000..070909968 --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/Debug1.mls @@ -0,0 +1,4 @@ +import "./Debug2.mls" +import "./Debug4.mls" + +let x = 42 diff --git a/driver/js/src/test/esprojects/mlscript/Debug2.mls b/driver/js/src/test/esprojects/mlscript/Debug2.mls new file mode 100644 index 000000000..45248da6b --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/Debug2.mls @@ -0,0 +1,5 @@ +//:d + +import "./Debug3.mls" + +let y = 42 diff --git a/driver/js/src/test/esprojects/mlscript/Debug3.mls b/driver/js/src/test/esprojects/mlscript/Debug3.mls new file mode 100644 index 000000000..0e6ac214b --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/Debug3.mls @@ -0,0 +1 @@ +let z = 1 diff --git a/driver/js/src/test/esprojects/mlscript/Debug4.mls b/driver/js/src/test/esprojects/mlscript/Debug4.mls new file mode 100644 index 000000000..c5193957c --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/Debug4.mls @@ -0,0 +1 @@ +let w = "wuwuwu" diff --git a/driver/js/src/test/esprojects/mlscript/MLS2TheMax.mls b/driver/js/src/test/esprojects/mlscript/MLS2TheMax.mls new file mode 100644 index 000000000..f12dfd48a --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/MLS2TheMax.mls @@ -0,0 +1,44 @@ +import "../ts/ReadLine.ts" +import "./tools/Concat.mls" + +fun ask(question: Str) = + console.log(question) + ReadLine.getStrLn() + +class Some[A](value: A) +module None + +fun parse(s: Str) = + let i = parseInt(s, undefined) + if isNaN(i) + then None + else Some(i) + +class Game(name: Str) { + let number = 4 // fixed, or we can not apply diff test + + fun shouldContinue = + let ans = ask("Do you want to continue?") + if + ans === "y" then loop + _ then console.log("Bye!") + + fun check(x: Num) = + if + x == number then console.log(Concat.concat2("You guessed right, ", name)) + _ then console.log(Concat.concat2("You guessed wrong, ", name)) + + fun loop = + let guess = ask(Concat.concat3("Dear ", name, ", please guess a number from 1 to 5")) + if parse(guess) is + Some(i) then check(i) + _ then console.log("Not a number!") + shouldContinue +} + +fun main = + let name = ask("What is your name?") + console.log(Concat.concat3("Hello, ", name, " welcome to the game!")) + Game(name).loop + +main diff --git a/driver/js/src/test/esprojects/mlscript/Mixin1.mls b/driver/js/src/test/esprojects/mlscript/Mixin1.mls new file mode 100644 index 000000000..52d636559 --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/Mixin1.mls @@ -0,0 +1,17 @@ +import "./Mixin2.mls" + +class Neg(expr: A) + +mixin EvalNeg { + fun eval(e) = + if e is Neg(d) then 0 - this.eval(d) + else super.eval(e) +} + +module MyLang extends Mixin2.EvalBase, EvalNeg + +fun show = + let program = Mixin2.Add(Mixin2.Lit(48), Neg(Mixin2.Lit(6))) + console.log(MyLang.eval(program)) + +show diff --git a/driver/js/src/test/esprojects/mlscript/Mixin2.mls b/driver/js/src/test/esprojects/mlscript/Mixin2.mls new file mode 100644 index 000000000..d860a3b4b --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/Mixin2.mls @@ -0,0 +1,14 @@ +export class Add(lhs: E, rhs: E) +export class Lit(n: Int) + +fun eval(e) = + if e is + Lit(n) then n + Add(l, r) then eval(l) + eval(r) + +export mixin EvalBase { + fun eval(e) = + if e is + Lit(n) then n: Int + Add(l, r) then this.eval(l) + this.eval(r) +} diff --git a/driver/js/src/test/esprojects/mlscript/MyPartialOrder.mls b/driver/js/src/test/esprojects/mlscript/MyPartialOrder.mls new file mode 100644 index 000000000..da4b31214 --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/MyPartialOrder.mls @@ -0,0 +1,7 @@ +import "fp-ts/BoundedMeetSemilattice" + +class MyPartialOrder extends BoundedMeetSemilattice.BoundedMeetSemilattice { + // TODO: implement +} + +let order = new MyPartialOrder() diff --git a/driver/js/src/test/esprojects/mlscript/NewTSClass.mls b/driver/js/src/test/esprojects/mlscript/NewTSClass.mls new file mode 100644 index 000000000..8b228b064 --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/NewTSClass.mls @@ -0,0 +1,4 @@ +import "../ts/MyClass.ts" + +class Bar() extends MyClass.FooClass +Bar().foo() diff --git a/driver/js/src/test/esprojects/mlscript/Opened.mls b/driver/js/src/test/esprojects/mlscript/Opened.mls new file mode 100644 index 000000000..5d76d7e83 --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/Opened.mls @@ -0,0 +1,5 @@ +import "./tools/Inc.mls" + +export fun hello(x: Int) = log(["hello!", Inc.inc(x)]) + +hello(114513) diff --git a/driver/js/src/test/esprojects/mlscript/Output.mls b/driver/js/src/test/esprojects/mlscript/Output.mls new file mode 100644 index 000000000..dddee4c31 --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/Output.mls @@ -0,0 +1,4 @@ +import "../ts/ConfigGen.ts" + +let res = ConfigGen.generate("foo") +log(res) diff --git a/driver/js/src/test/esprojects/mlscript/Output2.mls b/driver/js/src/test/esprojects/mlscript/Output2.mls new file mode 100644 index 000000000..841ea16c3 --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/Output2.mls @@ -0,0 +1,9 @@ +import "json5" + +fun createConfig(path: Str) = + let options = { outDir: path } + let config = { compilerOptions: options } + json5.stringify(config) + +let config = createConfig("bar") +log(config) diff --git a/driver/js/src/test/esprojects/mlscript/Parent.mls b/driver/js/src/test/esprojects/mlscript/Parent.mls new file mode 100644 index 000000000..1ae64e579 --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/Parent.mls @@ -0,0 +1,7 @@ +export class Parent1(val x: Int) { + fun inc = x + 1 +} + +export class Parent2 { + fun x = 42 +} diff --git a/driver/js/src/test/esprojects/mlscript/Self.mls b/driver/js/src/test/esprojects/mlscript/Self.mls new file mode 100644 index 000000000..3eeb9c61a --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/Self.mls @@ -0,0 +1,3 @@ +import "./Self.mls" + +class Foo() {} diff --git a/driver/js/src/test/esprojects/mlscript/Simple.mls b/driver/js/src/test/esprojects/mlscript/Simple.mls new file mode 100644 index 000000000..ef341b2e0 --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/Simple.mls @@ -0,0 +1,14 @@ +import "./Opened.mls" + +mixin B { fun foo = this.n } + +class A(val n: Int) extends B +let a = A(42) + +log(a.foo) + +module C { + let b = 1 +} + +Opened.hello(a.n) diff --git a/driver/js/src/test/esprojects/mlscript/TS.mls b/driver/js/src/test/esprojects/mlscript/TS.mls new file mode 100644 index 000000000..3e5324923 --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/TS.mls @@ -0,0 +1,5 @@ +import "../ts/MyPrint.ts" + +let tspt = MyPrint.DatePrint +let printer = new tspt("love from ts") +printer.print("hello world!") diff --git a/driver/js/src/test/esprojects/mlscript/TyperDebug.mls b/driver/js/src/test/esprojects/mlscript/TyperDebug.mls new file mode 100644 index 000000000..0ea6a1503 --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/TyperDebug.mls @@ -0,0 +1,6 @@ +// :d +class A(x: Int) { + fun add(y: Int) = x + y +} +let aa = A(42) +console.log(aa.add(6)) diff --git a/driver/js/src/test/esprojects/mlscript/tools/Concat.mls b/driver/js/src/test/esprojects/mlscript/tools/Concat.mls new file mode 100644 index 000000000..f84f943be --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/tools/Concat.mls @@ -0,0 +1,2 @@ +export fun concat2(s1, s2) = concat(s1)(s2) +export fun concat3(s1, s2, s3) = concat2(concat2(s1, s2), s3) diff --git a/driver/js/src/test/esprojects/mlscript/tools/Inc.mls b/driver/js/src/test/esprojects/mlscript/tools/Inc.mls new file mode 100644 index 000000000..339f71cb8 --- /dev/null +++ b/driver/js/src/test/esprojects/mlscript/tools/Inc.mls @@ -0,0 +1 @@ +export fun inc(x: Int) = x + 1 diff --git a/driver/js/src/test/esprojects/package-lock.json b/driver/js/src/test/esprojects/package-lock.json new file mode 100644 index 000000000..65c3e4dce --- /dev/null +++ b/driver/js/src/test/esprojects/package-lock.json @@ -0,0 +1,41 @@ +{ + "name": "esprojects", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "dependencies": { + "fp-ts": "^2.16.0", + "json5": "^2.2.3" + } + }, + "node_modules/fp-ts": { + "version": "2.16.0", + "resolved": "https://registry.npmjs.org/fp-ts/-/fp-ts-2.16.0.tgz", + "integrity": "sha512-bLq+KgbiXdTEoT1zcARrWEpa5z6A/8b7PcDW7Gef3NSisQ+VS7ll2Xbf1E+xsgik0rWub/8u0qP/iTTjj+PhxQ==" + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + } + }, + "dependencies": { + "fp-ts": { + "version": "2.16.0", + "resolved": "https://registry.npmjs.org/fp-ts/-/fp-ts-2.16.0.tgz", + "integrity": "sha512-bLq+KgbiXdTEoT1zcARrWEpa5z6A/8b7PcDW7Gef3NSisQ+VS7ll2Xbf1E+xsgik0rWub/8u0qP/iTTjj+PhxQ==" + }, + "json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==" + } + } +} diff --git a/driver/js/src/test/esprojects/package.json b/driver/js/src/test/esprojects/package.json new file mode 100644 index 000000000..52643d6b6 --- /dev/null +++ b/driver/js/src/test/esprojects/package.json @@ -0,0 +1,8 @@ +{ + "dependencies": { + "fp-ts": "^2.16.0", + "json5": "^2.2.3" + }, + "module": "es2015", + "type": "module" +} diff --git a/driver/js/src/test/esprojects/ts/ConfigGen.ts b/driver/js/src/test/esprojects/ts/ConfigGen.ts new file mode 100644 index 000000000..d7963ca3c --- /dev/null +++ b/driver/js/src/test/esprojects/ts/ConfigGen.ts @@ -0,0 +1,11 @@ +import json5 from "json5"; + +export function generate(outDir: string) { + const json = { + "compilerOptions": { + "outDir": outDir + } + } + + return json5.stringify(json); +} diff --git a/driver/js/src/test/esprojects/ts/MyClass.ts b/driver/js/src/test/esprojects/ts/MyClass.ts new file mode 100644 index 000000000..6e6efd3f7 --- /dev/null +++ b/driver/js/src/test/esprojects/ts/MyClass.ts @@ -0,0 +1,5 @@ +export class FooClass { + foo() { + console.log("foo") + } +} diff --git a/driver/js/src/test/esprojects/ts/MyPrint.ts b/driver/js/src/test/esprojects/ts/MyPrint.ts new file mode 100644 index 000000000..168ce0eff --- /dev/null +++ b/driver/js/src/test/esprojects/ts/MyPrint.ts @@ -0,0 +1,11 @@ +export class DatePrint { + private prefix: string + constructor(p: string) { + this.prefix = p + } + + print(msg: string) { + let date = new Date(1145141919810) + console.log(`[${this.prefix}] ${msg}. (${date.toLocaleString("en-US", { timeZone: "America/New_York" })})`) + } +} diff --git a/driver/js/src/test/esprojects/ts/ReadLine.ts b/driver/js/src/test/esprojects/ts/ReadLine.ts new file mode 100644 index 000000000..c52aede02 --- /dev/null +++ b/driver/js/src/test/esprojects/ts/ReadLine.ts @@ -0,0 +1,9 @@ +const lines = [ + "Admin", "1", "y", "foo", "y", "4", "n" +] + +let i = 0 + +export function getStrLn(): string { + return lines[i++]; +} diff --git a/driver/js/src/test/esprojects/tsconfig.json b/driver/js/src/test/esprojects/tsconfig.json new file mode 100644 index 000000000..e9fc657b8 --- /dev/null +++ b/driver/js/src/test/esprojects/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "outDir": "js/my_ts_path", + "module": "ES2015", + "target": "ES2015", + "moduleResolution": "node", + "allowJs": true, + "esModuleInterop": true + }, + "include": ["ts/*"], +} diff --git a/driver/js/src/test/output/Bar.check b/driver/js/src/test/output/Bar.check new file mode 100644 index 000000000..128976523 --- /dev/null +++ b/driver/js/src/test/output/Bar.check @@ -0,0 +1,2 @@ +bar +foo diff --git a/driver/js/src/test/output/BazBaz.check b/driver/js/src/test/output/BazBaz.check new file mode 100644 index 000000000..1f553352f --- /dev/null +++ b/driver/js/src/test/output/BazBaz.check @@ -0,0 +1,2 @@ +baz +baz diff --git a/driver/js/src/test/output/Builtin.check b/driver/js/src/test/output/Builtin.check new file mode 100644 index 000000000..430fc8d84 --- /dev/null +++ b/driver/js/src/test/output/Builtin.check @@ -0,0 +1,7 @@ +b +2 +@ +52 +1.7976931348623157e+308 +false +3.141592653589793 diff --git a/driver/js/src/test/output/CJS1.check b/driver/js/src/test/output/CJS1.check new file mode 100644 index 000000000..69a893aa3 --- /dev/null +++ b/driver/js/src/test/output/CJS1.check @@ -0,0 +1 @@ +66 diff --git a/driver/js/src/test/output/Child.check b/driver/js/src/test/output/Child.check new file mode 100644 index 000000000..f259f2362 --- /dev/null +++ b/driver/js/src/test/output/Child.check @@ -0,0 +1,2 @@ +4 +42 diff --git a/driver/js/src/test/output/Cycle2.check b/driver/js/src/test/output/Cycle2.check new file mode 100644 index 000000000..dee79f109 --- /dev/null +++ b/driver/js/src/test/output/Cycle2.check @@ -0,0 +1 @@ +114 diff --git a/driver/js/src/test/output/Lodash.check b/driver/js/src/test/output/Lodash.check new file mode 100644 index 000000000..f194bd1cf --- /dev/null +++ b/driver/js/src/test/output/Lodash.check @@ -0,0 +1 @@ +[ 2, 3, 4 ] diff --git a/driver/js/src/test/output/MLS2TheMax.check b/driver/js/src/test/output/MLS2TheMax.check new file mode 100644 index 000000000..2f23d78ed --- /dev/null +++ b/driver/js/src/test/output/MLS2TheMax.check @@ -0,0 +1,12 @@ +What is your name? +Hello, Admin welcome to the game! +Dear Admin, please guess a number from 1 to 5 +You guessed wrong, Admin +Do you want to continue? +Dear Admin, please guess a number from 1 to 5 +Not a number! +Do you want to continue? +Dear Admin, please guess a number from 1 to 5 +You guessed right, Admin +Do you want to continue? +Bye! diff --git a/driver/js/src/test/output/Mixin1.check b/driver/js/src/test/output/Mixin1.check new file mode 100644 index 000000000..d81cc0710 --- /dev/null +++ b/driver/js/src/test/output/Mixin1.check @@ -0,0 +1 @@ +42 diff --git a/driver/js/src/test/output/NewTSClass.check b/driver/js/src/test/output/NewTSClass.check new file mode 100644 index 000000000..257cc5642 --- /dev/null +++ b/driver/js/src/test/output/NewTSClass.check @@ -0,0 +1 @@ +foo diff --git a/driver/js/src/test/output/Output.check b/driver/js/src/test/output/Output.check new file mode 100644 index 000000000..56cfa19d7 --- /dev/null +++ b/driver/js/src/test/output/Output.check @@ -0,0 +1 @@ +{compilerOptions:{outDir:'foo'}} diff --git a/driver/js/src/test/output/Output2.check b/driver/js/src/test/output/Output2.check new file mode 100644 index 000000000..343f9d4ba --- /dev/null +++ b/driver/js/src/test/output/Output2.check @@ -0,0 +1 @@ +{compilerOptions:{outDir:'bar'}} diff --git a/driver/js/src/test/output/Simple.check b/driver/js/src/test/output/Simple.check new file mode 100644 index 000000000..54f544546 --- /dev/null +++ b/driver/js/src/test/output/Simple.check @@ -0,0 +1,3 @@ +[ 'hello!', 114514 ] +42 +[ 'hello!', 43 ] diff --git a/driver/js/src/test/output/TS.check b/driver/js/src/test/output/TS.check new file mode 100644 index 000000000..a5908a56a --- /dev/null +++ b/driver/js/src/test/output/TS.check @@ -0,0 +1 @@ +[love from ts] hello world!. (4/15/2006, 6:58:39 PM) diff --git a/driver/js/src/test/output/TyperDebug.check b/driver/js/src/test/output/TyperDebug.check new file mode 100644 index 000000000..21e72e8ac --- /dev/null +++ b/driver/js/src/test/output/TyperDebug.check @@ -0,0 +1 @@ +48 diff --git a/driver/js/src/test/scala/driver/DriverDiffTests.scala b/driver/js/src/test/scala/driver/DriverDiffTests.scala new file mode 100644 index 000000000..aca96e608 --- /dev/null +++ b/driver/js/src/test/scala/driver/DriverDiffTests.scala @@ -0,0 +1,124 @@ +package driver + +import org.scalatest.funsuite.AnyFunSuite +import scala.scalajs.js +import js.Dynamic.{global => g} +import js.DynamicImplicits._ +import mlscript.utils._, shorthands._ + +class DriverDiffTests extends AnyFunSuite { + import DriverDiffTests._ + import ts2mls.JSFileSystem._ + + private def run(cases: List[TestOption], workDir: Str, outputDir: Str, interfaceDir: Str, cjs: Bool) = { + cases.foreach { + case TestOption(filename, execution, tsconfig, expectTypeError, expectError) => test(filename) { + val options = + DriverOptions(filename, workDir, "./driver/npm/lib/predefs/", outputDir, tsconfig, interfaceDir, cjs, expectTypeError, expectError, true) + val driver = Driver(options) + if (!outputDir.isEmpty()) driver.genPackageJson() + val res = driver.execute + + import DriverResult._ + res match { + case Error => fail(s"Compiling error(s) found in $filename.") + case TypeError => fail(s"Type error(s) found in $filename") + case ExpectError => fail(s"Expect compiling error(s) in $filename") + case ExpectTypeError => fail(s"Expect type error(s) in $filename") + case OK => () + } + + if (!expectError) execution.fold(()){ + case (executionFile, checkFile) => + val output = cp.execSync(s"node $outputDir/$executionFile").toString() + val outputFile = s"$checkPath/$checkFile" + val original = readFile(outputFile).getOrElse("") + if (original =/= output) fs.writeFileSync(outputFile, output) + } + } + } + } + + run(ts2mlsCases, ts2mlsPath, "", "../diff", false) + run(esCases, esPath, s"${esPath}/js/", ".interfaces", false) + run(cjsCases, cjsPath, s"${cjsPath}/js/", ".interfaces", true) +} + +object DriverDiffTests { + private val diffPath = "driver/js/src/test/" + private val checkPath = s"${diffPath}output/" + private val ts2mlsPath = "ts2mls/js/src/test/typescript/" + private val esPath = s"${diffPath}esprojects/" + private val cjsPath = s"${diffPath}cjsprojects/" + + private case class TestOption( + filename: String, + execution: Option[(String, String)], + tsconfig: Option[String], + expectTypeError: Boolean, + expectError: Boolean + ) + + private def driverEntry( + entryModule: String, tsconfig: Option[String] = None, expectTypeError: Boolean = false, expectError: Boolean = false, + ) = TestOption(s"./mlscript/${entryModule}.mls", S((s"mlscript/${entryModule}.js", s"${entryModule}.check")), + tsconfig, expectTypeError, expectError) + + private def ts2mlsEntry(entryFile: String, expectTypeError: Boolean = false, expectError: Boolean = false) = + TestOption(s"./${entryFile}", None, None, expectTypeError, expectError) + + private val ts2mlsCases = List( + ts2mlsEntry("BasicFunctions.ts", expectTypeError = true), + ts2mlsEntry("ClassMember.ts"), + ts2mlsEntry("Cycle1.ts", expectTypeError = true), + ts2mlsEntry("Dec.d.ts"), + ts2mlsEntry("Enum.ts"), + ts2mlsEntry("Escape.ts"), + ts2mlsEntry("Export.ts", expectTypeError = true), + ts2mlsEntry("Heritage.ts", expectTypeError = true), + ts2mlsEntry("HighOrderFunc.ts"), + ts2mlsEntry("Import.ts"), + ts2mlsEntry("InterfaceMember.ts"), + ts2mlsEntry("Intersection.ts", expectTypeError = true), + ts2mlsEntry("Literal.ts"), + ts2mlsEntry("Namespace.ts", expectTypeError = true), + ts2mlsEntry("Optional.ts", expectTypeError = true), + ts2mlsEntry("Overload.ts"), + ts2mlsEntry("TSArray.ts", expectTypeError = true), + ts2mlsEntry("Tuple.ts", expectTypeError = true), + ts2mlsEntry("Type.ts", expectTypeError = true), + ts2mlsEntry("TypeParameter.ts", expectTypeError = true), + ts2mlsEntry("Union.ts"), + ts2mlsEntry("Variables.ts", expectTypeError = true), + ) + + private val esCases = List( + driverEntry("Simple"), + driverEntry("Cycle2"), + driverEntry("Cycle4", expectError = true, expectTypeError = true), + driverEntry("Self", expectError = true), + driverEntry("C", expectError = true, expectTypeError = true), + driverEntry("TS", Some("./tsconfig.json"), expectTypeError = true), // TODO: type members + driverEntry("Output", Some("./tsconfig.json"), expectTypeError = true), // TODO: type parameter position + driverEntry("Output2", Some("./tsconfig.json"), expectTypeError = true), // TODO: type parameter position + driverEntry("MLS2TheMax", Some("./tsconfig.json")), + driverEntry("MyPartialOrder", Some("./tsconfig.json"), expectError = true, expectTypeError = true), // TODO: type traits in modules + driverEntry("Builtin"), + driverEntry("TyperDebug"), + driverEntry("Debug1"), + driverEntry("Child", expectTypeError = true), + driverEntry("NewTSClass", Some("./tsconfig.json"), expectTypeError = true), + driverEntry("Mixin1", expectTypeError = true) + ) + + private val cjsCases = List( + driverEntry("Lodash", Some("./tsconfig.json"), expectTypeError = true), // TODO: module member selection/trait types + driverEntry("CJS1"), + driverEntry("Bar", Some("./tsconfig.json")), + driverEntry("BazBaz", Some("./tsconfig.json"), expectTypeError = true), + driverEntry("Call", Some("./tsconfig.json"), expectError = true) + ) + + private val cp = g.require("child_process") + private val fs = g.require("fs") +} diff --git a/driver/npm/README.md b/driver/npm/README.md new file mode 100644 index 000000000..bd53f8107 --- /dev/null +++ b/driver/npm/README.md @@ -0,0 +1,43 @@ +# MLscript + +**This is a pre-release of MLscript.** + +## Quick Start +To install MLscript, you can use `npm`: +```shell +npm i mlscript +``` + +The newest version is recommended: there may be lots of bugs in the previous versions. + +To watch the project directory, you can use TypeScript(recommended)/JavaScript: +```ts +import mlscript from "mlscript" + +// filename: string, workDir: string, outputDir: string, tsconfig: string, commonJS: boolean, expectTypeError: boolean +mlscript.watch("./mlscript/Main.mls", "./", "./js/", "./tsconfig.json", false, true) +``` + +The path must start with `./`, or it will be treated as `node_modules` paths. + +If you need to interoperate with TypeScript, you must provide the path of `tsconfig.json` file. +Otherwise, it is optional. + +You can choose to use CommonJS or ES modules(recommended). + +Since Mlscript is still under development, type inferences are not fully supported. +If there is a type error but it is correct, please set the `expectTypeError` flag to `true`. +To get the type error messages, please check the corresponding `.mlsi` files in `.interfaces`. + +For more details, you can check the demo [here](https://github.com/NeilKleistGao/mlscript-driver-demo). + +## Project Structure +The MLscript uses `git` to track the file changes. +Please make sure your project locates in a git repo. + +Though not necessary, we still recommend you organize the project in this structure: +- `.interfaces`: temporary interface files generated by MLscript. +- `mlscript`: directory for MLscript files. +- `node_modules`: third-party libraries in TypeScript. +- `ts`: directory for TypeScript files. +- configuration files: `package.json` and `tsconfig.json` should locate in the root directory. diff --git a/driver/npm/lib/index.d.ts b/driver/npm/lib/index.d.ts new file mode 100644 index 000000000..358a69f4b --- /dev/null +++ b/driver/npm/lib/index.d.ts @@ -0,0 +1,21 @@ +declare interface MLscript { + watch( + filename: string, + workDir: string, + outputDir: string, + tsconfig: string, + commonJS: boolean, + expectTypeError: boolean + ); + + watch( + filename: string, + workDir: string, + outputDir: string, + commonJS: boolean, + expectTypeError: boolean + ); +} + +declare const mlscript: MLscript +export = mlscript; diff --git a/driver/npm/lib/predefs/Dom.mlsi b/driver/npm/lib/predefs/Dom.mlsi new file mode 100644 index 000000000..ecd0bdf9b --- /dev/null +++ b/driver/npm/lib/predefs/Dom.mlsi @@ -0,0 +1,23 @@ +declare trait Console { + declare fun assert(args0: ((false) | (true)) | (undefined), args1: (anything) | (MutArray[anything])): unit + declare fun count(args0: (Str) | (undefined)): unit + declare fun timeEnd(args0: (Str) | (undefined)): unit + declare fun clear(): unit + declare fun timeStamp(args0: (Str) | (undefined)): unit + declare fun info(args0: (anything) | (MutArray[anything])): unit + declare fun debug(args0: (anything) | (MutArray[anything])): unit + declare fun countReset(args0: (Str) | (undefined)): unit + declare fun dir(args0: (anything) | (undefined), args1: (anything) | (undefined)): unit + declare fun error(args0: (anything) | (MutArray[anything])): unit + declare fun timeLog(args0: (Str) | (undefined), args1: (anything) | (MutArray[anything])): unit + declare fun time(args0: (Str) | (undefined)): unit + declare fun group(args0: (anything) | (MutArray[anything])): unit + declare fun table(args0: (anything) | (undefined), args1: (MutArray[Str]) | (undefined)): unit + declare fun trace(args0: (anything) | (MutArray[anything])): unit + declare fun warn(args0: (anything) | (MutArray[anything])): unit + declare fun groupCollapsed(args0: (anything) | (MutArray[anything])): unit + declare fun dirxml(args0: (anything) | (MutArray[anything])): unit + declare fun log(args0: (anything) | (MutArray[anything])): unit + declare fun groupEnd(): unit +} +val console: Console diff --git a/driver/npm/lib/predefs/ES5.mlsi b/driver/npm/lib/predefs/ES5.mlsi new file mode 100644 index 000000000..fa2d291da --- /dev/null +++ b/driver/npm/lib/predefs/ES5.mlsi @@ -0,0 +1,873 @@ +val NaN: Num +val Infinity: Num +declare fun eval(x: Str): anything +declare fun parseInt(string: Str, radix: (Num) | (undefined)): Num +declare fun parseFloat(string: Str): Num +declare fun isNaN(number: Num): (false) | (true) +declare fun isFinite(number: Num): (false) | (true) +declare fun decodeURI(encodedURI: Str): Str +declare fun decodeURIComponent(encodedURIComponent: Str): Str +declare fun encodeURI(uri: Str): Str +declare fun encodeURIComponent(uriComponent: (((Str) | (Num)) | (false)) | (true)): Str +declare fun escape(string: Str): Str +declare fun unescape(string: Str): Str +declare trait Symbol { + declare fun toString(): Str + declare fun valueOf(): Symbol +} +type PropertyKey = ((Str) | (Num)) | (Symbol) +declare trait PropertyDescriptor { + val configurable: ((false) | (true)) | (undefined) + val set: ((args0: anything) => unit) | (undefined) + val enumerable: ((false) | (true)) | (undefined) + val get: (() => anything) | (undefined) + val writable: ((false) | (true)) | (undefined) + val value: (anything) | (undefined) +} +declare trait PropertyDescriptorMap { + val __index: unsupported["[key: PropertyKey]: PropertyDescriptor;", "ES5.d.ts", 101, 33] +} +declare class Object { + declare fun hasOwnProperty(args0: ((Str) | (Num)) | (Symbol)): (false) | (true) + declare fun propertyIsEnumerable(args0: ((Str) | (Num)) | (Symbol)): (false) | (true) + declare fun valueOf(): Object + declare fun toLocaleString(): Str + declare fun isPrototypeOf(args0: Object): (false) | (true) + declare fun toString(): Str +} +declare trait ObjectConstructor: ((args0: anything) => anything) { + declare fun getOwnPropertyNames(args0: anything): MutArray[Str] + declare fun isFrozen(args0: anything): (false) | (true) + declare fun getPrototypeOf(args0: anything): anything + declare fun defineProperty['T](args0: 'T, args1: ((Str) | (Num)) | (Symbol), args2: (PropertyDescriptor) & (ThisType[anything])): 'T + val prototype: Object + declare fun isSealed(args0: anything): (false) | (true) + declare fun defineProperties['T](args0: 'T, args1: (PropertyDescriptorMap) & (ThisType[anything])): 'T + declare fun preventExtensions['T](args0: 'T): 'T + declare fun create(args0: Object, args1: (PropertyDescriptorMap) & (ThisType[anything])): anything /* warning: the overload of function create is not supported yet. */ + val freeze: unsupported["freeze(o: T): Readonly;", "ES5.d.ts", 210, 143] + val __new: unsupported["new(value?: any): Object;", "ES5.d.ts", 137, 29] + declare fun getOwnPropertyDescriptor(args0: anything, args1: ((Str) | (Num)) | (Symbol)): PropertyDescriptor + declare fun seal['T](args0: 'T): 'T + declare fun keys(args0: Object): MutArray[Str] + declare fun isExtensible(args0: anything): (false) | (true) +} +declare trait Function { + declare fun bind(args0: anything, args1: (anything) | (MutArray[anything])): anything + declare fun apply(args0: anything, args1: (anything) | (undefined)): anything + val prototype: anything + declare fun call(args0: anything, args1: (anything) | (MutArray[anything])): anything + declare fun toString(): Str + val length: Num + val caller: Function + val arguments: anything +} +declare trait FunctionConstructor: ((args0: (Str) | (MutArray[Str])) => Function) { + val __new: unsupported["new(...args: string[]): Function;", "ES5.d.ts", 291, 31] + val prototype: Function +} +type ThisParameterType = unsupported["type ThisParameterType = T extends (this: infer U, ...args: never) => any ? U : unknown;", "ES5.d.ts", 301, 42] +type OmitThisParameter = unsupported["type OmitThisParameter = unknown extends ThisParameterType ? T : T extends (...args: infer A) => infer R ? (...args: A) => R : T;", "ES5.d.ts", 306, 91] +declare trait CallableFunction extends Function { + declare fun apply['T, 'A, 'R](args0: 'T, args1: 'A): 'R /* warning: the overload of function apply is not supported yet. */ + declare fun call['T, 'A, 'R](args0: 'T, args1: 'A): 'R + declare fun bind['T, 'AX, 'R](args0: 'T, args1: ('AX) | (MutArray['AX])): (args: ('AX) | (MutArray['AX])) => 'R /* warning: the overload of function bind is not supported yet. */ +} +declare trait NewableFunction extends Function { + declare fun apply['T, 'A](args0: 'T, args1: 'A): unit /* warning: the overload of function apply is not supported yet. */ + declare fun call['T, 'A](args0: 'T, args1: 'A): unit + declare fun bind['AX, 'R](args0: anything, args1: ('AX) | (MutArray['AX])): (args: ('AX) | (MutArray['AX])) => 'R /* warning: the overload of function bind is not supported yet. */ +} +declare trait IArguments { + val __index: unsupported["[index: number]: any;", "ES5.d.ts", 373, 22] + val length: Num + val callee: Function +} +declare trait String { + declare fun replace(args0: (Str) | (RegExp), args1: (substring: Str, args: (anything) | (MutArray[anything])) => Str): Str /* warning: the overload of function replace is not supported yet. */ + declare fun valueOf(): Str + declare fun toLocaleUpperCase(args0: ((Str) | (MutArray[Str])) | (undefined)): Str + declare fun lastIndexOf(args0: Str, args1: (Num) | (undefined)): Num + declare fun localeCompare(args0: Str): Num + declare fun toLocaleLowerCase(args0: ((Str) | (MutArray[Str])) | (undefined)): Str + declare fun match(args0: (Str) | (RegExp)): RegExpMatchArray + declare fun split(args0: (Str) | (RegExp), args1: (Num) | (undefined)): MutArray[Str] + declare fun toUpperCase(): Str + declare fun indexOf(args0: Str, args1: (Num) | (undefined)): Num + declare fun toLowerCase(): Str + declare fun concat(args0: (Str) | (MutArray[Str])): Str + val __index: unsupported["readonly [index: number]: string;", "ES5.d.ts", 498, 22] + declare fun charCodeAt(args0: Num): Num + declare fun slice(args0: (Num) | (undefined), args1: (Num) | (undefined)): Str + declare fun substr(args0: Num, args1: (Num) | (undefined)): Str + declare fun toString(): Str + val length: Num + declare fun substring(args0: Num, args1: (Num) | (undefined)): Str + declare fun trim(): Str + declare fun search(args0: (Str) | (RegExp)): Num + declare fun charAt(args0: Num): Str +} +declare trait StringConstructor: ((args0: (anything) | (undefined)) => Str) { + val __new: unsupported["new(value?: any): String;", "ES5.d.ts", 503, 29] + val prototype: String + declare fun fromCharCode(args0: (Num) | (MutArray[Num])): Str +} +declare class Bool { + declare fun valueOf(): (false) | (true) +} +declare trait BooleanConstructor: (forall 'T: (args0: ('T) | (undefined)) => (false) | (true)) { + val __new: unsupported["new(value?: any): Bool;", "ES5.d.ts", 520, 30] + val prototype: Bool +} +val Boolean: BooleanConstructor +declare trait Number { + declare fun toExponential(args0: (Num) | (undefined)): Str + declare fun valueOf(): Num + declare fun toString(args0: (Num) | (undefined)): Str + declare fun toFixed(args0: (Num) | (undefined)): Str + declare fun toPrecision(args0: (Num) | (undefined)): Str +} +declare trait NumberConstructor: ((args0: (anything) | (undefined)) => Num) { + val NaN: Num + val MIN_VALUE: Num + val __new: unsupported["new(value?: any): Number;", "ES5.d.ts", 557, 29] + val NEGATIVE_INFINITY: Num + val POSITIVE_INFINITY: Num + val MAX_VALUE: Num + val prototype: Number +} +declare trait TemplateStringsArray extends ReadonlyArray[Str] { + val raw: ReadonlyArray[Str] +} +declare trait ImportMeta {} +declare trait ImportCallOptions { + val assert: (ImportAssertions) | (undefined) +} +declare trait ImportAssertions { + val __index: unsupported["[key: string]: string;", "ES5.d.ts", 616, 28] +} +declare trait Math { + declare fun random(): Num + declare fun asin(args0: Num): Num + val LOG2E: Num + declare fun min(args0: (Num) | (MutArray[Num])): Num + declare fun cos(args0: Num): Num + val LOG10E: Num + val PI: Num + declare fun floor(args0: Num): Num + val SQRT2: Num + declare fun round(args0: Num): Num + declare fun sin(args0: Num): Num + val E: Num + val LN10: Num + declare fun exp(args0: Num): Num + val LN2: Num + declare fun atan(args0: Num): Num + declare fun pow(args0: Num, args1: Num): Num + declare fun ceil(args0: Num): Num + declare fun max(args0: (Num) | (MutArray[Num])): Num + declare fun atan2(args0: Num, args1: Num): Num + declare fun sqrt(args0: Num): Num + declare fun tan(args0: Num): Num + val SQRT1_2: Num + declare fun abs(args0: Num): Num + declare fun log(args0: Num): Num + declare fun acos(args0: Num): Num +} +declare trait Date { + declare fun getUTCMonth(): Num + declare fun valueOf(): Num + declare fun getUTCMinutes(): Num + declare fun setMilliseconds(args0: Num): Num + declare fun toLocaleString(): Str + declare fun getDate(): Num + declare fun getUTCDate(): Num + declare fun setDate(args0: Num): Num + declare fun setFullYear(args0: Num, args1: (Num) | (undefined), args2: (Num) | (undefined)): Num + declare fun getMinutes(): Num + declare fun getFullYear(): Num + declare fun setUTCDate(args0: Num): Num + declare fun setMinutes(args0: Num, args1: (Num) | (undefined), args2: (Num) | (undefined)): Num + declare fun setTime(args0: Num): Num + declare fun toUTCString(): Str + declare fun toLocaleDateString(): Str + declare fun setUTCMonth(args0: Num, args1: (Num) | (undefined)): Num + declare fun setUTCFullYear(args0: Num, args1: (Num) | (undefined), args2: (Num) | (undefined)): Num + declare fun setHours(args0: Num, args1: (Num) | (undefined), args2: (Num) | (undefined), args3: (Num) | (undefined)): Num + declare fun getTime(): Num + declare fun setSeconds(args0: Num, args1: (Num) | (undefined)): Num + declare fun setUTCSeconds(args0: Num, args1: (Num) | (undefined)): Num + declare fun getUTCFullYear(): Num + declare fun getUTCHours(): Num + declare fun getUTCDay(): Num + declare fun setUTCMinutes(args0: Num, args1: (Num) | (undefined), args2: (Num) | (undefined)): Num + declare fun getHours(): Num + declare fun toISOString(): Str + declare fun toTimeString(): Str + declare fun setUTCMilliseconds(args0: Num): Num + declare fun getUTCSeconds(): Num + declare fun getMilliseconds(): Num + declare fun setMonth(args0: Num, args1: (Num) | (undefined)): Num + declare fun getDay(): Num + declare fun toLocaleTimeString(): Str + declare fun getSeconds(): Num + declare fun getUTCMilliseconds(): Num + declare fun toDateString(): Str + declare fun toString(): Str + declare fun getMonth(): Num + declare fun getTimezoneOffset(): Num + declare fun setUTCHours(args0: Num, args1: (Num) | (undefined), args2: (Num) | (undefined), args3: (Num) | (undefined)): Num + declare fun toJSON(args0: (anything) | (undefined)): Str +} +declare trait DateConstructor: (() => Str) { + declare fun UTC(args0: Num, args1: Num, args2: (Num) | (undefined), args3: (Num) | (undefined), args4: (Num) | (undefined), args5: (Num) | (undefined), args6: (Num) | (undefined)): Num + val __new: unsupported["new(year: number, monthIndex: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date;", "ES5.d.ts", 887, 38] + declare fun now(): Num + declare fun parse(args0: Str): Num + val prototype: Date +} +declare trait RegExpMatchArray extends Array[Str] { + val index: (Num) | (undefined) + val input: (Str) | (undefined) + val id"0": Str +} +declare trait RegExpExecArray extends Array[Str] { + val index: Num + val input: Str + val id"0": Str +} +declare trait RegExp { + declare fun test(args0: Str): (false) | (true) + val multiline: (false) | (true) + val source: Str + declare fun compile(args0: Str, args1: (Str) | (undefined)): 'RegExp + val global: (false) | (true) + val lastIndex: Num + val ignoreCase: (false) | (true) + declare fun exec(args0: Str): RegExpExecArray +} +declare trait RegExpConstructor: ((args0: Str, args1: (Str) | (undefined)) => RegExp) { + val id"$4": Str + val rightContext: Str + val lastParen: Str + val id"$5": Str + val id"$+": Str + val __new: unsupported["new(pattern: string, flags?: string): RegExp;", "ES5.d.ts", 987, 42] + val id"$'": Str + val id"$&": Str + val id"$7": Str + val prototype: RegExp + val id"$`": Str + val id"$_": Str + val lastMatch: Str + val id"$9": Str + val id"$6": Str + val id"$3": Str + val id"$2": Str + val leftContext: Str + val id"$8": Str + val id"$1": Str + val input: Str +} +declare trait Error { + val name: Str + val message: Str + val stack: (Str) | (undefined) +} +declare trait ErrorConstructor: ((args0: (Str) | (undefined)) => Error) { + val __new: unsupported["new(message?: string): Error;", "ES5.d.ts", 1042, 28] + val prototype: Error +} +declare trait EvalError extends Error {} +declare trait EvalErrorConstructor: ((args0: (Str) | (undefined)) => EvalError) extends ErrorConstructor { + val __new: unsupported["new(message?: string): EvalError;", "ES5.d.ts", 1053, 57] + val prototype: EvalError +} +declare trait RangeError extends Error {} +declare trait RangeErrorConstructor: ((args0: (Str) | (undefined)) => RangeError) extends ErrorConstructor { + val __new: unsupported["new(message?: string): RangeError;", "ES5.d.ts", 1064, 58] + val prototype: RangeError +} +declare trait ReferenceError extends Error {} +declare trait ReferenceErrorConstructor: ((args0: (Str) | (undefined)) => ReferenceError) extends ErrorConstructor { + val __new: unsupported["new(message?: string): ReferenceError;", "ES5.d.ts", 1075, 62] + val prototype: ReferenceError +} +declare trait SyntaxError extends Error {} +declare trait SyntaxErrorConstructor: ((args0: (Str) | (undefined)) => SyntaxError) extends ErrorConstructor { + val __new: unsupported["new(message?: string): SyntaxError;", "ES5.d.ts", 1086, 59] + val prototype: SyntaxError +} +declare trait TypeError extends Error {} +declare trait TypeErrorConstructor: ((args0: (Str) | (undefined)) => TypeError) extends ErrorConstructor { + val __new: unsupported["new(message?: string): TypeError;", "ES5.d.ts", 1097, 57] + val prototype: TypeError +} +declare trait URIError extends Error {} +declare trait URIErrorConstructor: ((args0: (Str) | (undefined)) => URIError) extends ErrorConstructor { + val __new: unsupported["new(message?: string): URIError;", "ES5.d.ts", 1108, 56] + val prototype: URIError +} +declare trait JSON { + declare fun parse(args0: Str, args1: ((key: Str, value: anything) => anything) | (undefined)): anything + declare fun stringify(args0: anything, args1: (MutArray[(Str) | (Num)]) | (undefined), args2: ((Str) | (Num)) | (undefined)): Str /* warning: the overload of function stringify is not supported yet. */ +} +declare trait ReadonlyArray['T] { + declare fun lastIndexOf(args0: 'T, args1: (Num) | (undefined)): Num + declare fun every(args0: (value: 'T, index: Num, array: ReadonlyArray['T]) => anything, args1: (anything) | (undefined)): (false) | (true) /* warning: the overload of function every is not supported yet. */ + declare fun forEach(args0: (value: 'T, index: Num, array: ReadonlyArray['T]) => unit, args1: (anything) | (undefined)): unit + declare fun filter(args0: (value: 'T, index: Num, array: ReadonlyArray['T]) => anything, args1: (anything) | (undefined)): MutArray['T] /* warning: the overload of function filter is not supported yet. */ + val __index: unsupported["readonly [n: number]: T;", "ES5.d.ts", 1272, 136] + declare fun reduceRight['U](args0: (previousValue: 'U, currentValue: 'T, currentIndex: Num, array: ReadonlyArray['T]) => 'U, args1: 'U): 'U /* warning: the overload of function reduceRight is not supported yet. */ + declare fun join(args0: (Str) | (undefined)): Str + declare fun map['U](args0: (value: 'T, index: Num, array: ReadonlyArray['T]) => 'U, args1: (anything) | (undefined)): MutArray['U] + declare fun concat(args0: (('T) | (ConcatArray['T])) | (MutArray[('T) | (ConcatArray['T])])): MutArray['T] /* warning: the overload of function concat is not supported yet. */ + declare fun toLocaleString(): Str + declare fun slice(args0: (Num) | (undefined), args1: (Num) | (undefined)): MutArray['T] + declare fun reduce['U](args0: (previousValue: 'U, currentValue: 'T, currentIndex: Num, array: ReadonlyArray['T]) => 'U, args1: 'U): 'U /* warning: the overload of function reduce is not supported yet. */ + declare fun toString(): Str + val length: Num + declare fun some(args0: (value: 'T, index: Num, array: ReadonlyArray['T]) => anything, args1: (anything) | (undefined)): (false) | (true) + declare fun indexOf(args0: 'T, args1: (Num) | (undefined)): Num +} +declare trait ConcatArray['T] { + val length: Num + val __index: unsupported["readonly [n: number]: T;", "ES5.d.ts", 1278, 28] + declare fun join(args0: (Str) | (undefined)): Str + declare fun slice(args0: (Num) | (undefined), args1: (Num) | (undefined)): MutArray['T] +} +declare trait Array['T] { + declare fun lastIndexOf(args0: 'T, args1: (Num) | (undefined)): Num + declare fun every(args0: (value: 'T, index: Num, array: MutArray['T]) => anything, args1: (anything) | (undefined)): (false) | (true) /* warning: the overload of function every is not supported yet. */ + declare fun push(args0: ('T) | (MutArray['T])): Num + declare fun forEach(args0: (value: 'T, index: Num, array: MutArray['T]) => unit, args1: (anything) | (undefined)): unit + declare fun reduceRight['U](args0: (previousValue: 'U, currentValue: 'T, currentIndex: Num, array: MutArray['T]) => 'U, args1: 'U): 'U /* warning: the overload of function reduceRight is not supported yet. */ + declare fun unshift(args0: ('T) | (MutArray['T])): Num + declare fun sort(args0: ((a: 'T, b: 'T) => Num) | (undefined)): 'Array + declare fun join(args0: (Str) | (undefined)): Str + declare fun map['U](args0: (value: 'T, index: Num, array: MutArray['T]) => 'U, args1: (anything) | (undefined)): MutArray['U] + declare fun pop(): 'T + declare fun shift(): 'T + declare fun concat(args0: (('T) | (ConcatArray['T])) | (MutArray[('T) | (ConcatArray['T])])): MutArray['T] /* warning: the overload of function concat is not supported yet. */ + declare fun toLocaleString(): Str + declare fun reverse(): MutArray['T] + declare fun filter(args0: (value: 'T, index: Num, array: MutArray['T]) => anything, args1: (anything) | (undefined)): MutArray['T] /* warning: the overload of function filter is not supported yet. */ + val __index: unsupported["[n: number]: T;", "ES5.d.ts", 1463, 127] + declare fun splice(args0: Num, args1: Num, args2: ('T) | (MutArray['T])): MutArray['T] /* warning: the overload of function splice is not supported yet. */ + declare fun slice(args0: (Num) | (undefined), args1: (Num) | (undefined)): MutArray['T] + declare fun reduce['U](args0: (previousValue: 'U, currentValue: 'T, currentIndex: Num, array: MutArray['T]) => 'U, args1: 'U): 'U /* warning: the overload of function reduce is not supported yet. */ + declare fun toString(): Str + val length: Num + declare fun some(args0: (value: 'T, index: Num, array: MutArray['T]) => anything, args1: (anything) | (undefined)): (false) | (true) + declare fun indexOf(args0: 'T, args1: (Num) | (undefined)): Num +} +declare trait ArrayConstructor: (forall 'T: (args0: ('T) | (MutArray['T])) => MutArray['T]) { + val __new: unsupported["new (...items: T[]): T[];", "ES5.d.ts", 1470, 38] + declare fun isArray(args0: anything): (false) | (true) + val prototype: MutArray[anything] +} +declare trait TypedPropertyDescriptor['T] { + val configurable: ((false) | (true)) | (undefined) + val set: ((value: 'T) => unit) | (undefined) + val enumerable: ((false) | (true)) | (undefined) + val get: (() => 'T) | (undefined) + val writable: ((false) | (true)) | (undefined) + val value: ('T) | (undefined) +} +type PromiseConstructorLike = forall 'T: (executor: (resolve: (value: ('T) | (PromiseLike['T])) => unit, reject: (reason: (anything) | (undefined)) => unit) => unit) => PromiseLike['T] +declare trait PromiseLike['T] { + declare fun id"then"['TResult1, 'TResult2](args0: ((value: 'T) => ('TResult1) | (PromiseLike['TResult1])) | (undefined), args1: ((reason: anything) => ('TResult2) | (PromiseLike['TResult2])) | (undefined)): PromiseLike[('TResult1) | ('TResult2)] +} +declare trait Promise['T] { + declare fun id"then"['TResult1, 'TResult2](args0: ((value: 'T) => ('TResult1) | (PromiseLike['TResult1])) | (undefined), args1: ((reason: anything) => ('TResult2) | (PromiseLike['TResult2])) | (undefined)): Promise[('TResult1) | ('TResult2)] + declare fun catch['TResult](args0: ((reason: anything) => ('TResult) | (PromiseLike['TResult])) | (undefined)): Promise[('T) | ('TResult)] +} +type Awaited = unsupported["type Awaited = T extends null | undefined ? T : // special case for `null | undefined` when not in `--strictNullChecks` mode T extends object & { then(onfulfilled: infer F, ...args: infer _): any } ? // `await` only unwraps object types with a callable `then`. Non-object types are not unwrapped F extends ((value: infer V, ...args: infer _) => any) ? // if the argument to `then` is callable, extracts the first argument Awaited : // recursively unwrap the value never : // the argument to `then` was not callable T;", "ES5.d.ts", 1520, 1] +declare trait ArrayLike['T] { + val length: Num + val __index: unsupported["readonly [n: number]: T;", "ES5.d.ts", 1534, 28] +} +type Partial = unsupported["type Partial = { [P in keyof T]?: T[P]; };", "ES5.d.ts", 1536, 1] +type Required = unsupported["type Required = { [P in keyof T]-?: T[P]; };", "ES5.d.ts", 1543, 2] +type Readonly = unsupported["type Readonly = { readonly [P in keyof T]: T[P]; };", "ES5.d.ts", 1550, 2] +type Pick = unsupported["type Pick = { [P in K]: T[P]; };", "ES5.d.ts", 1557, 2] +type Record = unsupported["type Record = { [P in K]: T; };", "ES5.d.ts", 1564, 2] +type Exclude = unsupported["type Exclude = T extends U ? never : T;", "ES5.d.ts", 1571, 2] +type Extract = unsupported["type Extract = T extends U ? T : never;", "ES5.d.ts", 1576, 45] +type Omit = unsupported["type Omit = Pick>;", "ES5.d.ts", 1581, 45] +type NonNullable['T] = ('T) & ({}) +type Parameters = unsupported["type Parameters any> = T extends (...args: infer P) => any ? P : never;", "ES5.d.ts", 1591, 29] +type ConstructorParameters = unsupported["type ConstructorParameters any> = T extends abstract new (...args: infer P) => any ? P : never;", "ES5.d.ts", 1596, 99] +type ReturnType = unsupported["type ReturnType any> = T extends (...args: any) => infer R ? R : any;", "ES5.d.ts", 1601, 136] +type InstanceType = unsupported["type InstanceType any> = T extends abstract new (...args: any) => infer R ? R : any;", "ES5.d.ts", 1606, 97] +type Uppercase = unsupported["type Uppercase = intrinsic;", "ES5.d.ts", 1611, 125] +type Lowercase = unsupported["type Lowercase = intrinsic;", "ES5.d.ts", 1616, 45] +type Capitalize = unsupported["type Capitalize = intrinsic;", "ES5.d.ts", 1621, 45] +type Uncapitalize = unsupported["type Uncapitalize = intrinsic;", "ES5.d.ts", 1626, 46] +declare trait ThisType['T] {} +declare trait ArrayBuffer { + val byteLength: Num + declare fun slice(args0: Num, args1: (Num) | (undefined)): ArrayBuffer +} +declare trait ArrayBufferTypes { + val ArrayBuffer: unsupported["ArrayBuffer: ArrayBuffer;", "ES5.d.ts", 1659, 28] +} +type ArrayBufferLike = ArrayBuffer +declare trait ArrayBufferConstructor { + val prototype: ArrayBuffer + val __new: unsupported["new(byteLength: number): ArrayBuffer;", "ES5.d.ts", 1665, 36] + declare fun isView(args0: anything): (false) | (true) +} +declare trait ArrayBufferView { + val buffer: ArrayBuffer + val byteLength: Num + val byteOffset: Num +} +declare trait DataView { + declare fun setInt32(args0: Num, args1: Num, args2: ((false) | (true)) | (undefined)): unit + declare fun setUint32(args0: Num, args1: Num, args2: ((false) | (true)) | (undefined)): unit + declare fun setFloat64(args0: Num, args1: Num, args2: ((false) | (true)) | (undefined)): unit + declare fun getInt8(args0: Num): Num + val buffer: ArrayBuffer + declare fun setInt16(args0: Num, args1: Num, args2: ((false) | (true)) | (undefined)): unit + declare fun getUint8(args0: Num): Num + val byteLength: Num + declare fun getFloat64(args0: Num, args1: ((false) | (true)) | (undefined)): Num + declare fun getFloat32(args0: Num, args1: ((false) | (true)) | (undefined)): Num + declare fun getUint16(args0: Num, args1: ((false) | (true)) | (undefined)): Num + declare fun setInt8(args0: Num, args1: Num): unit + declare fun setUint16(args0: Num, args1: Num, args2: ((false) | (true)) | (undefined)): unit + declare fun setFloat32(args0: Num, args1: Num, args2: ((false) | (true)) | (undefined)): unit + declare fun getUint32(args0: Num, args1: ((false) | (true)) | (undefined)): Num + declare fun getInt32(args0: Num, args1: ((false) | (true)) | (undefined)): Num + declare fun getInt16(args0: Num, args1: ((false) | (true)) | (undefined)): Num + declare fun setUint8(args0: Num, args1: Num): unit + val byteOffset: Num +} +declare trait DataViewConstructor { + val prototype: DataView + val __new: unsupported["new(buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView;", "ES5.d.ts", 1817, 33] +} +declare trait Int8Array { + declare fun valueOf(): Int8Array + declare fun lastIndexOf(args0: Num, args1: (Num) | (undefined)): Num + declare fun every(args0: (value: Num, index: Num, array: Int8Array) => anything, args1: (anything) | (undefined)): (false) | (true) + declare fun set(args0: ArrayLike[Num], args1: (Num) | (undefined)): unit + declare fun toLocaleString(): Str + val __index: unsupported["[index: number]: number;", "ES5.d.ts", 2065, 25] + declare fun reduceRight['U](args0: (previousValue: 'U, currentValue: Num, currentIndex: Num, array: Int8Array) => 'U, args1: 'U): 'U /* warning: the overload of function reduceRight is not supported yet. */ + declare fun fill(args0: Num, args1: (Num) | (undefined), args2: (Num) | (undefined)): 'Int8Array + declare fun sort(args0: ((a: Num, b: Num) => Num) | (undefined)): 'Int8Array + val BYTES_PER_ELEMENT: Num + declare fun copyWithin(args0: Num, args1: (Num) | (undefined), args2: (Num) | (undefined)): 'Int8Array + declare fun find(args0: (value: Num, index: Num, obj: Int8Array) => (false) | (true), args1: (anything) | (undefined)): Num + declare fun subarray(args0: (Num) | (undefined), args1: (Num) | (undefined)): Int8Array + declare fun join(args0: (Str) | (undefined)): Str + declare fun map(args0: (value: Num, index: Num, array: Int8Array) => Num, args1: (anything) | (undefined)): Int8Array + declare fun forEach(args0: (value: Num, index: Num, array: Int8Array) => unit, args1: (anything) | (undefined)): unit + val buffer: ArrayBuffer + declare fun findIndex(args0: (value: Num, index: Num, obj: Int8Array) => (false) | (true), args1: (anything) | (undefined)): Num + declare fun reverse(): Int8Array + declare fun filter(args0: (value: Num, index: Num, array: Int8Array) => anything, args1: (anything) | (undefined)): Int8Array + declare fun slice(args0: (Num) | (undefined), args1: (Num) | (undefined)): Int8Array + val byteLength: Num + declare fun reduce['U](args0: (previousValue: 'U, currentValue: Num, currentIndex: Num, array: Int8Array) => 'U, args1: 'U): 'U /* warning: the overload of function reduce is not supported yet. */ + declare fun toString(): Str + val length: Num + declare fun some(args0: (value: Num, index: Num, array: Int8Array) => anything, args1: (anything) | (undefined)): (false) | (true) + declare fun indexOf(args0: Num, args1: (Num) | (undefined)): Num + val byteOffset: Num +} +declare trait Int8ArrayConstructor { + val __new: unsupported["new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array;", "ES5.d.ts", 2072, 63] + declare fun from['T](args0: ArrayLike['T], args1: (v: 'T, k: Num) => Num, args2: (anything) | (undefined)): Int8Array /* warning: the overload of function from is not supported yet. */ + val prototype: Int8Array + declare fun id"of"(args0: (Num) | (MutArray[Num])): Int8Array + val BYTES_PER_ELEMENT: Num +} +declare trait Uint8Array { + declare fun valueOf(): Uint8Array + declare fun lastIndexOf(args0: Num, args1: (Num) | (undefined)): Num + declare fun every(args0: (value: Num, index: Num, array: Uint8Array) => anything, args1: (anything) | (undefined)): (false) | (true) + declare fun set(args0: ArrayLike[Num], args1: (Num) | (undefined)): unit + declare fun toLocaleString(): Str + val __index: unsupported["[index: number]: number;", "ES5.d.ts", 2347, 26] + declare fun reduceRight['U](args0: (previousValue: 'U, currentValue: Num, currentIndex: Num, array: Uint8Array) => 'U, args1: 'U): 'U /* warning: the overload of function reduceRight is not supported yet. */ + declare fun fill(args0: Num, args1: (Num) | (undefined), args2: (Num) | (undefined)): 'Uint8Array + declare fun sort(args0: ((a: Num, b: Num) => Num) | (undefined)): 'Uint8Array + val BYTES_PER_ELEMENT: Num + declare fun copyWithin(args0: Num, args1: (Num) | (undefined), args2: (Num) | (undefined)): 'Uint8Array + declare fun find(args0: (value: Num, index: Num, obj: Uint8Array) => (false) | (true), args1: (anything) | (undefined)): Num + declare fun subarray(args0: (Num) | (undefined), args1: (Num) | (undefined)): Uint8Array + declare fun join(args0: (Str) | (undefined)): Str + declare fun map(args0: (value: Num, index: Num, array: Uint8Array) => Num, args1: (anything) | (undefined)): Uint8Array + declare fun forEach(args0: (value: Num, index: Num, array: Uint8Array) => unit, args1: (anything) | (undefined)): unit + val buffer: ArrayBuffer + declare fun findIndex(args0: (value: Num, index: Num, obj: Uint8Array) => (false) | (true), args1: (anything) | (undefined)): Num + declare fun reverse(): Uint8Array + declare fun filter(args0: (value: Num, index: Num, array: Uint8Array) => anything, args1: (anything) | (undefined)): Uint8Array + declare fun slice(args0: (Num) | (undefined), args1: (Num) | (undefined)): Uint8Array + val byteLength: Num + declare fun reduce['U](args0: (previousValue: 'U, currentValue: Num, currentIndex: Num, array: Uint8Array) => 'U, args1: 'U): 'U /* warning: the overload of function reduce is not supported yet. */ + declare fun toString(): Str + val length: Num + declare fun some(args0: (value: Num, index: Num, array: Uint8Array) => anything, args1: (anything) | (undefined)): (false) | (true) + declare fun indexOf(args0: Num, args1: (Num) | (undefined)): Num + val byteOffset: Num +} +declare trait Uint8ArrayConstructor { + val __new: unsupported["new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array;", "ES5.d.ts", 2355, 64] + declare fun from['T](args0: ArrayLike['T], args1: (v: 'T, k: Num) => Num, args2: (anything) | (undefined)): Uint8Array /* warning: the overload of function from is not supported yet. */ + val prototype: Uint8Array + declare fun id"of"(args0: (Num) | (MutArray[Num])): Uint8Array + val BYTES_PER_ELEMENT: Num +} +declare trait Uint8ClampedArray { + declare fun valueOf(): Uint8ClampedArray + declare fun lastIndexOf(args0: Num, args1: (Num) | (undefined)): Num + declare fun every(args0: (value: Num, index: Num, array: Uint8ClampedArray) => anything, args1: (anything) | (undefined)): (false) | (true) + declare fun set(args0: ArrayLike[Num], args1: (Num) | (undefined)): unit + declare fun toLocaleString(): Str + val __index: unsupported["[index: number]: number;", "ES5.d.ts", 2629, 33] + declare fun reduceRight['U](args0: (previousValue: 'U, currentValue: Num, currentIndex: Num, array: Uint8ClampedArray) => 'U, args1: 'U): 'U /* warning: the overload of function reduceRight is not supported yet. */ + declare fun fill(args0: Num, args1: (Num) | (undefined), args2: (Num) | (undefined)): 'Uint8ClampedArray + declare fun sort(args0: ((a: Num, b: Num) => Num) | (undefined)): 'Uint8ClampedArray + val BYTES_PER_ELEMENT: Num + declare fun copyWithin(args0: Num, args1: (Num) | (undefined), args2: (Num) | (undefined)): 'Uint8ClampedArray + declare fun find(args0: (value: Num, index: Num, obj: Uint8ClampedArray) => (false) | (true), args1: (anything) | (undefined)): Num + declare fun subarray(args0: (Num) | (undefined), args1: (Num) | (undefined)): Uint8ClampedArray + declare fun join(args0: (Str) | (undefined)): Str + declare fun map(args0: (value: Num, index: Num, array: Uint8ClampedArray) => Num, args1: (anything) | (undefined)): Uint8ClampedArray + declare fun forEach(args0: (value: Num, index: Num, array: Uint8ClampedArray) => unit, args1: (anything) | (undefined)): unit + val buffer: ArrayBuffer + declare fun findIndex(args0: (value: Num, index: Num, obj: Uint8ClampedArray) => (false) | (true), args1: (anything) | (undefined)): Num + declare fun reverse(): Uint8ClampedArray + declare fun filter(args0: (value: Num, index: Num, array: Uint8ClampedArray) => anything, args1: (anything) | (undefined)): Uint8ClampedArray + declare fun slice(args0: (Num) | (undefined), args1: (Num) | (undefined)): Uint8ClampedArray + val byteLength: Num + declare fun reduce['U](args0: (previousValue: 'U, currentValue: Num, currentIndex: Num, array: Uint8ClampedArray) => 'U, args1: 'U): 'U /* warning: the overload of function reduce is not supported yet. */ + declare fun toString(): Str + val length: Num + declare fun some(args0: (value: Num, index: Num, array: Uint8ClampedArray) => anything, args1: (anything) | (undefined)): (false) | (true) + declare fun indexOf(args0: Num, args1: (Num) | (undefined)): Num + val byteOffset: Num +} +declare trait Uint8ClampedArrayConstructor { + val __new: unsupported["new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray;", "ES5.d.ts", 2637, 71] + declare fun from['T](args0: ArrayLike['T], args1: (v: 'T, k: Num) => Num, args2: (anything) | (undefined)): Uint8ClampedArray /* warning: the overload of function from is not supported yet. */ + val prototype: Uint8ClampedArray + declare fun id"of"(args0: (Num) | (MutArray[Num])): Uint8ClampedArray + val BYTES_PER_ELEMENT: Num +} +declare trait Int16Array { + declare fun valueOf(): Int16Array + declare fun lastIndexOf(args0: Num, args1: (Num) | (undefined)): Num + declare fun every(args0: (value: Num, index: Num, array: Int16Array) => anything, args1: (anything) | (undefined)): (false) | (true) + declare fun set(args0: ArrayLike[Num], args1: (Num) | (undefined)): unit + declare fun toLocaleString(): Str + val __index: unsupported["[index: number]: number;", "ES5.d.ts", 2909, 26] + declare fun reduceRight['U](args0: (previousValue: 'U, currentValue: Num, currentIndex: Num, array: Int16Array) => 'U, args1: 'U): 'U /* warning: the overload of function reduceRight is not supported yet. */ + declare fun fill(args0: Num, args1: (Num) | (undefined), args2: (Num) | (undefined)): 'Int16Array + declare fun sort(args0: ((a: Num, b: Num) => Num) | (undefined)): 'Int16Array + val BYTES_PER_ELEMENT: Num + declare fun copyWithin(args0: Num, args1: (Num) | (undefined), args2: (Num) | (undefined)): 'Int16Array + declare fun find(args0: (value: Num, index: Num, obj: Int16Array) => (false) | (true), args1: (anything) | (undefined)): Num + declare fun subarray(args0: (Num) | (undefined), args1: (Num) | (undefined)): Int16Array + declare fun join(args0: (Str) | (undefined)): Str + declare fun map(args0: (value: Num, index: Num, array: Int16Array) => Num, args1: (anything) | (undefined)): Int16Array + declare fun forEach(args0: (value: Num, index: Num, array: Int16Array) => unit, args1: (anything) | (undefined)): unit + val buffer: ArrayBuffer + declare fun findIndex(args0: (value: Num, index: Num, obj: Int16Array) => (false) | (true), args1: (anything) | (undefined)): Num + declare fun reverse(): Int16Array + declare fun filter(args0: (value: Num, index: Num, array: Int16Array) => anything, args1: (anything) | (undefined)): Int16Array + declare fun slice(args0: (Num) | (undefined), args1: (Num) | (undefined)): Int16Array + val byteLength: Num + declare fun reduce['U](args0: (previousValue: 'U, currentValue: Num, currentIndex: Num, array: Int16Array) => 'U, args1: 'U): 'U /* warning: the overload of function reduce is not supported yet. */ + declare fun toString(): Str + val length: Num + declare fun some(args0: (value: Num, index: Num, array: Int16Array) => anything, args1: (anything) | (undefined)): (false) | (true) + declare fun indexOf(args0: Num, args1: (Num) | (undefined)): Num + val byteOffset: Num +} +declare trait Int16ArrayConstructor { + val __new: unsupported["new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array;", "ES5.d.ts", 2917, 64] + declare fun from['T](args0: ArrayLike['T], args1: (v: 'T, k: Num) => Num, args2: (anything) | (undefined)): Int16Array /* warning: the overload of function from is not supported yet. */ + val prototype: Int16Array + declare fun id"of"(args0: (Num) | (MutArray[Num])): Int16Array + val BYTES_PER_ELEMENT: Num +} +declare trait Uint16Array { + declare fun valueOf(): Uint16Array + declare fun lastIndexOf(args0: Num, args1: (Num) | (undefined)): Num + declare fun every(args0: (value: Num, index: Num, array: Uint16Array) => anything, args1: (anything) | (undefined)): (false) | (true) + declare fun set(args0: ArrayLike[Num], args1: (Num) | (undefined)): unit + declare fun toLocaleString(): Str + val __index: unsupported["[index: number]: number;", "ES5.d.ts", 3192, 27] + declare fun reduceRight['U](args0: (previousValue: 'U, currentValue: Num, currentIndex: Num, array: Uint16Array) => 'U, args1: 'U): 'U /* warning: the overload of function reduceRight is not supported yet. */ + declare fun fill(args0: Num, args1: (Num) | (undefined), args2: (Num) | (undefined)): 'Uint16Array + declare fun sort(args0: ((a: Num, b: Num) => Num) | (undefined)): 'Uint16Array + val BYTES_PER_ELEMENT: Num + declare fun copyWithin(args0: Num, args1: (Num) | (undefined), args2: (Num) | (undefined)): 'Uint16Array + declare fun find(args0: (value: Num, index: Num, obj: Uint16Array) => (false) | (true), args1: (anything) | (undefined)): Num + declare fun subarray(args0: (Num) | (undefined), args1: (Num) | (undefined)): Uint16Array + declare fun join(args0: (Str) | (undefined)): Str + declare fun map(args0: (value: Num, index: Num, array: Uint16Array) => Num, args1: (anything) | (undefined)): Uint16Array + declare fun forEach(args0: (value: Num, index: Num, array: Uint16Array) => unit, args1: (anything) | (undefined)): unit + val buffer: ArrayBuffer + declare fun findIndex(args0: (value: Num, index: Num, obj: Uint16Array) => (false) | (true), args1: (anything) | (undefined)): Num + declare fun reverse(): Uint16Array + declare fun filter(args0: (value: Num, index: Num, array: Uint16Array) => anything, args1: (anything) | (undefined)): Uint16Array + declare fun slice(args0: (Num) | (undefined), args1: (Num) | (undefined)): Uint16Array + val byteLength: Num + declare fun reduce['U](args0: (previousValue: 'U, currentValue: Num, currentIndex: Num, array: Uint16Array) => 'U, args1: 'U): 'U /* warning: the overload of function reduce is not supported yet. */ + declare fun toString(): Str + val length: Num + declare fun some(args0: (value: Num, index: Num, array: Uint16Array) => anything, args1: (anything) | (undefined)): (false) | (true) + declare fun indexOf(args0: Num, args1: (Num) | (undefined)): Num + val byteOffset: Num +} +declare trait Uint16ArrayConstructor { + val __new: unsupported["new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array;", "ES5.d.ts", 3200, 65] + declare fun from['T](args0: ArrayLike['T], args1: (v: 'T, k: Num) => Num, args2: (anything) | (undefined)): Uint16Array /* warning: the overload of function from is not supported yet. */ + val prototype: Uint16Array + declare fun id"of"(args0: (Num) | (MutArray[Num])): Uint16Array + val BYTES_PER_ELEMENT: Num +} +declare trait Int32Array { + declare fun valueOf(): Int32Array + declare fun lastIndexOf(args0: Num, args1: (Num) | (undefined)): Num + declare fun every(args0: (value: Num, index: Num, array: Int32Array) => anything, args1: (anything) | (undefined)): (false) | (true) + declare fun set(args0: ArrayLike[Num], args1: (Num) | (undefined)): unit + declare fun toLocaleString(): Str + val __index: unsupported["[index: number]: number;", "ES5.d.ts", 3475, 26] + declare fun reduceRight['U](args0: (previousValue: 'U, currentValue: Num, currentIndex: Num, array: Int32Array) => 'U, args1: 'U): 'U /* warning: the overload of function reduceRight is not supported yet. */ + declare fun fill(args0: Num, args1: (Num) | (undefined), args2: (Num) | (undefined)): 'Int32Array + declare fun sort(args0: ((a: Num, b: Num) => Num) | (undefined)): 'Int32Array + val BYTES_PER_ELEMENT: Num + declare fun copyWithin(args0: Num, args1: (Num) | (undefined), args2: (Num) | (undefined)): 'Int32Array + declare fun find(args0: (value: Num, index: Num, obj: Int32Array) => (false) | (true), args1: (anything) | (undefined)): Num + declare fun subarray(args0: (Num) | (undefined), args1: (Num) | (undefined)): Int32Array + declare fun join(args0: (Str) | (undefined)): Str + declare fun map(args0: (value: Num, index: Num, array: Int32Array) => Num, args1: (anything) | (undefined)): Int32Array + declare fun forEach(args0: (value: Num, index: Num, array: Int32Array) => unit, args1: (anything) | (undefined)): unit + val buffer: ArrayBuffer + declare fun findIndex(args0: (value: Num, index: Num, obj: Int32Array) => (false) | (true), args1: (anything) | (undefined)): Num + declare fun reverse(): Int32Array + declare fun filter(args0: (value: Num, index: Num, array: Int32Array) => anything, args1: (anything) | (undefined)): Int32Array + declare fun slice(args0: (Num) | (undefined), args1: (Num) | (undefined)): Int32Array + val byteLength: Num + declare fun reduce['U](args0: (previousValue: 'U, currentValue: Num, currentIndex: Num, array: Int32Array) => 'U, args1: 'U): 'U /* warning: the overload of function reduce is not supported yet. */ + declare fun toString(): Str + val length: Num + declare fun some(args0: (value: Num, index: Num, array: Int32Array) => anything, args1: (anything) | (undefined)): (false) | (true) + declare fun indexOf(args0: Num, args1: (Num) | (undefined)): Num + val byteOffset: Num +} +declare trait Int32ArrayConstructor { + val __new: unsupported["new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array;", "ES5.d.ts", 3483, 64] + declare fun from['T](args0: ArrayLike['T], args1: (v: 'T, k: Num) => Num, args2: (anything) | (undefined)): Int32Array /* warning: the overload of function from is not supported yet. */ + val prototype: Int32Array + declare fun id"of"(args0: (Num) | (MutArray[Num])): Int32Array + val BYTES_PER_ELEMENT: Num +} +declare trait Uint32Array { + declare fun valueOf(): Uint32Array + declare fun lastIndexOf(args0: Num, args1: (Num) | (undefined)): Num + declare fun every(args0: (value: Num, index: Num, array: Uint32Array) => anything, args1: (anything) | (undefined)): (false) | (true) + declare fun set(args0: ArrayLike[Num], args1: (Num) | (undefined)): unit + declare fun toLocaleString(): Str + val __index: unsupported["[index: number]: number;", "ES5.d.ts", 3756, 27] + declare fun reduceRight['U](args0: (previousValue: 'U, currentValue: Num, currentIndex: Num, array: Uint32Array) => 'U, args1: 'U): 'U /* warning: the overload of function reduceRight is not supported yet. */ + declare fun fill(args0: Num, args1: (Num) | (undefined), args2: (Num) | (undefined)): 'Uint32Array + declare fun sort(args0: ((a: Num, b: Num) => Num) | (undefined)): 'Uint32Array + val BYTES_PER_ELEMENT: Num + declare fun copyWithin(args0: Num, args1: (Num) | (undefined), args2: (Num) | (undefined)): 'Uint32Array + declare fun find(args0: (value: Num, index: Num, obj: Uint32Array) => (false) | (true), args1: (anything) | (undefined)): Num + declare fun subarray(args0: (Num) | (undefined), args1: (Num) | (undefined)): Uint32Array + declare fun join(args0: (Str) | (undefined)): Str + declare fun map(args0: (value: Num, index: Num, array: Uint32Array) => Num, args1: (anything) | (undefined)): Uint32Array + declare fun forEach(args0: (value: Num, index: Num, array: Uint32Array) => unit, args1: (anything) | (undefined)): unit + val buffer: ArrayBuffer + declare fun findIndex(args0: (value: Num, index: Num, obj: Uint32Array) => (false) | (true), args1: (anything) | (undefined)): Num + declare fun reverse(): Uint32Array + declare fun filter(args0: (value: Num, index: Num, array: Uint32Array) => anything, args1: (anything) | (undefined)): Uint32Array + declare fun slice(args0: (Num) | (undefined), args1: (Num) | (undefined)): Uint32Array + val byteLength: Num + declare fun reduce['U](args0: (previousValue: 'U, currentValue: Num, currentIndex: Num, array: Uint32Array) => 'U, args1: 'U): 'U /* warning: the overload of function reduce is not supported yet. */ + declare fun toString(): Str + val length: Num + declare fun some(args0: (value: Num, index: Num, array: Uint32Array) => anything, args1: (anything) | (undefined)): (false) | (true) + declare fun indexOf(args0: Num, args1: (Num) | (undefined)): Num + val byteOffset: Num +} +declare trait Uint32ArrayConstructor { + val __new: unsupported["new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array;", "ES5.d.ts", 3764, 65] + declare fun from['T](args0: ArrayLike['T], args1: (v: 'T, k: Num) => Num, args2: (anything) | (undefined)): Uint32Array /* warning: the overload of function from is not supported yet. */ + val prototype: Uint32Array + declare fun id"of"(args0: (Num) | (MutArray[Num])): Uint32Array + val BYTES_PER_ELEMENT: Num +} +declare trait Float32Array { + declare fun valueOf(): Float32Array + declare fun lastIndexOf(args0: Num, args1: (Num) | (undefined)): Num + declare fun every(args0: (value: Num, index: Num, array: Float32Array) => anything, args1: (anything) | (undefined)): (false) | (true) + declare fun set(args0: ArrayLike[Num], args1: (Num) | (undefined)): unit + declare fun toLocaleString(): Str + val __index: unsupported["[index: number]: number;", "ES5.d.ts", 4038, 28] + declare fun reduceRight['U](args0: (previousValue: 'U, currentValue: Num, currentIndex: Num, array: Float32Array) => 'U, args1: 'U): 'U /* warning: the overload of function reduceRight is not supported yet. */ + declare fun fill(args0: Num, args1: (Num) | (undefined), args2: (Num) | (undefined)): 'Float32Array + declare fun sort(args0: ((a: Num, b: Num) => Num) | (undefined)): 'Float32Array + val BYTES_PER_ELEMENT: Num + declare fun copyWithin(args0: Num, args1: (Num) | (undefined), args2: (Num) | (undefined)): 'Float32Array + declare fun find(args0: (value: Num, index: Num, obj: Float32Array) => (false) | (true), args1: (anything) | (undefined)): Num + declare fun subarray(args0: (Num) | (undefined), args1: (Num) | (undefined)): Float32Array + declare fun join(args0: (Str) | (undefined)): Str + declare fun map(args0: (value: Num, index: Num, array: Float32Array) => Num, args1: (anything) | (undefined)): Float32Array + declare fun forEach(args0: (value: Num, index: Num, array: Float32Array) => unit, args1: (anything) | (undefined)): unit + val buffer: ArrayBuffer + declare fun findIndex(args0: (value: Num, index: Num, obj: Float32Array) => (false) | (true), args1: (anything) | (undefined)): Num + declare fun reverse(): Float32Array + declare fun filter(args0: (value: Num, index: Num, array: Float32Array) => anything, args1: (anything) | (undefined)): Float32Array + declare fun slice(args0: (Num) | (undefined), args1: (Num) | (undefined)): Float32Array + val byteLength: Num + declare fun reduce['U](args0: (previousValue: 'U, currentValue: Num, currentIndex: Num, array: Float32Array) => 'U, args1: 'U): 'U /* warning: the overload of function reduce is not supported yet. */ + declare fun toString(): Str + val length: Num + declare fun some(args0: (value: Num, index: Num, array: Float32Array) => anything, args1: (anything) | (undefined)): (false) | (true) + declare fun indexOf(args0: Num, args1: (Num) | (undefined)): Num + val byteOffset: Num +} +declare trait Float32ArrayConstructor { + val __new: unsupported["new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array;", "ES5.d.ts", 4046, 66] + declare fun from['T](args0: ArrayLike['T], args1: (v: 'T, k: Num) => Num, args2: (anything) | (undefined)): Float32Array /* warning: the overload of function from is not supported yet. */ + val prototype: Float32Array + declare fun id"of"(args0: (Num) | (MutArray[Num])): Float32Array + val BYTES_PER_ELEMENT: Num +} +declare trait Float64Array { + declare fun valueOf(): Float64Array + declare fun lastIndexOf(args0: Num, args1: (Num) | (undefined)): Num + declare fun every(args0: (value: Num, index: Num, array: Float64Array) => anything, args1: (anything) | (undefined)): (false) | (true) + declare fun set(args0: ArrayLike[Num], args1: (Num) | (undefined)): unit + val __index: unsupported["[index: number]: number;", "ES5.d.ts", 4312, 28] + declare fun reduceRight['U](args0: (previousValue: 'U, currentValue: Num, currentIndex: Num, array: Float64Array) => 'U, args1: 'U): 'U /* warning: the overload of function reduceRight is not supported yet. */ + declare fun fill(args0: Num, args1: (Num) | (undefined), args2: (Num) | (undefined)): 'Float64Array + declare fun sort(args0: ((a: Num, b: Num) => Num) | (undefined)): 'Float64Array + val BYTES_PER_ELEMENT: Num + declare fun copyWithin(args0: Num, args1: (Num) | (undefined), args2: (Num) | (undefined)): 'Float64Array + declare fun find(args0: (value: Num, index: Num, obj: Float64Array) => (false) | (true), args1: (anything) | (undefined)): Num + declare fun subarray(args0: (Num) | (undefined), args1: (Num) | (undefined)): Float64Array + declare fun join(args0: (Str) | (undefined)): Str + declare fun map(args0: (value: Num, index: Num, array: Float64Array) => Num, args1: (anything) | (undefined)): Float64Array + declare fun forEach(args0: (value: Num, index: Num, array: Float64Array) => unit, args1: (anything) | (undefined)): unit + val buffer: ArrayBuffer + declare fun findIndex(args0: (value: Num, index: Num, obj: Float64Array) => (false) | (true), args1: (anything) | (undefined)): Num + declare fun reverse(): Float64Array + declare fun filter(args0: (value: Num, index: Num, array: Float64Array) => anything, args1: (anything) | (undefined)): Float64Array + declare fun slice(args0: (Num) | (undefined), args1: (Num) | (undefined)): Float64Array + val byteLength: Num + declare fun reduce['U](args0: (previousValue: 'U, currentValue: Num, currentIndex: Num, array: Float64Array) => 'U, args1: 'U): 'U /* warning: the overload of function reduce is not supported yet. */ + declare fun toString(): Str + val length: Num + declare fun some(args0: (value: Num, index: Num, array: Float64Array) => anything, args1: (anything) | (undefined)): (false) | (true) + declare fun indexOf(args0: Num, args1: (Num) | (undefined)): Num + val byteOffset: Num +} +declare trait Float64ArrayConstructor { + val __new: unsupported["new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array;", "ES5.d.ts", 4320, 66] + declare fun from['T](args0: ArrayLike['T], args1: (v: 'T, k: Num) => Num, args2: (anything) | (undefined)): Float64Array /* warning: the overload of function from is not supported yet. */ + val prototype: Float64Array + declare fun id"of"(args0: (Num) | (MutArray[Num])): Float64Array + val BYTES_PER_ELEMENT: Num +} +declare module Intl { + export declare trait CollatorOptions { + val sensitivity: (Str) | (undefined) + val ignorePunctuation: ((false) | (true)) | (undefined) + val usage: (Str) | (undefined) + val localeMatcher: (Str) | (undefined) + val numeric: ((false) | (true)) | (undefined) + val caseFirst: (Str) | (undefined) + } + export declare trait ResolvedCollatorOptions { + val sensitivity: Str + val ignorePunctuation: (false) | (true) + val usage: Str + val locale: Str + val numeric: (false) | (true) + val caseFirst: Str + val collation: Str + } + export declare trait Collator { + declare fun compare(args0: Str, args1: Str): Num + declare fun resolvedOptions(): ResolvedCollatorOptions + declare fun supportedLocalesOf(args0: (Str) | (MutArray[Str]), args1: (CollatorOptions) | (undefined)): MutArray[Str] + } + export declare trait NumberFormatOptions { + val minimumSignificantDigits: (Num) | (undefined) + val useGrouping: ((false) | (true)) | (undefined) + val style: (Str) | (undefined) + val localeMatcher: (Str) | (undefined) + val currency: (Str) | (undefined) + val minimumIntegerDigits: (Num) | (undefined) + val maximumFractionDigits: (Num) | (undefined) + val currencySign: (Str) | (undefined) + val maximumSignificantDigits: (Num) | (undefined) + val minimumFractionDigits: (Num) | (undefined) + } + export declare trait ResolvedNumberFormatOptions { + val numberingSystem: Str + val minimumSignificantDigits: (Num) | (undefined) + val useGrouping: (false) | (true) + val style: Str + val locale: Str + val currency: (Str) | (undefined) + val minimumIntegerDigits: Num + val maximumFractionDigits: Num + val maximumSignificantDigits: (Num) | (undefined) + val minimumFractionDigits: Num + } + export declare trait NumberFormat { + declare fun format(args0: Num): Str + declare fun resolvedOptions(): ResolvedNumberFormatOptions + declare fun supportedLocalesOf(args0: (Str) | (MutArray[Str]), args1: (NumberFormatOptions) | (undefined)): MutArray[Str] + val prototype: NumberFormat + } + export declare trait DateTimeFormatOptions { + val minute: ((Str) | (Str)) | (undefined) + val year: ((Str) | (Str)) | (undefined) + val hour: ((Str) | (Str)) | (undefined) + val hour12: ((false) | (true)) | (undefined) + val weekday: (((Str) | (Str)) | (Str)) | (undefined) + val formatMatcher: ((Str) | (Str)) | (undefined) + val day: ((Str) | (Str)) | (undefined) + val timeZone: (Str) | (undefined) + val month: (((((Str) | (Str)) | (Str)) | (Str)) | (Str)) | (undefined) + val second: ((Str) | (Str)) | (undefined) + val localeMatcher: ((Str) | (Str)) | (undefined) + val timeZoneName: ((((((Str) | (Str)) | (Str)) | (Str)) | (Str)) | (Str)) | (undefined) + val era: (((Str) | (Str)) | (Str)) | (undefined) + } + export declare trait ResolvedDateTimeFormatOptions { + val numberingSystem: Str + val minute: (Str) | (undefined) + val year: (Str) | (undefined) + val hour: (Str) | (undefined) + val second: (Str) | (undefined) + val hour12: ((false) | (true)) | (undefined) + val weekday: (Str) | (undefined) + val day: (Str) | (undefined) + val timeZone: Str + val month: (Str) | (undefined) + val locale: Str + val calendar: Str + val timeZoneName: (Str) | (undefined) + val era: (Str) | (undefined) + } + export declare trait DateTimeFormat { + declare fun format(args0: ((Num) | (Date)) | (undefined)): Str + declare fun resolvedOptions(): ResolvedDateTimeFormatOptions + declare fun supportedLocalesOf(args0: (Str) | (MutArray[Str]), args1: (DateTimeFormatOptions) | (undefined)): MutArray[Str] + val prototype: DateTimeFormat + } +} diff --git a/driver/npm/lib/predefs/Predef.mlsi b/driver/npm/lib/predefs/Predef.mlsi new file mode 100644 index 000000000..05056a23d --- /dev/null +++ b/driver/npm/lib/predefs/Predef.mlsi @@ -0,0 +1,134 @@ +// Re-declare some types in es5 + +declare type PropertyKey = Str | Num | Symbol + +declare class Object { + fun toString(): Str + fun toLocaleString(): Str + fun valueOf(): Str + fun hasOwnProperty(v: PropertyKey): Bool + fun isPrototypeOf(v: Object): Bool + fun propertyIsEnumerable(v: PropertyKey): Bool +} + +declare class Str extends Object { + fun toString(): Str + fun charAt(pos: Num): Str + fun charCodeAt(index: Num): Num + fun concat(strings: Str | Array[Str]): Str + fun indexOf(searchString: Str, position: Num | undefined): Num + fun lastIndexOf(searchString: Str, position: Num | undefined): Num + fun localeCompare(that: Str): Num + fun match(regexp: Str | RegExp): RegExpMatchArray | null + fun replace(searchValue: Str | RegExp, replaceValue: Str): Str + fun search(regexp: Str | RegExp): Num + fun slice(start: Num | undefined, end: Num | undefined): Str + fun split(separator: Str | RegExp, limit: Num | undefined): Array[Str] + fun substring(start: Num, end: Num | undefined): Str + fun toLowerCase(): Str + fun toLocaleLowerCase(locales: Str | Array[Str] | undefined): Str + fun toUpperCase(): Str + fun toLocaleUpperCase(locales: Str | Array[Str] | undefined): Str + fun trim(): Str + val length: Num +} + +declare module String { + fun fromCharCode(codes: Num | Array[Num]): Str +} + +declare class Num { + fun toString(radix: Num | undefined): Str + fun toFixed(fractionDigits: Num | undefined): Str + fun toExponential(fractionDigits: Num | undefined): Str + fun toPrecision(precision: Num | undefined): Str +} + +declare module Number { + val MAX_VALUE: Num + val MIN_VALUE: Num + val NaN: Num + val NEGATIVE_INFINITY: Num + val POSITIVE_INFINITY: Num +} + +declare module Math { + val E: Num + val LN10: Num + val LN2: Num + val LOG2E: Num + val LOG10E: Num + val PI: Num + val SQRT1_2: Num + val SQRT2: Num + fun abs(x: Num): Num + fun acos(x: Num): Num + fun asin(x: Num): Num + fun atan(x: Num): Num + fun atan2(y: Num, x: Num): Num + fun ceil(x: Num): Num + fun cos(x: Num): Num + fun exp(x: Num): Num + fun floor(x: Num): Num + fun log(x: Num): Num + fun max(values: Num | Array[Num]): Num + fun min(values: Num | Array[Num]): Num + fun pow(x: Num, y: Num): Num + fun random(): Num + fun round(x: Num): Num + fun sin(x: Num): Num + fun sqrt(x: Num): Num + fun tan(x: Num): Num +} + +class Date { + constructor(value: Num | Str | undefined) + toString(): Str + toDateString(): Str + toTimeString(): Str + toLocaleString(): Str + toLocaleDateString(): Str + toLocaleTimeString(): Str + valueOf(): Num + getTime(): Num + getFullYear(): Num + getUTCFullYear(): Num + getMonth(): Num + getUTCMonth(): Num + getDate(): Num + getUTCDate(): Num + getDay(): Num + getUTCDay(): Num + getHours(): Num + getUTCHours(): Num + getMinutes(): Num + getUTCMinutes(): Num + getSeconds(): Num + getUTCSeconds(): Num + getMilliseconds(): Num + getUTCMilliseconds(): Num + getTimezoneOffset(): Num + setTime(time: Num): Num + setMilliseconds(ms: Num): Num + setUTCMilliseconds(ms: Num): Num + setSeconds(sec: Num, ms: Num | undefined): Num + setUTCSeconds(sec: Num, ms: Num | undefined): Num + setMinutes(min: Num, sec: Num | undefined, ms: Num | undefined): Num + setUTCMinutes(min: Num, sec: Num | undefined, ms: Num | undefined): Num + setHours(hours: Num, min: Num | undefined, sec: Num | undefined, ms: Num | undefined): Num + setUTCHours(hours: Num, min: Num | undefined, sec: Num | undefined, ms: Num | undefined): Num + setDate(date: Num): Num + setUTCDate(date: Num): Num + setMonth(month: Num, date: Num): Num + setUTCMonth(month: Num, date: Num | undefined): Num + setFullYear(year: Num, month: Num | undefined, date: Num | undefined): Num + setUTCFullYear(year: Num, month: Num | undefined, date: Num | undefined): Num + toUTCString(): Str + toISOString(): Str + toJSON(key: anything | undefined): Str +} + +declare module JSON { + fun parse(text: Str, reviver: ((this: anything, key: Str, value: anything) => anything) | undefined): anything + fun stringify(value: anything, replacer: Array[(Num | Str)] | null, space: Str | Num | undefined): Str +} diff --git a/driver/npm/package.json b/driver/npm/package.json new file mode 100644 index 000000000..40e715b89 --- /dev/null +++ b/driver/npm/package.json @@ -0,0 +1,28 @@ +{ + "name": "mlscript", + "version": "0.0.1-beta.5", + "description": "mlscript", + "types": "lib/index.d.ts", + "main": "lib/index.js", + "scripts": { + }, + "repository": { + "type": "git", + "url": "git+https://github.com/hkust-taco/mlscript.git" + }, + "keywords": [ + "functional-programming", + "type-inference" + ], + "author": "HKUST TACO Lab", + "license": "MIT", + "bugs": { + "url": "https://github.com/hkust-taco/mlscript/issues" + }, + "homepage": "https://github.com/hkust-taco/mlscript#readme", + "dependencies": { + "json5": "^2.2.3", + "typescript": "^4.7.4", + "chokidar": "^3.5.3" + } +} diff --git a/package-lock.json b/package-lock.json index 636e503a3..bbc51e65f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5,9 +5,193 @@ "packages": { "": { "dependencies": { + "chokidar": "^3.5.3", + "json5": "^2.2.3", "typescript": "^4.7.4" } }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/binary-extensions": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", + "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==", + "engines": { + "node": ">=8" + } + }, + "node_modules/braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "dependencies": { + "fill-range": "^7.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/chokidar": { + "version": "3.5.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz", + "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", + "funding": [ + { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + ], + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, "node_modules/typescript": { "version": "4.7.4", "resolved": "https://registry.npmmirror.com/typescript/-/typescript-4.7.4.tgz", @@ -22,6 +206,122 @@ } }, "dependencies": { + "anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "requires": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + } + }, + "binary-extensions": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", + "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==" + }, + "braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "requires": { + "fill-range": "^7.0.1" + } + }, + "chokidar": { + "version": "3.5.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz", + "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", + "requires": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "fsevents": "~2.3.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + } + }, + "fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "requires": { + "to-regex-range": "^5.0.1" + } + }, + "fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "optional": true + }, + "glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "requires": { + "is-glob": "^4.0.1" + } + }, + "is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "requires": { + "binary-extensions": "^2.0.0" + } + }, + "is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==" + }, + "is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "requires": { + "is-extglob": "^2.1.1" + } + }, + "is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==" + }, + "json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==" + }, + "normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==" + }, + "picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==" + }, + "readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "requires": { + "picomatch": "^2.2.1" + } + }, + "to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "requires": { + "is-number": "^7.0.0" + } + }, "typescript": { "version": "4.7.4", "resolved": "https://registry.npmmirror.com/typescript/-/typescript-4.7.4.tgz", diff --git a/package.json b/package.json index bc371fcd6..33eb144b3 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,7 @@ { "dependencies": { + "chokidar": "^3.5.3", + "json5": "^2.2.3", "typescript": "^4.7.4" } } diff --git a/scripts/ts-prepare.sh b/scripts/ts-prepare.sh new file mode 100755 index 000000000..88816657d --- /dev/null +++ b/scripts/ts-prepare.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash + +echo "install typescript and json5 for mlscript..." +npm ci +chmod 777 ./node_modules/typescript/bin/tsc + +cd driver/js/src/test/cjsprojects +echo "install ts libraries for driver cjsprojects test..." +npm ci +echo "compile ts files for driver cjsprojects test..." +../../../../../node_modules/typescript/bin/tsc + +cd ../esprojects +echo "install ts libraries for driver esprojects test..." +npm ci +echo "compile ts files for driver esprojects test..." +../../../../../node_modules/typescript/bin/tsc diff --git a/shared/src/main/scala/mlscript/ConstraintSolver.scala b/shared/src/main/scala/mlscript/ConstraintSolver.scala index e509a4857..cbc446ff6 100644 --- a/shared/src/main/scala/mlscript/ConstraintSolver.scala +++ b/shared/src/main/scala/mlscript/ConstraintSolver.scala @@ -36,8 +36,10 @@ class ConstraintSolver extends NormalForms { self: Typer => val info = ctx.tyDefs2.getOrElse(clsNme, ???/*TODO*/) if (info.isComputing) { - - ??? // TODO support? + + L(ErrorReport( + // TODO improve + msg"${info.decl.kind.str.capitalize} `${info.decl.name}` has a cyclic type dependency that is not supported yet." -> fld.toLoc :: Nil, newDefs)) } else info.complete() match { @@ -577,7 +579,13 @@ class ConstraintSolver extends NormalForms { self: Typer => if (pts.exists(p => (p.id === pt.id) || l.allTags.contains(p.id))) println(s"OK $pt <: ${pts.mkString(" | ")}") // else f.fold(reportError())(f => annoying(Nil, done_ls, Nil, f)) - else annoying(Nil, LhsRefined(N, ts, r, trs), Nil, RhsBases(Nil, bf, trs2)) + else annoying(pt.id match { + case _: IntLit => IntType :: Nil + case _: DecLit => DecType :: Nil + case _: StrLit => StrType :: Nil + case _: UnitLit => Nil + case _: Var => Nil + }, LhsRefined(N, ts, r, trs), Nil, RhsBases(Nil, bf, trs2)) case (lr @ LhsRefined(bo, ts, r, _), rf @ RhsField(n, t2)) => // Reuse the case implemented below: (this shortcut adds a few more annoying calls in stats) annoying(Nil, lr, Nil, RhsBases(Nil, S(R(rf)), SortedMap.empty)) @@ -783,7 +791,8 @@ class ConstraintSolver extends NormalForms { self: Typer => case (_, TypeBounds(lb, ub)) => rec(lhs, lb, true) case (p @ ProvType(und), _) => rec(und, rhs, true) case (_, p @ ProvType(und)) => rec(lhs, und, true) - case (_: TypeTag, _: TypeTag) if lhs === rhs => () + case (_: TypeTag, _: TypeTag) if lhs === rhs => () // required to allow signature overriding checks in declarations + case (lhs: Unsupported, rhs: Unsupported) => () case (NegType(lhs), NegType(rhs)) => rec(rhs, lhs, true) case (ClassTag(Var(nme), _), rt: RecordType) if newDefs && nme.isCapitalized => @@ -1064,6 +1073,7 @@ class ConstraintSolver extends NormalForms { self: Typer => def doesntMatch(ty: SimpleType) = msg"does not match type `${ty.expNeg}`" def doesntHaveField(n: Str) = msg"does not have field '$n'" + def doesntSupport(uns: Unsupported) = msg"(TypeScript type ${uns.showTSType}) is not supported" val lhsChain: List[ST] = cctx._1 val rhsChain: List[ST] = cctx._2 @@ -1196,6 +1206,8 @@ class ConstraintSolver extends NormalForms { self: Typer => } ) return raise(ErrorReport(msgs ::: mk_constraintProvenanceHints, newDefs)) + case (lhs: Unsupported, _) => doesntSupport(lhs) + case (_, rhs: Unsupported) => doesntSupport(rhs) case (_: TV | _: ProxyType, _) => doesntMatch(rhs) case (RecordType(fs0), RecordType(fs1)) => (fs1.map(_._1).toSet -- fs0.map(_._1).toSet) @@ -1376,7 +1388,7 @@ class ConstraintSolver extends NormalForms { self: Typer => new Extruded(!pol, tt)( tt.prov.copy(desc = "extruded type variable reference"), reason) } else die // shouldn't happen - case _: ClassTag | _: TraitTag | _: Extruded => ty + case _: ClassTag | _: TraitTag | _: Extruded | _: UnusableLike => ty case tr @ TypeRef(d, ts) => TypeRef(d, tr.mapTargs(S(pol)) { case (N, targ) => @@ -1581,7 +1593,7 @@ class ConstraintSolver extends NormalForms { self: Typer => case p @ ProxyType(und) => freshen(und) case s @ SkolemTag(id) if s.level > above && s.level <= below => freshen(id) - case _: ClassTag | _: TraitTag | _: SkolemTag | _: Extruded => ty + case _: ClassTag | _: TraitTag | _: SkolemTag | _: UnusableLike => ty case w @ Without(b, ns) => Without(freshen(b), ns)(w.prov) case tr @ TypeRef(d, ts) => TypeRef(d, ts.map(freshen(_)))(tr.prov) case pt @ PolymorphicType(polyLvl, bod) if pt.level <= above => pt // is this really useful? diff --git a/shared/src/main/scala/mlscript/Diagnostic.scala b/shared/src/main/scala/mlscript/Diagnostic.scala index b552dc7f3..4d020c835 100644 --- a/shared/src/main/scala/mlscript/Diagnostic.scala +++ b/shared/src/main/scala/mlscript/Diagnostic.scala @@ -23,6 +23,63 @@ object Diagnostic { case object Compilation extends Source case object Runtime extends Source + def report(diag: Diagnostic, output: Str => Unit, blockLineNum: Int, showRelativeLineNums: Bool, newDefs: Bool): Unit = { + val sctx = Message.mkCtx(diag.allMsgs.iterator.map(_._1), newDefs, "?") + val headStr = + diag match { + case ErrorReport(msg, loco, src) => + src match { + case Diagnostic.Lexing => + s"╔══[LEXICAL ERROR] " + case Diagnostic.Parsing => + s"╔══[PARSE ERROR] " + case _ => // TODO customize too + s"╔══[ERROR] " + } + case WarningReport(msg, loco, src) => + s"╔══[WARNING] " + } + val lastMsgNum = diag.allMsgs.size - 1 + var globalLineNum = blockLineNum // solely used for reporting useful test failure messages + diag.allMsgs.zipWithIndex.foreach { case ((msg, loco), msgNum) => + val isLast = msgNum =:= lastMsgNum + val msgStr = msg.showIn(sctx) + if (msgNum =:= 0) output(headStr + msgStr) + else output(s"${if (isLast && loco.isEmpty) "╙──" else "╟──"} ${msgStr}") + if (loco.isEmpty && diag.allMsgs.size =:= 1) output("╙──") + loco.foreach { loc => + val (startLineNum, startLineStr, startLineCol) = + loc.origin.fph.getLineColAt(loc.spanStart) + if (globalLineNum =:= 0) globalLineNum += startLineNum - 1 + val (endLineNum, endLineStr, endLineCol) = + loc.origin.fph.getLineColAt(loc.spanEnd) + var l = startLineNum + var c = startLineCol + while (l <= endLineNum) { + val globalLineNum = loc.origin.startLineNum + l - 1 + val relativeLineNum = globalLineNum - blockLineNum + 1 + val shownLineNum = + if (showRelativeLineNums && relativeLineNum > 0) s"l.+$relativeLineNum" + else "l." + globalLineNum + val prepre = "║ " + val pre = s"$shownLineNum: " + val curLine = loc.origin.fph.lines(l - 1) + output(prepre + pre + "\t" + curLine) + val tickBuilder = new StringBuilder() + tickBuilder ++= ( + (if (isLast && l =:= endLineNum) "╙──" else prepre) + + " " * pre.length + "\t" + " " * (c - 1)) + val lastCol = if (l =:= endLineNum) endLineCol else curLine.length + 1 + while (c < lastCol) { tickBuilder += ('^'); c += 1 } + if (c =:= startLineCol) tickBuilder += ('^') + output(tickBuilder.toString) + c = 1 + l += 1 + } + } + } + if (diag.allMsgs.isEmpty) output("╙──") + } } final case class ErrorReport(mainMsg: Str, allMsgs: Ls[Message -> Opt[Loc]], source: Source) extends Diagnostic(mainMsg) { diff --git a/shared/src/main/scala/mlscript/JSBackend.scala b/shared/src/main/scala/mlscript/JSBackend.scala index 0351fae58..b244e740f 100644 --- a/shared/src/main/scala/mlscript/JSBackend.scala +++ b/shared/src/main/scala/mlscript/JSBackend.scala @@ -251,7 +251,7 @@ abstract class JSBackend(allowUnresolvedSymbols: Bool) { JSLetDecl(Ls(pat.runtimeName -> S(translateTerm(rhs)(blkScope)))) case (nt: NuTypeDef, _) => translateLocalNewType(nt)(blkScope) // TODO: find out if we need to support this. - case (_: Def | _: TypeDef | _: NuFunDef | _: DataDefn | _: DatatypeDefn | _: LetS | _: Constructor, _) => + case (_: Def | _: TypeDef | _: NuFunDef | _: DataDefn | _: DatatypeDefn | _: LetS | _: Constructor | _: Import, _) => throw CodeGenError("unsupported definitions in blocks") }.toList)), Nil @@ -550,8 +550,9 @@ abstract class JSBackend(allowUnresolvedSymbols: Bool) { sym match { case S(sym: NewClassSymbol) => val localScope = scope.derive(s"local ${sym.name}") - val nd = translateNewTypeDefinition(sym, N, false)(localScope) + val nd = translateNewTypeDefinition(sym, N, false, false)(localScope) val ctorMth = localScope.declareValue("ctor", Some(false), false, N).runtimeName + val ctorScope = localScope.derive(s"${sym.lexicalName} ctor") val (constructor, params) = translateNewClassParameters(nd) val initList = if (sym.isPlainJSClass) @@ -569,7 +570,7 @@ abstract class JSBackend(allowUnresolvedSymbols: Bool) { case S(sym: MixinSymbol) => val localScope = scope.derive(s"local ${sym.name}") val base = localScope.declareValue("base", Some(false), false, N) - val nd = translateNewTypeDefinition(sym, S(base), false)(localScope) + val nd = translateNewTypeDefinition(sym, S(base), false, false)(localScope) JSConstDecl(sym.name, JSArrowFn( Ls(JSNamePattern(base.runtimeName)), R(Ls( JSReturnStmt(S(JSClassExpr(nd))) @@ -577,7 +578,7 @@ abstract class JSBackend(allowUnresolvedSymbols: Bool) { )) case S(sym: ModuleSymbol) => val localScope = scope.derive(s"local ${sym.name}") - val nd = translateNewTypeDefinition(sym, N, false)(localScope) + val nd = translateNewTypeDefinition(sym, N, false, false)(localScope) val ins = localScope.declareValue("ins", Some(false), false, N).runtimeName JSConstDecl(sym.name, JSImmEvalFn( N, Nil, R(Ls( @@ -597,7 +598,7 @@ abstract class JSBackend(allowUnresolvedSymbols: Bool) { )(implicit getterScope: Scope): JSClassMethod = { val base = getterScope.declareValue("base", Some(false), false, N) - val classBody = translateNewTypeDefinition(mixinSymbol, S(base), false)(getterScope) + val classBody = translateNewTypeDefinition(mixinSymbol, S(base), false, false)(getterScope) val qualifierStmt = mixinSymbol.qualifier.fold[JSConstDecl](die)(qualifier => JSConstDecl(qualifier, JSIdent("this"))) JSClassMethod(mixinSymbol.name, Ls(JSNamePattern(base.runtimeName)), R((qualifierStmt :: Nil) ::: Ls(JSReturnStmt(S(JSClassExpr(classBody))) @@ -610,21 +611,50 @@ abstract class JSBackend(allowUnresolvedSymbols: Bool) { def resolveName(term: Term): Str = term match { case App(lhs, _) => resolveName(lhs) case Var(name) => name - case Sel(_, Var(fieldName)) => fieldName + case Sel(parent, Var(fieldName)) => s"${resolveName(parent)}.$fieldName" case TyApp(lhs, _) => resolveName(lhs) case _ => throw CodeGenError("unsupported parents.") } - val name = resolveName(current) - - scope.resolveValue(name) match { - case Some(_: TraitSymbol) => base // TODO: - case Some(sym: MixinSymbol) => - JSInvoke(translateNuTypeSymbol(sym, true), Ls(base)) // class D() extends B -> class D extends B.class - case Some(sym: NuTypeSymbol) if !mixinOnly => - translateNuTypeSymbol(sym, true) - case Some(t) => throw CodeGenError(s"unexpected parent symbol $t.") - case N => throw CodeGenError(s"unresolved parent $name.") + val fullname = resolveName(current).split("\\.").toList + fullname match { + case name :: Nil => scope.resolveValue(name) match { + case Some(_: TraitSymbol) => base // TODO: + case Some(sym: MixinSymbol) => + JSInvoke(translateNuTypeSymbol(sym, true), Ls(base)) + case Some(sym: NuTypeSymbol) if !mixinOnly => + translateNuTypeSymbol(sym, true) + case Some(t) => throw CodeGenError(s"unexpected parent symbol $t.") + case N => throw CodeGenError(s"unresolved parent $name.") + } + case top :: rest => { + def insertParent(parent: Str, child: JSExpr): JSExpr = child match { + case JSIdent(name) => JSIdent(parent).member(name) + case field: JSField => insertParent(parent, field.`object`).member(field.property.name) + case _ => throw new AssertionError("unsupported parent expression.") + } + def resolveSelection(restNames: Ls[Str], nested: Ls[NuTypeDef], res: JSExpr): JSExpr = restNames match { + case name :: Nil => nested.find(_.nme.name === name).fold( + throw CodeGenError(s"parent $name not found.") + )(p => + if (p.kind === Mxn) JSInvoke(res.member(name), Ls(base)) + else if (p.isPlainJSClass) res.member(name) + else res.member(name).member("class") + ) + case cur :: rest => (nested.find { + case nd: NuTypeDef => nd.kind === Mod && nd.nme.name === cur + case _ => false + }).fold[JSExpr]( + throw CodeGenError(s"module $cur not found.") + )(md => resolveSelection(rest, md.body.entities.collect{ case nd: NuTypeDef => nd }, insertParent(cur, res))) + case Nil => throw new AssertionError("unexpected code state in resolve selection.") + } + scope.resolveValue(top) match { + case Some(sym: ModuleSymbol) => resolveSelection(rest, sym.nested, translateNuTypeSymbol(sym, false)) + case _ => throw CodeGenError(s"type selection ${fullname.mkString(".")} is not supported in inheritance now.") + } + } + case _ => throw CodeGenError(s"unresolved parent ${fullname.mkString(".")}.") } } @@ -640,15 +670,16 @@ abstract class JSBackend(allowUnresolvedSymbols: Bool) { protected def translateTopModuleDeclaration( moduleSymbol: ModuleSymbol, - keepTopLevelScope: Bool + keepTopLevelScope: Bool, + needSeparateCtor: Bool )(implicit scope: Scope): JSClassNewDecl = - translateNewTypeDefinition(moduleSymbol, N, keepTopLevelScope) + translateNewTypeDefinition(moduleSymbol, N, keepTopLevelScope, needSeparateCtor) protected def translateModuleDeclaration( moduleSymbol: ModuleSymbol, siblingsMembers: Ls[RuntimeSymbol] )(implicit getterScope: Scope): JSClassGetter = { - val decl = translateNewTypeDefinition(moduleSymbol, N, false)(getterScope) + val decl = translateNewTypeDefinition(moduleSymbol, N, false, false)(getterScope) val privateIdent = JSIdent(s"this.#${moduleSymbol.name}") val qualifierStmt = moduleSymbol.qualifier.fold[JSConstDecl](die)(qualifier => JSConstDecl(qualifier, JSIdent("this"))) JSClassGetter(moduleSymbol.name, R((qualifierStmt :: Nil) ::: @@ -674,7 +705,7 @@ abstract class JSBackend(allowUnresolvedSymbols: Bool) { siblingsMembers: Ls[RuntimeSymbol] )(implicit getterScope: Scope): JSClassGetter = { val classBody = - translateNewTypeDefinition(classSymbol, N, false)(getterScope) + translateNewTypeDefinition(classSymbol, N, false, false)(getterScope) val (constructor, params) = translateNewClassParameters(classBody) val privateIdent = JSIdent(s"this.#${classSymbol.name}") @@ -701,7 +732,8 @@ abstract class JSBackend(allowUnresolvedSymbols: Bool) { protected def translateNewTypeDefinition( sym: TypeSymbol with NuTypeSymbol, baseSym: Opt[ValueSymbol], - keepTopLevelScope: Bool + keepTopLevelScope: Bool, + needSeparateCtor: Bool )(implicit scope: Scope): JSClassNewDecl = { // * nuTypeScope: root scope // ** inheritanceScope: contains specialized parameters for `super(...)` @@ -711,7 +743,9 @@ abstract class JSBackend(allowUnresolvedSymbols: Bool) { val nuTypeScope = scope.derive(sym.toString) val inheritanceScope = nuTypeScope.derive(s"${sym.name} inheritance") val bodyScope = nuTypeScope.derive(s"${sym.name} body") - val constructorScope = bodyScope.derive(s"${sym.name} constructor") + val constructorScope = + if (!needSeparateCtor) bodyScope.derive(s"${sym.lexicalName} constructor") + else bodyScope.derive(s"${sym.lexicalName} $$init") val memberList = ListBuffer[RuntimeSymbol]() // pass to the getter of nested types val typeList = ListBuffer[Str]() @@ -851,6 +885,15 @@ abstract class JSBackend(allowUnresolvedSymbols: Bool) { case _ => Nil } + val qualifierStmt = qualifier.fold[Ls[JSStmt]](Nil)(qualifier => + translateQualifierDeclaration(constructorScope.resolveQualifier(qualifier))) + val (initStmts, initMths) = + if (!needSeparateCtor) (qualifierStmt ++ tempDecs ++ stmts, Nil) + else { + val initSymbol = nuTypeScope.declareValue("$init", Some(false), true, N) + (Nil, JSClassMethod(initSymbol.runtimeName, Nil, R(qualifierStmt ++ tempDecs ++ stmts)) :: Nil) + } + val staticMethods = sym.unapplyMtd match { // * Note: this code is a bad temporary hack until we have proper `unapply` desugaring case S(unapplyMtd) => unapplyMtd.rhs match { @@ -868,8 +911,6 @@ abstract class JSBackend(allowUnresolvedSymbols: Bool) { case _ => Nil } - val qualifierStmt = qualifier.fold[Ls[JSStmt]](Nil)(qualifier => - translateQualifierDeclaration(constructorScope.resolveQualifier(qualifier))) JSClassNewDecl( sym.name, fields, @@ -879,9 +920,9 @@ abstract class JSBackend(allowUnresolvedSymbols: Bool) { superParameters, ctorParams, rest, - members, + members ::: initMths, traits, - qualifierStmt ++ tempDecs ++ initFields ++ stmts, + tempDecs ++ initFields ++ initStmts, typeList.toList, sym.ctorParams.isDefined, staticMethods @@ -1042,10 +1083,15 @@ abstract class JSBackend(allowUnresolvedSymbols: Bool) { (body, members, signatures, stmts, nested, publicCtors) } + def checkNewTypeName(nme: Str): Unit = + if (Symbol.isKeyword(nme)) + throw CodeGenError(s"$nme is a reserved keyword in ECMAScript and can not be used as type name.") + typeDefs.foreach { - case td @ NuTypeDef(Mxn, TypeName(mxName), tps, tup, ctor, sig, pars, sup, ths, unit) => { - val (body, members, signatures, stmts, nested, publicCtors) = prepare(mxName, tup.getOrElse(Tup(Nil)).fields, pars, unit) - val sym = MixinSymbol(mxName, tps map { _._2.name }, body, members, signatures, stmts, publicCtors, nested, qualifier).tap(scope.register) + case td @ NuTypeDef(Mxn, TypeName(nme), tps, tup, ctor, sig, pars, sup, ths, unit) => { + if (!td.isDecl) checkNewTypeName(nme) + val (body, members, signatures, stmts, nested, publicCtors) = prepare(nme, tup.getOrElse(Tup(Nil)).fields, pars, unit) + val sym = MixinSymbol(nme, tps map { _._2.name }, body, members, signatures, stmts, publicCtors, nested, qualifier).tap(scope.register) if (!td.isDecl) mixins += sym } case td @ NuTypeDef(Mod, TypeName(nme), tps, tup, ctor, sig, pars, sup, ths, unit) => { @@ -1054,9 +1100,11 @@ abstract class JSBackend(allowUnresolvedSymbols: Bool) { if (!td.isDecl) modules += sym } case td @ NuTypeDef(Als, TypeName(nme), tps, _, ctor, sig, pars, _, _, _) => { + if (!td.isDecl) checkNewTypeName(nme) scope.declareTypeAlias(nme, tps map { _._2.name }, sig.getOrElse(Top)) } case td @ NuTypeDef(Cls, TypeName(nme), tps, tup, ctor, sig, pars, sup, ths, unit) => { + if (!td.isDecl) checkNewTypeName(nme) val (params, preStmts) = ctor match { case S(Constructor(Tup(ls), Blk(stmts))) => (S(ls.map { case (S(Var(nme)), Fld(flags, _)) => (nme, flags.genGetter) @@ -1075,6 +1123,7 @@ abstract class JSBackend(allowUnresolvedSymbols: Bool) { if (!td.isDecl) classes += sym } case td @ NuTypeDef(Trt, TypeName(nme), tps, tup, ctor, sig, pars, sup, ths, unit) => { + if (!td.isDecl) checkNewTypeName(nme) val (body, members, _, _, _, _) = prepare(nme, tup.getOrElse(Tup(Nil)).fields, pars, unit) val sym = scope.declareTrait(nme, tps map { _._2.name }, body, members) if (!td.isDecl) traits += sym @@ -1216,7 +1265,7 @@ class JSWebBackend extends JSBackend(allowUnresolvedSymbols = true) { // don't pass `otherStmts` to the top-level module, because we need to execute them one by one later val topModule = topLevelScope.declareTopModule("TypingUnit", Nil, typeDefs, true) val moduleIns = topLevelScope.declareValue("typing_unit", Some(false), false, N) - val moduleDecl = translateTopModuleDeclaration(topModule, true)(topLevelScope) + val moduleDecl = translateTopModuleDeclaration(topModule, true, false)(topLevelScope) val insDecl = JSConstDecl(moduleIns.runtimeName, JSNew(JSIdent(topModule.name))) @@ -1419,7 +1468,7 @@ abstract class JSTestBackend extends JSBackend(allowUnresolvedSymbols = false) { // don't pass `otherStmts` to the top-level module, because we need to execute them one by one later val topModule = topLevelScope.declareTopModule("TypingUnit", Nil, typeDefs, true) val moduleIns = topLevelScope.declareValue("typing_unit", Some(false), false, N) - val moduleDecl = translateTopModuleDeclaration(topModule, true) + val moduleDecl = translateTopModuleDeclaration(topModule, true, false) val insDecl = JSConstDecl(moduleIns.runtimeName, JSNew(JSIdent(topModule.runtimeName))) diff --git a/shared/src/main/scala/mlscript/NewLexer.scala b/shared/src/main/scala/mlscript/NewLexer.scala index 4985c2fce..5733f0f90 100644 --- a/shared/src/main/scala/mlscript/NewLexer.scala +++ b/shared/src/main/scala/mlscript/NewLexer.scala @@ -52,13 +52,7 @@ class NewLexer(origin: Origin, raise: Diagnostic => Unit, dbg: Bool) { // ">", ) - private val isAlphaOp = Set( - "with", - "and", - "or", - "is", - "as", - ) + private val isAlphaOp = alpahOp @tailrec final def takeWhile(i: Int, cur: Ls[Char] = Nil)(pred: Char => Bool): (Str, Int) = @@ -200,6 +194,13 @@ class NewLexer(origin: Origin, raise: Diagnostic => Unit, dbg: Bool) { // @inline // def go(j: Int, tok: Token) = lex(j, ind, (tok, loc(i, j)) :: acc) def next(j: Int, tok: Token) = (tok, loc(i, j)) :: acc + def isIdentEscape(i: Int): Bool = i + 2 < length && bytes(i) === 'i' && bytes(i + 1) === 'd' && bytes(i + 2) === '"' + def takeIdentFromEscape(i: Int, ctor: Str => Token) = { + val (n, j) = takeWhile(i + 3)(_ != '"') + if (j < length && bytes(j) === '"') (ctor(n), j + 1) + else { pe(msg"unfinished identifier escape"); (ERROR, j + 1) } + } + c match { case ' ' => val (_, j) = takeWhile(i)(_ === ' ') @@ -263,6 +264,9 @@ class NewLexer(origin: Origin, raise: Diagnostic => Unit, dbg: Bool) { else (NEWLINE, loc(i, k)) :: acc ) } + case _ if isIdentEscape(i) => + val (tok, n) = takeIdentFromEscape(i, s => IDENT(s, false)) + lex(n, ind, next(n, tok)) case _ if isIdentFirstChar(c) => val (n, j) = takeWhile(i)(isIdentChar) // go(j, if (keywords.contains(n)) KEYWORD(n) else IDENT(n, isAlphaOp(n))) @@ -271,7 +275,11 @@ class NewLexer(origin: Origin, raise: Diagnostic => Unit, dbg: Bool) { val (n, j) = takeWhile(i)(isOpChar) if (n === "." && j < length) { val nc = bytes(j) - if (isIdentFirstChar(nc)) { + if (isIdentFirstChar(bytes(j)) && isIdentEscape(j)) { + val (body, m) = takeIdentFromEscape(j, SELECT) + lex(m, ind, next(m, body)) + } + else if (isIdentFirstChar(nc)) { val (name, k) = takeWhile(j)(isIdentChar) // go(k, SELECT(name)) lex(k, ind, next(k, SELECT(name))) @@ -415,6 +423,7 @@ object NewLexer { // "all", "mut", "declare", + "export", "class", "trait", "mixin", @@ -431,11 +440,22 @@ object NewLexer { "exists", "in", "out", + "weak", + "import", "null", "undefined", "abstract", "constructor", - "virtual" + "virtual", + "unsupported" + ) + + val alpahOp: Set[Str] = Set( + "with", + "and", + "or", + "is", + "as", ) def printToken(tl: TokLoc): Str = tl match { diff --git a/shared/src/main/scala/mlscript/NewParser.scala b/shared/src/main/scala/mlscript/NewParser.scala index a85ea1a83..b081c880c 100644 --- a/shared/src/main/scala/mlscript/NewParser.scala +++ b/shared/src/main/scala/mlscript/NewParser.scala @@ -224,8 +224,28 @@ abstract class NewParser(origin: Origin, tokens: Ls[Stroken -> Loc], newDefs: Bo } */ + final def tuWithImports: (TypingUnit, Ls[Import]) = { + val ts = block(Nil)(false, false) + val (es, dp) = ts.partitionMap { + case R(imp: Import) => R(imp) + case s => L(s) + } match { + case (es, dp) => + (es.map { + case L(t) => + err(msg"Unexpected 'then'/'else' clause" -> t.toLoc :: Nil) + errExpr + case R(d: NuDecl) => d + case R(e: Term) => e + case R(c: Constructor) => c + case _ => ??? + }, dp) + } + (TypingUnit(es), dp) + } + final def typingUnit: TypingUnit = { - val ts = block(false, false) + val ts = block(Nil)(false, false) val es = ts.map { case L(t) => err(msg"Unexpected 'then'/'else' clause" -> t.toLoc :: Nil) @@ -277,6 +297,10 @@ abstract class NewParser(origin: Origin, tokens: Ls[Stroken -> Loc], newDefs: Bo consume yeetSpaces go(acc.copy(acc.mods + ("declare" -> l0))) + case (KEYWORD("export"), l0) :: c => + consume + yeetSpaces + go(acc.copy(acc.mods + ("export" -> l0))) case (KEYWORD("virtual"), l0) :: c => consume yeetSpaces @@ -301,11 +325,24 @@ abstract class NewParser(origin: Origin, tokens: Ls[Stroken -> Loc], newDefs: Bo S(res, _cur) } } - final def block(implicit et: ExpectThen, fe: FoundErr): Ls[IfBody \/ Statement] = + + final def importPath: Str = yeetSpaces match { + case (LITVAL(StrLit(path)), _) :: _ => + consume + path + case c => + val (tkstr, loc) = c.headOption.fold(("end of input", lastLoc))(_.mapFirst(_.describe).mapSecond(some)) + err(( + msg"Expected a module path; found ${tkstr} instead" -> loc :: Nil)) + "" + } + + + final def block(prev: Ls[IfBody \/ Statement])(implicit et: ExpectThen, fe: FoundErr): Ls[IfBody \/ Statement] = cur match { - case Nil => Nil - case (NEWLINE, _) :: _ => consume; block - case (SPACE, _) :: _ => consume; block + case Nil => prev.reverse + case (NEWLINE, _) :: _ => consume; block(prev) + case (SPACE, _) :: _ => consume; block(prev) case (KEYWORD("constructor"), l0) :: _ => consume val res = yeetSpaces match { @@ -318,14 +355,37 @@ abstract class NewParser(origin: Origin, tokens: Ls[Stroken -> Loc], newDefs: Bo err(msg"Expect parameter list for the constructor" -> S(l0) :: Nil) Constructor(Tup(Nil), Blk(Nil)) } - R(res.withLoc(S(l0 ++ res.getLoc))) :: block + val t = R(res.withLoc(S(l0 ++ res.getLoc))) + yeetSpaces match { + case (NEWLINE | KEYWORD(";;"), _) :: _ => consume; block(t :: prev) + case _ => (t :: prev).reverse + } case c => val t = c match { + case (KEYWORD("weak"), l0) :: c => + consume + yeetSpaces match { + case (KEYWORD("import"), l1) :: _ => + consume + val path = importPath + val res = Import(path, true) + R(res.withLoc(S(l0 ++ l1 ++ res.getLoc))) + case _ => + err(msg"Unexpected weak" -> S(l0) :: Nil) + R(errExpr) + } + + case (KEYWORD("import"), l0) :: c => + consume + val path = importPath + val res = Import(path, false) + R(res.withLoc(S(l0 ++ res.getLoc))) case ModifierSet(mods, (KEYWORD(k @ ("class" | "infce" | "trait" | "mixin" | "type" | "module")), l0) :: c) => consume val (isDecl, mods2) = mods.handle("declare") - val (isAbs, mods3) = mods2.handle("abstract") - mods3.done + val (isExported, mods3) = mods2.handle("export") + val (isAbs, mods4) = mods3.handle("abstract") + mods4.done val kind = k match { case "class" => Cls case "trait" => Trt @@ -417,15 +477,15 @@ abstract class NewParser(origin: Origin, tokens: Ls[Stroken -> Loc], newDefs: Bo } val ctor = ctors.headOption val res = - NuTypeDef(kind, tn, tparams, params, ctor, sig, ps2, N, N, tu)(isDecl, isAbs) + NuTypeDef(kind, tn, tparams, params, ctor, sig, ps2, N, N, tu)(isDecl, isExported, isAbs) R(res.withLoc(S(l0 ++ tn.getLoc ++ res.getLoc))) - R(res.withLoc(S(l0 ++ res.getLoc))) case ModifierSet(mods, (KEYWORD(kwStr @ ("fun" | "val" | "let")), l0) :: c) => // TODO support rec? consume val (isDecl, mods2) = mods.handle("declare") - val (isVirtual, mods3) = mods2.handle("virtual") - mods3.done + val (isExported, mods3) = mods2.handle("export") + val (isVirtual, mods4) = mods3.handle("virtual") + mods4.done val genField = kwStr =/= "let" val isLetRec = yeetSpaces match { case (KEYWORD("rec"), l1) :: _ if kwStr === "let" => @@ -511,7 +571,7 @@ abstract class NewParser(origin: Origin, tokens: Ls[Stroken -> Loc], newDefs: Bo val annotatedBody = asc.fold(newBody)(ty => Asc(newBody, ty)) R(NuFunDef( isLetRec, v, opStr, tparams, L(ps.foldRight(annotatedBody)((i, acc) => Lam(i, acc))) - )(isDecl, isVirtual, N, N, genField).withLoc(S(l0 ++ annotatedBody.toLoc))) + )(isDecl, isExported, isVirtual, N, N, genField).withLoc(S(l0 ++ annotatedBody.toLoc))) case c => asc match { case S(ty) => @@ -519,7 +579,7 @@ abstract class NewParser(origin: Origin, tokens: Ls[Stroken -> Loc], newDefs: Bo R(NuFunDef(isLetRec, v, opStr, tparams, R(PolyType(Nil, ps.foldRight(ty)((p, r) => Function(p.toType match { case L(diag) => raise(diag); Top // TODO better case R(tp) => tp - }, r)))))(isDecl, isVirtual, N, N, genField).withLoc(S(l0 ++ ty.toLoc))) + }, r)))))(isDecl, isExported, isVirtual, N, N, genField).withLoc(S(l0 ++ ty.toLoc))) // TODO rm PolyType after FCP is merged case N => // TODO dedup: @@ -530,7 +590,7 @@ abstract class NewParser(origin: Origin, tokens: Ls[Stroken -> Loc], newDefs: Bo val bod = errExpr R(NuFunDef( isLetRec, v, opStr, Nil, L(ps.foldRight(bod: Term)((i, acc) => Lam(i, acc))) - )(isDecl, isVirtual, N, N, genField).withLoc(S(l0 ++ bod.toLoc))) + )(isDecl, isExported, isVirtual, N, N, genField).withLoc(S(l0 ++ bod.toLoc))) } } } @@ -547,9 +607,9 @@ abstract class NewParser(origin: Origin, tokens: Ls[Stroken -> Loc], newDefs: Bo case _ => t } yeetSpaces match { - case (KEYWORD(";;"), _) :: _ => consume; finalTerm :: block - case (NEWLINE, _) :: _ => consume; finalTerm :: block - case _ => finalTerm :: Nil + case (KEYWORD(";;"), _) :: _ => consume; block(finalTerm :: prev) + case (NEWLINE, _) :: _ => consume; block(finalTerm :: prev) + case _ => (finalTerm :: prev).reverse } } @@ -603,7 +663,7 @@ abstract class NewParser(origin: Origin, tokens: Ls[Stroken -> Loc], newDefs: Bo case _ => true }) => consume - val ts = rec(toks, S(br.innerLoc), br.describe).concludeWith(_.block) + val ts = rec(toks, S(br.innerLoc), br.describe).concludeWith(_.block(Nil)) val es = ts.map { case L(t) => return L(IfBlock(ts)); case R(e) => e } R(Blk(es)) case (LITVAL(lit), l0) :: _ => @@ -614,10 +674,17 @@ abstract class NewParser(origin: Origin, tokens: Ls[Stroken -> Loc], newDefs: Bo exprCont(UnitLit(kwStr === "undefined").withLoc(S(l0)), prec, allowNewlines = false) case (IDENT(nme, false), l0) :: _ => consume - exprCont(Var(nme).withLoc(S(l0)), prec, allowNewlines = false) + if (nme.isEmpty()) { + err(msg"empty identifier escaped." -> S(l0) :: Nil) + R(errExpr) + } + else exprCont(Var(nme).withLoc(S(l0)), prec, allowNewlines = false) case (KEYWORD("super"), l0) :: _ => consume exprCont(Super().withLoc(S(l0)), prec, allowNewlines = false) + case (KEYWORD("unsupported"), l0) :: _ => + consume + exprCont(Var("unsupported").withLoc(S(l0)), prec, allowNewlines = false) case (IDENT("~", _), l0) :: _ => consume val rest = expr(prec, allowSpace = true) diff --git a/shared/src/main/scala/mlscript/NuTypeDefs.scala b/shared/src/main/scala/mlscript/NuTypeDefs.scala index 8d97dc000..008b57319 100644 --- a/shared/src/main/scala/mlscript/NuTypeDefs.scala +++ b/shared/src/main/scala/mlscript/NuTypeDefs.scala @@ -28,6 +28,7 @@ class NuTypeDefs extends ConstraintSolver { self: Typer => def toLoc: Opt[Loc] def level: Level def isImplemented: Bool + def isDecl: Bool def isPublic: Bool def isPrivate: Bool = !isPublic // * We currently don't support `protected` @@ -64,6 +65,8 @@ class NuTypeDefs extends ConstraintSolver { self: Typer => def kind: DeclKind = if (isType) Als // FIXME? else Val + + def isDecl: Bool = false def toLoc: Opt[Loc] = nme.toLoc def isImplemented: Bool = true def isVirtual: Bool = false // TODO allow annotating parameters with `virtual` @@ -120,6 +123,7 @@ class NuTypeDefs extends ConstraintSolver { self: Typer => { def decl: NuTypeDef = td def kind: DeclKind = td.kind + def isDecl: Bool = td.isDecl def name: Str = nme.name def nme: mlscript.TypeName = td.nme def members: Map[Str, NuMember] = Map.empty @@ -167,6 +171,7 @@ class NuTypeDefs extends ConstraintSolver { self: Typer => { def decl: NuTypeDef = td def kind: DeclKind = td.kind + def isDecl: Bool = td.isDecl def nme: TypeName = td.nme def name: Str = nme.name def isImplemented: Bool = true @@ -227,6 +232,7 @@ class NuTypeDefs extends ConstraintSolver { self: Typer => { def decl: NuTypeDef = td def kind: DeclKind = td.kind + def isDecl: Bool = td.isDecl def nme: TypeName = td.nme def name: Str = nme.name def isImplemented: Bool = true @@ -349,6 +355,7 @@ class NuTypeDefs extends ConstraintSolver { self: Typer => { def decl: NuTypeDef = td def kind: DeclKind = td.kind + def isDecl: Bool = td.isDecl def nme: TypeName = td.nme def name: Str = nme.name def isImplemented: Bool = true @@ -392,6 +399,7 @@ class NuTypeDefs extends ConstraintSolver { self: Typer => case class TypedNuDummy(d: NuDecl) extends TypedNuDecl with TypedNuTermDef { def level = MinLevel def kind: DeclKind = Val + def isDecl: Bool = d.isDecl def toLoc: Opt[Loc] = N def name: Str = d.name def isImplemented: Bool = true @@ -420,6 +428,7 @@ class NuTypeDefs extends ConstraintSolver { self: Typer => case class TypedNuFun(level: Level, fd: NuFunDef, bodyType: ST)(val isImplemented: Bool) extends TypedNuDecl with TypedNuTermDef { def kind: DeclKind = Val + def isDecl: Bool = fd.isDecl def name: Str = fd.nme.name def symbolicName: Opt[Str] = fd.symbolicNme.map(_.name) def toLoc: Opt[Loc] = fd.toLoc @@ -530,7 +539,7 @@ class NuTypeDefs extends ConstraintSolver { self: Typer => /** Type checks a typing unit, which is a sequence of possibly-mutually-recursive type and function definitions * interleaved with plain statements. */ - def typeTypingUnit(tu: TypingUnit, outer: Opt[Outer]) + def typeTypingUnit(tu: TypingUnit, outer: Opt[Outer], isPredef: Bool = false) (implicit ctx: Ctx, raise: Raise, vars: Map[Str, SimpleType]): TypedTypingUnit = trace(s"${ctx.lvl}. Typing $tu") { @@ -584,12 +593,12 @@ class NuTypeDefs extends ConstraintSolver { self: Typer => assert(fd.signature.isEmpty) funSigs.get(fd.nme.name) match { case S(sig) => - fd.copy()(fd.declareLoc, fd.virtualLoc, S(sig), outer, fd.genField) + fd.copy()(fd.declareLoc, fd.exportLoc, fd.virtualLoc, S(sig), outer, fd.genField) case _ => - fd.copy()(fd.declareLoc, fd.virtualLoc, fd.signature, outer, fd.genField) + fd.copy()(fd.declareLoc, fd.exportLoc, fd.virtualLoc, fd.signature, outer, fd.genField) } case td: NuTypeDef => - if (td.nme.name in reservedTypeNames) + if ((td.nme.name in reservedTypeNames) && !isPredef) err(msg"Type name '${td.nme.name}' is reserved", td.toLoc) td } @@ -1305,7 +1314,7 @@ class NuTypeDefs extends ConstraintSolver { self: Typer => val fd = NuFunDef((a.fd.isLetRec, b.fd.isLetRec) match { case (S(a), S(b)) => S(a || b) case _ => N // if one is fun, then it will be fun - }, a.fd.nme, N/*no sym name?*/, a.fd.tparams, a.fd.rhs)(a.fd.declareLoc, a.fd.virtualLoc, N, a.fd.outer orElse b.fd.outer, a.fd.genField) + }, a.fd.nme, N/*no sym name?*/, a.fd.tparams, a.fd.rhs)(a.fd.declareLoc, a.fd.exportLoc, a.fd.virtualLoc, N, a.fd.outer orElse b.fd.outer, a.fd.genField) S(TypedNuFun(a.level, fd, a.bodyType & b.bodyType)(a.isImplemented || b.isImplemented)) case (a: NuParam, S(b: NuParam)) => if (!a.isPublic) S(b) else if (!b.isPublic) S(a) @@ -1642,7 +1651,7 @@ class NuTypeDefs extends ConstraintSolver { self: Typer => implemCheck(impltdMems, (clsSigns.iterator ++ ifaceMembers.iterator) - .distinctBy(_.name).filterNot(_.isImplemented).toList) + .distinctBy(_.name).filterNot(m => m.isImplemented || m.isDecl).toList) val allMembers = (ifaceMembers ++ impltdMems).map(d => d.name -> d).toMap ++ typedSignatureMembers diff --git a/shared/src/main/scala/mlscript/TypeSimplifier.scala b/shared/src/main/scala/mlscript/TypeSimplifier.scala index f2a4b297b..015efaee7 100644 --- a/shared/src/main/scala/mlscript/TypeSimplifier.scala +++ b/shared/src/main/scala/mlscript/TypeSimplifier.scala @@ -952,7 +952,7 @@ trait TypeSimplifier { self: Typer => case ot @ Overload(as) => ot.mapAltsPol(pol)((p, t) => transform(t, p, parents, canDistribForall)) case SkolemTag(id) => transform(id, pol, parents) - case _: ObjectTag | _: Extruded | _: ExtrType => st + case _: ObjectTag | _: Extruded | _: ExtrType | _: UnusableLike => st case tv: TypeVariable if parents(tv) => pol(tv) match { case S(true) => BotType diff --git a/shared/src/main/scala/mlscript/Typer.scala b/shared/src/main/scala/mlscript/Typer.scala index 3a3e5d15d..1924190bd 100644 --- a/shared/src/main/scala/mlscript/Typer.scala +++ b/shared/src/main/scala/mlscript/Typer.scala @@ -229,16 +229,16 @@ class Typer(var dbg: Boolean, var verbose: Bool, var explainErrors: Bool, val ne private val preludeLoc = Loc(0, 0, Origin("", 0, new FastParseHelpers(""))) val nuBuiltinTypes: Ls[NuTypeDef] = Ls( - NuTypeDef(Cls, TN("Object"), Nil, N, N, N, Nil, N, N, TypingUnit(Nil))(N, S(preludeLoc)), - NuTypeDef(Trt, TN("Eql"), (S(VarianceInfo.contra), TN("A")) :: Nil, N, N, N, Nil, N, N, TypingUnit(Nil))(N, S(preludeLoc)), - NuTypeDef(Cls, TN("Num"), Nil, N, N, N, Nil, N, N, TypingUnit(Nil))(N, S(preludeLoc)), - NuTypeDef(Cls, TN("Int"), Nil, N, N, N, Var("Num") :: Nil, N, N, TypingUnit(Nil))(N, S(preludeLoc)), - NuTypeDef(Cls, TN("Bool"), Nil, N, N, S(Union(TN("true"), TN("false"))), Nil, N, N, TypingUnit(Nil))(N, S(preludeLoc)), - NuTypeDef(Mod, TN("true"), Nil, N, N, N, Var("Bool") :: Nil, N, N, TypingUnit(Nil))(N, N), - NuTypeDef(Mod, TN("false"), Nil, N, N, N, Var("Bool") :: Nil, N, N, TypingUnit(Nil))(N, N), - NuTypeDef(Cls, TN("Str"), Nil, N, N, N, Nil, N, N, TypingUnit(Nil))(N, S(preludeLoc)), - NuTypeDef(Als, TN("undefined"), Nil, N, N, S(Literal(UnitLit(true))), Nil, N, N, TypingUnit(Nil))(N, S(preludeLoc)), - NuTypeDef(Als, TN("null"), Nil, N, N, S(Literal(UnitLit(false))), Nil, N, N, TypingUnit(Nil))(N, S(preludeLoc)), + NuTypeDef(Cls, TN("Object"), Nil, N, N, N, Nil, N, N, TypingUnit(Nil))(N, N, S(preludeLoc)), + NuTypeDef(Trt, TN("Eql"), (S(VarianceInfo.contra), TN("A")) :: Nil, N, N, N, Nil, N, N, TypingUnit(Nil))(N, N, S(preludeLoc)), + NuTypeDef(Cls, TN("Num"), Nil, N, N, N, Nil, N, N, TypingUnit(Nil))(N, N, S(preludeLoc)), + NuTypeDef(Cls, TN("Int"), Nil, N, N, N, Var("Num") :: Nil, N, N, TypingUnit(Nil))(N, N, S(preludeLoc)), + NuTypeDef(Cls, TN("Bool"), Nil, N, N, S(Union(TN("true"), TN("false"))), Nil, N, N, TypingUnit(Nil))(N, N, S(preludeLoc)), + NuTypeDef(Mod, TN("true"), Nil, N, N, N, Var("Bool") :: Nil, N, N, TypingUnit(Nil))(N, N, N), + NuTypeDef(Mod, TN("false"), Nil, N, N, N, Var("Bool") :: Nil, N, N, TypingUnit(Nil))(N, N, N), + NuTypeDef(Cls, TN("Str"), Nil, N, N, N, Nil, N, N, TypingUnit(Nil))(N, N, S(preludeLoc)), + NuTypeDef(Als, TN("undefined"), Nil, N, N, S(Literal(UnitLit(true))), Nil, N, N, TypingUnit(Nil))(N, N, S(preludeLoc)), + NuTypeDef(Als, TN("null"), Nil, N, N, S(Literal(UnitLit(false))), Nil, N, N, TypingUnit(Nil))(N, N, S(preludeLoc)), ) val builtinTypes: Ls[TypeDef] = TypeDef(Cls, TN("?"), Nil, TopType, Nil, Nil, Set.empty, N, Nil) :: // * Dummy for pretty-printing unknown type locations @@ -538,6 +538,11 @@ class Typer(var dbg: Boolean, var verbose: Bool, var explainErrors: Bool, val ne (outerCtxLvl)) // * Type variables not explicily bound are assigned the widest (the outer context's) level ).withProv(tyTp(ty.toLoc, "type variable")) } + case app @ AppliedType(base, targs) if (base.name === "unsupported") => targs match { + case Literal(StrLit(tp)) :: Literal(StrLit(file)) :: Literal(IntLit(line)) :: Literal(IntLit(col)) :: Nil => + Unsupported(tp, file, line, col)(noProv) + case _ => err(msg"unsupported type information missing", app.toLoc)(raise) + } case AppliedType(base, targs) => val prov = tyTp(ty.toLoc, "applied type reference") typeNamed(ty.toLoc, base.name) match { @@ -1701,7 +1706,7 @@ class Typer(var dbg: Boolean, var verbose: Bool, var explainErrors: Bool, val ne case TypedNuAls(level, td, tparams, body) => ectx(tparams) |> { implicit ectx => NuTypeDef(td.kind, td.nme, td.tparams, N, N, S(go(body)), Nil, N, N, TypingUnit(Nil))( - td.declareLoc, td.abstractLoc) + td.declareLoc, td.exportLoc, td.abstractLoc) } case TypedNuMxn(level, td, thisTy, superTy, tparams, params, members) => ectx(tparams) |> { implicit ectx => @@ -1713,7 +1718,7 @@ class Typer(var dbg: Boolean, var verbose: Bool, var explainErrors: Bool, val ne Option.when(!(TopType <:< superTy))(go(superTy)), Option.when(!(TopType <:< thisTy))(go(thisTy)), mkTypingUnit(thisTy, members) - )(td.declareLoc, td.abstractLoc) + )(td.declareLoc, td.exportLoc, td.abstractLoc) } case TypedNuCls(level, td, tparams, params, acParams, members, thisTy, sign, ihtags, ptps) => ectx(tparams) |> { implicit ectx => @@ -1733,7 +1738,7 @@ class Typer(var dbg: Boolean, var verbose: Bool, var explainErrors: Bool, val ne case N => tun } } - )(td.declareLoc, td.abstractLoc) + )(td.declareLoc, td.exportLoc, td.abstractLoc) } case TypedNuTrt(level, td, tparams, members, thisTy, sign, ihtags, ptps) => ectx(tparams) |> { implicit ectx => @@ -1745,10 +1750,10 @@ class Typer(var dbg: Boolean, var verbose: Bool, var explainErrors: Bool, val ne N,//TODO Option.when(!(TopType <:< thisTy))(go(thisTy)), mkTypingUnit(thisTy, members) - )(td.declareLoc, td.abstractLoc) + )(td.declareLoc, td.exportLoc, td.abstractLoc) } case tf @ TypedNuFun(level, fd, bodyTy) => - NuFunDef(fd.isLetRec, fd.nme, fd.symbolicNme, Nil, R(go(tf.typeSignature)))(fd.declareLoc, fd.virtualLoc, fd.signature, fd.outer, fd.genField) + NuFunDef(fd.isLetRec, fd.nme, fd.symbolicNme, Nil, R(go(tf.typeSignature)))(fd.declareLoc, fd.exportLoc, fd.virtualLoc, fd.signature, fd.outer, fd.genField) case p: NuParam => ??? // TODO case TypedNuDummy(d) => @@ -1822,6 +1827,7 @@ class Typer(var dbg: Boolean, var verbose: Bool, var explainErrors: Bool, val ne } case ex @ Extruded(p, SkolemTag(tv)) => if (p) tv.asPosExtrudedTypeVar else tv.asNegExtrudedTypeVar + case _: Unsupported => Bot case TypeRef(td, Nil) => td case tr @ TypeRef(td, targs) => AppliedType(td, tr.mapTargs(S(true)) { case ta @ ((S(true), TopType) | (S(false), BotType)) => Bounds(Bot, Top) diff --git a/shared/src/main/scala/mlscript/TyperDatatypes.scala b/shared/src/main/scala/mlscript/TyperDatatypes.scala index 5fc80392a..3e2535eec 100644 --- a/shared/src/main/scala/mlscript/TyperDatatypes.scala +++ b/shared/src/main/scala/mlscript/TyperDatatypes.scala @@ -307,16 +307,26 @@ abstract class TyperDatatypes extends TyperHelpers { Typer: Typer => def levelBelow(ub: Level)(implicit cache: MutSet[TV]): Level = MinLevel override def toString = if (pol) "⊥" else "⊤" } + + sealed abstract class UnusableLike extends AbstractTag /** Represents a type variable skolem that was extruded outsdie its polym level. * The goal is to retain precise information to produce good errors, * but still have this be functionally equivalent to `ExtrType(pol)`. */ - case class Extruded(pol: Bool, underlying: SkolemTag)(val prov: TypeProvenance, val reason: Ls[Ls[ST]]) extends AbstractTag with TypeVarOrRigidVar { + case class Extruded(pol: Bool, underlying: SkolemTag)(val prov: TypeProvenance, val reason: Ls[Ls[ST]]) extends UnusableLike with TypeVarOrRigidVar { val level: Level = MinLevel val id = underlying.id def levelBelow(ub: Level)(implicit cache: MutSet[TV]): Level = 0 override def toString = if (pol) s"⊥(${underlying})" else s"⊤(${underlying})" } + + case class Unsupported(tp: Str, file: Str, line: BigInt, col: BigInt)(val prov: TypeProvenance) extends UnusableLike { + val id = StrLit(showTSType) + val level: Level = MinLevel + def levelBelow(ub: Level)(implicit cache: MutSet[TV]): Level = 0 + override def toString = s"Unsupported($showTSType)" + def showTSType: Str = s"\"$tp\" at $file, $line, $col" + } /** Polarity `pol` being `true` means union; `false` means intersection. */ case class ComposedType(pol: Bool, lhs: SimpleType, rhs: SimpleType)(val prov: TypeProvenance) extends SimpleType { @@ -393,10 +403,13 @@ abstract class TyperDatatypes extends TyperHelpers { Typer: Typer => case (obj1: ObjectTag, obj2: ObjectTag) => obj1.id compare obj2.id case (SkolemTag(id1), SkolemTag(id2)) => id1 compare id2 case (Extruded(_, id1), Extruded(_, id2)) => id1 compare id2 + case (uns1: Unsupported, uns2: Unsupported) => 0 case (_: ObjectTag, _: SkolemTag | _: Extruded) => -1 case (_: SkolemTag | _: Extruded, _: ObjectTag) => 1 case (_: SkolemTag, _: Extruded) => -1 case (_: Extruded, _: SkolemTag) => 1 + case (_, _: UnusableLike) => -1 + case (_: UnusableLike, _) => 1 } } diff --git a/shared/src/main/scala/mlscript/TyperHelpers.scala b/shared/src/main/scala/mlscript/TyperHelpers.scala index 727b0001c..08cb30680 100644 --- a/shared/src/main/scala/mlscript/TyperHelpers.scala +++ b/shared/src/main/scala/mlscript/TyperHelpers.scala @@ -713,7 +713,7 @@ abstract class TyperHelpers { Typer: Typer => case ExtrType(_) => Nil case ProxyType(und) => pol -> und :: Nil // case _: TypeTag => Nil - case _: ObjectTag | _: Extruded => Nil + case _: ObjectTag | _: Extruded | _: UnusableLike => Nil case SkolemTag(id) => pol -> id :: Nil case tr: TypeRef => tr.mapTargs(pol)(_ -> _) case Without(b, ns) => pol -> b :: Nil @@ -799,7 +799,7 @@ abstract class TyperHelpers { Typer: Typer => case ExtrType(_) => Nil case ProxyType(und) => pol -> und :: Nil // case _: TypeTag => Nil - case _: ObjectTag | _: Extruded => Nil + case _: ObjectTag | _: Extruded | _: UnusableLike => Nil case SkolemTag(id) => pol -> id :: Nil case tr: TypeRef => tr.mapTargs(pol)(_ -> _) case Without(b, ns) => pol -> b :: Nil @@ -955,7 +955,7 @@ abstract class TyperHelpers { Typer: Typer => case ExtrType(_) => Nil case ProxyType(und) => und :: Nil // case _: TypeTag => Nil - case _: ObjectTag | _: Extruded => Nil + case _: ObjectTag | _: Extruded | _: UnusableLike => Nil case SkolemTag(id) => id :: Nil case TypeRef(d, ts) => ts case Without(b, ns) => b :: Nil @@ -1336,7 +1336,7 @@ abstract class TyperHelpers { Typer: Typer => case ExtrType(_) => () case ProxyType(und) => apply(pol)(und) // case _: TypeTag => () - case _: ObjectTag | _: Extruded => () + case _: ObjectTag | _: Extruded | _: UnusableLike => () case SkolemTag(id) => apply(pol)(id) case tr: TypeRef => tr.mapTargs(pol)(apply(_)(_)); () case Without(b, ns) => apply(pol)(b) diff --git a/shared/src/main/scala/mlscript/codegen/Codegen.scala b/shared/src/main/scala/mlscript/codegen/Codegen.scala index 9a785cfc1..081cde914 100644 --- a/shared/src/main/scala/mlscript/codegen/Codegen.scala +++ b/shared/src/main/scala/mlscript/codegen/Codegen.scala @@ -598,7 +598,7 @@ object JSMember { def apply(`object`: JSExpr, property: JSExpr): JSMember = new JSMember(`object`, property) } -class JSField(`object`: JSExpr, val property: JSIdent) extends JSMember(`object`, property) { +class JSField(val `object`: JSExpr, val property: JSIdent) extends JSMember(`object`, property) { override def toSourceCode: SourceCode = `object`.toSourceCode.parenthesized( `object`.precedence < precedence || `object`.isInstanceOf[JSRecord] @@ -922,6 +922,24 @@ final case class JSClassNewDecl( private val fieldsSet = collection.immutable.HashSet.from(fields) } +final case class JSExport(module: JSConstDecl \/ JSIdent) extends JSStmt { + def toSourceCode: SourceCode = module match { + case L(dec) => SourceCode(s"export ${dec.toSourceCode}") + case R(name) => SourceCode(s"module.exports = ${name.toSourceCode};") + } +} + +// None: mls module, Some(true): ES module, Some(false): common JS module +final case class JSImport(name: Str, path: Str, isESModule: Opt[Bool], genRequire: Bool) extends JSStmt { + def toSourceCode: SourceCode = + if (genRequire) SourceCode(s"const $name = require(\"$path\")\n") + else isESModule match { + case N => SourceCode(s"import { $name } from \"$path\"\n") + case S(true) => SourceCode(s"import * as $name from \"$path\"\n") + case S(false) => SourceCode(s"import $name from \"$path\"\n") + } +} + final case class JSComment(text: Str) extends JSStmt { def toSourceCode: SourceCode = SourceCode(s"// $text") } diff --git a/shared/src/main/scala/mlscript/helpers.scala b/shared/src/main/scala/mlscript/helpers.scala index b6154bd40..604004679 100644 --- a/shared/src/main/scala/mlscript/helpers.scala +++ b/shared/src/main/scala/mlscript/helpers.scala @@ -423,10 +423,13 @@ trait NuDeclImpl extends Located { self: NuDecl => val body: Located def kind: DeclKind val declareLoc: Opt[Loc] + val exportLoc: Opt[Loc] val abstractLoc: Opt[Loc] def isDecl: Bool = declareLoc.nonEmpty def isAbstract: Bool = abstractLoc.nonEmpty def declStr: Str = if (isDecl) "declare " else "" + def isExported: Bool = exportLoc.isDefined + def exportStr: Str = if (isExported) "export " else "" val nameVar: Var = self match { case td: NuTypeDef => td.nme.toVar case fd: NuFunDef => fd.nme @@ -459,7 +462,7 @@ trait NuDeclImpl extends Located { self: NuDecl => })) NuFunDef(N, Var("unapply"), N, Nil, L(Lam( Tup(N -> Fld(FldFlags.empty, Var("x")) :: Nil), - ret)))(N, N, N, N, true) + ret)))(N, N, N, N, N, true) } case _ => N } @@ -828,9 +831,12 @@ trait StatementImpl extends Located { self: Statement => lazy val desugared = doDesugar private def doDesugar: Ls[Diagnostic] -> Ls[DesugaredStatement] = this match { - // case ctor: Constructor => - // import Message._ - // (ErrorReport(msg"constructor must be in a class." -> ctor.toLoc :: Nil, newDefs=true) :: Nil) -> Nil + case ctor: Constructor => + import Message._ + (ErrorReport(msg"constructor must be in a class." -> ctor.toLoc :: Nil, newDefs=true) :: Nil) -> Nil + case imp: Import => + import Message._ + (ErrorReport(msg"unexpected import statement." -> imp.toLoc :: Nil, newDefs=true) :: Nil) -> Nil case l @ LetS(isrec, pat, rhs) => val (diags, v, args) = desugDefnPattern(pat, Nil) diags -> (Def(isrec, v, L(args.foldRight(rhs)(Lam(_, _))), false).withLocOf(l) :: Nil) // TODO use v, not v.name @@ -998,6 +1004,7 @@ trait StatementImpl extends Located { self: Statement => case Forall(ps, bod) => ps ::: bod :: Nil case Inst(bod) => bod :: Nil case Super() => Nil + case _: Import => Nil case Constructor(params, body) => params :: body :: Nil case Eqn(lhs, rhs) => lhs :: rhs :: Nil case NuTypeDef(k, nme, tps, ps, ctor, sig, pars, sup, ths, bod) => @@ -1019,6 +1026,7 @@ trait StatementImpl extends Located { self: Statement => case n: NuFunDef => if (n.rhs.isLeft) " = " else ": " case _: NuTypeDef => " " }) + n.showBody + case imp: Import => s"${if (imp.weak) "weak " else ""}import ${imp.path}" } } diff --git a/shared/src/main/scala/mlscript/syntax.scala b/shared/src/main/scala/mlscript/syntax.scala index d3d3b05c4..ed145c11f 100644 --- a/shared/src/main/scala/mlscript/syntax.scala +++ b/shared/src/main/scala/mlscript/syntax.scala @@ -128,6 +128,12 @@ final case class LetS(isRec: Bool, pat: Term, rhs: Term) extends Statement final case class DataDefn(body: Term) extends Statement final case class DatatypeDefn(head: Term, body: Term) extends Statement +class Import(val path: Str, val weak: Bool) extends Statement + +object Import { + def apply(path: Str, weak: Bool): Import = new Import(path, weak) +} + sealed trait DesugaredStatement extends Statement with DesugaredStatementImpl sealed trait Terms extends DesugaredStatement @@ -205,7 +211,7 @@ final case class NuTypeDef( superAnnot: Opt[Type], thisAnnot: Opt[Type], body: TypingUnit -)(val declareLoc: Opt[Loc], val abstractLoc: Opt[Loc]) +)(val declareLoc: Opt[Loc], val exportLoc: Opt[Loc], val abstractLoc: Opt[Loc]) extends NuDecl with Statement with Outer { def isPlainJSClass: Bool = params.isEmpty } @@ -218,6 +224,7 @@ final case class NuFunDef( rhs: Term \/ Type, )( val declareLoc: Opt[Loc], + val exportLoc: Opt[Loc], val virtualLoc: Opt[Loc], // Some(Loc) means that the function is modified by keyword `virtual` val signature: Opt[NuFunDef], val outer: Opt[Outer], diff --git a/shared/src/main/scala/mlscript/utils/GitHelper.scala b/shared/src/main/scala/mlscript/utils/GitHelper.scala new file mode 100644 index 000000000..d3eb8ab95 --- /dev/null +++ b/shared/src/main/scala/mlscript/utils/GitHelper.scala @@ -0,0 +1,27 @@ +package mlscript.utils + +import shorthands._ +import os.FilePath +import os.Path +import scala.collection.Iterator + +abstract class GitHelper[PathType, RelPathType](rootDir: PathType, workDir: PathType) { + protected def diff: Iterator[Str] + protected def str2RelPath(s: Str): RelPathType + def filter(file: PathType): Bool + + // Aggregate unstaged modified files to only run the tests on them, if there are any + final protected lazy val modified: Set[RelPathType] = try diff.flatMap { gitStr => + println(" [git] " + gitStr) + val prefix = gitStr.take(2) + val filePath = str2RelPath(gitStr.drop(3)) + if (prefix =:= "A " || prefix =:= "M " || prefix =:= "R " || prefix =:= "D ") + N // * Disregard modified files that are staged + else S(filePath) + }.toSet catch { + case err: Throwable => System.err.println("/!\\ git command failed with: " + err) + Set.empty + } + + final def getFiles(allFiles: IndexedSeq[PathType]): IndexedSeq[PathType] = allFiles.filter(filter(_)) +} diff --git a/shared/src/test/diff/codegen/ModuleInheritance.mls b/shared/src/test/diff/codegen/ModuleInheritance.mls new file mode 100644 index 000000000..c263a1065 --- /dev/null +++ b/shared/src/test/diff/codegen/ModuleInheritance.mls @@ -0,0 +1,284 @@ +:NewParser +:NewDefs + +module A { + class B(x: Int) { + fun add(y: Int) = x + y + } + class C {} +} +//│ module A { +//│ class B(x: Int) { +//│ fun add: (y: Int) -> Int +//│ } +//│ class C { +//│ constructor() +//│ } +//│ } + +:e +:js +class C() extends A.B(1) +class CC() extends A.C +//│ ╔══[ERROR] Unsupported parent specification +//│ ║ l.21: class C() extends A.B(1) +//│ ╙── ^^^^^^ +//│ ╔══[ERROR] Unsupported parent specification +//│ ║ l.22: class CC() extends A.C +//│ ╙── ^^^ +//│ class C() +//│ class CC() +//│ // Prelude +//│ class TypingUnit1 { +//│ #C; +//│ #CC; +//│ constructor() { +//│ } +//│ get C() { +//│ const qualifier = this; +//│ if (this.#C === undefined) { +//│ class C extends A.B.class { +//│ constructor() { +//│ super(1); +//│ } +//│ static +//│ unapply(x) { +//│ return []; +//│ } +//│ }; +//│ this.#C = (() => Object.freeze(new C())); +//│ this.#C.class = C; +//│ this.#C.unapply = C.unapply; +//│ } +//│ return this.#C; +//│ } +//│ get CC() { +//│ const qualifier = this; +//│ if (this.#CC === undefined) { +//│ class CC extends A.C { +//│ constructor() { +//│ super(); +//│ } +//│ static +//│ unapply(x) { +//│ return []; +//│ } +//│ }; +//│ this.#CC = (() => Object.freeze(new CC())); +//│ this.#CC.class = CC; +//│ this.#CC.unapply = CC.unapply; +//│ } +//│ return this.#CC; +//│ } +//│ } +//│ const typing_unit1 = new TypingUnit1; +//│ globalThis.C = typing_unit1.C; +//│ globalThis.CC = typing_unit1.CC; +//│ // End of generated code + +:e +C().add(3) +//│ ╔══[ERROR] Type `C` does not contain member `add` +//│ ║ l.80: C().add(3) +//│ ╙── ^^^^ +//│ error +//│ res +//│ = 4 + +:e +:js +module B { + class C() + class D() extends B.C { + val x = 42 + } +} +//│ ╔══[ERROR] Unsupported parent specification +//│ ║ l.92: class D() extends B.C { +//│ ╙── ^^^ +//│ module B { +//│ class C() +//│ class D() { +//│ val x: 42 +//│ } +//│ } +//│ // Prelude +//│ class TypingUnit3 { +//│ #B; +//│ constructor() { +//│ } +//│ get B() { +//│ const qualifier = this; +//│ if (this.#B === undefined) { +//│ class B { +//│ #C; +//│ #D; +//│ constructor() { +//│ } +//│ get C() { +//│ const qualifier1 = this; +//│ if (this.#C === undefined) { +//│ class C { +//│ constructor() { +//│ } +//│ static +//│ unapply(x) { +//│ return []; +//│ } +//│ }; +//│ this.#C = (() => Object.freeze(new C())); +//│ this.#C.class = C; +//│ this.#C.unapply = C.unapply; +//│ } +//│ return this.#C; +//│ } +//│ get D() { +//│ const qualifier1 = this; +//│ if (this.#D === undefined) { +//│ class D extends qualifier.B.C.class { +//│ #x; +//│ get x() { return this.#x; } +//│ constructor() { +//│ super(); +//│ this.#x = 42; +//│ const x = this.#x; +//│ } +//│ static +//│ unapply(x) { +//│ return []; +//│ } +//│ }; +//│ this.#D = (() => Object.freeze(new D())); +//│ this.#D.class = D; +//│ this.#D.unapply = D.unapply; +//│ } +//│ return this.#D; +//│ } +//│ } +//│ this.#B = new B(); +//│ this.#B.class = B; +//│ } +//│ return this.#B; +//│ } +//│ } +//│ const typing_unit3 = new TypingUnit3; +//│ globalThis.B = typing_unit3.B; +//│ // End of generated code + +:e +let dd = B.D() +dd.x +//│ ╔══[ERROR] Access to class member not yet supported +//│ ║ l.169: let dd = B.D() +//│ ╙── ^^ +//│ let dd: error +//│ error +//│ dd +//│ = D {} +//│ res +//│ = 42 + +:e +:js +module C { + module D { + class E() + } + class F(val x: Int) extends D.E +} +//│ ╔══[ERROR] Unsupported parent specification +//│ ║ l.187: class F(val x: Int) extends D.E +//│ ╙── ^^^ +//│ module C { +//│ module D { +//│ class E() +//│ } +//│ class F(x: Int) +//│ } +//│ // Prelude +//│ class TypingUnit5 { +//│ #C; +//│ constructor() { +//│ } +//│ get C() { +//│ const qualifier = this; +//│ if (this.#C === undefined) { +//│ class C { +//│ #F; +//│ #D; +//│ constructor() { +//│ } +//│ get D() { +//│ const qualifier1 = this; +//│ if (this.#D === undefined) { +//│ class D { +//│ #E; +//│ constructor() { +//│ } +//│ get E() { +//│ const qualifier2 = this; +//│ if (this.#E === undefined) { +//│ class E { +//│ constructor() { +//│ } +//│ static +//│ unapply(x) { +//│ return []; +//│ } +//│ }; +//│ this.#E = (() => Object.freeze(new E())); +//│ this.#E.class = E; +//│ this.#E.unapply = E.unapply; +//│ } +//│ return this.#E; +//│ } +//│ } +//│ this.#D = new D(); +//│ this.#D.class = D; +//│ } +//│ return this.#D; +//│ } +//│ get F() { +//│ const qualifier1 = this; +//│ if (this.#F === undefined) { +//│ class F extends qualifier1.D.E.class { +//│ #x; +//│ get x() { return this.#x; } +//│ constructor(x) { +//│ super(); +//│ this.#x = x; +//│ } +//│ static +//│ unapply(x) { +//│ return [x.#x]; +//│ } +//│ }; +//│ this.#F = ((x) => Object.freeze(new F(x))); +//│ this.#F.class = F; +//│ this.#F.unapply = F.unapply; +//│ } +//│ return this.#F; +//│ } +//│ } +//│ this.#C = new C(); +//│ this.#C.class = C; +//│ } +//│ return this.#C; +//│ } +//│ } +//│ const typing_unit5 = new TypingUnit5; +//│ globalThis.C = typing_unit5.C; +//│ // End of generated code + +:e +let fff = C.F(24) +fff.x +//│ ╔══[ERROR] Access to class member not yet supported +//│ ║ l.274: let fff = C.F(24) +//│ ╙── ^^ +//│ let fff: error +//│ error +//│ fff +//│ = F {} +//│ res +//│ = 24 diff --git a/shared/src/test/diff/nu/AuxCtors.mls b/shared/src/test/diff/nu/AuxCtors.mls index 3f753f4fa..e0b80a4ef 100644 --- a/shared/src/test/diff/nu/AuxCtors.mls +++ b/shared/src/test/diff/nu/AuxCtors.mls @@ -172,46 +172,29 @@ new C(1, 2) //│ [ 1, 1 ] :pe -:w class C { constructor(x: Int);; constructor(y: Int) } //│ ╔══[PARSE ERROR] A class may have at most one explicit constructor -//│ ║ l.176: class C { constructor(x: Int);; constructor(y: Int) } +//│ ║ l.175: class C { constructor(x: Int);; constructor(y: Int) } //│ ╙── ^^^^^ -//│ ╔══[WARNING] Pure expression does nothing in statement position. -//│ ║ l.176: class C { constructor(x: Int);; constructor(y: Int) } -//│ ╙── ^^ //│ class C { //│ constructor(x: Int) //│ } -:w // * FIXME class Foo { constructor(x: Int){};; val y = 2 } -//│ ╔══[WARNING] Pure expression does nothing in statement position. -//│ ║ l.189: class Foo { constructor(x: Int){};; val y = 2 } -//│ ╙── ^^ //│ class Foo { //│ constructor(x: Int) //│ val y: 2 //│ } :pe -:e class Foo { constructor(x: Int){}; val y = 2 } -//│ ╔══[PARSE ERROR] Unexpected operator in expression position -//│ ║ l.200: class Foo { constructor(x: Int){}; val y = 2 } +//│ ╔══[PARSE ERROR] Unexpected operator here +//│ ║ l.191: class Foo { constructor(x: Int){}; val y = 2 } //│ ╙── ^ -//│ ╔══[PARSE ERROR] Unexpected 'val' keyword in expression position -//│ ║ l.200: class Foo { constructor(x: Int){}; val y = 2 } -//│ ╙── ^^^ -//│ ╔══[ERROR] Unexpected equation in this position -//│ ║ l.200: class Foo { constructor(x: Int){}; val y = 2 } -//│ ╙── ^^^^^ //│ class Foo { //│ constructor(x: Int) //│ } -//│ Syntax error: -//│ Private field '#y' must be declared in an enclosing class class Foo { constructor(x: Int){} diff --git a/shared/src/test/diff/nu/DeclaredMembers.mls b/shared/src/test/diff/nu/DeclaredMembers.mls new file mode 100644 index 000000000..f3d1a6ffd --- /dev/null +++ b/shared/src/test/diff/nu/DeclaredMembers.mls @@ -0,0 +1,18 @@ +:NewDefs + +declare class Parent { + declare fun foo: () -> Str // there's an implementation, trust me! +} +//│ declare class Parent { +//│ constructor() +//│ fun foo: () -> Str +//│ } + + +:re +class Child() extends Parent +//│ class Child() extends Parent { +//│ fun foo: () -> Str +//│ } +//│ Runtime error: +//│ ReferenceError: Parent is not defined diff --git a/shared/src/test/diff/nu/Export.mls b/shared/src/test/diff/nu/Export.mls new file mode 100644 index 000000000..283f5fc48 --- /dev/null +++ b/shared/src/test/diff/nu/Export.mls @@ -0,0 +1,29 @@ +:NewDefs + + +export class A() +//│ class A() + + +module M { + export fun g = A() + fun f = A() +} +//│ module M { +//│ fun f: A +//│ fun g: A +//│ } + +let a = M.g +//│ let a: A +//│ a +//│ = A {} + +// TODO reject +// :e +let a = M.f +//│ let a: A +//│ a +//│ = A {} + + diff --git a/shared/src/test/diff/nu/IdentEscape.mls b/shared/src/test/diff/nu/IdentEscape.mls new file mode 100644 index 000000000..11b167544 --- /dev/null +++ b/shared/src/test/diff/nu/IdentEscape.mls @@ -0,0 +1,85 @@ +:NewDefs + +let id"of" = 42 +fun id"fun"(x: Int) = x + 1 +fun id"declare"(id"if": Int) = id"of" + id"if" +//│ let of: 42 +//│ fun fun: (x: Int) -> Int +//│ fun declare: (if: Int) -> Int +//│ of +//│ = 42 + +id"fun"(id"of") +id"declare"(id"of") +//│ Int +//│ res +//│ = 43 +//│ res +//│ = 84 + +let id"if" = 1 +id"if" + 1 +//│ let if: 1 +//│ Int +//│ if +//│ = 1 +//│ res +//│ = 2 + + +class Foo(id"class": Int) { + fun id"mixin"(x: Int) = id"class" + x +} +let foo = Foo(2) +foo.id"mixin"(3) +//│ class Foo(class: Int) { +//│ fun mixin: (x: Int) -> Int +//│ } +//│ let foo: Foo +//│ Int +//│ foo +//│ = Foo {} +//│ res +//│ = 5 + +:pe +id"" +//│ ╔══[PARSE ERROR] empty identifier escaped. +//│ ║ l.46: id"" +//│ ╙── ^^^^ +//│ () +//│ res +//│ = undefined + +:pe +id"id +//│ ╔══[LEXICAL ERROR] unfinished identifier escape +//│ ║ l.55: id"id +//│ ╙── ^ +//│ ╔══[PARSE ERROR] Unexpected error in expression position +//│ ║ l.55: id"id +//│ ╙── ^^^^^^ +//│ ╔══[PARSE ERROR] Unexpected end of input; an expression was expected here +//│ ║ l.55: id"id +//│ ╙── ^ +//│ () +//│ res +//│ = undefined + +class id"of" +//│ class of { +//│ constructor() +//│ } + +:ge +class id"class" +//│ class class { +//│ constructor() +//│ } +//│ Code generation encountered an error: +//│ class is a reserved keyword in ECMAScript and can not be used as type name. + +let id"$4" = 4 +//│ let $4: 4 +//│ $4 +//│ = 4 diff --git a/shared/src/test/diff/nu/MethodSignatures.mls b/shared/src/test/diff/nu/MethodSignatures.mls index 347391dae..da0f694e7 100644 --- a/shared/src/test/diff/nu/MethodSignatures.mls +++ b/shared/src/test/diff/nu/MethodSignatures.mls @@ -172,6 +172,14 @@ module M { fun a: M.A fun a = 1 } -//│ /!!!\ Uncaught error: scala.NotImplementedError: an implementation is missing +//│ ╔══[ERROR] Module `M` has a cyclic type dependency that is not supported yet. +//│ ║ l.172: fun a: M.A +//│ ╙── ^^ +//│ module M { +//│ class A { +//│ constructor() +//│ } +//│ fun a: error +//│ } diff --git a/shared/src/test/diff/nu/Unsupported.mls b/shared/src/test/diff/nu/Unsupported.mls new file mode 100644 index 000000000..d329f88f8 --- /dev/null +++ b/shared/src/test/diff/nu/Unsupported.mls @@ -0,0 +1,58 @@ +:NewDefs + +declare class Foo() { + val index: unsupported["(id: string): string;", "Invoker.ts", 11, 4] + val x = 42 +} +//│ declare class Foo() { +//│ val index: nothing +//│ val x: 42 +//│ } + +declare fun call: unsupported["(source: string, subString: string): boolean;", "Invoker.ts", 31, 54] +//│ fun call: nothing + +:re +let foo = Foo() +//│ let foo: Foo +//│ foo +//│ Runtime error: +//│ ReferenceError: Foo is not defined + +:re +foo.x // ok! 42 is supported! +//│ 42 +//│ res +//│ Runtime error: +//│ ReferenceError: foo is not defined + +:e +:re +foo.index("abc") +//│ ╔══[ERROR] Type mismatch in application: +//│ ║ l.31: foo.index("abc") +//│ ║ ^^^^^^^^^^^^^^^^ +//│ ╟── signature of member `index` of type `nothing` (TypeScript type "(id: string): string;" at Invoker.ts, 11, 4) is not supported +//│ ║ l.4: val index: unsupported["(id: string): string;", "Invoker.ts", 11, 4] +//│ ║ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +//│ ╟── but it flows into field selection with expected type `"abc" -> ?a` +//│ ║ l.31: foo.index("abc") +//│ ╙── ^^^^^^^^^ +//│ error +//│ res +//│ Runtime error: +//│ ReferenceError: foo is not defined + +:e +:re +call() +//│ ╔══[ERROR] Type mismatch in application: +//│ ║ l.48: call() +//│ ║ ^^^^^^ +//│ ╟── reference of type `nothing` (TypeScript type "(source: string, subString: string): boolean;" at Invoker.ts, 31, 54) is not supported +//│ ║ l.48: call() +//│ ╙── ^^^^ +//│ error +//│ res +//│ Runtime error: +//│ ReferenceError: call is not defined diff --git a/shared/src/test/scala/mlscript/DiffTests.scala b/shared/src/test/scala/mlscript/DiffTests.scala index b5772437f..708726712 100644 --- a/shared/src/test/scala/mlscript/DiffTests.scala +++ b/shared/src/test/scala/mlscript/DiffTests.scala @@ -60,11 +60,7 @@ class DiffTests // scala test will not execute a test if the test class has constructor parameters. // override this to get the correct paths of test files. - protected lazy val files = allFiles.filter { file => - val fileName = file.baseName - // validExt(file.ext) && filter(fileName) - validExt(file.ext) && filter(file.relativeTo(pwd)) - } + protected lazy val files = gitHelper.getFiles(allFiles) val timeLimit = TimeLimit @@ -338,59 +334,16 @@ class DiffTests src match { case Diagnostic.Lexing => totalParseErrors += 1 - s"╔══[LEXICAL ERROR] " case Diagnostic.Parsing => totalParseErrors += 1 - s"╔══[PARSE ERROR] " case _ => // TODO customize too totalTypeErrors += 1 - s"╔══[ERROR] " } case WarningReport(msg, loco, src) => totalWarnings += 1 - s"╔══[WARNING] " - } - val lastMsgNum = diag.allMsgs.size - 1 - var globalLineNum = blockLineNum // solely used for reporting useful test failure messages - diag.allMsgs.zipWithIndex.foreach { case ((msg, loco), msgNum) => - val isLast = msgNum =:= lastMsgNum - val msgStr = msg.showIn(sctx) - if (msgNum =:= 0) output(headStr + msgStr) - else output(s"${if (isLast && loco.isEmpty) "╙──" else "╟──"} ${msgStr}") - if (loco.isEmpty && diag.allMsgs.size =:= 1) output("╙──") - loco.foreach { loc => - val (startLineNum, startLineStr, startLineCol) = - loc.origin.fph.getLineColAt(loc.spanStart) - if (globalLineNum =:= 0) globalLineNum += startLineNum - 1 - val (endLineNum, endLineStr, endLineCol) = - loc.origin.fph.getLineColAt(loc.spanEnd) - var l = startLineNum - var c = startLineCol - while (l <= endLineNum) { - val globalLineNum = loc.origin.startLineNum + l - 1 - val relativeLineNum = globalLineNum - blockLineNum + 1 - val shownLineNum = - if (showRelativeLineNums && relativeLineNum > 0) s"l.+$relativeLineNum" - else "l." + globalLineNum - val prepre = "║ " - val pre = s"$shownLineNum: " - val curLine = loc.origin.fph.lines(l - 1) - output(prepre + pre + "\t" + curLine) - val tickBuilder = new StringBuilder() - tickBuilder ++= ( - (if (isLast && l =:= endLineNum) "╙──" else prepre) - + " " * pre.length + "\t" + " " * (c - 1)) - val lastCol = if (l =:= endLineNum) endLineCol else curLine.length + 1 - while (c < lastCol) { tickBuilder += ('^'); c += 1 } - if (c =:= startLineCol) tickBuilder += ('^') - output(tickBuilder.toString) - c = 1 - l += 1 - } - } } - if (diag.allMsgs.isEmpty) output("╙──") - + val globalLineNum = blockLineNum + Diagnostic.report(diag, output, blockLineNum, showRelativeLineNums, newDefs) if (!mode.fixme) { if (!allowTypeErrors && !mode.expectTypeErrors && diag.isInstanceOf[ErrorReport] && diag.source =:= Diagnostic.Typing) @@ -1098,52 +1051,6 @@ object DiffTests { private val pwd = os.pwd private val dir = pwd/"shared"/"src"/"test"/"diff" - private val allFiles = os.walk(dir).filter(_.toIO.isFile) - - private val validExt = Set("fun", "mls") - - // Aggregate unstaged modified files to only run the tests on them, if there are any - private val modified: Set[os.RelPath] = - try os.proc("git", "status", "--porcelain", dir).call().out.lines().iterator.flatMap { gitStr => - println(" [git] " + gitStr) - val prefix = gitStr.take(2) - val filePath = os.RelPath(gitStr.drop(3)) - if (prefix =:= "A " || prefix =:= "M " || prefix =:= "R " || prefix =:= "D ") - N // * Disregard modified files that are staged - else S(filePath) - }.toSet catch { - case err: Throwable => System.err.println("/!\\ git command failed with: " + err) - Set.empty - } - - // Allow overriding which specific tests to run, sometimes easier for development: - private val focused = Set[Str]( - // "LetRec" - // "Ascribe", - // "Repro", - // "RecursiveTypes", - // "Simple", - // "Inherit", - // "Basics", - // "Paper", - // "Negations", - // "RecFuns", - // "With", - // "Annoying", - // "Tony", - // "Lists", - // "Traits", - // "BadTraits", - // "TraitMatching", - // "Subsume", - // "Methods", - ).map(os.RelPath(_)) - // private def filter(name: Str): Bool = - def filter(file: os.RelPath): Bool = { - if (focused.nonEmpty) focused(file) else modified(file) || modified.isEmpty && - true - // name.startsWith("new/") - // file.segments.toList.init.lastOption.contains("parser") - } + private val gitHelper = JVMGitHelper(pwd, dir) } diff --git a/shared/src/test/scala/mlscript/JVMGitHelper.scala b/shared/src/test/scala/mlscript/JVMGitHelper.scala new file mode 100644 index 000000000..969bf7d5f --- /dev/null +++ b/shared/src/test/scala/mlscript/JVMGitHelper.scala @@ -0,0 +1,50 @@ +package mlscript + +import mlscript.utils.GitHelper +import mlscript.utils._, shorthands._ +import os.FilePath +import os.Path +import scala.collection.Iterator + +class JVMGitHelper(rootDir: os.Path, workDir: os.Path) extends GitHelper[os.Path, os.RelPath](rootDir, workDir) { + override protected def str2RelPath(s: Str): os.RelPath = os.RelPath(s) + override protected def diff: Iterator[Str] = + os.proc("git", "status", "--porcelain", workDir).call().out.lines().iterator + override def filter(file: Path): Bool = { + JVMGitHelper.validExt(file.ext) && filter(file.relativeTo(rootDir)) + } + + // Allow overriding which specific tests to run, sometimes easier for development: + private val focused = Set[Str]( + // "LetRec" + // "Ascribe", + // "Repro", + // "RecursiveTypes", + // "Simple", + // "Inherit", + // "Basics", + // "Paper", + // "Negations", + // "RecFuns", + // "With", + // "Annoying", + // "Tony", + // "Lists", + // "Traits", + // "BadTraits", + // "TraitMatching", + // "Subsume", + // "Methods", + ).map(os.RelPath(_)) + def filter(file: os.RelPath): Bool = { + if (focused.nonEmpty) focused(file) else modified(file) || modified.isEmpty && + true + } +} + +object JVMGitHelper { + def apply(rootDir: os.Path, workDir: os.Path): JVMGitHelper = + new JVMGitHelper(rootDir, workDir) + + private val validExt = Set("fun", "mls") +} diff --git a/ts2mls/js/src/main/scala/ts2mls/FileInfo.scala b/ts2mls/js/src/main/scala/ts2mls/FileInfo.scala new file mode 100644 index 000000000..6a499887d --- /dev/null +++ b/ts2mls/js/src/main/scala/ts2mls/FileInfo.scala @@ -0,0 +1,84 @@ +package ts2mls + +import scala.scalajs.js +import ts2mls.{TypeScript, TSImport} +import ts2mls.TSPathResolver + +final case class FileInfo( + workDir: String, // Work directory (related to compiler path) + localFilename: String, // Filename (related to work dir, or in node_modules) + interfaceDir: String, // `.mlsi` file directory (related to output dir) + parent: Option[String] = None, // File that imports this (related to work dir) + nodeModulesNested: Boolean = false // If it is a local file in node_modules +) { + import TSPathResolver.{normalize, isLocal, dirname, basename, extname} + + val relatedPath: Option[String] = + if (isLocal(localFilename)) Some(normalize(dirname(localFilename))) + else None + + val isNodeModule: Boolean = nodeModulesNested || relatedPath.isEmpty + + // Module name in ts/mls + val moduleName = basename(localFilename) + + // Full filename (related to compiler path, or module name in node_modules) + lazy val filename: String = + if (!isNodeModule) normalize(s"./$workDir/$localFilename") + else if (nodeModulesNested) localFilename + else localFilename.replace(extname(localFilename), "") + + def translateImportToInterface(file: FileInfo)(implicit config: js.Dynamic): String = { + val importedPath = + if (!file.isNodeModule) { + val rel = normalize(TSPathResolver.relative(dirname(localFilename), file.localFilename)) + if (isLocal(rel)) rel else s"./$rel" + } + else if (file.nodeModulesNested) { // `node_modules`, but relative path + val p = dirname(TSImport.createInterfaceForNode(resolve)) + val rel = normalize(TSPathResolver.relative(p, file.localFilename)) + if (isLocal(rel)) rel else s"./$rel" + } + else + file.localFilename + val ext = TSPathResolver.extname(importedPath) + if (!ext.isEmpty()) + importedPath.replace(ext, ".mlsi") + else importedPath + ".mlsi" + } + + def translateImportToInterface(path: String)(implicit config: js.Dynamic): String = { + val file = `import`(path) + translateImportToInterface(file) + } + + def resolve(implicit config: js.Dynamic) = + if (isNodeModule && !nodeModulesNested) TypeScript.resolveModuleName(filename, parent.getOrElse(""), config) + else if (nodeModulesNested) TypeScript.resolveModuleName(s"./$moduleName", parent.getOrElse(""), config) + else TSPathResolver.resolve(filename) + + def interfaceFilename(implicit config: js.Dynamic): String = // Interface filename (related to work directory) + relatedPath.fold( + s"$interfaceDir/${dirname(TSImport.createInterfaceForNode(resolve))}/${moduleName}.mlsi" + )(path => s"${normalize(s"$interfaceDir/$path/$moduleName.mlsi")}") + + val jsFilename: String = + relatedPath.fold(filename)(path => normalize(s"$path/$moduleName.js")) + + def `import`(path: String)(implicit config: js.Dynamic): FileInfo = + if (isLocal(path)) + relatedPath match { + case Some(value) => + if (TSPathResolver.isMLScirpt(path)) + FileInfo(workDir, s"./${normalize(s"$value/$path")}", interfaceDir, Some(resolve)) + else { + val res = TypeScript.resolveModuleName(s"./${dirname(path)}/${basename(path)}", resolve, config) + val absWordDir = TSPathResolver.resolve(workDir) + FileInfo(workDir, s"./${TSPathResolver.relative(absWordDir, res)}", interfaceDir, Some(resolve)) + } + case _ => + val currentPath = dirname(TSImport.createInterfaceForNode(resolve)) + FileInfo(workDir, s"./$currentPath/$path", interfaceDir, Some(resolve), true) + } + else FileInfo(workDir, path, interfaceDir, Some(resolve)) +} diff --git a/ts2mls/js/src/main/scala/ts2mls/JSFileSystem.scala b/ts2mls/js/src/main/scala/ts2mls/JSFileSystem.scala new file mode 100644 index 000000000..0e03704fb --- /dev/null +++ b/ts2mls/js/src/main/scala/ts2mls/JSFileSystem.scala @@ -0,0 +1,30 @@ +package ts2mls + +import scala.scalajs.js +import js.Dynamic.{global => g} +import js.DynamicImplicits._ +import js.JSConverters._ +import ts2mls.TSPathResolver + +object JSFileSystem { + private val fs = g.require("fs") // Must use fs module to manipulate files in JS + + def exists(filename: String): Boolean = fs.existsSync(filename) + + def readFile(filename: String): Option[String] = + if (!exists(filename)) None + else Some(fs.readFileSync(filename).toString) + + def writeFile(filename: String, content: String): Unit = { + val dir = TSPathResolver.dirname(filename) + if (!exists(dir)) fs.mkdirSync(dir, js.Dictionary("recursive" -> true)) + fs.writeFileSync(filename, content) + } + + def getModificationTime(filename: String): Double = + if (!exists(filename)) 0.0 + else { + val state = fs.statSync(filename) + state.mtimeMs.asInstanceOf[Double] + } +} diff --git a/ts2mls/js/src/main/scala/ts2mls/JSGitHelper.scala b/ts2mls/js/src/main/scala/ts2mls/JSGitHelper.scala new file mode 100644 index 000000000..e11229b4b --- /dev/null +++ b/ts2mls/js/src/main/scala/ts2mls/JSGitHelper.scala @@ -0,0 +1,25 @@ +package ts2mls + +import mlscript.utils.GitHelper +import scala.scalajs.js +import js.Dynamic.{global => g} +import js.DynamicImplicits._ + +class JSGitHelper(rootDir: String, workDir: String, val forceIfNoChange: Boolean) extends GitHelper[String, String](rootDir, workDir) { + override protected def str2RelPath(s: String): String = s + override protected def diff: Iterator[String] = { + val res = JSGitHelper.cp.execSync(s"git status --porcelain $workDir").toString() + if (res.isEmpty()) Iterator() + else res.split("\n").iterator + } + + override def filter(file: String): Boolean = + modified(TSPathResolver.normalize(file)) || (forceIfNoChange && modified.isEmpty) +} + +object JSGitHelper { + def apply(rootDir: String, workDir: String, forceIfNoChange: Boolean): JSGitHelper = + new JSGitHelper(rootDir, workDir, forceIfNoChange) + + private val cp = g.require("child_process") +} diff --git a/ts2mls/js/src/main/scala/ts2mls/JSWriter.scala b/ts2mls/js/src/main/scala/ts2mls/JSWriter.scala index b448bbcbf..890c9fe65 100644 --- a/ts2mls/js/src/main/scala/ts2mls/JSWriter.scala +++ b/ts2mls/js/src/main/scala/ts2mls/JSWriter.scala @@ -1,50 +1,33 @@ package ts2mls import scala.scalajs.js -import js.Dynamic.{global => g} import js.DynamicImplicits._ import mlscript.utils._ +import scala.collection.mutable.StringBuilder class JSWriter(filename: String) { - import JSWriter._ - - // Create an empty file if it does not exists. - if (!fs.existsSync(filename)) fs.writeFileSync(filename, "") - - // r+: Open file for reading and writing. An exception occurs if the file does not exist. - // See https://nodejs.org/api/fs.html#file-system-flags to get more details. - private val out = fs.openSync(filename, "r+") - - private var fileSize = 0 // how many bytes we've written in the file - private var needTruncate = false - - writeln(":NewDefs\n:ParseOnly") - - def writeln(str: String) = { - val strln = str + "\n" - val buffer = createBuffer(strln.length) - fs.readSync(out, buffer, 0, strln.length) - - // override when the content is different - if (strln =/= buffer.toString()) { - fs.writeSync(out, strln, fileSize) // `fileSize` is the offset from the beginning of the file - needTruncate = true // if the file has been modified, we need to truncate the file to keep it clean - } - - fileSize += strln.length + import JSFileSystem._ + + private val buffer = new StringBuilder() + private val dbg = new StringBuilder() + private val err = new StringBuilder() + + def writeln(str: String): Unit = write(str + "\n") + def write(str: String): Unit = buffer ++= str + def writeErr(str: String): Unit = err ++= s"//| $str\n" + def writeDbg(str: String): Unit = str.split("\n").foreach(s => dbg ++= s"//| $s\n") + + def close(): Boolean = { + val str = buffer.toString() + dbg.toString() + err.toString() + val origin = readFile(filename).getOrElse("") + val updated = str =/= origin + if (updated) writeFile(filename, str) + updated } - def close() = { - if (needTruncate) fs.truncateSync(out, fileSize) // remove other content to keep the file from chaos - - fs.closeSync(out) - } + def getContent: String = buffer.toString() } object JSWriter { - private val fs = g.require("fs") // must use fs module to manipulate files in JS - def apply(filename: String) = new JSWriter(filename) - - private def createBuffer(length: Int) = g.Buffer.alloc(length) } diff --git a/ts2mls/js/src/main/scala/ts2mls/TSCompilerInfo.scala b/ts2mls/js/src/main/scala/ts2mls/TSCompilerInfo.scala index b57f67d16..844dfccae 100644 --- a/ts2mls/js/src/main/scala/ts2mls/TSCompilerInfo.scala +++ b/ts2mls/js/src/main/scala/ts2mls/TSCompilerInfo.scala @@ -5,30 +5,79 @@ import js.Dynamic.{global => g} import js.DynamicImplicits._ import js.JSConverters._ import ts2mls.types._ +import mlscript.utils._ +import js.isUndefined object TypeScript { - private val ts: js.Dynamic = try g.require("typescript") catch { + def load(moduleName: String) = try g.require(moduleName) catch { case _ : Throwable => { - System.err.println("Cannot find typescript in the current directory. Please install by running \"npm install\".") + System.err.println(s"Cannot find $moduleName in the current directory. Please install by running \"npm install\".") val process = g.require("process") process.exit(-1) } } + private val ts: js.Dynamic = load("typescript") + private val json: js.Dynamic = load("json5") + private val sys: js.Dynamic = ts.sys + private val process: js.Dynamic = g.require("process") + + // * For other platforms, we need to invoke `toLowerCase` on the resolved names, or the file would not be found. + lazy val isLinux: Boolean = process.platform.toString().toLowerCase === "linux" + + // tsconfig.json + def parseOption(basePath: String, filename: Option[String]): js.Dynamic = { + val config = filename.fold[js.Any](js.Dictionary())(filename => { + val content = JSFileSystem.readFile(TSPathResolver.normalize(s"$basePath/$filename")).getOrElse("") + json.parse(content) + }) + val name = filename.getOrElse("tsconfig.json") + ts.parseJsonConfigFileContent(config, sys, basePath, null, name) + } + + // package.json + def parsePackage(path: String): js.Dynamic = { + val content = JSFileSystem.readFile(TSPathResolver.normalize(path)).getOrElse("") + json.parse(content) + } + + def resolveModuleName(importName: String, containingName: String, config: js.Dynamic): String = { + val res = ts.resolveModuleName(importName, containingName, config, sys) + if (!isUndefined(res.resolvedModule) && !isUndefined(res.resolvedModule.resolvedFileName)) + res.resolvedModule.resolvedFileName.toString() + else + throw new Exception(s"can not resolve module $importName in $containingName.") + } + + def getOutputFileNames(filename: String, config: js.Dynamic): String = + ts.getOutputFileNames(config, filename, false).toString() + val typeFlagsEnumLike = ts.TypeFlags.EnumLike val typeFlagsObject = ts.TypeFlags.Object val typeFlagsTypeParameter = ts.TypeFlags.TypeParameter val syntaxKindPrivate = ts.SyntaxKind.PrivateKeyword val syntaxKindProtected = ts.SyntaxKind.ProtectedKeyword val syntaxKindStatic = ts.SyntaxKind.StaticKeyword + val syntaxKindExport = ts.SyntaxKind.ExportKeyword val objectFlagsAnonymous = ts.ObjectFlags.Anonymous - val symbolFlagsOptional = ts.SymbolFlags.Optional // this flag is only for checking optional members of interfaces + val objectFlagsMapped = ts.ObjectFlags.Mapped + val symbolFlagsOptional = ts.SymbolFlags.Optional // This flag is only for checking optional members of interfaces + val typeFlagsConditional = ts.TypeFlags.Conditional // `T extends U ? X : Y` + val typeFlagsIndex = ts.TypeFlags.Index // `keyof T` + val typeFlagsIndexedAccess = ts.TypeFlags.IndexedAccess // `T[K]` def isToken(node: js.Dynamic) = ts.isToken(node) def isClassDeclaration(node: js.Dynamic) = ts.isClassDeclaration(node) def isInterfaceDeclaration(node: js.Dynamic) = ts.isInterfaceDeclaration(node) def isFunctionLike(node: js.Dynamic) = ts.isFunctionLike(node) def isModuleDeclaration(node: js.Dynamic) = ts.isModuleDeclaration(node) + def isImportDeclaration(node: js.Dynamic) = ts.isImportDeclaration(node) + def isSourceFile(node: js.Dynamic) = ts.isSourceFile(node) + def isExportDeclaration(node: js.Dynamic) = ts.isExportDeclaration(node) + def isImportEqualsDeclaration(node: js.Dynamic) = ts.isImportEqualsDeclaration(node) + def isExportAssignment(node: js.Dynamic) = ts.isExportAssignment(node) + def isNamespaceExportDeclaration(node: js.Dynamic) = ts.isNamespaceExportDeclaration(node) + def isArrayTypeNode(node: js.Dynamic) = ts.isArrayTypeNode(node) def isTupleTypeNode(node: js.Dynamic) = ts.isTupleTypeNode(node) def isTypeAliasDeclaration(node: js.Dynamic) = ts.isTypeAliasDeclaration(node) @@ -36,10 +85,38 @@ object TypeScript { def isLiteralTypeNode(node: js.Dynamic) = ts.isLiteralTypeNode(node) def isStringLiteral(node: js.Dynamic) = ts.isStringLiteral(node) def isVariableDeclaration(node: js.Dynamic) = ts.isVariableDeclaration(node) + def isIndexSignatureDeclaration(node: js.Dynamic) = ts.isIndexSignatureDeclaration(node) + def isConstructSignatureDeclaration(node: js.Dynamic) = ts.isConstructSignatureDeclaration(node) + def isCallSignatureDeclaration(node: js.Dynamic) = ts.isCallSignatureDeclaration(node) def forEachChild(root: js.Dynamic, func: js.Dynamic => Unit) = ts.forEachChild(root, func) def createProgram(filenames: Seq[String]) = - ts.createProgram(filenames.toJSArray, js.Dictionary("maxNodeModuleJsDepth" -> 0, "target" -> ts.ScriptTarget.ES5, "module" -> ts.ModuleKind.CommonJS)) + ts.createProgram(filenames.toJSArray, js.Dictionary( + "maxNodeModuleJsDepth" -> 0, + "target" -> ts.ScriptTarget.ES5, + "module" -> ts.ModuleKind.ES5, + "esModuleInterop" -> true + )) + + def isESModule(config: js.Dynamic, isJS: Boolean): Boolean = + if (isJS) { + val tp = config.selectDynamic("type") + if (isUndefined(tp)) false + else tp.toString() === "module" + } + else { + val raw = config.selectDynamic("raw") + if (isUndefined(raw)) false + else { + val opt = raw.selectDynamic("compilerOptions") + if (isUndefined(opt)) false + else { + val mdl = opt.selectDynamic("module") + if (isUndefined(mdl)) false + else mdl.toString() =/= "CommonJS" + } + } + } } class TSTypeChecker(checker: js.Dynamic) { @@ -62,11 +139,11 @@ object TSTypeChecker { } class TSSymbolObject(sym: js.Dynamic)(implicit checker: TSTypeChecker) extends TSAny(sym) { - private lazy val parent = TSSymbolObject(sym.parent) private lazy val flags = sym.flags + lazy val parent = TSSymbolObject(sym.parent) - // the first declaration of this symbol - // if there is no overloading, there is only one declaration + // The first declaration of this symbol/ + // If there is no overloading, there is only one declaration lazy val declaration = if (declarations.isUndefined) TSNodeObject(g.undefined) else declarations.get(0) @@ -75,12 +152,8 @@ class TSSymbolObject(sym: js.Dynamic)(implicit checker: TSTypeChecker) extends T lazy val `type` = TSTypeObject(sym.selectDynamic("type")) lazy val isOptionalMember = (flags & TypeScript.symbolFlagsOptional) > 0 - - // get the full name of the reference symbol - // e.g. class A extends B => class A extends SomeNamespace'B - lazy val fullName: String = - if (parent.isUndefined || !parent.declaration.isNamespace) escapedName - else s"${parent.fullName}.$escapedName" + lazy val valueDeclaration = TSNodeObject(sym.valueDeclaration) + lazy val isMerged = !js.isUndefined(sym.mergeId) } object TSSymbolObject { @@ -89,6 +162,7 @@ object TSSymbolObject { class TSNodeObject(node: js.Dynamic)(implicit checker: TSTypeChecker) extends TSAny(node) { private lazy val modifiers = TSTokenArray(node.modifiers) + lazy val parent = TSNodeObject(node.parent) lazy val isToken = TypeScript.isToken(node) lazy val isClassDeclaration = TypeScript.isClassDeclaration(node) @@ -97,24 +171,35 @@ class TSNodeObject(node: js.Dynamic)(implicit checker: TSTypeChecker) extends TS lazy val isTypeAliasDeclaration = TypeScript.isTypeAliasDeclaration(node) lazy val isLiteralTypeNode = TypeScript.isLiteralTypeNode(node) lazy val isVariableDeclaration = TypeScript.isVariableDeclaration(node) + lazy val isIndexSignature = TypeScript.isIndexSignatureDeclaration(node) + lazy val isCallSignature = TypeScript.isCallSignatureDeclaration(node) + lazy val isConstructSignature = TypeScript.isConstructSignatureDeclaration(node) lazy val isObjectLiteral = !initializer.isUndefined && !initializer.isToken && TypeScript.isObjectLiteralExpression(node.initializer) - // `TypeScript.isModuleDeclaration` works on both namespaces and modules - // but namespaces are more recommended, so we merely use `isNamespace` here + // `TypeScript.isModuleDeclaration` works on both namespaces and modules. + // But namespaces are more recommended, so we merely use `isNamespace` here lazy val isNamespace = TypeScript.isModuleDeclaration(node) lazy val isArrayTypeNode = TypeScript.isArrayTypeNode(node) lazy val isTupleTypeNode = TypeScript.isTupleTypeNode(node) lazy val isImplementationOfOverload = checker.isImplementationOfOverload(node) - - // if a node has an initializer or is marked by a question notation it is optional + lazy val isImportDeclaration = TypeScript.isImportDeclaration(node) + lazy val isRequire = TypeScript.isImportEqualsDeclaration(node) + lazy val isSourceFile = TypeScript.isSourceFile(node) + lazy val isExportDeclaration = TypeScript.isExportDeclaration(node) + lazy val isExportAssignment = TypeScript.isExportAssignment(node) + lazy val exportedAsNamespace = TypeScript.isNamespaceExportDeclaration(node) + + // If a node has an initializer or is marked by a question notation it is optional // e.g. `function f(x?: int) {}`, we can use it directly: `f()`. - // in this case, there would be a question token. + // In this case, there would be a question token. // e.g. `function f(x: int = 42) {}`, we can use it directly: `f()`. - // in this case, the initializer would store the default value and be non-empty. + // In this case, the initializer would store the default value and be non-empty. lazy val isOptionalParameter = checker.isOptionalParameter(node) lazy val isStatic = if (modifiers.isUndefined) false else modifiers.foldLeft(false)((s, t) => t.isStatic) + lazy val isExported = if (modifiers.isUndefined) false + else modifiers.foldLeft(false)((s, t) => t.isExported) lazy val typeNode = TSTypeObject(checker.getTypeFromTypeNode(node)) lazy val typeAtLocation = TSTypeObject(checker.getTypeAtLocation(node)) @@ -127,7 +212,8 @@ class TSNodeObject(node: js.Dynamic)(implicit checker: TSTypeChecker) extends TS lazy val types = TSNodeArray(node.types) lazy val heritageClauses = TSNodeArray(node.heritageClauses) lazy val initializer = TSNodeObject(node.initializer) - lazy val initToken = TSTokenObject(node.initializer) // for object literal, the initializer is a token. + lazy val initToken = TSTokenObject(node.initializer) // For object literal, the initializer is a token. + lazy val initID = TSIdentifierObject(node.initializer) lazy val modifier = if (modifiers.isUndefined) Public else modifiers.foldLeft[TSAccessModifier](Public)( @@ -140,12 +226,38 @@ class TSNodeObject(node: js.Dynamic)(implicit checker: TSTypeChecker) extends TS else declarations.get(0) lazy val locals = TSSymbolMap(node.locals) + lazy val exports = TSSymbolMap(node.symbol.exports) lazy val returnType = TSTypeObject(checker.getReturnTypeOfSignature(node)) lazy val `type` = TSNodeObject(node.selectDynamic("type")) lazy val symbolType = TSTypeObject(checker.getTypeOfSymbolAtLocation(node.symbol, node)) lazy val literal = TSTokenObject(node.literal) lazy val name = TSIdentifierObject(node.name) + + // TODO: multiline string support + override def toString(): String = + if (js.isUndefined(node)) "" else node.getText().toString().replaceAll("\n", " ").replaceAll("\"", "'") + lazy val filename: String = + if (parent.isUndefined) node.fileName.toString() + else parent.filename + lazy val pos = node.pos + + lazy val moduleSpecifier = TSTokenObject(node.moduleSpecifier) + lazy val importClause = TSNodeObject(node.importClause) + lazy val namedBindings = TSNodeObject(node.namedBindings) + lazy val elements = TSNodeArray(node.elements) + lazy val propertyName = TSIdentifierObject(node.propertyName) + lazy val exportClause = TSNodeObject(node.exportClause) + lazy val resolvedPath: String = node.resolvedPath.toString() + lazy val moduleReference = TSNodeObject(node.moduleReference) + lazy val expression = TSTokenObject(node.expression) + lazy val idExpression = TSIdentifierObject(node.expression) + lazy val nodeExpression = TSNodeObject(node.expression) + lazy val isVarParam = !js.isUndefined(node.dotDotDotToken) + lazy val hasModuleReference = !js.isUndefined(node.moduleReference) + lazy val moduleAugmentation = + if (js.isUndefined(node.moduleAugmentations)) TSTokenObject(g.undefined) + else TSTokenObject(node.moduleAugmentations.selectDynamic("0")) } object TSNodeObject { @@ -158,6 +270,7 @@ class TSTokenObject(token: js.Dynamic)(implicit checker: TSTypeChecker) extends lazy val isPrivate = kind == TypeScript.syntaxKindPrivate lazy val isProtected = kind == TypeScript.syntaxKindProtected lazy val isStatic = kind == TypeScript.syntaxKindStatic + lazy val isExported = kind == TypeScript.syntaxKindExport lazy val typeNode = TSTypeObject(checker.getTypeFromTypeNode(token)) lazy val text = token.text.toString() @@ -170,15 +283,17 @@ object TSTokenObject { class TSTypeObject(obj: js.Dynamic)(implicit checker: TSTypeChecker) extends TSAny(obj) { private lazy val flags = obj.flags - private lazy val objectFlags = if (IsUndefined(obj.objectFlags)) 0 else obj.objectFlags + private lazy val objectFlags: js.Dynamic = if (js.isUndefined(obj.objectFlags)) 0 else obj.objectFlags private lazy val baseType = TSTypeObject(checker.getBaseType(obj)) lazy val symbol = TSSymbolObject(obj.symbol) + lazy val aliasSymbol = TSSymbolObject(obj.aliasSymbol) lazy val typeArguments = TSTypeArray(checker.getTypeArguments(obj)) lazy val intrinsicName: String = - if (!IsUndefined(obj.intrinsicName)) obj.intrinsicName.toString + if (!js.isUndefined(obj.intrinsicName)) obj.intrinsicName.toString else baseType.intrinsicName + lazy val `type` = TSTypeObject(obj.selectDynamic("type")) lazy val types = TSTypeArray(obj.types) lazy val properties = TSSymbolArray(checker.getPropertiesOfType(obj)) lazy val node = TSNodeObject(checker.typeToTypeNode(obj)) @@ -190,10 +305,14 @@ class TSTypeObject(obj: js.Dynamic)(implicit checker: TSTypeChecker) extends TSA lazy val isUnionType = obj.isUnion() lazy val isIntersectionType = obj.isIntersection() lazy val isFunctionLike = node.isFunctionLike - lazy val isAnonymous = objectFlags == TypeScript.objectFlagsAnonymous + lazy val isAnonymous = (objectFlags & TypeScript.objectFlagsAnonymous) > 0 + lazy val isMapped = (objectFlags & TypeScript.objectFlagsMapped) > 0 // Mapping a type to another by using `keyof` and so on lazy val isTypeParameter = flags == TypeScript.typeFlagsTypeParameter lazy val isObject = flags == TypeScript.typeFlagsObject lazy val isTypeParameterSubstitution = isObject && typeArguments.length > 0 + lazy val isConditionalType = flags == TypeScript.typeFlagsConditional + lazy val isIndexType = flags == TypeScript.typeFlagsIndex + lazy val isIndexedAccessType = flags == TypeScript.typeFlagsIndexedAccess } object TSTypeObject { diff --git a/ts2mls/js/src/main/scala/ts2mls/TSData.scala b/ts2mls/js/src/main/scala/ts2mls/TSData.scala index 525664801..4d6ec419b 100644 --- a/ts2mls/js/src/main/scala/ts2mls/TSData.scala +++ b/ts2mls/js/src/main/scala/ts2mls/TSData.scala @@ -3,16 +3,13 @@ package ts2mls import scala.scalajs.js import js.DynamicImplicits._ import js.JSConverters._ +import mlscript.utils._ abstract class TSAny(v: js.Dynamic) { - val isUndefined: Boolean = IsUndefined(v) + val isUndefined: Boolean = js.isUndefined(v) } -object IsUndefined { - def apply(v: js.Dynamic): Boolean = js.isUndefined(v) -} - -// array for information object in tsc +// Array for information object in tsc abstract class TSArray[T <: TSAny](arr: js.Dynamic) extends TSAny(arr) { def get(index: Int): T = ??? lazy val length = arr.length @@ -30,6 +27,11 @@ abstract class TSArray[T <: TSAny](arr: js.Dynamic) extends TSAny(arr) { f(get(index)) foreach(f, index + 1) } + + def mapToList[U](f: T => U, index: Int = 0, res: List[U] = Nil): List[U] = + if (!isUndefined && index < length) + mapToList(f, index + 1, f(get(index)) :: res) + else res.reverse } class TSNodeArray(arr: js.Dynamic)(implicit checker: TSTypeChecker) extends TSArray[TSNodeObject](arr) { @@ -68,8 +70,35 @@ class TSSymbolMap(map: js.Dynamic)(implicit checker: TSTypeChecker) extends TSAn def foreach(f: TSSymbolObject => Unit): Unit = if (!isUndefined) map.forEach({(s: js.Dynamic) => f(TSSymbolObject(s))}) + + def contains(name: String): Boolean = map.has(name) } object TSSymbolMap { def apply(map: js.Dynamic)(implicit checker: TSTypeChecker) = new TSSymbolMap(map) } + +class TSLineStartsHelper(arr: js.Dynamic) extends TSAny(arr) { + if (isUndefined) throw new AssertionError("can not read line starts from the source file.") + + // line, column in string + def getPos(pos: js.Dynamic): (String, String) = if (js.isUndefined(pos)) die else { + val len = arr.length + def run(index: Int): (String, String) = + if (index >= len) throw new AssertionError(s"invalid pos parameter $pos.") + else { + val starts = arr.selectDynamic(index.toString) + if (pos >= starts) { + if (index + 1 >= len) ((index + 1).toString, (pos - starts).toString()) + else { + val next = arr.selectDynamic((index + 1).toString) + if (pos >= next) run(index + 1) + else ((index + 1).toString, (pos - starts).toString()) + } + } + else throw new AssertionError(s"invalid pos parameter $pos.") + } + + run(0) + } +} diff --git a/ts2mls/js/src/main/scala/ts2mls/TSModules.scala b/ts2mls/js/src/main/scala/ts2mls/TSModules.scala new file mode 100644 index 000000000..e271aebc3 --- /dev/null +++ b/ts2mls/js/src/main/scala/ts2mls/TSModules.scala @@ -0,0 +1,92 @@ +package ts2mls + +import scala.collection.mutable.HashMap +import mlscript.utils._ +import ts2mls.types.{TSTypeAlias, TSReferenceType, Converter} +import ts2mls.TSPathResolver + +final case class TSReExport(alias: String, filename: String, memberName: Option[String]) + +trait TSImport { self => + val filename: String + + def resolveTypeAlias(name: String): Option[String] = self match { + case TSFullImport(filename, _) => Some(s"${TSPathResolver.basename(filename)}.$name") + case TSSingleImport(filename, items) => + items.collect { + case (originalName, _) if (originalName === name) => + s"${TSPathResolver.basename(filename)}.$name" + }.headOption + } + + def createAlias: List[TSReExport] = self match { + case TSFullImport(filename, alias) => + TSReExport(alias, filename, None) :: Nil + case TSSingleImport(filename, items) => + items.map{ case (name, alias) => + TSReExport(alias.getOrElse(name), filename, Some(name)) + } + } +} + +object TSImport { + def createInterfaceForNode(fullpath: String): String = { + import TSPathResolver.{basename, dirname} + val moduleName = basename(fullpath) + val dir = dirname(fullpath) + val nodeName = "node_modules" + val related = + if (dir.contains(nodeName)) dir.substring(dir.lastIndexOf(nodeName) + nodeName.length()) + else throw new AssertionError(s"$fullpath is not related to $nodeName.") + s"$nodeName/$related/$moduleName.mlsi" + } +} + +// import * as alias from "filename" +case class TSFullImport(filename: String, alias: String) extends TSImport +// import { s1, s2 as a } from "filename" +// export { s1, s2 as a } from "filename" +case class TSSingleImport(filename: String, items: List[(String, Option[String])]) extends TSImport + +class TSImportList { + private val singleList = new HashMap[String, TSSingleImport]() + private val fullList = new HashMap[String, TSFullImport]() + + def add(fullPath: String, imp: TSImport): Unit = imp match { + case imp: TSFullImport => fullList.addOne((fullPath, imp)) + case imp @ TSSingleImport(filename, items) => + if (singleList.contains(fullPath)) + singleList.update(fullPath, TSSingleImport(filename, singleList(fullPath).items ::: items)) + else singleList.addOne((fullPath, imp)) + } + + def remove(fullPath: String): Unit = { + singleList.remove(fullPath) + fullList.remove(fullPath) + () + } + + def resolveTypeAlias(modulePath: String, name: String): String = { + val singleAlias = + if (singleList.contains(modulePath)) singleList(modulePath).resolveTypeAlias(name) + else None + singleAlias match { + case Some(alias) => alias + case None => + val fullAlias = + if (fullList.contains(modulePath)) fullList(modulePath).resolveTypeAlias(name) + else None + fullAlias.getOrElse(throw new Exception(s"$name is not found at $modulePath")) + } + } + + def contains(modulePath: String): Boolean = + singleList.contains(modulePath) || fullList.contains(modulePath) + + def getFilelist: List[TSImport] = + (singleList.values.toList ::: fullList.values.toList) +} + +object TSImportList { + def apply() = new TSImportList() +} diff --git a/ts2mls/js/src/main/scala/ts2mls/TSNamespace.scala b/ts2mls/js/src/main/scala/ts2mls/TSNamespace.scala index bd54aa568..d48b0722f 100644 --- a/ts2mls/js/src/main/scala/ts2mls/TSNamespace.scala +++ b/ts2mls/js/src/main/scala/ts2mls/TSNamespace.scala @@ -4,63 +4,178 @@ import scala.collection.mutable.{HashMap, ListBuffer} import types._ import mlscript.utils._ -class TSNamespace(name: String, parent: Option[TSNamespace]) { - private val subSpace = HashMap[String, TSNamespace]() - private val members = HashMap[String, TSType]() +class TSNamespace(name: String, parent: Option[TSNamespace], allowReservedTypes: Boolean) { + // name -> (namespace/type, export) + private val subSpace = HashMap[String, (TSNamespace, Boolean)]() + private val members = HashMap[String, (TSType, Boolean)]() + private val cjsExport = HashMap[String, String]() - // write down the order of members - // easier to check the output one by one + // Write down the order of members. + // Easier to check the output one by one. private val order = ListBuffer.empty[Either[String, String]] - def derive(name: String): TSNamespace = - if (subSpace.contains(name)) subSpace(name) // if the namespace has appeared in another file, just return it + def isCommonJS = !cjsExport.isEmpty + + override def toString(): String = parent match { + case Some(parent) if !parent.toString().isEmpty() => s"${parent.toString()}.$name" + case _ => name + } + + def derive(name: String, exported: Boolean): TSNamespace = + if (subSpace.contains(name)) subSpace(name)._1 // If the namespace has appeared in another file, just return it else { - val sub = new TSNamespace(name, Some(this)) - subSpace.put(name, sub) + val sub = new TSNamespace(name, Some(this), allowReservedTypes) // Not a top level module! + subSpace.put(name, (sub, exported)) order += Left(name) sub } - def put(name: String, tp: TSType): Unit = + def put(name: String, tp: TSType, exported: Boolean, overrided: Boolean): Unit = if (!members.contains(name)) { order += Right(name) - members.put(name, tp) + members.put(name, (tp, exported)) + } + else if (overrided) members.update(name, (tp, exported)) + else (members(name), tp) match { + case ((cls: TSClassType, exp), itf: TSInterfaceType) => + members.update(name, (TSClassType( + name, cls.members ++ itf.members, cls.statics, cls.typeVars, + cls.parents, cls.constructor + ), exported || exp)) + case ((itf1: TSInterfaceType, exp), itf2: TSInterfaceType) => + members.update(name, (TSInterfaceType( + name, itf1.members ++ itf2.members, itf1.typeVars, itf1.parents, + itf1.callSignature.fold(itf2.callSignature)(cs => Some(cs)) + ), exported || exp)) + case _ => () + } + + def `export`(name: String): Unit = + if (members.contains(name)) + members.update(name, (members(name)._1, true)) + else if (subSpace.contains(name)) + subSpace.update(name, (subSpace(name)._1, true)) + + def renameExport(from: String, to: String): Unit = + if (members.contains(from)) { + cjsExport.put(from, to) + members.update(from, (members(from)._1, true)) + } + else if (subSpace.contains(from)) { + cjsExport.put(from, to) + subSpace.update(from, (subSpace(from)._1, true)) } - else members.update(name, tp) + else throw new Exception(s"member $from not found.") + + def exported(name: String): Boolean = + if (members.contains(name)) members(name)._2 + else throw new Exception(s"member $name not found.") + + private def getNS(name: String): TSNamespace = + if (subSpace.contains(name)) subSpace(name)._1 + else parent.fold(throw new Exception(s"namespace $name not found."))(p => p.getNS(name)) def get(name: String): TSType = - members.getOrElse(name, - if (!parent.isEmpty) parent.get.get(name) else throw new Exception(s"member $name not found.")) + if (members.contains(name)) members(name)._1 + else parent.fold[TSType](TSReferenceType(name))(p => p.get(name)) // Default in es5 + + def get(names: List[String]): TSType = names match { + case head :: Nil => get(head) + case head :: tails => + def run(ns: TSNamespace, list: List[String]): TSType = + list match { + case head :: Nil => ns.members(head)._1 + case head :: tails => run(ns.subSpace(name)._1, tails) + case _ => throw new Exception(s"member ${names.mkString(".")} not found.") + } + run(getNS(head), tails) + case _ => throw new Exception(s"member ${names.mkString(".")} not found.") + } + + def exportWithAlias(name: String, alias: String): Unit = + if (members.contains(name)) members(name)._1 match { + case _: TSClassType => put(alias, TSRenamedType(alias, TSReferenceType(name)), true, false) + case _: TSInterfaceType => put(alias, TSRenamedType(alias, TSReferenceType(name)), true, false) + case _: TSTypeAlias => None // Type alias in ts would be erased. + case tp => put(alias, TSRenamedType(alias, tp), true, false) // Variables & functions + } + else if (subSpace.contains(name)) put(alias, TSRenamedType(alias, TSReferenceType(name)), true, false) def containsMember(name: String, searchParent: Boolean = true): Boolean = if (parent.isEmpty) members.contains(name) else (members.contains(name) || (searchParent && parent.get.containsMember(name))) + private lazy val typer = + new mlscript.Typer( + dbg = false, + verbose = false, + explainErrors = false, + newDefs = true + ) + + private def generateNS(name: String, writer: JSWriter, indent: String): Unit = { + val ss = subSpace(name) + val realName = cjsExport.getOrElse(name, name) + val exp = Converter.genExport(realName =/= name || ss._2) + writer.writeln(s"${indent}${exp}declare module ${Converter.escapeIdent(realName)} {") + ss._1.generate(writer, indent + " ") + writer.writeln(s"$indent}") + } + + private def merge(name: String, writer: JSWriter, indent: String): Unit = { + (members(name), subSpace(name)._1) match { + case ((ref: TSReferenceType, exp), ns) => get(ref.nameList) match { + case TSInterfaceType(itf, members, _, _, _) => + ns.subSpace.mapValuesInPlace { + case (_, (ns, _)) => (ns, false) + } + ns.members.mapValuesInPlace { + case (_, (mem, _)) => (mem, false) + } + members.foreach{ + case (name, TSMemberType(tp, _)) => + ns.put(name, tp, true, true) + } + case _ => + writer.writeln(s"$indent// WARNING: duplicate $name") // If merging is not supported, do nothing + } + case _ => + writer.writeln(s"$indent// WARNING: duplicate $name") // If merging is not supported, do nothing + } + generateNS(name, writer, indent) + } + def generate(writer: JSWriter, indent: String): Unit = order.toList.foreach((p) => p match { - case Left(subName) => { - writer.writeln(s"${indent}module $subName {") - subSpace(subName).generate(writer, indent + " ") - writer.writeln(s"$indent}") - } - case Right(name) => { - val mem = members(name) - mem match { - case inter: TSIntersectionType => // overloaded functions - writer.writeln(Converter.generateFunDeclaration(inter, name)(indent)) - case f: TSFunctionType => - writer.writeln(Converter.generateFunDeclaration(f, name)(indent)) - case overload: TSIgnoredOverload => - writer.writeln(Converter.generateFunDeclaration(overload, name)(indent)) - case _: TSClassType => writer.writeln(Converter.convert(mem)(indent)) - case TSInterfaceType(name, _, _, _) if (name =/= "") => - writer.writeln(Converter.convert(mem)(indent)) - case _: TSTypeAlias => writer.writeln(Converter.convert(mem)(indent)) - case _ => writer.writeln(s"${indent}let $name: ${Converter.convert(mem)("")}") + case Left(subName) if (!members.contains(subName)) => + generateNS(subName, writer, indent) + case Right(name) => + if (typer.reservedTypeNames.contains(name) && !allowReservedTypes) + writer.writeln(s"$indent// WARNING: type $name is reserved") + else if (subSpace.contains(name)) + merge(name, writer, indent) + else { + val (mem, exp) = members(name) + val realName = cjsExport.getOrElse(name, name) + mem match { + case inter: TSIntersectionType => // Overloaded functions + writer.writeln(Converter.generateFunDeclaration(inter, realName, exp)(indent)) + case f: TSFunctionType => + writer.writeln(Converter.generateFunDeclaration(f, realName, exp)(indent)) + case overload: TSIgnoredOverload => + writer.writeln(Converter.generateFunDeclaration(overload, realName, exp)(indent)) + case _: TSClassType => writer.writeln(Converter.convert(mem, exp)(indent)) + case TSInterfaceType(name, _, _, _, _) if (name =/= "") => // TODO: rename? + writer.writeln(Converter.convert(mem, exp)(indent)) + case _: TSTypeAlias => writer.writeln(Converter.convert(mem, exp)(indent)) + case TSRenamedType(name, original) => + writer.writeln(s"${indent}${Converter.genExport(exp)}val ${Converter.escapeIdent(realName)} = ${Converter.convert(original)("")}") + case _ => writer.writeln(s"${indent}${Converter.genExport(exp)}val ${Converter.escapeIdent(realName)}: ${Converter.convert(mem)("")}") + } } - } + case _ => () }) } object TSNamespace { - def apply() = new TSNamespace("", None) // global namespace + def apply(allowReservedTypes: Boolean) = new TSNamespace("", None, allowReservedTypes) // global namespace } diff --git a/ts2mls/js/src/main/scala/ts2mls/TSPathResolver.scala b/ts2mls/js/src/main/scala/ts2mls/TSPathResolver.scala new file mode 100644 index 000000000..d8a1b509d --- /dev/null +++ b/ts2mls/js/src/main/scala/ts2mls/TSPathResolver.scala @@ -0,0 +1,26 @@ +package ts2mls + +import scala.scalajs.js +import js.Dynamic.{global => g} +import js.DynamicImplicits._ +import js.JSConverters._ + +object TSPathResolver { + private val np: js.Dynamic = g.require("path") // Built-in node module + + def resolve(path: String): String = np.resolve(path).toString() + def dirname(filename: String): String = np.dirname(filename).toString() + def isLocal(path: String): Boolean = + path.startsWith("./") || path.startsWith("/") || path.startsWith("../") + def isMLScirpt(path: String): Boolean = + path.endsWith(".mls") || path.endsWith(".mlsi") + def normalize(path: String): String = np.normalize(path).toString() + + def relative(from: String, to: String) = np.relative(from, to).toString() + def extname(path: String) = + if (path.endsWith(".d.ts")) ".d.ts" // `filename.d.ts`'s extname is `.ts` by default + else np.extname(path).toString() + def basename(filename: String) = + np.basename(filename, extname(filename)).toString() + def basenameWithExt(filename: String) = np.basename(filename).toString() +} diff --git a/ts2mls/js/src/main/scala/ts2mls/TSProgram.scala b/ts2mls/js/src/main/scala/ts2mls/TSProgram.scala index 631e08df6..61a5cfdc4 100644 --- a/ts2mls/js/src/main/scala/ts2mls/TSProgram.scala +++ b/ts2mls/js/src/main/scala/ts2mls/TSProgram.scala @@ -3,21 +3,143 @@ package ts2mls import scala.scalajs.js import js.DynamicImplicits._ import ts2mls.types._ +import scala.collection.mutable.{HashSet, HashMap} -class TSProgram(filenames: Seq[String]) { - private val program = TypeScript.createProgram(filenames) +// For general ts, we still consider that there is a top-level module +// and in mls we will import ts file like this: +// `import * as TopLevelModuleName from "filename"`. +// For es5.d.ts and dom.d.ts, we only need to translate everything +// and it will be imported without top-level module before we compile other files +class TSProgram( + file: FileInfo, + uesTopLevelModule: Boolean, + tsconfig: Option[String], + typer: (FileInfo, JSWriter) => Unit, + gitHelper: Option[JSGitHelper] +) { + private implicit val configContent: js.Dynamic = TypeScript.parseOption(file.workDir, tsconfig) + private val program = TypeScript.createProgram(Seq( + if (file.isNodeModule) file.resolve + else file.filename + )) + private val cache = new HashMap[String, TSSourceFile]() + private implicit val checker: TSTypeChecker = TSTypeChecker(program.getTypeChecker()) - // check if files exist - filenames.foreach((fn) => if (!program.fileExists(fn)) throw new Exception(s"file ${fn} doesn't exist.")) + import TSPathResolver.{basename, extname, isLocal, resolve, dirname, relative, normalize} - val globalNamespace = TSNamespace() - - implicit val checker = TSTypeChecker(program.getTypeChecker()) - filenames.foreach(filename => TSSourceFile(program.getSourceFile(filename), globalNamespace)) + def generate: Boolean = generate(file, None)(Nil) - def generate(writer: JSWriter): Unit = globalNamespace.generate(writer, "") + private def generate(file: FileInfo, ambientNS: Option[TSNamespace])(implicit stack: List[String]): Boolean = { + def resolve(file: FileInfo) = if (TypeScript.isLinux) file.resolve else file.resolve.toLowerCase() + // We prefer to not tract node_modules in git, so we need to check if the interface file exists + def shouldRecompile(filename: String, interface: String) = gitHelper.fold(true)( + helper => helper.forceIfNoChange || helper.filter(relative(TSPathResolver.resolve(file.workDir), filename)) || !JSFileSystem.exists(interface) + ) + + val filename = resolve(file) + val moduleName = file.moduleName + val globalNamespace = ambientNS.getOrElse(TSNamespace(!uesTopLevelModule)) + val sfObj = program.getSourceFileByPath(filename) + val sourceFile = + if (js.isUndefined(sfObj)) throw new Exception(s"can not load source file $filename.") + else TSSourceFile(sfObj, globalNamespace, moduleName) + val importList = sourceFile.getImportList + val reExportList = sourceFile.getReExportList + cache.addOne(filename, sourceFile) + val relatedPath = relative(file.workDir, dirname(filename)) + val interfaceFilename = s"${file.workDir}/${file.interfaceFilename}" + + val (cycleList, otherList) = + importList.map(imp => file.`import`(imp.filename)).filter( + imp => !resolve(imp).endsWith(".js") // If it is not a ts lib, we ignore it and require users to provide full type annotations + ).partitionMap(imp => { + if (stack.contains(resolve(imp))) Left(imp) + else Right(imp) + }) + + val cycleRecompile = cycleList.foldLeft(false)((r, f) => + r || shouldRecompile(resolve(f), s"${f.workDir}/${f.interfaceFilename}")) + val reExportRecompile = reExportList.foldLeft(false)((r, e) => + r || { + val f = file.`import`(e.filename) + shouldRecompile(resolve(f), s"${f.workDir}/${f.interfaceFilename}") + }) + val referencedRecompile: Boolean = sourceFile.referencedFiles.reduce((r: Boolean, s: js.Dynamic) => { + val f = file.`import`(s.toString()) + r || shouldRecompile(resolve(f), interfaceFilename) + }, false) + + val dependentRecompile = otherList.foldLeft(cycleRecompile || reExportRecompile || referencedRecompile)((r, imp) => { + generate(imp, None)(filename :: stack) || r + }) + + if (file.isNodeModule && JSFileSystem.exists(interfaceFilename)) return false // * We do not check files in node modules if the interfaces exist + else if (!dependentRecompile && !shouldRecompile(filename, interfaceFilename)) return false + System.out.println(s"generating interface for ${file.filename}...") + sourceFile.parse + + val writer = JSWriter(interfaceFilename) + val imported = new HashSet[String]() + + otherList.foreach(imp => { + val name = file.translateImportToInterface(imp) + if (!imported(name)) { + imported += name + writer.writeln(s"""import "$name"""") + } + }) + cycleList.foreach(imp => { + if (ambientNS.isEmpty || stack.indexOf(filename) > 0) { + writer.writeln(s"declare module ${Converter.escapeIdent(imp.moduleName)} {") + val sf = cache(resolve(imp)) + sf.parse + sf.global.generate(writer, " ") + writer.writeln("}") + } + }) + + reExportList.foreach { + case TSReExport(alias, imp, memberName) => + val absName = resolve(file.`import`(imp)) + if (!cache.contains(absName)) + throw new AssertionError(s"unexpected re-export from ${imp}") + else { + val ns = cache(absName).global + val moduleName = basename(absName) + memberName.fold( + globalNamespace.put(alias, TSRenamedType(alias, TSReferenceType(moduleName)), true, false) + )(name => globalNamespace.put(alias, TSRenamedType(alias, TSReferenceType(s"$moduleName.$name")), true, false)) + } + } + + sourceFile.referencedFiles.forEach((s: js.Dynamic) => { + generate(file.`import`(s.toString()), sourceFile.getUMDModule)(filename :: stack) + }) + + if (ambientNS.isEmpty) { + generate(writer, globalNamespace, moduleName, globalNamespace.isCommonJS) + typer(file, writer) + writer.close() + } + else false + } + + private def generate(writer: JSWriter, globalNamespace: TSNamespace, moduleName: String, commonJS: Boolean): Unit = + if (!uesTopLevelModule || commonJS) globalNamespace.generate(writer, "") + else { + writer.writeln(s"export declare module ${Converter.escapeIdent(moduleName)} {") + globalNamespace.generate(writer, " ") + writer.writeln("}") + } } object TSProgram { - def apply(filenames: Seq[String]) = new TSProgram(filenames) + def apply( + file: FileInfo, + uesTopLevelModule: Boolean, + tsconfig: Option[String], + typer: (FileInfo, JSWriter) => Unit, + gitHelper: Option[JSGitHelper] + ) = + new TSProgram(file, uesTopLevelModule, tsconfig, typer, gitHelper) } diff --git a/ts2mls/js/src/main/scala/ts2mls/TSSourceFile.scala b/ts2mls/js/src/main/scala/ts2mls/TSSourceFile.scala index aa0f6e15a..983391df1 100644 --- a/ts2mls/js/src/main/scala/ts2mls/TSSourceFile.scala +++ b/ts2mls/js/src/main/scala/ts2mls/TSSourceFile.scala @@ -4,138 +4,332 @@ import scala.scalajs.js import js.DynamicImplicits._ import types._ import mlscript.utils._ +import scala.collection.mutable.ListBuffer -object TSSourceFile { - def apply(sf: js.Dynamic, global: TSNamespace)(implicit checker: TSTypeChecker) = +class TSSourceFile(sf: js.Dynamic, val global: TSNamespace, topName: String)(implicit checker: TSTypeChecker, config: js.Dynamic) { + private val lineHelper = new TSLineStartsHelper(sf.getLineStarts()) + private val importList = TSImportList() + private val reExportList = new ListBuffer[TSReExport]() + private val resolvedPath = sf.resolvedPath.toString() + private var umdModuleName: Option[String] = None // `export as namespace` in ts + + val referencedFiles = sf.referencedFiles.map((x: js.Dynamic) => x.fileName.toString()) + def getUMDModule: Option[TSNamespace] = + umdModuleName.fold[Option[TSNamespace]](Some(global))(name => Some(global.derive(name, false))) + + // Parse import & re-export first + TypeScript.forEachChild(sf, (node: js.Dynamic) => { + val nodeObject = TSNodeObject(node) + if (nodeObject.isRequire) + parseRequire(nodeObject) + else if (nodeObject.isImportDeclaration) + parseImportDeclaration(nodeObject.importClause, nodeObject.moduleSpecifier, false) + else if (nodeObject.isExportDeclaration && !nodeObject.moduleSpecifier.isUndefined) // Re-export + parseImportDeclaration(nodeObject.exportClause, nodeObject.moduleSpecifier, true) + }) + + private var parsed = false + def parse = if (!parsed) { + parsed = true + // Parse main body TypeScript.forEachChild(sf, (node: js.Dynamic) => { val nodeObject = TSNodeObject(node) if (!nodeObject.isToken) { - if (!nodeObject.symbol.isUndefined) // for functions/classes/interfaces - addNodeIntoNamespace(nodeObject, nodeObject.symbol.escapedName)(global) - else if (!nodeObject.declarationList.isUndefined) { // for variables + if (!nodeObject.symbol.isUndefined) { // For functions + if (nodeObject.isFunctionLike) + addFunctionIntoNamespace(nodeObject.symbol, nodeObject, nodeObject.symbol.escapedName)(global) + else // For classes/interfaces/namespace + addNodeIntoNamespace(nodeObject, nodeObject.symbol.escapedName, nodeObject.isExported)(global) + } + else if (!nodeObject.declarationList.isUndefined) { // For variables val decNode = nodeObject.declarationList.declaration - addNodeIntoNamespace(decNode, decNode.symbol.escapedName)(global) + addNodeIntoNamespace(decNode, decNode.symbol.escapedName, decNode.isExported)(global) } } }) - private def getSubstitutionArguments[T <: TSAny](args: TSArray[T]): List[TSType] = + // Parse export + TypeScript.forEachChild(sf, (node: js.Dynamic) => { + val nodeObject = TSNodeObject(node) + if (nodeObject.isExportDeclaration) { + if (nodeObject.moduleSpecifier.isUndefined) // ES modules + parseExportDeclaration(nodeObject.exportClause.elements) + } + else if (nodeObject.isExportAssignment) { // CommonJS + val name = nodeObject.idExpression.escapedText + if (name === "undefined") { // For exports = { ... }. In this case we still need the top-level module + val props = nodeObject.nodeExpression.properties + props.foreach(node => { + val name = node.initID.escapedText + if (name === "undefined") + addNodeIntoNamespace(node.initializer, node.name.escapedText, true)(global) + else if (node.name.escapedText === name) + global.`export`(name) + else global.put(node.name.escapedText, TSRenamedType(node.name.escapedText, TSReferenceType(name)), true, false) + }) + } + else global.renameExport(name, topName) // Export the member directly + } + else if (nodeObject.exportedAsNamespace) // UMD + umdModuleName = Some(nodeObject.symbol.escapedName) + }) + } + + def getImportList: List[TSImport] = importList.getFilelist + def getReExportList: List[TSReExport] = reExportList.toList + + private def parseRequire(req: TSNodeObject): Unit = { + val localName = req.moduleReference.expression.text + val fullname = TypeScript.resolveModuleName(localName, resolvedPath, config) + val moduleName = TSPathResolver.basename(fullname) + val varName = req.name.escapedText + if (req.hasModuleReference) { + val imp = TSFullImport(localName, varName) + importList.add(fullname, imp) + global.put(varName, TSRenamedType(varName, TSReferenceType(s"$moduleName")), false, false) + } + else { + val imp = TSSingleImport(localName, List((varName, None))) + importList.add(fullname, imp) + global.put(varName, TSRenamedType(varName, TSReferenceType(s"$moduleName.$varName")), false, false) + } + } + + private def parseExportDeclaration(elements: TSNodeArray): Unit = { + elements.foreach(ele => + if (ele.propertyName.isUndefined) + global.`export`(ele.symbol.escapedName) + else global.exportWithAlias(ele.propertyName.escapedText, ele.symbol.escapedName) + ) + } + + private def parseImportDeclaration(clause: TSNodeObject, moduleSpecifier: TSTokenObject, exported: Boolean): Unit = { + // Ignore `import "filename.ts"` + if (!clause.isUndefined) { + val bindings = clause.namedBindings + val importName = moduleSpecifier.text + val fullPath = TypeScript.resolveModuleName(importName, resolvedPath, config) + def run(node: TSNodeObject): Unit = + if (!node.elements.isUndefined) { + val list = node.elements.mapToList(ele => + if (ele.propertyName.isUndefined) + (ele.symbol.escapedName, None) + else + (ele.propertyName.escapedText, Some(ele.symbol.escapedName)) + ) + val imp = TSSingleImport(importName, list) + if (exported) imp.createAlias.foreach(re => reExportList += re) // Re-export + importList.add(fullPath, imp) + } + else if (!node.name.isUndefined) { + val imp = TSFullImport(importName, node.name.escapedText) + if (exported) imp.createAlias.foreach(re => reExportList += re) // Re-export + importList.add(fullPath, imp) + } + + if (!bindings.isUndefined) run(bindings) + else run(clause) + } + } + + private def getSubstitutionArguments[T <: TSAny](args: TSArray[T])(implicit ns: TSNamespace): List[TSType] = args.foldLeft(List[TSType]())((lst, arg) => arg match { case token: TSTokenObject => lst :+ getObjectType(token.typeNode) case tp: TSTypeObject => lst :+ getObjectType(tp) }) - private def getObjectType(obj: TSTypeObject): TSType = - if (obj.isEnumType) TSEnumType - else if (obj.isFunctionLike) getFunctionType(obj.symbol.declaration) + private def getSymbolFullname(sym: TSSymbolObject)(implicit ns: TSNamespace): String = { + def simplify(symName: String, nsName: String): String = // Remove unnecessary namespaces prefixes + if (symName.startsWith(nsName + ".")) symName.substring(nsName.length() + 1) + else if (nsName.lastIndexOf('.') > -1) simplify(symName, nsName.substring(0, nsName.lastIndexOf('.'))) + else symName + if (!sym.parent.isUndefined && sym.parent.declaration.isSourceFile) // Imported from another file + importList.resolveTypeAlias(sym.parent.declaration.resolvedPath, sym.escapedName) + else if (!sym.parent.isUndefined && sym.parent.isMerged) { // Merged with other declarations + def findDecFile(node: TSNodeObject): String = + if (node.parent.isUndefined) "" + else if (node.parent.isSourceFile) { + if (node.parent.moduleAugmentation.isUndefined) + node.parent.resolvedPath + else { + val base = node.parent.resolvedPath + val rel = node.parent.moduleAugmentation.text + if (TSPathResolver.isLocal(rel)) TypeScript.resolveModuleName(rel, base, config) + else base + } + } + else findDecFile(node.parent) + val filename = sym.declarations.foldLeft[Option[String]](None)((filename, dec) => filename match { + case filename: Some[String] => filename + case _ => + val res = findDecFile(dec) + Option.when((res === resolvedPath) || importList.contains(res))(res) + }) + filename.fold(sym.escapedName)(filename => // Not found: this file is referenced by `///`. directly use the name is safe + if (filename === resolvedPath) // In the same file + simplify(s"${getSymbolFullname(sym.parent)}.${sym.escapedName}", ns.toString()) + else importList.resolveTypeAlias(filename, sym.escapedName) // In an imported file + ) + } + else if (sym.parent.isUndefined) { // Already top-level symbol + val name = sym.escapedName + if (name.contains("\"")) TSPathResolver.basename(name.substring(1, name.length() - 1)) + else name + } + else + simplify(s"${getSymbolFullname(sym.parent)}.${sym.escapedName}", ns.toString()) + } + + private def markUnsupported(node: TSNodeObject): TSUnsupportedType = + lineHelper.getPos(node.pos) match { + case (line, column) => + TSUnsupportedType(node.toString(), TSPathResolver.basenameWithExt(node.filename), line, column) + } + + private def getObjectType(obj: TSTypeObject)(implicit ns: TSNamespace): TSType = + if (obj.isMapped) TSNoInfoUnsupported + else if (obj.isEnumType) TSEnumType + else if (obj.isFunctionLike) getFunctionType(obj.symbol.declaration, true) else if (obj.isTupleType) TSTupleType(getTupleElements(obj.typeArguments)) else if (obj.isUnionType) getStructuralType(obj.types, true) else if (obj.isIntersectionType) getStructuralType(obj.types, false) else if (obj.isArrayType) TSArrayType(getObjectType(obj.elementTypeOfArray)) - else if (obj.isTypeParameterSubstitution) TSSubstitutionType(obj.symbol.escapedName, getSubstitutionArguments(obj.typeArguments)) + else if (obj.isTypeParameterSubstitution) { + val baseName = getSymbolFullname(if (obj.symbol.isUndefined) obj.aliasSymbol else obj.symbol) + if (baseName.contains(".")) TSNoInfoUnsupported // A.B is not supported in mlscript so far + else TSSubstitutionType(TSReferenceType(baseName), getSubstitutionArguments(obj.typeArguments)) + } else if (obj.isObject) - if (obj.isAnonymous) TSInterfaceType("", getAnonymousPropertiesType(obj.properties), List(), List()) - else TSReferenceType(obj.symbol.fullName) + if (obj.isAnonymous) { + val props = getAnonymousPropertiesType(obj.properties) + // Upper case field names are not supported in records in mlscript so far + if (!props.exists{ case (name, _) if (!name.isEmpty()) => Character.isUpperCase(name(0)); case _ => false}) + TSInterfaceType("", props, List(), List(), None) + else TSNoInfoUnsupported + } + else TSReferenceType(getSymbolFullname(obj.symbol)) else if (obj.isTypeParameter) TSTypeParameter(obj.symbol.escapedName) + else if (obj.isConditionalType || obj.isIndexType || obj.isIndexedAccessType) TSNoInfoUnsupported else TSPrimitiveType(obj.intrinsicName) - // the function `getMemberType` can't process function/tuple type alias correctly - private def getTypeAlias(tn: TSNodeObject): TSType = - if (tn.isFunctionLike) getFunctionType(tn) + // The function `getMemberType` can't process function/tuple type alias correctly + private def getTypeAlias(tn: TSNodeObject)(implicit ns: TSNamespace): TSType = + if (tn.isFunctionLike) + getFunctionType(tn, true) else if (tn.isTupleTypeNode) TSTupleType(getTupleElements(tn.typeNode.typeArguments)) - else getObjectType(tn.typeNode) + else getObjectType(tn.typeNode) match { + case TSPrimitiveType("intrinsic") => markUnsupported(tn) + case t => t + } - // parse string/numeric literal types. we need to add quotes if it is a string literal - private def getLiteralType(tp: TSNodeObject) = + // Parse string/numeric literal types. We need to add quotes if it is a string literal + private def getLiteralType(tp: TSNodeObject)(implicit ns: TSNamespace) = TSLiteralType(tp.literal.text, tp.literal.isStringLiteral) - // parse object literal types - private def getObjectLiteralMembers(props: TSNodeArray) = + // Parse object literal types + private def getObjectLiteralMembers(props: TSNodeArray)(implicit ns: TSNamespace) = props.foldLeft(Map[String, TSMemberType]())((mp, p) => { - mp ++ Map(p.name.escapedText -> TSMemberType(TSLiteralType(p.initToken.text, p.initToken.isStringLiteral))) + mp.updated(p.name.escapedText, TSMemberType(TSLiteralType(p.initToken.text, p.initToken.isStringLiteral))) }) - // get the type of variables in classes/named interfaces/anonymous interfaces - private def getMemberType(node: TSNodeObject): TSType = { - val res: TSType = - if (node.isFunctionLike) getFunctionType(node) - else if (node.`type`.isUndefined) getObjectType(node.typeAtLocation) - else if (node.`type`.isLiteralTypeNode) getLiteralType(node.`type`) - else getObjectType(node.`type`.typeNode) - if (node.symbol.isOptionalMember) TSUnionType(res, TSPrimitiveType("undefined")) - else res - } + // Get the type of variables in classes/named interfaces/anonymous interfaces + private def getMemberType(node: TSNodeObject)(implicit ns: TSNamespace): TSType = + if (node.isIndexSignature || node.isConstructSignature) + markUnsupported(node) + else { + val res = + if (node.isFunctionLike) getFunctionType(node, false) // Erase name to avoid name clash when overriding methods in ts + else if (node.`type`.isUndefined) getObjectType(node.typeAtLocation) + else if (node.`type`.isLiteralTypeNode) getLiteralType(node.`type`) + else getObjectType(node.`type`.typeNode) + if (res.unsupported) markUnsupported(node) + else if (node.symbol.isOptionalMember) TSUnionType(res, TSPrimitiveType("undefined")) + else res + } - private def getTypeParameters(node: TSNodeObject): List[TSTypeParameter] = + private def getTypeParameters(node: TSNodeObject)(implicit ns: TSNamespace): List[TSTypeParameter] = node.typeParameters.foldLeft(List[TSTypeParameter]())((lst, tp) => if (tp.constraint.isUndefined) lst :+ TSTypeParameter(tp.symbol.escapedName, None) else lst :+ TSTypeParameter(tp.symbol.escapedName, Some(getObjectType(tp.constraint.typeNode))) ) - private def getFunctionType(node: TSNodeObject): TSFunctionType = { - val pList = node.parameters.foldLeft(List[TSParameterType]())((lst, p) => ( - // in typescript, you can use `this` to explicitly specifies the callee - // but it never appears in the final javascript file + private def getFunctionType(node: TSNodeObject, keepNames: Boolean)(implicit ns: TSNamespace): TSFunctionType = { + def eraseVarParam(tp: TSType, erase: Boolean) = tp match { // TODO: support ... soon + case arr @ TSArrayType(eleType) if erase => TSUnionType(eleType, arr) + case _ => tp + } + + val pList = node.parameters.foldLeft(List[TSParameterType]())((lst, p) => { + // Erase name to avoid name clash when overriding methods in ts + val name = if (keepNames) p.symbol.escapedName else s"args${lst.length}" + // In typescript, you can use `this` to explicitly specifies the callee. + // But it never appears in the final javascript file if (p.symbol.escapedName === "this") lst - else if (p.isOptionalParameter) - lst :+ TSParameterType(p.symbol.escapedName, TSUnionType(getObjectType(p.symbolType), TSPrimitiveType("undefined"))) - else lst :+ TSParameterType(p.symbol.escapedName, getObjectType(p.symbolType))) - ) + else if (p.isOptionalParameter) // TODO: support optional and default value soon + lst :+ TSParameterType(name, TSUnionType(getObjectType(p.symbolType), TSPrimitiveType("undefined"))) + else lst :+ TSParameterType(name, eraseVarParam(getObjectType(p.symbolType), p.isVarParam)) + }) TSFunctionType(pList, getObjectType(node.returnType), getTypeParameters(node)) } + - private def getStructuralType(types: TSTypeArray, isUnion: Boolean): TSType = + private def getStructuralType(types: TSTypeArray, isUnion: Boolean)(implicit ns: TSNamespace): TSType = types.foldLeft[Option[TSType]](None)((prev, cur) => prev match { case None => Some(getObjectType(cur)) case Some(p) => if (isUnion) Some(TSUnionType(p, getObjectType(cur))) else Some(TSIntersectionType(p, getObjectType(cur))) }).get - private def getTupleElements(elements: TSTypeArray): List[TSType] = + private def getTupleElements(elements: TSTypeArray)(implicit ns: TSNamespace): List[TSType] = elements.foldLeft(List[TSType]())((lst, ele) => lst :+ getObjectType(ele)) - private def getHeritageList(node: TSNodeObject): List[TSType] = - node.heritageClauses.foldLeftIndexed(List[TSType]())((lst, h, index) => - lst :+ getObjectType(h.types.get(index).typeNode) - ) + private def getHeritageList(node: TSNodeObject)(implicit ns: TSNamespace): List[TSType] = + node.heritageClauses.foldLeftIndexed(List[TSType]())((lst, h, index) => { + lst :+ (getObjectType(h.types.get(index).typeNode) match { + case TSArrayType(ele) => TSSubstitutionType(TSReferenceType("Array"), ele :: Nil) + case t => t + }) + }) - private def getClassMembersType(list: TSNodeArray, requireStatic: Boolean): Map[String, TSMemberType] = - list.foldLeft(Map[String, TSMemberType]())((mp, p) => { - val name = p.symbol.escapedName + private def addMember( + mem: TSType, + node: TSNodeObject, + name: String, + mod: Option[TSAccessModifier], + others: Map[String, TSMemberType] + )(implicit ns: TSNamespace): Map[String, TSMemberType] = mem match { + case func: TSFunctionType => { + if (!others.contains(name)) others.updated(name, TSMemberType(func, mod.getOrElse(node.modifier))) + else { // TODO: handle functions' overloading + val res = TSIgnoredOverload(func, name) // The implementation is always after declarations + others.updated(name, TSMemberType(res, mod.getOrElse(node.modifier))) + } + } + case _ => mem match { + // If the member's name is the same as the type name, we need to mark it unsupported + case TSReferenceType(ref) if name === ref => + others.updated(name, TSMemberType( + markUnsupported(node), + mod.getOrElse(node.modifier) + )) + case _ => others.updated(name, TSMemberType(mem, mod.getOrElse(node.modifier))) + } + } - if (name =/= "__constructor" && p.isStatic == requireStatic) { + private def getClassMembersType(list: TSNodeArray, requireStatic: Boolean)(implicit ns: TSNamespace): Map[String, TSMemberType] = + list.foldLeft(Map[String, TSMemberType]())((mp, p) => { + // The constructors have no name identifier. + if (!p.name.isUndefined && p.isStatic == requireStatic) { + val name = p.name.escapedText val mem = if (!p.isStatic) getMemberType(p) else parseMembers(name, p.initializer, true) - - mem match { - case func: TSFunctionType => { - if (!mp.contains(name)) mp ++ Map(name -> TSMemberType(func, p.modifier)) - else { // deal with functions overloading - val old = mp(name) - val res = old.base match { - case f @ TSFunctionType(_, _, tv) => - if (!tv.isEmpty || !func.typeVars.isEmpty) TSIgnoredOverload(func, name) - else if (!p.isImplementationOfOverload) TSIntersectionType(f, func) - else f - case int: TSIntersectionType => - if (!func.typeVars.isEmpty) TSIgnoredOverload(func, name) - else if (!p.isImplementationOfOverload) TSIntersectionType(int, func) - else int - case TSIgnoredOverload(_, name) => TSIgnoredOverload(func, name) // the implementation is always after declarations - case _ => old.base - } - - mp.removed(name) ++ Map(name -> TSMemberType(res, p.modifier)) - } - } - case _ => mp ++ Map(name -> TSMemberType(mem, p.modifier)) - } + addMember(mem, p, name, Option.when[TSAccessModifier](name.startsWith("#"))(Private), mp) } else mp }) - private def getConstructorList(members: TSNodeArray): List[TSParameterType] = + private def getConstructorList(members: TSNodeArray)(implicit ns: TSNamespace): List[TSParameterType] = members.foldLeft(List[TSParameterType]())((lst, mem) => { val name = mem.symbol.escapedName @@ -144,71 +338,82 @@ object TSSourceFile { res :+ TSParameterType(p.symbol.escapedName, getMemberType(p))) }) - private def getInterfacePropertiesType(list: TSNodeArray): Map[String, TSMemberType] = - list.foldLeft(Map[String, TSMemberType]())((mp, p) => mp ++ Map(p.symbol.escapedName -> TSMemberType(getMemberType(p)))) + private def getInterfacePropertiesType(list: TSNodeArray)(implicit ns: TSNamespace): Map[String, TSMemberType] = + list.foldLeft(Map[String, TSMemberType]())((mp, p) => + if (p.isCallSignature) mp else addMember(getMemberType(p), p, p.symbol.escapedName, None, mp)) - private def getAnonymousPropertiesType(list: TSSymbolArray): Map[String, TSMemberType] = + private def getAnonymousPropertiesType(list: TSSymbolArray)(implicit ns: TSNamespace): Map[String, TSMemberType] = list.foldLeft(Map[String, TSMemberType]())((mp, p) => - mp ++ Map(p.escapedName -> TSMemberType(if (p.`type`.isUndefined) getMemberType(p.declaration) else getObjectType(p.`type`)))) + mp.updated(p.escapedName, TSMemberType(if (p.`type`.isUndefined) getMemberType(p.declaration) else getObjectType(p.`type`)))) - private def parseMembers(name: String, node: TSNodeObject, isClass: Boolean): TSType = - if (isClass) - TSClassType(name, getClassMembersType(node.members, false), getClassMembersType(node.members, true), - getTypeParameters(node), getHeritageList(node), getConstructorList(node.members)) - else TSInterfaceType(name, getInterfacePropertiesType(node.members), getTypeParameters(node), getHeritageList(node)) + private def parseMembers(name: String, node: TSNodeObject, isClass: Boolean)(implicit ns: TSNamespace): TSType = { + val res = // Do not handle parents here. we have not had enough information so far. + if (isClass) + TSClassType(name, getClassMembersType(node.members, false), getClassMembersType(node.members, true), + getTypeParameters(node), getHeritageList(node), getConstructorList(node.members)) + else + TSInterfaceType(name, getInterfacePropertiesType(node.members), getTypeParameters(node), + getHeritageList(node), parseCallSignature(node.members)) + if (res.unsupported) markUnsupported(node) else res + } - private def parseNamespaceLocals(map: TSSymbolMap)(implicit ns: TSNamespace) = + private def parseCallSignature(list: TSNodeArray)(implicit ns: TSNamespace) = + list.foldLeft[Option[TSFunctionType]](None)((cs, node) => + if (node.isCallSignature) Some(getFunctionType(node, false)) + else cs + ) + + private def parseNamespaceLocals(map: TSSymbolMap, exports: TSSymbolMap)(implicit ns: TSNamespace) = map.foreach((sym) => { val node = sym.declaration - if (!node.isToken) - addNodeIntoNamespace(node, sym.escapedName, if (node.isFunctionLike) Some(sym.declarations) else None) + val name = sym.escapedName + if (node.isFunctionLike) addFunctionIntoNamespace(sym, node, name) + else if (!node.isToken) + sym.declarations.foreach(dec => + addNodeIntoNamespace(dec, name, exports.contains(name)) + ) }) - private def addFunctionIntoNamespace(fun: TSFunctionType, node: TSNodeObject, name: String)(implicit ns: TSNamespace) = - if (!ns.containsMember(name, false)) ns.put(name, fun) - else { - val old = ns.get(name) - val res = old match { - case f @ TSFunctionType(_, _, tv) => - if (!tv.isEmpty || !fun.typeVars.isEmpty) TSIgnoredOverload(fun, name) - else if (!node.isImplementationOfOverload) TSIntersectionType(f, fun) - else f - case int: TSIntersectionType => - if (!fun.typeVars.isEmpty) TSIgnoredOverload(fun, name) - else if (!node.isImplementationOfOverload) TSIntersectionType(int, fun) - else old - case TSIgnoredOverload(_, name) => TSIgnoredOverload(fun, name) // the implementation is always after declarations - case _ => old - } - - ns.put(name, res) - } + private def addFunctionIntoNamespace(sym: TSSymbolObject, node: TSNodeObject, name: String)(implicit ns: TSNamespace) = + sym.declarations.foreach(d => { + val fun = getFunctionType(d, true) + if (fun.unsupported) ns.put(name, markUnsupported(node), node.isExported, false) + else if (!ns.containsMember(name, false)) ns.put(name, fun, node.isExported, false) + else + ns.put(name, TSIgnoredOverload(fun, name), node.isExported || ns.exported(name), true) // The implementation is always after declarations + }) - // overload functions in a sub-namespace need to provide an overload array + // Overload functions in a sub-namespace need to provide an overload array // because the namespace merely exports symbols rather than node objects themselves - private def addNodeIntoNamespace(node: TSNodeObject, name: String, overload: Option[TSNodeArray] = None)(implicit ns: TSNamespace) = - if (node.isFunctionLike) overload match { - case None => - addFunctionIntoNamespace(getFunctionType(node), node, name) - case Some(decs) => { - decs.foreach((d) => - addFunctionIntoNamespace(getFunctionType(d), d, name) - ) - } - } - else if (node.isClassDeclaration) - ns.put(name, parseMembers(name, node, true)) + private def addNodeIntoNamespace(node: TSNodeObject, name: String, exported: Boolean)(implicit ns: TSNamespace) = + if (node.isClassDeclaration) + ns.put(name, parseMembers(name, node, true), exported, false) else if (node.isInterfaceDeclaration) - ns.put(name, parseMembers(name, node, false)) - else if (node.isTypeAliasDeclaration) - ns.put(name, TSTypeAlias(name, getTypeAlias(node.`type`), getTypeParameters(node))) - else if (node.isObjectLiteral) - ns.put(name, TSInterfaceType("", getObjectLiteralMembers(node.initializer.properties), List(), List())) - else if (node.isVariableDeclaration) - ns.put(name, getMemberType(node)) + ns.put(name, parseMembers(name, node, false), exported, false) + else if (node.isTypeAliasDeclaration) { + val alias = TSTypeAlias(name, getTypeAlias(node.`type`), getTypeParameters(node)) + ns.put(name, if (alias.unsupported) TSTypeAlias(name, markUnsupported(node), Nil) else alias, exported, false) + } + else if (node.isObjectLiteral) { + val obj = TSInterfaceType("", getObjectLiteralMembers(node.initializer.properties), List(), List(), None) + ns.put(name, if (obj.unsupported) markUnsupported(node) else obj, exported, false) + } + else if (node.isVariableDeclaration) ns.put(name, getMemberType(node), exported, false) else if (node.isNamespace) parseNamespace(node) - private def parseNamespace(node: TSNodeObject)(implicit ns: TSNamespace): Unit = - parseNamespaceLocals(node.locals)(ns.derive(node.symbol.escapedName)) + private def parseNamespace(node: TSNodeObject)(implicit ns: TSNamespace): Unit = { + val name = node.symbol.escapedName + if (name.contains("\"")) { // Ambient Modules + val fullname = TypeScript.resolveModuleName(name.substring(1, name.length() - 1), resolvedPath, config) + importList.remove(fullname) + parseNamespaceLocals(node.locals, node.exports) + } + else parseNamespaceLocals(node.locals, node.exports)(ns.derive(name, node.isExported)) + } +} + +object TSSourceFile { + def apply(sf: js.Dynamic, global: TSNamespace, topName: String)(implicit checker: TSTypeChecker, config: js.Dynamic) = + new TSSourceFile(sf, global, topName) } diff --git a/ts2mls/js/src/main/scala/ts2mls/types/Converter.scala b/ts2mls/js/src/main/scala/ts2mls/types/Converter.scala index 8dadf566c..ecb3db857 100644 --- a/ts2mls/js/src/main/scala/ts2mls/types/Converter.scala +++ b/ts2mls/js/src/main/scala/ts2mls/types/Converter.scala @@ -4,67 +4,122 @@ import mlscript.utils._ object Converter { private val primitiveName = Map[String, String]( - "boolean" -> "bool", - "number" -> "number", - "string" -> "string", + "boolean" -> "Bool", + "number" -> "Num", + "string" -> "Str", "any" -> "anything", "unknown" -> "anything", "void" -> "unit", "null" -> "null", "undefined" -> "undefined", "never" -> "nothing", - "object" -> "object", + "object" -> "Object", "true" -> "true", - "false" -> "false" + "false" -> "false", + "symbol" -> "Symbol", + "error" -> "error", + "bigint" -> "Num" ) - def generateFunDeclaration(tsType: TSType, name: String)(implicit indent: String = ""): String = tsType match { + def escapeIdent(name: String) = { + import mlscript.NewLexer + if (NewLexer.keywords(name) || NewLexer.alpahOp(name) || name.contains("$") || + (!name.isEmpty() && name(0) >= '0' && name(0) <= '9')) + s"""id"$name"""" + else name + } + + def genExport(exported: Boolean) = if (exported) "export " else "" + + private def generateFunParamsList(params: List[TSParameterType]) = + if (params.isEmpty) "" + else params.iterator.zipWithIndex.map{ + case (tp, i) => convert(tp)("") + }.reduceLeft((r, p) => s"$r, $p") + + def generateFunDeclaration(tsType: TSType, name: String, exported: Boolean)(implicit indent: String = ""): String = tsType match { case TSFunctionType(params, res, typeVars) => { - val pList = if (params.isEmpty) "" else params.map(p => s"${convert(p)("")}").reduceLeft((r, p) => s"$r, $p") - val tpList = if (typeVars.isEmpty) "" else s"<${typeVars.map(p => convert(p)("")).reduceLeft((r, p) => s"$r, $p")}>" - s"${indent}fun $name$tpList($pList): ${convert(res)("")}" + val pList = generateFunParamsList(params) + val tpList = if (typeVars.isEmpty) "" else s"[${typeVars.map(p => convert(p)("")).reduceLeft((r, p) => s"$r, $p")}]" + s"${indent}${genExport(exported)}declare fun ${escapeIdent(name)}$tpList($pList): ${convert(res)("")}" } - case overload @ TSIgnoredOverload(base, _) => s"${generateFunDeclaration(base, name)} ${overload.warning}" - case inter: TSIntersectionType => s"${indent}fun ${name}: ${Converter.convert(inter)}" + case overload @ TSIgnoredOverload(base, _) => s"${generateFunDeclaration(base, name, exported)} ${overload.warning}" case _ => throw new AssertionError("non-function type is not allowed.") } - def convert(tsType: TSType)(implicit indent: String = ""): String = tsType match { + def convert(tsType: TSType, exported: Boolean = false)(implicit indent: String = ""): String = tsType match { case TSPrimitiveType(typeName) => primitiveName(typeName) case TSReferenceType(name) => name - case TSFunctionType(params, res, _) => - if (params.length == 0) s"${primitiveName("void")} => ${convert(res)}" - else - params.foldRight(convert(res))((p, f) => s"(${convert(p.tp)}) => $f") + case TSFunctionType(params, res, typeVars) => + val tpNames = typeVars.map(_.name) + val tpList = tpNames.foldLeft("")((res, tp) => s"${res}forall '$tp: ") + val pList = generateFunParamsList(params) + s"$tpList($pList) => ${convert(res)}" case TSUnionType(lhs, rhs) => s"(${convert(lhs)}) | (${convert(rhs)})" case TSIntersectionType(lhs, rhs) => s"(${convert(lhs)}) & (${convert(rhs)})" - case TSTypeParameter(name, _) => name // constraints should be translated where the type parameters were created rather than be used - case TSTupleType(lst) => s"[${lst.map(convert).mkString(", ")}]" - case TSArrayType(element) => s"MutArray<${convert(element)}>" - case TSEnumType => "int" + case TSTypeParameter(name, _) => s"'$name" // Constraints should be translated where the type parameters were created rather than be used + case TSTupleType(lst) => s"[${lst.foldLeft("")((p, t) => s"$p${convert(t)}, ")}]" + case TSArrayType(element) => s"MutArray[${convert(element)}]" + case TSEnumType => "Int" case TSMemberType(base, _) => convert(base) // TODO: support private/protected members - case TSInterfaceType(name, members, typeVars, parents) => - convertRecord(s"trait $name", members, typeVars, parents, Map(), List())(indent) - case TSClassType(name, members, statics, typeVars, parents, cons) => - convertRecord(s"class $name", members, typeVars, parents, statics, cons)(indent) - case TSSubstitutionType(base, applied) => s"${base}<${applied.map((app) => convert(app)).reduceLeft((res, s) => s"$res, $s")}>" + case itf: TSInterfaceType => + if (itf.name.isEmpty()) convertRecord(itf.members, Nil, Nil, Map(), Nil, true) // Anonymous interfaces + else convertClassOrInterface(Right(itf), exported) + case cls: TSClassType => + convertClassOrInterface(Left(cls), exported) + case TSSubstitutionType(TSReferenceType(base), applied) => s"${base}[${applied.map((app) => convert(app)).reduceLeft((res, s) => s"$res, $s")}]" case overload @ TSIgnoredOverload(base, _) => s"${convert(base)} ${overload.warning}" - case TSParameterType(name, tp) => s"${name}: ${convert(tp)}" - case TSTypeAlias(name, ori, tp) => - if (tp.isEmpty) s"${indent}type $name = ${convert(ori)}" - else s"${indent}type $name<${tp.map(t => convert(t)).reduceLeft((s, t) => s"$s, $t")}> = ${convert(ori)}" + case TSParameterType(name, tp) => s"${escapeIdent(name)}: ${convert(tp)}" + case TSTypeAlias(name, ori, tp) => { + if (tp.isEmpty) s"${indent}${genExport(exported)}type ${escapeIdent(name)} = ${convert(ori)}" + else s"${indent}${genExport(exported)}type ${escapeIdent(name)}[${tp.map(t => convert(t)).reduceLeft((s, t) => s"$s, $t")}] = ${convert(ori)}" + } case TSLiteralType(value, isString) => if (isString) s"\"$value\"" else value + case TSUnsupportedType(code, filename, line, column) => + s"""unsupported["$code", "$filename", $line, $column]""" + case tp => throw new AssertionError(s"unexpected type $tp.") } - private def convertRecord(typeName: String, members: Map[String, TSMemberType], typeVars: List[TSTypeParameter], - parents: List[TSType], statics: Map[String, TSMemberType], constructorList: List[TSType])(implicit indent: String) = { + private def convertClassOrInterface(tp: Either[TSClassType, TSInterfaceType], exported: Boolean)(implicit indent: String) = { + val exp = genExport(exported) + def convertParents(parents: List[TSType]) = + if (parents.isEmpty) "" + else parents.foldLeft(s" extends ")((b, p) => s"$b${convert(p)}, ").dropRight(2) + def combineWithTypeVars(body: String, parents: List[TSType], typeName: String, typeVars: List[TSTypeParameter]) = { + val inheritance = convertParents(parents) + if (typeVars.isEmpty) s"${indent}${exp}declare $typeName$inheritance $body" + else + s"${indent}${exp}declare $typeName[${typeVars.map(convert(_)).reduceLeft((p, s) => s"$p, $s")}]$inheritance $body" // TODO: add constraints + } + tp match { + case Left(TSClassType(name, members, statics, typeVars, parents, cons)) => + val body = convertRecord(members, typeVars, parents, statics, cons, false) + val typeName = s"class ${escapeIdent(name)}" + combineWithTypeVars(body, parents, typeName, typeVars) + case Right(TSInterfaceType(name, members, typeVars, parents, callSignature)) => + callSignature match { + case Some(cs) => + val prefix = s"${indent}${exp}declare " + val inheritance = convertParents(parents) + val tp = if (typeVars.isEmpty) "" else s"[${typeVars.map((tv) => tv.name).reduceLeft((p, s) => s"$p, $s")}]" + s"${prefix}trait ${escapeIdent(name)}$tp: (${convert(cs)})$inheritance ${convertRecord(members, Nil, Nil, Map(), List(), false)}" + case _ => + val body = convertRecord(members, typeVars, parents, Map(), List(), false) + val typeName = s"trait ${escapeIdent(name)}" + combineWithTypeVars(body, parents, typeName, typeVars) + } + } + } + + private def convertRecord(members: Map[String, TSMemberType], typeVars: List[TSTypeParameter], parents: List[TSType], + statics: Map[String, TSMemberType], constructorList: List[TSType], anonymous: Boolean)(implicit indent: String) = { val allRecs = members.toList.map((m) => m._2.modifier match { case Public => - if (typeName === "trait ") s"${m._1}: ${convert(m._2)}," + if (anonymous) s"${escapeIdent(m._1)}: ${convert(m._2)}," else m._2.base match { - case _: TSFunctionType => s"${generateFunDeclaration(m._2.base, m._1)(indent + " ")}\n" - case _: TSIgnoredOverload => s"${generateFunDeclaration(m._2.base, m._1)(indent + " ")}\n" - case _ => s"${indent} let ${m._1}: ${convert(m._2)}\n" + case _: TSFunctionType => s"${generateFunDeclaration(m._2.base, m._1, false)(indent + " ")}\n" + case _: TSIgnoredOverload => s"${generateFunDeclaration(m._2.base, m._1, false)(indent + " ")}\n" + case _ => s"${indent} val ${escapeIdent(m._1)}: ${convert(m._2)}\n" } case _ => "" // TODO: deal with private/protected members }) ::: @@ -76,25 +131,14 @@ object Converter { case _ => "" // TODO: deal with private/protected static members }) - val body = { // members without independent type parameters, translate them directly - val lst = allRecs.filter((s) => !s.isEmpty()) - if (lst.isEmpty) "{}" - else if (typeName === "trait ") s"{${lst.reduceLeft((bd, m) => s"$bd$m")}}" - else s"{\n${lst.reduceLeft((bd, m) => s"$bd$m")}$indent}" - } - - if (typeName === "trait ") body // anonymous interfaces - else { // named interfaces and classes - val constructor = - if (constructorList.isEmpty) "()" - else s"(${constructorList.map(p => s"${convert(p)("")}").reduceLeft((res, p) => s"$res, $p")})" - - val inheritance = - if (parents.isEmpty) constructor - else parents.foldLeft(s"$constructor: ")((b, p) => s"$b${convert(p)}, ").dropRight(2) - if (typeVars.isEmpty) s"${indent}$typeName$inheritance $body" + val ctor = + if (constructorList.isEmpty) "" else - s"${indent}$typeName<${typeVars.map((tv) => tv.name).reduceLeft((p, s) => s"$p, $s")}>$inheritance $body" // TODO: add constraints - } + s"${indent} constructor(${constructorList.map(p => s"${convert(p)("")}").reduceLeft((res, p) => s"$res, $p")})\n" + + val lst = (ctor :: allRecs).filter((s) => !s.isEmpty()) + if (lst.isEmpty) s"{}" + else if (anonymous) s"{${lst.reduceLeft((bd, m) => s"$bd$m")}}" + else s"{\n${lst.reduceLeft((bd, m) => s"$bd$m")}$indent}" } } diff --git a/ts2mls/js/src/main/scala/ts2mls/types/TSType.scala b/ts2mls/js/src/main/scala/ts2mls/types/TSType.scala index ce0527db8..5dddaac5f 100644 --- a/ts2mls/js/src/main/scala/ts2mls/types/TSType.scala +++ b/ts2mls/js/src/main/scala/ts2mls/types/TSType.scala @@ -5,44 +5,103 @@ case object Public extends TSAccessModifier case object Private extends TSAccessModifier case object Protected extends TSAccessModifier -sealed abstract class TSType -case class TSParameterType(name: String, val tp: TSType) extends TSType // record both parameter's name and parameter's type -case class TSMemberType(val base: TSType, val modifier: TSAccessModifier = Public) extends TSType -case class TSTypeParameter(val name: String, constraint: Option[TSType] = None) extends TSType +sealed abstract class TSType { + val unsupported = false +} + +// Record both parameter's name and parameter's type +case class TSParameterType(name: String, tp: TSType) extends TSType { + override val unsupported: Boolean = tp.unsupported +} +case class TSMemberType(base: TSType, modifier: TSAccessModifier = Public) extends TSType { + override val unsupported: Boolean = base.unsupported +} + +case class TSTypeParameter(name: String, constraint: Option[TSType] = None) extends TSType { + override val unsupported: Boolean = constraint.fold(false)(c => c.unsupported) +} + case class TSPrimitiveType(typeName: String) extends TSType -case class TSReferenceType(name: String) extends TSType +case class TSReferenceType(name: String) extends TSType { + val nameList = if (name.contains(".")) name.split("\\.").toList else name :: Nil +} case object TSEnumType extends TSType -case class TSTupleType(types: List[TSType]) extends TSType -case class TSFunctionType(params: List[TSParameterType], res: TSType, val typeVars: List[TSTypeParameter]) extends TSType -case class TSArrayType(eleType: TSType) extends TSType -case class TSSubstitutionType(base: String, applied: List[TSType]) extends TSType +case class TSTupleType(types: List[TSType]) extends TSType { + override val unsupported: Boolean = types.foldLeft(false)((r, t) => r || t.unsupported) +} + +case class TSFunctionType(params: List[TSParameterType], res: TSType, typeVars: List[TSTypeParameter]) extends TSType { + override val unsupported: Boolean = + res.unsupported || params.foldLeft(false)((r, t) => r || t.unsupported) || + typeVars.foldLeft(false)((r, t) => r || t.unsupported) +} + +case class TSArrayType(eleType: TSType) extends TSType { + override val unsupported: Boolean = eleType.unsupported +} +case class TSSubstitutionType(base: TSReferenceType, applied: List[TSType]) extends TSType { + override val unsupported: Boolean = base.unsupported || applied.foldLeft(false)((r, t) => r || t.unsupported) +} case class TSClassType( - name: String, - members: Map[String, TSMemberType], - statics: Map[String, TSMemberType], - typeVars: List[TSTypeParameter], - parents: List[TSType], - constructor: List[TSParameterType] - ) extends TSType + name: String, + members: Map[String, TSMemberType], + statics: Map[String, TSMemberType], + typeVars: List[TSTypeParameter], + parents: List[TSType], + constructor: List[TSParameterType] +) extends TSType { + override val unsupported: Boolean = + typeVars.foldLeft(false)((r, t) => r || t.unsupported) || parents.foldLeft(false)((r, t) => t match { + case cls: TSClassType => cls.members.values.foldLeft(r || cls.unsupported)((r, t) => r || t.unsupported) + case itf: TSInterfaceType => itf.members.values.foldLeft(r || itf.unsupported)((r, t) => r || t.unsupported) + case _ => r || t.unsupported + }) +} case class TSInterfaceType( - name: String, - members: Map[String, TSMemberType], - typeVars: List[TSTypeParameter], - parents: List[TSType], - ) extends TSType + name: String, + members: Map[String, TSMemberType], + typeVars: List[TSTypeParameter], + parents: List[TSType], + callSignature: Option[TSFunctionType] +) extends TSType { + override val unsupported: Boolean = + typeVars.foldLeft(callSignature.fold(false)(cs => cs.unsupported))((r, t) => r || t.unsupported) || + parents.foldLeft(false)((r, t) => t match { + case cls: TSClassType => cls.members.values.foldLeft(r || cls.unsupported)((r, t) => r || t.unsupported) + case itf: TSInterfaceType => itf.members.values.foldLeft(r || itf.unsupported)((r, t) => r || t.unsupported) + case _ => r || t.unsupported + }) +} -sealed abstract class TSStructuralType(lhs: TSType, rhs: TSType, notion: String) extends TSType +sealed abstract class TSStructuralType(lhs: TSType, rhs: TSType, notion: String) extends TSType { + override val unsupported: Boolean = lhs.unsupported || rhs.unsupported +} case class TSUnionType(lhs: TSType, rhs: TSType) extends TSStructuralType(lhs, rhs, "|") case class TSIntersectionType(lhs: TSType, rhs: TSType) extends TSStructuralType(lhs, rhs, "&") -// ts2mls doesn't support overloading functions with type parameters -// TSIgnoredOverload is used to store these functions and raise a warning later -// only the most general overloading form would be stored +// `ts2mls` doesn't support overloading functions with type parameters. +// TSIgnoredOverload is used to store these functions and raise a warning later. +// Only the most general overloading form would be stored case class TSIgnoredOverload(base: TSFunctionType, name: String) extends TSType { val warning = s"/* warning: the overload of function $name is not supported yet. */" + override val unsupported: Boolean = base.unsupported } -case class TSTypeAlias(name: String, original: TSType, tp: List[TSType]) extends TSType +// Generate type name = ... in mlscript +case class TSTypeAlias(name: String, original: TSType, tp: List[TSType]) extends TSType { + override val unsupported: Boolean = + original.unsupported || tp.foldLeft(false)((r, t) => r || t.unsupported) +} +// Generate val name = ... in mlscript +case class TSRenamedType(name: String, original: TSType) extends TSType { + override val unsupported: Boolean = original.unsupported +} case class TSLiteralType(value: String, isString: Boolean) extends TSType +case class TSUnsupportedType(code: String, filename: String, line: String, column: String) extends TSType { + override val unsupported: Boolean = true +} +object TSNoInfoUnsupported extends TSType { // Unsupported type without code and location information + override val unsupported: Boolean = true +} diff --git a/ts2mls/js/src/test/diff/Array.d.mls b/ts2mls/js/src/test/diff/Array.d.mls deleted file mode 100644 index a6a43ee80..000000000 --- a/ts2mls/js/src/test/diff/Array.d.mls +++ /dev/null @@ -1,24 +0,0 @@ -:NewDefs -:ParseOnly -fun first(x: MutArray): string -fun getZero3(): MutArray -fun first2(fs: MutArray<(number) => number>): (number) => number -fun doEs(e: MutArray): MutArray -class C() {} -trait I() { - let i: number -} -fun doCs(c: MutArray): MutArray -fun doIs(i: MutArray): MutArray -fun inter(x: MutArray<(U) & (T)>): MutArray<(U) & (T)> -fun clean(x: MutArray<[string, number]>): MutArray<[string, number]> -fun translate(x: MutArray): MutArray -fun uu(x: MutArray<((number) | (false)) | (true)>): MutArray<((number) | (false)) | (true)> -class Temp() { - let x: T -} -fun ta(ts: MutArray>): MutArray> -fun tat(ts: MutArray>): MutArray> -//│ |#fun| |first|(|x|#:| |MutArray|‹|string|›|)|#:| |string|↵|#fun| |getZero3|(||)|#:| |MutArray|‹|number|›|↵|#fun| |first2|(|fs|#:| |MutArray|‹|(|number|)| |#=>| |number|›|)|#:| |(|number|)| |#=>| |number|↵|#fun| |doEs|(|e|#:| |MutArray|‹|int|›|)|#:| |MutArray|‹|int|›|↵|#class| |C|(||)| |{||}|↵|#trait| |I|(||)| |{|→|#let| |i|#:| |number|←|↵|}|↵|#fun| |doCs|(|c|#:| |MutArray|‹|C|›|)|#:| |MutArray|‹|C|›|↵|#fun| |doIs|(|i|#:| |MutArray|‹|I|›|)|#:| |MutArray|‹|I|›|↵|#fun| |inter|‹|U|,| |T|›|(|x|#:| |MutArray|‹|(|U|)| |&| |(|T|)|›|)|#:| |MutArray|‹|(|U|)| |&| |(|T|)|›|↵|#fun| |clean|(|x|#:| |MutArray|‹|[|string|,| |number|]|›|)|#:| |MutArray|‹|[|string|,| |number|]|›|↵|#fun| |translate|‹|T|,| |U|›|(|x|#:| |MutArray|‹|T|›|)|#:| |MutArray|‹|U|›|↵|#fun| |uu|(|x|#:| |MutArray|‹|(|(|number|)| ||| |(|false|)|)| ||| |(|true|)|›|)|#:| |MutArray|‹|(|(|number|)| ||| |(|false|)|)| ||| |(|true|)|›|↵|#class| |Temp|‹|T|›|(||)| |{|→|#let| |x|#:| |T|←|↵|}|↵|#fun| |ta|(|ts|#:| |MutArray|‹|Temp|‹|(|false|)| ||| |(|true|)|›|›|)|#:| |MutArray|‹|Temp|‹|(|false|)| ||| |(|true|)|›|›|↵|#fun| |tat|‹|T|›|(|ts|#:| |MutArray|‹|Temp|‹|T|›|›|)|#:| |MutArray|‹|Temp|‹|T|›|›| -//│ Parsed: {fun first: (x: MutArray[string]) -> string; fun getZero3: () -> MutArray[number]; fun first2: (fs: MutArray[number -> number]) -> number -> number; fun doEs: (e: MutArray[int]) -> MutArray[int]; class C() {}; trait I() {let i: number}; fun doCs: (c: MutArray[C]) -> MutArray[C]; fun doIs: (i: MutArray[I]) -> MutArray[I]; fun inter: (x: MutArray[U & T]) -> MutArray[U & T]; fun clean: (x: MutArray[[string, number]]) -> MutArray[[string, number]]; fun translate: (x: MutArray[T]) -> MutArray[U]; fun uu: (x: MutArray[number | false | true]) -> MutArray[number | false | true]; class Temp‹T›() {let x: T}; fun ta: (ts: MutArray[Temp[bool]]) -> MutArray[Temp[bool]]; fun tat: (ts: MutArray[Temp[T]]) -> MutArray[Temp[T]]} -//│ diff --git a/ts2mls/js/src/test/diff/BasicFunctions.d.mls b/ts2mls/js/src/test/diff/BasicFunctions.d.mls deleted file mode 100644 index 00356e3ad..000000000 --- a/ts2mls/js/src/test/diff/BasicFunctions.d.mls +++ /dev/null @@ -1,29 +0,0 @@ -:NewDefs -:ParseOnly -fun hello(): unit -fun add(x: number, y: number): number -fun sub(x: number, y: number): number -fun foo(): number -fun id(x: anything): anything -fun odd(x: number): (false) | (true) -fun isnull(x: anything): (false) | (true) -fun bar(): anything -fun nu(n: null): null -fun un(n: undefined): undefined -fun fail(): nothing -fun create(): object -fun pa(x: number): number -fun wtf(x: anything): unit -class Foooooo() { - let ooooooo: number -} -fun inn(f: Foooooo): unit -fun out1(): Foooooo -trait Barrrrrrrrr() { - let rrrrrrr: number -} -fun inn2(b: Barrrrrrrrr): unit -fun out2(): Barrrrrrrrr -//│ |#fun| |hello|(||)|#:| |unit|↵|#fun| |add|(|x|#:| |number|,| |y|#:| |number|)|#:| |number|↵|#fun| |sub|(|x|#:| |number|,| |y|#:| |number|)|#:| |number|↵|#fun| |foo|(||)|#:| |number|↵|#fun| |id|(|x|#:| |anything|)|#:| |anything|↵|#fun| |odd|(|x|#:| |number|)|#:| |(|false|)| ||| |(|true|)|↵|#fun| |isnull|(|x|#:| |anything|)|#:| |(|false|)| ||| |(|true|)|↵|#fun| |bar|(||)|#:| |anything|↵|#fun| |nu|(|n|#:| |#null|)|#:| |#null|↵|#fun| |un|(|n|#:| |#undefined|)|#:| |#undefined|↵|#fun| |fail|(||)|#:| |nothing|↵|#fun| |create|(||)|#:| |object|↵|#fun| |pa|(|x|#:| |number|)|#:| |number|↵|#fun| |wtf|(|x|#:| |anything|)|#:| |unit|↵|#class| |Foooooo|(||)| |{|→|#let| |ooooooo|#:| |number|←|↵|}|↵|#fun| |inn|(|f|#:| |Foooooo|)|#:| |unit|↵|#fun| |out1|(||)|#:| |Foooooo|↵|#trait| |Barrrrrrrrr|(||)| |{|→|#let| |rrrrrrr|#:| |number|←|↵|}|↵|#fun| |inn2|(|b|#:| |Barrrrrrrrr|)|#:| |unit|↵|#fun| |out2|(||)|#:| |Barrrrrrrrr| -//│ Parsed: {fun hello: () -> unit; fun add: (x: number, y: number) -> number; fun sub: (x: number, y: number) -> number; fun foo: () -> number; fun id: (x: anything) -> anything; fun odd: (x: number) -> bool; fun isnull: (x: anything) -> bool; fun bar: () -> anything; fun nu: (n: null) -> null; fun un: (n: ()) -> (); fun fail: () -> nothing; fun create: () -> object; fun pa: (x: number) -> number; fun wtf: (x: anything) -> unit; class Foooooo() {let ooooooo: number}; fun inn: (f: Foooooo) -> unit; fun out1: () -> Foooooo; trait Barrrrrrrrr() {let rrrrrrr: number}; fun inn2: (b: Barrrrrrrrr) -> unit; fun out2: () -> Barrrrrrrrr} -//│ diff --git a/ts2mls/js/src/test/diff/BasicFunctions.mlsi b/ts2mls/js/src/test/diff/BasicFunctions.mlsi new file mode 100644 index 000000000..5dd9cfaa6 --- /dev/null +++ b/ts2mls/js/src/test/diff/BasicFunctions.mlsi @@ -0,0 +1,38 @@ +export declare module BasicFunctions { + declare fun hello(): unit + declare fun add(x: Num, y: Num): Num + declare fun sub(x: Num, y: Num): Num + declare fun foo(): Num + declare fun id(x: anything): anything + declare fun odd(x: Num): (false) | (true) + declare fun isnull(x: anything): (false) | (true) + declare fun bar(): anything + declare fun nu(n: null): null + declare fun un(n: undefined): undefined + declare fun fail(): nothing + declare fun create(): Object + declare fun pa(x: Num): Num + declare fun wtf(x: anything): unit + declare class Foooooo { + val ooooooo: Num + } + declare fun inn(f: Foooooo): unit + declare fun out1(): Foooooo + declare trait Barrrrrrrrr { + val rrrrrrr: Num + } + declare fun inn2(b: Barrrrrrrrr): unit + declare fun out2(): Barrrrrrrrr +} +//| ╔══[ERROR] type identifier not found: Foooooo +//| ║ l.19: declare fun inn(f: Foooooo): unit +//| ╙── ^^^^^^^ +//| ╔══[ERROR] type identifier not found: Foooooo +//| ║ l.20: declare fun out1(): Foooooo +//| ╙── ^^^^^^^ +//| ╔══[ERROR] type identifier not found: Barrrrrrrrr +//| ║ l.24: declare fun inn2(b: Barrrrrrrrr): unit +//| ╙── ^^^^^^^^^^^ +//| ╔══[ERROR] type identifier not found: Barrrrrrrrr +//| ║ l.25: declare fun out2(): Barrrrrrrrr +//| ╙── ^^^^^^^^^^^ diff --git a/ts2mls/js/src/test/diff/ClassMember.d.mls b/ts2mls/js/src/test/diff/ClassMember.d.mls deleted file mode 100644 index 03848dcb2..000000000 --- a/ts2mls/js/src/test/diff/ClassMember.d.mls +++ /dev/null @@ -1,26 +0,0 @@ -:NewDefs -:ParseOnly -class Student(s: string, age: number) { - let name: string - fun isFriend(other: Student): (false) | (true) - fun addScore(sub: string, score: number): unit - fun getID(): number -} -class Foo() { - fun bar(x: T): unit -} -class EZ() { - fun inc(x: number): number -} -class Outer() { - class Inner() { - let a: number - } -} -class TTT() { - fun ttt(x: T): T - fun ttt2(x: T): T -} -//│ |#class| |Student|(|s|#:| |string|,| |age|#:| |number|)| |{|→|#let| |name|#:| |string|↵|#fun| |isFriend|(|other|#:| |Student|)|#:| |(|false|)| ||| |(|true|)|↵|#fun| |addScore|(|sub|#:| |string|,| |score|#:| |number|)|#:| |unit|↵|#fun| |getID|(||)|#:| |number|←|↵|}|↵|#class| |Foo|‹|T|›|(||)| |{|→|#fun| |bar|(|x|#:| |T|)|#:| |unit|←|↵|}|↵|#class| |EZ|(||)| |{|→|#fun| |inc|(|x|#:| |number|)|#:| |number|←|↵|}|↵|#class| |Outer|(||)| |{|→|#class| |Inner|(||)| |{|→|#let| |a|#:| |number|←|↵|}|←|↵|}|↵|#class| |TTT|‹|T|›|(||)| |{|→|#fun| |ttt|(|x|#:| |T|)|#:| |T|↵|#fun| |ttt2|(|x|#:| |T|)|#:| |T|←|↵|}| -//│ Parsed: {class Student(s: string, age: number,) {let name: string; fun isFriend: (other: Student) -> bool; fun addScore: (sub: string, score: number) -> unit; fun getID: () -> number}; class Foo‹T›() {fun bar: (x: T) -> unit}; class EZ() {fun inc: (x: number) -> number}; class Outer() {class Inner() {let a: number}}; class TTT‹T›() {fun ttt: (x: T) -> T; fun ttt2: (x: T) -> T}} -//│ diff --git a/ts2mls/js/src/test/diff/ClassMember.mlsi b/ts2mls/js/src/test/diff/ClassMember.mlsi new file mode 100644 index 000000000..987adcd7f --- /dev/null +++ b/ts2mls/js/src/test/diff/ClassMember.mlsi @@ -0,0 +1,24 @@ +export declare module ClassMember { + declare class Student { + constructor(s: Str, age: Num) + val name: Str + declare fun isFriend(args0: Student): (false) | (true) + declare fun addScore(args0: Str, args1: Num): unit + declare fun getID(): Num + } + declare class Foo['T] { + declare fun bar(args0: 'T): unit + } + declare class EZ { + declare fun inc(args0: Num): Num + } + declare class Outer { + declare class Inner { + val a: Num + } + } + declare class TTT['T] { + declare fun ttt(args0: 'T): 'T + declare fun ttt2(x: 'T): 'T + } +} diff --git a/ts2mls/js/src/test/diff/Cycle1.mlsi b/ts2mls/js/src/test/diff/Cycle1.mlsi new file mode 100644 index 000000000..a81e08619 --- /dev/null +++ b/ts2mls/js/src/test/diff/Cycle1.mlsi @@ -0,0 +1,5 @@ +import "./Cycle2.mlsi" +export declare module Cycle1 { + export declare class A {} + val b: Cycle2.B +} diff --git a/ts2mls/js/src/test/diff/Cycle2.mlsi b/ts2mls/js/src/test/diff/Cycle2.mlsi new file mode 100644 index 000000000..bb3e4ebe2 --- /dev/null +++ b/ts2mls/js/src/test/diff/Cycle2.mlsi @@ -0,0 +1,11 @@ +declare module Cycle1 { + export declare class A {} + val b: Cycle2.B +} +export declare module Cycle2 { + export declare class B {} + val a: Cycle1.A +} +//| ╔══[ERROR] Module `Cycle1` has a cyclic type dependency that is not supported yet. +//| ║ l.7: val a: Cycle1.A +//| ╙── ^^ diff --git a/ts2mls/js/src/test/diff/Dec.d.mls b/ts2mls/js/src/test/diff/Dec.d.mls deleted file mode 100644 index 6ad560cd7..000000000 --- a/ts2mls/js/src/test/diff/Dec.d.mls +++ /dev/null @@ -1,15 +0,0 @@ -:NewDefs -:ParseOnly -fun getName(id: (string) | (number)): string -fun render(callback: (unit => unit) | (undefined)): string -trait Get() { - fun __call(id: string): string -} -class Person(name: string, age: number) { - fun getName(id: number): string -} -module OOO { -} -//│ |#fun| |getName|(|id|#:| |(|string|)| ||| |(|number|)|)|#:| |string|↵|#fun| |render|(|callback|#:| |(|unit| |#=>| |unit|)| ||| |(|#undefined|)|)|#:| |string|↵|#trait| |Get|(||)| |{|→|#fun| |__call|(|id|#:| |string|)|#:| |string|←|↵|}|↵|#class| |Person|(|name|#:| |string|,| |age|#:| |number|)| |{|→|#fun| |getName|(|id|#:| |number|)|#:| |string|←|↵|}|↵|#module| |OOO| |{|↵|}| -//│ Parsed: {fun getName: (id: string | number) -> string; fun render: (callback: unit -> unit | ()) -> string; trait Get() {fun __call: (id: string) -> string}; class Person(name: string, age: number,) {fun getName: (id: number) -> string}; module OOO {}} -//│ diff --git a/ts2mls/js/src/test/diff/Dec.mlsi b/ts2mls/js/src/test/diff/Dec.mlsi new file mode 100644 index 000000000..6caa6d1c7 --- /dev/null +++ b/ts2mls/js/src/test/diff/Dec.mlsi @@ -0,0 +1,11 @@ +export declare module Dec { + declare fun getName(id: (Str) | (Num)): Str + declare fun render(callback: (() => unit) | (undefined)): Str + declare trait Get: ((args0: Str) => Str) {} + declare class Person { + constructor(name: Str, age: Num) + declare fun getName(args0: Num): Str + } + declare module OOO { + } +} diff --git a/ts2mls/js/src/test/diff/Dependency.mlsi b/ts2mls/js/src/test/diff/Dependency.mlsi new file mode 100644 index 000000000..65d282d5c --- /dev/null +++ b/ts2mls/js/src/test/diff/Dependency.mlsi @@ -0,0 +1,15 @@ +export declare module Dependency { + export declare class A { + val a: Num + } + export declare class B { + val b: Num + } + export declare class C { + val c: Num + } + export declare class D { + val d: Num + } + declare fun default(): Num +} diff --git a/ts2mls/js/src/test/diff/Enum.d.mls b/ts2mls/js/src/test/diff/Enum.d.mls deleted file mode 100644 index 75e68ab29..000000000 --- a/ts2mls/js/src/test/diff/Enum.d.mls +++ /dev/null @@ -1,8 +0,0 @@ -:NewDefs -:ParseOnly -fun pass(c: int): (false) | (true) -fun stop(): int -fun g(x: int): int -//│ |#fun| |pass|(|c|#:| |int|)|#:| |(|false|)| ||| |(|true|)|↵|#fun| |stop|(||)|#:| |int|↵|#fun| |g|(|x|#:| |int|)|#:| |int| -//│ Parsed: {fun pass: (c: int) -> bool; fun stop: () -> int; fun g: (x: int) -> int} -//│ diff --git a/ts2mls/js/src/test/diff/Enum.mlsi b/ts2mls/js/src/test/diff/Enum.mlsi new file mode 100644 index 000000000..f72b28baf --- /dev/null +++ b/ts2mls/js/src/test/diff/Enum.mlsi @@ -0,0 +1,5 @@ +export declare module Enum { + declare fun pass(c: Int): (false) | (true) + declare fun stop(): Int + declare fun g(x: Int): Int +} diff --git a/ts2mls/js/src/test/diff/Escape.mlsi b/ts2mls/js/src/test/diff/Escape.mlsi new file mode 100644 index 000000000..5e64e9e35 --- /dev/null +++ b/ts2mls/js/src/test/diff/Escape.mlsi @@ -0,0 +1,14 @@ +export declare module Escape { + declare class id"fun" { + val id"rec": Num + } + declare trait id"rec" { + val id"fun": Str + } + declare fun id"mixin"(id"module": Str): unit + val id"forall": Num + declare module id"trait" { + declare module id"of" { + } + } +} diff --git a/ts2mls/js/src/test/diff/Export.mlsi b/ts2mls/js/src/test/diff/Export.mlsi new file mode 100644 index 000000000..2626e153a --- /dev/null +++ b/ts2mls/js/src/test/diff/Export.mlsi @@ -0,0 +1,30 @@ +import "./Dependency.mlsi" +export declare module Export { + export declare module Foo { + export declare fun Baz(aa: Str): IBar + declare trait IBar { + val a: Str + } + export declare class Bar extends IBar { + val a: Str + } + export val baz: IBar + } + declare fun default(x: anything): anything + export declare class E {} + export val F = E + export val G = Dependency.B + export val H = Dependency +} +//| ╔══[ERROR] type identifier not found: IBar +//| ║ l.4: export declare fun Baz(aa: Str): IBar +//| ╙── ^^^^ +//| ╔══[ERROR] type identifier not found: IBar +//| ║ l.11: export val baz: IBar +//| ╙── ^^^^ +//| ╔══[ERROR] Class E cannot be instantiated as it exposes no constructor +//| ║ l.15: export val F = E +//| ╙── ^ +//| ╔══[ERROR] Access to class member not yet supported +//| ║ l.16: export val G = Dependency.B +//| ╙── ^^ diff --git a/ts2mls/js/src/test/diff/Heritage.d.mls b/ts2mls/js/src/test/diff/Heritage.d.mls deleted file mode 100644 index bc5d879a1..000000000 --- a/ts2mls/js/src/test/diff/Heritage.d.mls +++ /dev/null @@ -1,45 +0,0 @@ -:NewDefs -:ParseOnly -class A() { - fun foo(): unit -} -class B(): A {} -class C() { - fun set(x: T): unit - fun get(): T -} -class D(): C {} -trait Wu() { - let x: (false) | (true) -} -class WuWu(): Wu { - let y: (false) | (true) -} -trait WuWuWu(): WuWu { - let z: (false) | (true) -} -trait Never(): WuWuWu { - fun w(): nothing -} -class VG() { - let x: T -} -class Home(): VG { - let y: T -} -trait O() { - fun xx(x: I): I -} -class OR(): O { - fun xx(x: R): R -} -module Five { - class ROTK() { - let wu: string - } - class Y(): Five.ROTK {} -} -class Y(): Five.ROTK {} -//│ |#class| |A|(||)| |{|→|#fun| |foo|(||)|#:| |unit|←|↵|}|↵|#class| |B|(||)|#:| |A| |{||}|↵|#class| |C|‹|T|›|(||)| |{|→|#fun| |set|(|x|#:| |T|)|#:| |unit|↵|#fun| |get|(||)|#:| |T|←|↵|}|↵|#class| |D|(||)|#:| |C|‹|number|›| |{||}|↵|#trait| |Wu|(||)| |{|→|#let| |x|#:| |(|false|)| ||| |(|true|)|←|↵|}|↵|#class| |WuWu|(||)|#:| |Wu| |{|→|#let| |y|#:| |(|false|)| ||| |(|true|)|←|↵|}|↵|#trait| |WuWuWu|(||)|#:| |WuWu| |{|→|#let| |z|#:| |(|false|)| ||| |(|true|)|←|↵|}|↵|#trait| |Never|(||)|#:| |WuWuWu| |{|→|#fun| |w|(||)|#:| |nothing|←|↵|}|↵|#class| |VG|‹|T|›|(||)| |{|→|#let| |x|#:| |T|←|↵|}|↵|#class| |Home|‹|T|›|(||)|#:| |VG|‹|string|›| |{|→|#let| |y|#:| |T|←|↵|}|↵|#trait| |O|‹|I|›|(||)| |{|→|#fun| |xx|(|x|#:| |I|)|#:| |I|←|↵|}|↵|#class| |OR|‹|R|›|(||)|#:| |O|‹|R|›| |{|→|#fun| |xx|(|x|#:| |R|)|#:| |R|←|↵|}|↵|#module| |Five| |{|→|#class| |ROTK|(||)| |{|→|#let| |wu|#:| |string|←|↵|}|↵|#class| |Y|(||)|#:| |Five|.ROTK| |{||}|←|↵|}|↵|#class| |Y|(||)|#:| |Five|.ROTK| |{||}| -//│ Parsed: {class A() {fun foo: () -> unit}; class B(): A {}; class C‹T›() {fun set: (x: T) -> unit; fun get: () -> T}; class D(): C[number] {}; trait Wu() {let x: bool}; class WuWu(): Wu {let y: bool}; trait WuWuWu(): WuWu {let z: bool}; trait Never(): WuWuWu {fun w: () -> nothing}; class VG‹T›() {let x: T}; class Home‹T›(): VG[string] {let y: T}; trait O‹I›() {fun xx: (x: I) -> I}; class OR‹R›(): O[R] {fun xx: (x: R) -> R}; module Five {class ROTK() {let wu: string}; class Y(): Five.ROTK {}}; class Y(): Five.ROTK {}} -//│ diff --git a/ts2mls/js/src/test/diff/Heritage.mlsi b/ts2mls/js/src/test/diff/Heritage.mlsi new file mode 100644 index 000000000..39481956e --- /dev/null +++ b/ts2mls/js/src/test/diff/Heritage.mlsi @@ -0,0 +1,11 @@ +export declare module Heritage { + declare module Five { + export declare class ROTK { + val wu: Str + } + } + declare class Y extends Five.ROTK {} +} +//| ╔══[ERROR] Unsupported parent specification +//| ║ l.7: declare class Y extends Five.ROTK {} +//| ╙── ^^^^^^^^^ diff --git a/ts2mls/js/src/test/diff/HighOrderFunc.d.mls b/ts2mls/js/src/test/diff/HighOrderFunc.d.mls deleted file mode 100644 index e497bae1d..000000000 --- a/ts2mls/js/src/test/diff/HighOrderFunc.d.mls +++ /dev/null @@ -1,8 +0,0 @@ -:NewDefs -:ParseOnly -fun h1(inc: (number) => number, num: number): number -fun h2(hint: string): unit => string -fun h3(f: (number) => number, g: (number) => number): (number) => number -//│ |#fun| |h1|(|inc|#:| |(|number|)| |#=>| |number|,| |num|#:| |number|)|#:| |number|↵|#fun| |h2|(|hint|#:| |string|)|#:| |unit| |#=>| |string|↵|#fun| |h3|(|f|#:| |(|number|)| |#=>| |number|,| |g|#:| |(|number|)| |#=>| |number|)|#:| |(|number|)| |#=>| |number| -//│ Parsed: {fun h1: (inc: number -> number, num: number) -> number; fun h2: (hint: string) -> unit -> string; fun h3: (f: number -> number, g: number -> number) -> number -> number} -//│ diff --git a/ts2mls/js/src/test/diff/HighOrderFunc.mlsi b/ts2mls/js/src/test/diff/HighOrderFunc.mlsi new file mode 100644 index 000000000..0fa77d46d --- /dev/null +++ b/ts2mls/js/src/test/diff/HighOrderFunc.mlsi @@ -0,0 +1,5 @@ +export declare module HighOrderFunc { + declare fun h1(inc: (n: Num) => Num, num: Num): Num + declare fun h2(hint: Str): () => Str + declare fun h3(f: (x: Num) => Num, g: (x: Num) => Num): (x: Num) => Num +} diff --git a/ts2mls/js/src/test/diff/Import.mlsi b/ts2mls/js/src/test/diff/Import.mlsi new file mode 100644 index 000000000..c2f55a3d2 --- /dev/null +++ b/ts2mls/js/src/test/diff/Import.mlsi @@ -0,0 +1,9 @@ +import "./Dependency.mlsi" +export declare module Import { + val t: Num + val a: Dependency.A + val b: Dependency.B + val c: Dependency.C + val d: Dependency.D + val dd: Num +} diff --git a/ts2mls/js/src/test/diff/InterfaceMember.d.mls b/ts2mls/js/src/test/diff/InterfaceMember.d.mls deleted file mode 100644 index 30b8dadda..000000000 --- a/ts2mls/js/src/test/diff/InterfaceMember.d.mls +++ /dev/null @@ -1,41 +0,0 @@ -:NewDefs -:ParseOnly -trait IFoo() { - let a: string - fun b(x: number): number - fun c(): (false) | (true) - fun d(x: string): unit -} -trait II() { - fun test(x: T): number -} -fun create(): {v: number,} -fun get(x: {t: string,}): string -trait IEvent() { - fun callback(): (number) => unit -} -trait SearchFunc() { - fun __call(source: string, subString: string): (false) | (true) -} -trait StringArray() { - fun __index(index: number): string -} -trait Counter() { - fun __call(start: number): string - let interval: number - fun reset(): unit -} -trait Simple() { - let a: number - fun b(x: (false) | (true)): string -} -trait Simple2() { - let abc: T -} -trait Next(): Simple {} -trait TTT() { - fun ttt(x: T): T -} -//│ |#trait| |IFoo|(||)| |{|→|#let| |a|#:| |string|↵|#fun| |b|(|x|#:| |number|)|#:| |number|↵|#fun| |c|(||)|#:| |(|false|)| ||| |(|true|)|↵|#fun| |d|(|x|#:| |string|)|#:| |unit|←|↵|}|↵|#trait| |II|‹|T|›|(||)| |{|→|#fun| |test|(|x|#:| |T|)|#:| |number|←|↵|}|↵|#fun| |create|(||)|#:| |{|v|#:| |number|,|}|↵|#fun| |get|(|x|#:| |{|t|#:| |string|,|}|)|#:| |string|↵|#trait| |IEvent|(||)| |{|→|#fun| |callback|(||)|#:| |(|number|)| |#=>| |unit|←|↵|}|↵|#trait| |SearchFunc|(||)| |{|→|#fun| |__call|(|source|#:| |string|,| |subString|#:| |string|)|#:| |(|false|)| ||| |(|true|)|←|↵|}|↵|#trait| |StringArray|(||)| |{|→|#fun| |__index|(|index|#:| |number|)|#:| |string|←|↵|}|↵|#trait| |Counter|(||)| |{|→|#fun| |__call|(|start|#:| |number|)|#:| |string|↵|#let| |interval|#:| |number|↵|#fun| |reset|(||)|#:| |unit|←|↵|}|↵|#trait| |Simple|(||)| |{|→|#let| |a|#:| |number|↵|#fun| |b|(|x|#:| |(|false|)| ||| |(|true|)|)|#:| |string|←|↵|}|↵|#trait| |Simple2|‹|T|›|(||)| |{|→|#let| |abc|#:| |T|←|↵|}|↵|#trait| |Next|(||)|#:| |Simple| |{||}|↵|#trait| |TTT|‹|T|›|(||)| |{|→|#fun| |ttt|(|x|#:| |T|)|#:| |T|←|↵|}| -//│ Parsed: {trait IFoo() {let a: string; fun b: (x: number) -> number; fun c: () -> bool; fun d: (x: string) -> unit}; trait II‹T›() {fun test: (x: T) -> number}; fun create: () -> {v: number}; fun get: (x: {t: string}) -> string; trait IEvent() {fun callback: () -> number -> unit}; trait SearchFunc() {fun __call: (source: string, subString: string) -> bool}; trait StringArray() {fun __index: (index: number) -> string}; trait Counter() {fun __call: (start: number) -> string; let interval: number; fun reset: () -> unit}; trait Simple() {let a: number; fun b: (x: bool) -> string}; trait Simple2‹T›() {let abc: T}; trait Next(): Simple {}; trait TTT‹T›() {fun ttt: (x: T) -> T}} -//│ diff --git a/ts2mls/js/src/test/diff/InterfaceMember.mlsi b/ts2mls/js/src/test/diff/InterfaceMember.mlsi new file mode 100644 index 000000000..114d03506 --- /dev/null +++ b/ts2mls/js/src/test/diff/InterfaceMember.mlsi @@ -0,0 +1,35 @@ +export declare module InterfaceMember { + declare trait IFoo { + val a: Str + declare fun b(x: Num): Num + declare fun c(): (false) | (true) + declare fun d(x: Str): unit + } + declare trait II['T] { + declare fun test(x: 'T): Num + } + declare fun create(): {v: Num,} + declare fun get(x: {t: Str,}): Str + declare trait IEvent { + declare fun callback(): (x: Num) => unit + } + declare trait SearchFunc: ((args0: Str, args1: Str) => (false) | (true)) {} + declare trait StringArray { + val __index: unsupported["[index: number]: string;", "InterfaceMember.ts", 28, 23] + } + declare trait Counter: ((args0: Num) => Str) { + val interval: Num + declare fun reset(): unit + } + declare trait Simple { + val a: Num + declare fun b(x: (false) | (true)): Str + } + declare trait Simple2['T] { + val abc: 'T + } + declare trait Next extends Simple {} + declare trait TTT['T] { + declare fun ttt(x: 'T): 'T + } +} diff --git a/ts2mls/js/src/test/diff/Intersection.d.mls b/ts2mls/js/src/test/diff/Intersection.d.mls deleted file mode 100644 index 54213af52..000000000 --- a/ts2mls/js/src/test/diff/Intersection.d.mls +++ /dev/null @@ -1,22 +0,0 @@ -:NewDefs -:ParseOnly -fun extend(first: T, second: U): (T) & (U) -fun foo(x: (T) & (U)): unit -fun over(f: ((number) => string) & ((object) => string)): string -trait IA() { - let x: number -} -trait IB() { - let y: number -} -fun iii(x: (IA) & (IB)): (IA) & (IB) -fun uu(x: ((((U) & (T)) | ((U) & (P))) | ((V) & (T))) | ((V) & (P))): ((((U) & (T)) | ((U) & (P))) | ((V) & (T))) | ((V) & (P)) -fun iiii(x: ((U) & (T)) & (V)): ((U) & (T)) & (V) -fun arr(a: (MutArray) & (MutArray)): (MutArray) & (MutArray) -fun tt(x: ([U, T]) & ([V, V])): ([U, T]) & ([V, V]) -class A() {} -class B() {} -fun inter(c: (A) & (B)): (A) & (B) -//│ |#fun| |extend|‹|T|,| |U|›|(|first|#:| |T|,| |second|#:| |U|)|#:| |(|T|)| |&| |(|U|)|↵|#fun| |foo|‹|T|,| |U|›|(|x|#:| |(|T|)| |&| |(|U|)|)|#:| |unit|↵|#fun| |over|(|f|#:| |(|(|number|)| |#=>| |string|)| |&| |(|(|object|)| |#=>| |string|)|)|#:| |string|↵|#trait| |IA|(||)| |{|→|#let| |x|#:| |number|←|↵|}|↵|#trait| |IB|(||)| |{|→|#let| |y|#:| |number|←|↵|}|↵|#fun| |iii|(|x|#:| |(|IA|)| |&| |(|IB|)|)|#:| |(|IA|)| |&| |(|IB|)|↵|#fun| |uu|‹|U|,| |V|,| |T|,| |P|›|(|x|#:| |(|(|(|(|U|)| |&| |(|T|)|)| ||| |(|(|U|)| |&| |(|P|)|)|)| ||| |(|(|V|)| |&| |(|T|)|)|)| ||| |(|(|V|)| |&| |(|P|)|)|)|#:| |(|(|(|(|U|)| |&| |(|T|)|)| ||| |(|(|U|)| |&| |(|P|)|)|)| ||| |(|(|V|)| |&| |(|T|)|)|)| ||| |(|(|V|)| |&| |(|P|)|)|↵|#fun| |iiii|‹|U|,| |T|,| |V|›|(|x|#:| |(|(|U|)| |&| |(|T|)|)| |&| |(|V|)|)|#:| |(|(|U|)| |&| |(|T|)|)| |&| |(|V|)|↵|#fun| |arr|‹|U|,| |T|›|(|a|#:| |(|MutArray|‹|U|›|)| |&| |(|MutArray|‹|T|›|)|)|#:| |(|MutArray|‹|U|›|)| |&| |(|MutArray|‹|T|›|)|↵|#fun| |tt|‹|U|,| |T|,| |V|›|(|x|#:| |(|[|U|,| |T|]|)| |&| |(|[|V|,| |V|]|)|)|#:| |(|[|U|,| |T|]|)| |&| |(|[|V|,| |V|]|)|↵|#class| |A|(||)| |{||}|↵|#class| |B|(||)| |{||}|↵|#fun| |inter|(|c|#:| |(|A|)| |&| |(|B|)|)|#:| |(|A|)| |&| |(|B|)| -//│ Parsed: {fun extend: (first: T, second: U) -> (T & U); fun foo: (x: T & U) -> unit; fun over: (f: number -> string & object -> string) -> string; trait IA() {let x: number}; trait IB() {let y: number}; fun iii: (x: IA & IB) -> (IA & IB); fun uu: (x: U & T | U & P | V & T | V & P) -> (U & T | U & P | V & T | V & P); fun iiii: (x: U & T & V) -> (U & T & V); fun arr: (a: MutArray[U] & MutArray[T]) -> (MutArray[U] & MutArray[T]); fun tt: (x: [U, T] & [V, V]) -> ([U, T] & [V, V]); class A() {}; class B() {}; fun inter: (c: A & B) -> (A & B)} -//│ diff --git a/ts2mls/js/src/test/diff/Intersection.mlsi b/ts2mls/js/src/test/diff/Intersection.mlsi new file mode 100644 index 000000000..dc7cd7019 --- /dev/null +++ b/ts2mls/js/src/test/diff/Intersection.mlsi @@ -0,0 +1,43 @@ +export declare module Intersection { + declare fun extend['T, 'U](first: 'T, second: 'U): ('T) & ('U) + declare fun foo['T, 'U](x: ('T) & ('U)): unit + declare fun over(f: ((x: Num) => Str) & ((x: Object) => Str)): Str + declare trait IA { + val x: Num + } + declare trait IB { + val y: Num + } + declare fun iii(x: (IA) & (IB)): (IA) & (IB) + declare fun uu['U, 'V, 'T, 'P](x: (((('U) & ('T)) | (('U) & ('P))) | (('V) & ('T))) | (('V) & ('P))): (((('U) & ('T)) | (('U) & ('P))) | (('V) & ('T))) | (('V) & ('P)) + declare fun iiii['U, 'T, 'V](x: (('U) & ('T)) & ('V)): (('U) & ('T)) & ('V) + declare fun arr['U, 'T](a: (MutArray['U]) & (MutArray['T])): (MutArray['U]) & (MutArray['T]) + declare fun tt['U, 'T, 'V](x: (['U, 'T, ]) & (['V, 'V, ])): (['U, 'T, ]) & (['V, 'V, ]) + declare class A {} + declare class B {} + declare fun inter(c: (A) & (B)): (A) & (B) +} +//| ╔══[ERROR] type identifier not found: IA +//| ║ l.11: declare fun iii(x: (IA) & (IB)): (IA) & (IB) +//| ╙── ^^^^ +//| ╔══[ERROR] type identifier not found: IB +//| ║ l.11: declare fun iii(x: (IA) & (IB)): (IA) & (IB) +//| ╙── ^^^^ +//| ╔══[ERROR] type identifier not found: IA +//| ║ l.11: declare fun iii(x: (IA) & (IB)): (IA) & (IB) +//| ╙── ^^^^ +//| ╔══[ERROR] type identifier not found: IB +//| ║ l.11: declare fun iii(x: (IA) & (IB)): (IA) & (IB) +//| ╙── ^^^^ +//| ╔══[ERROR] type identifier not found: A +//| ║ l.18: declare fun inter(c: (A) & (B)): (A) & (B) +//| ╙── ^^^ +//| ╔══[ERROR] type identifier not found: B +//| ║ l.18: declare fun inter(c: (A) & (B)): (A) & (B) +//| ╙── ^^^ +//| ╔══[ERROR] type identifier not found: A +//| ║ l.18: declare fun inter(c: (A) & (B)): (A) & (B) +//| ╙── ^^^ +//| ╔══[ERROR] type identifier not found: B +//| ║ l.18: declare fun inter(c: (A) & (B)): (A) & (B) +//| ╙── ^^^ diff --git a/ts2mls/js/src/test/diff/Literal.d.mls b/ts2mls/js/src/test/diff/Literal.d.mls deleted file mode 100644 index 1ff16c9da..000000000 --- a/ts2mls/js/src/test/diff/Literal.d.mls +++ /dev/null @@ -1,8 +0,0 @@ -:NewDefs -:ParseOnly -let a: {a: "A",b: "B",} -let num: {y: 114,} -fun foo(x: {xx: "X",}): {yy: "Y",} -//│ |#let| |a|#:| |{|a|#:| |"A"|,|b|#:| |"B"|,|}|↵|#let| |num|#:| |{|y|#:| |114|,|}|↵|#fun| |foo|(|x|#:| |{|xx|#:| |"X"|,|}|)|#:| |{|yy|#:| |"Y"|,|}| -//│ Parsed: {let a: {a: "A", b: "B"}; let num: {y: 114}; fun foo: (x: {xx: "X"}) -> {yy: "Y"}} -//│ diff --git a/ts2mls/js/src/test/diff/Literal.mlsi b/ts2mls/js/src/test/diff/Literal.mlsi new file mode 100644 index 000000000..1f853f1d7 --- /dev/null +++ b/ts2mls/js/src/test/diff/Literal.mlsi @@ -0,0 +1,5 @@ +export declare module Literal { + val a: {a: "A",b: "B",} + val num: {y: 114,} + declare fun foo(x: {xx: "X",}): {yy: "Y",} +} diff --git a/ts2mls/js/src/test/diff/MultiFiles.d.mls b/ts2mls/js/src/test/diff/MultiFiles.d.mls deleted file mode 100644 index d44b2d913..000000000 --- a/ts2mls/js/src/test/diff/MultiFiles.d.mls +++ /dev/null @@ -1,23 +0,0 @@ -:NewDefs -:ParseOnly -fun multi1(x: number): number -fun multi3(): unit -class Foo(): Base {} -trait AnotherBase() { - let y: string -} -module N { - fun f(): unit - fun g(): unit - fun h(): unit -} -fun multi2(x: string): string -fun multi4(): unit -trait Base() { - let a: number -} -class AnotherFoo(): AnotherBase {} -fun multi5(): unit -//│ |#fun| |multi1|(|x|#:| |number|)|#:| |number|↵|#fun| |multi3|(||)|#:| |unit|↵|#class| |Foo|(||)|#:| |Base| |{||}|↵|#trait| |AnotherBase|(||)| |{|→|#let| |y|#:| |string|←|↵|}|↵|#module| |N| |{|→|#fun| |f|(||)|#:| |unit|↵|#fun| |g|(||)|#:| |unit|↵|#fun| |h|(||)|#:| |unit|←|↵|}|↵|#fun| |multi2|(|x|#:| |string|)|#:| |string|↵|#fun| |multi4|(||)|#:| |unit|↵|#trait| |Base|(||)| |{|→|#let| |a|#:| |number|←|↵|}|↵|#class| |AnotherFoo|(||)|#:| |AnotherBase| |{||}|↵|#fun| |multi5|(||)|#:| |unit| -//│ Parsed: {fun multi1: (x: number) -> number; fun multi3: () -> unit; class Foo(): Base {}; trait AnotherBase() {let y: string}; module N {fun f: () -> unit; fun g: () -> unit; fun h: () -> unit}; fun multi2: (x: string) -> string; fun multi4: () -> unit; trait Base() {let a: number}; class AnotherFoo(): AnotherBase {}; fun multi5: () -> unit} -//│ diff --git a/ts2mls/js/src/test/diff/Namespace.d.mls b/ts2mls/js/src/test/diff/Namespace.d.mls deleted file mode 100644 index a11aa1f25..000000000 --- a/ts2mls/js/src/test/diff/Namespace.d.mls +++ /dev/null @@ -1,33 +0,0 @@ -:NewDefs -:ParseOnly -module N1 { - fun f(x: anything): number - fun ff(y: anything): number - class C() { - fun f(): unit - } - trait I() { - fun f(): number - } - module N2 { - fun fff(x: (false) | (true)): number - fun gg(c: N1.C): N1.C - class BBB(): N1.C {} - } -} -module AA { - fun f(x: anything): string - class C() { - fun f(): unit - } - trait I() { - fun f(): number - } - module N2 { - } -} -fun f1(x: N1.C): N1.C -fun f2(x: AA.C): AA.C -//│ |#module| |N1| |{|→|#fun| |f|(|x|#:| |anything|)|#:| |number|↵|#fun| |ff|(|y|#:| |anything|)|#:| |number|↵|#class| |C|(||)| |{|→|#fun| |f|(||)|#:| |unit|←|↵|}|↵|#trait| |I|(||)| |{|→|#fun| |f|(||)|#:| |number|←|↵|}|↵|#module| |N2| |{|→|#fun| |fff|(|x|#:| |(|false|)| ||| |(|true|)|)|#:| |number|↵|#fun| |gg|(|c|#:| |N1|.C|)|#:| |N1|.C|↵|#class| |BBB|(||)|#:| |N1|.C| |{||}|←|↵|}|←|↵|}|↵|#module| |AA| |{|→|#fun| |f|(|x|#:| |anything|)|#:| |string|↵|#class| |C|(||)| |{|→|#fun| |f|(||)|#:| |unit|←|↵|}|↵|#trait| |I|(||)| |{|→|#fun| |f|(||)|#:| |number|←|↵|}|↵|#module| |N2| |{|↵|}|←|↵|}|↵|#fun| |f1|(|x|#:| |N1|.C|)|#:| |N1|.C|↵|#fun| |f2|(|x|#:| |AA|.C|)|#:| |AA|.C| -//│ Parsed: {module N1 {fun f: (x: anything) -> number; fun ff: (y: anything) -> number; class C() {fun f: () -> unit}; trait I() {fun f: () -> number}; module N2 {fun fff: (x: bool) -> number; fun gg: (c: N1.C) -> N1.C; class BBB(): N1.C {}}}; module AA {fun f: (x: anything) -> string; class C() {fun f: () -> unit}; trait I() {fun f: () -> number}; module N2 {}}; fun f1: (x: N1.C) -> N1.C; fun f2: (x: AA.C) -> AA.C} -//│ diff --git a/ts2mls/js/src/test/diff/Namespace.mlsi b/ts2mls/js/src/test/diff/Namespace.mlsi new file mode 100644 index 000000000..07c7f6fac --- /dev/null +++ b/ts2mls/js/src/test/diff/Namespace.mlsi @@ -0,0 +1,34 @@ +export declare module Namespace { + declare module N1 { + export declare fun f(x: anything): Num + declare fun ff(y: anything): Num + export declare class C { + declare fun f(): unit + } + declare trait I { + declare fun f(): Num + } + export declare module N2 { + export declare fun fff(x: (false) | (true)): Num + declare fun gg(c: C): C + declare class BBB extends C {} + } + } + declare module AA { + export declare fun f(x: anything): Str + export declare class C { + declare fun f(): unit + } + export declare trait I { + declare fun f(): Num + } + export declare module N2 { + } + } + declare fun f1(x: N1.C): N1.C + declare fun f2(x: AA.C): AA.C +} +//| ╔══[ERROR] type identifier not found: N1 +//| ║ l.28: declare fun f1(x: N1.C): N1.C +//| ╙── ^^ +//| scala.NotImplementedError: an implementation is missing diff --git a/ts2mls/js/src/test/diff/Optional.d.mls b/ts2mls/js/src/test/diff/Optional.d.mls deleted file mode 100644 index 10ed5607f..000000000 --- a/ts2mls/js/src/test/diff/Optional.d.mls +++ /dev/null @@ -1,25 +0,0 @@ -:NewDefs -:ParseOnly -fun buildName(firstName: string, lastName: (string) | (undefined)): string -fun buildName2(firstName: string, lastName: (string) | (undefined)): string -fun buildName3(firstName: string, lastName: MutArray): string -fun buildName4(firstName: string, lastName: MutArray): string -trait SquareConfig() { - let color: (string) | (undefined) - let width: (number) | (undefined) -} -fun did(x: number, f: ((number) => number) | (undefined)): number -fun getOrElse(arr: (MutArray) | (undefined)): object -class ABC() {} -fun testABC(abc: (ABC) | (undefined)): unit -fun testSquareConfig(conf: (SquareConfig) | (undefined)): unit -fun err(msg: ([number, string]) | (undefined)): unit -fun toStr(x: (((number) | (false)) | (true)) | (undefined)): string -fun boo(x: ((T) & (U)) | (undefined)): unit -class B() { - let b: T -} -fun boom(b: (B) | (undefined)): anything -//│ |#fun| |buildName|(|firstName|#:| |string|,| |lastName|#:| |(|string|)| ||| |(|#undefined|)|)|#:| |string|↵|#fun| |buildName2|(|firstName|#:| |string|,| |lastName|#:| |(|string|)| ||| |(|#undefined|)|)|#:| |string|↵|#fun| |buildName3|(|firstName|#:| |string|,| |lastName|#:| |MutArray|‹|string|›|)|#:| |string|↵|#fun| |buildName4|(|firstName|#:| |string|,| |lastName|#:| |MutArray|‹|anything|›|)|#:| |string|↵|#trait| |SquareConfig|(||)| |{|→|#let| |color|#:| |(|string|)| ||| |(|#undefined|)|↵|#let| |width|#:| |(|number|)| ||| |(|#undefined|)|←|↵|}|↵|#fun| |did|(|x|#:| |number|,| |f|#:| |(|(|number|)| |#=>| |number|)| ||| |(|#undefined|)|)|#:| |number|↵|#fun| |getOrElse|(|arr|#:| |(|MutArray|‹|object|›|)| ||| |(|#undefined|)|)|#:| |object|↵|#class| |ABC|(||)| |{||}|↵|#fun| |testABC|(|abc|#:| |(|ABC|)| ||| |(|#undefined|)|)|#:| |unit|↵|#fun| |testSquareConfig|(|conf|#:| |(|SquareConfig|)| ||| |(|#undefined|)|)|#:| |unit|↵|#fun| |err|(|msg|#:| |(|[|number|,| |string|]|)| ||| |(|#undefined|)|)|#:| |unit|↵|#fun| |toStr|(|x|#:| |(|(|(|number|)| ||| |(|false|)|)| ||| |(|true|)|)| ||| |(|#undefined|)|)|#:| |string|↵|#fun| |boo|‹|T|,| |U|›|(|x|#:| |(|(|T|)| |&| |(|U|)|)| ||| |(|#undefined|)|)|#:| |unit|↵|#class| |B|‹|T|›|(||)| |{|→|#let| |b|#:| |T|←|↵|}|↵|#fun| |boom|(|b|#:| |(|B|‹|nothing|›|)| ||| |(|#undefined|)|)|#:| |anything| -//│ Parsed: {fun buildName: (firstName: string, lastName: string | ()) -> string; fun buildName2: (firstName: string, lastName: string | ()) -> string; fun buildName3: (firstName: string, lastName: MutArray[string]) -> string; fun buildName4: (firstName: string, lastName: MutArray[anything]) -> string; trait SquareConfig() {let color: string | (); let width: number | ()}; fun did: (x: number, f: number -> number | ()) -> number; fun getOrElse: (arr: MutArray[object] | ()) -> object; class ABC() {}; fun testABC: (abc: ABC | ()) -> unit; fun testSquareConfig: (conf: SquareConfig | ()) -> unit; fun err: (msg: [number, string] | ()) -> unit; fun toStr: (x: number | false | true | ()) -> string; fun boo: (x: T & U | ()) -> unit; class B‹T›() {let b: T}; fun boom: (b: B[nothing] | ()) -> anything} -//│ diff --git a/ts2mls/js/src/test/diff/Optional.mlsi b/ts2mls/js/src/test/diff/Optional.mlsi new file mode 100644 index 000000000..480a92113 --- /dev/null +++ b/ts2mls/js/src/test/diff/Optional.mlsi @@ -0,0 +1,31 @@ +export declare module Optional { + declare fun buildName(firstName: Str, lastName: (Str) | (undefined)): Str + declare fun buildName2(firstName: Str, lastName: (Str) | (undefined)): Str + declare fun buildName3(firstName: Str, lastName: (Str) | (MutArray[Str])): Str + declare fun buildName4(firstName: Str, lastName: (anything) | (MutArray[anything])): Str + declare trait SquareConfig { + val color: (Str) | (undefined) + val width: (Num) | (undefined) + } + declare fun did(x: Num, f: ((x: Num) => Num) | (undefined)): Num + declare fun getOrElse(arr: (MutArray[Object]) | (undefined)): Object + declare class ABC {} + declare fun testABC(abc: (ABC) | (undefined)): unit + declare fun testSquareConfig(conf: (SquareConfig) | (undefined)): unit + declare fun err(msg: ([Num, Str, ]) | (undefined)): unit + declare fun toStr(x: (((Num) | (false)) | (true)) | (undefined)): Str + declare fun boo['T, 'U](x: (('T) & ('U)) | (undefined)): unit + declare class B['T] { + val b: 'T + } + declare fun boom(b: (B[nothing]) | (undefined)): anything +} +//| ╔══[ERROR] type identifier not found: ABC +//| ║ l.13: declare fun testABC(abc: (ABC) | (undefined)): unit +//| ╙── ^^^^^ +//| ╔══[ERROR] type identifier not found: SquareConfig +//| ║ l.14: declare fun testSquareConfig(conf: (SquareConfig) | (undefined)): unit +//| ╙── ^^^^^^^^^^^^^^ +//| ╔══[ERROR] type identifier not found: B +//| ║ l.21: declare fun boom(b: (B[nothing]) | (undefined)): anything +//| ╙── ^^^^^^^^^^^^ diff --git a/ts2mls/js/src/test/diff/Overload.d.mls b/ts2mls/js/src/test/diff/Overload.d.mls deleted file mode 100644 index b8977f71e..000000000 --- a/ts2mls/js/src/test/diff/Overload.d.mls +++ /dev/null @@ -1,27 +0,0 @@ -:NewDefs -:ParseOnly -fun f: ((number) => string) & ((string) => string) -class M() { - let foo: ((number) => string) & ((string) => string) -} -fun app: (((string) => unit) => (number) => unit) & (((string) => unit) => (string) => unit) -fun create: ((number) => unit => (false) | (true)) & (((false) | (true)) => unit => (false) | (true)) -fun g0: ((MutArray) => string) & ((MutArray) => string) -fun db: ((number) => MutArray) & ((object) => MutArray) -class N() {} -fun id: ((M) => unit) & ((N) => unit) -fun tst: (({z: number,}) => {y: string,}) & (({z: (false) | (true),}) => {y: string,}) -fun op: ((number) => ((number) | (undefined)) => unit) & ((number) => (((false) | (true)) | (undefined)) => unit) -fun swap: (([number, string]) => [number, string]) & (([string, number]) => [number, string]) -fun u: ((((number) | (false)) | (true)) => string) & ((object) => string) -fun doSome(x: anything): unit /* warning: the overload of function doSome is not supported yet. */ -module XX { - fun f(x: T, n: anything): string /* warning: the overload of function f is not supported yet. */ -} -class WWW() { - fun F(x: T): anything /* warning: the overload of function F is not supported yet. */ -} -fun baz(): anything /* warning: the overload of function baz is not supported yet. */ -//│ |#fun| |f|#:| |(|(|number|)| |#=>| |string|)| |&| |(|(|string|)| |#=>| |string|)|↵|#class| |M|(||)| |{|→|#let| |foo|#:| |(|(|number|)| |#=>| |string|)| |&| |(|(|string|)| |#=>| |string|)|←|↵|}|↵|#fun| |app|#:| |(|(|(|string|)| |#=>| |unit|)| |#=>| |(|number|)| |#=>| |unit|)| |&| |(|(|(|string|)| |#=>| |unit|)| |#=>| |(|string|)| |#=>| |unit|)|↵|#fun| |create|#:| |(|(|number|)| |#=>| |unit| |#=>| |(|false|)| ||| |(|true|)|)| |&| |(|(|(|false|)| ||| |(|true|)|)| |#=>| |unit| |#=>| |(|false|)| ||| |(|true|)|)|↵|#fun| |g0|#:| |(|(|MutArray|‹|string|›|)| |#=>| |string|)| |&| |(|(|MutArray|‹|object|›|)| |#=>| |string|)|↵|#fun| |db|#:| |(|(|number|)| |#=>| |MutArray|‹|number|›|)| |&| |(|(|object|)| |#=>| |MutArray|‹|number|›|)|↵|#class| |N|(||)| |{||}|↵|#fun| |id|#:| |(|(|M|)| |#=>| |unit|)| |&| |(|(|N|)| |#=>| |unit|)|↵|#fun| |tst|#:| |(|(|{|z|#:| |number|,|}|)| |#=>| |{|y|#:| |string|,|}|)| |&| |(|(|{|z|#:| |(|false|)| ||| |(|true|)|,|}|)| |#=>| |{|y|#:| |string|,|}|)|↵|#fun| |op|#:| |(|(|number|)| |#=>| |(|(|number|)| ||| |(|#undefined|)|)| |#=>| |unit|)| |&| |(|(|number|)| |#=>| |(|(|(|false|)| ||| |(|true|)|)| ||| |(|#undefined|)|)| |#=>| |unit|)|↵|#fun| |swap|#:| |(|(|[|number|,| |string|]|)| |#=>| |[|number|,| |string|]|)| |&| |(|(|[|string|,| |number|]|)| |#=>| |[|number|,| |string|]|)|↵|#fun| |u|#:| |(|(|(|(|number|)| ||| |(|false|)|)| ||| |(|true|)|)| |#=>| |string|)| |&| |(|(|object|)| |#=>| |string|)|↵|#fun| |doSome|‹|T|,| |U|›|(|x|#:| |anything|)|#:| |unit| |/* warning: the overload of function doSome is not supported yet. */|↵|#module| |XX| |{|→|#fun| |f|‹|T|›|(|x|#:| |T|,| |n|#:| |anything|)|#:| |string| |/* warning: the overload of function f is not supported yet. */|←|↵|}|↵|#class| |WWW|(||)| |{|→|#fun| |F|‹|T|›|(|x|#:| |T|)|#:| |anything| |/* warning: the overload of function F is not supported yet. */|←|↵|}|↵|#fun| |baz|(||)|#:| |anything| |/* warning: the overload of function baz is not supported yet. */| -//│ Parsed: {fun f: number -> string & string -> string; class M() {let foo: number -> string & string -> string}; fun app: (string -> unit) -> number -> unit & (string -> unit) -> string -> unit; fun create: number -> unit -> bool & bool -> unit -> bool; fun g0: MutArray[string] -> string & MutArray[object] -> string; fun db: number -> MutArray[number] & object -> MutArray[number]; class N() {}; fun id: M -> unit & N -> unit; fun tst: {z: number} -> {y: string} & {z: bool} -> {y: string}; fun op: number -> (number | ()) -> unit & number -> (false | true | ()) -> unit; fun swap: ([number, string]) -> [number, string] & ([string, number]) -> [number, string]; fun u: (number | false | true) -> string & object -> string; fun doSome: (x: anything) -> unit; module XX {fun f: (x: T, n: anything) -> string}; class WWW() {fun F: (x: T) -> anything}; fun baz: () -> anything} -//│ diff --git a/ts2mls/js/src/test/diff/Overload.mlsi b/ts2mls/js/src/test/diff/Overload.mlsi new file mode 100644 index 000000000..b8890833c --- /dev/null +++ b/ts2mls/js/src/test/diff/Overload.mlsi @@ -0,0 +1,24 @@ +export declare module Overload { + declare fun f(x: anything): Str /* warning: the overload of function f is not supported yet. */ + declare class M { + declare fun foo(args0: anything): Str /* warning: the overload of function foo is not supported yet. */ + } + declare fun app(f: anything, x: anything): unit /* warning: the overload of function app is not supported yet. */ + declare fun create(x: anything): () => (false) | (true) /* warning: the overload of function create is not supported yet. */ + declare fun g0(x: anything): Str /* warning: the overload of function g0 is not supported yet. */ + declare fun db(x: anything): MutArray[Num] /* warning: the overload of function db is not supported yet. */ + declare class N {} + declare fun id(x: anything): unit /* warning: the overload of function id is not supported yet. */ + declare fun tst(x: anything): {y: Str,} /* warning: the overload of function tst is not supported yet. */ + declare fun op(x: anything, y: anything): unit /* warning: the overload of function op is not supported yet. */ + declare fun swap(x: anything): MutArray[anything] /* warning: the overload of function swap is not supported yet. */ + declare fun u(x: anything): Str /* warning: the overload of function u is not supported yet. */ + declare fun doSome['T, 'U](x: anything): nothing /* warning: the overload of function doSome is not supported yet. */ + declare module XX { + export declare fun f['T](x: 'T, n: anything): Str /* warning: the overload of function f is not supported yet. */ + } + declare class WWW { + declare fun F['T](args0: 'T): 'T /* warning: the overload of function F is not supported yet. */ + } + declare fun baz(): anything /* warning: the overload of function baz is not supported yet. */ +} diff --git a/ts2mls/js/src/test/diff/TSArray.mlsi b/ts2mls/js/src/test/diff/TSArray.mlsi new file mode 100644 index 000000000..c5ef46d71 --- /dev/null +++ b/ts2mls/js/src/test/diff/TSArray.mlsi @@ -0,0 +1,45 @@ +export declare module TSArray { + declare fun first(x: MutArray[Str]): Str + declare fun getZero3(): MutArray[Num] + declare fun first2(fs: MutArray[(x: Num) => Num]): (x: Num) => Num + declare fun doEs(e: MutArray[Int]): MutArray[Int] + declare class C {} + declare trait I { + val i: Num + } + declare fun doCs(c: MutArray[C]): MutArray[C] + declare fun doIs(i: MutArray[I]): MutArray[I] + declare fun inter['U, 'T](x: MutArray[('U) & ('T)]): MutArray[('U) & ('T)] + declare fun clean(x: MutArray[[Str, Num, ]]): MutArray[[Str, Num, ]] + declare fun translate['T, 'U](x: MutArray['T]): MutArray['U] + declare fun uu(x: MutArray[((Num) | (false)) | (true)]): MutArray[((Num) | (false)) | (true)] + declare class Temp['T] { + val x: 'T + } + declare fun ta(ts: MutArray[Temp[(false) | (true)]]): MutArray[Temp[(false) | (true)]] + declare fun tat['T](ts: MutArray[Temp['T]]): MutArray[Temp['T]] +} +//| ╔══[ERROR] type identifier not found: C +//| ║ l.10: declare fun doCs(c: MutArray[C]): MutArray[C] +//| ╙── ^ +//| ╔══[ERROR] type identifier not found: C +//| ║ l.10: declare fun doCs(c: MutArray[C]): MutArray[C] +//| ╙── ^ +//| ╔══[ERROR] type identifier not found: I +//| ║ l.11: declare fun doIs(i: MutArray[I]): MutArray[I] +//| ╙── ^ +//| ╔══[ERROR] type identifier not found: I +//| ║ l.11: declare fun doIs(i: MutArray[I]): MutArray[I] +//| ╙── ^ +//| ╔══[ERROR] type identifier not found: Temp +//| ║ l.19: declare fun ta(ts: MutArray[Temp[(false) | (true)]]): MutArray[Temp[(false) | (true)]] +//| ╙── ^^^^^^^^^^^^^^^^^^^^^^ +//| ╔══[ERROR] type identifier not found: Temp +//| ║ l.19: declare fun ta(ts: MutArray[Temp[(false) | (true)]]): MutArray[Temp[(false) | (true)]] +//| ╙── ^^^^^^^^^^^^^^^^^^^^^^ +//| ╔══[ERROR] type identifier not found: Temp +//| ║ l.20: declare fun tat['T](ts: MutArray[Temp['T]]): MutArray[Temp['T]] +//| ╙── ^^^^^^^^ +//| ╔══[ERROR] type identifier not found: Temp +//| ║ l.20: declare fun tat['T](ts: MutArray[Temp['T]]): MutArray[Temp['T]] +//| ╙── ^^^^^^^^ diff --git a/ts2mls/js/src/test/diff/Tuple.d.mls b/ts2mls/js/src/test/diff/Tuple.d.mls deleted file mode 100644 index 672f433a2..000000000 --- a/ts2mls/js/src/test/diff/Tuple.d.mls +++ /dev/null @@ -1,21 +0,0 @@ -:NewDefs -:ParseOnly -fun key(x: [string, (false) | (true)]): string -fun value(x: [string, (false) | (true)]): (false) | (true) -fun third(x: [number, number, number]): number -fun vec2(x: number, y: number): [number, number] -fun twoFunctions(ff: [(number) => number, (number) => number], x: number): number -fun tupleIt(x: string): [unit => string] -fun s(flag: (false) | (true)): [(string) | (number), ((number) | (false)) | (true)] -fun s2(t: [(false) | (true), (string) | (number)]): (string) | (number) -fun ex(x: T, y: U): [T, U, (T) & (U)] -fun foo(x: [(T) & (U)]): unit -fun conv(x: {y: number,}): [{y: number,}, {z: string,}] -class A() { - let x: number -} -class B() {} -fun swap(x: [A, B]): [B, A] -//│ |#fun| |key|(|x|#:| |[|string|,| |(|false|)| ||| |(|true|)|]|)|#:| |string|↵|#fun| |value|(|x|#:| |[|string|,| |(|false|)| ||| |(|true|)|]|)|#:| |(|false|)| ||| |(|true|)|↵|#fun| |third|(|x|#:| |[|number|,| |number|,| |number|]|)|#:| |number|↵|#fun| |vec2|(|x|#:| |number|,| |y|#:| |number|)|#:| |[|number|,| |number|]|↵|#fun| |twoFunctions|(|ff|#:| |[|(|number|)| |#=>| |number|,| |(|number|)| |#=>| |number|]|,| |x|#:| |number|)|#:| |number|↵|#fun| |tupleIt|(|x|#:| |string|)|#:| |[|unit| |#=>| |string|]|↵|#fun| |s|(|flag|#:| |(|false|)| ||| |(|true|)|)|#:| |[|(|string|)| ||| |(|number|)|,| |(|(|number|)| ||| |(|false|)|)| ||| |(|true|)|]|↵|#fun| |s2|(|t|#:| |[|(|false|)| ||| |(|true|)|,| |(|string|)| ||| |(|number|)|]|)|#:| |(|string|)| ||| |(|number|)|↵|#fun| |ex|‹|T|,| |U|›|(|x|#:| |T|,| |y|#:| |U|)|#:| |[|T|,| |U|,| |(|T|)| |&| |(|U|)|]|↵|#fun| |foo|‹|T|,| |U|›|(|x|#:| |[|(|T|)| |&| |(|U|)|]|)|#:| |unit|↵|#fun| |conv|(|x|#:| |{|y|#:| |number|,|}|)|#:| |[|{|y|#:| |number|,|}|,| |{|z|#:| |string|,|}|]|↵|#class| |A|(||)| |{|→|#let| |x|#:| |number|←|↵|}|↵|#class| |B|(||)| |{||}|↵|#fun| |swap|(|x|#:| |[|A|,| |B|]|)|#:| |[|B|,| |A|]| -//│ Parsed: {fun key: (x: [string, bool]) -> string; fun value: (x: [string, bool]) -> bool; fun third: (x: [number, number, number]) -> number; fun vec2: (x: number, y: number) -> [number, number]; fun twoFunctions: (ff: [number -> number, number -> number], x: number) -> number; fun tupleIt: (x: string) -> [unit -> string]; fun s: (flag: bool) -> [string | number, number | false | true]; fun s2: (t: [bool, string | number]) -> (string | number); fun ex: (x: T, y: U) -> [T, U, T & U]; fun foo: (x: [T & U]) -> unit; fun conv: (x: {y: number}) -> [{y: number}, {z: string}]; class A() {let x: number}; class B() {}; fun swap: (x: [A, B]) -> [B, A]} -//│ diff --git a/ts2mls/js/src/test/diff/Tuple.mlsi b/ts2mls/js/src/test/diff/Tuple.mlsi new file mode 100644 index 000000000..ae51b2749 --- /dev/null +++ b/ts2mls/js/src/test/diff/Tuple.mlsi @@ -0,0 +1,30 @@ +export declare module Tuple { + declare fun key(x: [Str, (false) | (true), ]): Str + declare fun value(x: [Str, (false) | (true), ]): (false) | (true) + declare fun third(x: [Num, Num, Num, ]): Num + declare fun vec2(x: Num, y: Num): [Num, Num, ] + declare fun twoFunctions(ff: [(x: Num) => Num, (x: Num) => Num, ], x: Num): Num + declare fun tupleIt(x: Str): [() => Str, ] + declare fun s(flag: (false) | (true)): [(Str) | (Num), ((Num) | (false)) | (true), ] + declare fun s2(t: [(false) | (true), (Str) | (Num), ]): (Str) | (Num) + declare fun ex['T, 'U](x: 'T, y: 'U): ['T, 'U, ('T) & ('U), ] + declare fun foo['T, 'U](x: [('T) & ('U), ]): unit + declare fun conv(x: {y: Num,}): [{y: Num,}, {z: Str,}, ] + declare class A { + val x: Num + } + declare class B {} + declare fun swap(x: [A, B, ]): [B, A, ] +} +//| ╔══[ERROR] type identifier not found: A +//| ║ l.17: declare fun swap(x: [A, B, ]): [B, A, ] +//| ╙── ^ +//| ╔══[ERROR] type identifier not found: B +//| ║ l.17: declare fun swap(x: [A, B, ]): [B, A, ] +//| ╙── ^ +//| ╔══[ERROR] type identifier not found: B +//| ║ l.17: declare fun swap(x: [A, B, ]): [B, A, ] +//| ╙── ^ +//| ╔══[ERROR] type identifier not found: A +//| ║ l.17: declare fun swap(x: [A, B, ]): [B, A, ] +//| ╙── ^ diff --git a/ts2mls/js/src/test/diff/Type.d.mls b/ts2mls/js/src/test/diff/Type.d.mls deleted file mode 100644 index 1839cd27c..000000000 --- a/ts2mls/js/src/test/diff/Type.d.mls +++ /dev/null @@ -1,33 +0,0 @@ -:NewDefs -:ParseOnly -trait None() { - let _tag: "None" -} -trait Some() { - let _tag: "Some" - let value: A -} -type Option = (None) | (Some) -type Func = (number) => number -type S2 = [string, string] -trait I1() {} -trait I2() {} -type I3 = (I1) & (I2) -type StringArray = Array -type SomeInterface = {x: number,y: number,} -class ABC() {} -type DEF = ABC -type TP = [A, B, C] -module NA { - fun fb(b: string): unit - type B = string -} -class NC() { - let b: string -} -type G = ABC -let none: {_tag: "None",} -fun some(a: A): (None) | (Some) -//│ |#trait| |None|(||)| |{|→|#let| |_tag|#:| |"None"|←|↵|}|↵|#trait| |Some|‹|A|›|(||)| |{|→|#let| |_tag|#:| |"Some"|↵|#let| |value|#:| |A|←|↵|}|↵|#type| |Option|‹|A|›| |#=| |(|None|)| ||| |(|Some|‹|A|›|)|↵|#type| |Func| |#=| |(|number|)| |#=>| |number|↵|#type| |S2| |#=| |[|string|,| |string|]|↵|#trait| |I1|(||)| |{||}|↵|#trait| |I2|(||)| |{||}|↵|#type| |I3| |#=| |(|I1|)| |&| |(|I2|)|↵|#type| |StringArray| |#=| |Array|‹|string|›|↵|#type| |SomeInterface| |#=| |{|x|#:| |number|,|y|#:| |number|,|}|↵|#class| |ABC|(||)| |{||}|↵|#type| |DEF| |#=| |ABC|↵|#type| |TP|‹|A|,| |B|,| |C|›| |#=| |[|A|,| |B|,| |C|]|↵|#module| |NA| |{|→|#fun| |fb|(|b|#:| |string|)|#:| |unit|↵|#type| |B| |#=| |string|←|↵|}|↵|#class| |NC|(||)| |{|→|#let| |b|#:| |string|←|↵|}|↵|#type| |G| |#=| |ABC|↵|#let| |none|#:| |{|_tag|#:| |"None"|,|}|↵|#fun| |some|‹|A|›|(|a|#:| |A|)|#:| |(|None|)| ||| |(|Some|‹|A|›|)| -//│ Parsed: {trait None() {let _tag: "None"}; trait Some‹A›() {let _tag: "Some"; let value: A}; type alias Option‹A›: None | Some[A] {}; type alias Func: number -> number {}; type alias S2: [string, string] {}; trait I1() {}; trait I2() {}; type alias I3: I1 & I2 {}; type alias StringArray: Array[string] {}; type alias SomeInterface: {x: number, y: number} {}; class ABC() {}; type alias DEF: ABC {}; type alias TP‹A, B, C›: [A, B, C] {}; module NA {fun fb: (b: string) -> unit; type alias B: string {}}; class NC() {let b: string}; type alias G: ABC {}; let none: {_tag: "None"}; fun some: (a: A) -> (None | Some[A])} -//│ diff --git a/ts2mls/js/src/test/diff/Type.mlsi b/ts2mls/js/src/test/diff/Type.mlsi new file mode 100644 index 000000000..2c9647fab --- /dev/null +++ b/ts2mls/js/src/test/diff/Type.mlsi @@ -0,0 +1,36 @@ +export declare module Type { + declare trait None { + val _tag: "None" + } + declare trait Some['A] { + val _tag: "Some" + val value: 'A + } + type Option['A] = (None) | (Some['A]) + type Func = (x: Num) => Num + type S2 = [Str, Str, ] + declare trait I1 {} + declare trait I2 {} + type I3 = (I1) & (I2) + type StringArray = Array[Str] + type SomeInterface = {x: Num,y: Num,} + declare class ABC {} + type DEF = ABC + type TP['A, 'B, 'C] = ['A, 'B, 'C, ] + declare module NA { + declare fun fb(b: Str): unit + export type B = Str + } + declare class NC { + val b: Str + } + type G = ABC + val none: {_tag: "None",} + declare fun some['A](a: 'A): (None) | (Some['A]) +} +//| ╔══[ERROR] type identifier not found: None +//| ║ l.29: declare fun some['A](a: 'A): (None) | (Some['A]) +//| ╙── ^^^^^^ +//| ╔══[ERROR] type identifier not found: Some +//| ║ l.29: declare fun some['A](a: 'A): (None) | (Some['A]) +//| ╙── ^^^^^^^^^^ diff --git a/ts2mls/js/src/test/diff/TypeParameter.d.mls b/ts2mls/js/src/test/diff/TypeParameter.d.mls deleted file mode 100644 index 0f9147888..000000000 --- a/ts2mls/js/src/test/diff/TypeParameter.d.mls +++ /dev/null @@ -1,30 +0,0 @@ -:NewDefs -:ParseOnly -fun inc(x: T): number -class CC() { - fun print(s: T): unit -} -fun con(t: T): U -class Printer() { - fun print(t: T): unit -} -fun setStringPrinter(p: Printer): unit -fun getStringPrinter(): Printer -fun foo(p: Printer, x: T): T -fun foo2(p: Printer, x: T): T -class F() { - let x: T - fun GG(y: U): T -} -trait I() { - let x: T - fun GG(y: U): T -} -class FFF() { - fun fff(x: T): unit -} -fun fff(p: FFF, s: string): unit -fun getFFF(): FFF -//│ |#fun| |inc|‹|T|›|(|x|#:| |T|)|#:| |number|↵|#class| |CC|‹|T|›|(||)| |{|→|#fun| |print|(|s|#:| |T|)|#:| |unit|←|↵|}|↵|#fun| |con|‹|U|,| |T|›|(|t|#:| |T|)|#:| |U|↵|#class| |Printer|‹|T|›|(||)| |{|→|#fun| |print|(|t|#:| |T|)|#:| |unit|←|↵|}|↵|#fun| |setStringPrinter|(|p|#:| |Printer|‹|string|›|)|#:| |unit|↵|#fun| |getStringPrinter|(||)|#:| |Printer|‹|string|›|↵|#fun| |foo|‹|T|›|(|p|#:| |Printer|‹|T|›|,| |x|#:| |T|)|#:| |T|↵|#fun| |foo2|‹|T|›|(|p|#:| |Printer|‹|T|›|,| |x|#:| |T|)|#:| |T|↵|#class| |F|‹|T|›|(||)| |{|→|#let| |x|#:| |T|↵|#fun| |GG|‹|U|›|(|y|#:| |U|)|#:| |T|←|↵|}|↵|#trait| |I|‹|T|›|(||)| |{|→|#let| |x|#:| |T|↵|#fun| |GG|‹|U|›|(|y|#:| |U|)|#:| |T|←|↵|}|↵|#class| |FFF|‹|T|›|(||)| |{|→|#fun| |fff|(|x|#:| |T|)|#:| |unit|←|↵|}|↵|#fun| |fff|(|p|#:| |FFF|‹|string|›|,| |s|#:| |string|)|#:| |unit|↵|#fun| |getFFF|(||)|#:| |FFF|‹|number|›| -//│ Parsed: {fun inc: (x: T) -> number; class CC‹T›() {fun print: (s: T) -> unit}; fun con: (t: T) -> U; class Printer‹T›() {fun print: (t: T) -> unit}; fun setStringPrinter: (p: Printer[string]) -> unit; fun getStringPrinter: () -> Printer[string]; fun foo: (p: Printer[T], x: T) -> T; fun foo2: (p: Printer[T], x: T) -> T; class F‹T›() {let x: T; fun GG: (y: U) -> T}; trait I‹T›() {let x: T; fun GG: (y: U) -> T}; class FFF‹T›() {fun fff: (x: T) -> unit}; fun fff: (p: FFF[string], s: string) -> unit; fun getFFF: () -> FFF[number]} -//│ diff --git a/ts2mls/js/src/test/diff/TypeParameter.mlsi b/ts2mls/js/src/test/diff/TypeParameter.mlsi new file mode 100644 index 000000000..a2104c5ee --- /dev/null +++ b/ts2mls/js/src/test/diff/TypeParameter.mlsi @@ -0,0 +1,47 @@ +export declare module TypeParameter { + declare fun inc['T](x: 'T): Num + declare class CC['T] { + declare fun print(args0: 'T): unit + } + declare fun con['U, 'T](t: 'T): 'U + declare class Printer['T] { + declare fun print(args0: 'T): unit + } + declare fun setStringPrinter(p: Printer[Str]): unit + declare fun getStringPrinter(): Printer[Str] + declare fun foo['T](p: Printer['T], x: 'T): 'T + declare fun foo2['T](p: Printer['T], x: 'T): 'T + declare class F['T] { + val x: 'T + declare fun GG['U](args0: 'U): 'T + } + declare trait I['T] { + val x: 'T + declare fun GG['U](args0: 'U): 'T + } + declare class FFF['T] { + declare fun fff(args0: 'T): unit + } + declare fun fff(p: FFF[Str], s: Str): unit + declare fun getFFF(): FFF[Num] + type PolyToString = forall 'T: (x: 'T) => Str + type PolyID = forall 'T: (x: 'T) => 'T +} +//| ╔══[ERROR] type identifier not found: Printer +//| ║ l.10: declare fun setStringPrinter(p: Printer[Str]): unit +//| ╙── ^^^^^^^^^^^^ +//| ╔══[ERROR] type identifier not found: Printer +//| ║ l.11: declare fun getStringPrinter(): Printer[Str] +//| ╙── ^^^^^^^^^^^^ +//| ╔══[ERROR] type identifier not found: Printer +//| ║ l.12: declare fun foo['T](p: Printer['T], x: 'T): 'T +//| ╙── ^^^^^^^^^^^ +//| ╔══[ERROR] type identifier not found: Printer +//| ║ l.13: declare fun foo2['T](p: Printer['T], x: 'T): 'T +//| ╙── ^^^^^^^^^^^ +//| ╔══[ERROR] type identifier not found: FFF +//| ║ l.25: declare fun fff(p: FFF[Str], s: Str): unit +//| ╙── ^^^^^^^^ +//| ╔══[ERROR] type identifier not found: FFF +//| ║ l.26: declare fun getFFF(): FFF[Num] +//| ╙── ^^^^^^^^ diff --git a/ts2mls/js/src/test/diff/Union.d.mls b/ts2mls/js/src/test/diff/Union.d.mls deleted file mode 100644 index 8ad24730b..000000000 --- a/ts2mls/js/src/test/diff/Union.d.mls +++ /dev/null @@ -1,12 +0,0 @@ -:NewDefs -:ParseOnly -fun getString(x: (((string) | (number)) | (false)) | (true)): string -fun test(x: (false) | (true)): (string) | (number) -fun run(f: ((number) => number) | ((number) => string)): anything -fun get(arr: (MutArray) | (MutArray)): unit -fun get2(t: ([string, string]) | ([number, string])): string -fun typeVar(x: (T) | (U)): (T) | (U) -fun uuuu(x: (((string) | (number)) | (false)) | (true)): (((string) | (number)) | (false)) | (true) -//│ |#fun| |getString|(|x|#:| |(|(|(|string|)| ||| |(|number|)|)| ||| |(|false|)|)| ||| |(|true|)|)|#:| |string|↵|#fun| |test|(|x|#:| |(|false|)| ||| |(|true|)|)|#:| |(|string|)| ||| |(|number|)|↵|#fun| |run|(|f|#:| |(|(|number|)| |#=>| |number|)| ||| |(|(|number|)| |#=>| |string|)|)|#:| |anything|↵|#fun| |get|(|arr|#:| |(|MutArray|‹|number|›|)| ||| |(|MutArray|‹|string|›|)|)|#:| |unit|↵|#fun| |get2|(|t|#:| |(|[|string|,| |string|]|)| ||| |(|[|number|,| |string|]|)|)|#:| |string|↵|#fun| |typeVar|‹|T|,| |U|›|(|x|#:| |(|T|)| ||| |(|U|)|)|#:| |(|T|)| ||| |(|U|)|↵|#fun| |uuuu|(|x|#:| |(|(|(|string|)| ||| |(|number|)|)| ||| |(|false|)|)| ||| |(|true|)|)|#:| |(|(|(|string|)| ||| |(|number|)|)| ||| |(|false|)|)| ||| |(|true|)| -//│ Parsed: {fun getString: (x: string | number | false | true) -> string; fun test: (x: bool) -> (string | number); fun run: (f: number -> number | number -> string) -> anything; fun get: (arr: MutArray[number] | MutArray[string]) -> unit; fun get2: (t: [string, string] | [number, string]) -> string; fun typeVar: (x: T | U) -> (T | U); fun uuuu: (x: string | number | false | true) -> (string | number | false | true)} -//│ diff --git a/ts2mls/js/src/test/diff/Union.mlsi b/ts2mls/js/src/test/diff/Union.mlsi new file mode 100644 index 000000000..bf028e12e --- /dev/null +++ b/ts2mls/js/src/test/diff/Union.mlsi @@ -0,0 +1,9 @@ +export declare module Union { + declare fun getString(x: (((Str) | (Num)) | (false)) | (true)): Str + declare fun test(x: (false) | (true)): (Str) | (Num) + declare fun run(f: ((x: Num) => Num) | ((x: Num) => Str)): anything + declare fun get(arr: (MutArray[Num]) | (MutArray[Str])): unit + declare fun get2(t: ([Str, Str, ]) | ([Num, Str, ])): Str + declare fun typeVar['T, 'U](x: ('T) | ('U)): ('T) | ('U) + declare fun uuuu(x: (((Str) | (Num)) | (false)) | (true)): (((Str) | (Num)) | (false)) | (true) +} diff --git a/ts2mls/js/src/test/diff/Variables.d.mls b/ts2mls/js/src/test/diff/Variables.d.mls deleted file mode 100644 index 89f39fa49..000000000 --- a/ts2mls/js/src/test/diff/Variables.d.mls +++ /dev/null @@ -1,19 +0,0 @@ -:NewDefs -:ParseOnly -let URI: string -let URI2: string -let foo: number -let bar: false -class FooBar() {} -let fb: FooBar -module ABC { - class DEF() {} -} -let d: ABC.DEF -module DD { - let foo: number - let bar: number -} -//│ |#let| |URI|#:| |string|↵|#let| |URI2|#:| |string|↵|#let| |foo|#:| |number|↵|#let| |bar|#:| |false|↵|#class| |FooBar|(||)| |{||}|↵|#let| |fb|#:| |FooBar|↵|#module| |ABC| |{|→|#class| |DEF|(||)| |{||}|←|↵|}|↵|#let| |d|#:| |ABC|.DEF|↵|#module| |DD| |{|→|#let| |foo|#:| |number|↵|#let| |bar|#:| |number|←|↵|}| -//│ Parsed: {let URI: string; let URI2: string; let foo: number; let bar: false; class FooBar() {}; let fb: FooBar; module ABC {class DEF() {}}; let d: ABC.DEF; module DD {let foo: number; let bar: number}} -//│ diff --git a/ts2mls/js/src/test/diff/Variables.mlsi b/ts2mls/js/src/test/diff/Variables.mlsi new file mode 100644 index 000000000..b5ad2a081 --- /dev/null +++ b/ts2mls/js/src/test/diff/Variables.mlsi @@ -0,0 +1,23 @@ +export declare module Variables { + val URI: Str + val URI2: Str + val foo: Num + val bar: false + declare class FooBar {} + val fb: FooBar + declare module ABC { + export declare class DEF {} + } + val d: ABC.DEF + declare module DD { + export val foo: Num + val bar: Num + } +} +//| ╔══[ERROR] type identifier not found: FooBar +//| ║ l.7: val fb: FooBar +//| ╙── ^^^^^^ +//| ╔══[ERROR] type identifier not found: ABC +//| ║ l.11: val d: ABC.DEF +//| ╙── ^^^ +//| scala.NotImplementedError: an implementation is missing diff --git a/ts2mls/js/src/test/scala/ts2mls/TSTypeGenerationTests.scala b/ts2mls/js/src/test/scala/ts2mls/TSTypeGenerationTests.scala index b5f973f4c..4b1af6d5b 100644 --- a/ts2mls/js/src/test/scala/ts2mls/TSTypeGenerationTests.scala +++ b/ts2mls/js/src/test/scala/ts2mls/TSTypeGenerationTests.scala @@ -4,38 +4,22 @@ import org.scalatest.funsuite.AnyFunSuite class TSTypeGenerationTest extends AnyFunSuite { import TSTypeGenerationTest._ - - testsData.foreach((data) => test(data._2) { - val program = TSProgram(tsPath(data._1)) - var writer = JSWriter(diffPath(data._2)) - program.generate(writer) - writer.close() + + testsData.foreach((filename) => test(filename) { + val program = TSProgram( + FileInfo("./ts2mls/js/src/test/typescript", filename, "../../../../../driver/npm/lib/predefs"), + false, None, (file: FileInfo, writer: JSWriter) => (), None) // No need for builtin check + program.generate }) } object TSTypeGenerationTest { - private def tsPath(filenames: Seq[String]) = filenames.map((fn) => s"ts2mls/js/src/test/typescript/$fn") - private def diffPath(filename: String) = s"ts2mls/js/src/test/diff/$filename" - + // We only generate type information for builtin declarations here. + // User-defined scripts may contain errors and printing error messages can lead to test failure + // if we use the two-pass test. + // Builtin declarations should never contain an error. private val testsData = List( - (Seq("Array.ts"), "Array.d.mls"), - (Seq("BasicFunctions.ts"), "BasicFunctions.d.mls"), - (Seq("ClassMember.ts"), "ClassMember.d.mls"), - (Seq("Dec.d.ts"), "Dec.d.mls"), - (Seq("Enum.ts"), "Enum.d.mls"), - (Seq("Heritage.ts"), "Heritage.d.mls"), - (Seq("HighOrderFunc.ts"), "HighOrderFunc.d.mls"), - (Seq("InterfaceMember.ts"), "InterfaceMember.d.mls"), - (Seq("Intersection.ts"), "Intersection.d.mls"), - (Seq("Literal.ts"), "Literal.d.mls"), - (Seq("Multi1.ts", "Multi2.ts", "Multi3.ts"), "MultiFiles.d.mls"), - (Seq("Namespace.ts"), "Namespace.d.mls"), - (Seq("Optional.ts"), "Optional.d.mls"), - (Seq("Overload.ts"), "Overload.d.mls"), - (Seq("Tuple.ts"), "Tuple.d.mls"), - (Seq("Type.ts"), "Type.d.mls"), - (Seq("TypeParameter.ts"), "TypeParameter.d.mls"), - (Seq("Union.ts"), "Union.d.mls"), - (Seq("Variables.ts"), "Variables.d.mls"), + "./Dom.d.ts", + "./ES5.d.ts", ) } diff --git a/ts2mls/js/src/test/typescript/Cycle1.ts b/ts2mls/js/src/test/typescript/Cycle1.ts new file mode 100644 index 000000000..572c62ed1 --- /dev/null +++ b/ts2mls/js/src/test/typescript/Cycle1.ts @@ -0,0 +1,4 @@ +import { B } from "./Cycle2" + +export class A {} +export const b = new B(); diff --git a/ts2mls/js/src/test/typescript/Cycle2.ts b/ts2mls/js/src/test/typescript/Cycle2.ts new file mode 100644 index 000000000..daf987b8d --- /dev/null +++ b/ts2mls/js/src/test/typescript/Cycle2.ts @@ -0,0 +1,4 @@ +import { A } from "./Cycle1" + +export class B {} +export const a = new A(); diff --git a/ts2mls/js/src/test/typescript/Dependency.ts b/ts2mls/js/src/test/typescript/Dependency.ts new file mode 100644 index 000000000..99f8158a7 --- /dev/null +++ b/ts2mls/js/src/test/typescript/Dependency.ts @@ -0,0 +1,19 @@ +export class A { + a: number +} + +export class B { + b: number +} + +export class C { + c: number +} + +export class D { + d: number +} + +export default function f() { + return 42; +} diff --git a/ts2mls/js/src/test/typescript/Dom.d.ts b/ts2mls/js/src/test/typescript/Dom.d.ts new file mode 100644 index 000000000..23219f4ea --- /dev/null +++ b/ts2mls/js/src/test/typescript/Dom.d.ts @@ -0,0 +1,48 @@ +///////////////////////////// +/// Window APIs +///////////////////////////// + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ +interface Console { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/assert) */ + assert(condition?: boolean, ...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear) */ + clear(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count) */ + count(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset) */ + countReset(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug) */ + debug(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir) */ + dir(item?: any, options?: any): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml) */ + dirxml(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error) */ + error(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group) */ + group(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed) */ + groupCollapsed(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd) */ + groupEnd(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info) */ + info(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log) */ + log(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table) */ + table(tabularData?: any, properties?: string[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time) */ + time(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd) */ + timeEnd(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog) */ + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace) */ + trace(...data: any[]): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn) */ + warn(...data: any[]): void; +} + +declare var console: Console; diff --git a/ts2mls/js/src/test/typescript/ES5.d.ts b/ts2mls/js/src/test/typescript/ES5.d.ts new file mode 100644 index 000000000..dabff3f6a --- /dev/null +++ b/ts2mls/js/src/test/typescript/ES5.d.ts @@ -0,0 +1,4465 @@ +/// +/// + +///////////////////////////// +/// ECMAScript APIs +///////////////////////////// + +declare var NaN: number; +declare var Infinity: number; + +/** + * Evaluates JavaScript code and executes it. + * @param x A String value that contains valid JavaScript code. + */ +declare function eval(x: string): any; + +/** + * Converts a string to an integer. + * @param string A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in `string`. + * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. + * All other strings are considered decimal. + */ +declare function parseInt(string: string, radix?: number): number; + +/** + * Converts a string to a floating-point number. + * @param string A string that contains a floating-point number. + */ +declare function parseFloat(string: string): number; + +/** + * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number). + * @param number A numeric value. + */ +declare function isNaN(number: number): boolean; + +/** + * Determines whether a supplied number is finite. + * @param number Any numeric value. + */ +declare function isFinite(number: number): boolean; + +/** + * Gets the unencoded version of an encoded Uniform Resource Identifier (URI). + * @param encodedURI A value representing an encoded URI. + */ +declare function decodeURI(encodedURI: string): string; + +/** + * Gets the unencoded version of an encoded component of a Uniform Resource Identifier (URI). + * @param encodedURIComponent A value representing an encoded URI component. + */ +declare function decodeURIComponent(encodedURIComponent: string): string; + +/** + * Encodes a text string as a valid Uniform Resource Identifier (URI) + * @param uri A value representing an unencoded URI. + */ +declare function encodeURI(uri: string): string; + +/** + * Encodes a text string as a valid component of a Uniform Resource Identifier (URI). + * @param uriComponent A value representing an unencoded URI component. + */ +declare function encodeURIComponent(uriComponent: string | number | boolean): string; + +/** + * Computes a new string in which certain characters have been replaced by a hexadecimal escape sequence. + * @deprecated A legacy feature for browser compatibility + * @param string A string value + */ +declare function escape(string: string): string; + +/** + * Computes a new string in which hexadecimal escape sequences are replaced with the character that it represents. + * @deprecated A legacy feature for browser compatibility + * @param string A string value + */ +declare function unescape(string: string): string; + +interface Symbol { + /** Returns a string representation of an object. */ + toString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): symbol; +} + +declare type PropertyKey = string | number | symbol; + +interface PropertyDescriptor { + configurable?: boolean; + enumerable?: boolean; + value?: any; + writable?: boolean; + get?(): any; + set?(v: any): void; +} + +interface PropertyDescriptorMap { + [key: PropertyKey]: PropertyDescriptor; +} + +class Object { + /** The initial value of Object.prototype.constructor is the standard built-in Object constructor. */ + constructor: Function; + + /** Returns a string representation of an object. */ + toString(): string; + + /** Returns a date converted to a string using the current locale. */ + toLocaleString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): Object; + + /** + * Determines whether an object has a property with the specified name. + * @param v A property name. + */ + hasOwnProperty(v: PropertyKey): boolean; + + /** + * Determines whether an object exists in another object's prototype chain. + * @param v Another object whose prototype chain is to be checked. + */ + isPrototypeOf(v: Object): boolean; + + /** + * Determines whether a specified property is enumerable. + * @param v A property name. + */ + propertyIsEnumerable(v: PropertyKey): boolean; +} + +interface ObjectConstructor { + new(value?: any): Object; + (): any; + (value: any): any; + + /** A reference to the prototype for a class of objects. */ + readonly prototype: Object; + + /** + * Returns the prototype of an object. + * @param o The object that references the prototype. + */ + getPrototypeOf(o: any): any; + + /** + * Gets the own property descriptor of the specified object. + * An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype. + * @param o Object that contains the property. + * @param p Name of the property. + */ + getOwnPropertyDescriptor(o: any, p: PropertyKey): PropertyDescriptor | undefined; + + /** + * Returns the names of the own properties of an object. The own properties of an object are those that are defined directly + * on that object, and are not inherited from the object's prototype. The properties of an object include both fields (objects) and functions. + * @param o Object that contains the own properties. + */ + getOwnPropertyNames(o: any): string[]; + + /** + * Creates an object that has the specified prototype or that has null prototype. + * @param o Object to use as a prototype. May be null. + */ + create(o: object | null): any; + + /** + * Creates an object that has the specified prototype, and that optionally contains specified properties. + * @param o Object to use as a prototype. May be null + * @param properties JavaScript object that contains one or more property descriptors. + */ + create(o: object | null, properties: PropertyDescriptorMap & ThisType): any; + + /** + * Adds a property to an object, or modifies attributes of an existing property. + * @param o Object on which to add or modify the property. This can be a native JavaScript object (that is, a user-defined object or a built in object) or a DOM object. + * @param p The property name. + * @param attributes Descriptor for the property. It can be for a data property or an accessor property. + */ + defineProperty(o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType): T; + + /** + * Adds one or more properties to an object, and/or modifies attributes of existing properties. + * @param o Object on which to add or modify the properties. This can be a native JavaScript object or a DOM object. + * @param properties JavaScript object that contains one or more descriptor objects. Each descriptor object describes a data property or an accessor property. + */ + defineProperties(o: T, properties: PropertyDescriptorMap & ThisType): T; + + /** + * Prevents the modification of attributes of existing properties, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + seal(o: T): T; + + /** + * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. + * @param f Object on which to lock the attributes. + */ + freeze(f: T): T; + + /** + * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + freeze(o: T): Readonly; + + /** + * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + freeze(o: T): Readonly; + + /** + * Prevents the addition of new properties to an object. + * @param o Object to make non-extensible. + */ + preventExtensions(o: T): T; + + /** + * Returns true if existing property attributes cannot be modified in an object and new properties cannot be added to the object. + * @param o Object to test. + */ + isSealed(o: any): boolean; + + /** + * Returns true if existing property attributes and values cannot be modified in an object, and new properties cannot be added to the object. + * @param o Object to test. + */ + isFrozen(o: any): boolean; + + /** + * Returns a value that indicates whether new properties can be added to an object. + * @param o Object to test. + */ + isExtensible(o: any): boolean; + + /** + * Returns the names of the enumerable string properties and methods of an object. + * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ + keys(o: object): string[]; +} + +/** + * Provides functionality common to all JavaScript objects. + */ +declare var Object: ObjectConstructor; + +/** + * Creates a new function. + */ +interface Function { + /** + * Calls the function, substituting the specified object for the this value of the function, and the specified array for the arguments of the function. + * @param thisArg The object to be used as the this object. + * @param argArray A set of arguments to be passed to the function. + */ + apply(this: Function, thisArg: any, argArray?: any): any; + + /** + * Calls a method of an object, substituting another object for the current object. + * @param thisArg The object to be used as the current object. + * @param argArray A list of arguments to be passed to the method. + */ + call(this: Function, thisArg: any, ...argArray: any[]): any; + + /** + * For a given function, creates a bound function that has the same body as the original function. + * The this object of the bound function is associated with the specified object, and has the specified initial parameters. + * @param thisArg An object to which the this keyword can refer inside the new function. + * @param argArray A list of arguments to be passed to the new function. + */ + bind(this: Function, thisArg: any, ...argArray: any[]): any; + + /** Returns a string representation of a function. */ + toString(): string; + + prototype: any; + readonly length: number; + + // Non-standard extensions + arguments: any; + caller: Function; +} + +interface FunctionConstructor { + /** + * Creates a new function. + * @param args A list of arguments the function accepts. + */ + new(...args: string[]): Function; + (...args: string[]): Function; + readonly prototype: Function; +} + +declare var Function: FunctionConstructor; + +/** + * Extracts the type of the 'this' parameter of a function type, or 'unknown' if the function type has no 'this' parameter. + */ +type ThisParameterType = T extends (this: infer U, ...args: never) => any ? U : unknown; + +/** + * Removes the 'this' parameter from a function type. + */ +type OmitThisParameter = unknown extends ThisParameterType ? T : T extends (...args: infer A) => infer R ? (...args: A) => R : T; + +interface CallableFunction extends Function { + /** + * Calls the function with the specified object as the this value and the elements of specified array as the arguments. + * @param thisArg The object to be used as the this object. + * @param args An array of argument values to be passed to the function. + */ + apply(this: (this: T) => R, thisArg: T): R; + apply(this: (this: T, ...args: A) => R, thisArg: T, args: A): R; + + /** + * Calls the function with the specified object as the this value and the specified rest arguments as the arguments. + * @param thisArg The object to be used as the this object. + * @param args Argument values to be passed to the function. + */ + call(this: (this: T, ...args: A) => R, thisArg: T, ...args: A): R; + + /** + * For a given function, creates a bound function that has the same body as the original function. + * The this object of the bound function is associated with the specified object, and has the specified initial parameters. + * @param thisArg The object to be used as the this object. + * @param args Arguments to bind to the parameters of the function. + */ + bind(this: T, thisArg: ThisParameterType): OmitThisParameter; + bind(this: (this: T, arg0: A0, ...args: A) => R, thisArg: T, arg0: A0): (...args: A) => R; + bind(this: (this: T, arg0: A0, arg1: A1, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1): (...args: A) => R; + bind(this: (this: T, arg0: A0, arg1: A1, arg2: A2, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1, arg2: A2): (...args: A) => R; + bind(this: (this: T, arg0: A0, arg1: A1, arg2: A2, arg3: A3, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1, arg2: A2, arg3: A3): (...args: A) => R; + bind(this: (this: T, ...args: AX[]) => R, thisArg: T, ...args: AX[]): (...args: AX[]) => R; +} + +interface NewableFunction extends Function { + /** + * Calls the function with the specified object as the this value and the elements of specified array as the arguments. + * @param thisArg The object to be used as the this object. + * @param args An array of argument values to be passed to the function. + */ + apply(this: new () => T, thisArg: T): void; + apply(this: new (...args: A) => T, thisArg: T, args: A): void; + + /** + * Calls the function with the specified object as the this value and the specified rest arguments as the arguments. + * @param thisArg The object to be used as the this object. + * @param args Argument values to be passed to the function. + */ + call(this: new (...args: A) => T, thisArg: T, ...args: A): void; + + /** + * For a given function, creates a bound function that has the same body as the original function. + * The this object of the bound function is associated with the specified object, and has the specified initial parameters. + * @param thisArg The object to be used as the this object. + * @param args Arguments to bind to the parameters of the function. + */ + bind(this: T, thisArg: any): T; + bind(this: new (arg0: A0, ...args: A) => R, thisArg: any, arg0: A0): new (...args: A) => R; + bind(this: new (arg0: A0, arg1: A1, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1): new (...args: A) => R; + bind(this: new (arg0: A0, arg1: A1, arg2: A2, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1, arg2: A2): new (...args: A) => R; + bind(this: new (arg0: A0, arg1: A1, arg2: A2, arg3: A3, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1, arg2: A2, arg3: A3): new (...args: A) => R; + bind(this: new (...args: AX[]) => R, thisArg: any, ...args: AX[]): new (...args: AX[]) => R; +} + +interface IArguments { + [index: number]: any; + length: number; + callee: Function; +} + +interface String { + /** Returns a string representation of a string. */ + toString(): string; + + /** + * Returns the character at the specified index. + * @param pos The zero-based index of the desired character. + */ + charAt(pos: number): string; + + /** + * Returns the Unicode value of the character at the specified location. + * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned. + */ + charCodeAt(index: number): number; + + /** + * Returns a string that contains the concatenation of two or more strings. + * @param strings The strings to append to the end of the string. + */ + concat(...strings: string[]): string; + + /** + * Returns the position of the first occurrence of a substring. + * @param searchString The substring to search for in the string + * @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string. + */ + indexOf(searchString: string, position?: number): number; + + /** + * Returns the last occurrence of a substring in the string. + * @param searchString The substring to search for. + * @param position The index at which to begin searching. If omitted, the search begins at the end of the string. + */ + lastIndexOf(searchString: string, position?: number): number; + + /** + * Determines whether two strings are equivalent in the current locale. + * @param that String to compare to target string + */ + localeCompare(that: string): number; + + /** + * Matches a string with a regular expression, and returns an array containing the results of that search. + * @param regexp A variable name or string literal containing the regular expression pattern and flags. + */ + match(regexp: string | RegExp): RegExpMatchArray | null; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A string or regular expression to search for. + * @param replaceValue A string containing the text to replace. When the {@linkcode searchValue} is a `RegExp`, all matches are replaced if the `g` flag is set (or only those matches at the beginning, if the `y` flag is also present). Otherwise, only the first match of {@linkcode searchValue} is replaced. + */ + replace(searchValue: string | RegExp, replaceValue: string): string; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A string to search for. + * @param replacer A function that returns the replacement text. + */ + replace(searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the first substring match in a regular expression search. + * @param regexp The regular expression pattern and applicable flags. + */ + search(regexp: string | RegExp): number; + + /** + * Returns a section of a string. + * @param start The index to the beginning of the specified portion of stringObj. + * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. + * If this value is not specified, the substring continues to the end of stringObj. + */ + slice(start?: number, end?: number): string; + + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(separator: string | RegExp, limit?: number): string[]; + + /** + * Returns the substring at the specified location within a String object. + * @param start The zero-based index number indicating the beginning of the substring. + * @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end. + * If end is omitted, the characters from start through the end of the original string are returned. + */ + substring(start: number, end?: number): string; + + /** Converts all the alphabetic characters in a string to lowercase. */ + toLowerCase(): string; + + /** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */ + toLocaleLowerCase(locales?: string | string[]): string; + + /** Converts all the alphabetic characters in a string to uppercase. */ + toUpperCase(): string; + + /** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */ + toLocaleUpperCase(locales?: string | string[]): string; + + /** Removes the leading and trailing white space and line terminator characters from a string. */ + trim(): string; + + /** Returns the length of a String object. */ + readonly length: number; + + // IE extensions + /** + * Gets a substring beginning at the specified location and having the specified length. + * @deprecated A legacy feature for browser compatibility + * @param from The starting position of the desired substring. The index of the first character in the string is zero. + * @param length The number of characters to include in the returned substring. + */ + substr(from: number, length?: number): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): string; + + readonly [index: number]: string; +} + +interface StringConstructor { + new(value?: any): String; + (value?: any): string; + readonly prototype: String; + fromCharCode(...codes: number[]): string; +} + +/** + * Allows manipulation and formatting of text strings and determination and location of substrings within strings. + */ +declare var String: StringConstructor; + +class Bool { + /** Returns the primitive value of the specified object. */ + valueOf(): boolean; +} + +interface BooleanConstructor { + new(value?: any): Bool; + (value?: T): boolean; + readonly prototype: Bool; +} + +declare var Boolean: BooleanConstructor; + +interface Number { + /** + * Returns a string representation of an object. + * @param radix Specifies a radix for converting numeric values to strings. This value is only used for numbers. + */ + toString(radix?: number): string; + + /** + * Returns a string representing a number in fixed-point notation. + * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. + */ + toFixed(fractionDigits?: number): string; + + /** + * Returns a string containing a number represented in exponential notation. + * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. + */ + toExponential(fractionDigits?: number): string; + + /** + * Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits. + * @param precision Number of significant digits. Must be in the range 1 - 21, inclusive. + */ + toPrecision(precision?: number): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): number; +} + +interface NumberConstructor { + new(value?: any): Number; + (value?: any): number; + readonly prototype: Number; + + /** The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. */ + readonly MAX_VALUE: number; + + /** The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. */ + readonly MIN_VALUE: number; + + /** + * A value that is not a number. + * In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function. + */ + readonly NaN: number; + + /** + * A value that is less than the largest negative number that can be represented in JavaScript. + * JavaScript displays NEGATIVE_INFINITY values as -infinity. + */ + readonly NEGATIVE_INFINITY: number; + + /** + * A value greater than the largest number that can be represented in JavaScript. + * JavaScript displays POSITIVE_INFINITY values as infinity. + */ + readonly POSITIVE_INFINITY: number; +} + +/** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */ +declare var Number: NumberConstructor; + +interface TemplateStringsArray extends ReadonlyArray { + readonly raw: readonly string[]; +} + +/** + * The type of `import.meta`. + * + * If you need to declare that a given property exists on `import.meta`, + * this type may be augmented via interface merging. + */ +interface ImportMeta { +} + +/** + * The type for the optional second argument to `import()`. + * + * If your host environment supports additional options, this type may be + * augmented via interface merging. + */ +interface ImportCallOptions { + assert?: ImportAssertions; +} + +/** + * The type for the `assert` property of the optional second argument to `import()`. + */ +interface ImportAssertions { + [key: string]: string; +} + +interface Math { + /** The mathematical constant e. This is Euler's number, the base of natural logarithms. */ + readonly E: number; + /** The natural logarithm of 10. */ + readonly LN10: number; + /** The natural logarithm of 2. */ + readonly LN2: number; + /** The base-2 logarithm of e. */ + readonly LOG2E: number; + /** The base-10 logarithm of e. */ + readonly LOG10E: number; + /** Pi. This is the ratio of the circumference of a circle to its diameter. */ + readonly PI: number; + /** The square root of 0.5, or, equivalently, one divided by the square root of 2. */ + readonly SQRT1_2: number; + /** The square root of 2. */ + readonly SQRT2: number; + /** + * Returns the absolute value of a number (the value without regard to whether it is positive or negative). + * For example, the absolute value of -5 is the same as the absolute value of 5. + * @param x A numeric expression for which the absolute value is needed. + */ + abs(x: number): number; + /** + * Returns the arc cosine (or inverse cosine) of a number. + * @param x A numeric expression. + */ + acos(x: number): number; + /** + * Returns the arcsine of a number. + * @param x A numeric expression. + */ + asin(x: number): number; + /** + * Returns the arctangent of a number. + * @param x A numeric expression for which the arctangent is needed. + */ + atan(x: number): number; + /** + * Returns the angle (in radians) from the X axis to a point. + * @param y A numeric expression representing the cartesian y-coordinate. + * @param x A numeric expression representing the cartesian x-coordinate. + */ + atan2(y: number, x: number): number; + /** + * Returns the smallest integer greater than or equal to its numeric argument. + * @param x A numeric expression. + */ + ceil(x: number): number; + /** + * Returns the cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + cos(x: number): number; + /** + * Returns e (the base of natural logarithms) raised to a power. + * @param x A numeric expression representing the power of e. + */ + exp(x: number): number; + /** + * Returns the greatest integer less than or equal to its numeric argument. + * @param x A numeric expression. + */ + floor(x: number): number; + /** + * Returns the natural logarithm (base e) of a number. + * @param x A numeric expression. + */ + log(x: number): number; + /** + * Returns the larger of a set of supplied numeric expressions. + * @param values Numeric expressions to be evaluated. + */ + max(...values: number[]): number; + /** + * Returns the smaller of a set of supplied numeric expressions. + * @param values Numeric expressions to be evaluated. + */ + min(...values: number[]): number; + /** + * Returns the value of a base expression taken to a specified power. + * @param x The base value of the expression. + * @param y The exponent value of the expression. + */ + pow(x: number, y: number): number; + /** Returns a pseudorandom number between 0 and 1. */ + random(): number; + /** + * Returns a supplied numeric expression rounded to the nearest integer. + * @param x The value to be rounded to the nearest integer. + */ + round(x: number): number; + /** + * Returns the sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + sin(x: number): number; + /** + * Returns the square root of a number. + * @param x A numeric expression. + */ + sqrt(x: number): number; + /** + * Returns the tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + tan(x: number): number; +} +/** An intrinsic object that provides basic mathematics functionality and constants. */ +declare var Math: Math; + +/** Enables basic storage and retrieval of dates and times. */ +interface Date { + /** Returns a string representation of a date. The format of the string depends on the locale. */ + toString(): string; + /** Returns a date as a string value. */ + toDateString(): string; + /** Returns a time as a string value. */ + toTimeString(): string; + /** Returns a value as a string value appropriate to the host environment's current locale. */ + toLocaleString(): string; + /** Returns a date as a string value appropriate to the host environment's current locale. */ + toLocaleDateString(): string; + /** Returns a time as a string value appropriate to the host environment's current locale. */ + toLocaleTimeString(): string; + /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */ + valueOf(): number; + /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */ + getTime(): number; + /** Gets the year, using local time. */ + getFullYear(): number; + /** Gets the year using Universal Coordinated Time (UTC). */ + getUTCFullYear(): number; + /** Gets the month, using local time. */ + getMonth(): number; + /** Gets the month of a Date object using Universal Coordinated Time (UTC). */ + getUTCMonth(): number; + /** Gets the day-of-the-month, using local time. */ + getDate(): number; + /** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */ + getUTCDate(): number; + /** Gets the day of the week, using local time. */ + getDay(): number; + /** Gets the day of the week using Universal Coordinated Time (UTC). */ + getUTCDay(): number; + /** Gets the hours in a date, using local time. */ + getHours(): number; + /** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */ + getUTCHours(): number; + /** Gets the minutes of a Date object, using local time. */ + getMinutes(): number; + /** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */ + getUTCMinutes(): number; + /** Gets the seconds of a Date object, using local time. */ + getSeconds(): number; + /** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */ + getUTCSeconds(): number; + /** Gets the milliseconds of a Date, using local time. */ + getMilliseconds(): number; + /** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */ + getUTCMilliseconds(): number; + /** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */ + getTimezoneOffset(): number; + /** + * Sets the date and time value in the Date object. + * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT. + */ + setTime(time: number): number; + /** + * Sets the milliseconds value in the Date object using local time. + * @param ms A numeric value equal to the millisecond value. + */ + setMilliseconds(ms: number): number; + /** + * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC). + * @param ms A numeric value equal to the millisecond value. + */ + setUTCMilliseconds(ms: number): number; + + /** + * Sets the seconds value in the Date object using local time. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setSeconds(sec: number, ms?: number): number; + /** + * Sets the seconds value in the Date object using Universal Coordinated Time (UTC). + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCSeconds(sec: number, ms?: number): number; + /** + * Sets the minutes value in the Date object using local time. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setMinutes(min: number, sec?: number, ms?: number): number; + /** + * Sets the minutes value in the Date object using Universal Coordinated Time (UTC). + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCMinutes(min: number, sec?: number, ms?: number): number; + /** + * Sets the hour value in the Date object using local time. + * @param hours A numeric value equal to the hours value. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setHours(hours: number, min?: number, sec?: number, ms?: number): number; + /** + * Sets the hours value in the Date object using Universal Coordinated Time (UTC). + * @param hours A numeric value equal to the hours value. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number; + /** + * Sets the numeric day-of-the-month value of the Date object using local time. + * @param date A numeric value equal to the day of the month. + */ + setDate(date: number): number; + /** + * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC). + * @param date A numeric value equal to the day of the month. + */ + setUTCDate(date: number): number; + /** + * Sets the month value in the Date object using local time. + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. + * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used. + */ + setMonth(month: number, date?: number): number; + /** + * Sets the month value in the Date object using Universal Coordinated Time (UTC). + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. + * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used. + */ + setUTCMonth(month: number, date?: number): number; + /** + * Sets the year of the Date object using local time. + * @param year A numeric value for the year. + * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified. + * @param date A numeric value equal for the day of the month. + */ + setFullYear(year: number, month?: number, date?: number): number; + /** + * Sets the year value in the Date object using Universal Coordinated Time (UTC). + * @param year A numeric value equal to the year. + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied. + * @param date A numeric value equal to the day of the month. + */ + setUTCFullYear(year: number, month?: number, date?: number): number; + /** Returns a date converted to a string using Universal Coordinated Time (UTC). */ + toUTCString(): string; + /** Returns a date as a string value in ISO format. */ + toISOString(): string; + /** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */ + toJSON(key?: any): string; +} + +interface DateConstructor { + new(): Date; + new(value: number | string): Date; + /** + * Creates a new Date. + * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year. + * @param monthIndex The month as a number between 0 and 11 (January to December). + * @param date The date as a number between 1 and 31. + * @param hours Must be supplied if minutes is supplied. A number from 0 to 23 (midnight to 11pm) that specifies the hour. + * @param minutes Must be supplied if seconds is supplied. A number from 0 to 59 that specifies the minutes. + * @param seconds Must be supplied if milliseconds is supplied. A number from 0 to 59 that specifies the seconds. + * @param ms A number from 0 to 999 that specifies the milliseconds. + */ + new(year: number, monthIndex: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; + (): string; + readonly prototype: Date; + /** + * Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970. + * @param s A date string + */ + parse(s: string): number; + /** + * Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date. + * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year. + * @param monthIndex The month as a number between 0 and 11 (January to December). + * @param date The date as a number between 1 and 31. + * @param hours Must be supplied if minutes is supplied. A number from 0 to 23 (midnight to 11pm) that specifies the hour. + * @param minutes Must be supplied if seconds is supplied. A number from 0 to 59 that specifies the minutes. + * @param seconds Must be supplied if milliseconds is supplied. A number from 0 to 59 that specifies the seconds. + * @param ms A number from 0 to 999 that specifies the milliseconds. + */ + UTC(year: number, monthIndex: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number; + /** Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC). */ + now(): number; +} + +declare var Date: DateConstructor; + +interface RegExpMatchArray extends Array { + /** + * The index of the search at which the result was found. + */ + index?: number; + /** + * A copy of the search string. + */ + input?: string; + /** + * The first match. This will always be present because `null` will be returned if there are no matches. + */ + 0: string; +} + +interface RegExpExecArray extends Array { + /** + * The index of the search at which the result was found. + */ + index: number; + /** + * A copy of the search string. + */ + input: string; + /** + * The first match. This will always be present because `null` will be returned if there are no matches. + */ + 0: string; +} + +interface RegExp { + /** + * Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search. + * @param string The String object or string literal on which to perform the search. + */ + exec(string: string): RegExpExecArray | null; + + /** + * Returns a Boolean value that indicates whether or not a pattern exists in a searched string. + * @param string String on which to perform the search. + */ + test(string: string): boolean; + + /** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */ + readonly source: string; + + /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */ + readonly global: boolean; + + /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */ + readonly ignoreCase: boolean; + + /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */ + readonly multiline: boolean; + + lastIndex: number; + + // Non-standard extensions + /** @deprecated A legacy feature for browser compatibility */ + compile(pattern: string, flags?: string): this; +} + + +interface RegExpConstructor { + new(pattern: RegExp | string): RegExp; + new(pattern: string, flags?: string): RegExp; + (pattern: RegExp | string): RegExp; + (pattern: string, flags?: string): RegExp; + readonly prototype: RegExp; + + // Non-standard extensions + /** @deprecated A legacy feature for browser compatibility */ + $1: string; + /** @deprecated A legacy feature for browser compatibility */ + $2: string; + /** @deprecated A legacy feature for browser compatibility */ + $3: string; + /** @deprecated A legacy feature for browser compatibility */ + $4: string; + /** @deprecated A legacy feature for browser compatibility */ + $5: string; + /** @deprecated A legacy feature for browser compatibility */ + $6: string; + /** @deprecated A legacy feature for browser compatibility */ + $7: string; + /** @deprecated A legacy feature for browser compatibility */ + $8: string; + /** @deprecated A legacy feature for browser compatibility */ + $9: string; + /** @deprecated A legacy feature for browser compatibility */ + input: string; + /** @deprecated A legacy feature for browser compatibility */ + $_: string; + /** @deprecated A legacy feature for browser compatibility */ + lastMatch: string; + /** @deprecated A legacy feature for browser compatibility */ + "$&": string; + /** @deprecated A legacy feature for browser compatibility */ + lastParen: string; + /** @deprecated A legacy feature for browser compatibility */ + "$+": string; + /** @deprecated A legacy feature for browser compatibility */ + leftContext: string; + /** @deprecated A legacy feature for browser compatibility */ + "$`": string; + /** @deprecated A legacy feature for browser compatibility */ + rightContext: string; + /** @deprecated A legacy feature for browser compatibility */ + "$'": string; +} + +declare var RegExp: RegExpConstructor; + +interface Error { + name: string; + message: string; + stack?: string; +} + +interface ErrorConstructor { + new(message?: string): Error; + (message?: string): Error; + readonly prototype: Error; +} + +declare var Error: ErrorConstructor; + +interface EvalError extends Error { +} + +interface EvalErrorConstructor extends ErrorConstructor { + new(message?: string): EvalError; + (message?: string): EvalError; + readonly prototype: EvalError; +} + +declare var EvalError: EvalErrorConstructor; + +interface RangeError extends Error { +} + +interface RangeErrorConstructor extends ErrorConstructor { + new(message?: string): RangeError; + (message?: string): RangeError; + readonly prototype: RangeError; +} + +declare var RangeError: RangeErrorConstructor; + +interface ReferenceError extends Error { +} + +interface ReferenceErrorConstructor extends ErrorConstructor { + new(message?: string): ReferenceError; + (message?: string): ReferenceError; + readonly prototype: ReferenceError; +} + +declare var ReferenceError: ReferenceErrorConstructor; + +interface SyntaxError extends Error { +} + +interface SyntaxErrorConstructor extends ErrorConstructor { + new(message?: string): SyntaxError; + (message?: string): SyntaxError; + readonly prototype: SyntaxError; +} + +declare var SyntaxError: SyntaxErrorConstructor; + +interface TypeError extends Error { +} + +interface TypeErrorConstructor extends ErrorConstructor { + new(message?: string): TypeError; + (message?: string): TypeError; + readonly prototype: TypeError; +} + +declare var TypeError: TypeErrorConstructor; + +interface URIError extends Error { +} + +interface URIErrorConstructor extends ErrorConstructor { + new(message?: string): URIError; + (message?: string): URIError; + readonly prototype: URIError; +} + +declare var URIError: URIErrorConstructor; + +interface JSON { + /** + * Converts a JavaScript Object Notation (JSON) string into an object. + * @param text A valid JSON string. + * @param reviver A function that transforms the results. This function is called for each member of the object. + * If a member contains nested objects, the nested objects are transformed before the parent object is. + */ + parse(text: string, reviver?: (this: any, key: string, value: any) => any): any; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer A function that transforms the results. + * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. + */ + stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer An array of strings and numbers that acts as an approved list for selecting the object properties that will be stringified. + * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. + */ + stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string; +} + +/** + * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format. + */ +declare var JSON: JSON; + + +///////////////////////////// +/// ECMAScript Array API (specially handled by compiler) +///////////////////////////// + +interface ReadonlyArray { + /** + * Gets the length of the array. This is a number one higher than the highest element defined in an array. + */ + readonly length: number; + /** + * Returns a string representation of an array. + */ + toString(): string; + /** + * Returns a string representation of an array. The elements are converted to string using their toLocaleString methods. + */ + toLocaleString(): string; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: ConcatArray[]): T[]; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: (T | ConcatArray)[]): T[]; + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. + */ + slice(start?: number, end?: number): T[]; + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + */ + indexOf(searchElement: T, fromIndex?: number): number; + /** + * Returns the index of the last occurrence of a specified value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. + */ + lastIndexOf(searchElement: T, fromIndex?: number): number; + /** + * Determines whether all the members of an array satisfy the specified test. + * @param predicate A function that accepts up to three arguments. The every method calls + * the predicate function for each element in the array until the predicate returns a value + * which is coercible to the Boolean value false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(predicate: (value: T, index: number, array: readonly T[]) => value is S, thisArg?: any): this is readonly S[]; + /** + * Determines whether all the members of an array satisfy the specified test. + * @param predicate A function that accepts up to three arguments. The every method calls + * the predicate function for each element in the array until the predicate returns a value + * which is coercible to the Boolean value false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): boolean; + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param predicate A function that accepts up to three arguments. The some method calls + * the predicate function for each element in the array until the predicate returns a value + * which is coercible to the Boolean value true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): boolean; + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: T, index: number, array: readonly T[]) => void, thisArg?: any): void; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: T, index: number, array: readonly T[]) => U, thisArg?: any): U[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value. + */ + filter(predicate: (value: T, index: number, array: readonly T[]) => value is S, thisArg?: any): S[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value. + */ + filter(predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): T[]; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T): T; + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T, initialValue: T): T; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: readonly T[]) => U, initialValue: U): U; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T): T; + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T, initialValue: T): T; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: readonly T[]) => U, initialValue: U): U; + + readonly [n: number]: T; +} + +interface ConcatArray { + readonly length: number; + readonly [n: number]: T; + join(separator?: string): string; + slice(start?: number, end?: number): T[]; +} + +interface Array { + /** + * Gets or sets the length of the array. This is a number one higher than the highest index in the array. + */ + length: number; + /** + * Returns a string representation of an array. + */ + toString(): string; + /** + * Returns a string representation of an array. The elements are converted to string using their toLocaleString methods. + */ + toLocaleString(): string; + /** + * Removes the last element from an array and returns it. + * If the array is empty, undefined is returned and the array is not modified. + */ + pop(): T | undefined; + /** + * Appends new elements to the end of an array, and returns the new length of the array. + * @param items New elements to add to the array. + */ + push(...items: T[]): number; + /** + * Combines two or more arrays. + * This method returns a new array without modifying any existing arrays. + * @param items Additional arrays and/or items to add to the end of the array. + */ + concat(...items: ConcatArray[]): T[]; + /** + * Combines two or more arrays. + * This method returns a new array without modifying any existing arrays. + * @param items Additional arrays and/or items to add to the end of the array. + */ + concat(...items: (T | ConcatArray)[]): T[]; + /** + * Adds all the elements of an array into a string, separated by the specified separator string. + * @param separator A string used to separate one element of the array from the next in the resulting string. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + /** + * Reverses the elements in an array in place. + * This method mutates the array and returns a reference to the same array. + */ + reverse(): T[]; + /** + * Removes the first element from an array and returns it. + * If the array is empty, undefined is returned and the array is not modified. + */ + shift(): T | undefined; + /** + * Returns a copy of a section of an array. + * For both start and end, a negative index can be used to indicate an offset from the end of the array. + * For example, -2 refers to the second to last element of the array. + * @param start The beginning index of the specified portion of the array. + * If start is undefined, then the slice begins at index 0. + * @param end The end index of the specified portion of the array. This is exclusive of the element at the index 'end'. + * If end is undefined, then the slice extends to the end of the array. + */ + slice(start?: number, end?: number): T[]; + /** + * Sorts an array in place. + * This method mutates the array and returns a reference to the same array. + * @param compareFn Function used to determine the order of the elements. It is expected to return + * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive + * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. + * ```ts + * [11,2,22,1].sort((a, b) => a - b) + * ``` + */ + sort(compareFn?: (a: T, b: T) => number): this; + /** + * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the array from which to start removing elements. + * @param deleteCount The number of elements to remove. + * @returns An array containing the elements that were deleted. + */ + splice(start: number, deleteCount?: number): T[]; + /** + * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the array from which to start removing elements. + * @param deleteCount The number of elements to remove. + * @param items Elements to insert into the array in place of the deleted elements. + * @returns An array containing the elements that were deleted. + */ + splice(start: number, deleteCount: number, ...items: T[]): T[]; + /** + * Inserts new elements at the start of an array, and returns the new length of the array. + * @param items Elements to insert at the start of the array. + */ + unshift(...items: T[]): number; + /** + * Returns the index of the first occurrence of a value in an array, or -1 if it is not present. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + */ + indexOf(searchElement: T, fromIndex?: number): number; + /** + * Returns the index of the last occurrence of a specified value in an array, or -1 if it is not present. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin searching backward. If fromIndex is omitted, the search starts at the last index in the array. + */ + lastIndexOf(searchElement: T, fromIndex?: number): number; + /** + * Determines whether all the members of an array satisfy the specified test. + * @param predicate A function that accepts up to three arguments. The every method calls + * the predicate function for each element in the array until the predicate returns a value + * which is coercible to the Boolean value false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(predicate: (value: T, index: number, array: T[]) => value is S, thisArg?: any): this is S[]; + /** + * Determines whether all the members of an array satisfy the specified test. + * @param predicate A function that accepts up to three arguments. The every method calls + * the predicate function for each element in the array until the predicate returns a value + * which is coercible to the Boolean value false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): boolean; + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param predicate A function that accepts up to three arguments. The some method calls + * the predicate function for each element in the array until the predicate returns a value + * which is coercible to the Boolean value true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): boolean; + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value. + */ + filter(predicate: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value. + */ + filter(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): T[]; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T; + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T; + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + + [n: number]: T; +} + +interface ArrayConstructor { + new(arrayLength?: number): any[]; + new (arrayLength: number): T[]; + new (...items: T[]): T[]; + (arrayLength?: number): any[]; + (arrayLength: number): T[]; + (...items: T[]): T[]; + isArray(arg: any): arg is any[]; + readonly prototype: any[]; +} + +declare var Array: ArrayConstructor; + +interface TypedPropertyDescriptor { + enumerable?: boolean; + configurable?: boolean; + writable?: boolean; + value?: T; + get?: () => T; + set?: (value: T) => void; +} + +declare type PromiseConstructorLike = new (executor: (resolve: (value: T | PromiseLike) => void, reject: (reason?: any) => void) => void) => PromiseLike; + +interface PromiseLike { + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): PromiseLike; +} + +/** + * Represents the completion of an asynchronous operation + */ +interface Promise { + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): Promise; + + /** + * Attaches a callback for only the rejection of the Promise. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch(onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): Promise; +} + +/** + * Recursively unwraps the "awaited type" of a type. Non-promise "thenables" should resolve to `never`. This emulates the behavior of `await`. + */ +type Awaited = + T extends null | undefined ? T : // special case for `null | undefined` when not in `--strictNullChecks` mode + T extends object & { then(onfulfilled: infer F, ...args: infer _): any } ? // `await` only unwraps object types with a callable `then`. Non-object types are not unwrapped + F extends ((value: infer V, ...args: infer _) => any) ? // if the argument to `then` is callable, extracts the first argument + Awaited : // recursively unwrap the value + never : // the argument to `then` was not callable + T; // non-object or non-thenable + +interface ArrayLike { + readonly length: number; + readonly [n: number]: T; +} + +/** + * Make all properties in T optional + */ +type Partial = { + [P in keyof T]?: T[P]; +}; + +/** + * Make all properties in T required + */ +type Required = { + [P in keyof T]-?: T[P]; +}; + +/** + * Make all properties in T readonly + */ +type Readonly = { + readonly [P in keyof T]: T[P]; +}; + +/** + * From T, pick a set of properties whose keys are in the union K + */ +type Pick = { + [P in K]: T[P]; +}; + +/** + * Construct a type with a set of properties K of type T + */ +type Record = { + [P in K]: T; +}; + +/** + * Exclude from T those types that are assignable to U + */ +type Exclude = T extends U ? never : T; + +/** + * Extract from T those types that are assignable to U + */ +type Extract = T extends U ? T : never; + +/** + * Construct a type with the properties of T except for those in type K. + */ +type Omit = Pick>; + +/** + * Exclude null and undefined from T + */ +type NonNullable = T & {}; + +/** + * Obtain the parameters of a function type in a tuple + */ +type Parameters any> = T extends (...args: infer P) => any ? P : never; + +/** + * Obtain the parameters of a constructor function type in a tuple + */ +type ConstructorParameters any> = T extends abstract new (...args: infer P) => any ? P : never; + +/** + * Obtain the return type of a function type + */ +type ReturnType any> = T extends (...args: any) => infer R ? R : any; + +/** + * Obtain the return type of a constructor function type + */ +type InstanceType any> = T extends abstract new (...args: any) => infer R ? R : any; + +/** + * Convert string literal type to uppercase + */ +type Uppercase = intrinsic; + +/** + * Convert string literal type to lowercase + */ +type Lowercase = intrinsic; + +/** + * Convert first character of string literal type to uppercase + */ +type Capitalize = intrinsic; + +/** + * Convert first character of string literal type to lowercase + */ +type Uncapitalize = intrinsic; + +/** + * Marker for contextual 'this' type + */ +interface ThisType { } + +/** + * Represents a raw buffer of binary data, which is used to store data for the + * different typed arrays. ArrayBuffers cannot be read from or written to directly, + * but can be passed to a typed array or DataView Object to interpret the raw + * buffer as needed. + */ +interface ArrayBuffer { + /** + * Read-only. The length of the ArrayBuffer (in bytes). + */ + readonly byteLength: number; + + /** + * Returns a section of an ArrayBuffer. + */ + slice(begin: number, end?: number): ArrayBuffer; +} + +/** + * Allowed ArrayBuffer types for the buffer of an ArrayBufferView and related Typed Arrays. + */ +interface ArrayBufferTypes { + ArrayBuffer: ArrayBuffer; +} +type ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes]; + +interface ArrayBufferConstructor { + readonly prototype: ArrayBuffer; + new(byteLength: number): ArrayBuffer; + isView(arg: any): arg is ArrayBufferView; +} +declare var ArrayBuffer: ArrayBufferConstructor; + +interface ArrayBufferView { + /** + * The ArrayBuffer instance referenced by the array. + */ + buffer: ArrayBufferLike; + + /** + * The length in bytes of the array. + */ + byteLength: number; + + /** + * The offset in bytes of the array. + */ + byteOffset: number; +} + +interface DataView { + readonly buffer: ArrayBuffer; + readonly byteLength: number; + readonly byteOffset: number; + /** + * Gets the Float32 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + * @param littleEndian If false or undefined, a big-endian value should be read. + */ + getFloat32(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Float64 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + * @param littleEndian If false or undefined, a big-endian value should be read. + */ + getFloat64(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Int8 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getInt8(byteOffset: number): number; + + /** + * Gets the Int16 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + * @param littleEndian If false or undefined, a big-endian value should be read. + */ + getInt16(byteOffset: number, littleEndian?: boolean): number; + /** + * Gets the Int32 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + * @param littleEndian If false or undefined, a big-endian value should be read. + */ + getInt32(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Uint8 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getUint8(byteOffset: number): number; + + /** + * Gets the Uint16 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + * @param littleEndian If false or undefined, a big-endian value should be read. + */ + getUint16(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Uint32 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + * @param littleEndian If false or undefined, a big-endian value should be read. + */ + getUint32(byteOffset: number, littleEndian?: boolean): number; + + /** + * Stores an Float32 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written. + */ + setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Float64 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written. + */ + setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Int8 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + */ + setInt8(byteOffset: number, value: number): void; + + /** + * Stores an Int16 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written. + */ + setInt16(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Int32 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written. + */ + setInt32(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Uint8 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + */ + setUint8(byteOffset: number, value: number): void; + + /** + * Stores an Uint16 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written. + */ + setUint16(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Uint32 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written. + */ + setUint32(byteOffset: number, value: number, littleEndian?: boolean): void; +} + +interface DataViewConstructor { + readonly prototype: DataView; + new(buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView; +} +declare var DataView: DataViewConstructor; + +/** + * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Int8Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBufferLike; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. If start is omitted, `0` is used. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start?: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param predicate A function that accepts up to three arguments. The every method calls + * the predicate function for each element in the array until the predicate returns a value + * which is coercible to the Boolean value false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(predicate: (value: number, index: number, array: Int8Array) => unknown, thisArg?: any): boolean; + + /** + * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param predicate A function that accepts up to three arguments. The filter method calls + * the predicate function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(predicate: (value: number, index: number, array: Int8Array) => any, thisArg?: any): Int8Array; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Int8Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Int8Array; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. + */ + slice(start?: number, end?: number): Int8Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param predicate A function that accepts up to three arguments. The some method calls + * the predicate function for each element in the array until the predicate returns a value + * which is coercible to the Boolean value true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(predicate: (value: number, index: number, array: Int8Array) => unknown, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn Function used to determine the order of the elements. It is expected to return + * a negative value if first argument is less than second argument, zero if they're equal and a positive + * value otherwise. If omitted, the elements are sorted in ascending order. + * ```ts + * [11,2,22,1].sort((a, b) => a - b) + * ``` + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Int8Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin?: number, end?: number): Int8Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): Int8Array; + + [index: number]: number; +} +interface Int8ArrayConstructor { + readonly prototype: Int8Array; + new(length: number): Int8Array; + new(array: ArrayLike | ArrayBufferLike): Int8Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Int8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + */ + from(arrayLike: ArrayLike): Int8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Int8Array; + + +} +declare var Int8Array: Int8ArrayConstructor; + +/** + * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBufferLike; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. If start is omitted, `0` is used. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start?: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param predicate A function that accepts up to three arguments. The every method calls + * the predicate function for each element in the array until the predicate returns a value + * which is coercible to the Boolean value false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(predicate: (value: number, index: number, array: Uint8Array) => unknown, thisArg?: any): boolean; + + /** + * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param predicate A function that accepts up to three arguments. The filter method calls + * the predicate function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(predicate: (value: number, index: number, array: Uint8Array) => any, thisArg?: any): Uint8Array; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint8Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint8Array; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. + */ + slice(start?: number, end?: number): Uint8Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param predicate A function that accepts up to three arguments. The some method calls + * the predicate function for each element in the array until the predicate returns a value + * which is coercible to the Boolean value true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(predicate: (value: number, index: number, array: Uint8Array) => unknown, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn Function used to determine the order of the elements. It is expected to return + * a negative value if first argument is less than second argument, zero if they're equal and a positive + * value otherwise. If omitted, the elements are sorted in ascending order. + * ```ts + * [11,2,22,1].sort((a, b) => a - b) + * ``` + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin?: number, end?: number): Uint8Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): Uint8Array; + + [index: number]: number; +} + +interface Uint8ArrayConstructor { + readonly prototype: Uint8Array; + new(length: number): Uint8Array; + new(array: ArrayLike | ArrayBufferLike): Uint8Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + */ + from(arrayLike: ArrayLike): Uint8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Uint8Array; + +} +declare var Uint8Array: Uint8ArrayConstructor; + +/** + * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. + * If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8ClampedArray { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBufferLike; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. If start is omitted, `0` is used. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start?: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param predicate A function that accepts up to three arguments. The every method calls + * the predicate function for each element in the array until the predicate returns a value + * which is coercible to the Boolean value false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(predicate: (value: number, index: number, array: Uint8ClampedArray) => unknown, thisArg?: any): boolean; + + /** + * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param predicate A function that accepts up to three arguments. The filter method calls + * the predicate function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(predicate: (value: number, index: number, array: Uint8ClampedArray) => any, thisArg?: any): Uint8ClampedArray; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint8ClampedArray; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. + */ + slice(start?: number, end?: number): Uint8ClampedArray; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param predicate A function that accepts up to three arguments. The some method calls + * the predicate function for each element in the array until the predicate returns a value + * which is coercible to the Boolean value true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(predicate: (value: number, index: number, array: Uint8ClampedArray) => unknown, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn Function used to determine the order of the elements. It is expected to return + * a negative value if first argument is less than second argument, zero if they're equal and a positive + * value otherwise. If omitted, the elements are sorted in ascending order. + * ```ts + * [11,2,22,1].sort((a, b) => a - b) + * ``` + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Uint8ClampedArray view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin?: number, end?: number): Uint8ClampedArray; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): Uint8ClampedArray; + + [index: number]: number; +} + +interface Uint8ClampedArrayConstructor { + readonly prototype: Uint8ClampedArray; + new(length: number): Uint8ClampedArray; + new(array: ArrayLike | ArrayBufferLike): Uint8ClampedArray; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint8ClampedArray; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + */ + from(arrayLike: ArrayLike): Uint8ClampedArray; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Uint8ClampedArray; +} +declare var Uint8ClampedArray: Uint8ClampedArrayConstructor; + +/** + * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int16Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBufferLike; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. If start is omitted, `0` is used. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start?: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param predicate A function that accepts up to three arguments. The every method calls + * the predicate function for each element in the array until the predicate returns a value + * which is coercible to the Boolean value false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(predicate: (value: number, index: number, array: Int16Array) => unknown, thisArg?: any): boolean; + + /** + * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param predicate A function that accepts up to three arguments. The filter method calls + * the predicate function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(predicate: (value: number, index: number, array: Int16Array) => any, thisArg?: any): Int16Array; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: number, index: number, obj: Int16Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: number, index: number, obj: Int16Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Int16Array) => void, thisArg?: any): void; + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Int16Array; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. + */ + slice(start?: number, end?: number): Int16Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param predicate A function that accepts up to three arguments. The some method calls + * the predicate function for each element in the array until the predicate returns a value + * which is coercible to the Boolean value true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(predicate: (value: number, index: number, array: Int16Array) => unknown, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn Function used to determine the order of the elements. It is expected to return + * a negative value if first argument is less than second argument, zero if they're equal and a positive + * value otherwise. If omitted, the elements are sorted in ascending order. + * ```ts + * [11,2,22,1].sort((a, b) => a - b) + * ``` + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Int16Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin?: number, end?: number): Int16Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): Int16Array; + + [index: number]: number; +} + +interface Int16ArrayConstructor { + readonly prototype: Int16Array; + new(length: number): Int16Array; + new(array: ArrayLike | ArrayBufferLike): Int16Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Int16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + */ + from(arrayLike: ArrayLike): Int16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Int16Array; + + +} +declare var Int16Array: Int16ArrayConstructor; + +/** + * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint16Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBufferLike; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. If start is omitted, `0` is used. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start?: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param predicate A function that accepts up to three arguments. The every method calls + * the predicate function for each element in the array until the predicate returns a value + * which is coercible to the Boolean value false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(predicate: (value: number, index: number, array: Uint16Array) => unknown, thisArg?: any): boolean; + + /** + * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param predicate A function that accepts up to three arguments. The filter method calls + * the predicate function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(predicate: (value: number, index: number, array: Uint16Array) => any, thisArg?: any): Uint16Array; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: number, index: number, obj: Uint16Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: number, index: number, obj: Uint16Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint16Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint16Array; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. + */ + slice(start?: number, end?: number): Uint16Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param predicate A function that accepts up to three arguments. The some method calls + * the predicate function for each element in the array until the predicate returns a value + * which is coercible to the Boolean value true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(predicate: (value: number, index: number, array: Uint16Array) => unknown, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn Function used to determine the order of the elements. It is expected to return + * a negative value if first argument is less than second argument, zero if they're equal and a positive + * value otherwise. If omitted, the elements are sorted in ascending order. + * ```ts + * [11,2,22,1].sort((a, b) => a - b) + * ``` + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Uint16Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin?: number, end?: number): Uint16Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): Uint16Array; + + [index: number]: number; +} + +interface Uint16ArrayConstructor { + readonly prototype: Uint16Array; + new(length: number): Uint16Array; + new(array: ArrayLike | ArrayBufferLike): Uint16Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + */ + from(arrayLike: ArrayLike): Uint16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Uint16Array; + + +} +declare var Uint16Array: Uint16ArrayConstructor; + +/** + * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int32Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBufferLike; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. If start is omitted, `0` is used. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start?: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param predicate A function that accepts up to three arguments. The every method calls + * the predicate function for each element in the array until the predicate returns a value + * which is coercible to the Boolean value false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(predicate: (value: number, index: number, array: Int32Array) => unknown, thisArg?: any): boolean; + + /** + * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param predicate A function that accepts up to three arguments. The filter method calls + * the predicate function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(predicate: (value: number, index: number, array: Int32Array) => any, thisArg?: any): Int32Array; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: number, index: number, obj: Int32Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: number, index: number, obj: Int32Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Int32Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Int32Array) => number, thisArg?: any): Int32Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Int32Array; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. + */ + slice(start?: number, end?: number): Int32Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param predicate A function that accepts up to three arguments. The some method calls + * the predicate function for each element in the array until the predicate returns a value + * which is coercible to the Boolean value true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(predicate: (value: number, index: number, array: Int32Array) => unknown, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn Function used to determine the order of the elements. It is expected to return + * a negative value if first argument is less than second argument, zero if they're equal and a positive + * value otherwise. If omitted, the elements are sorted in ascending order. + * ```ts + * [11,2,22,1].sort((a, b) => a - b) + * ``` + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Int32Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin?: number, end?: number): Int32Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): Int32Array; + + [index: number]: number; +} + +interface Int32ArrayConstructor { + readonly prototype: Int32Array; + new(length: number): Int32Array; + new(array: ArrayLike | ArrayBufferLike): Int32Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Int32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + */ + from(arrayLike: ArrayLike): Int32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Int32Array; + +} +declare var Int32Array: Int32ArrayConstructor; + +/** + * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint32Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBufferLike; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. If start is omitted, `0` is used. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start?: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param predicate A function that accepts up to three arguments. The every method calls + * the predicate function for each element in the array until the predicate returns a value + * which is coercible to the Boolean value false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(predicate: (value: number, index: number, array: Uint32Array) => unknown, thisArg?: any): boolean; + + /** + * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param predicate A function that accepts up to three arguments. The filter method calls + * the predicate function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(predicate: (value: number, index: number, array: Uint32Array) => any, thisArg?: any): Uint32Array; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: number, index: number, obj: Uint32Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: number, index: number, obj: Uint32Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint32Array) => void, thisArg?: any): void; + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint32Array; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. + */ + slice(start?: number, end?: number): Uint32Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param predicate A function that accepts up to three arguments. The some method calls + * the predicate function for each element in the array until the predicate returns a value + * which is coercible to the Boolean value true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(predicate: (value: number, index: number, array: Uint32Array) => unknown, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn Function used to determine the order of the elements. It is expected to return + * a negative value if first argument is less than second argument, zero if they're equal and a positive + * value otherwise. If omitted, the elements are sorted in ascending order. + * ```ts + * [11,2,22,1].sort((a, b) => a - b) + * ``` + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Uint32Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin?: number, end?: number): Uint32Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): Uint32Array; + + [index: number]: number; +} + +interface Uint32ArrayConstructor { + readonly prototype: Uint32Array; + new(length: number): Uint32Array; + new(array: ArrayLike | ArrayBufferLike): Uint32Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + */ + from(arrayLike: ArrayLike): Uint32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Uint32Array; + +} +declare var Uint32Array: Uint32ArrayConstructor; + +/** + * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number + * of bytes could not be allocated an exception is raised. + */ +interface Float32Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBufferLike; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. If start is omitted, `0` is used. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start?: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param predicate A function that accepts up to three arguments. The every method calls + * the predicate function for each element in the array until the predicate returns a value + * which is coercible to the Boolean value false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(predicate: (value: number, index: number, array: Float32Array) => unknown, thisArg?: any): boolean; + + /** + * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param predicate A function that accepts up to three arguments. The filter method calls + * the predicate function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(predicate: (value: number, index: number, array: Float32Array) => any, thisArg?: any): Float32Array; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: number, index: number, obj: Float32Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: number, index: number, obj: Float32Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Float32Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Float32Array; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. + */ + slice(start?: number, end?: number): Float32Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param predicate A function that accepts up to three arguments. The some method calls + * the predicate function for each element in the array until the predicate returns a value + * which is coercible to the Boolean value true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(predicate: (value: number, index: number, array: Float32Array) => unknown, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn Function used to determine the order of the elements. It is expected to return + * a negative value if first argument is less than second argument, zero if they're equal and a positive + * value otherwise. If omitted, the elements are sorted in ascending order. + * ```ts + * [11,2,22,1].sort((a, b) => a - b) + * ``` + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Float32Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin?: number, end?: number): Float32Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): Float32Array; + + [index: number]: number; +} + +interface Float32ArrayConstructor { + readonly prototype: Float32Array; + new(length: number): Float32Array; + new(array: ArrayLike | ArrayBufferLike): Float32Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Float32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + */ + from(arrayLike: ArrayLike): Float32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Float32Array; + + +} +declare var Float32Array: Float32ArrayConstructor; + +/** + * A typed array of 64-bit float values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Float64Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBufferLike; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. If start is omitted, `0` is used. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start?: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param predicate A function that accepts up to three arguments. The every method calls + * the predicate function for each element in the array until the predicate returns a value + * which is coercible to the Boolean value false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(predicate: (value: number, index: number, array: Float64Array) => unknown, thisArg?: any): boolean; + + /** + * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param predicate A function that accepts up to three arguments. The filter method calls + * the predicate function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(predicate: (value: number, index: number, array: Float64Array) => any, thisArg?: any): Float64Array; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: number, index: number, obj: Float64Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: number, index: number, obj: Float64Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Float64Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Float64Array; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. + */ + slice(start?: number, end?: number): Float64Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param predicate A function that accepts up to three arguments. The some method calls + * the predicate function for each element in the array until the predicate returns a value + * which is coercible to the Boolean value true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the predicate function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(predicate: (value: number, index: number, array: Float64Array) => unknown, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn Function used to determine the order of the elements. It is expected to return + * a negative value if first argument is less than second argument, zero if they're equal and a positive + * value otherwise. If omitted, the elements are sorted in ascending order. + * ```ts + * [11,2,22,1].sort((a, b) => a - b) + * ``` + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin?: number, end?: number): Float64Array; + + toString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): Float64Array; + + [index: number]: number; +} + +interface Float64ArrayConstructor { + readonly prototype: Float64Array; + new(length: number): Float64Array; + new(array: ArrayLike | ArrayBufferLike): Float64Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Float64Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + */ + from(arrayLike: ArrayLike): Float64Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Float64Array; + +} +declare var Float64Array: Float64ArrayConstructor; + +///////////////////////////// +/// ECMAScript Internationalization API +///////////////////////////// + +declare namespace Intl { + interface CollatorOptions { + usage?: string | undefined; + localeMatcher?: string | undefined; + numeric?: boolean | undefined; + caseFirst?: string | undefined; + sensitivity?: string | undefined; + ignorePunctuation?: boolean | undefined; + } + + interface ResolvedCollatorOptions { + locale: string; + usage: string; + sensitivity: string; + ignorePunctuation: boolean; + collation: string; + caseFirst: string; + numeric: boolean; + } + + interface Collator { + compare(x: string, y: string): number; + resolvedOptions(): ResolvedCollatorOptions; + } + var Collator: { + new(locales?: string | string[], options?: CollatorOptions): Collator; + (locales?: string | string[], options?: CollatorOptions): Collator; + supportedLocalesOf(locales: string | string[], options?: CollatorOptions): string[]; + }; + + interface NumberFormatOptions { + localeMatcher?: string | undefined; + style?: string | undefined; + currency?: string | undefined; + currencySign?: string | undefined; + useGrouping?: boolean | undefined; + minimumIntegerDigits?: number | undefined; + minimumFractionDigits?: number | undefined; + maximumFractionDigits?: number | undefined; + minimumSignificantDigits?: number | undefined; + maximumSignificantDigits?: number | undefined; + } + + interface ResolvedNumberFormatOptions { + locale: string; + numberingSystem: string; + style: string; + currency?: string; + minimumIntegerDigits: number; + minimumFractionDigits: number; + maximumFractionDigits: number; + minimumSignificantDigits?: number; + maximumSignificantDigits?: number; + useGrouping: boolean; + } + + interface NumberFormat { + format(value: number): string; + resolvedOptions(): ResolvedNumberFormatOptions; + } + var NumberFormat: { + new(locales?: string | string[], options?: NumberFormatOptions): NumberFormat; + (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; + supportedLocalesOf(locales: string | string[], options?: NumberFormatOptions): string[]; + readonly prototype: NumberFormat; + }; + + interface DateTimeFormatOptions { + localeMatcher?: "best fit" | "lookup" | undefined; + weekday?: "long" | "short" | "narrow" | undefined; + era?: "long" | "short" | "narrow" | undefined; + year?: "numeric" | "2-digit" | undefined; + month?: "numeric" | "2-digit" | "long" | "short" | "narrow" | undefined; + day?: "numeric" | "2-digit" | undefined; + hour?: "numeric" | "2-digit" | undefined; + minute?: "numeric" | "2-digit" | undefined; + second?: "numeric" | "2-digit" | undefined; + timeZoneName?: "short" | "long" | "shortOffset" | "longOffset" | "shortGeneric" | "longGeneric" | undefined; + formatMatcher?: "best fit" | "basic" | undefined; + hour12?: boolean | undefined; + timeZone?: string | undefined; + } + + interface ResolvedDateTimeFormatOptions { + locale: string; + calendar: string; + numberingSystem: string; + timeZone: string; + hour12?: boolean; + weekday?: string; + era?: string; + year?: string; + month?: string; + day?: string; + hour?: string; + minute?: string; + second?: string; + timeZoneName?: string; + } + + interface DateTimeFormat { + format(date?: Date | number): string; + resolvedOptions(): ResolvedDateTimeFormatOptions; + } + var DateTimeFormat: { + new(locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; + (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; + supportedLocalesOf(locales: string | string[], options?: DateTimeFormatOptions): string[]; + readonly prototype: DateTimeFormat; + }; +} diff --git a/ts2mls/js/src/test/typescript/Escape.ts b/ts2mls/js/src/test/typescript/Escape.ts new file mode 100644 index 000000000..5a139c20c --- /dev/null +++ b/ts2mls/js/src/test/typescript/Escape.ts @@ -0,0 +1,15 @@ +class fun { + rec = 42 +} +interface rec { + fun: string +} + +function mixin(module: string) { +} + +const forall = 42 + +namespace trait { + namespace of {} +} diff --git a/ts2mls/js/src/test/typescript/Export.ts b/ts2mls/js/src/test/typescript/Export.ts new file mode 100644 index 000000000..e150754c0 --- /dev/null +++ b/ts2mls/js/src/test/typescript/Export.ts @@ -0,0 +1,29 @@ +export namespace Foo { + interface IBar { + a: string + } + + export class Bar implements IBar { + a = "bar" + } + + export function Baz(aa: string): IBar { + return { + a: aa + } + } + + export const baz = Baz("baz") +} + +export default function id(x) { + return x; +} + +class E {} + +export { E } +export { E as F } +export { B as G } from "./Dependency" +export * as H from "./Dependency" + diff --git a/ts2mls/js/src/test/typescript/Heritage.ts b/ts2mls/js/src/test/typescript/Heritage.ts index a4d8386fe..c931e4811 100644 --- a/ts2mls/js/src/test/typescript/Heritage.ts +++ b/ts2mls/js/src/test/typescript/Heritage.ts @@ -1,65 +1,65 @@ -class A { - constructor() {} +// class A { +// constructor() {} - foo() { - console.log("foo") - } -} +// foo() { +// console.log("foo") +// } +// } -class B extends A {} +// class B extends A {} -class C { - constructor() {} +// class C { +// constructor() {} - private t: T +// private t: T - set(x: T) { this.t = x; } - get() { return this.t; } -} +// set(x: T) { this.t = x; } +// get() { return this.t; } +// } -class D extends C { -} +// class D extends C { +// } -interface Wu { - x: boolean -} +// interface Wu { +// x: boolean +// } -class WuWu extends Wu { - y: boolean -} +// class WuWu extends Wu { +// y: boolean +// } -interface WuWuWu extends WuWu { - z: boolean -} +// interface WuWuWu extends WuWu { +// z: boolean +// } -interface Never extends WuWuWu { - w: () => never -} +// interface Never extends WuWuWu { +// w: () => never +// } -class VG { - x: T -} +// class VG { +// x: T +// } -class Home extends VG { - y: T -} +// class Home extends VG { +// y: T +// } -interface O { - xx: (x: I) => I -} +// interface O { +// xx: (x: I) => I +// } -class OR implements O { - xx(x: R): R { - return x; - } -} +// class OR implements O { +// xx(x: R): R { +// return x; +// } +// } namespace Five { export class ROTK { wu: string } - export class Y extends Five.ROTK {} + // export class Y extends Five.ROTK {} } class Y extends Five.ROTK {} diff --git a/ts2mls/js/src/test/typescript/Import.ts b/ts2mls/js/src/test/typescript/Import.ts new file mode 100644 index 000000000..bc3a66c83 --- /dev/null +++ b/ts2mls/js/src/test/typescript/Import.ts @@ -0,0 +1,15 @@ +import "./Dependency" +import f from "./Dependency" +import { A } from "./Dependency" +import { B as BB } from "./Dependency" +import * as D from "./Dependency" +import type { C as CC } from "./Dependency" + + +const t = f(); + +const a = new A(); +const b = new BB(); +let c: CC +const d = new D.D(); +const dd = D.default(); diff --git a/ts2mls/js/src/test/typescript/Multi1.ts b/ts2mls/js/src/test/typescript/Multi1.ts deleted file mode 100644 index d36fc248b..000000000 --- a/ts2mls/js/src/test/typescript/Multi1.ts +++ /dev/null @@ -1,15 +0,0 @@ -function multi1(x: number) { - return x; -} - -function multi3() {} - -class Foo extends Base {} - -interface AnotherBase { - y: string -} - -namespace N { - export function f() {} -} diff --git a/ts2mls/js/src/test/typescript/Multi2.ts b/ts2mls/js/src/test/typescript/Multi2.ts deleted file mode 100644 index 2a8ce088c..000000000 --- a/ts2mls/js/src/test/typescript/Multi2.ts +++ /dev/null @@ -1,17 +0,0 @@ -function multi2(x: string) { - return x; -} - -function multi4() { - multi3() -} - -interface Base { - a: number -} - -class AnotherFoo extends AnotherBase {} - -namespace N { - export function g() {} -} diff --git a/ts2mls/js/src/test/typescript/Multi3.ts b/ts2mls/js/src/test/typescript/Multi3.ts deleted file mode 100644 index 0807a9fcc..000000000 --- a/ts2mls/js/src/test/typescript/Multi3.ts +++ /dev/null @@ -1,7 +0,0 @@ -function multi5() { - console.log("wuwuwu") -} - -namespace N { - export function h() {} -} diff --git a/ts2mls/js/src/test/typescript/Overload.ts b/ts2mls/js/src/test/typescript/Overload.ts index d0c26274b..fc4b0dd12 100644 --- a/ts2mls/js/src/test/typescript/Overload.ts +++ b/ts2mls/js/src/test/typescript/Overload.ts @@ -10,7 +10,7 @@ class M { foo(x: number): string; foo(x: string): string; - foo(x) { + foo(x): string { return x.toString(); } } @@ -25,21 +25,21 @@ function app(f, x): void { function create(x: number): () => boolean; function create(x: boolean): () => boolean; -function create(x) { +function create(x): () => boolean { return function() { return x == 0; } } function g0(x: string[]): string; function g0(x: object[]): string; -function g0(x) { +function g0(x): string { return x[0].toString(); } function db(x: number): number[]; function db(x: object): number[]; -function db(x) { +function db(x): number[] { return [0, 1]; } @@ -53,16 +53,16 @@ function id(x) {} function tst(x: {z: number}): {y: string}; function tst(x: {z: boolean}): {y: string}; -function tst(x) { +function tst(x): {y: string} { return {y: x.z.toString()} } function op(x: number, y?: number): void; function op(x: number, y?: boolean): void; -function op(x, y) {} +function op(x, y): void {} -function swap(x: [number, string]): [number, string]; +function swap(x: [number, string]): [string, number]; function swap(x: [string, number]): [number, string]; function swap(x) { @@ -72,14 +72,14 @@ function swap(x) { function u(x: number | boolean): string; function u(x: object): string; -function u(x) { +function u(x): string { return x.toString(); } function doSome(x: T & U): never; function doSome(x: string): never; -function doSome(x) { +function doSome(x): never { while (true); } @@ -87,7 +87,7 @@ namespace XX { export function f(x: T, n: number): string; export function f(x: T, n: boolean): string; - export function f(x: T, n) { + export function f(x: T, n): string { return ""; } } @@ -96,7 +96,7 @@ class WWW { F(x: string): T; F(x: number): T; - F(x: T) { + F(x: T): T { return null; } } diff --git a/ts2mls/js/src/test/typescript/Array.ts b/ts2mls/js/src/test/typescript/TSArray.ts similarity index 100% rename from ts2mls/js/src/test/typescript/Array.ts rename to ts2mls/js/src/test/typescript/TSArray.ts diff --git a/ts2mls/js/src/test/typescript/TypeParameter.ts b/ts2mls/js/src/test/typescript/TypeParameter.ts index 7b7d915c4..4b26bae3a 100644 --- a/ts2mls/js/src/test/typescript/TypeParameter.ts +++ b/ts2mls/js/src/test/typescript/TypeParameter.ts @@ -56,3 +56,6 @@ function fff(p: FFF, s: string) { function getFFF(): FFF { return new FFF(); } + +type PolyToString = (x: T) => string +type PolyID = (x: T) => T diff --git a/ts2mls/jvm/src/test/scala/ts2mls/TsTypeDiffTests.scala b/ts2mls/jvm/src/test/scala/ts2mls/TsTypeDiffTests.scala deleted file mode 100644 index e919d5683..000000000 --- a/ts2mls/jvm/src/test/scala/ts2mls/TsTypeDiffTests.scala +++ /dev/null @@ -1,8 +0,0 @@ -package ts2mls - -import mlscript.DiffTests - -class TsTypeDiffTests extends DiffTests { - override protected lazy val files = - os.walk(os.pwd/"ts2mls"/"js"/"src"/"test"/"diff").filter(_.toIO.isFile) -}