From 4145dbd78ad7d888b14f56a42bde9c0772bb952f Mon Sep 17 00:00:00 2001 From: mor-n4 Date: Wed, 20 Oct 2021 16:03:03 +0200 Subject: [PATCH] GH-2233: As a developer I want type definitions for runtime libraries imported from standard documents (#2234) * remove scope folder @n4js-temp * switch from npm to yarn Now "preinstall": "npx npm-force-resolutions" is no longer required in package.json, because yarn supports resolutions out-of-the-box. * add support for type alias * add tests * support for read-only fields and getter in interfaces * minor improvement * support for type parameters of classes and interfaces * add cmd line option --runtime-libs * do not include TS built-in libs when --runtime-libs is specified * support the "ctor/instance type pattern" in runtime lib .d.ts files * support construct and call signature declarations * some features and improvements (e.g. annotations, illegal member names) * tests * remove an unused import * add support for static members * support for generic methods * some adjustments in runtimeLibs.n4js to reflect recent changes in N4JS * add first support for converting type references from .d.ts to .n4jsd * temporary: ignore folder TEMP * support for object types * temporary: minor changes for ease of debugging * support for 'this' type * support for type operators (e.g. readonly) - ignored on N4JS side * add test for type operators * add place-holder support for type predicates and mapped types * skip ignored elements as early as possible * add place-holder support for index signatures * support for JSDoc comments * minor fix * avoid "this" as parameter name + support for additional members * support multiple declarations for the same interface * better support for prefix/suffix of scripts * replace builtin_js.n4jsd (without jsdoc) * handling of parameterized call signatures (not supported in N4JS) * re-generated builtin_js.n4jsd * strip 'undefined' from unions * re-generated builtin_js.n4jsd * support for member replacement in runtimeLibs mode * re-generated builtin_js.n4jsd * support for extends/implements clauses of classifiers * fix some tests * more fixes to get tests green * even more fixes to get tests green * some changes to make n4js-libs compile (partial) * Squashed commit of the following (GH-2224): commit 8d0f49c60de022c14c9f010b9f19bcfb8e0dae9d Author: Mark-Oliver Reiser Date: Thu Oct 7 13:49:58 2021 +0200 minor: improve wording of some comments commit aa40a908750501494e6830d4b47f0b9e9102f8f5 Author: Mark-Oliver Reiser Date: Thu Oct 7 13:42:24 2021 +0200 more tests commit 8cfd1c4f2c5e61009561596b876bdaf58f6ecae8 Author: Mark-Oliver Reiser Date: Thu Oct 7 13:35:05 2021 +0200 fix bug in n4js-runtime-html5 commit a7d4258b35dd39752dbc4ca2504cefdf2cbbc85a Author: Mark-Oliver Reiser Date: Thu Oct 7 13:11:05 2021 +0200 add a validation commit 7b8d5bdf5b1bf2ff0883d10974602317fc3df9a1 Author: Mark-Oliver Reiser Date: Thu Oct 7 12:52:19 2021 +0200 clean up: remove two obsolete FIXMEs commit 6e9178fbc07c5880d1d7a7fbb178a9e8cbfaa769 Author: Mark-Oliver Reiser Date: Thu Oct 7 12:46:08 2021 +0200 yet more tests commit 74ffddfbda1bd00b4d02a070a417d620ad588db9 Author: Mark-Oliver Reiser Date: Thu Oct 7 12:31:50 2021 +0200 more tests commit 180b137710fded9fc52e4922e055ce0d5199019f Author: Mark-Oliver Reiser Date: Thu Oct 7 12:20:55 2021 +0200 more validations commit 61781b85756cf5b5e435994b962a2468ffff7aa0 Author: Mark-Oliver Reiser Date: Thu Oct 7 11:35:06 2021 +0200 add/adjust some validations commit 05a72f1afa859932ae17c38cc0cc9d78ccebccea Author: Mark-Oliver Reiser Date: Thu Oct 7 09:56:15 2021 +0200 support (non-static) polyfills for interfaces (pending: validations) * misc. fixes to avoid compile errors in n4js-libs * move runtimeLib configuration to separate file * adjust some test * add option for not emitting JSDoc comments * support more cases of declaration merging + better approach * process runtime libs in the order they are defined in the config file * refactoring: change from functions to class methods * minor clean up * support for handling ctor/instance type pattern across file boundaries * registration of remaining runtime library files * fixes in handling of multiple declarations across files * replace .n4jsd files in n4js-libs by generated files * initial version of script for generating built-in types * minor unrelated fix in MWE2 workflow for building n4js-libs * minor fix * change temporary handling of overloading Emit signature "(...args: any+): any+" instead of arbitrarily emitting the first signature. * support symbols as member names * ctor/instance type pattern: create type alias for removed ctor type * more improvements and adjustments * support for generic type aliases * more patching * more improvements and patching (now es2015 compiles) * yet more improvements and patching (now esnext compiles) * add support for tuple types * add place-holder functionality for indexed access types * improvements and more patching to resolve compile errors in nj4s-libs * minor clean up * Merge branch GH-2230 (squashed). * slightly more patching * support ignoring individual signatures + type parameters per signature * more patching + some fixes and improvements * prepare conversion of DOM API in shell script * adjustment in n4js-runtime-html5 for compatibility with new built-ins * experimental: 1st approach of bug fix to avoid failure on GitLab CI * experimental: continues previous commit * more improvements, fixes, patching to get stdlib to compile * more improvements, fixes, patching to get OPR to compile * fix scoping tests * improve BuiltInTypesDefinitionTest + fix validation issues in built-ins * fix more tests + minor improvement of patching * bump version from 0.28.x to 0.29.x * remove a few obsolete FIXME markers * fix fix scoping tests (again) * allow custom runtime library generation config in tests + clean up * resolve/remove a few more FIXMEs * review feedback * revert experimental commits a40d9915c f07b8ff46 * add temporary work-around for GH-2235 --- .../src/n4js/Number.n4jsd | 4 +- .../n4js-runtime-es2015/src/n4js/Array.n4jsd | 33 - .../src/n4js/ArrayBuffer.n4jsd | 25 - .../src/n4js/Function.n4jsd | 15 - .../src/n4js/Iterator.n4jsd | 7 +- .../n4js-runtime-es2015/src/n4js/Map.n4jsd | 70 - .../n4js-runtime-es2015/src/n4js/Math.n4jsd | 31 - .../n4js-runtime-es2015/src/n4js/Number.n4jsd | 25 - .../n4js-runtime-es2015/src/n4js/Object.n4jsd | 18 - .../n4js-runtime-es2015/src/n4js/Proxy.n4jsd | 45 - .../n4js-runtime-es2015/src/n4js/RegExp.n4jsd | 15 - .../n4js-runtime-es2015/src/n4js/Set.n4jsd | 68 - .../n4js-runtime-es2015/src/n4js/String.n4jsd | 22 - .../src/n4js/WeakMap.n4jsd | 41 - .../src/n4js/WeakSet.n4jsd | 36 - .../src/n4js/es2015.collection.n4jsd | 48 + .../src/n4js/es2015.core.n4jsd | 96 + .../src/n4js/es2015.generator.n4jsd | 15 + .../src/n4js/es2015.iterable.n4jsd | 129 + .../src/n4js/es2015.promise.n4jsd | 3 + .../src/n4js/es2015.proxy.n4jsd | 22 + .../src/n4js/es2015.reflect.n4jsd | 3 + .../src/n4js/es2015.symbol.n4jsd | 3 + .../src/n4js/es2015.symbol.wellknown.n4jsd | 121 + .../n4js-runtime-es2015/src/n4js/timers.n4jsd | 17 - .../n4js-runtime-esnext/src/n4js/Array.n4jsd | 25 - .../n4js-runtime-esnext/src/n4js/Object.n4jsd | 17 - .../n4js-runtime-esnext/src/n4js/String.n4jsd | 18 - .../src/n4js/TypedArray.n4jsd | 540 ---- .../src/n4js/es2016.array.include.n4jsd | 51 + .../src/n4js/es2017.intl.n4jsd | 3 + .../src/n4js/es2017.object.n4jsd | 8 + .../src/n4js/es2017.sharedmemory.n4jsd | 31 + .../src/n4js/es2017.string.n4jsd | 7 + .../src/n4js/es2017.typedarrays.n4jsd | 28 + .../src/n4js/es2018.asyncgenerator.n4jsd | 15 + .../src/n4js/es2018.asynciterable.n4jsd | 8 + .../src/n4js/es2018.intl.n4jsd | 3 + .../src/n4js/es2018.promise.n4jsd | 8 + .../src/n4js/es2018.regexp.n4jsd | 16 + .../src/n4js/es2019.array.n4jsd | 9 + .../src/n4js/es2019.object.n4jsd | 6 + .../src/n4js/es2019.string.n4jsd | 9 + .../src/n4js/es2019.symbol.n4jsd | 6 + .../src/n4js/es2020.bigint.n4jsd | 132 + .../src/n4js/es2020.globalThis.n4jsd | 8 + .../src/n4js/es2020.intl.n4jsd | 3 + .../src/n4js/es2020.promise.n4jsd | 18 + .../src/n4js/es2020.sharedmemory.n4jsd | 4 + .../src/n4js/es2020.string.n4jsd | 6 + .../src/n4js/es2020.symbol.wellknown.n4jsd | 9 + .../src/n4js/globalThis.n4jsd | 13 - .../src/n4js/immediate.n4jsd | 15 - .../src/n4js/fetch/Headers.n4jsd | 6 +- .../src/n4js/webcrypto.n4jsd | 6 +- .../n4js-runtime-v8/src/n4js/Error.n4jsd | 3 +- .../n4js-runtime/src/n4js/Runtime.n4js | 5 +- .../package.json | 6 +- .../package.json | 6 +- .../package.json | 6 +- .../eclipse/n4js/mangelhaft/TestExecutor.n4js | 2 +- .../eclipse/n4js/mangelhaft/util/proc.n4js | 2 +- n4js-tools/n4jsd-generator/.gitignore | 1 + .../n4jsd-generator/src/n4js/cmdLineOpts.n4js | 13 + .../n4jsd-generator/src/n4js/convert.n4jsd | 4 +- .../n4jsd-generator/src/n4js/generator.n4js | 39 +- .../n4jsd-generator/src/n4js/model.n4js | 528 +++- .../n4jsd-generator/src/n4js/runtimeLibs.n4js | 627 ++++ .../src/n4js/runtimeLibsConfig.js | 1267 ++++++++ .../n4jsd-generator/src/n4js/utils.n4js | 7 +- .../src/n4js/utilsObjectParsing.n4js | 144 + n4js-tools/n4jsd-generator/src/ts/convert.ts | 573 +++- n4js-tools/n4jsd-generator/src/ts/model.d.ts | 62 +- n4js-tools/n4jsd-generator/src/ts/utils.d.ts | 1 + n4js-tools/n4jsd-generator/src/ts/utils_ts.ts | 73 +- .../test/n4js/AbstractN4jsdGeneratorTest.n4js | 23 +- .../test/n4js/ConvertClassifiersTest.n4js | 237 +- .../test/n4js/ConvertDocumentationTest.n4js | 205 ++ .../n4js/ConvertMultipleDeclarationsTest.n4js | 130 + .../test/n4js/ConvertRuntimeLibsTest.n4js | 216 ++ ...peAlias.n4js => ConvertTypeAliasTest.n4js} | 0 .../test/n4js/ConvertTypeRefsTest.n4js | 226 ++ .../test/n4js/ModuleStructureLegacyTest.n4js | 3 +- .../src-env/env/builtin_js.n4jsd | 2597 +++++------------ .../n4js/validation/utils/MemberCube.java | 22 + .../validators/N4JSTypeValidator.xtend | 20 +- .../n4js/libs/build/BuildN4jsLibs.java | 12 +- .../utils/scripts/generate-built-in-types.sh | 96 + ...InvalidStaticPolyfillOfBuiltInType.n4js.xt | 2 +- ...gSignatureOfRegExpMethodsExecMatch.n4js.xt | 2 +- ...nspilerIssuesInCustomErrorTypeCtor.n4js.xt | 2 +- .../object/object_defineProperty.n4js.xt | 32 +- .../builtin_js/object/object_freeze.n4js.xt | 6 +- .../object_getOwnPropertyDescriptor.n4js.xt | 7 +- .../builtin_js/object/object_isFrozen.n4js.xt | 15 +- .../builtin_js/object/object_isSealed.n4js.xt | 3 +- .../builtin_js/object/object_seal.n4js.xt | 6 +- .../builtin_js/string/string_search.n4js.xt | 2 +- .../builtin_js/string/string_split.n4js.xt | 2 +- .../CamelCaseCompletionTest.java | 3 +- .../CompletionWithImportsTest.xtend | 27 +- .../n4js/ide/tests/symbol/DefinitionTest.java | 12 +- .../ide/tests/symbol/ImplementationTest.java | 7 +- .../builtin/BuiltInTypesDefinitionTest.xtend | 31 +- .../N4JSScopingTestWithIndexTest.xtend | 2 +- .../ClassWithMethodsTypesBuilderTest.xtend | 4 +- .../ClassesGetterSetterTypesBuilderTest.xtend | 4 +- .../FunctionsTypesBuilderTest.xtend | 12 +- ...tLiteralGetterSetterTypesBuilderTest.xtend | 2 +- .../Error/Error_optionalFields.n4js.xt | 10 +- .../src/Req152_PolyfillConstructor.n4jsd.xt | 2 +- .../memberPatching/delegation_ifc2ifc.n4js.xt | 12 +- .../Scoping_StaticMembersInInterfaces.n4js.xt | 8 +- .../predefined_properties.n4js.xt | 66 +- .../ref_to_filled_type_scoping.n4js.xt | 6 +- .../xt-tests/scoping/Sister.n4js.xt | 32 +- .../xt-tests/scoping/enums/EnumUser.n4js.xt | 2 +- .../n4jsx/ClassComponentDescriptions.n4jsx.xt | 27 +- .../xt-tests/scoping/object_literals.n4js.xt | 23 +- version.json | 2 +- 120 files changed, 6238 insertions(+), 3231 deletions(-) delete mode 100644 n4js-libs/packages/n4js-runtime-es2015/src/n4js/Array.n4jsd delete mode 100644 n4js-libs/packages/n4js-runtime-es2015/src/n4js/ArrayBuffer.n4jsd delete mode 100644 n4js-libs/packages/n4js-runtime-es2015/src/n4js/Function.n4jsd delete mode 100644 n4js-libs/packages/n4js-runtime-es2015/src/n4js/Map.n4jsd delete mode 100644 n4js-libs/packages/n4js-runtime-es2015/src/n4js/Math.n4jsd delete mode 100644 n4js-libs/packages/n4js-runtime-es2015/src/n4js/Number.n4jsd delete mode 100644 n4js-libs/packages/n4js-runtime-es2015/src/n4js/Object.n4jsd delete mode 100644 n4js-libs/packages/n4js-runtime-es2015/src/n4js/Proxy.n4jsd delete mode 100644 n4js-libs/packages/n4js-runtime-es2015/src/n4js/RegExp.n4jsd delete mode 100644 n4js-libs/packages/n4js-runtime-es2015/src/n4js/Set.n4jsd delete mode 100644 n4js-libs/packages/n4js-runtime-es2015/src/n4js/String.n4jsd delete mode 100644 n4js-libs/packages/n4js-runtime-es2015/src/n4js/WeakMap.n4jsd delete mode 100644 n4js-libs/packages/n4js-runtime-es2015/src/n4js/WeakSet.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.collection.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.core.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.generator.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.iterable.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.promise.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.proxy.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.reflect.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.symbol.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.symbol.wellknown.n4jsd delete mode 100644 n4js-libs/packages/n4js-runtime-es2015/src/n4js/timers.n4jsd delete mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/Array.n4jsd delete mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/Object.n4jsd delete mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/String.n4jsd delete mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/TypedArray.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2016.array.include.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2017.intl.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2017.object.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2017.sharedmemory.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2017.string.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2017.typedarrays.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2018.asyncgenerator.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2018.asynciterable.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2018.intl.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2018.promise.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2018.regexp.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2019.array.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2019.object.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2019.string.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2019.symbol.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.bigint.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.globalThis.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.intl.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.promise.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.sharedmemory.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.string.n4jsd create mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.symbol.wellknown.n4jsd delete mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/globalThis.n4jsd delete mode 100644 n4js-libs/packages/n4js-runtime-esnext/src/n4js/immediate.n4jsd create mode 100644 n4js-tools/n4jsd-generator/src/n4js/runtimeLibs.n4js create mode 100644 n4js-tools/n4jsd-generator/src/n4js/runtimeLibsConfig.js create mode 100644 n4js-tools/n4jsd-generator/src/n4js/utilsObjectParsing.n4js create mode 100644 n4js-tools/n4jsd-generator/test/n4js/ConvertDocumentationTest.n4js create mode 100644 n4js-tools/n4jsd-generator/test/n4js/ConvertMultipleDeclarationsTest.n4js create mode 100644 n4js-tools/n4jsd-generator/test/n4js/ConvertRuntimeLibsTest.n4js rename n4js-tools/n4jsd-generator/test/n4js/{ConvertTypeAlias.n4js => ConvertTypeAliasTest.n4js} (100%) create mode 100644 n4js-tools/n4jsd-generator/test/n4js/ConvertTypeRefsTest.n4js create mode 100755 releng/utils/scripts/generate-built-in-types.sh diff --git a/n4js-libs/packages/n4js-runtime-ecma402/src/n4js/Number.n4jsd b/n4js-libs/packages/n4js-runtime-ecma402/src/n4js/Number.n4jsd index a4b7cba140..c5ef17cc7f 100644 --- a/n4js-libs/packages/n4js-runtime-ecma402/src/n4js/Number.n4jsd +++ b/n4js-libs/packages/n4js-runtime-ecma402/src/n4js/Number.n4jsd @@ -20,6 +20,6 @@ * * @see https://www.ecma-international.org/ecma-402/4.0/ */ - @Override - public toLocaleString (locales: string | string[]=, options: ~r~NumberFormatOptions=): string +// @Override +// public toLocaleString (locales: string | string[]=, options: ~r~NumberFormatOptions=): string } diff --git a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Array.n4jsd b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Array.n4jsd deleted file mode 100644 index 51c6d050e4..0000000000 --- a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Array.n4jsd +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2017 NumberFour AG. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * NumberFour AG - Initial API and implementation - */ -@@Global @@ProvidedByRuntime - -import {IteratorExt} from "Iterator"; -export public interface ~ArrayLike { - public get length(): int; -} - -export public interface ~ArrayIterator extends Iterator {} - -@Polyfill export external public class Array extends Array { - public static from(source: Iterable|ArrayLike|Iterator|string, mapFn: (I, int) => any=, thisArg: Object=): I[]; - - // TODO: Currently impossible due to missing support for default type parameters, see GH-157 - // public static from(source: Iterable|ArrayLike|Iterator, mapFn: (I, int) => O=, thisArg: Object=): O[]; - - public findIndex(predicate: (T, int=, T[]=) => boolean, thisArg: Object=): int; - public find(predicate: (T, int=, T[]=) => boolean, thisArg: Object=): T; - - public entries(): IteratorExt>; - public keys(): IteratorExt; - public values(): IteratorExt; -} - diff --git a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/ArrayBuffer.n4jsd b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/ArrayBuffer.n4jsd deleted file mode 100644 index fff98483ff..0000000000 --- a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/ArrayBuffer.n4jsd +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2017 NumberFour AG. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * NumberFour AG - Initial API and implementation - */ -@@Global @@ProvidedByRuntime - -export external public class ArrayBuffer { - public static isView(obj: Object): boolean; - - /* - * TODO: Symbol.species is currently not supported. - * public static get [Symbol.species](): constructor{? extends ArrayBuffer}; - */ - - public constructor(length: int); - - public get byteLength(): int; - public slice(begin: int, end: int=): ArrayBuffer; -} diff --git a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Function.n4jsd b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Function.n4jsd deleted file mode 100644 index 83d2a118fa..0000000000 --- a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Function.n4jsd +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright (c) 2019 NumberFour AG. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * NumberFour AG - Initial API and implementation - */ -@@Global @@ProvidedByRuntime - -@Polyfill export external public class Function extends Function { - public get name(): string; -} diff --git a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Iterator.n4jsd b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Iterator.n4jsd index fdeb1166c9..2668fc1eec 100644 --- a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Iterator.n4jsd +++ b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Iterator.n4jsd @@ -10,11 +10,10 @@ */ @@ProvidedByRuntime +// TODO remove this file (after updating the @n4jsd packages) + /** - * Use this interface type to denote common ES2015 work-around cases - * used to make Iterators compatible with for..of loops. - * - * Dirty, but properly represents the ES2015 work-around. + * Deprecated! Use IterableIterator instead. */ export public interface ~IteratorExt extends Iterator, Iterable { // @Override diff --git a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Map.n4jsd b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Map.n4jsd deleted file mode 100644 index 6b53906e1b..0000000000 --- a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Map.n4jsd +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2017 NumberFour AG. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * NumberFour AG - Initial API and implementation - */ -@@Global @@ProvidedByRuntime - - -import {IteratorExt} from "Iterator"; -export external public class Map extends Object implements Iterable> { - public constructor(arg: Iterable> =); - - @Override public [Symbol.iterator](): IteratorExt>; - - /** - * Number of key/value pairs. - */ - public get size(): int; - - /** - * Removes all key/value pairs. - */ - public clear(): void; - - /** - * Removes value associated with given key. - */ - public delete(key: KeyT): boolean; - - /** - * New iterator of [key, value] tuples for each element in insertion order. - */ - public entries(): IteratorExt>; - - /** - * Calls callbackFn for each key/value pai, in insertion order. - */ - public forEach(callbackFn: {function(ValueT, KeyT, Map):void}, thisArg: Object=): void; - - /** - * Value associated with key. - */ - public get(key: KeyT): ValueT; - - /** - * Tests whether a value has been associated with the key. - */ - public has(key: KeyT): boolean; - - /** - * New iterator that contains the keys in insertion order. - */ - public keys(): IteratorExt; - - /** - * Sets a key/value; returns the Map object. - */ - public set(key: KeyT, value: ValueT): this; - - /** - * New iterator that contains the values in insertion order. - */ - public values(): IteratorExt; -} - diff --git a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Math.n4jsd b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Math.n4jsd deleted file mode 100644 index 147daa75f7..0000000000 --- a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Math.n4jsd +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2017 NumberFour AG. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * NumberFour AG - Initial API and implementation - */ -@@Global @@ProvidedByRuntime - -@Polyfill export external public class Math extends Math { - public static log10(x: number): number; - public static log2(x: number): number; - public static log1p(x: number): number; - public static expm1(x: number): number; - public static cosh(x: number): number; - public static sinh(x: number): number; - public static tanh(x: number): number; - public static acosh(x: number): number; - public static asinh(x: number): number; - public static atanh(x: number): number; - public static hypot(value1: number, value2: number, value3: number=): number; - public static trunc(x: number): number; - public static sign(x: number): number; - public static cbrt(x: number): number; - public static imul(x: number): number; - public static clz32(x: number): number; - public static fround(x: number): number; -} diff --git a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Number.n4jsd b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Number.n4jsd deleted file mode 100644 index 176103f70d..0000000000 --- a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Number.n4jsd +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2017 NumberFour AG. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * NumberFour AG - Initial API and implementation - */ -@@Global @@ProvidedByRuntime - -@Polyfill export external public class Number extends Number { - public const EPSILON: number; - public const MAX_SAFE_INTEGER: number; - public const MIN_SAFE_INTEGER: number; - - public static parseInt(str: string, radix: number=): number; - public static parseFloat(str: string): number; - public static isNaN(number: number): boolean; - public static isFinite(number: number): boolean; - public static isInteger(number: number): boolean; - public static isSafeInteger(number: number): boolean; - //public static number toInteger(number number); // maybe ES.next? -} diff --git a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Object.n4jsd b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Object.n4jsd deleted file mode 100644 index fa8438a08a..0000000000 --- a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Object.n4jsd +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2017 NumberFour AG. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * NumberFour AG - Initial API and implementation - */ -@@Global @@ProvidedByRuntime - -@Polyfill export external public class Object extends Object { - public static assign(target: Object, ... sources: Object): Object; - public static setPrototypeOf(obj: Object, prototype: Object): Object; -} - - diff --git a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Proxy.n4jsd b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Proxy.n4jsd deleted file mode 100644 index df089cca18..0000000000 --- a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Proxy.n4jsd +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2017 NumberFour AG. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * NumberFour AG - Initial API and implementation - */ -@@Global @@ProvidedByRuntime - -export external public interface ~ProxyHandler { - public construct?: {function(/*target: */T, /*argumentsList: */any[]): Object}; - public apply?: {function(/*target: */T, /*thisArg: */Object, /*argumentsList: */any[]): any}; - public has?: {function(/*target: */T, /*property: */union{string, symbol}): boolean}; - public get?: {function(/*target: */T, /*property: */union{string, symbol}, /*receiver: */T): any}; - public set?: {function(/*target: */T, /*property: */union{string, symbol}, /*value: */any, /*receiver: */T): boolean}; - public deleteProperty?: {function(/*target: */T, /*property: */union{string, symbol}): boolean}; - public defineProperty?: {function(/*target: */T, /*property: */union{string, symbol}, /*descriptor: */Object): boolean}; - public ownKeys?: {function(/*target: */T): union{symbol, string}[]}; - - public getOwnPropertyDescriptor?: {function(/*target: */T, /*property: */union{string, symbol}): Object?}; - public getPrototypeOf?: {function(/*target: */T): Object}; - public isExtensible?: {function(/*target: */T): boolean}; - public preventExtensions?: {function(/*target: */T): boolean}; - public setPrototypeOf?: {function(/*target: */T, /*proto: */Object): void}; -} - -@Final export external public class Proxy { - /** - * Creates a proxy for the given target. - */ - public constructor(target: T, handler: ~ProxyHandler)/*: T*/; - - /** - * Creates a revocable proxy, i.e. {proxy, revoke function}. - * - * Calling revoke() redners the proxy unusable, any trap will throw a TypeError. - * Revoked proxies can be garbage collected. - */ - public static revocable(target: T, handler: ~ProxyHandler): ~Object with { proxy: T; revoke: Function; }; -} - - diff --git a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/RegExp.n4jsd b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/RegExp.n4jsd deleted file mode 100644 index cf7fe7374d..0000000000 --- a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/RegExp.n4jsd +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright (c) 2017 NumberFour AG. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * NumberFour AG - Initial API and implementation - */ -@@Global @@ProvidedByRuntime - -@Polyfill export external public class RegExp extends RegExp { - public get flags(): string; -} diff --git a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Set.n4jsd b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Set.n4jsd deleted file mode 100644 index 0f5af5ef6c..0000000000 --- a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Set.n4jsd +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2017 NumberFour AG. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * NumberFour AG - Initial API and implementation - */ -@@Global @@ProvidedByRuntime - - -import {IteratorExt} from "Iterator"; -export external public class Set extends Object implements Iterable { - public constructor(arg: Iterable =); - - @Override public [Symbol.iterator](): IteratorExt; - - /** - * Number of values. - */ - public get size(): int; - - /** - * Adds a new element; returns the Set object. - */ - public add(value: ValueT): this; - - /** - * Removes all elements. - */ - public clear(): void; - - /** - * Deletes an element. - * - * @param value - The element to be deleted. - * @return true in case the set has been modified, otherwise false. - */ - public delete(value: ValueT): boolean; - - /** - * New iterator of [value, value] tuples for each element, in insertion order. - */ - public entries(): IteratorExt>; - - /** - * Calls callbackFn for each value, in insertion order. - */ - public forEach(callbackFn: {function(ValueT, ValueT, Set):void}, thisArg: Object=): void; - - /** - * Tests whether an element is part of this set. - */ - public has(value: ValueT): boolean; - - /** - * New iterator of the values for each element, in insertion order. - */ - public keys(): IteratorExt; - - /** - * New iterator of values for each element, in insertion order. - */ - public values(): IteratorExt; -} - diff --git a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/String.n4jsd b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/String.n4jsd deleted file mode 100644 index 2361cbe837..0000000000 --- a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/String.n4jsd +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2017 NumberFour AG. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * NumberFour AG - Initial API and implementation - */ -@@Global @@ProvidedByRuntime - -@Polyfill export external public class String extends String { - public static fromCodePoint(... codePoints: string): string; - public static raw(callSite: Object, ... substitutions: string): string; - public startsWith(searchString: string, position: number=): boolean; - public endsWith(searchString: string, endPosition: number=): boolean; - public includes(searchString: string, position: number=): boolean; - public codePointAt(pos: int): number; - public normalize(form: string): string; - public repeat(count: number): string; -} diff --git a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/WeakMap.n4jsd b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/WeakMap.n4jsd deleted file mode 100644 index a9b1e1584a..0000000000 --- a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/WeakMap.n4jsd +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2017 NumberFour AG. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * NumberFour AG - Initial API and implementation - */ -@@Global @@ProvidedByRuntime - -export external public class WeakMap extends Object { - public constructor(arg: Iterable =); - - /** - * Length property is 1. - */ - @Final public length: number; - - /** - * Removes any value associated with the key. - */ - public delete(key: KeyT): boolean; - - /** - * Gets the value associated with the key. - */ - public get(key: KeyT): ValueT; - - /** - * Tests whether a value has been associated with the key. - */ - public has(key: KeyT): boolean; - - /** - * Sets a key/value. - */ - public set(key: KeyT, value: ValueT): this; -} - diff --git a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/WeakSet.n4jsd b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/WeakSet.n4jsd deleted file mode 100644 index 2e5031b03c..0000000000 --- a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/WeakSet.n4jsd +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2017 NumberFour AG. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * NumberFour AG - Initial API and implementation - */ -@@Global @@ProvidedByRuntime - -export external public class WeakSet extends Object { - public constructor(arg: Iterable =); - - /** - * Length property is 1. - */ - @Final public length: number; - - /** - * Adds a new element. - */ - public add(value: ValueT): this; - - /** - * Removes the element associated with the value. - */ - public delete(value: ValueT): boolean; - - /** - * Tests whether an element is present. - */ - public has(value: ValueT): boolean; -} - diff --git a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.collection.n4jsd b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.collection.n4jsd new file mode 100644 index 0000000000..0ab46f162e --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.collection.n4jsd @@ -0,0 +1,48 @@ +@@Global @@ProvidedByRuntime + +export external public class Map { + public clear(): void; + public delete(key: K): boolean; + public forEach(callbackfn: (value: V, key: K, map: Map)=>void, thisArg: any = ): void; + public get(key: K): V; + public has(key: K): boolean; + public set(key: K, value: V): this; + public get size(): number; + public constructor(entries: Iterable> = ); +} + +export external public type MapConstructor = constructor{Map}; + +export external public class WeakMap { + public delete(key: K): boolean; + public get(key: K): V; + public has(key: K): boolean; + public set(key: K, value: V): this; + public constructor(entries: Iterable> = ); +} + +export external public type WeakMapConstructor = constructor{WeakMap}; + +export external public class Set { + public add(value: T): this; + public clear(): void; + public delete(value: T): boolean; + public forEach(callbackfn: (value: T, value2: T, set: Set)=>void, thisArg: any = ): void; + public has(value: T): boolean; + public get size(): number; + public constructor(values: Iterable = ); +} + +export external public type SetConstructor = constructor{Set}; + +export external public class WeakSet { + public add(value: T): this; + public delete(value: T): boolean; + public has(value: T): boolean; + public constructor(values: Iterable = ); +} + +export external public type WeakSetConstructor = constructor{WeakSet}; + +export external public type ReadonlySet = Set; +export external public type ReadonlyMap = Map; diff --git a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.core.n4jsd b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.core.n4jsd new file mode 100644 index 0000000000..b5d85416d2 --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.core.n4jsd @@ -0,0 +1,96 @@ +@@Global @@ProvidedByRuntime + +@Polyfill +export external public class Array extends Array { + public find(predicate: (T, int=, T[]=) => boolean, thisArg: Object=): T; + public findIndex(predicate: (value: T, index: number, obj: Array)=>any+, thisArg: any = ): number; + public fill(value: T, start: number = , end: number = ): this; + public copyWithin(target: number, start: number, end: number = ): this; + public static from(source: Iterable|ArrayLike|Iterator|string, mapFn: (I, int) => any=, thisArg: Object=): I[]; + public static of(...items: T): Array; +} + +@Polyfill +export external public class Date extends Date {} + +@Polyfill +export external public class Function extends Function { + public get name(): string; +} + +@Polyfill +export external public class Math extends Math { + public static clz32(x: number): number; + public static imul(x: number, y: number): number; + public static sign(x: number): number; + public static log10(x: number): number; + public static log2(x: number): number; + public static log1p(x: number): number; + public static expm1(x: number): number; + public static cosh(x: number): number; + public static sinh(x: number): number; + public static tanh(x: number): number; + public static acosh(x: number): number; + public static asinh(x: number): number; + public static atanh(x: number): number; + public static hypot(...values: number): number; + public static trunc(x: number): number; + public static fround(x: number): number; + public static cbrt(x: number): number; +} + +@Polyfill +export external public class Number extends Number { + public static get EPSILON(): number; + public static isFinite(number: any+): boolean; + public static isInteger(number: any+): boolean; + public static isNaN(number: any+): boolean; + public static isSafeInteger(number: any+): boolean; + public static get MAX_SAFE_INTEGER(): number; + public static get MIN_SAFE_INTEGER(): number; + public static parseFloat(string: string): number; + public static parseInt(string: string, radix: number = ): number; +} + +@Polyfill +export external public class Object extends Object { + public static assign(...args: any+): any+; // overloading not supported + public static getOwnPropertySymbols(o: any): Array; + @Override + public static keys(o: ~Object): Array; + public static is(value1: any, value2: any): boolean; + public static setPrototypeOf(o: any, proto: Object): any; +} + +@Polyfill +export external public class RegExp extends RegExp { + public get flags(): string; + public get sticky(): boolean; + public get unicode(): boolean; + (pattern: RegExp | string, flags: string = ): RegExp; +} + +@Polyfill +export external public class String extends String { + public codePointAt(pos: number): number; + public includes(searchString: string, position: number = ): boolean; + public endsWith(searchString: string, endPosition: number = ): boolean; + public normalize(...args: any+): any+; // overloading not supported + public repeat(count: number): string; + public startsWith(searchString: string, position: number = ): boolean; + public anchor(name: string): string; + public big(): string; + public blink(): string; + public bold(): string; + public fixed(): string; + public fontcolor(color: string): string; + public fontsize(...args: any+): any+; // overloading not supported + public italics(): string; + public link(url: string): string; + public small(): string; + public strike(): string; + public sub(): string; + public sup(): string; + public static fromCodePoint(...codePoints: number): string; + public static raw(template: ~Object with { raw: Array | ArrayLike; }, ...substitutions: any): string; +} diff --git a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.generator.n4jsd b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.generator.n4jsd new file mode 100644 index 0000000000..eff46aa530 --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.generator.n4jsd @@ -0,0 +1,15 @@ +@@Global @@ProvidedByRuntime + +export external public interface ~GeneratorFunction { + @CovariantConstructor + constructor(...args: any); + get length(): number; + get name(): string; +} + +export external public interface ~GeneratorFunctionConstructor { + @CovariantConstructor + constructor(...args: string); + get length(): number; + get name(): string; +} diff --git a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.iterable.n4jsd b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.iterable.n4jsd new file mode 100644 index 0000000000..a710adcbc7 --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.iterable.n4jsd @@ -0,0 +1,129 @@ +@@Global @@ProvidedByRuntime + +@Polyfill +export external public class Symbol extends Symbol {} + +export external public interface ~IteratorYieldResult { + done?: false; + value: TYield; +} + +export external public interface ~IteratorReturnResult { + done: true; + value: TReturn; +} + +export external public type IteratorResult = IteratorYieldResult | IteratorReturnResult; + +@Polyfill +export external public class Array extends Array { + public entries(): IterableIterator<[number,T]>; + public keys(): IterableIterator; + public values(): IterableIterator; +} + +export external public interface ~IArguments { + [Symbol.iterator](): IterableIterator; +} + +@Polyfill +export external public class Map extends Map { + public [Symbol.iterator](): IterableIterator<[K,V]>; + public entries(): IterableIterator<[K,V]>; + public keys(): IterableIterator; + public values(): IterableIterator; +} + +@Polyfill +export external public class WeakMap extends WeakMap {} + +@Polyfill +export external public class Set extends Set { + public [Symbol.iterator](): IterableIterator; + public entries(): IterableIterator<[T,T]>; + public keys(): IterableIterator; + public values(): IterableIterator; +} + +@Polyfill +export external public class WeakSet extends WeakSet {} + +@Polyfill +export external public class String extends String {} + +@Polyfill +export external public class Int8Array extends Int8Array { + public [Symbol.iterator](): IterableIterator; + public entries(): IterableIterator<[number,number]>; + public keys(): IterableIterator; + public values(): IterableIterator; +} + +@Polyfill +export external public class Uint8Array extends Uint8Array { + public [Symbol.iterator](): IterableIterator; + public entries(): IterableIterator<[number,number]>; + public keys(): IterableIterator; + public values(): IterableIterator; +} + +@Polyfill +export external public class Uint8ClampedArray extends Uint8ClampedArray { + public [Symbol.iterator](): IterableIterator; + public entries(): IterableIterator<[number,number]>; + public keys(): IterableIterator; + public values(): IterableIterator; +} + +@Polyfill +export external public class Int16Array extends Int16Array { + public [Symbol.iterator](): IterableIterator; + public entries(): IterableIterator<[number,number]>; + public keys(): IterableIterator; + public values(): IterableIterator; +} + +@Polyfill +export external public class Uint16Array extends Uint16Array { + public [Symbol.iterator](): IterableIterator; + public entries(): IterableIterator<[number,number]>; + public keys(): IterableIterator; + public values(): IterableIterator; +} + +@Polyfill +export external public class Int32Array extends Int32Array { + public [Symbol.iterator](): IterableIterator; + public entries(): IterableIterator<[number,number]>; + public keys(): IterableIterator; + public values(): IterableIterator; +} + +@Polyfill +export external public class Uint32Array extends Uint32Array { + public [Symbol.iterator](): IterableIterator; + public entries(): IterableIterator<[number,number]>; + public keys(): IterableIterator; + public values(): IterableIterator; +} + +@Polyfill +export external public class Float32Array extends Float32Array { + public [Symbol.iterator](): IterableIterator; + public entries(): IterableIterator<[number,number]>; + public keys(): IterableIterator; + public values(): IterableIterator; +} + +@Polyfill +export external public class Float64Array extends Float64Array { + public [Symbol.iterator](): IterableIterator; + public entries(): IterableIterator<[number,number]>; + public keys(): IterableIterator; + public values(): IterableIterator; +} + +export external public interface ~IterableIterator extends Iterator, Iterable { + @Override + [Symbol.iterator](): IterableIterator; +} diff --git a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.promise.n4jsd b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.promise.n4jsd new file mode 100644 index 0000000000..4854a822d1 --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.promise.n4jsd @@ -0,0 +1,3 @@ +@@Global @@ProvidedByRuntime + + diff --git a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.proxy.n4jsd b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.proxy.n4jsd new file mode 100644 index 0000000000..539d00cf68 --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.proxy.n4jsd @@ -0,0 +1,22 @@ +@@Global @@ProvidedByRuntime + +export external public class Proxy { + public static revocable(target: T, handler: ProxyHandler): ~Object with { proxy: T; revoke: ()=>void; }; + public constructor(target: T, handler: ProxyHandler); +} + +export external public interface ~ProxyHandler { + apply?: (target: T, thisArg: Object, argArray: Array) => any; + construct?: (target: T, argArray: Array, newTarget: Function) => Object; + defineProperty?: (target: T, p: string | symbol, attributes: PropertyDescriptor) => boolean; + deleteProperty?: (target: T, p: string | symbol) => boolean; + get?: (target: T, p: string | symbol, receiver: Object) => any; + getOwnPropertyDescriptor?: (target: T, p: string | symbol) => PropertyDescriptor; + getPrototypeOf?: (target: T) => Object; + has?: (target: T, p: string | symbol) => boolean; + isExtensible?: (target: T) => boolean; + ownKeys?: (target: T) => ArrayLike; + preventExtensions?: (target: T) => boolean; + set?: (target: T, p: string | symbol, value: any, receiver: Object) => boolean; + setPrototypeOf?: (target: T, v: Object) => boolean; +} diff --git a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.reflect.n4jsd b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.reflect.n4jsd new file mode 100644 index 0000000000..4854a822d1 --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.reflect.n4jsd @@ -0,0 +1,3 @@ +@@Global @@ProvidedByRuntime + + diff --git a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.symbol.n4jsd b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.symbol.n4jsd new file mode 100644 index 0000000000..4854a822d1 --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.symbol.n4jsd @@ -0,0 +1,3 @@ +@@Global @@ProvidedByRuntime + + diff --git a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.symbol.wellknown.n4jsd b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.symbol.wellknown.n4jsd new file mode 100644 index 0000000000..66005dd401 --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/es2015.symbol.wellknown.n4jsd @@ -0,0 +1,121 @@ +@@Global @@ProvidedByRuntime + +@Polyfill +export external public class Array extends Array { + public [Symbol.unscopables](): ~Object with { copyWithin: boolean; entries: boolean; fill: boolean; find: boolean; findIndex: boolean; keys: boolean; values: boolean; }; + public static get [Symbol.species](): ArrayConstructor; +} + +@Polyfill +export external public class Date extends Date { + public [Symbol.toPrimitive](...args: any+): any+; // overloading not supported +} + +@Polyfill +export external public class Map extends Map { + public get [Symbol.toStringTag](): string; + public static get [Symbol.species](): MapConstructor; +} + +@Polyfill +export external public class WeakMap extends WeakMap { + public get [Symbol.toStringTag](): string; +} + +@Polyfill +export external public class Set extends Set { + public get [Symbol.toStringTag](): string; + public static get [Symbol.species](): SetConstructor; +} + +@Polyfill +export external public class WeakSet extends WeakSet { + public get [Symbol.toStringTag](): string; +} + +@Polyfill +export external public class JSON extends JSON { + public static get [Symbol.toStringTag](): string; +} + +@Polyfill +export external public class Function extends Function { + public [Symbol.hasInstance](value: any): boolean; +} + +export external public interface ~GeneratorFunction { + get [Symbol.toStringTag](): string; +} + +@Polyfill +export external public class Math extends Math { + public static get [Symbol.toStringTag](): string; +} + +@Polyfill +export external public class RegExp extends RegExp { + public [Symbol.match](string: string): RegExpMatchArray; + public [Symbol.replace](...args: any+): any+; // overloading not supported + public [Symbol.search](string: string): number; + public [Symbol.split](string: string, limit: number = ): Array; + public static get [Symbol.species](): RegExpConstructor; +} + +@Polyfill +export external public class String extends String {} + +@Polyfill +export external public class ArrayBuffer extends ArrayBuffer { + public get [Symbol.toStringTag](): string; + public static get [Symbol.species](): ArrayBufferConstructor; +} + +@Polyfill +export external public class DataView extends DataView { + public get [Symbol.toStringTag](): string; +} + +@Polyfill +export external public class Int8Array extends Int8Array { + public get [Symbol.toStringTag](): "Int8Array"; +} + +@Polyfill +export external public class Uint8Array extends Uint8Array { + public get [Symbol.toStringTag](): "Uint8Array"; +} + +@Polyfill +export external public class Uint8ClampedArray extends Uint8ClampedArray { + public get [Symbol.toStringTag](): "Uint8ClampedArray"; +} + +@Polyfill +export external public class Int16Array extends Int16Array { + public get [Symbol.toStringTag](): "Int16Array"; +} + +@Polyfill +export external public class Uint16Array extends Uint16Array { + public get [Symbol.toStringTag](): "Uint16Array"; +} + +@Polyfill +export external public class Int32Array extends Int32Array { + public get [Symbol.toStringTag](): "Int32Array"; +} + +@Polyfill +export external public class Uint32Array extends Uint32Array { + public get [Symbol.toStringTag](): "Uint32Array"; +} + +@Polyfill +export external public class Float32Array extends Float32Array { + public get [Symbol.toStringTag](): "Float32Array"; +} + +@Polyfill +export external public class Float64Array extends Float64Array { + public get [Symbol.toStringTag](): "Float64Array"; +} diff --git a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/timers.n4jsd b/n4js-libs/packages/n4js-runtime-es2015/src/n4js/timers.n4jsd deleted file mode 100644 index aee8ec1e34..0000000000 --- a/n4js-libs/packages/n4js-runtime-es2015/src/n4js/timers.n4jsd +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright (c) 2017 NumberFour AG. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * NumberFour AG - Initial API and implementation - */ -@@Global @@ProvidedByRuntime - -export external public function setTimeout(callback: Function, timeout: number): number; -export external public function clearTimeout(handle: number): void; -export external public function setInterval(callback: Function, timeout: number): number; -export external public function clearInterval(handle: number): void; - diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/Array.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/Array.n4jsd deleted file mode 100644 index d7fc69b343..0000000000 --- a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/Array.n4jsd +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2021 NumberFour AG. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * NumberFour AG - Initial API and implementation - */ -@@Global @@ProvidedByRuntime - -@Polyfill export external public class Array extends Array { - // @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap - public flatMap(callback: (currentValue: T, index: int, array: T[]) => (U|U[]), thisArg: Object=): U[]; - // @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat - public flat(depth: int = 1): U[]; - - // @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes - public includes(valueToFind: T, fromIndex: int = 0): boolean; - // @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin - public copyWithin(target: int, start: int=, end: int=): this; - // @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill - public fill(value: T, start: int = 0, end: int=): this; -} diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/Object.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/Object.n4jsd deleted file mode 100644 index 18ff20d230..0000000000 --- a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/Object.n4jsd +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright (c) 2018 NumberFour AG. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * NumberFour AG - Initial API and implementation - */ -@@Global @@ProvidedByRuntime - -@Polyfill export external public class Object extends Object { - public static values(obj: Object): any[]; - public static entries(obj: Object): Iterable2[]; -} - diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/String.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/String.n4jsd deleted file mode 100644 index 22c58597d8..0000000000 --- a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/String.n4jsd +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2017 NumberFour AG. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * NumberFour AG - Initial API and implementation - */ -@@Global @@ProvidedByRuntime - -@Polyfill export external public class String extends String { - public substr(begin: number, length: number=): string; - - public padStart(len: int, pad: string=): string; - public padEnd(len: int, pad: string=): string; -} diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/TypedArray.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/TypedArray.n4jsd deleted file mode 100644 index 632d582638..0000000000 --- a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/TypedArray.n4jsd +++ /dev/null @@ -1,540 +0,0 @@ -@@Global @@ProvidedByRuntime - -export external public abstract class ArrayBufferView { - public get buffer(): ArrayBuffer; - public get byteLength(): int; - public get byteOffsett(): int; -} - -export external public abstract class TypedArray extends ArrayBufferView implements Iterable { - public get BYTES_PER_ELEMENT(): int; - public get name(): string; - public get length(): int; - public static from(source: union{Iterable, ArrayLike, Iterator }, mapFn: (T) => number=, thisArg: Object=): TypedArray; - public static of(...elements: T): TypedArray; - public copyWithin(target: int, start: int, end: int = this.length); - public entries(): ArrayIterator; - public every(callback: (number, int, TypedArray) => boolean, thisArg: Object=): boolean; - public fill(value: number, start: int = 0, end: int = this.length): TypedArray - public filter(callback: (number, int, TypedArray) => boolean, thisArg: Object=): TypedArray; - public find(callback: (number, int, TypedArray) => boolean, thisArg: Object=): number; - public findIndex(callback: (number, int, TypedArray) => boolean, thisArg: Object=): int; - public forEach(callback: (number, int, TypedArray) => void, thisArg: Object=): void; - public includes(searchElement: number, fromIndex: int = 0): boolean; - public indexOf(searchElement: number, fromIndex: int = 0): int; - public join(separator: string = ','): string; - public keys(): ArrayIterator; - public lastIndexOf(searchElement: number, fromIndex: int = this.length): int; - public map(callback: (number, int, TypedArray) => number, thisArg: Object=): TypedArray; - public reduce(callback: (number, number, int, TypedArray) => number, initialValue: number=): number; - public reduceRight(callback: (number, number, int, TypedArray) => number, initialValue: number=): number; - public reverse(): TypedArray; - public set(array: T[]|TypedArray, offset: int = 0): void; - public slice(begin: int = 0, end: int = this.length): TypedArray; - public some(callback: (number, int, TypedArray) => boolean, thisArg: Object=): boolean; - public sort(compareFunction: (number, number) => int = ): TypedArray; - public subarray(begin: int = 0, end: int = this.length): TypedArray; - public values(): ArrayIterator; - - @Override - public [Symbol.iterator](): Iterator; -} - -export external public class Int8Array extends TypedArray { - - public constructor(a1: int|TypedArray|Object|ArrayBuffer=, byteOffset: int=, length: int=); - - @Override - public static from(source: union{Iterable, ArrayLike, Iterator }, mapFn: (T) => number=, thisArg: Object=): Int8Array; - - @Override - public static of(...elements: T): Int8Array; - - @Override - public every(callback: (number, int, Int8Array) => boolean, thisArg: Object=): boolean; - - @Override - public fill(value: number, start: int = 0, end: int = this.length): Int8Array - - @Override - public filter(callback: (number, int, Int8Array) => boolean, thisArg: Object=): Int8Array; - - @Override - public find(callback: (number, int, Int8Array) => boolean, thisArg: Object=): number; - - @Override - public findIndex(callback: (number, int, Int8Array) => boolean, thisArg: Object=): int; - - @Override - public forEach(callback: (number, int, Int8Array) => void, thisArg: Object=): void; - - @Override - public map(callback: (number, int, Int8Array) => number, thisArg: Object=): Int8Array; - - @Override - public reduce(callback: (number, number, int, Int8Array) => number, initialValue: number=): number; - - @Override - public reduceRight(callback: (number, number, int, Int8Array) => number, initialValue: number=): number; - - @Override - public reverse(): Int8Array; - - @Override - public slice(begin: int = 0, end: int = this.length): Int8Array; - - @Override - public some(callback: (number, int, Int8Array) => boolean, thisArg: Object=): boolean; - - @Override - public sort(compareFunction: (number, number) => int = ): Int8Array; - - @Override - public subarray(begin: int = 0, end: int = this.length): Int8Array; -} - -export external public class Uint8Array extends TypedArray { - - public constructor(a1: int|TypedArray|Object|ArrayBuffer=, byteOffset: int=, length: int=); - - @Override - public static from(source: union{Iterable, ArrayLike, Iterator }, mapFn: (T) => number=, thisArg: Object=): Uint8Array; - - @Override - public static of(...elements: T): Uint8Array; - - @Override - public every(callback: (number, int, Uint8Array) => boolean, thisArg: Object=): boolean; - - @Override - public fill(value: number, start: int = 0, end: int = this.length): Uint8Array - - @Override - public filter(callback: (number, int, Uint8Array) => boolean, thisArg: Object=): Uint8Array; - - @Override - public find(callback: (number, int, Uint8Array) => boolean, thisArg: Object=): number; - - @Override - public findIndex(callback: (number, int, Uint8Array) => boolean, thisArg: Object=): int; - - @Override - public forEach(callback: (number, int, Uint8Array) => void, thisArg: Object=): void; - - @Override - public map(callback: (number, int, Uint8Array) => number, thisArg: Object=): Uint8Array; - - @Override - public reduce(callback: (number, number, int, Uint8Array) => number, initialValue: number=): number; - - @Override - public reduceRight(callback: (number, number, int, Uint8Array) => number, initialValue: number=): number; - - @Override - public reverse(): Uint8Array; - - @Override - public slice(begin: int = 0, end: int = this.length): Uint8Array; - - @Override - public some(callback: (number, int, Uint8Array) => boolean, thisArg: Object=): boolean; - - @Override - public sort(compareFunction: (number, number) => int = ): Uint8Array; - - @Override - public subarray(begin: int = 0, end: int = this.length): Uint8Array; -} - -export external public class Uint8ClampedArray extends TypedArray { - - public constructor(a1: int|TypedArray|Object|ArrayBuffer=, byteOffset: int=, length: int=); - - @Override - public static from(source: union{Iterable, ArrayLike, Iterator }, mapFn: (T) => number=, thisArg: Object=): Uint8ClampedArray; - - @Override - public static of(...elements: T): Uint8ClampedArray; - - @Override - public every(callback: (number, int, Uint8ClampedArray) => boolean, thisArg: Object=): boolean; - - @Override - public fill(value: number, start: int = 0, end: int = this.length): Uint8ClampedArray - - @Override - public filter(callback: (number, int, Uint8ClampedArray) => boolean, thisArg: Object=): Uint8ClampedArray; - - @Override - public find(callback: (number, int, Uint8ClampedArray) => boolean, thisArg: Object=): number; - - @Override - public findIndex(callback: (number, int, Uint8ClampedArray) => boolean, thisArg: Object=): int; - - @Override - public forEach(callback: (number, int, Uint8ClampedArray) => void, thisArg: Object=): void; - - @Override - public map(callback: (number, int, Uint8ClampedArray) => number, thisArg: Object=): Uint8ClampedArray; - - @Override - public reduce(callback: (number, number, int, Uint8ClampedArray) => number, initialValue: number=): number; - - @Override - public reduceRight(callback: (number, number, int, Uint8ClampedArray) => number, initialValue: number=): number; - - @Override - public reverse(): Uint8ClampedArray; - - @Override - public slice(begin: int = 0, end: int = this.length): Uint8ClampedArray; - - @Override - public some(callback: (number, int, Uint8ClampedArray) => boolean, thisArg: Object=): boolean; - - @Override - public sort(compareFunction: (number, number) => int = ): Uint8ClampedArray; - - @Override - public subarray(begin: int = 0, end: int = this.length): Uint8ClampedArray; -} - -export external public class Int16Array extends TypedArray { - - public constructor(a1: int|TypedArray|Object|ArrayBuffer=, byteOffset: int=, length: int=); - - @Override - public static from(source: union{Iterable, ArrayLike, Iterator }, mapFn: (T) => number=, thisArg: Object=): Int16Array; - - @Override - public static of(...elements: T): Int16Array; - - @Override - public every(callback: (number, int, Int16Array) => boolean, thisArg: Object=): boolean; - - @Override - public fill(value: number, start: int = 0, end: int = this.length): Int16Array - - @Override - public filter(callback: (number, int, Int16Array) => boolean, thisArg: Object=): Int16Array; - - @Override - public find(callback: (number, int, Int16Array) => boolean, thisArg: Object=): number; - - @Override - public findIndex(callback: (number, int, Int16Array) => boolean, thisArg: Object=): int; - - @Override - public forEach(callback: (number, int, Int16Array) => void, thisArg: Object=): void; - - @Override - public map(callback: (number, int, Int16Array) => number, thisArg: Object=): Int16Array; - - @Override - public reduce(callback: (number, number, int, Int16Array) => number, initialValue: number=): number; - - @Override - public reduceRight(callback: (number, number, int, Int16Array) => number, initialValue: number=): number; - - @Override - public reverse(): Int16Array; - - @Override - public slice(begin: int = 0, end: int = this.length): Int16Array; - - @Override - public some(callback: (number, int, Int16Array) => boolean, thisArg: Object=): boolean; - - @Override - public sort(compareFunction: (number, number) => int = ): Int16Array; - - @Override - public subarray(begin: int = 0, end: int = this.length): Int16Array; -} - -export external public class Uint16Array extends TypedArray { - - public constructor(a1: int|TypedArray|Object|ArrayBuffer=, byteOffset: int=, length: int=); - - @Override - public static from(source: union{Iterable, ArrayLike, Iterator }, mapFn: (T) => number=, thisArg: Object=): Uint16Array; - - @Override - public static of(...elements: T): Uint16Array; - - @Override - public every(callback: (number, int, Uint16Array) => boolean, thisArg: Object=): boolean; - - @Override - public fill(value: number, start: int = 0, end: int = this.length): Uint16Array - - @Override - public filter(callback: (number, int, Uint16Array) => boolean, thisArg: Object=): Uint16Array; - - @Override - public find(callback: (number, int, Uint16Array) => boolean, thisArg: Object=): number; - - @Override - public findIndex(callback: (number, int, Uint16Array) => boolean, thisArg: Object=): int; - - @Override - public forEach(callback: (number, int, Uint16Array) => void, thisArg: Object=): void; - - @Override - public map(callback: (number, int, Uint16Array) => number, thisArg: Object=): Uint16Array; - - @Override - public reduce(callback: (number, number, int, Uint16Array) => number, initialValue: number=): number; - - @Override - public reduceRight(callback: (number, number, int, Uint16Array) => number, initialValue: number=): number; - - @Override - public reverse(): Uint16Array; - - @Override - public slice(begin: int = 0, end: int = this.length): Uint16Array; - - @Override - public some(callback: (number, int, Uint16Array) => boolean, thisArg: Object=): boolean; - - @Override - public sort(compareFunction: (number, number) => int = ): Uint16Array; - - @Override - public subarray(begin: int = 0, end: int = this.length): Uint16Array; -} - -export external public class Int32Array extends TypedArray { - - public constructor(a1: int|TypedArray|Object|ArrayBuffer=, byteOffset: int=, length: int=); - - @Override - public static from(source: union{Iterable, ArrayLike, Iterator }, mapFn: (T) => number=, thisArg: Object=): Int32Array; - - @Override - public static of(...elements: T): Int32Array; - - @Override - public every(callback: (number, int, Int32Array) => boolean, thisArg: Object=): boolean; - - @Override - public fill(value: number, start: int = 0, end: int = this.length): Int32Array - - @Override - public filter(callback: (number, int, Int32Array) => boolean, thisArg: Object=): Int32Array; - - @Override - public find(callback: (number, int, Int32Array) => boolean, thisArg: Object=): number; - - @Override - public findIndex(callback: (number, int, Int32Array) => boolean, thisArg: Object=): int; - - @Override - public forEach(callback: (number, int, Int32Array) => void, thisArg: Object=): void; - - @Override - public map(callback: (number, int, Int32Array) => number, thisArg: Object=): Int32Array; - - @Override - public reduce(callback: (number, number, int, Int32Array) => number, initialValue: number=): number; - - @Override - public reduceRight(callback: (number, number, int, Int32Array) => number, initialValue: number=): number; - - @Override - public reverse(): Int32Array; - - @Override - public slice(begin: int = 0, end: int = this.length): Int32Array; - - @Override - public some(callback: (number, int, Int32Array) => boolean, thisArg: Object=): boolean; - - @Override - public sort(compareFunction: (number, number) => int = ): Int32Array; - - @Override - public subarray(begin: int = 0, end: int = this.length): Int32Array; -} - -export external public class Uint32Array extends TypedArray { - - public constructor(a1: int|TypedArray|Object|ArrayBuffer=, byteOffset: int=, length: int=); - - @Override - public static from(source: union{Iterable, ArrayLike, Iterator }, mapFn: (T) => number=, thisArg: Object=): Uint32Array; - - @Override - public static of(...elements: T): Uint32Array; - - @Override - public every(callback: (number, int, Uint32Array) => boolean, thisArg: Object=): boolean; - - @Override - public fill(value: number, start: int = 0, end: int = this.length): Uint32Array - - @Override - public filter(callback: (number, int, Uint32Array) => boolean, thisArg: Object=): Uint32Array; - - @Override - public find(callback: (number, int, Uint32Array) => boolean, thisArg: Object=): number; - - @Override - public findIndex(callback: (number, int, Uint32Array) => boolean, thisArg: Object=): int; - - @Override - public forEach(callback: (number, int, Uint32Array) => void, thisArg: Object=): void; - - @Override - public map(callback: (number, int, Uint32Array) => number, thisArg: Object=): Uint32Array; - - @Override - public reduce(callback: (number, number, int, Uint32Array) => number, initialValue: number=): number; - - @Override - public reduceRight(callback: (number, number, int, Uint32Array) => number, initialValue: number=): number; - - @Override - public reverse(): Uint32Array; - - @Override - public slice(begin: int = 0, end: int = this.length): Uint32Array; - - @Override - public some(callback: (number, int, Uint32Array) => boolean, thisArg: Object=): boolean; - - @Override - public sort(compareFunction: (number, number) => int = ): Uint32Array; - - @Override - public subarray(begin: int = 0, end: int = this.length): Uint32Array; -} - -export external public class Float32Array extends TypedArray { - - public constructor(a1: int|TypedArray|Object|ArrayBuffer=, byteOffset: int=, length: int=); - - @Override - public static from(source: union{Iterable, ArrayLike, Iterator }, mapFn: (T) => number=, thisArg: Object=): Float32Array; - - @Override - public static of(...elements: T): Float32Array; - - @Override - public every(callback: (number, int, Float32Array) => boolean, thisArg: Object=): boolean; - - @Override - public fill(value: number, start: int = 0, end: int = this.length): Float32Array - - @Override - public filter(callback: (number, int, Float32Array) => boolean, thisArg: Object=): Float32Array; - - @Override - public find(callback: (number, int, Float32Array) => boolean, thisArg: Object=): number; - - @Override - public findIndex(callback: (number, int, Float32Array) => boolean, thisArg: Object=): int; - - @Override - public forEach(callback: (number, int, Float32Array) => void, thisArg: Object=): void; - - @Override - public map(callback: (number, int, Float32Array) => number, thisArg: Object=): Float32Array; - - @Override - public reduce(callback: (number, number, int, Float32Array) => number, initialValue: number=): number; - - @Override - public reduceRight(callback: (number, number, int, Float32Array) => number, initialValue: number=): number; - - @Override - public reverse(): Float32Array; - - @Override - public slice(begin: int = 0, end: int = this.length): Float32Array; - - @Override - public some(callback: (number, int, Float32Array) => boolean, thisArg: Object=): boolean; - - @Override - public sort(compareFunction: (number, number) => int = ): Float32Array; - - @Override - public subarray(begin: int = 0, end: int = this.length): Float32Array; -} - -export external public class Float64Array extends TypedArray { - - public constructor(a1: int|TypedArray|Object|ArrayBuffer=, byteOffset: int=, length: int=); - - @Override - public static from(source: union{Iterable, ArrayLike, Iterator }, mapFn: (T) => number=, thisArg: Object=): Float64Array; - - @Override - public static of(...elements: T): Float64Array; - - @Override - public every(callback: (number, int, Float64Array) => boolean, thisArg: Object=): boolean; - - @Override - public fill(value: number, start: int = 0, end: int = this.length): Float64Array - - @Override - public filter(callback: (number, int, Float64Array) => boolean, thisArg: Object=): Float64Array; - - @Override - public find(callback: (number, int, Float64Array) => boolean, thisArg: Object=): number; - - @Override - public findIndex(callback: (number, int, Float64Array) => boolean, thisArg: Object=): int; - - @Override - public forEach(callback: (number, int, Float64Array) => void, thisArg: Object=): void; - - @Override - public map(callback: (number, int, Float64Array) => number, thisArg: Object=): Float64Array; - - @Override - public reduce(callback: (number, number, int, Float64Array) => number, initialValue: number=): number; - - @Override - public reduceRight(callback: (number, number, int, Float64Array) => number, initialValue: number=): number; - - @Override - public reverse(): Float64Array; - - @Override - public slice(begin: int = 0, end: int = this.length): Float64Array; - - @Override - public some(callback: (number, int, Float64Array) => boolean, thisArg: Object=): boolean; - - @Override - public sort(compareFunction: (number, number) => int = ): Float64Array; - - @Override - public subarray(begin: int = 0, end: int = this.length): Float64Array; -} - -export external public class DataView extends ArrayBufferView { - public constructor(buffer: ArrayBuffer, byteOffset: int=, byteLength: int=); - - public getInt8(byteOffset: int, littleEndian: boolean = false): number; - public getUint8(byteOffset: int, littleEndian: boolean = false): number; - public getInt16(byteOffset: int, littleEndian: boolean = false): number; - public getUint16(byteOffset: int, littleEndian: boolean = false): number; - public getInt32(byteOffset: int, littleEndian: boolean = false): number; - public getUint32(byteOffset: int, littleEndian: boolean = false): number; - public getFloat32(byteOffset: int, littleEndian: boolean = false): number; - public getFloat64(byteOffset: int, littleEndian: boolean = false): number; - - public setInt8(byteOffset: int, value: number, littleEndian: boolean = false): number; - public setUint8(byteOffset: int, value: number, littleEndian: boolean = false): number; - public setInt16(byteOffset: int, value: number, littleEndian: boolean = false): number; - public setUint16(byteOffset: int, value: number, littleEndian: boolean = false): number; - public setInt32(byteOffset: int, value: number, littleEndian: boolean = false): number; - public setUint32(byteOffset: int, value: number, littleEndian: boolean = false): number; - public setFloat32(byteOffset: int, value: number, littleEndian: boolean = false): number; - public setFloat64(byteOffset: int, value: number, littleEndian: boolean = false): number; -} \ No newline at end of file diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2016.array.include.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2016.array.include.n4jsd new file mode 100644 index 0000000000..2e66bd7b39 --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2016.array.include.n4jsd @@ -0,0 +1,51 @@ +@@Global @@ProvidedByRuntime + +@Polyfill +export external public class Array extends Array { + public includes(searchElement: T, fromIndex: number = ): boolean; +} + +@Polyfill +export external public class Int8Array extends Int8Array { + public includes(searchElement: number, fromIndex: number = ): boolean; +} + +@Polyfill +export external public class Uint8Array extends Uint8Array { + public includes(searchElement: number, fromIndex: number = ): boolean; +} + +@Polyfill +export external public class Uint8ClampedArray extends Uint8ClampedArray { + public includes(searchElement: number, fromIndex: number = ): boolean; +} + +@Polyfill +export external public class Int16Array extends Int16Array { + public includes(searchElement: number, fromIndex: number = ): boolean; +} + +@Polyfill +export external public class Uint16Array extends Uint16Array { + public includes(searchElement: number, fromIndex: number = ): boolean; +} + +@Polyfill +export external public class Int32Array extends Int32Array { + public includes(searchElement: number, fromIndex: number = ): boolean; +} + +@Polyfill +export external public class Uint32Array extends Uint32Array { + public includes(searchElement: number, fromIndex: number = ): boolean; +} + +@Polyfill +export external public class Float32Array extends Float32Array { + public includes(searchElement: number, fromIndex: number = ): boolean; +} + +@Polyfill +export external public class Float64Array extends Float64Array { + public includes(searchElement: number, fromIndex: number = ): boolean; +} diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2017.intl.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2017.intl.n4jsd new file mode 100644 index 0000000000..4854a822d1 --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2017.intl.n4jsd @@ -0,0 +1,3 @@ +@@Global @@ProvidedByRuntime + + diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2017.object.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2017.object.n4jsd new file mode 100644 index 0000000000..345a233434 --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2017.object.n4jsd @@ -0,0 +1,8 @@ +@@Global @@ProvidedByRuntime + +@Polyfill +export external public class Object extends Object { + public static values(obj: Object): any[]; + public static entries(obj: Object): Iterable2[]; + public static getOwnPropertyDescriptors(o: T): Object+ & ~Object+; +} diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2017.sharedmemory.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2017.sharedmemory.n4jsd new file mode 100644 index 0000000000..62be4e0be2 --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2017.sharedmemory.n4jsd @@ -0,0 +1,31 @@ +@@Global @@ProvidedByRuntime + +export external public class SharedArrayBuffer { + public get byteLength(): number; + public slice(begin: number, end: number = ): SharedArrayBuffer; + public get [Symbol.species](): SharedArrayBuffer; + public get [Symbol.toStringTag](): "SharedArrayBuffer"; + public constructor(byteLength: number); +} + +export external public type SharedArrayBufferConstructor = constructor{SharedArrayBuffer}; + +export external public interface ~ArrayBufferTypes { + SharedArrayBuffer: SharedArrayBuffer; +} + +export external public class Atomics { + public static add(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + public static and(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + public static compareExchange(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, expectedValue: number, replacementValue: number): number; + public static exchange(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + public static isLockFree(size: number): boolean; + public static load(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number): number; + public static or(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + public static store(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + public static sub(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + public static wait(typedArray: Int32Array, index: number, value: number, timeout: number = ): "ok" | "not-equal" | "timed-out"; + public static notify(typedArray: Int32Array, index: number, count: number = ): number; + public static xor(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + public static get [Symbol.toStringTag](): "Atomics"; +} diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2017.string.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2017.string.n4jsd new file mode 100644 index 0000000000..5679772df9 --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2017.string.n4jsd @@ -0,0 +1,7 @@ +@@Global @@ProvidedByRuntime + +@Polyfill +export external public class String extends String { + public padStart(maxLength: number, fillString: string = ): string; + public padEnd(maxLength: number, fillString: string = ): string; +} diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2017.typedarrays.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2017.typedarrays.n4jsd new file mode 100644 index 0000000000..98fc6636de --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2017.typedarrays.n4jsd @@ -0,0 +1,28 @@ +@@Global @@ProvidedByRuntime + +@Polyfill +export external public class Int8Array extends Int8Array {} + +@Polyfill +export external public class Uint8Array extends Uint8Array {} + +@Polyfill +export external public class Uint8ClampedArray extends Uint8ClampedArray {} + +@Polyfill +export external public class Int16Array extends Int16Array {} + +@Polyfill +export external public class Uint16Array extends Uint16Array {} + +@Polyfill +export external public class Int32Array extends Int32Array {} + +@Polyfill +export external public class Uint32Array extends Uint32Array {} + +@Polyfill +export external public class Float32Array extends Float32Array {} + +@Polyfill +export external public class Float64Array extends Float64Array {} diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2018.asyncgenerator.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2018.asyncgenerator.n4jsd new file mode 100644 index 0000000000..2bbf475f13 --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2018.asyncgenerator.n4jsd @@ -0,0 +1,15 @@ +@@Global @@ProvidedByRuntime + +export external public interface ~AsyncGeneratorFunction { + @CovariantConstructor + constructor(...args: any); + get length(): number; + get name(): string; +} + +export external public interface ~AsyncGeneratorFunctionConstructor { + @CovariantConstructor + constructor(...args: string); + get length(): number; + get name(): string; +} diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2018.asynciterable.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2018.asynciterable.n4jsd new file mode 100644 index 0000000000..b7c6e3d35b --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2018.asynciterable.n4jsd @@ -0,0 +1,8 @@ +@@Global @@ProvidedByRuntime + +@Polyfill +export external public class Symbol extends Symbol {} + +export external public interface ~AsyncIterableIterator extends AsyncIterator { + [Symbol.asyncIterator](): AsyncIterableIterator; +} diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2018.intl.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2018.intl.n4jsd new file mode 100644 index 0000000000..4854a822d1 --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2018.intl.n4jsd @@ -0,0 +1,3 @@ +@@Global @@ProvidedByRuntime + + diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2018.promise.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2018.promise.n4jsd new file mode 100644 index 0000000000..61a20c11ec --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2018.promise.n4jsd @@ -0,0 +1,8 @@ +@@Global @@ProvidedByRuntime + + + +@Polyfill +export external public class Promise extends Promise { + public finally(onfinally: (()=>void) = ): Promise; +} diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2018.regexp.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2018.regexp.n4jsd new file mode 100644 index 0000000000..b3a5a8fa72 --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2018.regexp.n4jsd @@ -0,0 +1,16 @@ +@@Global @@ProvidedByRuntime + +@Polyfill +export external public class ~RegExpMatchArray extends RegExpMatchArray { + public groups?: ~Object+; +} + +@Polyfill +export external public class ~RegExpExecArray extends RegExpExecArray { + public groups?: ~Object+; +} + +@Polyfill +export external public class RegExp extends RegExp { + public get dotAll(): boolean; +} diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2019.array.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2019.array.n4jsd new file mode 100644 index 0000000000..b599ccde10 --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2019.array.n4jsd @@ -0,0 +1,9 @@ +@@Global @@ProvidedByRuntime + +export external public type FlatArray = any+; + +@Polyfill +export external public class Array extends Array { + public flatMap(callback: {@This(This) function(value: T, index: number, array: Array): (U | ReadonlyArray)}, thisArg: This = ): Array; + public flat(depth: D = ): Array>; +} diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2019.object.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2019.object.n4jsd new file mode 100644 index 0000000000..5b4bd5644f --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2019.object.n4jsd @@ -0,0 +1,6 @@ +@@Global @@ProvidedByRuntime + +@Polyfill +export external public class Object extends Object { + public static fromEntries(...args: any+): any+; // overloading not supported +} diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2019.string.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2019.string.n4jsd new file mode 100644 index 0000000000..5820685a56 --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2019.string.n4jsd @@ -0,0 +1,9 @@ +@@Global @@ProvidedByRuntime + +@Polyfill +export external public class String extends String { + public trimEnd(): string; + public trimStart(): string; + public trimLeft(): string; + public trimRight(): string; +} diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2019.symbol.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2019.symbol.n4jsd new file mode 100644 index 0000000000..e3b8263f3c --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2019.symbol.n4jsd @@ -0,0 +1,6 @@ +@@Global @@ProvidedByRuntime + +@Polyfill +export external public class Symbol extends Symbol { + public get description(): string; +} diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.bigint.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.bigint.n4jsd new file mode 100644 index 0000000000..e2b4a69353 --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.bigint.n4jsd @@ -0,0 +1,132 @@ +@@Global @@ProvidedByRuntime + +export external public interface ~BigIntToLocaleStringOptions { + localeMatcher?: string; + style?: string; + numberingSystem?: string; + unit?: string; + unitDisplay?: string; + currency?: string; + currencyDisplay?: string; + useGrouping?: boolean; + minimumIntegerDigits?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21; + minimumFractionDigits?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20; + maximumFractionDigits?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20; + minimumSignificantDigits?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21; + maximumSignificantDigits?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21; + notation?: string; + compactDisplay?: string; +} + +export external public class BigInt { + @Override + public toString(radix: number = ): string; + @Override + public toLocaleString(locales: string = , options: BigIntToLocaleStringOptions = ): string; + @Override + public valueOf(): any+; + public get [Symbol.toStringTag](): "BigInt"; + (value: any+ | boolean | number | string): any+; + public static asIntN(bits: number, int: any+): any+; + public static asUintN(bits: number, int: any+): any+; +} + +export external public type BigIntConstructor = constructor{BigInt}; + +export external public class BigInt64Array { + public get BYTES_PER_ELEMENT(): number; + public get buffer(): ArrayBufferLike; + public get byteLength(): number; + public get byteOffset(): number; + public copyWithin(target: number, start: number, end: number = ): this; + public entries(): IterableIterator<[number,any+]>; + public every(predicate: (value: any+, index: number, array: BigInt64Array)=>boolean, thisArg: any = ): boolean; + public fill(value: any+, start: number = , end: number = ): this; + public filter(predicate: (value: any+, index: number, array: BigInt64Array)=>any, thisArg: any = ): BigInt64Array; + public find(predicate: (value: any+, index: number, array: BigInt64Array)=>boolean, thisArg: any = ): any+; + public findIndex(predicate: (value: any+, index: number, array: BigInt64Array)=>boolean, thisArg: any = ): number; + public forEach(callbackfn: (value: any+, index: number, array: BigInt64Array)=>void, thisArg: any = ): void; + public includes(searchElement: any+, fromIndex: number = ): boolean; + public indexOf(searchElement: any+, fromIndex: number = ): number; + public join(separator: string = ): string; + public keys(): IterableIterator; + public lastIndexOf(searchElement: any+, fromIndex: number = ): number; + public get length(): number; + public map(callbackfn: (value: any+, index: number, array: BigInt64Array)=>any+, thisArg: any = ): BigInt64Array; + public reduce(...args: any+): any+; // overloading not supported + public reduceRight(...args: any+): any+; // overloading not supported + public reverse(): this; + public set(array: ArrayLike, offset: number = ): void; + public slice(start: number = , end: number = ): BigInt64Array; + public some(predicate: (value: any+, index: number, array: BigInt64Array)=>boolean, thisArg: any = ): boolean; + public sort(compareFn: (a: any+, b: any+)=>(number | any+) = ): this; + public subarray(begin: number = , end: number = ): BigInt64Array; + @Override + public toLocaleString(): string; + @Override + public toString(): string; + @Override + public valueOf(): BigInt64Array; + public values(): IterableIterator; + public [Symbol.iterator](): IterableIterator; + public get [Symbol.toStringTag](): "BigInt64Array"; + public constructor(...args: any+); // overloading not supported + public static get BYTES_PER_ELEMENT(): number; + public static of(...items: any+): BigInt64Array; + public static from(...args: any+): any+; // overloading not supported +} + +export external public type BigInt64ArrayConstructor = constructor{BigInt64Array}; + +export external public class BigUint64Array { + public get BYTES_PER_ELEMENT(): number; + public get buffer(): ArrayBufferLike; + public get byteLength(): number; + public get byteOffset(): number; + public copyWithin(target: number, start: number, end: number = ): this; + public entries(): IterableIterator<[number,any+]>; + public every(predicate: (value: any+, index: number, array: BigUint64Array)=>boolean, thisArg: any = ): boolean; + public fill(value: any+, start: number = , end: number = ): this; + public filter(predicate: (value: any+, index: number, array: BigUint64Array)=>any, thisArg: any = ): BigUint64Array; + public find(predicate: (value: any+, index: number, array: BigUint64Array)=>boolean, thisArg: any = ): any+; + public findIndex(predicate: (value: any+, index: number, array: BigUint64Array)=>boolean, thisArg: any = ): number; + public forEach(callbackfn: (value: any+, index: number, array: BigUint64Array)=>void, thisArg: any = ): void; + public includes(searchElement: any+, fromIndex: number = ): boolean; + public indexOf(searchElement: any+, fromIndex: number = ): number; + public join(separator: string = ): string; + public keys(): IterableIterator; + public lastIndexOf(searchElement: any+, fromIndex: number = ): number; + public get length(): number; + public map(callbackfn: (value: any+, index: number, array: BigUint64Array)=>any+, thisArg: any = ): BigUint64Array; + public reduce(...args: any+): any+; // overloading not supported + public reduceRight(...args: any+): any+; // overloading not supported + public reverse(): this; + public set(array: ArrayLike, offset: number = ): void; + public slice(start: number = , end: number = ): BigUint64Array; + public some(predicate: (value: any+, index: number, array: BigUint64Array)=>boolean, thisArg: any = ): boolean; + public sort(compareFn: (a: any+, b: any+)=>(number | any+) = ): this; + public subarray(begin: number = , end: number = ): BigUint64Array; + @Override + public toLocaleString(): string; + @Override + public toString(): string; + @Override + public valueOf(): BigUint64Array; + public values(): IterableIterator; + public [Symbol.iterator](): IterableIterator; + public get [Symbol.toStringTag](): "BigUint64Array"; + public constructor(...args: any+); // overloading not supported + public static get BYTES_PER_ELEMENT(): number; + public static of(...items: any+): BigUint64Array; + public static from(...args: any+): any+; // overloading not supported +} + +export external public type BigUint64ArrayConstructor = constructor{BigUint64Array}; + +@Polyfill +export external public class DataView extends DataView { + public getBigInt64(byteOffset: number, littleEndian: boolean = ): any+; + public getBigUint64(byteOffset: number, littleEndian: boolean = ): any+; + public setBigInt64(byteOffset: number, value: any+, littleEndian: boolean = ): void; + public setBigUint64(byteOffset: number, value: any+, littleEndian: boolean = ): void; +} diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.globalThis.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.globalThis.n4jsd new file mode 100644 index 0000000000..3ee2d7b2ed --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.globalThis.n4jsd @@ -0,0 +1,8 @@ +@@Global @@ProvidedByRuntime +export external public const globalThis: Object+; + +// Before, this was defined in "globalThis.n4jsd" of "n4js-runtime-esnext" as follows: +// @@Global @@ProvidedByRuntime +// export external public const globalThis: Object+; +// and in "globalThis.n4jsd" of "n4js-runtime-html5" it was commented out as follows: +// //export external public const globalThis: Window+; diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.intl.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.intl.n4jsd new file mode 100644 index 0000000000..4854a822d1 --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.intl.n4jsd @@ -0,0 +1,3 @@ +@@Global @@ProvidedByRuntime + + diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.promise.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.promise.n4jsd new file mode 100644 index 0000000000..4eb4f22336 --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.promise.n4jsd @@ -0,0 +1,18 @@ +@@Global @@ProvidedByRuntime + +export external public interface ~PromiseFulfilledResult { + status: "fulfilled"; + value: T; +} + +export external public interface ~PromiseRejectedResult { + status: "rejected"; + reason: any; +} + +export external public type PromiseSettledResult = PromiseFulfilledResult | PromiseRejectedResult; + +@Polyfill +export external public class Promise extends Promise { + public static allSettled(...args: any+): any+; // overloading not supported +} diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.sharedmemory.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.sharedmemory.n4jsd new file mode 100644 index 0000000000..c19f845e7a --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.sharedmemory.n4jsd @@ -0,0 +1,4 @@ +@@Global @@ProvidedByRuntime + +@Polyfill +export external public class Atomics extends Atomics {} diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.string.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.string.n4jsd new file mode 100644 index 0000000000..4346cbc6a5 --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.string.n4jsd @@ -0,0 +1,6 @@ +@@Global @@ProvidedByRuntime + +@Polyfill +export external public class String extends String { + public matchAll(regexp: RegExp): IterableIterator; +} diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.symbol.wellknown.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.symbol.wellknown.n4jsd new file mode 100644 index 0000000000..c7a3e16070 --- /dev/null +++ b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/es2020.symbol.wellknown.n4jsd @@ -0,0 +1,9 @@ +@@Global @@ProvidedByRuntime + +@Polyfill +export external public class Symbol extends Symbol {} + +@Polyfill +export external public class RegExp extends RegExp { + public [Symbol.matchAll](str: string): IterableIterator; +} diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/globalThis.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/globalThis.n4jsd deleted file mode 100644 index 0635aed1f9..0000000000 --- a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/globalThis.n4jsd +++ /dev/null @@ -1,13 +0,0 @@ -/* - * Copyright (c) 2020 NumberFour AG. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * NumberFour AG - Initial API and implementation - */ -@@Global @@ProvidedByRuntime - -export external public const globalThis: Object+; diff --git a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/immediate.n4jsd b/n4js-libs/packages/n4js-runtime-esnext/src/n4js/immediate.n4jsd deleted file mode 100644 index 3d1a415f7c..0000000000 --- a/n4js-libs/packages/n4js-runtime-esnext/src/n4js/immediate.n4jsd +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright (c) 2017 NumberFour AG. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * NumberFour AG - Initial API and implementation - */ -@@Global @@ProvidedByRuntime - -export external public function setImmediate(fn: Function): number; -export external public function clearImmediate(handle: number): void; - diff --git a/n4js-libs/packages/n4js-runtime-fetch/src/n4js/fetch/Headers.n4jsd b/n4js-libs/packages/n4js-runtime-fetch/src/n4js/fetch/Headers.n4jsd index 76957ac55d..d238d398bb 100644 --- a/n4js-libs/packages/n4js-runtime-fetch/src/n4js/fetch/Headers.n4jsd +++ b/n4js-libs/packages/n4js-runtime-fetch/src/n4js/fetch/Headers.n4jsd @@ -10,8 +10,6 @@ */ @@Global @@ProvidedByRuntime -import {IteratorExt} from "Iterator"; - export external public class Headers implements Iterable> { public append(name: string, value: string): void; public delete(name: string): void; @@ -20,8 +18,8 @@ export external public class Headers implements Iterable>; + public entries(): IterableIterator>; public forEach(callback: (value: string, name: string, context: Object) => void, context: Object=): void; - @Override public [Symbol.iterator](): IteratorExt>; + @Override public [Symbol.iterator](): IterableIterator>; } diff --git a/n4js-libs/packages/n4js-runtime-html5/src/n4js/webcrypto.n4jsd b/n4js-libs/packages/n4js-runtime-html5/src/n4js/webcrypto.n4jsd index 3b39dc0e37..10a76846f2 100644 --- a/n4js-libs/packages/n4js-runtime-html5/src/n4js/webcrypto.n4jsd +++ b/n4js-libs/packages/n4js-runtime-html5/src/n4js/webcrypto.n4jsd @@ -4,14 +4,14 @@ export external public const crypto: Crypto; export external public interface Crypto { public get subtle(): SubtleCrypto; - public getRandomValues(typedArray: TypedArray); + public getRandomValues(typedArray: ArrayBufferView); } export external public interface SubtleCrypto { - public decrypt(algorithm: CryptoEncryptDecryptAlgorithm, key: CryptoKey, data: ArrayBuffer|TypedArray): Promise; + public decrypt(algorithm: CryptoEncryptDecryptAlgorithm, key: CryptoKey, data: ArrayBuffer|ArrayBufferView): Promise; public deriveKey(algorithm: CryptoDeriveKeyAlgorithm, masterKey: CryptoKey, derivedKeyAlgorithm: CryptoAlgorithm, extractable: boolean, keyUsages: string /* CryptoKeyUsage */[]): Promise; public digest(algorithm: string, buffer: ArrayBuffer|ArrayBufferView): Promise; - public encrypt(algorithm: CryptoEncryptDecryptAlgorithm, key: CryptoKey, data: ArrayBuffer|TypedArray): Promise; + public encrypt(algorithm: CryptoEncryptDecryptAlgorithm, key: CryptoKey, data: ArrayBuffer|ArrayBufferView): Promise; public exportKey(format: string /* CryptoKeyFormat */, key: CryptoKey): Promise public generateKey(algorithm: CryptoGenerateKeyAlgorithm, extractable: boolean, keyUsages: string /* CryptoKeyUsage */[]): Promise; public importKey(format: string /* CryptoKeyFormat */, keyData: ArrayBuffer|string, algorithm: CryptoGenerateKeyAlgorithm, extractable: boolean, usages: string /* CryptoKeyUsage */[]): Promise; diff --git a/n4js-libs/packages/n4js-runtime-v8/src/n4js/Error.n4jsd b/n4js-libs/packages/n4js-runtime-v8/src/n4js/Error.n4jsd index af3afbfc92..3b5461653f 100644 --- a/n4js-libs/packages/n4js-runtime-v8/src/n4js/Error.n4jsd +++ b/n4js-libs/packages/n4js-runtime-v8/src/n4js/Error.n4jsd @@ -11,6 +11,5 @@ @@Global @@ProvidedByRuntime @Polyfill export external public class Error extends Error { - public stack?: string; + @Override public stack?: string; } - diff --git a/n4js-libs/packages/n4js-runtime/src/n4js/Runtime.n4js b/n4js-libs/packages/n4js-runtime/src/n4js/Runtime.n4js index ee68cb4b2c..3e3fda1e4f 100644 --- a/n4js-libs/packages/n4js-runtime/src/n4js/Runtime.n4js +++ b/n4js-libs/packages/n4js-runtime/src/n4js/Runtime.n4js @@ -63,10 +63,11 @@ function $getReflectionForEnum(staticProto: Object, reflectionString: string) { */ function $defineFields(target: Object, ...names: string) { for (const name of names) { - Object.defineProperty(target, name, { + Object.defineProperty(target, name, { writable: true, enumerable: true, - configurable: true + configurable: true, + value: undefined }); } } diff --git a/n4js-libs/packages/org.eclipse.n4js.mangelhaft.assert.test/package.json b/n4js-libs/packages/org.eclipse.n4js.mangelhaft.assert.test/package.json index 36c9f8975f..f936362017 100644 --- a/n4js-libs/packages/org.eclipse.n4js.mangelhaft.assert.test/package.json +++ b/n4js-libs/packages/org.eclipse.n4js.mangelhaft.assert.test/package.json @@ -32,7 +32,8 @@ }, "requiredRuntimeLibraries": [ "n4js-runtime-v8", - "n4js-runtime-es2015" + "n4js-runtime-es2015", + "n4js-runtime-node" ] }, "dependencies": { @@ -40,7 +41,8 @@ "org.eclipse.n4js.mangelhaft.assert": "^0.1.0", "n4js-runtime": "^0.1.0", "n4js-runtime-v8": "^0.1.0", - "n4js-runtime-es2015": "^0.1.0" + "n4js-runtime-es2015": "^0.1.0", + "n4js-runtime-node": "^0.1.0" }, "devDependencies": {} } diff --git a/n4js-libs/packages/org.eclipse.n4js.mangelhaft.assert/package.json b/n4js-libs/packages/org.eclipse.n4js.mangelhaft.assert/package.json index 829fbccd7a..d88cb22d94 100644 --- a/n4js-libs/packages/org.eclipse.n4js.mangelhaft.assert/package.json +++ b/n4js-libs/packages/org.eclipse.n4js.mangelhaft.assert/package.json @@ -31,13 +31,15 @@ }, "requiredRuntimeLibraries": [ "n4js-runtime-v8", - "n4js-runtime-es2015" + "n4js-runtime-es2015", + "n4js-runtime-node" ] }, "dependencies": { "n4js-runtime": "^0.1.0", "n4js-runtime-v8": "^0.1.0", - "n4js-runtime-es2015": "^0.1.0" + "n4js-runtime-es2015": "^0.1.0", + "n4js-runtime-node": "^0.1.0" }, "devDependencies": {} } diff --git a/n4js-libs/packages/org.eclipse.n4js.mangelhaft.test/package.json b/n4js-libs/packages/org.eclipse.n4js.mangelhaft.test/package.json index b4834441a4..3d00b4b76d 100644 --- a/n4js-libs/packages/org.eclipse.n4js.mangelhaft.test/package.json +++ b/n4js-libs/packages/org.eclipse.n4js.mangelhaft.test/package.json @@ -31,14 +31,16 @@ ] }, "requiredRuntimeLibraries": [ - "n4js-runtime-es2015" + "n4js-runtime-es2015", + "n4js-runtime-node" ] }, "dependencies": { "org.eclipse.n4js.mangelhaft": "^0.1.0", "org.eclipse.n4js.mangelhaft.assert": "^0.1.0", "n4js-runtime": "^0.1.0", - "n4js-runtime-es2015": "^0.1.0" + "n4js-runtime-es2015": "^0.1.0", + "n4js-runtime-node": "^0.1.0" }, "devDependencies": {} } diff --git a/n4js-libs/packages/org.eclipse.n4js.mangelhaft/src/n4js/org/eclipse/n4js/mangelhaft/TestExecutor.n4js b/n4js-libs/packages/org.eclipse.n4js.mangelhaft/src/n4js/org/eclipse/n4js/mangelhaft/TestExecutor.n4js index 7184ea918a..6c093c9a78 100644 --- a/n4js-libs/packages/org.eclipse.n4js.mangelhaft/src/n4js/org/eclipse/n4js/mangelhaft/TestExecutor.n4js +++ b/n4js-libs/packages/org.eclipse.n4js.mangelhaft/src/n4js/org/eclipse/n4js/mangelhaft/TestExecutor.n4js @@ -312,7 +312,7 @@ function getExecutingFunction(instrumentedTest: IInstrumentedTest): (TestMethodD return testMethodDescriptor => (new Promise((resolve, reject) => { const pr = Promise.resolve(testMethodDescriptor.value.call(instrumentedTest.testObject)); - let timeoutId: int; + let timeoutId: Timeout; if (!process.env.N4JS_RT_mangelhaft_timeout_disabled) { timeoutId = setTimeout(() => reject(new Error(`Test object ${testMethodDescriptor.name} timed out after ${testMethodDescriptor.timeout} milliseconds`)), testMethodDescriptor.timeout); } diff --git a/n4js-libs/packages/org.eclipse.n4js.mangelhaft/src/n4js/org/eclipse/n4js/mangelhaft/util/proc.n4js b/n4js-libs/packages/org.eclipse.n4js.mangelhaft/src/n4js/org/eclipse/n4js/mangelhaft/util/proc.n4js index 3f0fd6a043..c8b0dbd928 100644 --- a/n4js-libs/packages/org.eclipse.n4js.mangelhaft/src/n4js/org/eclipse/n4js/mangelhaft/util/proc.n4js +++ b/n4js-libs/packages/org.eclipse.n4js.mangelhaft/src/n4js/org/eclipse/n4js/mangelhaft/util/proc.n4js @@ -14,7 +14,7 @@ * Optionally the event loop can be kept active while the promise hasn't resolved. */ export public function waitAndExitProcess(proc: Function, keepEventLoop = false): void { - let timerHandle: number; + let timerHandle: Timeout; if (keepEventLoop) { // dummy interval to avoid termination on open main/exec promise: timerHandle = setInterval(function() {}, 0x7fffffff /* max 32bit signed int */); diff --git a/n4js-tools/n4jsd-generator/.gitignore b/n4js-tools/n4jsd-generator/.gitignore index 49a831d454..35ab6361c1 100644 --- a/n4js-tools/n4jsd-generator/.gitignore +++ b/n4js-tools/n4jsd-generator/.gitignore @@ -3,3 +3,4 @@ .vscode node_modules src-gen +/TEMP/ diff --git a/n4js-tools/n4jsd-generator/src/n4js/cmdLineOpts.n4js b/n4js-tools/n4jsd-generator/src/n4js/cmdLineOpts.n4js index 0030cc2765..3d4f94f5d1 100644 --- a/n4js-tools/n4jsd-generator/src/n4js/cmdLineOpts.n4js +++ b/n4js-tools/n4jsd-generator/src/n4js/cmdLineOpts.n4js @@ -35,6 +35,13 @@ OPTIONS out as 'any+'. When this option is given, type references will be copied over from the TypeScript source code without change (might cause syntax errors, etc. on the N4JS side). +--no-doc + Do not copy JSDoc comments from '.d.ts' to N4JSD files. + +--runtime-libs + The '.d.ts' files to convert represent runtime library definitions. This modifies compilation of the + input files and generation of the output code in various ways. Only intended for internal use. + --verbose, -v Print more information while running. @@ -56,6 +63,8 @@ export interface Options { inputPaths: string[]; outputPath?: string; copyTypeRefs: boolean; + noDoc: boolean; + runtimeLibs: boolean; verbose: boolean; force: boolean; /** A fatal error encountered during command line option parsing. */ @@ -77,12 +86,16 @@ class Option { const OPT_FORCE = new Option([ "--force", "-f" ], false, (opts) => opts.force = true); const OPT_OUTPUT = new Option([ "--output", "-o" ], true, (opts, arg) => opts.outputPath = arg); const OPT_COPY_TYPE_REFS = new Option([ "--copy-type-refs" ], false, (opts) => opts.copyTypeRefs = true); +const OPT_NO_DOC = new Option([ "--no-doc" ], false, (opts) => opts.noDoc = true); +const OPT_RUNTIME_LIBS = new Option([ "--runtime-libs" ], false, (opts) => opts.runtimeLibs = true); const OPT_VERBOSE = new Option([ "--verbose", "-v" ], false, (opts) => opts.verbose = true); const allOptions = [ OPT_FORCE, OPT_OUTPUT, OPT_COPY_TYPE_REFS, + OPT_NO_DOC, + OPT_RUNTIME_LIBS, OPT_VERBOSE ]; diff --git a/n4js-tools/n4jsd-generator/src/n4js/convert.n4jsd b/n4js-tools/n4jsd-generator/src/n4js/convert.n4jsd index aecf64cb59..b4b6c22bb1 100644 --- a/n4js-tools/n4jsd-generator/src/n4js/convert.n4jsd +++ b/n4js-tools/n4jsd-generator/src/n4js/convert.n4jsd @@ -11,9 +11,11 @@ import * as model from "model"; +export external type IgnorePredicate = (filePath: string, elementName: string =, memberName: string =, signatureIndex: int =) => boolean; + export external public class Converter { - constructor(sourceDtsFilePaths: string[], projectPath: string =); + constructor(sourceDtsFilePaths: string[], projectPath: string =, ignorePredicate: IgnorePredicate =, runtimeLibs: boolean =); convertScript(sourceFilePath: string): model.Script; diff --git a/n4js-tools/n4jsd-generator/src/n4js/generator.n4js b/n4js-tools/n4jsd-generator/src/n4js/generator.n4js index 40c5641923..d3e9901a31 100644 --- a/n4js-tools/n4jsd-generator/src/n4js/generator.n4js +++ b/n4js-tools/n4jsd-generator/src/n4js/generator.n4js @@ -14,7 +14,8 @@ import * as path_lib from "path"; import { USAGE, Options, parseCommandLineOptions } from "cmdLineOpts"; import * as model from "model"; -import { Converter } from "convert"; +import { Converter, IgnorePredicate } from "convert"; +import * as runtimeLibs from "runtimeLibs" import * as utils from "utils"; @@ -65,7 +66,14 @@ function processFileOrFolder(inputPath: string, opts: Options) { return; } - const converter = new Converter(sourceDtsFilePaths, sourceProjectPath); + let ignorePredicate: IgnorePredicate = undefined; + if (opts.runtimeLibs) { + ignorePredicate = (filePath, elementName, memberName, signatureIndex) => { + return runtimeLibs.isIgnored(filePath, elementName, memberName, signatureIndex); + }; + } + + const converter = new Converter(sourceDtsFilePaths, sourceProjectPath, ignorePredicate, opts.runtimeLibs); // check for compile errors on TypeScript side // TODO: this seems to take a long time and is not strictly necessary; consider removing it or making it optional! @@ -75,17 +83,17 @@ function processFileOrFolder(inputPath: string, opts: Options) { return; } - const scripts = new Map(); + const scripts: model.Script[] = []; let hasIssues = false; for (const srcDtsPath of sourceDtsFilePaths) { const script = converter.convertScript(srcDtsPath); - scripts.set(srcDtsPath, script); + scripts.push(script); hasIssues = hasIssues || script.issues.length > 0; } if (hasIssues) { - for (const srcDtsPath of sourceDtsFilePaths) { - const script = scripts.get(srcDtsPath); + for (const script of scripts) { + const srcDtsPath = script.tsFilePath; if (script.issues.length > 0) { utils.log(srcDtsPath + ":"); utils.logIssues(script.issues); @@ -96,6 +104,19 @@ function processFileOrFolder(inputPath: string, opts: Options) { } } + // perform adjustments for runtime libraries (if requested) + if (opts.runtimeLibs) { + try { + runtimeLibs.postProcessRuntimeLibs(scripts); // will change scripts in place and may add additional scripts to the given array + } catch(err) { + if (err instanceof runtimeLibs.RuntimeLibsError) { + utils.logError(err.message); + return; // abort (even if opts.force is true) + } + throw err; + } + } + // create target project (if necessary) let targetProjectPath: string = undefined; if (sourceProjectPath !== undefined) { @@ -107,15 +128,15 @@ function processFileOrFolder(inputPath: string, opts: Options) { } // create target n4jsd-files - for (const srcDtsPath of sourceDtsFilePaths) { - const script = scripts.get(srcDtsPath); + for (const script of scripts) { + const srcDtsPath = script.tsFilePath; const n4jsdStr = model.scriptToString(script); const trgtN4jsdPath = chooseTargetN4jsdPath(srcDtsPath, sourceProjectPath, targetProjectPath); if (opts.verbose) { utils.log("Writing n4jsd-file: " + trgtN4jsdPath); } utils.mkdirs(path_lib.dirname(trgtN4jsdPath)); - fs_lib.writeFileSync(trgtN4jsdPath, n4jsdStr + "\n", undefined); + fs_lib.writeFileSync(trgtN4jsdPath, n4jsdStr, undefined); } } diff --git a/n4js-tools/n4jsd-generator/src/n4js/model.n4js b/n4js-tools/n4jsd-generator/src/n4js/model.n4js index b0a1c6b8ba..ee4ad5d1d5 100644 --- a/n4js-tools/n4jsd-generator/src/n4js/model.n4js +++ b/n4js-tools/n4jsd-generator/src/n4js/model.n4js @@ -27,6 +27,7 @@ export enum Accessibility { export class Annotation { name: string; + args: (string | TypeRef)[] = []; constructor(name: string =) { this.name = name; @@ -38,10 +39,15 @@ export interface AnnotatableElement { } export class Script { + tsFileName: string; + tsFilePath: string; mode: DTSMode = DTSMode.NONE; - preamble?: string; + prefix?: string; + suffix?: string; imports: Import[] = []; topLevelElements: ExportableElement[] = []; + /** If defined, all other properties will be ignored and this string will be emitted. */ + replacementCode?: string; issues: utils.Issue[] = []; } @@ -64,6 +70,7 @@ export class NamedImport extends Import { export abstract class NamedElement { name: string; + jsdoc?: string; } export abstract class ExportableElement extends NamedElement { @@ -97,10 +104,12 @@ export class Type extends ExportableElement implements AnnotatableElement { defSiteStructural?: boolean; primitiveBased?: PrimitiveBasedKind; typeParams: string[] = []; - extends?: TypeRef; + extends: TypeRef[] = []; + implements: TypeRef[] = []; members: Member[] = []; literals: EnumLiteral[] = []; aliasedType: TypeRef; + additionalCode: string[] = []; } export class EnumLiteral extends NamedElement { @@ -108,19 +117,23 @@ export class EnumLiteral extends NamedElement { } export enum MemberKind { - CTOR, CALLABLE_CTOR, FIELD, GETTER, SETTER, METHOD + CTOR, CALLABLE_CTOR, INDEX_SIGNATURE, + FIELD, GETTER, SETTER, METHOD } export class Member extends NamedElement implements AnnotatableElement { kind: MemberKind; accessibility: Accessibility; isStatic: boolean; + isOptional: boolean; /** Will be defined iff this member is a data field or field accessor. */ type?: TypeRef; signatures?: Signature[]; + replacementCode?: string; } export class Signature { + typeParams: string[] = []; parameters: Parameter[] = []; /** Will be undefined iff this signature belongs to a constructor. */ returnType?: TypeRef; @@ -132,12 +145,49 @@ export class Parameter extends NamedElement { isVariadic: boolean; } -export class TypeRef { +export enum TypeRefKind { + /** Referring to a type by name or alias. Corresponds to ParameterizedTypeRef in N4JS. */ + NAMED, + LITERAL, + FUNCTION, + OBJECT, + THIS, + /** In this case, TypeRef#targetTypeName is either "Iterable*" or "Array*" and TypeRef#targetTypeArgs define the element types. */ + TUPLE, + UNION, + INTERSECTION, + PARENTHESES, + // the following are not actually supported on N4JS side: + PREDICATE, + INDEXED_ACCESS_TYPE, + MAPPED_TYPE +} + +export enum TypeRefOperator { + KEYOF, + UNIQUE, + READONLY +} + +export class TypeRef implements AnnotatableElement { // note: annotations only supported for TypeRefKind === FUNCTION + kind: TypeRefKind; + dynamic: boolean; + targetTypeName: string; + targetTypeArgs: TypeRef[] = []; + signature: Signature; + members: Member[] = []; + composedTypeRefs: TypeRef[] = []; + parenthesizedTypeRef: TypeRef; + /** The type operators that preceded this type reference on the TypeScript side. */ + tsOperators: TypeRefOperator[] = []; /** The type reference as given in the TypeScript source code. */ tsSourceString: string; - constructor(tsSourceString: string =) { - this.tsSourceString = tsSourceString; + public isBuiltInUndefined(): boolean { + return this.kind === TypeRefKind.NAMED && this.targetTypeName === "undefined"; + } + public isComposed(): boolean { + return this.kind === TypeRefKind.UNION || this.kind === TypeRefKind.INTERSECTION; } } @@ -158,8 +208,13 @@ class Emitter { emitScript(script: Script) { const buff = this.buff; - if (script.preamble) { - buff.pushln(script.preamble); + if (script.replacementCode) { + buff.pushln(script.replacementCode); + return; // all other properties will be ignored in this case! + } + if (script.prefix) { + buff.pushln(script.prefix); + buff.pushln(); // separate prefix from main code by one empty line } if (script.imports.length > 0) { script.imports.forEach((elem, idx) => { @@ -178,6 +233,11 @@ class Emitter { } this.emitExportableElement(elem); }); + buff.pushln(); + if (script.suffix) { + buff.pushln(); // separate main code from suffix by one empty line + buff.pushln(script.suffix); + } } emitImport(elem: Import) { @@ -223,8 +283,11 @@ class Emitter { emitVariable(variable: Variable) { const buff = this.buff; + this.emitDocumentation(variable); this.emitExportKeywordIfNecessary(variable); - buff.push("public "); + if (variable.exported) { + buff.push("public "); + } buff.push(variable.keyword.name.toLowerCase()); buff.push(" "); buff.push(variable.name); @@ -234,17 +297,24 @@ class Emitter { emitFunction(fun: Function) { const buff = this.buff; + this.emitDocumentation(fun); this.emitExportKeywordIfNecessary(fun); buff.push("external "); buff.push("public "); buff.push("function "); + const [isOverloading, signature] = chooseSignature(fun.signatures); + this.emitSignaturePart1(signature); buff.push(fun.name); - this.emitSignature(fun.signatures[0]); + this.emitSignaturePart2(signature); buff.push(";"); + if (isOverloading) { + buff.push(" // overloading not supported"); + } } emitType(type: Type) { const buff = this.buff; + this.emitDocumentation(type); this.emitAnnotations(type, true); if (type.primitiveBased === PrimitiveBasedKind.STRING_BASED) { buff.pushln("@StringBased"); @@ -262,34 +332,50 @@ class Emitter { if (type.typeParams.length > 0) { buff.push("<", type.typeParams.join(","), ">"); } - if (type.extends) { + if (type.extends.length > 0) { buff.push(" extends "); - this.emitTypeRef(type.extends); + this.emitTypeRefs(type.extends, true); + } + if (type.implements.length > 0) { + buff.push(" implements "); + this.emitTypeRefs(type.implements, true); } if (type.kind === TypeKind.TYPE_ALIAS) { buff.push(" = "); this.emitTypeRef(type.aliasedType); buff.push(";"); } else { - buff.pushln(" {"); + buff.push(" {"); buff.indent(); + let didEmit = false; if (type.kind === TypeKind.INTERFACE || type.kind === TypeKind.CLASS) { - this.emitMembers(type, type.members); + didEmit = this.emitMembers(type.members, type); } else if (type.kind === TypeKind.ENUM) { - this.emitEnumLiterals(type.literals, type.primitiveBased === PrimitiveBasedKind.STRING_BASED); + didEmit = this.emitEnumLiterals(type.literals, type.primitiveBased === PrimitiveBasedKind.STRING_BASED); } else { throw "unknown kind of type: " + type.kind; } + for (const code of type.additionalCode) { + buff.pushln(); + didEmit = this.emitCode(code) || didEmit; + } buff.undent(); + if (didEmit) { + buff.pushln(); + } buff.push("}"); } } - emitEnumLiterals(literals: EnumLiteral[], isStringBased: boolean) { + emitEnumLiterals(literals: EnumLiteral[], isStringBased: boolean): boolean { const buff = this.buff; - const len = literals.length; - for (let i = 0; i < len; i++) { - const lit = literals[i]; + let isFirst = true; + for (const lit of literals) { + if (!isFirst) { + buff.push(","); + } + buff.pushln(); + this.emitDocumentation(lit); buff.push(lit.name); if (lit.value !== undefined) { buff.push(": "); @@ -299,24 +385,40 @@ class Emitter { buff.push("" + lit.value); } } - if (i + 1 < len) { - buff.pushln(","); - } else { - buff.pushln(); - } + isFirst = false; } + return !isFirst; } - emitMembers(parent: Type, members: Member[]) { + emitMembers(members: Member[], parent: Type =, onePerLine: boolean = true): boolean { const buff = this.buff; + let isFirst = true; for (const m of members) { - this.emitMember(parent, m); - buff.pushln(); + if (m.kind === MemberKind.INDEX_SIGNATURE) { + continue; // ignore index signatures, for now + } + if (onePerLine) { + buff.pushln(); + } else { + if (!isFirst) { + buff.push(" "); + } + } + this.emitMember(m, onePerLine, parent, onePerLine); + isFirst = false; } + return !isFirst; } - emitMember(parent: Type, member: Member) { + emitMember(member: Member, emitDocumentation: boolean, parent: Type =, onePerLine: boolean = true) { const buff = this.buff; + if (emitDocumentation) { + this.emitDocumentation(member); + } + if (member.replacementCode) { + this.emitCode(member.replacementCode); + return; + } this.emitAnnotations(member, true); if (member.accessibility !== undefined) { if (member.kind !== MemberKind.CALLABLE_CTOR) { // TODO how to define accessibility of a callable ctor? @@ -329,22 +431,30 @@ class Emitter { buff.push("static "); } } + const [isOverloaded, signature] = chooseSignature(member.signatures); switch(member.kind) { case MemberKind.CTOR: if (parent && parent.kind === TypeKind.INTERFACE) { buff.push("@CovariantConstructor"); - buff.pushln(); + if (onePerLine) { + buff.pushln(); + } else { + buff.push(" "); + } } buff.push("constructor"); - this.emitSignature(member.signatures[0], true); + this.emitSignaturePart2(signature, true); buff.push(";"); break; case MemberKind.CALLABLE_CTOR: - this.emitSignature(member.signatures[0]); + this.emitSignaturePart2(signature); buff.push(";"); break; case MemberKind.FIELD: this.emitPropertyName(member.name); + if (member.isOptional) { + buff.push("?"); + } this.emitTypeAnnotation(member.type); buff.push(";"); break; @@ -363,19 +473,33 @@ class Emitter { buff.push(");"); break; case MemberKind.METHOD: + this.emitSignaturePart1(signature); this.emitPropertyName(member.name); - this.emitSignature(member.signatures[0]); + this.emitSignaturePart2(signature); buff.push(";"); break; default: throw "unknown kind of member: " + member.kind; } - if (member.signatures !== undefined && member.signatures.length > 1) { - buff.push(" // further signatures were omitted"); + if (isOverloaded) { + if (onePerLine) { + buff.push(" // overloading not supported"); + } else { + buff.push(" /* <-- overloading not supported */"); + } } } - emitSignature(sig: Signature, ignoreReturnType: boolean = false) { + /** Emits the first part of a signature, that will appear before the function's/method's name. */ + emitSignaturePart1(sig: Signature) { + const buff = this.buff; + if (sig.typeParams.length > 0) { + buff.push("<", sig.typeParams.join(","), "> "); + } + } + + /** Emits the second part of a signature, that will appear after the function's/method's name. */ + emitSignaturePart2(sig: Signature, ignoreReturnType: boolean = false) { const buff = this.buff; buff.push("("); let needSep = false; @@ -388,7 +512,7 @@ class Emitter { } buff.push(")"); if (!ignoreReturnType) { - this.emitTypeAnnotation(sig.returnType); + this.emitTypeAnnotation(simplifyUnion(sig.returnType)); } } @@ -419,27 +543,198 @@ class Emitter { } } - emitTypeAnnotation(typeRef: TypeRef) { + emitTypeAnnotation(typeRef: TypeRef, separator: string = ": ") { const buff = this.buff; if (getGlobalOptions()?.copyTypeRefs) { if (typeRef) { - buff.push(": "); + buff.push(separator); this.emitTypeRef(typeRef); + } else { + buff.push(separator, "any+"); } } else { // note: in "any+ mode" we write out "any+" even in case // the type was undeclared on the TypeScript side, because // N4JS would infer the type to "any" instead of "any+": - buff.push(": ", "any+"); + buff.push(separator, "any+"); } } - emitTypeRef(typeRef: TypeRef) { + emitTypeRefs(typeRefs: TypeRef[], emitAlways: boolean = false): boolean { const buff = this.buff; - if (getGlobalOptions()?.copyTypeRefs && typeRef) { - buff.push(typeRef.tsSourceString); - } else { + let isFirst = true; + for (const typeRef of typeRefs) { + if (!isFirst) { + buff.push(", "); + } + this.emitTypeRef(typeRef, emitAlways); + isFirst = false; + } + return !isFirst; + } + + emitTypeRef(typeRef: TypeRef, emitAlways: boolean = false) { + const buff = this.buff; + if (!(emitAlways || getGlobalOptions()?.copyTypeRefs) || !typeRef) { buff.push("any+"); + return; + } + switch(typeRef.kind) { + case TypeRefKind.NAMED: + this.emitNamedTypeRef(typeRef); + break; + case TypeRefKind.LITERAL: + buff.push(typeRef.tsSourceString); + break; + case TypeRefKind.FUNCTION: + this.emitFunctionTypeRef(typeRef); + break; + case TypeRefKind.OBJECT: + this.emitObjectTypeRef(typeRef); + break; + case TypeRefKind.THIS: + buff.push("this"); + break; + case TypeRefKind.TUPLE: + this.emitTupleTypeRef(typeRef); + break; + case TypeRefKind.UNION: + case TypeRefKind.INTERSECTION: + this.emitComposedTypeRef(typeRef.kind, typeRef.composedTypeRefs); + break; + case TypeRefKind.PARENTHESES: + buff.push("("); + this.emitTypeRef(typeRef.parenthesizedTypeRef); + buff.push(")"); + break; + case TypeRefKind.PREDICATE: + buff.push("boolean"); + break; + case TypeRefKind.INDEXED_ACCESS_TYPE: + buff.push("any+"); + break; + case TypeRefKind.MAPPED_TYPE: + buff.push("Object+"); + break; + default: + throw "unsupported TypeRefKind: " + typeRef.kind + } + } + + emitNamedTypeRef(typeRef: TypeRef) { + if (typeRef.kind !== TypeRefKind.NAMED) { + throw "expected a TypeRef of kind TypeRefKind.NAMED, but got: " + typeRef.kind; + } + const buff = this.buff; + buff.push(typeRef.targetTypeName); + if (typeRef.targetTypeArgs.length > 0) { + buff.push("<"); + let isFirst = true; + for (const currTypeArg of typeRef.targetTypeArgs) { + if (!isFirst) { + buff.push(","); + } + this.emitTypeRef(currTypeArg); + isFirst = false; + } + buff.push(">"); + } + if (typeRef.dynamic) { + buff.push("+"); + } + } + + emitFunctionTypeRef(typeRef: TypeRef) { + if (typeRef.kind !== TypeRefKind.FUNCTION) { + throw "expected a TypeRef of kind TypeRefKind.FUNCTION, but got: " + typeRef.kind; + } + const buff = this.buff; + const useOldSyntax = typeRef.annotations.length > 0; + if (useOldSyntax) { + buff.push("{"); + this.emitAnnotations(typeRef, false); // will emit a space at the end + buff.push("function"); + } + this.emitSignaturePart2(typeRef.signature, true); + if (useOldSyntax) { + buff.push(": "); + } else { + buff.push("=>"); + } + const returnType = typeRef.signature.returnType; + if (returnType) { + const needParens = returnType.isComposed(); + if (needParens) { + buff.push("("); + } + this.emitTypeRef(returnType); + if (needParens) { + buff.push(")"); + } + } else { + buff.push("void"); + } + if (useOldSyntax) { + buff.push("}"); + } + } + + emitObjectTypeRef(typeRef: TypeRef) { + if (typeRef.kind !== TypeRefKind.OBJECT) { + throw "expected a TypeRef of kind TypeRefKind.OBJECT, but got: " + typeRef.kind; + } + const buff = this.buff; + buff.push("~Object"); + if (typeRef.members.length === 0) { + // no members -> nothing more to emit + } else if (typeRef.members.every(m => m.kind === MemberKind.INDEX_SIGNATURE)) { + // typical special case of an object type with only an index signature + // --> convert to "~Object+" instead of "~Object with {}" + buff.push("+"); + } else { + // standard case + buff.push(" with { "); + this.emitMembers(typeRef.members, undefined, false); + buff.push(" }"); + } + } + + emitTupleTypeRef(typeRef: TypeRef) { + if (typeRef.kind !== TypeRefKind.TUPLE) { + throw "expected a TypeRef of kind TypeRefKind.TUPLE, but got: " + typeRef.kind; + } + const buff = this.buff; + const isArrayTuple = typeRef.targetTypeName.startsWith("Array"); + if (isArrayTuple) { + buff.push("["); + } else { + buff.push("Iterable" + typeRef.targetTypeArgs.length + "<"); + } + let isFirst = true; + for (const elemTypeRef of typeRef.targetTypeArgs) { + if (!isFirst) { + buff.push(","); + } + isFirst = false; + this.emitTypeRef(elemTypeRef); + } + if (isArrayTuple) { + buff.push("]"); + } else { + buff.push(">"); + } + } + + emitComposedTypeRef(typeRefKind: TypeRefKind, memberTypeRefs: TypeRef[]) { + const buff = this.buff; + const spearator = typeRefKind === TypeRefKind.UNION ? " | " : " & "; + let isFirst = true; + for (const memberTypeRef of memberTypeRefs) { + if (!isFirst) { + buff.push(spearator); + } + isFirst = false; + this.emitTypeRef(memberTypeRef); } } @@ -456,6 +751,22 @@ class Emitter { buff.push("@"); } buff.push(name); + if (ann.args.length > 0) { + buff.push("("); + let isFirst = true; + for (const arg of ann.args) { + if (!isFirst) { + buff.push(", "); + } + isFirst = false; + if (arg instanceof TypeRef) { + this.emitTypeRef(arg); + } else { + buff.push(arg); + } + } + buff.push(")"); + } if (separateLine) { buff.pushln(); } else { @@ -465,6 +776,15 @@ class Emitter { emitPropertyName(name: string) { const buff = this.buff; + // special case: well-known symbol used as name + const symbolName = getSymbolNameFromPropertyName(name); + if (symbolName) { + buff.push("[Symbol."); + buff.push(symbolName); + buff.push("]"); + return; + } + // ordinary names const legal = utils.isLegalIdentifier(name); if (!legal) { buff.push('"'); @@ -476,4 +796,126 @@ class Emitter { buff.push('"'); } } + + emitDocumentation(elem: NamedElement) { + if (getGlobalOptions()?.noDoc) { + // do not emit JSDoc comments + return false; + } + const doc = elem.jsdoc; + if (!doc) { + return false; + } + if (this.emitCode(doc)) { + this.buff.pushln(); + return true; + } + return false; + } + + emitCode(code: string): boolean { + if (code === undefined || code === null) { + return false; + } + const buff = this.buff; + const codeLines = code.split("\n"); + let isFirst = true; + for (const line of codeLines) { + if (!isFirst) { + buff.pushln(); + } + buff.push(line); + isFirst = false; + } + return !isFirst; + } +} + + +export function simplifyUnion(typeRef: TypeRef): TypeRef { + if (typeRef?.kind !== TypeRefKind.UNION) { + return typeRef; + } + let idx = 0; + const typeRefs = [...typeRef.composedTypeRefs]; + while (idx < typeRefs.length) { + const curr = typeRefs[idx]; + if (curr.isBuiltInUndefined()) { + typeRefs.splice(idx,1); + } else { + ++idx; + } + } + const len = typeRefs.length; + if (len === 0) { + return createUndefined(); + } else if (len === 1) { + return typeRefs[0]; + } else { + const result = new TypeRef(); + result.kind = TypeRefKind.UNION; + for (const typeRef of typeRefs) { + result.composedTypeRefs.push(typeRef); + } + return result; + } +} + +export function chooseSignature(signatures: Signature[]): [boolean, Signature] { + if (!signatures || signatures.length === 0) { + return [false, undefined]; + } else if (signatures.length === 1) { + return [false, signatures[0]]; + } + // overloading case + // --> create a fall-back signature + const result = new Signature(); + const param = new Parameter(); + param.name = "args"; + param.isVariadic = true; + param.type = createAnyPlus(); + result.parameters.push(param); + result.returnType = createAnyPlus(); + return [true, result]; +} + +// TODO try to find a better approach +export function getSymbolNameFromPropertyName(propertyName: string): string { + if (propertyName && propertyName.startsWith("__@")) { + const idxEnd = propertyName.lastIndexOf("@"); + if (idxEnd > 2) { + const symbolName = propertyName.substring(3, idxEnd); + return symbolName; + } + } + return undefined; // not a symbol +} + +export function createNamedTypeRef(targetType: Type | string): TypeRef { + const result = new TypeRef(); + result.kind = TypeRefKind.NAMED; + if (targetType instanceof Type) { + result.targetTypeName = targetType.name; + for (const typeParam of targetType.typeParams) { + result.targetTypeArgs.push(createNamedTypeRef(typeParam)); + } + } else { + result.targetTypeName = targetType; + } + return result; +} + +export function createUndefined(): TypeRef { + const result = new TypeRef(); + result.kind = TypeRefKind.NAMED; + result.targetTypeName = "undefined"; + return result; +} + +export function createAnyPlus(): TypeRef { + const result = new TypeRef(); + result.kind = TypeRefKind.NAMED; + result.targetTypeName = "any"; + result.dynamic = true; + return result; } diff --git a/n4js-tools/n4jsd-generator/src/n4js/runtimeLibs.n4js b/n4js-tools/n4jsd-generator/src/n4js/runtimeLibs.n4js new file mode 100644 index 0000000000..8dc76700bd --- /dev/null +++ b/n4js-tools/n4jsd-generator/src/n4js/runtimeLibs.n4js @@ -0,0 +1,627 @@ +/** + * Copyright (c) 2021 NumberFour AG. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * NumberFour AG - Initial API and implementation + */ + +// This file contains various special handling for converting runtime library definitions. +// Additional tweaks may be found also in other places; see usage of Options#runtimeLibs in +// file 'cmdLineOpts.n4js' for finding those. + +import * as path_lib from "path"; +import * as model from "model"; +import * as utils from "utils"; +import { parseObject, PropertyTypeInfo } from "utilsObjectParsing"; + +import configUnparsed+ from "runtimeLibsConfig"; // TODO make configurable from command line! + + +const CONSTRUCTOR_TYPE_SUFFIX = "Constructor"; + + +class GenConfig { + preamble: string; + patchFiles = new Map(); + addFiles = new Map(); +} +class FileGenConfig { + public prefix: string; + public suffix: string; + public ignore = new Set(); + public polyfills = new Set(); + public changeToClass = new Set(); + public ctorInstanceTypes = [] as string[]; + public patchMembers = new Map(); + public appendCode = new Map(); +} +class PatchMemberConfig { + public replaceBy: string; + public addAnnotations: string[]; +} +const GEN_CONFIG_TYPE_INFO = new Map([ + [ "GenConfig#patchFiles", new PropertyTypeInfo({ type: FileGenConfig, collectionType: Map }) ] as [string,PropertyTypeInfo], + [ "GenConfig#addFiles", new PropertyTypeInfo({ type: String, collectionType: Map }) ] as [string,PropertyTypeInfo], + [ "FileGenConfig#ignore", new PropertyTypeInfo({ type: String, collectionType: Set }) ] as [string,PropertyTypeInfo], + [ "FileGenConfig#polyfills", new PropertyTypeInfo({ type: String, collectionType: Set }) ] as [string,PropertyTypeInfo], + [ "FileGenConfig#changeToClass", new PropertyTypeInfo({ type: String, collectionType: Set }) ] as [string,PropertyTypeInfo], + [ "FileGenConfig#ctorInstanceTypes", new PropertyTypeInfo({ type: String, collectionType: Array }) ] as [string,PropertyTypeInfo], + [ "FileGenConfig#patchMembers", new PropertyTypeInfo({ type: PatchMemberConfig, collectionType: Map }) ] as [string,PropertyTypeInfo], + [ "FileGenConfig#appendCode", new PropertyTypeInfo({ type: String, collectionType: Map }) ] as [string,PropertyTypeInfo], + [ "PatchMemberConfig#addAnnotations", new PropertyTypeInfo({ type: String, collectionType: Array }) ] as [string,PropertyTypeInfo] +]); + + +export public function isIgnored(filePath: string, elementName: string =, memberName: string =, signatureIndex: int =): boolean { + const fileName = path_lib.basename(filePath); + const ignoreConfig = getGenConfig().patchFiles.get(fileName)?.ignore; + if (!ignoreConfig) { + return false; + } + let elemQualifier = ""; + if (memberName) { + elemQualifier += "#" + memberName; + if (signatureIndex !== undefined && signatureIndex >= 0) { + elemQualifier += "#signature" + signatureIndex; + } + } + if (elementName) { + if (ignoreConfig.has(elementName + elemQualifier)) { + return true; + } + } + if (elemQualifier.length > 0) { + if (ignoreConfig.has("*" + elemQualifier)) { + return true; + } + } + return false; +} + +export public class RuntimeLibsError extends Error {} + +/** + * Invoked iff in "--runtime-libs" mode. Will modify the given scripts in various ways (in place) + * and may add additional scripts to the given array. + * + * @param scripts all scripts that were imported from '.d.ts' files. + */ +export public function postProcessRuntimeLibs(scripts: model.Script[]) { + // patch scripts loaded from .d.ts files + new RuntimeLibsPatcher(scripts).patch(); + // add additional scripts + let path: string; + for (const [fileName, fileContent] of getGenConfig().addFiles.entries()) { + if (path === undefined) { + path = path_lib.dirname(scripts.find(s => s.tsFilePath !== undefined)?.tsFilePath ?? "."); + if (path === ".") { + throw "unable to obtain default path for added files"; + } + } + const newScript = new model.Script(); + newScript.tsFileName = (fileName.endsWith(".n4jsd") ? fileName.substring(0, fileName.length - 6) : fileName) + ".d.ts"; + newScript.tsFilePath = path + "/" + newScript.tsFileName; + newScript.replacementCode = utils.trimMultiLineString(fileContent ?? ""); + scripts.push(newScript); + } +} + +class RuntimeLibsPatcher { + + @Final private scriptsOrdered: model.Script[]; + @Final private knownCtorTypes = new Set(); + @Final private knownInstanceTypes = new Set(); + @Final private identifiedPolyfills = new Set(); + + constructor(scripts: model.Script[]) { + this.scriptsOrdered = getScriptsOrderedAndAsserted(scripts); + } + + public patch() { + for (const script of this.scriptsOrdered) { + this.patchScript(script); + } + } + + private patchScript(script: model.Script) { + this.removeMetaProperties(script); + this.handleCtorInstanceTypePattern(script); + this.handleSimpleConfigurations(script); + this.handlePolyfills(script); + } + + private handleSimpleConfigurations(script: model.Script) { + const config = getGenConfig(); + const fileConfig = config.patchFiles.get(script.tsFileName); + // script prefix/suffix + const preamble = config.preamble; + const prefix = fileConfig?.prefix; + if (preamble || prefix) { + script.prefix = utils.trimMultiLineString(preamble ?? "") + utils.trimMultiLineString(prefix ?? ""); + } + const suffix = fileConfig?.suffix; + if (suffix) { + script.suffix = utils.trimMultiLineString(suffix); + } + // change to class + const changeToClass = fileConfig?.changeToClass; + if (changeToClass && changeToClass.size > 0) { + for (const elem of script.topLevelElements) { + if (elem instanceof model.Type + && elem.kind === model.TypeKind.INTERFACE + && changeToClass.has(elem.name)) { + changeInterfaceToClass(elem); + } + } + } + // member patching + const patchedMembers = fileConfig?.patchMembers; + if (patchedMembers && patchedMembers.size > 0) { + for (const elem of script.topLevelElements) { + if (!(elem instanceof model.Type)) { + continue; + } + const typeName = elem.name; + let idx = 0; + while (idx < elem.members.length) { + const member = elem.members[idx]; + let memberName: string; + if (member.kind === model.MemberKind.CTOR) { + memberName = "constructor"; + } else if (member.kind === model.MemberKind.CALLABLE_CTOR) { + memberName = "()"; + } else { + memberName = member.name; + const symbolName = model.getSymbolNameFromPropertyName(memberName); + if (symbolName) { + memberName = "[Symbol." + symbolName + "]"; + } + } + const key = typeName + "#" + memberName; + if (patchedMembers.has(key)) { + const patchConfig = patchedMembers.get(key); + if (patchConfig) { + const replacementStr = patchConfig.replaceBy; + if (replacementStr !== undefined && replacementStr !== null) { + member.replacementCode = utils.trimMultiLineString(replacementStr); + } else { + for (const annName of patchConfig.addAnnotations ?? []) { + member.annotations.push(new model.Annotation(annName)); + } + } + } else { + // null/undefined means: remove the member entirely + elem.members.splice(idx, 1); + --idx; + } + } + ++idx; + } + } + } + // additional code for types + const additionalCode = fileConfig?.appendCode; + if (additionalCode && additionalCode.size > 0) { + for (const elem of script.topLevelElements) { + if (!(elem instanceof model.Type)) { + continue; + } + const elemName = elem.name; + if (elemName && additionalCode.has(elemName)) { + const code = additionalCode.get(elemName); + if (code !== undefined && code !== null) { + elem.additionalCode.push(utils.trimMultiLineString(code)); + } + } + } + } + } + + private removeMetaProperties(script: model.Script) { + for (const elem of script.topLevelElements) { + if (elem instanceof model.Type) { + const ms = elem.members; + let i = 0; + while (i < ms.length) { + const m = ms[i]; + if ((m.name === "constructor" && m.kind !== model.MemberKind.CTOR) + || m.name === "prototype") { + ms.splice(i, 1); + } else { + ++i; + } + } + } + } + } + + private handleCtorInstanceTypePattern(script: model.Script) { + const elemsByName = new Map(); + for (const elem of script.topLevelElements) { + const name = elem.name; + let arr = elemsByName.get(name); + if (!arr) { + arr = []; + elemsByName.set(name, arr); + } + arr.push(elem); + } + + const topLevelElementModifications = new ElementModifications(); + + for (const elem of script.topLevelElements) { + if (elem instanceof model.Type && elem.kind === model.TypeKind.INTERFACE) { + if (this.knownCtorTypes.has(elem.name)) { + const ctorType = elem; + let instanceType = this.findInstanceTypeForCtorType(ctorType, elemsByName); + if (instanceType && !this.knownInstanceTypes.has(instanceType.name)) { + instanceType = undefined; + } + const adjustedType = this.adjustCtorInstanceTypes(ctorType, [], instanceType, elemsByName, topLevelElementModifications); + this.identifiedPolyfills.add(adjustedType); + } + } + } + for (const elem of script.topLevelElements) { + if (elem instanceof model.Type && elem.kind === model.TypeKind.INTERFACE) { + if (this.knownInstanceTypes.has(elem.name)) { + const instanceType = elem; + const adjustedType = this.adjustCtorInstanceTypes(undefined, [], instanceType, elemsByName, topLevelElementModifications); + this.identifiedPolyfills.add(adjustedType); + } + } + } + for (const elem of script.topLevelElements) { + if (elem instanceof model.Variable) { + this.adjustCtorInstanceTypesForVarDecl(elem, elemsByName, topLevelElementModifications); + } + } + + topLevelElementModifications.applyTo(script); + + // register additional known ctor/instance types, as requested by this file's FileGenConfig + const fileConfig = getGenConfig().patchFiles.get(script.tsFileName); + for (const typeName of fileConfig?.ctorInstanceTypes ?? []) { + if (typeName.endsWith(CONSTRUCTOR_TYPE_SUFFIX)) { + this.knownCtorTypes.add(typeName); + } else { + this.knownInstanceTypes.add(typeName); + } + } + } + + private adjustCtorInstanceTypesForVarDecl( + varDecl: model.Variable, + elemsByName: Map, + topLevelElementModifications: ElementModifications) { + + /* + Here we have to support two flavours of the ctor/instance pattern: + + interface MyType { // <--- this is optional! + // instance members + } + interface MyTypeConstructor { + // static members + } + var MyType: MyTypeConstructor; + + and + + interface MyType { + // instance members + } + var MyType: { + // static members + }; + */ + + const varDeclType = varDecl.type; + if (!varDeclType) { + return; + } + let ctorType: model.Type; + let moreStaticMembers: model.Member[]; + let instanceType: model.Type; + if (varDeclType.kind === model.TypeRefKind.NAMED) { + // could be flavour #1 + const typeRefTargetName = varDecl.type?.tsSourceString; + if (!typeRefTargetName) { + return; + } + const types = elemsByName.get(typeRefTargetName)?.filter(elem => elem instanceof model.Type) as model.Type[]; + if (!types || types.length === 0) { + return; + } + if (types.length > 1) { + return; + } + const type = types[0]; + if (type.kind !== model.TypeKind.INTERFACE) { + return; + } + ctorType = type; + moreStaticMembers = undefined; + // look for a corresponding instance type (optional) + instanceType = this.findInstanceTypeForCtorType(ctorType, elemsByName); + } else if (varDeclType.kind === model.TypeRefKind.OBJECT) { + // could be flavour #2 + const types = elemsByName.get(varDecl.name)?.filter(elem => elem instanceof model.Type) as model.Type[]; + if (!types || types.length === 0) { + return; + } + if (types.length > 1) { + return; + } + const type = types[0]; + if (type.kind !== model.TypeKind.INTERFACE) { + return; + } + ctorType = undefined; + moreStaticMembers = varDeclType.members; + instanceType = type; + } else { + return; + } + // we have identified the ctor/instance type pattern for variable declaration 'varDecl' and interface 'ctorType' + // --> so, adjust 'varDecl' and 'ctorType' accordingly + + // remember ctorType/instanceType for processing of following files + if (ctorType) { + this.knownCtorTypes.add(ctorType.name); + } + if (instanceType) { + this.knownInstanceTypes.add(instanceType.name); + } + + // actually adjust the ctorType/instanceType + const originalCtorTypeName = ctorType?.name; + this.adjustCtorInstanceTypes(ctorType, moreStaticMembers, instanceType, elemsByName, topLevelElementModifications); + // mark the variable declaration as "to be removed" + topLevelElementModifications.toBeRemoved.add(varDecl); + // add type alias for original ctorType (if any) + if (ctorType + && instanceType + && topLevelElementModifications.toBeRemoved.has(ctorType) + && instanceType.name !== originalCtorTypeName) { + const alias = new model.Type(); + alias.kind = model.TypeKind.TYPE_ALIAS; + alias.exported = true; + alias.name = originalCtorTypeName; + alias.aliasedType = model.createNamedTypeRef("constructor{" + instanceType.name + "}"); + topLevelElementModifications.toBeAdded.set(instanceType, alias); + } + } + + private adjustCtorInstanceTypes( + ctorType: model.Type, + moreStaticMembers: model.Member[], + instanceType: model.Type, + elemsByName: Map, + topLevelElementModifications: ElementModifications): model.Type { + + // change "constructor type" to a class, strip CONSTRUCTOR_TYPE_SUFFIX from its name, and make all members static + if (ctorType) { + changeInterfaceToClass(ctorType, false); + const ctorTypeName = ctorType.name; + if (ctorTypeName.endsWith(CONSTRUCTOR_TYPE_SUFFIX)) { + ctorType.name = ctorTypeName.substring(0, ctorTypeName.length - CONSTRUCTOR_TYPE_SUFFIX.length); + } + ctorType.members.forEach(m => m.isStatic = true); + } + // change "instance type" to a class + if (instanceType) { + changeInterfaceToClass(instanceType, false); + } + // merge the "constructor type" into the "instance type" (if both exist) + if (ctorType && instanceType) { + // move all members of the "constructor type" into the "instance type" + ctorType.members.forEach(m => instanceType.members.push(m)); + ctorType.members.length = 0; + // mark the "constructor type" as "to be removed" + topLevelElementModifications.toBeRemoved.add(ctorType); + } + if (moreStaticMembers && moreStaticMembers.length > 0 && instanceType) { + moreStaticMembers.forEach(m => { + if (m.accessibility === undefined) { + m.accessibility = model.Accessibility.PUBLIC; + } + m.isStatic = true; // enfore static + instanceType.members.push(m); + }); + } + // return the "surviving" type + return instanceType ? instanceType : ctorType; + } + + private findInstanceTypeForCtorType(ctorType: model.Type, elemsByName: Map): model.Type { + let instanceType: model.Type = undefined; + const ctorTypeName = ctorType.name; + if (ctorTypeName.endsWith(CONSTRUCTOR_TYPE_SUFFIX)) { + const instanceTypeName = ctorTypeName.substring(0, ctorTypeName.length - CONSTRUCTOR_TYPE_SUFFIX.length); + const instanceTypes = elemsByName.get(instanceTypeName)?.filter(elem => elem instanceof model.Type) as model.Type[]; + if (instanceTypes) { + for (const instanceTypeCandidate of instanceTypes) { + if (instanceTypeCandidate.kind === model.TypeKind.INTERFACE) { + instanceType = instanceTypeCandidate; + break; + } + } + } + } + return instanceType; + } + + private handlePolyfills(script: model.Script) { + const fileConfig = getGenConfig().patchFiles.get(script.tsFileName); + const configuredPolyfills = fileConfig?.polyfills ?? new Set(); + if (this.identifiedPolyfills.size === 0 && configuredPolyfills.size === 0) { + return; + } + for (const elem of script.topLevelElements) { + if (!(elem instanceof model.Type)) { + continue; + } + const elemName = elem.name; + if (elemName && (this.identifiedPolyfills.has(elem) || configuredPolyfills.has(elemName))) { + changeToPolyfill(elem); + } + } + } +} + +function changeInterfaceToClass(ifc: model.Type, defSiteStructural: boolean | undefined = undefined) { + if (ifc.kind !== model.TypeKind.INTERFACE) { + return; + } + ifc.kind = model.TypeKind.CLASS; + if (ifc.extends.length > 1) { + // WARNING: since we cannot tell whether a target type is an interface or a class, + // we have to use the assumption that the first extended interface is the super class + // and all remaining extended interfaces are implemented interfaces: + const extendedIfcs = ifc.extends.splice(1, ifc.extends.length - 1); + let idx = -1; + for (const extendedIfc of extendedIfcs) { + ifc.implements.splice(++idx, 0, extendedIfc); + } + } + // due to different default accessibilities, we have to make accessibility PUBLIC explicit: + ifc.members.forEach(m => { + if (!m.accessibility) { + m.accessibility = model.Accessibility.PUBLIC; + } + }); + // in TypeScript, a non-generic interface may have a generic construct signature, + // which we turn into a generic class: + for (const m of ifc.members) { + if (m.kind === model.MemberKind.CTOR) { + const sig = m.signatures?.[0]; + if (sig) { + for (const paramName of sig.typeParams) { + if (ifc.typeParams.indexOf(paramName) < 0) { + ifc.typeParams.push(paramName); + } + } + } + } + } + // set 'defSiteStructural', if requested + if (defSiteStructural !== undefined) { + ifc.defSiteStructural = defSiteStructural; + } +} + +function changeToPolyfill(type: model.Type) { + const typeName = type.name; + if (!typeName) { + return; + } + type.annotations.push(new model.Annotation("@Polyfill")); + type.extends.length = 0; + const superTypeRef = model.createNamedTypeRef(type); + type.extends.push(superTypeRef); +} + +/** + * Returns the given scripts in the order their configuration was defined in GenConfig. + * In addition, this method performs two assertions: + * 1) that the GenConfig file contains file configurations for all input files. + * 2) that an input file exists for all file configurations given in the GenConfig file. + */ +function getScriptsOrderedAndAsserted(scripts: model.Script[]): model.Script[] { + const fileConfigs = getGenConfig().patchFiles; + + const scriptsWithoutGenConfig = [] as model.Script[]; + for (const script of scripts) { + if (!fileConfigs.has(script.tsFileName)) { + scriptsWithoutGenConfig.push(script); + } + } + if (scriptsWithoutGenConfig.length > 0) { + throw new RuntimeLibsError("no generator configuration in config property 'files' found for:\n " + + scriptsWithoutGenConfig.map(s => s.tsFileName + " (at " + s.tsFilePath + ")").join("\n ")); + } + + const result: model.Script[] = []; + const scriptsByName = new Map(scripts.map(s => [s.tsFileName, s])); + const namesWithoutScript = [] as string[]; + for (const name of fileConfigs.keys()) { + const script = scriptsByName.get(name); + if (!script) { + namesWithoutScript.push(name); + } else { + result.push(script); + } + } + if (namesWithoutScript.length > 0) { + throw new RuntimeLibsError("no .d.ts input file found for generator configuration with name(s): " + + namesWithoutScript.join(", ")); + } + + for (const scriptWithoutGenConfig of scriptsWithoutGenConfig) { + result.push(scriptWithoutGenConfig); + } + + return result; +} + +let _cachedGenConfig: GenConfig; +/** see setTemporaryGenConfig() */ +let _temporaryGenConfig: GenConfig; +function getGenConfig(): GenConfig { + if (_temporaryGenConfig) { + return _temporaryGenConfig; + } + if (!_cachedGenConfig) { + try { + _cachedGenConfig = parseObject(configUnparsed, GenConfig, GEN_CONFIG_TYPE_INFO); + } catch (err) { + throw new RuntimeLibsError("error while parsing default configuration file for runtime-libs conversion:\n " + err); + } + } + return _cachedGenConfig; +} +/** + * Sets a custom configuration for the runtime library generation that will replace + * the default configuration of file "runtimeLibsConfig.js". Pass in 'undefined' to + * switch back to the default configuration. + */ +export public function setTemporaryGenConfig(config: Object) { + if (config) { + try { + _temporaryGenConfig = parseObject(config, GenConfig, GEN_CONFIG_TYPE_INFO); + } catch (err) { + throw new RuntimeLibsError("error while parsing temporary configuration for runtime-libs conversion:\n " + err); + } + } else { + _temporaryGenConfig = undefined; + } +} + +class ElementModifications { + @Final public toBeRemoved = new Set(); + /** Map from existing element to the elment that should be added after the existing element. */ + @Final public toBeAdded = new Map(); + + public applyTo(script: model.Script) { + const topLevelElems = script.topLevelElements; + let i = 0; + while (i < topLevelElems.length) { + const currElem = topLevelElems[i]; + if (this.toBeRemoved.has(currElem)) { + topLevelElems.splice(i, 1); + } else { + ++i; + } + const newElem = this.toBeAdded.get(currElem); + if (newElem) { + topLevelElems.splice(i, 0, newElem); + ++i; + } + } + } +} diff --git a/n4js-tools/n4jsd-generator/src/n4js/runtimeLibsConfig.js b/n4js-tools/n4jsd-generator/src/n4js/runtimeLibsConfig.js new file mode 100644 index 0000000000..db6bb5d988 --- /dev/null +++ b/n4js-tools/n4jsd-generator/src/n4js/runtimeLibsConfig.js @@ -0,0 +1,1267 @@ +export default { + preamble: `@@Global @@ProvidedByRuntime`, + patchFiles: { + "es5.d.ts": { + prefix: ``, + suffix: ` + export external public type ReadonlyArray = Array; + + /** + * See [ECMA6] Section 19.4. + * + * A symbol is a unique and immutable data type and may be used as an identifier for object properties. The symbol + * object is an implicit object wrapper for the symbol primitive data type. + * + * TODO in ES6 this is defined to be a property of the global object and a constructor function + */ + export external public class Symbol extends Object { + + /** + * Creates a new, primitive symbol. + * + * @param description A description of the symbol which can be used for debugging but not to access the symbol itself. + */ + (description: string = undefined): symbol + + /** + * This "well-known" symbol may be used to define the default iterator of an object. + * + * @see ES6, 19.4.2.4 + */ + public const iterator: symbol + + // well-known symbols moved here from file 'es2015.symbol.wellknown.d.ts' + public const hasInstance: symbol; + public const isConcatSpreadable: symbol; + public const match: symbol; + public const replace: symbol; + public const search: symbol; + public const species: symbol; + public const split: symbol; + public const toPrimitive: symbol; + public const toStringTag: symbol; + public const unscopables: symbol; + // well-known symbols moved here from file 'es2018.asynciterable.d.ts' + public const asyncIterator: symbol; + // well-known symbols moved here from file 'es2020.symbol.wellknown.d.ts' + public const matchAll: symbol; + + /** + * Returns the shared symbol with the given key from the Javascript engine's shared symbol registry. + * Creates a new symbol if not found. + * + * @see ES6, 19.4.2.1 + */ + public static for(key: string): symbol + + /** + * Returns the key for the given shared symbol if found in the Javascript engine's shared symbol registry. + * Otherwise 'undefined' is returned. + * + * @see ES6, 19.4.2.5 + */ + public static keyFor(sym: symbol): string + } + + /** + * An iterator over a collection, defining a standard way to produce a sequence of values (either finite + * or infinite). + *

+ * Note that in ECMAScript 6 this is not a built-in type, but a protocol. This protocol can be implemented + * by any object respecting some conventions. + */ + export external public interface ~Iterator { + /** + * A zero arguments function that returns an object with two properties: + *

    + *
  • done (boolean)
    + * Has the value true if the iterator is past the end of the iterated sequence. In this case value + * optionally specifies the return value of the iterator. The return values are explained here. + * Has the value false if the iterator was able to produce the next value in the sequence. This is + * equivalent of not specifying the done property altogether. + *
  • value
    + * any JavaScript value returned by the iterator. Can be omitted when done is true. + *
+ */ + public abstract next(): IteratorEntry + } + + /** + * Same as interface Iterator, but for asynchronous iteration. + */ + export external public interface ~AsyncIterator { + /** + * A zero arguments function that returns a promise of an object with two properties: + *
    + *
  • done (boolean)
    + * Has the value true if the iterator is past the end of the iterated sequence. In this case value + * optionally specifies the return value of the iterator. The return values are explained here. + * Has the value false if the iterator was able to produce the next value in the sequence. This is + * equivalent of not specifying the done property altogether. + *
  • value
    + * any JavaScript value returned by the iterator. Can be omitted when done is true. + *
+ */ + public abstract next(): Promise, ?> + } + + /** + * The value returned by an Iterator's method next(). + */ + export external public interface ~IteratorEntry { + /** + * Has the value true if the iterator is past the end of the iterated sequence. In this case value + * optionally specifies the return value of the iterator. The return values are explained here. + * Has the value false if the iterator was able to produce the next value in the sequence. This is + * equivalent of not specifying the done property altogether. + */ + public done: boolean; + // public get done(): boolean + /** + * Any JavaScript value returned by the iterator. Can be omitted when done is true. + */ + // TODO dirty hack: to use covariant T as type of field 'value', we make the field final; but usually fields + // in interfaces cannot be final - only works because no validation in n4ts! + @Final public value?: T; + // this would be the alternative, but then we would lose the optionality of 'value': + // public get value(): T + } + + /** + * An object that can be iterated over. Whenever an object needs to be iterated (such as at the beginning + * of a for..of loop), its [Symbol.iterator] method is called with no arguments, and the + * returned iterator is used to obtain the values to be iterated. + *

+ * Note that in ECMAScript 6 this is not a built-in type, but a protocol. This protocol can be implemented + * by any object respecting some conventions. + *

+ * For asynchronous iteration use interface AsyncIterable instead. + */ + export external public interface ~Iterable { + /** + * Returns an object conforming to the iteration protocol. + */ + public abstract [Symbol.iterator](): Iterator + } + + /** + * Same as interface Iterable, but for asynchronous iteration. + */ + export external public interface ~AsyncIterable { + /** + * Returns an object conforming to the asynchronous iteration protocol. + */ + public abstract [Symbol.asyncIterator](): AsyncIterator + } + + + /** + * An iterator over a collection, defining a standard way to produce a sequence of values (either finite + * or infinite). + *

+ * Note that in ECMAScript 6 this is not a built-in type, but a protocol. This protocol can be implemented + * by any object respecting some conventions. + */ + export external public interface ~Generator extends Iterable, Iterator { + + /** + * A one (optional) argument function. The (optional) argument value is passed to the + * current yield expression in the generator function. The return is an IteratorEntry + * with two properties: + *

    + *
  • done (boolean)
    + * Has the value true if the iterator is past the end of the iterated sequence. In this case value + * optionally specifies the return value of the iterator. The return values are explained here. + * Has the value false if the iterator was able to produce the next value in the sequence. This is + * equivalent of not specifying the done property altogether. + *
  • value
    + * any JavaScript value returned by the iterator. Can be omitted when done is true. + *
+ */ + @Override public abstract next(value: TNext = undefined): IteratorEntry + + /** + * A zero arguments function that returns the this object, conforming to the iterator + * interface. + *

+ * Note that the iterator can only be iterated once. + */ + @Override public abstract [Symbol.iterator](): Generator + + /** + * A one argument function. The argument exception is thrown at the current yield + * expression in the generator function. The return is an IteratorEntry with two + * properties: + *

    + *
  • done (boolean)
    + * Has the value true if the iterator is past the end of the iterated sequence. In this case value + * optionally specifies the return value of the iterator. The return values are explained here. + * Has the value false if the iterator was able to produce the next value in the sequence. This is + * equivalent of not specifying the done property altogether. + *
  • value
    + * any JavaScript value returned by the iterator. Can be omitted when done is true. + *
+ */ + public abstract throw(exception: any): IteratorEntry; + + /** + * A one (optional) argument function. The (optional) argument value is passed to the + * current yield expression in the generator function. The return is an IteratorEntry with + * two properties: + *
    + *
  • done (boolean)
    + * Has the value true if the iterator is past the end of the iterated sequence. In this case value + * optionally specifies the return value of the iterator. The return values are explained here. + * Has the value false if the iterator was able to produce the next value in the sequence. This is + * equivalent of not specifying the done property altogether. + *
  • value
    + * any JavaScript value returned by the iterator. Can be omitted when done is true. + *
+ */ + public abstract return(value: TNext = undefined): IteratorEntry; + } + + /** + * An asynchronous generator object. See interface Generator for details. + */ + export external public interface ~AsyncGenerator extends AsyncIterable, AsyncIterator { + + /** + * A one (optional) argument function. The (optional) argument value is passed to the + * current yield expression in the generator function. Return a promise of an IteratorEntry + * with two properties: + *
    + *
  • done (boolean)
    + * Has the value true if the iterator is past the end of the iterated sequence. In this case value + * optionally specifies the return value of the iterator. The return values are explained here. + * Has the value false if the iterator was able to produce the next value in the sequence. This is + * equivalent of not specifying the done property altogether. + *
  • value
    + * any JavaScript value returned by the iterator. Can be omitted when done is true. + *
+ */ + @Override public abstract next(value: TNext = undefined): Promise, ?> + + /** + * A zero arguments function that returns the this object, conforming to the asynchronous + * iterator interface. + *

+ * Note that the iterator can only be iterated once. + */ + @Override public abstract [Symbol.asyncIterator](): AsyncGenerator + + /** + * A one argument function. The argument exception is thrown at the current yield + * expression in the generator function. Returns a promise of an IteratorEntry with two + * properties: + *

    + *
  • done (boolean)
    + * Has the value true if the iterator is past the end of the iterated sequence. In this case value + * optionally specifies the return value of the iterator. The return values are explained here. + * Has the value false if the iterator was able to produce the next value in the sequence. This is + * equivalent of not specifying the done property altogether. + *
  • value
    + * any JavaScript value returned by the iterator. Can be omitted when done is true. + *
+ */ + public abstract throw(exception: any): Promise, any>; + + /** + * A one (optional) argument function. The (optional) argument value is passed to the + * current yield expression in the generator function. Returns a promise of an IteratorEntry with + * two properties: + *
    + *
  • done (boolean)
    + * Has the value true if the iterator is past the end of the iterated sequence. In this case value + * optionally specifies the return value of the iterator. The return values are explained here. + * Has the value false if the iterator was able to produce the next value in the sequence. This is + * equivalent of not specifying the done property altogether. + *
  • value
    + * any JavaScript value returned by the iterator. Can be omitted when done is true. + *
+ */ + public abstract return(value: TNext = undefined): Promise, ?>; + } + + /** + * A promise represents a proxy for a value that is usually not yet known + * when the promise is created. + *

+ * A promise can exist in either of two states: "pending" and "settled". + * If the result value of a promise is not yet determined, the promise is + * "pending". Once the value has been determined, the promise becomes + * "settled". + *

+ * A promise can either be fulfilled or rejected. A fulfilled promise + * indicates a successful completion of whatever asynchronous process it + * encapsulates. A rejected promise indicates erroneous or abnormal completion + * of the process. + */ + export external public class Promise extends Object { + + public constructor( + executor: {function( + resolveFn:{function(arg: S = undefined):void}, + rejectFn: {function(arg: F = undefined):void} + ): void} + ) + + public then( + onFulfilled: {function(arg:S = undefined): union{Snew, Promise}?}, + onRejected: {function(arg:F = undefined): union{Fnew, Promise}?} = undefined + ): Promise + + public catch( + onRejected: {function(arg:F = undefined): union{Fnew, Promise}?} + ): Promise + + public static reject(f: F): Promise + public static resolve( + s: union{ + Promise, + ~Object with { then(...args: any): Promise; }, // i.e. thenable + S + } + ): Promise + + public static all(iterable: Iterable, T}>): Promise, any> + public static race(iterable: Iterable, T}>): Promise + } + + export external public type PromiseConstructor = constructor{Promise}; + + + export external public interface ~ArrayBufferView { + /** + * The ArrayBuffer instance referenced by the array. + */ + get buffer(): ArrayBufferLike; + + /** + * The length in bytes of the array. + */ + get byteLength(): number; + + /** + * The offset in bytes of the array. + */ + get byteOffset(): number; + } + `, + ignore: [ + // temporarily ignored, because we need our own definition: + "Symbol", "Promise", + // unfortunately we have to replace ArrayBufferView by our own definition (see suffix above), because TypeScript is + // using writable fields in ArrayBufferView but the types expected to be subtypes (e.g. Uint8Array) only provide + // readonly fields / getters, meaning they would not actually be subtypes when applying strict subtype checking: + "ArrayBufferView", + // stuff defined in primitive_js.n4ts and global.n4jsd: + "NaN", "Infinity", "eval", "parseInt", "parseFloat", "isNaN", "isFinite", "decodeURI", "decodeURIComponent", + "encodeURI", "encodeURIComponent", "escape", "unescape", + // read-only types: + "ReadonlyArray", "TemplateStringsArray", + // type constructors: + "Partial", "Required", "Readonly", "Pick", "Record", "Exclude", "Extract", "Omit", "NonNullable", + "Parameters", "ConstructorParameters", "ReturnType", "InstanceType", "Uppercase", "Lowercase", + "Capitalize", "Uncapitalize", "Awaited", + // decorators: + "ClassDecorator", "PropertyDecorator", "MethodDecorator", "ParameterDecorator", + // odd stuff: + "ThisParameterType", "OmitThisParameter", "CallableFunction", "NewableFunction", "PromiseConstructorLike" + ], + polyfills: [], + changeToClass: [ + "RegExpMatchArray", + "RegExpExecArray" + ], + ctorInstanceTypes: [ + "Symbol", "SymbolConstructor", + "Promise", "PromiseConstructor" + ], + patchMembers: { + // required due to odd return types on TypeScript side + "Function#bind": { replaceBy: "public bind(thisArg: any, ...args: any): {function(... args: any): any}" }, // return type in .d.ts is 'any' instead of a function + "Object#valueOf": { replaceBy: "public valueOf(): any" }, // return type in .d.ts is 'Object' causing errors when overridden to return a primitve type + "Object#getPrototypeOf": { replaceBy: "public static getPrototypeOf(o: any): Object;" }, // return type in .d.ts is 'any' instead of 'Object' + // required due to stricter type checking in N4JS (type of searchElement must be 'any' instead of 'T' on N4JS side) + "Array#indexOf": { replaceBy: "public indexOf(searchElement: any, fromIndex: number = ): number;" }, + "Array#lastIndexOf": { replaceBy: "public lastIndexOf(searchElement: any, fromIndex: number = ): number;" }, + // required due to different signature + "Array#map": { replaceBy: "public map(callback: {function(value: T, index: number, traversedObject: Array) : U}, thisObject: ThisT = undefined): Array;" }, + // required due to overloading: + "Object#()": { replaceBy: "(...args: any): Object;" }, + "Object#create": { replaceBy: "public static create(proto: Object, props: Object = undefined): Object;" }, + "Object#freeze": { replaceBy: "public static freeze(obj: T): T;" }, + "String#localeCompare": { replaceBy: "public localeCompare(that: string, locales: string = undefined, options: any+ = undefined): number;" }, + "String#replace": { replaceBy: "public replace(searchValue: union{RegExp, string}, replaceValue: union{string, Function}): string;" }, + "Array#constructor": { replaceBy: "public constructor(first: union{number, T} = undefined, ...items: T); // TODO: signature is type unsafe, allows to create arrays with elements of wrong type, new Array(5, 'x', 'y'), but cannot write constructor(items : union {number, T... items} = undefined)" }, + "Array#concat": { replaceBy: "public concat(...items: union {T, Array}): Array;" }, + "Array#splice": { replaceBy: "public splice(start: number = undefined, deleteCount: number = undefined, ...items: T): Array;" }, + "Array#every": { replaceBy: "public every(callback: {function(value: T, index: number, traversedObject: Array)}, thisObject: ThisT = undefined): boolean;" }, + "Array#filter": { replaceBy: "public filter(callback: {function(value: T, index: number, traversedObject: Array) : boolean}, thisObject: ThisT = undefined): Array;" }, + "Array#reduce": { replaceBy: "public reduce(callback: {function(previousValue: MemoT, currentValue: T, index: number, traversedObject: Array) : MemoT}, initialValue: MemoT = undefined): MemoT;" }, + "Array#reduceRight": { replaceBy: "public reduceRight(callback: {function(previousValue: MemoT, currentValue: T, index: number, traversedObject: Array) : MemoT}, initialValue: MemoT = undefined): MemoT;" }, + "Date#constructor": { replaceBy: "public constructor(numberOrStringOrYear: union{string, number} = undefined, month: number = undefined, date: number = undefined, hours: number = undefined, minutes: number = undefined, seconds: number = undefined, ms: number = undefined);" }, + "RegExp#constructor": { replaceBy: "public constructor(pattern: string = undefined, flags: string = undefined);" }, + "JSON#stringify": { replaceBy: "public static stringify(value: any, replacer: union{Array, {function(key: string, value: any) : any} } = undefined, space: union{number , string} = undefined): string;" }, + // required because optional methods used in .d.ts and not supported in N4JS + "PropertyDescriptor#get": { replaceBy: "get?: ()=>any;" }, + "PropertyDescriptor#set": { replaceBy: "set?: (value: any)=>void;" }, + // missing @Override annotations for methods #valueOf(), #toString(), #toLocaleString() + "Function#toString": { addAnnotations: [ "@Override" ] }, + "String#valueOf": { addAnnotations: [ "@Override" ] }, + "String#toString": { addAnnotations: [ "@Override" ] }, + "Boolean#valueOf": { addAnnotations: [ "@Override" ] }, + "Number#valueOf": { addAnnotations: [ "@Override" ] }, + "Number#toString": { addAnnotations: [ "@Override" ] }, + "Number#toLocaleString": { addAnnotations: [ "@Override" ] }, + "Date#valueOf": { addAnnotations: [ "@Override" ] }, + "Date#toString": { addAnnotations: [ "@Override" ] }, + "Date#toLocaleString": { addAnnotations: [ "@Override" ] }, + "Array#toString": { addAnnotations: [ "@Override" ] }, + "Array#toLocaleString": { addAnnotations: [ "@Override" ] }, + "Int8Array#valueOf": { addAnnotations: [ "@Override" ] }, + "Int8Array#toString": { addAnnotations: [ "@Override" ] }, + "Int8Array#toLocaleString": { addAnnotations: [ "@Override" ] }, + "Uint8Array#valueOf": { addAnnotations: [ "@Override" ] }, + "Uint8Array#toString": { addAnnotations: [ "@Override" ] }, + "Uint8Array#toLocaleString": { addAnnotations: [ "@Override" ] }, + "Uint8ClampedArray#valueOf": { addAnnotations: [ "@Override" ] }, + "Uint8ClampedArray#toString": { addAnnotations: [ "@Override" ] }, + "Uint8ClampedArray#toLocaleString": { addAnnotations: [ "@Override" ] }, + "Int16Array#valueOf": { addAnnotations: [ "@Override" ] }, + "Int16Array#toString": { addAnnotations: [ "@Override" ] }, + "Int16Array#toLocaleString": { addAnnotations: [ "@Override" ] }, + "Uint16Array#valueOf": { addAnnotations: [ "@Override" ] }, + "Uint16Array#toString": { addAnnotations: [ "@Override" ] }, + "Uint16Array#toLocaleString": { addAnnotations: [ "@Override" ] }, + "Int32Array#valueOf": { addAnnotations: [ "@Override" ] }, + "Int32Array#toString": { addAnnotations: [ "@Override" ] }, + "Int32Array#toLocaleString": { addAnnotations: [ "@Override" ] }, + "Uint32Array#valueOf": { addAnnotations: [ "@Override" ] }, + "Uint32Array#toString": { addAnnotations: [ "@Override" ] }, + "Uint32Array#toLocaleString": { addAnnotations: [ "@Override" ] }, + "Float32Array#valueOf": { addAnnotations: [ "@Override" ] }, + "Float32Array#toString": { addAnnotations: [ "@Override" ] }, + "Float32Array#toLocaleString": { addAnnotations: [ "@Override" ] }, + "Float64Array#valueOf": { addAnnotations: [ "@Override" ] }, + "Float64Array#toString": { addAnnotations: [ "@Override" ] } + }, + appendCode: { + "Object": ` + /** + * The built-in ES5 property "__proto__", here modeled as a read-only property (i.e. no setter provided), because + * changing an object's prototype after creation is strongly discouraged in todays Javascript engines. + */ + public get __proto__(): Object; + /** + * The initial value of Object.prototype is the standard built-in Object prototype object (15.2.4). + * + * Remark: Modeled as getter to emulate const and to allow for overriding. + * @see ES5, 15.2.3.1 + */ + public static get prototype(): Object; + `, + "String": ` + /** + * Returns a new Iterator object that iterates over the code points of a String value, returning each code point as + * a String value. + */ + public [Symbol.iterator](): Iterator + `, + "Array": ` + public [Symbol.iterator](): Iterator; + /** + * The initial value of Array.prototype is the Array prototype object (15.4.4). + * + * @see ES5 15.4.3.1 + */ + @Override public static get prototype(): Array + `, + "Function": ` + /** + * The Function prototype object is itself a Function object (its [[Class]] is "Function") that, when invoked, accepts any arguments and returns undefined. + */ + @Override public static get prototype(): Function; + /** + * The value of the prototype property is used to initialize the [[Prototype]] internal property of a newly created object before the Function object is invoked as a constructor for that newly created object. This property has the attribute { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }. + * NOTE Function objects created using Function.prototype.bind do not have a prototype property. + * + * @see ES5 15.3.5.2 + */ + public get prototype(): Object; + ` + } + }, + "es2015.core.d.ts": { + ignore: [ + // read-only types: + "ReadonlyArray" + ], + patchMembers: { + "Object#keys": { addAnnotations: [ "@Override" ] }, + "Date#constructor": undefined, + "RegExp#constructor": undefined, + // required due to overloading: + "Array#find": { replaceBy: "public find(predicate: (T, int=, T[]=) => boolean, thisArg: Object=): T;" }, + "Array#from": { replaceBy: "public static from(source: Iterable|ArrayLike|Iterator|string, mapFn: (I, int) => any=, thisArg: Object=): I[];" } + } + }, + "es2015.collection.d.ts": { + ignore: [ + // read-only types: + "ReadonlySet", "ReadonlyMap" + ], + patchMembers: { + // TypeScript provides constructors accepting Iterables via overloading in file "es2015.iterable.d.ts" (which we do not support): + "Map#constructor": { replaceBy: "public constructor(entries: Iterable> = );" }, + "WeakMap#constructor": { replaceBy: "public constructor(entries: Iterable> = );" }, + "Set#constructor": { replaceBy: "public constructor(values: Iterable = );" }, + "WeakSet#constructor": { replaceBy: "public constructor(values: Iterable = );" }, + }, + suffix: ` + export external public type ReadonlySet = Set; + export external public type ReadonlyMap = Map; + ` + }, + "es2015.symbol.d.ts": { + ignore: [ + "Symbol", "SymbolConstructor" // Symbol was moved to es5.n4jsd (see above) + ] + }, + "es2015.symbol.wellknown.d.ts": { + ignore: [ + "Symbol", "SymbolConstructor", // Symbol was moved to es5.n4jsd (see above) + "Promise", "PromiseConstructor" // this would work fine, except for different number of type parameters + ], + patchMembers: { + // the signatures of the following members use computed property names inside ~Object with {} + "String#replace": undefined, + "String#match": undefined, + "String#search": undefined, + "String#split": undefined + } + }, + "es2015.iterable.d.ts": { + ignore: [ + "IterableIterator", // replaced by modified declaration in suffix below (see below for details) + "Iterator", // Iterator was moved to es5.n4jsd (see above) + "Iterable", // Iterable was moved to es5.n4jsd (see above) + "Promise", "PromiseConstructor", // Promise was moved to es5.n4jsd (see above) + // read-only types: + "ReadonlyArray", "ReadonlySet", "ReadonlyMap" + ], + patchMembers: { + "Symbol#iterator": undefined, // was moved to es5.n4jsd (see above) + "Array#[Symbol.iterator]": undefined, // was moved to es5.n4jsd (see above) + "Array#from": undefined, + "String#[Symbol.iterator]": undefined, // was moved to es5.n4jsd (see above) + "Map#constructor": undefined, // the signature added here via overloading was moved to "es2015.collection.d.ts" (see above) + "WeakMap#constructor": undefined, // the signature added here via overloading was moved to "es2015.collection.d.ts" (see above) + "Set#constructor": undefined, // the signature added here via overloading was moved to "es2015.collection.d.ts" (see above) + "WeakSet#constructor": undefined, // the signature added here via overloading was moved to "es2015.collection.d.ts" (see above) + "Uint8ClampedArray#constructor": undefined, + "Uint8ClampedArray#from": undefined, + "Int8Array#constructor": undefined, + "Int8Array#from": undefined, + "Uint8Array#constructor": undefined, + "Uint8Array#from": undefined, + "Uint8Clampe#constructor": undefined, + "Uint8Clampe#from": undefined, + "Int16Array#constructor": undefined, + "Int16Array#from": undefined, + "Uint16Array#constructor": undefined, + "Uint16Array#from": undefined, + "Int32Array#constructor": undefined, + "Int32Array#from": undefined, + "Uint32Array#constructor": undefined, + "Uint32Array#from": undefined, + "Float32Array#constructor": undefined, + "Float32Array#from": undefined, + "Float64Array#constructor": undefined, + "Float64Array#from": undefined + }, + // we need to provide our own modified variant of IterableIterator, because + // 1) we must add "out" modifier to type parameter, + // 2) extend interface "Iterable" explicitly to avoid error message "All N4Objects must explicitly extend/implement definition site structural type Iterable.", + // 3) due to 2), @Override annotation must be added. + suffix: ` + export external public interface ~IterableIterator extends Iterator, Iterable { + @Override + [Symbol.iterator](): IterableIterator; + } + ` + }, + "es2015.generator.d.ts": { + ignore: [ + "Generator" // Generator was moved to es5.n4jsd (see above) + ], + patchMembers: { + "GeneratorFunction#()": undefined, // callable ctor not supported in interface + "GeneratorFunctionConstructor#()": undefined // callable ctor not supported in interface + } + }, + "es2015.promise.d.ts": { + ignore: [ + "Promise", "PromiseConstructor" // Promise was moved to es5.n4jsd (see above) + ] + }, + "es2015.proxy.d.ts": { + ignore: [ + // need to replace ProxyHandler entirely, because of + // 1) heavy use of optional methods (not supported in N4JS), and + // 2) use of unfortunate type 'any' instead of 'Object' for parameters "thisArg" and "receiver" + "ProxyHandler" + ], + suffix: ` + export external public interface ~ProxyHandler { + apply?: (target: T, thisArg: Object, argArray: Array) => any; + construct?: (target: T, argArray: Array, newTarget: Function) => Object; + defineProperty?: (target: T, p: string | symbol, attributes: PropertyDescriptor) => boolean; + deleteProperty?: (target: T, p: string | symbol) => boolean; + get?: (target: T, p: string | symbol, receiver: Object) => any; + getOwnPropertyDescriptor?: (target: T, p: string | symbol) => PropertyDescriptor; + getPrototypeOf?: (target: T) => Object; + has?: (target: T, p: string | symbol) => boolean; + isExtensible?: (target: T) => boolean; + ownKeys?: (target: T) => ArrayLike; + preventExtensions?: (target: T) => boolean; + set?: (target: T, p: string | symbol, value: any, receiver: Object) => boolean; + setPrototypeOf?: (target: T, v: Object) => boolean; + } + ` + }, + "es2015.reflect.d.ts": {}, + "es2016.array.include.d.ts": { + ignore: [ + // read-only types: + "ReadonlyArray" + ] + }, + "es2017.string.d.ts": {}, + "es2017.object.d.ts": { + patchMembers: { + // required due to overloading: + "Object#values": { replaceBy: "public static values(obj: Object): any[];" }, + "Object#entries": { replaceBy: "public static entries(obj: Object): Iterable2[];" } + } + }, + "es2017.sharedmemory.d.ts": {}, + "es2017.typedarrays.d.ts": { + patchMembers: { + // cannot add overload signatures via polyfill: + "Int8Array#constructor": undefined, + "Uint8Array#constructor": undefined, + "Uint8ClampedArray#constructor": undefined, + "Int16Array#constructor": undefined, + "Uint16Array#constructor": undefined, + "Int32Array#constructor": undefined, + "Uint32Array#constructor": undefined, + "Float32Array#constructor": undefined, + "Float64Array#constructor": undefined + } + }, + "es2017.intl.d.ts": {}, + "es2018.asynciterable.d.ts": { + ignore: [ + "AsyncIterator", // AsyncIterator was moved to es5.n4jsd (see above) + "AsyncIterable" // AsyncIterable was moved to es5.n4jsd (see above) + ], + patchMembers: { + "Symbol#asyncIterator": undefined // was moved to es5.n4jsd (see above) + } + }, + "es2018.asyncgenerator.d.ts": { + ignore: [ + "AsyncGenerator" // AsyncGenerator was moved to es5.n4jsd (see above) + ], + patchMembers: { + "AsyncGeneratorFunction#()": undefined, // callable ctor not supported in interface + "AsyncGeneratorFunctionConstructor#()": undefined // callable ctor not supported in interface + } + }, + "es2018.promise.d.ts": { + ignore: [ + "Promise", "PromiseConstructor" // this would work fine, except for different number of type parameters + ], + suffix: ` + @Polyfill + export external public class Promise extends Promise { + public finally(onfinally: (()=>void) = ): Promise; + } + ` + }, + "es2018.regexp.d.ts": { + polyfills: [ + "RegExpMatchArray", + "RegExpExecArray" + ], + changeToClass: [ + "RegExpMatchArray", + "RegExpExecArray" + ], + }, + "es2018.intl.d.ts": {}, + "es2019.string.d.ts": {}, + "es2019.object.d.ts": {}, + "es2019.array.d.ts": { + ignore: [ + // read-only types: + "ReadonlyArray" + ] + }, + "es2019.symbol.d.ts": {}, + "es2020.bigint.d.ts": { + patchMembers: { + "BigInt#toString": { addAnnotations: [ "@Override" ] }, + "BigInt#toLocaleString": { addAnnotations: [ "@Override" ] }, + "BigInt#valueOf": { addAnnotations: [ "@Override" ] }, + "BigInt64Array#toString": { addAnnotations: [ "@Override" ] }, + "BigInt64Array#toLocaleString": { addAnnotations: [ "@Override" ] }, + "BigInt64Array#valueOf": { addAnnotations: [ "@Override" ] }, + "BigUint64Array#toString": { addAnnotations: [ "@Override" ] }, + "BigUint64Array#toLocaleString": { addAnnotations: [ "@Override" ] }, + "BigUint64Array#valueOf": { addAnnotations: [ "@Override" ] } + } + }, + "es2020.string.d.ts": {}, + "es2020.promise.d.ts": { + ignore: [ + "Promise", "PromiseConstructor" // this would work fine, except for different number of type parameters + ], + suffix: ` + @Polyfill + export external public class Promise extends Promise { + public static allSettled(...args: any+): any+; // overloading not supported + } + ` + }, + "es2020.sharedmemory.d.ts": { + patchMembers: { + // these are cases of adding overloads to existing methods: + "Atomics#add": undefined, + "Atomics#and": undefined, + "Atomics#compareExchange": undefined, + "Atomics#exchange": undefined, + "Atomics#load": undefined, + "Atomics#or": undefined, + "Atomics#store": undefined, + "Atomics#sub": undefined, + "Atomics#wait": undefined, + "Atomics#notify": undefined, + "Atomics#xor": undefined + } + }, + "es2020.symbol.wellknown.d.ts": { + patchMembers: { + "Symbol#matchAll": undefined // was moved to es5.n4jsd (see above) + } + }, + "es2020.intl.d.ts": {}, + /* + "dom.generated.d.ts": { + ignore: [ + "*#prototype", + "*#addEventListener#signature0", + "*#removeEventListener#signature0" + ], + patchMembers: { + // @Override annotations: + // misc. methods ==================================================================================== + "AudioBufferSourceNode#start": { addAnnotations: [ "@Override" ] }, + "DOMMatrix#a": { addAnnotations: [ "@Override" ] }, + "DOMMatrix#b": { addAnnotations: [ "@Override" ] }, + "DOMMatrix#c": { addAnnotations: [ "@Override" ] }, + "DOMMatrix#d": { addAnnotations: [ "@Override" ] }, + "DOMMatrix#e": { addAnnotations: [ "@Override" ] }, + "DOMMatrix#f": { addAnnotations: [ "@Override" ] }, + "DOMMatrix#m11": { addAnnotations: [ "@Override" ] }, + "DOMMatrix#m12": { addAnnotations: [ "@Override" ] }, + "DOMMatrix#m13": { addAnnotations: [ "@Override" ] }, + "DOMMatrix#m14": { addAnnotations: [ "@Override" ] }, + "DOMMatrix#m21": { addAnnotations: [ "@Override" ] }, + "DOMMatrix#m22": { addAnnotations: [ "@Override" ] }, + "DOMMatrix#m23": { addAnnotations: [ "@Override" ] }, + "DOMMatrix#m24": { addAnnotations: [ "@Override" ] }, + "DOMMatrix#m31": { addAnnotations: [ "@Override" ] }, + "DOMMatrix#m32": { addAnnotations: [ "@Override" ] }, + "DOMMatrix#m33": { addAnnotations: [ "@Override" ] }, + "DOMMatrix#m34": { addAnnotations: [ "@Override" ] }, + "DOMMatrix#m41": { addAnnotations: [ "@Override" ] }, + "DOMMatrix#m42": { addAnnotations: [ "@Override" ] }, + "DOMMatrix#m43": { addAnnotations: [ "@Override" ] }, + "DOMMatrix#m44": { addAnnotations: [ "@Override" ] }, + "DOMMatrix#fromFloat32Array": { addAnnotations: [ "@Override" ] }, + "DOMMatrix#fromFloat64Array": { addAnnotations: [ "@Override" ] }, + "DOMMatrix#fromMatrix": { addAnnotations: [ "@Override" ] }, + "DOMPoint#w": { addAnnotations: [ "@Override" ] }, + "DOMPoint#x": { addAnnotations: [ "@Override" ] }, + "DOMPoint#y": { addAnnotations: [ "@Override" ] }, + "DOMPoint#z": { addAnnotations: [ "@Override" ] }, + "DOMPoint#fromPoint": { addAnnotations: [ "@Override" ] }, + "DOMRect#height": { addAnnotations: [ "@Override" ] }, + "DOMRect#width": { addAnnotations: [ "@Override" ] }, + "DOMRect#x": { addAnnotations: [ "@Override" ] }, + "DOMRect#y": { addAnnotations: [ "@Override" ] }, + "DOMRect#fromRect": { addAnnotations: [ "@Override" ] }, + "Document#getElementById": { addAnnotations: [ "@Override" ] }, + "DocumentFragment#getElementById": { addAnnotations: [ "@Override" ] }, + "HTMLOptionsCollection#length": { addAnnotations: [ "@Override" ] }, + "HTMLSelectElement#remove": { addAnnotations: [ "@Override" ] }, + "PerformanceNavigationTiming#toJSON": { addAnnotations: [ "@Override" ] }, + "PerformanceResourceTiming#toJSON": { addAnnotations: [ "@Override" ] }, + "Text#assignedSlot": { addAnnotations: [ "@Override" ] }, + "TextDecoderStream#readable": { addAnnotations: [ "@Override" ] }, + "TextDecoderStream#writable": { addAnnotations: [ "@Override" ] }, + "TextEncoderStream#readable": { addAnnotations: [ "@Override" ] }, + "TextEncoderStream#writable": { addAnnotations: [ "@Override" ] }, + "WindowEventMap#gamepadconnected": { addAnnotations: [ "@Override" ] }, + "WindowEventMap#gamepaddisconnected": { addAnnotations: [ "@Override" ] }, + // method ownerDocument ============================================================================= + "Attr#ownerDocument": { addAnnotations: [ "@Override" ] }, + "CharacterData#ownerDocument": { addAnnotations: [ "@Override" ] }, + "Document#ownerDocument": { addAnnotations: [ "@Override" ] }, + "DocumentFragment#ownerDocument": { addAnnotations: [ "@Override" ] }, + "DocumentType#ownerDocument": { addAnnotations: [ "@Override" ] }, + "Element#ownerDocument": { addAnnotations: [ "@Override" ] }, + "ProcessingInstruction#ownerDocument": { addAnnotations: [ "@Override" ] }, + // method toString ================================================================================== + "DOMMatrixReadOnly#toString": { addAnnotations: [ "@Override" ] }, + "DOMTokenList#toString": { addAnnotations: [ "@Override" ] }, + "Location#toString": { addAnnotations: [ "@Override" ] }, + "MediaList#toString": { addAnnotations: [ "@Override" ] }, + "Range#toString": { addAnnotations: [ "@Override" ] }, + "Selection#toString": { addAnnotations: [ "@Override" ] }, + "URL#toString": { addAnnotations: [ "@Override" ] }, + "URLSearchParams#toString": { addAnnotations: [ "@Override" ] }, + // method addEventListener ========================================================================== + "AbortSignal#addEventListener": { addAnnotations: [ "@Override" ] }, + "Animation#addEventListener": { addAnnotations: [ "@Override" ] }, + "AudioBufferSourceNode#addEventListener": { addAnnotations: [ "@Override" ] }, + "AudioContext#addEventListener": { addAnnotations: [ "@Override" ] }, + "AudioScheduledSourceNode#addEventListener": { addAnnotations: [ "@Override" ] }, + "AudioWorkletNode#addEventListener": { addAnnotations: [ "@Override" ] }, + "BaseAudioContext#addEventListener": { addAnnotations: [ "@Override" ] }, + "BroadcastChannel#addEventListener": { addAnnotations: [ "@Override" ] }, + "CSSAnimation#addEventListener": { addAnnotations: [ "@Override" ] }, + "CSSTransition#addEventListener": { addAnnotations: [ "@Override" ] }, + "ConstantSourceNode#addEventListener": { addAnnotations: [ "@Override" ] }, + "Document#addEventListener": { addAnnotations: [ "@Override" ] }, + "Element#addEventListener": { addAnnotations: [ "@Override" ] }, + "EventSource#addEventListener": { addAnnotations: [ "@Override" ] }, + "FileReader#addEventListener": { addAnnotations: [ "@Override" ] }, + "FontFaceSet#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLAnchorElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLAreaElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLAudioElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLBRElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLBaseElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLBodyElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLButtonElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLCanvasElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLDListElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLDataElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLDataListElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLDetailsElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLDirectoryElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLDivElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLDocument#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLEmbedElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLFieldSetElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLFontElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLFormElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLFrameElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLFrameSetElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLHRElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLHeadElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLHeadingElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLHtmlElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLIFrameElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLImageElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLInputElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLLIElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLLabelElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLLegendElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLLinkElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLMapElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLMarqueeElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLMediaElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLMenuElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLMetaElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLMeterElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLModElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLOListElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLObjectElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLOptGroupElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLOptionElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLOutputElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLParagraphElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLParamElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLPictureElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLPreElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLProgressElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLQuoteElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLScriptElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLSelectElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLSlotElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLSourceElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLSpanElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLStyleElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLTableCaptionElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLTableCellElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLTableColElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLTableElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLTableRowElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLTableSectionElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLTemplateElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLTextAreaElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLTimeElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLTitleElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLTrackElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLUListElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLUnknownElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLVideoElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "IDBDatabase#addEventListener": { addAnnotations: [ "@Override" ] }, + "IDBOpenDBRequest#addEventListener": { addAnnotations: [ "@Override" ] }, + "IDBRequest#addEventListener": { addAnnotations: [ "@Override" ] }, + "IDBTransaction#addEventListener": { addAnnotations: [ "@Override" ] }, + "MathMLElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "MediaDevices#addEventListener": { addAnnotations: [ "@Override" ] }, + "MediaKeySession#addEventListener": { addAnnotations: [ "@Override" ] }, + "MediaQueryList#addEventListener": { addAnnotations: [ "@Override" ] }, + "MediaRecorder#addEventListener": { addAnnotations: [ "@Override" ] }, + "MediaSource#addEventListener": { addAnnotations: [ "@Override" ] }, + "MediaStream#addEventListener": { addAnnotations: [ "@Override" ] }, + "MediaStreamTrack#addEventListener": { addAnnotations: [ "@Override" ] }, + "MessagePort#addEventListener": { addAnnotations: [ "@Override" ] }, + "Notification#addEventListener": { addAnnotations: [ "@Override" ] }, + "OfflineAudioContext#addEventListener": { addAnnotations: [ "@Override" ] }, + "OscillatorNode#addEventListener": { addAnnotations: [ "@Override" ] }, + "PaymentRequest#addEventListener": { addAnnotations: [ "@Override" ] }, + "Performance#addEventListener": { addAnnotations: [ "@Override" ] }, + "PermissionStatus#addEventListener": { addAnnotations: [ "@Override" ] }, + "PictureInPictureWindow#addEventListener": { addAnnotations: [ "@Override" ] }, + "RTCDTMFSender#addEventListener": { addAnnotations: [ "@Override" ] }, + "RTCDataChannel#addEventListener": { addAnnotations: [ "@Override" ] }, + "RTCDtlsTransport#addEventListener": { addAnnotations: [ "@Override" ] }, + "RTCPeerConnection#addEventListener": { addAnnotations: [ "@Override" ] }, + "RemotePlayback#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGAElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGAnimateElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGAnimateMotionElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGAnimateTransformElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGAnimationElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGCircleElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGClipPathElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGComponentTransferFunctionElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGDefsElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGDescElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGEllipseElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEBlendElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEColorMatrixElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEComponentTransferElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFECompositeElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEConvolveMatrixElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEDiffuseLightingElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEDisplacementMapElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEDistantLightElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEDropShadowElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEFloodElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEFuncAElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEFuncBElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEFuncGElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEFuncRElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEGaussianBlurElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEImageElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEMergeElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEMergeNodeElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEMorphologyElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEOffsetElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEPointLightElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFESpecularLightingElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFESpotLightElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFETileElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFETurbulenceElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFilterElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGForeignObjectElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGGElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGGeometryElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGGradientElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGGraphicsElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGImageElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGLineElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGLinearGradientElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGMPathElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGMarkerElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGMaskElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGMetadataElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGPathElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGPatternElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGPolygonElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGPolylineElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGRadialGradientElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGRectElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGSVGElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGScriptElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGSetElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGStopElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGStyleElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGSwitchElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGSymbolElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGTSpanElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGTextContentElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGTextElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGTextPathElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGTextPositioningElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGTitleElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGUseElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "SVGViewElement#addEventListener": { addAnnotations: [ "@Override" ] }, + "ScreenOrientation#addEventListener": { addAnnotations: [ "@Override" ] }, + "ScriptProcessorNode#addEventListener": { addAnnotations: [ "@Override" ] }, + "ServiceWorker#addEventListener": { addAnnotations: [ "@Override" ] }, + "ServiceWorkerContainer#addEventListener": { addAnnotations: [ "@Override" ] }, + "ServiceWorkerRegistration#addEventListener": { addAnnotations: [ "@Override" ] }, + "SharedWorker#addEventListener": { addAnnotations: [ "@Override" ] }, + "SourceBuffer#addEventListener": { addAnnotations: [ "@Override" ] }, + "SourceBufferList#addEventListener": { addAnnotations: [ "@Override" ] }, + "SpeechSynthesis#addEventListener": { addAnnotations: [ "@Override" ] }, + "SpeechSynthesisUtterance#addEventListener": { addAnnotations: [ "@Override" ] }, + "TextTrack#addEventListener": { addAnnotations: [ "@Override" ] }, + "TextTrackCue#addEventListener": { addAnnotations: [ "@Override" ] }, + "TextTrackList#addEventListener": { addAnnotations: [ "@Override" ] }, + "VTTCue#addEventListener": { addAnnotations: [ "@Override" ] }, + "VisualViewport#addEventListener": { addAnnotations: [ "@Override" ] }, + "WebSocket#addEventListener": { addAnnotations: [ "@Override" ] }, + "Window#addEventListener": { addAnnotations: [ "@Override" ] }, + "Worker#addEventListener": { addAnnotations: [ "@Override" ] }, + "XMLDocument#addEventListener": { addAnnotations: [ "@Override" ] }, + "XMLHttpRequest#addEventListener": { addAnnotations: [ "@Override" ] }, + "XMLHttpRequestEventTarget#addEventListener": { addAnnotations: [ "@Override" ] }, + "XMLHttpRequestUpload#addEventListener": { addAnnotations: [ "@Override" ] }, + // method removeEventListener ======================================================================= + "AbortSignal#removeEventListener": { addAnnotations: [ "@Override" ] }, + "Animation#removeEventListener": { addAnnotations: [ "@Override" ] }, + "AudioBufferSourceNode#removeEventListener": { addAnnotations: [ "@Override" ] }, + "AudioContext#removeEventListener": { addAnnotations: [ "@Override" ] }, + "AudioScheduledSourceNode#removeEventListener": { addAnnotations: [ "@Override" ] }, + "AudioWorkletNode#removeEventListener": { addAnnotations: [ "@Override" ] }, + "BaseAudioContext#removeEventListener": { addAnnotations: [ "@Override" ] }, + "BroadcastChannel#removeEventListener": { addAnnotations: [ "@Override" ] }, + "CSSAnimation#removeEventListener": { addAnnotations: [ "@Override" ] }, + "CSSTransition#removeEventListener": { addAnnotations: [ "@Override" ] }, + "ConstantSourceNode#removeEventListener": { addAnnotations: [ "@Override" ] }, + "Document#removeEventListener": { addAnnotations: [ "@Override" ] }, + "Element#removeEventListener": { addAnnotations: [ "@Override" ] }, + "EventSource#removeEventListener": { addAnnotations: [ "@Override" ] }, + "FileReader#removeEventListener": { addAnnotations: [ "@Override" ] }, + "FontFaceSet#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLAnchorElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLAreaElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLAudioElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLBRElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLBaseElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLBodyElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLButtonElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLCanvasElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLDListElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLDataElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLDataListElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLDetailsElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLDirectoryElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLDivElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLDocument#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLEmbedElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLFieldSetElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLFontElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLFormElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLFrameElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLFrameSetElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLHRElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLHeadElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLHeadingElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLHtmlElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLIFrameElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLImageElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLInputElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLLIElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLLabelElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLLegendElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLLinkElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLMapElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLMarqueeElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLMediaElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLMenuElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLMetaElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLMeterElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLModElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLOListElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLObjectElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLOptGroupElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLOptionElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLOutputElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLParagraphElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLParamElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLPictureElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLPreElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLProgressElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLQuoteElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLScriptElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLSelectElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLSlotElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLSourceElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLSpanElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLStyleElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLTableCaptionElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLTableCellElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLTableColElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLTableElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLTableRowElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLTableSectionElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLTemplateElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLTextAreaElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLTimeElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLTitleElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLTrackElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLUListElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLUnknownElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "HTMLVideoElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "IDBDatabase#removeEventListener": { addAnnotations: [ "@Override" ] }, + "IDBOpenDBRequest#removeEventListener": { addAnnotations: [ "@Override" ] }, + "IDBRequest#removeEventListener": { addAnnotations: [ "@Override" ] }, + "IDBTransaction#removeEventListener": { addAnnotations: [ "@Override" ] }, + "MathMLElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "MediaDevices#removeEventListener": { addAnnotations: [ "@Override" ] }, + "MediaKeySession#removeEventListener": { addAnnotations: [ "@Override" ] }, + "MediaQueryList#removeEventListener": { addAnnotations: [ "@Override" ] }, + "MediaRecorder#removeEventListener": { addAnnotations: [ "@Override" ] }, + "MediaSource#removeEventListener": { addAnnotations: [ "@Override" ] }, + "MediaStream#removeEventListener": { addAnnotations: [ "@Override" ] }, + "MediaStreamTrack#removeEventListener": { addAnnotations: [ "@Override" ] }, + "MessagePort#removeEventListener": { addAnnotations: [ "@Override" ] }, + "Notification#removeEventListener": { addAnnotations: [ "@Override" ] }, + "OfflineAudioContext#removeEventListener": { addAnnotations: [ "@Override" ] }, + "OscillatorNode#removeEventListener": { addAnnotations: [ "@Override" ] }, + "PaymentRequest#removeEventListener": { addAnnotations: [ "@Override" ] }, + "Performance#removeEventListener": { addAnnotations: [ "@Override" ] }, + "PermissionStatus#removeEventListener": { addAnnotations: [ "@Override" ] }, + "PictureInPictureWindow#removeEventListener": { addAnnotations: [ "@Override" ] }, + "RTCDTMFSender#removeEventListener": { addAnnotations: [ "@Override" ] }, + "RTCDataChannel#removeEventListener": { addAnnotations: [ "@Override" ] }, + "RTCDtlsTransport#removeEventListener": { addAnnotations: [ "@Override" ] }, + "RTCPeerConnection#removeEventListener": { addAnnotations: [ "@Override" ] }, + "RemotePlayback#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGAElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGAnimateElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGAnimateMotionElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGAnimateTransformElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGAnimationElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGCircleElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGClipPathElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGComponentTransferFunctionElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGDefsElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGDescElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGEllipseElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEBlendElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEColorMatrixElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEComponentTransferElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFECompositeElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEConvolveMatrixElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEDiffuseLightingElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEDisplacementMapElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEDistantLightElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEDropShadowElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEFloodElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEFuncAElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEFuncBElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEFuncGElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEFuncRElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEGaussianBlurElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEImageElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEMergeElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEMergeNodeElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEMorphologyElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEOffsetElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFEPointLightElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFESpecularLightingElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFESpotLightElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFETileElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFETurbulenceElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGFilterElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGForeignObjectElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGGElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGGeometryElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGGradientElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGGraphicsElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGImageElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGLineElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGLinearGradientElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGMPathElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGMarkerElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGMaskElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGMetadataElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGPathElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGPatternElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGPolygonElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGPolylineElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGRadialGradientElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGRectElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGSVGElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGScriptElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGSetElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGStopElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGStyleElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGSwitchElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGSymbolElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGTSpanElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGTextContentElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGTextElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGTextPathElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGTextPositioningElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGTitleElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGUseElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SVGViewElement#removeEventListener": { addAnnotations: [ "@Override" ] }, + "ScreenOrientation#removeEventListener": { addAnnotations: [ "@Override" ] }, + "ScriptProcessorNode#removeEventListener": { addAnnotations: [ "@Override" ] }, + "ServiceWorker#removeEventListener": { addAnnotations: [ "@Override" ] }, + "ServiceWorkerContainer#removeEventListener": { addAnnotations: [ "@Override" ] }, + "ServiceWorkerRegistration#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SharedWorker#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SourceBuffer#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SourceBufferList#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SpeechSynthesis#removeEventListener": { addAnnotations: [ "@Override" ] }, + "SpeechSynthesisUtterance#removeEventListener": { addAnnotations: [ "@Override" ] }, + "TextTrack#removeEventListener": { addAnnotations: [ "@Override" ] }, + "TextTrackCue#removeEventListener": { addAnnotations: [ "@Override" ] }, + "TextTrackList#removeEventListener": { addAnnotations: [ "@Override" ] }, + "VTTCue#removeEventListener": { addAnnotations: [ "@Override" ] }, + "VisualViewport#removeEventListener": { addAnnotations: [ "@Override" ] }, + "WebSocket#removeEventListener": { addAnnotations: [ "@Override" ] }, + "Window#removeEventListener": { addAnnotations: [ "@Override" ] }, + "Worker#removeEventListener": { addAnnotations: [ "@Override" ] }, + "XMLDocument#removeEventListener": { addAnnotations: [ "@Override" ] }, + "XMLHttpRequest#removeEventListener": { addAnnotations: [ "@Override" ] }, + "XMLHttpRequestEventTarget#removeEventListener": { addAnnotations: [ "@Override" ] }, + "XMLHttpRequestUpload#removeEventListener": { addAnnotations: [ "@Override" ] }, + } + }, + "dom.iterable.d.ts": {}, + "dom.iterable.generated.d.ts": {} + */ + }, + addFiles: { + "es2020.globalThis.n4jsd": ` + @@Global @@ProvidedByRuntime + export external public const globalThis: Object+; + + // Before, this was defined in "globalThis.n4jsd" of "n4js-runtime-esnext" as follows: + // @@Global @@ProvidedByRuntime + // export external public const globalThis: Object+; + // and in "globalThis.n4jsd" of "n4js-runtime-html5" it was commented out as follows: + // //export external public const globalThis: Window+; + ` + } +}; diff --git a/n4js-tools/n4jsd-generator/src/n4js/utils.n4js b/n4js-tools/n4jsd-generator/src/n4js/utils.n4js index 2ea47aa057..7deaa69ae3 100644 --- a/n4js-tools/n4jsd-generator/src/n4js/utils.n4js +++ b/n4js-tools/n4jsd-generator/src/n4js/utils.n4js @@ -28,10 +28,13 @@ export class Issue { } } export function error(msg: string): Issue { - return new Issue(msg, IssueKind.ERROR); + return issue(IssueKind.ERROR, msg); } export function warning(msg: string): Issue { - return new Issue(msg, IssueKind.WARNING); + return issue(IssueKind.WARNING, msg); +} +export function issue(kind: IssueKind, msg: string): Issue { + return new Issue(msg, kind); } diff --git a/n4js-tools/n4jsd-generator/src/n4js/utilsObjectParsing.n4js b/n4js-tools/n4jsd-generator/src/n4js/utilsObjectParsing.n4js new file mode 100644 index 0000000000..dd5210e8a2 --- /dev/null +++ b/n4js-tools/n4jsd-generator/src/n4js/utilsObjectParsing.n4js @@ -0,0 +1,144 @@ +/** + * Copyright (c) 2021 NumberFour AG. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * NumberFour AG - Initial API and implementation + */ + +import * as utils from "utils"; + +/** Defines the type of a configuration property. */ +export public class PropertyTypeInfo { + /** Supported types are: Boolean, Number, String, and subclasses of N4Object. */ + public type: constructor{? extends Object}; + /** Defined iff the property has more than one value. Supported collection types are: Array, Set, and Map. */ + public collectionType?: constructor{? extends Object}; + + constructor(@Spec spec: ~i~this) {} +} + + +export public function parseObject( + obj: Object, + type: constructor{T}, + typeInfo: Map): T { + + const result = new ObjectParser(type, typeInfo).parse(obj); + return result; +} + + +class ObjectParser { + + @Final private entryType: constructor{T}; + @Final private typeInfo: Map; + + constructor(entryType: constructor{T}, typeInfo: Map) { + this.entryType = entryType; + this.typeInfo = typeInfo; + } + + public parse(obj: Object): T { + return this.parseObject(obj, this.entryType, ""); + } + + private parseObject(obj: Object, type: constructor{? extends T2}, propertyPath: string): T2 { + const n4Type = type.n4type; + const result = new (type as constructor{Object})() as T2; + for (const field of n4Type.dataFields(true, true)) { + const fieldValue = obj[field.name]; + if (fieldValue === undefined || fieldValue === null) { + continue; + } + const fieldPropPath = propertyPath + "." + (utils.isLegalIdentifier(field.name) ? field.name : '"' + field.name + '"'); + const fieldId = n4Type.name + "#" + field.name; + const fieldTypeInfo = this.typeInfo.get(fieldId) ?? { + type: String, + collectionType: undefined + } as PropertyTypeInfo; + const fieldCollectionType = fieldTypeInfo.collectionType; + let fieldValueParsed; + if (fieldCollectionType === undefined || fieldCollectionType === null) { + fieldValueParsed = this.parseValue(fieldValue, fieldTypeInfo.type, fieldPropPath); + } else if (fieldCollectionType === Array || fieldCollectionType === Set) { + const isIterable = typeof fieldValue === "object" && (fieldValue as Object)[Symbol.iterator]; + if (!isIterable) { + throw "expected an Iterable at path " + fieldPropPath + "; but got: " + fieldValue; + } + const elements = []; + let idx = 0; + for (const elem of fieldValue as Iterable) { + elements.push(this.parseValue(elem, fieldTypeInfo.type, fieldPropPath + "[" + (++idx) + "]")); + } + if (fieldCollectionType === Array) { + const coll = []; + for (const elem of elements) { + coll.push(elem); + } + fieldValueParsed = coll; + } else if (fieldCollectionType === Set) { + const coll = new Set(); + for (const elem of elements) { + coll.add(elem); + } + fieldValueParsed = coll; + } + } else if (fieldCollectionType === Map) { + if (typeof fieldValue !== "object") { + throw "expected an Object at path " + fieldPropPath + "; but got: " + fieldValue; + } + const coll = new Map(); + for (const propName of Object.getOwnPropertyNames(fieldValue as Object)) { + const propValue = (fieldValue as Object)[propName]; + const propPropPath = fieldPropPath + "." + (utils.isLegalIdentifier(propName) ? propName : '"' + propName + '"'); + const propValueParsed = this.parseValue(propValue, fieldTypeInfo.type, propPropPath); + coll.set(propName, propValueParsed); + } + fieldValueParsed = coll; + } else { + throw "unsupported collectionType in TypeInfo for field " + fieldId + ": " + fieldCollectionType.name; + } + (result as Object)[field.name] = fieldValueParsed; + } + return result; + } + + private parseValue(value: any, type: constructor{? extends Object}, propertyPath: string): any { + if (value === undefined || value === null) { + return value; + } else if (type === Boolean) { + if (!(typeof value === "boolean")) { + throw "expected a boolean at path " + propertyPath + "; but got: " + value; + } + return value; + } else if (type === Number) { + if (!(typeof value === "number")) { + throw "expected a number at path " + propertyPath + "; but got: " + value; + } + return value; + } else if (type === String) { + if (!(typeof value === "string")) { + throw "expected a string at path " + propertyPath + "; but got: " + value; + } + return value; + } else if (isConstructorOfN4Object(type)) { + if (!(typeof value === "object")) { + throw "expected an object at path " + propertyPath + "; but got: " + value; + } + return this.parseObject(value as Object, type as constructor{? extends N4Object}, propertyPath); + } else { + throw "unsupported type in TypeInfo (must be Boolean, Number, String, or subclass of N4Object): " + type.name; + } + } +} + +function isConstructorOfN4Object(value: any) { + while (value !== undefined && value !== N4Object) { + value = Object.getPrototypeOf(value as Object); + } + return value === N4Object; +} diff --git a/n4js-tools/n4jsd-generator/src/ts/convert.ts b/n4js-tools/n4jsd-generator/src/ts/convert.ts index fda2f02d83..aca7da6952 100644 --- a/n4js-tools/n4jsd-generator/src/ts/convert.ts +++ b/n4js-tools/n4jsd-generator/src/ts/convert.ts @@ -15,26 +15,39 @@ import * as model from "./model"; import * as utils from "./utils"; import * as utils_ts from "./utils_ts"; +export type IgnorePredicate = (filePath: string, elementName?: string, memberName?: string, signatureIndex?: number) => boolean; + export class Converter { private readonly projectPath?: string; + private readonly ignorePredicate?: IgnorePredicate; + /** True iff option '--runtime-libs' was given on the command line. */ + private readonly runtimeLibs: boolean; private readonly program: ts.Program; private readonly checker: ts.TypeChecker; private exportAssignment: ts.ExportAssignment; + private readonly convertedTypes: Map = new Map(); + private readonly suppressedTypes: Set = new Set(); private readonly issues: utils.Issue[] = []; - constructor(sourceDtsFilePaths: string[], projectPath?: string) { + constructor(sourceDtsFilePaths: string[], projectPath?: string, ignorePredicate?: IgnorePredicate, runtimeLibs = false) { if (projectPath !== undefined && !path_lib.isAbsolute(projectPath)) { throw "projectPath must be absolute"; } this.projectPath = projectPath; + this.ignorePredicate = ignorePredicate; + this.runtimeLibs = runtimeLibs; // prepare compilation options const opts: ts.CompilerOptions = { allowJs: true }; + if (runtimeLibs) { + opts.noLib = true; + opts.types = []; // make sure we do not compile type definitions requested in a tsconfig.json the compiler might find! + } // compile .d.ts files const program = ts.createProgram(sourceDtsFilePaths, opts); @@ -64,6 +77,8 @@ export class Converter { convertScript(sourceFilePath: string): model.Script { // clean up this.exportAssignment = undefined; + this.convertedTypes.clear(); + this.suppressedTypes.clear(); this.issues.length = 0; const sourceFile = this.program.getSourceFile(sourceFilePath); @@ -74,6 +89,8 @@ export class Converter { } const result = new model.Script(); + result.tsFileName = path_lib.basename(sourceFilePath); + result.tsFilePath = sourceFilePath; result.mode = dtsMode; sourceFile.forEachChild(node => { if (ts.isImportDeclaration(node)) { @@ -128,7 +145,7 @@ export class Converter { return results; } } - this.createIssueForUnsupportedNode(node, "import"); + this.createErrorForUnsupportedNode(node, "import"); return []; } @@ -145,16 +162,15 @@ export class Converter { } else if (ts.isVariableDeclarationList(node)) { return this.convertVariableDeclList(node); // TODO can a VariableDeclarationList even appear here? } else if (ts.isFunctionDeclaration(node)) { - return [ this.convertFunction(node) ]; + return this.isIgnoredTopLevelElement(node) ? [] : inArrayIfDefined(this.convertFunction(node)); } else if (ts.isEnumDeclaration(node)) { - return [ this.convertEnum(node) ]; + return this.isIgnoredTopLevelElement(node) ? [] : inArrayIfDefined(this.convertEnum(node)); } else if (ts.isInterfaceDeclaration(node)) { - return [ this.convertInterface(node) ]; + return this.isIgnoredTopLevelElement(node) ? [] : inArrayIfDefined(this.convertInterface(node)); } else if (ts.isClassDeclaration(node)) { - return [ this.convertClass(node) ]; + return this.isIgnoredTopLevelElement(node) ? [] : inArrayIfDefined(this.convertClass(node)); } else if (ts.isTypeAliasDeclaration(node)) { - const elem = this.convertTypeAlias(node); - return elem !== undefined ? [ elem ] : []; + return this.isIgnoredTopLevelElement(node) ? [] : inArrayIfDefined(this.convertTypeAlias(node)); } else if (node.kind === ts.SyntaxKind.FirstStatement) { const children = utils_ts.getAllChildNodes(node); if (children.length === 2 @@ -162,15 +178,26 @@ export class Converter { || children[0].kind === ts.SyntaxKind.DeclareKeyword) && children[1].kind === ts.SyntaxKind.VariableDeclarationList) { // something like "export var someStr: string, someNum: number;" - return this.convertVariableDeclList(children[1] as ts.VariableDeclarationList); + const result = this.convertVariableDeclList(children[1] as ts.VariableDeclarationList); + if (result[0] && !result[0].jsdoc) { + result[0].jsdoc = utils_ts.getJSDocForNode(node); + } + return result; } } else if (ts.isModuleDeclaration(node)) { + if (this.isIgnoredTopLevelElement(node)) { + return []; + } + if (!this.exportAssignment) { + // we are *not* in legacy mode + return this.convertModuleDeclaration(node); + } const exportSymbol = this.checker.getSymbolAtLocation(this.exportAssignment.expression); - + if (utils.testFlagsOR(exportSymbol.flags, ts.SymbolFlags.ValueModule, ts.SymbolFlags.NamespaceModule)) { - + const sym = this.checker.getSymbolAtLocation(node.name); if (sym === exportSymbol) { const result = []; @@ -181,7 +208,12 @@ export class Converter { } } } - this.createIssueForUnsupportedNode(node); + this.createErrorForUnsupportedNode(node); + return []; + } + + private convertModuleDeclaration(node: ts.ModuleDeclaration): model.ExportableElement[] { + // TODO implement support for namespaces return []; } @@ -189,6 +221,9 @@ export class Converter { const keyword = utils_ts.getVarDeclKeyword(node); const result = [] as model.Variable[]; for (const varDecl of node.declarations) { + if (this.isIgnoredTopLevelElement(varDecl)) { + continue; + } result.push(this.convertVariable(varDecl, keyword)); } return result; @@ -197,6 +232,7 @@ export class Converter { private convertVariable(node: ts.VariableDeclaration, keyword: model.VariableKeyword): model.Variable { const result = new model.Variable(); result.name = utils_ts.getLocalNameOfExportableElement(node, this.checker, this.exportAssignment); + result.jsdoc = utils_ts.getJSDocForNode(node); result.keyword = keyword; result.type = this.convertTypeReference(node.type); result.exported = utils_ts.isExported(node); @@ -206,12 +242,19 @@ export class Converter { private convertFunction(node: ts.FunctionDeclaration): model.Function { const sym = this.checker.getSymbolAtLocation(node.name); - const funSigs = this.convertCallSignatures(sym); - + const sourceFile = node.getSourceFile(); + let firstDeclFromCurrentFile = sym.declarations?.find(decl => decl?.getSourceFile() === sourceFile); + if (firstDeclFromCurrentFile !== node) { + // we were called for the AST node of a signature other than this function's first signature + // --> ignore this call, because we have handled all signatures in one go when we were + // called for the AST node of the first signature + return undefined; + } + const result = new model.Function(); result.name = utils_ts.getLocalNameOfExportableElement(node, this.checker, this.exportAssignment); - const expOfModule = this.checker.getExportSymbolOfSymbol(sym); - + result.jsdoc = utils_ts.getJSDocForNode(node); + const funSigs = this.convertCallSignatures(node.getSourceFile(), sym); result.signatures = funSigs; result.exported = utils_ts.isExported(node); result.exportedAsDefault = utils_ts.isExportedAsDefault(node, this.checker, this.exportAssignment); @@ -221,6 +264,7 @@ export class Converter { private convertEnum(node: ts.EnumDeclaration): model.Type { let result = new model.Type(); result.name = utils_ts.getLocalNameOfExportableElement(node, this.checker, this.exportAssignment); + result.jsdoc = utils_ts.getJSDocForNode(node); result.kind = model.TypeKind.ENUM; result.exported = utils_ts.isExported(node); result.exportedAsDefault = utils_ts.isExportedAsDefault(node, this.checker, this.exportAssignment); @@ -240,7 +284,7 @@ export class Converter { } else { // use @StringBased enum in error case result.primitiveBased = model.PrimitiveBasedKind.STRING_BASED; - this.createIssueForNode("unsupported value types in const enum: " + Array.from(valueTypes).join(", "), node); + this.createErrorForNode("unsupported value types in const enum: " + Array.from(valueTypes).join(", "), node); } } @@ -255,6 +299,7 @@ export class Converter { const litSym = this.checker.getSymbolAtLocation(lit.name); const result = new model.EnumLiteral(); result.name = litSym.getName(); + result.jsdoc = utils_ts.getJSDocForNode(lit); if (isConst) { result.value = this.checker.getConstantValue(lit); } @@ -264,27 +309,62 @@ export class Converter { } private convertInterface(node: ts.InterfaceDeclaration): model.Type { - const result = new model.Type(); - result.name = utils_ts.getLocalNameOfExportableElement(node, this.checker, this.exportAssignment); - result.kind = model.TypeKind.INTERFACE; + const [result, isNew] = this.getOrCreateN4jsType(node); + if (result.kind === undefined) { // classes must not be changed to interfaces! + result.kind = model.TypeKind.INTERFACE; + } result.defSiteStructural = true; - result.typeParams.push(...this.convertTypeParameters(node)); + this.convertHeritageClauses(node, result); result.members.push(...this.convertMembers(node)); result.exported = utils_ts.isExported(node); result.exportedAsDefault = utils_ts.isExportedAsDefault(node, this.checker, this.exportAssignment); - return result; + return isNew ? result : undefined; } private convertClass(node: ts.ClassDeclaration): model.Type { - const result = new model.Type(); - result.name = utils_ts.getLocalNameOfExportableElement(node, this.checker, this.exportAssignment); - result.kind = model.TypeKind.CLASS; + const [result, isNew] = this.getOrCreateN4jsType(node); + result.kind = model.TypeKind.CLASS; // interfaces will be changed to classes! result.defSiteStructural = true; - result.typeParams.push(...this.convertTypeParameters(node)); + this.convertHeritageClauses(node, result); result.members.push(...this.convertMembers(node)); result.exported = utils_ts.isExported(node); result.exportedAsDefault = utils_ts.isExportedAsDefault(node, this.checker, this.exportAssignment); - return result; + return isNew ? result : undefined; + } + + /** + * Creates a new model.Type or returns an already existing type (if one exists). The latter occurs only + * in case of declaration merging. + * + * Since this method is invoked (only) from methods #convertInterface() and #convertClass(), an already + * existing type returned by this method might be an interface or a class. + */ + private getOrCreateN4jsType(node: ts.InterfaceDeclaration | ts.ClassDeclaration): [model.Type, boolean] { + const sym = this.checker.getSymbolAtLocation(node.name); + // 1) actually get/create the type + let result = this.convertedTypes.get(sym); + let isNew = false; + if (!result) { + result = new model.Type(); + result.name = utils_ts.getLocalNameOfExportableElement(node, this.checker, this.exportAssignment); + this.convertedTypes.set(sym, result); + isNew = true; + } + // 2) perform some updates/initializations that apply to all types + // 2.a) type parameters + // (in case of declaration merging, TypeScript enforces each declaration to + // have the identical type paramters (even names must be equal), so it is ok to do + // the following just once based on the first declaration) + if (isNew) { + result.typeParams.push(...this.convertTypeParameters(node)); + } + // 2.b) JSDoc + // (we do not merge JSDoc across declarations; instead, we use the JSDoc of the first + // declaration that actually has a JSDoc) + if (!result.jsdoc) { + result.jsdoc = utils_ts.getJSDocForNode(node); + } + return [result, isNew]; } private convertTypeParameters(node: ts.NamedDeclaration): string[] { @@ -299,97 +379,179 @@ export class Converter { return result; } - private convertMembers(node: ts.NamedDeclaration): model.Member[] { + private convertHeritageClauses(node: ts.InterfaceDeclaration | ts.ClassDeclaration, type: model.Type) { + for (const clause of node.heritageClauses ?? []) { + const n4jsTypeRefs = []; + for (const expr of clause.types) { + const n4jsTypeRef = this.convertExpressionWithTypeArguments(expr); + if (n4jsTypeRef) { + n4jsTypeRefs.push(n4jsTypeRef); + } else { + this.createErrorForNode("unable to convert type reference in heritage clause", expr); + } + } + if (n4jsTypeRefs.length > 0) { + switch (clause.token) { + case ts.SyntaxKind.ExtendsKeyword: + type.extends.push(...n4jsTypeRefs); + break; + case ts.SyntaxKind.ImplementsKeyword: + type.implements.push(...n4jsTypeRefs); + break; + default: + this.createErrorForNode("unsupported keyword in heritage clause: " + clause.token, clause); + break; + } + } + } + } + + private convertMembers(node: ts.InterfaceDeclaration | ts.ClassDeclaration): model.Member[] { + const result = [] as model.Member[]; + const sourceFile = node.getSourceFile(); const sym = this.checker.getSymbolAtLocation(node.name); + for (const m of node.members) { + const n4jsMember = this.convertMember(sourceFile, m, utils_ts.isStatic(m), sym); + if (n4jsMember !== undefined) { + result.push(n4jsMember); + } + } + return result; + } + + private convertMembersOfObjectType(node: ts.TypeLiteralNode): model.Member[] { const result = [] as model.Member[]; - sym.members?.forEach((symMember, name) => { - const member = this.convertMember(symMember, sym); - if (member !== undefined) { - result.push(member); + const sourceFile = node.getSourceFile(); + for (const m of node.members) { + const n4jsMember = this.convertMember(sourceFile, m, false, undefined); + if (n4jsMember !== undefined) { + result.push(n4jsMember); } - }); + } return result; } - private convertMember(symMember: ts.Symbol, symOwner: ts.Symbol): model.Member | undefined { - // we need an AST node; in case of overloading there will be several declarations (one per signature) - // but because relevant properties (kind, accessibility, etc.) will be the same in all cases we can - // simply use the first one as representative: - const representativeNode = symMember.declarations[0] as ts.NamedDeclaration; + private convertMember(sourceFile: ts.SourceFile, node: ts.ClassElement | ts.TypeElement, isStatic: boolean, symContainingClassifier?: ts.Symbol): model.Member | undefined { + const symMember = (node.name + ? this.checker.getSymbolAtLocation(node.name) + : this.checker.getSymbolAtLocation(node)) ?? (node as any).symbol as ts.Symbol; + + let firstDeclFromCurrentFile = symMember.declarations?.find(decl => decl?.getSourceFile() === sourceFile); + if (firstDeclFromCurrentFile !== node) { + // we were called for the AST node of a signature other than this member's first signature + // --> ignore this call, because we have handled all signatures in one go when we were + // called for the AST node of the first signature + return undefined; + } const result = new model.Member(); - result.accessibility = utils_ts.getAccessibility(representativeNode); - result.isStatic = false; // FIXME + result.jsdoc = utils_ts.getJSDocForNode(node); + result.accessibility = utils_ts.getAccessibility(node); + result.isStatic = isStatic; - if (ts.isTypeParameterDeclaration(representativeNode)) { - // type parameters appear as members, but they are handled elsewhere + if (ts.isTypeParameterDeclaration(node)) { + // type parameters of the containing classifier appear as members, but they are handled elsewhere // -> so ignore them here: return undefined; } - if (ts.isConstructorDeclaration(representativeNode)) { + if (ts.isConstructorDeclaration(node)) { + if (!symContainingClassifier) { + return undefined; // constructor declarations only supported in classifiers + } result.kind = model.MemberKind.CTOR; - result.signatures = this.convertConstructSignatures(symOwner); + result.signatures = this.convertConstructSignatures(sourceFile, symContainingClassifier); return result; - } else if (ts.isConstructSignatureDeclaration(representativeNode)) { + } else if (ts.isConstructSignatureDeclaration(node)) { result.kind = model.MemberKind.CTOR; result.signatures = this.convertSignatureDeclarationsInAST(symMember.declarations); return result; - } else if (ts.isCallSignatureDeclaration(representativeNode)) { + } else if (ts.isCallSignatureDeclaration(node)) { result.kind = model.MemberKind.CALLABLE_CTOR; result.signatures = this.convertSignatureDeclarationsInAST(symMember.declarations); return result; + } else if (ts.isIndexSignatureDeclaration(node)) { + result.kind = model.MemberKind.INDEX_SIGNATURE; + result.signatures = [ this.convertIndexSignatureDeclarationInAST(node) ]; + return result; } result.name = symMember.getName(); + if (this.isIgnoredMember(sourceFile, symContainingClassifier, symMember)) { + return undefined; + } - const isReadonly = utils_ts.isReadonly(representativeNode); - if ((!isReadonly && ts.isPropertyDeclaration(representativeNode)) - || (!isReadonly && ts.isPropertySignature(representativeNode))) { + const isReadonly = utils_ts.isReadonly(node); + if ((!isReadonly && ts.isPropertyDeclaration(node)) + || (!isReadonly && ts.isPropertySignature(node))) { result.kind = model.MemberKind.FIELD; + result.isOptional = !!node.questionToken; result.type = this.convertTypeReferenceOfTypedSymbol(symMember); - return result; - } else if (ts.isGetAccessorDeclaration(representativeNode) - || (isReadonly && ts.isPropertyDeclaration(representativeNode)) - || (isReadonly && ts.isPropertySignature(representativeNode))) { + } else if (ts.isGetAccessorDeclaration(node) + || (isReadonly && ts.isPropertyDeclaration(node)) + || (isReadonly && ts.isPropertySignature(node))) { result.kind = model.MemberKind.GETTER; result.type = this.convertTypeReferenceOfTypedSymbol(symMember); - return result; - } else if (ts.isSetAccessorDeclaration(representativeNode)) { + } else if (ts.isSetAccessorDeclaration(node)) { result.kind = model.MemberKind.SETTER; - result.type = this.convertTypeReferenceOfTypedDeclaration(representativeNode.parameters[0]); - return result; - } else if (ts.isMethodDeclaration(representativeNode) - || ts.isMethodSignature(representativeNode)) { - const sigs = this.convertCallSignatures(symMember); + result.type = this.convertTypeReferenceOfTypedDeclaration(node.parameters[0]); + } else if (ts.isMethodDeclaration(node) + || ts.isMethodSignature(node)) { + const sigs = this.convertCallSignatures(sourceFile, symMember, symContainingClassifier); result.kind = model.MemberKind.METHOD; + result.isOptional = !!node.questionToken; result.signatures = sigs; - return result; + } else { + this.createErrorForUnsupportedNode(node, "member"); + return undefined; } - this.createIssueForUnsupportedNode(representativeNode, "member"); - return undefined; + return result; } - private convertConstructSignatures(somethingWithCtors: ts.Symbol): model.Signature[] { + private convertConstructSignatures(sourceFile: ts.SourceFile, somethingWithCtors: ts.Symbol): model.Signature[] { const type = this.checker.getTypeOfSymbolAtLocation(somethingWithCtors, somethingWithCtors.valueDeclaration!); const constructSigs = type.getConstructSignatures(); - return this.convertSignatures([...constructSigs]); + return this.convertSignatures(sourceFile, somethingWithCtors, [...constructSigs]); } - private convertCallSignatures(somethingWithSignatures: ts.Symbol): model.Signature[] { + private convertCallSignatures(sourceFile: ts.SourceFile, somethingWithSignatures: ts.Symbol, symContainingClassifier?: ts.Symbol): model.Signature[] { const type = this.checker.getTypeOfSymbolAtLocation(somethingWithSignatures, somethingWithSignatures.valueDeclaration!); const callSigs = type.getCallSignatures(); - return this.convertSignatures([...callSigs]); + return this.convertSignatures(sourceFile, somethingWithSignatures, [...callSigs], symContainingClassifier); } - private convertSignatures(signatures: ts.Signature[]): model.Signature[] { + private convertSignatures(sourceFile: ts.SourceFile, somethingWithSignatures: ts.Symbol, signatures: ts.Signature[], symContainingClassifier?: ts.Symbol, + allowIgnore: boolean = true): model.Signature[] { + const results = [] as model.Signature[]; + let sigIndex = -1; + let didIgnoreSignatures = false; for (const sig of signatures) { + if (sig.declaration?.getSourceFile() !== sourceFile) { + continue; // ignore declarations from other source files (and do not increment sigIndex for them!) + } + ++sigIndex; + if (allowIgnore && symContainingClassifier) { + if (this.isIgnoredSignature(sourceFile, symContainingClassifier, somethingWithSignatures, sigIndex)) { + didIgnoreSignatures = true; + continue; + } + } const result = new model.Signature(); + if (sig.typeParameters) { + for (const typeParam of sig.typeParameters) { + result.typeParams.push(typeParam.symbol.name); + } + } result.parameters = sig.getParameters().map(param => this.convertParameter(param)); result.returnType = this.convertTypeReferenceOfTypedDeclaration(sig.declaration); results.push(result); } + if (allowIgnore && didIgnoreSignatures && results.length === 0) { + // ignoring one or more signatures led to all signatures being ignored, which is illegal + // --> try again with ignore functionality being disabled: + return this.convertSignatures(sourceFile, somethingWithSignatures, signatures, symContainingClassifier, false); + } return results; } @@ -399,8 +561,23 @@ export class Converter { const isConstructSigDecl = ts.isConstructSignatureDeclaration(decl); if (isConstructSigDecl || ts.isCallSignatureDeclaration(decl) - || ts.isIndexSignatureDeclaration(decl)) { + || ts.isIndexSignatureDeclaration(decl) + || ts.isFunctionTypeNode(decl)) { const result = new model.Signature(); + if (decl.typeParameters) { + // is parameterization for this kind of member supported on N4JS side? + const typeParamsSupported = !ts.isCallSignatureDeclaration(decl); + if (typeParamsSupported) { + // yes + for (const typeParam of decl.typeParameters) { + result.typeParams.push(typeParam.name.text); + } + } else { + // no, type parameters are not supported on N4JS side for this member, + // so in the signature of this member we have to suppress all references to these type parameters: + this.suppressTypes([...decl.typeParameters]); + } + } for (const param of decl.parameters) { const paramSym = this.checker.getSymbolAtLocation(param.name); if (paramSym) { @@ -416,6 +593,19 @@ export class Converter { return results; } + private convertIndexSignatureDeclarationInAST(decl: ts.IndexSignatureDeclaration): model.Signature { + const result = new model.Signature(); + const param = decl.parameters[0]; + if (param) { + const paramSym = this.checker.getSymbolAtLocation(param.name); + if (paramSym) { + result.parameters.push(this.convertParameter(paramSym)); + } + } + result.returnType = this.convertTypeReference(decl.type); + return result; + } + private convertParameter(param: ts.Symbol): model.Parameter { const result = new model.Parameter(); result.name = param.getName(); @@ -425,13 +615,23 @@ export class Converter { result.isOptional = this.checker.isOptionalParameter(paramDecl); result.isVariadic = !!paramDecl.dotDotDotToken; } + if (result.isVariadic + && result.type?.kind === model.TypeRefKind.NAMED + && result.type?.targetTypeName === "Array" + && result.type?.targetTypeArgs?.length > 0) { + // "(...args: string[]):void" must be turned into + // "(...args: string):void" on N4JS side: + result.type = result.type.targetTypeArgs[0]; + } return result; } private convertTypeAlias(node: ts.TypeAliasDeclaration): model.Type { const result = new model.Type(); - result.name = utils_ts.getLocalNameOfExportableElement(node, this.checker, this.exportAssignment); result.kind = model.TypeKind.TYPE_ALIAS; + result.name = utils_ts.getLocalNameOfExportableElement(node, this.checker, this.exportAssignment); + result.jsdoc = utils_ts.getJSDocForNode(node); + result.typeParams.push(...(node.typeParameters ?? []).map((p: ts.TypeParameterDeclaration) => p.name.text)); result.exported = utils_ts.isExported(node); result.exportedAsDefault = utils_ts.isExportedAsDefault(node, this.checker, this.exportAssignment); result.aliasedType = this.convertTypeReference(node.type); @@ -470,23 +670,238 @@ export class Converter { } return undefined; } + private convertExpressionWithTypeArguments(node: ts.ExpressionWithTypeArguments): model.TypeRef { + const type = this.checker.getTypeAtLocation(node.expression); + if (this.suppressedTypes.has(type)) { + return model.createAnyPlus(); + } + const result = new model.TypeRef(); + result.kind = model.TypeRefKind.NAMED; + result.targetTypeName = node.expression.getText().trim(); + if (node.typeArguments) { + for (const typeArg of node.typeArguments) { + result.targetTypeArgs.push(this.convertTypeReference(typeArg) ?? model.createAnyPlus()); + } + } + return result; + } private convertTypeReference(node?: ts.TypeNode): model.TypeRef { - if (node) { - const result = new model.TypeRef(); - result.tsSourceString = node.getText().trim(); - return result; + if (!node) { + return undefined; } - return undefined; + const kind = node.kind; + const sourceStr = node.getText().trim(); + const result = new model.TypeRef(); + + // search typescript.js for "function isTypeNodeKind(kind)" to see a list of possible kind values: + if (kind === ts.SyntaxKind.AnyKeyword + || kind === ts.SyntaxKind.BooleanKeyword + || kind === ts.SyntaxKind.NumberKeyword + || kind === ts.SyntaxKind.StringKeyword + || kind === ts.SyntaxKind.SymbolKeyword + || kind === ts.SyntaxKind.VoidKeyword + || kind === ts.SyntaxKind.UndefinedKeyword) { + // type keyword supported by N4JS + result.kind = model.TypeRefKind.NAMED; + result.targetTypeName = sourceStr; + } else if (kind === ts.SyntaxKind.ObjectKeyword) { + // type keyword NOT supported by N4JS, but it can be converted + result.kind = model.TypeRefKind.NAMED; + result.targetTypeName = "Object"; + } else if (kind === ts.SyntaxKind.NullKeyword + || kind === ts.SyntaxKind.NeverKeyword + || kind === ts.SyntaxKind.UnknownKeyword + || kind === ts.SyntaxKind.BigIntKeyword) { + // type keyword NOT supported by N4JS -> replace by "any+" + return model.createAnyPlus(); + } else if (ts.isTypeReferenceNode(node)) { + // reference to another type (except for those types that are represented as keyword, see above) + const type = this.checker.getTypeAtLocation(node.typeName); + if (this.suppressedTypes.has(type)) { + return model.createAnyPlus(); + } + result.kind = model.TypeRefKind.NAMED; + result.targetTypeName = node.typeName.getText().trim(); + if (node.typeArguments) { + for (const typeArg of node.typeArguments) { + result.targetTypeArgs.push(this.convertTypeReference(typeArg) ?? model.createAnyPlus()); + } + } + } else if (ts.isLiteralTypeNode(node)) { + const literal = node.literal; + if (literal.kind === ts.SyntaxKind.NullKeyword) { + // not supported on N4JS side + return model.createAnyPlus(); + } else if (literal.kind === ts.SyntaxKind.FalseKeyword) { + result.kind = model.TypeRefKind.LITERAL; + } else if (literal.kind === ts.SyntaxKind.TrueKeyword) { + result.kind = model.TypeRefKind.LITERAL; + } else if (ts.isLiteralExpression(literal)) { + result.kind = model.TypeRefKind.LITERAL; + } else if (ts.isPrefixUnaryExpression(literal)) { + result.kind = model.TypeRefKind.LITERAL; + } else { + this.createErrorForUnsupportedNode(literal, "literal in LiteralTypeNode"); + return model.createAnyPlus(); + } + } else if (ts.isFunctionTypeNode(node)) { + result.kind = model.TypeRefKind.FUNCTION; + result.signature = this.convertSignatureDeclarationsInAST([node])[0]; + const param0 = result.signature?.parameters?.[0]; + if (param0 && param0.name === "this") { + result.signature.parameters.splice(0, 1); + const annThis = new model.Annotation("@This"); + annThis.args.push(param0.type ?? model.createAnyPlus()); + result.annotations.push(annThis); + } + } else if (ts.isArrayTypeNode(node)) { + result.kind = model.TypeRefKind.NAMED; + result.targetTypeName = "Array"; + let elemType = node.elementType; + if (ts.isParenthesizedTypeNode(elemType)) { + elemType = elemType.type; + } + result.targetTypeArgs.push(this.convertTypeReference(elemType) ?? model.createAnyPlus()); + } else if (ts.isTypeLiteralNode(node)) { + // object type syntax, e.g. "let x: { prop: string };" + result.kind = model.TypeRefKind.OBJECT; + result.members.push(...this.convertMembersOfObjectType(node)); + } else if (ts.isThisTypeNode(node)) { + result.kind = model.TypeRefKind.THIS; + } else if (ts.isUnionTypeNode(node) + || ts.isIntersectionTypeNode(node)) { + const isUnion = ts.isUnionTypeNode(node); + const n4jsMemberTypeRefs = []; + for (const memberNode of node.types) { + if (isUnion) { + let memberKind = ts.isLiteralTypeNode(memberNode) ? memberNode.literal.kind : memberNode.kind; + if (memberKind === ts.SyntaxKind.NullKeyword || memberKind === ts.SyntaxKind.UndefinedKeyword) { + continue; // avoid 'null', 'undefined' in unions + } + } + const n4jsMemberTypeRef = this.convertTypeReference(memberNode); + if (n4jsMemberTypeRef) { + n4jsMemberTypeRefs.push(n4jsMemberTypeRef); + } + } + if (n4jsMemberTypeRefs.length === 0) { + return model.createUndefined(); + } else if (n4jsMemberTypeRefs.length === 1) { + return n4jsMemberTypeRefs[0]; + } + result.kind = isUnion ? model.TypeRefKind.UNION : model.TypeRefKind.INTERSECTION; + result.composedTypeRefs.push(...n4jsMemberTypeRefs); + } else if (ts.isTupleTypeNode(node)) { + result.kind = model.TypeRefKind.TUPLE; + result.targetTypeName = "Array"; + for (let elemTypeNode of node.elements) { + if (ts.isNamedTupleMember(elemTypeNode)) { + elemTypeNode = elemTypeNode.type; + } + const n4jsElemTypeRef = this.convertTypeReference(elemTypeNode); + result.targetTypeArgs.push(n4jsElemTypeRef ?? model.createAnyPlus()); + } + // } else if (ts.isTypeQueryNode(node)) { // unsupported (for now) + } else if (ts.isParenthesizedTypeNode(node)) { + result.kind = model.TypeRefKind.PARENTHESES; + result.parenthesizedTypeRef = this.convertTypeReference(node.type); + } else if (ts.isTypeOperatorNode(node)) { + let op: model.TypeRefOperator = undefined; + switch(node.operator) { + case ts.SyntaxKind.KeyOfKeyword: + op = model.TypeRefOperator.KEYOF; + break; + case ts.SyntaxKind.UniqueKeyword: + op = model.TypeRefOperator.UNIQUE; + break; + case ts.SyntaxKind.ReadonlyKeyword: + op = model.TypeRefOperator.READONLY; + break; + default: + this.createErrorForNode("unsupported type operator: " + node.operator, node); + } + const resultNested = this.convertTypeReference(node.type); + if (resultNested && op) { + resultNested.tsOperators.push(op); + } + return resultNested; + } else if (ts.isTypePredicateNode(node)) { + // e.g. "this is Cls" + result.kind = model.TypeRefKind.PREDICATE; + this.createWarningForNode("type predicate will be replaced by boolean", node); + } else if (ts.isIndexedAccessTypeNode(node)) { + // e.g. "SomeType['someProperty']" + result.kind = model.TypeRefKind.INDEXED_ACCESS_TYPE; + this.createWarningForNode("indexed access type will be replaced by any+", node); + } else if (ts.isMappedTypeNode(node)) { + // e.g. { [P in K]: T[P]; } + result.kind = model.TypeRefKind.MAPPED_TYPE; + this.createWarningForNode("mapped type will be replaced by Object+", node); + } else { + this.createErrorForUnsupportedNode(node, "TypeNode (in #convertTypeReference())") + return model.createAnyPlus(); + } + + result.tsSourceString = sourceStr; + return result; + } + + private isIgnoredTopLevelElement(elemDeclNode: ts.NamedDeclaration) { + if (!this.ignorePredicate) { + return false; + } + const filePath = utils_ts.getFilePath(elemDeclNode); + const elementName = utils_ts.getLocalNameOfExportableElement(elemDeclNode as ts.NamedDeclaration, this.checker); + return this.ignorePredicate(filePath, elementName); + } + + private isIgnoredMember(sourceFile: ts.SourceFile, classifierSym: ts.Symbol | undefined, memberSym: ts.Symbol) { + if (!this.ignorePredicate) { + return false; + } + return this.ignorePredicate(sourceFile.fileName, classifierSym?.name, memberSym.name); + } + + private isIgnoredSignature(sourceFile: ts.SourceFile, classifierSym: ts.Symbol, memberSym: ts.Symbol, signatureIndex: number) { + if (!this.ignorePredicate) { + return false; + } + return this.ignorePredicate(sourceFile.fileName, classifierSym.name, memberSym.name, signatureIndex); } - private createIssueForUnsupportedNode(node: ts.Node, superKind: string = "node") { + private suppressTypes(nodes: ts.NamedDeclaration[]): ts.Type[] { + const addedTypes = []; + for (const node of nodes) { + const type = this.checker.getTypeAtLocation(node.name); + if (type) { + this.suppressedTypes.add(type); + addedTypes.push(type); + } + } + return addedTypes; + } + + private createWarningForNode(msg: string, node: ts.Node) { + this.createIssueForNode(utils.IssueKind.WARNING, msg, node); + } + + private createErrorForUnsupportedNode(node: ts.Node, superKind: string = "node") { const nodeKindStr = ts.SyntaxKind[node.kind]; - this.createIssueForNode("unsupported kind of " + superKind + ": " + nodeKindStr, node); + this.createErrorForNode("unsupported kind of " + superKind + ": " + nodeKindStr, node); } - private createIssueForNode(msg: string, node: ts.Node) { + private createErrorForNode(msg: string, node: ts.Node) { + this.createIssueForNode(utils.IssueKind.ERROR, msg, node); + } + + private createIssueForNode(kind: utils.IssueKind, msg: string, node: ts.Node) { + const contextStr = utils_ts.getContextForNode(node, this.checker); const offendingCode = utils_ts.getSourceCodeForNode(node); - const error = utils.error(msg + "\n" + offendingCode); + const error = utils.issue(kind, msg + (contextStr ? " (in " + contextStr + ")" : "") + "\n" + offendingCode); this.issues.push(error); } } + +function inArrayIfDefined(value: T): T[] { + return value !== undefined && value !== null ? [ value ] : []; +} diff --git a/n4js-tools/n4jsd-generator/src/ts/model.d.ts b/n4js-tools/n4jsd-generator/src/ts/model.d.ts index 08044bf073..3ffcfd5477 100644 --- a/n4js-tools/n4jsd-generator/src/ts/model.d.ts +++ b/n4js-tools/n4jsd-generator/src/ts/model.d.ts @@ -25,6 +25,9 @@ export enum Accessibility { export class Annotation { name: string; + args: (string|TypeRef)[]; + + constructor(name?: string); } export interface AnnotatableElement { @@ -32,10 +35,14 @@ export interface AnnotatableElement { } export class Script { + tsFileName: string; + tsFilePath: string; mode: DTSMode; preamble?: string; imports: Import[]; topLevelElements: ExportableElement[]; + /** If defined, all other properties will be ignored and this string will be emitted. */ + replacementCode?: string; issues: utils.Issue[]; } @@ -58,6 +65,7 @@ export class NamedImport extends Import { export abstract class NamedElement { name: string; + jsdoc?: string; } export abstract class ExportableElement extends NamedElement { @@ -92,10 +100,12 @@ export class Type extends ExportableElement implements AnnotatableElement { defSiteStructural?: boolean; primitiveBased?: PrimitiveBasedKind; typeParams: string[]; - extends?: TypeRef; + extends: TypeRef[]; + implements: TypeRef[]; members: Member[]; literals: EnumLiteral[]; aliasedType: TypeRef; + additionalCode: string[]; } export class EnumLiteral extends NamedElement { @@ -103,7 +113,8 @@ export class EnumLiteral extends NamedElement { } export enum MemberKind { - CTOR, CALLABLE_CTOR, FIELD, GETTER, SETTER, METHOD + CTOR, CALLABLE_CTOR, INDEX_SIGNATURE, + FIELD, GETTER, SETTER, METHOD } export class Member extends NamedElement implements AnnotatableElement { @@ -111,12 +122,15 @@ export class Member extends NamedElement implements AnnotatableElement { kind: MemberKind; accessibility: Accessibility; isStatic: boolean; + isOptional: boolean; /** Will be defined iff this member is a data field or field accessor. */ type?: TypeRef; signatures?: Signature[]; + replacementCode?: string; } export class Signature { + typeParams: string[]; parameters: Parameter[]; /** Will be undefined iff this signature belongs to a constructor. */ returnType?: TypeRef; @@ -128,9 +142,51 @@ export class Parameter extends NamedElement { isVariadic: boolean; } -export class TypeRef { +export enum TypeRefKind { + /** Referring to a type by name or alias. Corresponds to ParameterizedTypeRef in N4JS. */ + NAMED, + LITERAL, + FUNCTION, + OBJECT, + THIS, + /** In this case, TypeRef#targetTypeName is either "Iterable*" or "Array*" and TypeRef#targetTypeArgs define the element types. */ + TUPLE, + UNION, + INTERSECTION, + PARENTHESES, + // the following are not actually supported on N4JS side: + PREDICATE, + INDEXED_ACCESS_TYPE, + MAPPED_TYPE +} + +export enum TypeRefOperator { + KEYOF, + UNIQUE, + READONLY +} + +export class TypeRef implements AnnotatableElement { // note: annotations only supported for TypeRefKind === FUNCTION + annotations: Annotation[]; + kind: TypeRefKind; + dynamic: boolean; + targetTypeName: string; + targetTypeArgs: TypeRef[]; + signature: Signature; + members: Member[]; + composedTypeRefs: TypeRef[]; + parenthesizedTypeRef: TypeRef; + /** The type operators that preceded this type reference on the TypeScript side. */ + tsOperators: TypeRefOperator[]; /** The type reference as given in the TypeScript source code. */ tsSourceString: string; + + public isBuiltInUndefined(): boolean; + public isComposed(): boolean; } +export function chooseSignature(signatures: Signature[]): [boolean, Signature]; +export function getSymbolNameFromPropertyName(propertyName: string): string; export function scriptToString(script: Script): string; +export function createUndefined(): TypeRef; +export function createAnyPlus(): TypeRef; diff --git a/n4js-tools/n4jsd-generator/src/ts/utils.d.ts b/n4js-tools/n4jsd-generator/src/ts/utils.d.ts index 45f5be6259..72bdfe4e58 100644 --- a/n4js-tools/n4jsd-generator/src/ts/utils.d.ts +++ b/n4js-tools/n4jsd-generator/src/ts/utils.d.ts @@ -23,6 +23,7 @@ export class Issue { } export function error(msg: string): Issue export function warning(msg: string): Issue +export function issue(kind: IssueKind, msg: string): Issue export enum LogKind { ERROR, ISSUE, INFO diff --git a/n4js-tools/n4jsd-generator/src/ts/utils_ts.ts b/n4js-tools/n4jsd-generator/src/ts/utils_ts.ts index 3fa0d462e7..5e388c96c4 100644 --- a/n4js-tools/n4jsd-generator/src/ts/utils_ts.ts +++ b/n4js-tools/n4jsd-generator/src/ts/utils_ts.ts @@ -15,6 +15,16 @@ import * as utils from "./utils"; // utilities related to TypeScript +export function getFilePath(node: ts.Node): string | undefined { + while (node && !ts.isSourceFile(node)) { + node = node.parent; + } + if (node && ts.isSourceFile(node)) { + return node.fileName; + } + return undefined; +} + export function getAllChildNodes(node: ts.Node): ts.Node[] { // for some reason, node.getChildren() does not do the trick in all cases, it seems const result = [] as ts.Node[]; @@ -132,6 +142,11 @@ export function getTypeKind(decl: ts.Node): model.TypeKind { return undefined; } +export function isStatic(node: ts.Declaration): boolean { + const flags = ts.getCombinedModifierFlags(node); + return utils.testFlag(flags, ts.ModifierFlags.Static); +} + export function isReadonly(node: ts.Declaration): boolean { const flags = ts.getCombinedModifierFlags(node); return utils.testFlag(flags, ts.ModifierFlags.Readonly); @@ -199,9 +214,9 @@ export function createEnumLiteralsFromValues(values: (string | number)[]): model return results; } -export function getSourceCodeForNode(node: ts.Node, indentStr: string = " |"): string { +export function getSourceCodeForNode(node: ts.Node, indentStr: string = " |"): string { const sourceFile = node.getSourceFile(); - let offendingCode = sourceFile.text.substring(node.pos, node.end); + let offendingCode = sourceFile.text.substring(node.getStart(), node.getEnd()); offendingCode = offendingCode.trim(); if (offendingCode.length > 256) { offendingCode = offendingCode.slice(0, 256) + " [...]"; @@ -210,3 +225,57 @@ export function getSourceCodeForNode(node: ts.Node, indentStr: string = " |"): offendingCode = indentStr + offendingCode.replace(/\n/gi, "\n" + indentStr); return offendingCode; } + +export function getJSDocForNode(node: ts.Node): string | undefined { + const sourceFile = node.getSourceFile(); + const leadingWhiteSpace = sourceFile.text.substring(node.pos, node.getStart()); + // search last "/**" that is not immediately followed by "/" + const len = leadingWhiteSpace.length; + let idxStart = -1; + let idx = 0; + while (true) { + idx = leadingWhiteSpace.indexOf("/*", idx); + if (idx < 0) { + break; + } else if (idx + 3 < len + && leadingWhiteSpace.charAt(idx + 2) === '*' + && leadingWhiteSpace.charAt(idx + 3) !== '/') { + // start of a JSDoc comment + idxStart = idx; + } + idx += 2; + } + if (idxStart < 0) { + return undefined; + } + let idxEnd = leadingWhiteSpace.indexOf("*/", idxStart); + if (idxEnd < 0) { + return undefined; + } + // get rid of unnecessary white space in comment + let doc = leadingWhiteSpace.substring(idxStart, idxEnd + 2); + doc = doc.replace(/\r\n/gi, "\n"); + doc = doc.replace(/\n\s+/gi, "\n"); + doc = doc.replace(/\n\*/gi, "\n *"); + return doc; +} + +export function getContextForNode(node: ts.Node, checker: ts.TypeChecker): string | undefined { + let result = undefined; + node = node?.parent; + while (node && !ts.isSourceFile(node)) { + const name = node['name']; + let nameStr: string = undefined; + if (typeof name === "string") { + nameStr = name; + } else if (name) { + const sym = checker.getSymbolAtLocation(name); + nameStr = sym.getName(); + } + if (nameStr) { + result = result ? nameStr + "." + result : nameStr; + } + node = node.parent; + } + return result; +} diff --git a/n4js-tools/n4jsd-generator/test/n4js/AbstractN4jsdGeneratorTest.n4js b/n4js-tools/n4jsd-generator/test/n4js/AbstractN4jsdGeneratorTest.n4js index 6fd4629b2d..cb93726507 100644 --- a/n4js-tools/n4jsd-generator/test/n4js/AbstractN4jsdGeneratorTest.n4js +++ b/n4js-tools/n4jsd-generator/test/n4js/AbstractN4jsdGeneratorTest.n4js @@ -13,6 +13,7 @@ import * as fs_lib from "fs"; import * as path_lib from "path"; import * as utils from "utils"; import {runN4jsdGenerator} from "generator"; +import * as runtimeLibs from "runtimeLibs"; import {Assert} from "org/eclipse/n4js/mangelhaft/assert/Assert"; // must use '_' as prefix of following constants to avoid N4JS warning @@ -27,6 +28,11 @@ export public interface ~ConversionOptions { args?: string[]; /** Expected errors reported by the generator. */ expectedErrors?: string[]; + /** + * Custom configuration for the runtime library generation that will replace + * the default configuration of file "runtimeLibsConfig.js". + */ + runtimeLibsConfig?: Object; } export public interface ~ModuleDesc { @@ -177,6 +183,8 @@ export public class AbstractN4jsdGeneratorTest { Assert.isTrue(modules.length > 0, "at least one module description must be given"); const additionalArgs = options.args ?? []; const expectedErrors = options.expectedErrors ?? []; + const runtimeLibsConfig = options.runtimeLibsConfig; + const projectName = "TestProject"; this.createProject("input", projectName); for (const currModule of modules) { @@ -191,10 +199,17 @@ export public class AbstractN4jsdGeneratorTest { } args.push(_ROOT + "/input/" + projectName); - if (expectedErrors.length === 0) { - this.doRunN4jsdGenerator(args, []); - } else { - this.doRunN4jsdGenerator(args, expectedErrors); + try { + if (runtimeLibsConfig) { + runtimeLibs.setTemporaryGenConfig(runtimeLibsConfig); + } + if (expectedErrors.length === 0) { + this.doRunN4jsdGenerator(args, []); + } else { + this.doRunN4jsdGenerator(args, expectedErrors); + } + } finally { + runtimeLibs.setTemporaryGenConfig(undefined); } for (const currModule of modules) { if (!currModule.n4jsd) { diff --git a/n4js-tools/n4jsd-generator/test/n4js/ConvertClassifiersTest.n4js b/n4js-tools/n4jsd-generator/test/n4js/ConvertClassifiersTest.n4js index 86a225df74..da2934cff7 100644 --- a/n4js-tools/n4jsd-generator/test/n4js/ConvertClassifiersTest.n4js +++ b/n4js-tools/n4jsd-generator/test/n4js/ConvertClassifiersTest.n4js @@ -28,25 +28,48 @@ export public class ConvertClassifiersTest extends AbstractN4jsdGeneratorTest { import { Buffer } from "./buffer" export interface Writable {} - export interface Writable2 extends Writable {} // TODO "extends" not yet supported by n4jsd-generator + export interface Writable2 extends Writable {} export class Stream implements Writable {} - export class Stream2 extends Stream implements Writable2 {} // TODO "extends"/"implements" not yet supported by n4jsd-generator + export class Stream2 extends Stream implements Writable2 {} `, n4jsd: ` import { Buffer } from "buffer"; - export external public interface ~Writable { - } + export external public interface ~Writable {} - export external public interface ~Writable2 { - } + export external public interface ~Writable2 extends Writable {} - export external public class ~Stream { - } + export external public class ~Stream implements Writable {} - export external public class ~Stream2 { - } + export external public class ~Stream2 extends Stream implements Writable2 {} + ` + } + ); + } + + @Test + public testClassifiersInheritance() { + this.assertConversion( + { + name: "main", + dts: ` + export interface Ifc {} + export interface IfcOther {} + export interface SubIfc extends Ifc, IfcOther {} + export class Cls implements Ifc {} + export class SubCls extends Cls implements SubIfc, IfcOther {} + `, + n4jsd: ` + export external public interface ~Ifc {} + + export external public interface ~IfcOther {} + + export external public interface ~SubIfc extends Ifc, IfcOther {} + + export external public class ~Cls implements Ifc {} + + export external public class ~SubCls extends Cls implements SubIfc, IfcOther {} ` } ); @@ -62,10 +85,40 @@ export public class ConvertClassifiersTest extends AbstractN4jsdGeneratorTest { export class Cls {} `, n4jsd: ` - export external public interface ~Ifc { + export external public interface ~Ifc {} + + export external public class ~Cls {} + ` + } + ); + } + + @Test + public testGenericMembers() { + this.assertConversionWithOptions( + { + args: [ "--copy-type-refs" ] + }, + { + name: "main", + dts: ` + export interface Ifc { + m(p: T): T; + // no static members in interfaces + } + export class Cls { + public m(p: T): T; + public static sm(p: T): T; + } + `, + n4jsd: ` + export external public interface ~Ifc { + m(p: T): T; } - export external public class ~Cls { + export external public class ~Cls { + public m(p: T): T; + public static sm(p: T): T; } ` } @@ -74,6 +127,110 @@ export public class ConvertClassifiersTest extends AbstractN4jsdGeneratorTest { @Test public testMembers() { + this.assertConversion( + { + name: "main", + dts: ` + export interface Ifc { + field: string; + get getter(): string; + set setter(p: string); + method1(): void; + method2(p1: string, p2: number): string; + } + + export class Cls { + field: string; + get getter(): string; + set setter(p: string); + method1(): void; + method2(p1: string, p2: number): string; + } + `, + n4jsd: ` + export external public interface ~Ifc { + field: any+; + get getter(): any+; + set setter(value: any+); + method1(): any+; + method2(p1: any+, p2: any+): any+; + } + + export external public class ~Cls { + field: any+; + get getter(): any+; + set setter(value: any+); + method1(): any+; + method2(p1: any+, p2: any+): any+; + } + ` + } + ); + } + + @Test + public testMembersStatic() { + this.assertConversion( + { + name: "main", + dts: ` + // static members in interfaces not supported by TypeScript + + export class Cls { + static field: string; + static get getter(): string; + static set setter(p: string); + static method1(): void; + static method2(p1: string, p2: number): string; + } + `, + n4jsd: ` + export external public class ~Cls { + static field: any+; + static get getter(): any+; + static set setter(value: any+); + static method1(): any+; + static method2(p1: any+, p2: any+): any+; + } + ` + } + ); + } + + @Test + public testMembersAccesibility() { + this.assertConversion( + { + name: "main", + dts: ` + export interface SomeInterface { + m1(): void; // accesibility modifiers not allowed here! + } + export class SomeClass { + m1(): void; + public m2(): void; + protected m3(): void; + private m4(): void; + } + `, + n4jsd: ` + export external public interface ~SomeInterface { + m1(): any+; + } + + export external public class ~SomeClass { + m1(): any+; + public m2(): any+; + protected m3(): any+; + private m4(): any+; + } + ` + } + ); + } + + @Test + public testMembersUseCase() { this.assertConversion( { name: "buffer", @@ -117,15 +274,15 @@ export public class ConvertClassifiersTest extends AbstractN4jsdGeneratorTest { export external public interface ~Writable { field: any+; get fieldReadOnly(): any+; - write(chunk: any+, fn: any+): any+; // further signatures were omitted + write(...args: any+): any+; // overloading not supported get getter(): any+; } - export external public class ~Stream { + export external public class ~Stream implements Writable { public field: any+; get fieldReadOnly(): any+; - public constructor(buff: any+); // further signatures were omitted - public write(chunk: any+, fn: any+): any+; // further signatures were omitted + public constructor(...args: any+); // overloading not supported + public write(...args: any+): any+; // overloading not supported get getter(): any+; set setter(value: any+); } @@ -135,31 +292,23 @@ export public class ConvertClassifiersTest extends AbstractN4jsdGeneratorTest { } @Test - public testMembersAccesibility() { - this.assertConversion( + public testConstructSignatures() { + this.assertConversionWithOptions( { - name: "main", + args: [ "--copy-type-refs" ] + }, + { + name: "es5.d.ts", dts: ` - export interface SomeInterface { - m1(): void; // accesibility modifiers not allowed here! - } - export class SomeClass { - m1(): void; - public m2(): void; - protected m3(): void; - private m4(): void; + export interface Ifc { + new(p: string): Ifc; + new(p1: string, p2: number): Ifc; } `, n4jsd: ` - export external public interface ~SomeInterface { - m1(): any+; - } - - export external public class ~SomeClass { - m1(): any+; - public m2(): any+; - protected m3(): any+; - private m4(): any+; + export external public interface ~Ifc { + @CovariantConstructor + constructor(...args: any+); // overloading not supported } ` } @@ -167,7 +316,7 @@ export public class ConvertClassifiersTest extends AbstractN4jsdGeneratorTest { } @Test - public testConstructSignatures() { + public testCallSignatures() { this.assertConversionWithOptions( { args: [ "--copy-type-refs" ] @@ -176,14 +325,13 @@ export public class ConvertClassifiersTest extends AbstractN4jsdGeneratorTest { name: "es5.d.ts", dts: ` export interface Ifc { - new(p: string): Ifc; - new(p1: string, p2: number): Ifc; + (p: string): number; + (p1: string, p2: number): boolean; } `, n4jsd: ` export external public interface ~Ifc { - @CovariantConstructor - constructor(p: string); // further signatures were omitted + (...args: any+): any+; // overloading not supported } ` } @@ -191,7 +339,7 @@ export public class ConvertClassifiersTest extends AbstractN4jsdGeneratorTest { } @Test - public testCallSignatures() { + public testCallSignatures_genericsUnsupported() { this.assertConversionWithOptions( { args: [ "--copy-type-refs" ] @@ -200,13 +348,12 @@ export public class ConvertClassifiersTest extends AbstractN4jsdGeneratorTest { name: "es5.d.ts", dts: ` export interface Ifc { - (p: string): number; - (p1: string, p2: number): boolean; + (value: T): boolean; } `, n4jsd: ` export external public interface ~Ifc { - (p: string): number; // further signatures were omitted + (value: any+): boolean; } ` } diff --git a/n4js-tools/n4jsd-generator/test/n4js/ConvertDocumentationTest.n4js b/n4js-tools/n4jsd-generator/test/n4js/ConvertDocumentationTest.n4js new file mode 100644 index 0000000000..44fb2b9d31 --- /dev/null +++ b/n4js-tools/n4jsd-generator/test/n4js/ConvertDocumentationTest.n4js @@ -0,0 +1,205 @@ +/** + * Copyright (c) 2021 NumberFour AG. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * NumberFour AG - Initial API and implementation + */ + +import {AbstractN4jsdGeneratorTest} from "AbstractN4jsdGeneratorTest"; + +export public class ConvertDocumentationTest extends AbstractN4jsdGeneratorTest { + + @Test + public testNonJsDoc01() { + this.assertConversion( + { + name: "main", + dts: ` + /* + * Some non-JSDoc documentation. + */ + export var myVar: string; + `, + n4jsd: ` + export public var myVar: any+; + ` + } + ); + } + + @Test + public testNonJsDoc02() { + this.assertConversion( + { + name: "main", + dts: ` + // + // Some non-JSDoc documentation. + // + export var myVar: string; + `, + n4jsd: ` + export public var myVar: any+; + ` + } + ); + } + + @Test + public testNonJsDoc03() { + this.assertConversion( + { + name: "main", + dts: ` + // + // + /** This should not be used. */ + // + /** + * Some JSDoc documentation. + */ + // + /**/ // <--- not a JSDoc comment! + // + export var myVar: string; + `, + n4jsd: ` + /** + * Some JSDoc documentation. + */ + export public var myVar: any+; + ` + } + ); + } + + @Test + public testDocumentedVariable01() { + this.assertConversion( + { + name: "main", + dts: ` + /** + * Some documentation. + */ + export var myVar: string; + `, + n4jsd: ` + /** + * Some documentation. + */ + export public var myVar: any+; + ` + } + ); + } + + @Test + public testDocumentedVariable02() { + this.assertConversion( + { + name: "main", + dts: ` + /** + * This should not override the documentaton for myVar1! + */ + export var + /** + * Documentation for myVar1. + */ + myVar1: string, + /** + * Documentation for myVar2. + */ + myVar2: string; + `, + n4jsd: ` + /** + * Documentation for myVar1. + */ + export public var myVar1: any+; + + /** + * Documentation for myVar2. + */ + export public var myVar2: any+; + ` + } + ); + } + + @Test + public testDocumentedFunction() { + this.assertConversion( + { + name: "main", + dts: ` + /** + * Some documentation. + */ + export function foo(): string; + `, + n4jsd: ` + /** + * Some documentation. + */ + export external public function foo(): any+; + ` + } + ); + } + + @Test + public testDocumentedClassifiers() { + this.assertConversion( + { + name: "main", + dts: ` + /** + * Some interface documentation. + */ + export interface Ifc { + /** + * Some method documentation (in interface). + */ + method(): string; + } + /** + * Some class documentation. + */ + export class Cls { + /** + * Some method documentation (in class). + */ + method(): string; + } + `, + n4jsd: ` + /** + * Some interface documentation. + */ + export external public interface ~Ifc { + /** + * Some method documentation (in interface). + */ + method(): any+; + } + + /** + * Some class documentation. + */ + export external public class ~Cls { + /** + * Some method documentation (in class). + */ + method(): any+; + } + ` + } + ); + } +} diff --git a/n4js-tools/n4jsd-generator/test/n4js/ConvertMultipleDeclarationsTest.n4js b/n4js-tools/n4jsd-generator/test/n4js/ConvertMultipleDeclarationsTest.n4js new file mode 100644 index 0000000000..50b14eae01 --- /dev/null +++ b/n4js-tools/n4jsd-generator/test/n4js/ConvertMultipleDeclarationsTest.n4js @@ -0,0 +1,130 @@ +/** + * Copyright (c) 2021 NumberFour AG. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * NumberFour AG - Initial API and implementation + */ + +import {AbstractN4jsdGeneratorTest} from "AbstractN4jsdGeneratorTest"; + +/** + * Tests for the case that multiple declarations are given for the same type. + */ +export public class ConvertMultipleDeclarationsTest extends AbstractN4jsdGeneratorTest { + + @Test + public testMultipleInterfaceDecls() { + this.assertConversion( + { + name: "main", + dts: ` + export interface Ifc { + field1: string; + method1(): string; + } + export interface Ifc { + field2: number; + method2(): number; + } + `, + n4jsd: ` + export external public interface ~Ifc { + field1: any+; + method1(): any+; + field2: any+; + method2(): any+; + } + ` + } + ); + } + + @Test + public testInterfaceAmendsClass() { + this.assertConversion( + { + name: "main", + dts: ` + export class MyType { + method1(): string; + static method1(): number; + } + export interface MyType { + method2(): number; + } + `, + n4jsd: ` + export external public class ~MyType { + method1(): any+; + static method1(): any+; + method2(): any+; + } + ` + } + ); + } + + @Test + public testClassAmendsInterface() { + this.assertConversion( + { + name: "main", + dts: ` + export interface MyType { + method1(): string; + } + export class MyType { + method2(): number; + static method2(): number; + } + `, + n4jsd: ` + export external public class ~MyType { + method1(): any+; + method2(): any+; + static method2(): any+; + } + ` + } + ); + } + + @Test + public testDifferentKindsOfMembers() { + this.assertConversion( + { + name: "main", + dts: ` + export interface Ifc { + field1: string; + get getter1(): string; + set setter1(value: string); + method1(): string; + } + export interface Ifc { + field2: number; + get getter2(): string; + set setter2(value: string); + method2(): number; + } + `, + n4jsd: ` + export external public interface ~Ifc { + field1: any+; + get getter1(): any+; + set setter1(value: any+); + method1(): any+; + field2: any+; + get getter2(): any+; + set setter2(value: any+); + method2(): any+; + } + ` + } + ); + } +} diff --git a/n4js-tools/n4jsd-generator/test/n4js/ConvertRuntimeLibsTest.n4js b/n4js-tools/n4jsd-generator/test/n4js/ConvertRuntimeLibsTest.n4js new file mode 100644 index 0000000000..27642fb726 --- /dev/null +++ b/n4js-tools/n4jsd-generator/test/n4js/ConvertRuntimeLibsTest.n4js @@ -0,0 +1,216 @@ +/** + * Copyright (c) 2021 NumberFour AG. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * NumberFour AG - Initial API and implementation + */ + +import {AbstractN4jsdGeneratorTest} from "AbstractN4jsdGeneratorTest"; + +export public class ConvertRuntimeLibsTest extends AbstractN4jsdGeneratorTest { + + @Test + public testCtorInstanceTypePattern_flavor1() { + this.assertConversionWithOptions( + { + args: [ "--runtime-libs", "--copy-type-refs" ], + runtimeLibsConfig: { + preamble: `@@Global @@ProvidedByRuntime`, + patchFiles: { + "es5test.d.ts": {} + } + } + }, + { + name: "es5test", + dts: ` + interface SomeType { + someInstanceMethod(p: string): number; + } + + interface SomeTypeConstructor { + new(p: string): SomeType; + someStaticMethod(p: string): number; + } + + declare var SomeType: SomeTypeConstructor; + `, + n4jsd: ` + @@Global @@ProvidedByRuntime + + export external public class SomeType { + public someInstanceMethod(p: string): number; + public constructor(p: string); + public static someStaticMethod(p: string): number; + } + + export external public type SomeTypeConstructor = constructor{SomeType}; + ` + } + ); + } + + @Test + public testCtorInstanceTypePattern_flavor2() { + this.assertConversionWithOptions( + { + args: [ "--runtime-libs", "--copy-type-refs" ], + runtimeLibsConfig: { + preamble: `@@Global @@ProvidedByRuntime`, + patchFiles: { + "es5test.d.ts": {} + } + } + }, + { + name: "es5test", + dts: ` + interface SomeType { + someInstanceMethod(p: string): number; + } + + declare var SomeType: { + new(p: string): SomeType; + someStaticMethod(p: string): number; + }; + `, + n4jsd: ` + @@Global @@ProvidedByRuntime + + export external public class SomeType { + public someInstanceMethod(p: string): number; + public constructor(p: string); + public static someStaticMethod(p: string): number; + } + ` + } + ); + } + + @Test + public testCtorInstanceTypePattern_withGenerics() { + this.assertConversionWithOptions( + { + args: [ "--runtime-libs", "--copy-type-refs" ], + runtimeLibsConfig: { + preamble: `@@Global @@ProvidedByRuntime`, + patchFiles: { + "es5test.d.ts": {} + } + } + }, + { + name: "es5test", + dts: ` + interface SomeGenType { + someInstanceMethod(p: string): T; + } + + interface SomeGenTypeConstructor { + new (...elems: T[]): SomeGenType; + someStaticMethod(p: string): number; + } + + declare var SomeGenType: SomeGenTypeConstructor; + `, + n4jsd: ` + @@Global @@ProvidedByRuntime + + export external public class SomeGenType { + public someInstanceMethod(p: string): T; + public constructor(...elems: T); + public static someStaticMethod(p: string): number; + } + + export external public type SomeGenTypeConstructor = constructor{SomeGenType}; + ` + } + ); + } + + @Test + public testCtorInstanceTypePattern_inheritance() { + this.assertConversionWithOptions( + { + args: [ "--runtime-libs", "--copy-type-refs" ], + runtimeLibsConfig: { + preamble: `@@Global @@ProvidedByRuntime`, + patchFiles: { + "es5test.d.ts": {} + } + } + }, + { + name: "es5test", + dts: ` + interface SomeType {} + interface SomeTypeConstructor {} + declare var SomeType: SomeTypeConstructor; + + interface SomeSubType extends SomeType {} + interface SomeSubTypeConstructor extends SomeTypeConstructor {} + declare var SomeSubType: SomeSubTypeConstructor; + `, + n4jsd: ` + @@Global @@ProvidedByRuntime + + export external public class SomeType {} + + export external public type SomeTypeConstructor = constructor{SomeType}; + + export external public class SomeSubType extends SomeType {} + + export external public type SomeSubTypeConstructor = constructor{SomeSubType}; + ` + } + ); + } + + @Test + public testPolyfill() { + this.assertConversionWithOptions( + { + args: [ "--runtime-libs", "--copy-type-refs" ], + runtimeLibsConfig: { + preamble: `@@Global @@ProvidedByRuntime`, + patchFiles: { + "es5test.d.ts": { + polyfills: [ + "Object", + "Math" + ] + } + } + } + }, + { + name: "es5test", + dts: ` + export class Object { + public someMemberAddedToObject(): string; + } + export class Math { + public someMemberAddedToMath(): string; + } + `, + n4jsd: ` + @@Global @@ProvidedByRuntime + + @Polyfill + export external public class ~Object extends Object { + public someMemberAddedToObject(): string; + } + + @Polyfill + export external public class ~Math extends Math { + public someMemberAddedToMath(): string; + } + ` + } + ); + } +} diff --git a/n4js-tools/n4jsd-generator/test/n4js/ConvertTypeAlias.n4js b/n4js-tools/n4jsd-generator/test/n4js/ConvertTypeAliasTest.n4js similarity index 100% rename from n4js-tools/n4jsd-generator/test/n4js/ConvertTypeAlias.n4js rename to n4js-tools/n4jsd-generator/test/n4js/ConvertTypeAliasTest.n4js diff --git a/n4js-tools/n4jsd-generator/test/n4js/ConvertTypeRefsTest.n4js b/n4js-tools/n4jsd-generator/test/n4js/ConvertTypeRefsTest.n4js new file mode 100644 index 0000000000..063f1e2e12 --- /dev/null +++ b/n4js-tools/n4jsd-generator/test/n4js/ConvertTypeRefsTest.n4js @@ -0,0 +1,226 @@ +/** + * Copyright (c) 2021 NumberFour AG. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * NumberFour AG - Initial API and implementation + */ + +import {AbstractN4jsdGeneratorTest} from "AbstractN4jsdGeneratorTest"; + +export public class ConvertTypeRefsTest extends AbstractN4jsdGeneratorTest { + + @Test + public testBuiltIns() { + this.assertTypeRefConversion("any", "any"); + this.assertTypeRefConversion("undefined", "undefined"); + this.assertTypeRefConversion("null", "any+"); // unsupported by N4JS + this.assertTypeRefConversion("never", "any+"); // unsupported by N4JS + this.assertTypeRefConversion("unknown", "any+"); // unsupported by N4JS + } + + @Test + public testPrimitives() { + this.assertTypeRefConversion("boolean", "boolean"); + this.assertTypeRefConversion("number", "number"); + this.assertTypeRefConversion("string", "string"); + this.assertTypeRefConversion("object", "Object"); // note: this is changed to upper-case Object! + this.assertTypeRefConversion("symbol", "symbol"); + } + + @Test + public testRefsToClassifier() { + this.assertTypeRefConversion("Ifc", "Ifc"); + this.assertTypeRefConversion("Cls", "Cls"); + this.assertTypeRefConversion("GenCls", "GenCls"); + } + + @Test + public testLiteralTypes() { + this.assertTypeRefConversion("false", "false"); + this.assertTypeRefConversion("true", "true"); + this.assertTypeRefConversion("42", "42"); + this.assertTypeRefConversion("42.1", "42.1"); + this.assertTypeRefConversion("-1.23", "-1.23"); + this.assertTypeRefConversion("- 1.23", "- 1.23"); + this.assertTypeRefConversion("''", "''"); + this.assertTypeRefConversion("'hello'", "'hello'"); + this.assertTypeRefConversion('"hello"', '"hello"'); + this.assertTypeRefConversion('`hello`', '`hello`'); + } + + @Test + public testFunctionTypes_parameters() { + this.assertTypeRefConversion("(p1:string,p2:number)=>void", "(p1: string, p2: number)=>void"); + this.assertTypeRefConversion("(p?:string)=>void", "(p: string = )=>void"); + this.assertTypeRefConversion("(...ps:string[])=>void", "(...ps: string)=>void"); + } + + @Test + public testFunctionTypes_returnTypes() { + this.assertTypeRefConversion("()=>void", "()=>void"); + this.assertTypeRefConversion("()=>string", "()=>string"); + this.assertTypeRefConversion("()=>Cls", "()=>Cls"); + this.assertTypeRefConversion("()=>Cls|Ifc", "()=>(Cls | Ifc)"); // important: parentheses required on N4JS side! + this.assertTypeRefConversion("()=>(Cls|Ifc)", "()=>(Cls | Ifc)"); + this.assertTypeRefConversion("(()=>Cls)|Ifc", "(()=>Cls) | Ifc"); + } + + @Test + public testArrayTypes() { + this.assertTypeRefConversion("string[]", "Array"); + this.assertTypeRefConversion("Cls[]", "Array"); + this.assertTypeRefConversion("(Ifc | Cls)[]", "Array"); + } + + @Test + public testObjectTypes() { + this.assertTypeRefConversion("{ prop: string }", "~Object with { prop: string; }"); + this.assertTypeRefConversion("{ get getter(): string }", "~Object with { get getter(): string; }"); + this.assertTypeRefConversion("{ set setter(p: string) }", "~Object with { set setter(value: string); }"); + this.assertTypeRefConversion("{ method(p: string): number }", "~Object with { method(p: string): number; }"); + + this.assertTypeRefConversion("{ prop }", "~Object with { prop: any+; }"); + this.assertTypeRefConversion("{ get getter() }", "~Object with { get getter(): any+; }"); + this.assertTypeRefConversion("{ set setter(p) }", "~Object with { set setter(value: any+); }"); + this.assertTypeRefConversion("{ method(p) }", "~Object with { method(p: any+): any+; }"); + } + + @Test + public testComposedTypeRef() { + this.assertTypeRefConversion("Ifc | Cls", "Ifc | Cls"); + this.assertTypeRefConversion("Ifc & Cls", "Ifc & Cls"); + } + + @Test + public testParentheses() { + this.assertTypeRefConversion("(Ifc | Cls) & Cls", "(Ifc | Cls) & Cls"); + this.assertTypeRefConversion("Ifc & (Ifc | Cls) & Cls", "Ifc & (Ifc | Cls) & Cls"); + } + + @Test + public testTypePredicates() { + this.assertTypeRefConversion("(value: any) => value is Cls", "(value: any)=>boolean"); // not supported on N4JS side + } + + @Test + public testMappedTypes() { + this.assertTypeRefConversion("{ [Property in keyof Cls]: number }", "Object+"); // not supported on N4JS side + } + + @Test + public testTypeOperators() { + this.assertTypeRefConversion("readonly string[]", "Array"); // for now, type operators are simply ignored on N4JS side + } + + @Test + public testNesting() { + // ensure that conversion works for type references that are nested within other type references + // (as test case for the nested conversion we use the conversion from "object" to "Object") + this.assertTypeRefConversion("GenCls", "GenCls"); // nested as type argument + this.assertTypeRefConversion("(p:object)=>object", "(p: Object)=>Object"); // nested in function type + this.assertTypeRefConversion("{ method(p: object): object }", "~Object with { method(p: Object): Object; }"); // nested in member of object type + this.assertTypeRefConversion("object | string", "Object | string"); // nested in composed type + } + + private assertTypeRefConversion(sourceDts: string, expectedSourceN4jsd: string) { + console.log(`Testing type reference conversion from "${sourceDts}" to "${expectedSourceN4jsd}" ...`); + this.assertConversionWithOptions( + { + args: [ "--copy-type-refs" ] + }, + { + name: "main", + dts: ` + export interface Ifc {} + export class Cls {} + export class GenCls {} + export const c: ${sourceDts}; + `, + n4jsd: ` + export external public interface ~Ifc {} + + export external public class ~Cls {} + + export external public class ~GenCls {} + + export public const c: ${expectedSourceN4jsd}; + ` + } + ); + } + + @Test + public testThisType() { + this.assertConversionWithOptions( + { + args: [ "--copy-type-refs" ] + }, + { + name: "main", + dts: ` + export class Cls { + public method(): this; + } + `, + n4jsd: ` + export external public class ~Cls { + public method(): this; + } + ` + } + ); + } + + @Test + public testVoidType() { + this.assertConversionWithOptions( + { + args: [ "--copy-type-refs" ] + }, + { + name: "main", + dts: ` + export function foo(): void; + export class Cls { + public method(): void; + } + `, + n4jsd: ` + export external public function foo(): void; + + export external public class ~Cls { + public method(): void; + } + ` + } + ); + } + + @Test + public testAvoidUndefinedInUnion() { + this.assertConversionWithOptions( + { + args: [ "--copy-type-refs" ] + }, + { + name: "main", + dts: ` + export class Cls { + public method1(): string | undefined; + public method2(): undefined | undefined; + } + `, + n4jsd: ` + export external public class ~Cls { + public method1(): string; + public method2(): undefined; + } + ` + } + ); + } +} diff --git a/n4js-tools/n4jsd-generator/test/n4js/ModuleStructureLegacyTest.n4js b/n4js-tools/n4jsd-generator/test/n4js/ModuleStructureLegacyTest.n4js index f537ff7adb..a4bd786ef2 100644 --- a/n4js-tools/n4jsd-generator/test/n4js/ModuleStructureLegacyTest.n4js +++ b/n4js-tools/n4jsd-generator/test/n4js/ModuleStructureLegacyTest.n4js @@ -47,8 +47,7 @@ export public class ModuleStructureLegacyTest extends AbstractN4jsdGeneratorTest export public var cachedBuffer: any+; - export external public interface ~Ifc { - } + export external public interface ~Ifc {} export external public function getBufferSize(buff: any+): any+; diff --git a/plugins/org.eclipse.n4js/src-env/env/builtin_js.n4jsd b/plugins/org.eclipse.n4js/src-env/env/builtin_js.n4jsd index cf4f6f3890..24c7c63139 100644 --- a/plugins/org.eclipse.n4js/src-env/env/builtin_js.n4jsd +++ b/plugins/org.eclipse.n4js/src-env/env/builtin_js.n4jsd @@ -1,1855 +1,858 @@ -/* - * Copyright (c) 2017 NumberFour AG. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * NumberFour AG - Initial API and implementation - */ - -@@Global @@ProvidedByRuntime - -// 15 Standard Built-in ECMAScript Objects, page 102 (PDF: 114) [ECMA5] - -// uncomment for stand-alone editing -// primitive void{}primitive string{}primitive number{}primitive boolean{}primitive any{} - - -// see also http://www.w3schools.com/jsref/default.asp - -/** - * When Object is called as a function rather than as a constructor, it performs a type conversion. - * - *

API description is copied from - * ECMAScript Language Specification / ISO/IEC. Geneva, Switzerland, June 2011 (ECMA-262, 5.1 Edition). - * International Standard. [URL] - *
Copyright (C) 2011 Ecma International - *
(see license documents (about/license) for complete copyright notice) - * - * - * @see ES5, 15.2 Object Objects, page 111 (PDF: 123) [ECMA5] - */ -export external public class Object { - - /** - * TODO finalize signature - */ - (...args: any): Object - - /** - * The built-in ES5 property "__proto__", here modeled as a read-only property (i.e. no setter provided), because - * changing an object's prototype after creation is strongly discouraged in todays Javascript engines. - */ - public get __proto__(): Object - - /** - * The initial value of Object.prototype is the standard built-in Object prototype object (15.2.4). - * - * Remark: Modeled as getter to emulate const and to allow for overriding. - * @see ES5, 15.2.3.1 - */ - public static get prototype(): Object - - /** - * Returns the prototype of the given object. - * - * @see ES5, 15.2.3.2 - */ - public static getPrototypeOf(obj: Object): Object - /** - * Returns the property descriptor of the given object. This descriptor has been directly - * defined for the object and not inherited by the prototype of the object. - * - * @see ES5, 15.2.3.3 - */ - public static getOwnPropertyDescriptor(obj: Object, prop: string): Object - /** - * Lists the names of the own defined properties in the given object. (So no inherited properties are listed.) - * - * @see ES5, 15.2.3.4 - */ - public static getOwnPropertyNames(obj: Object): Array - /** - * Creates a new object (with new Object) and sets the prototype to proto. Passes props to defineProperties. - * - * @see ES5, 15.2.3.5 - */ - public static create(proto: Object, props: Object = undefined): Object - /** - * Adds/changes a property to/of the given object. - * - * @see ES5, 15.2.3.6 - */ - public static defineProperty(obj: T, property: string, desc: Object): T - /** - * Adds/changes one or more properties to/of the given object. - * - * @see ES5, 15.2.3.7 - */ - public static defineProperties(obj: T, props: Object): T - /** - * Sets object's configurable flag to false. - * - * @see ES5, 15.2.3.8 - */ - public static seal(obj: T): T - /** - * Sets object's writable flag to false. - * - * @see ES5, 15.2.3.9 - */ - public static freeze(obj: T): T - /** - * Sets the extensible flag of this object to false. - * - * @see ES5, 15.2.3.10 - */ - public static preventExtensions(obj: T): T - /** - * Returns false, if object is configurable, true otherwise. - * - * @see ES5, 15.2.3.11 - */ - public static isSealed(obj: Object): boolean - /** - * Returns false, if object is writable, true otherwise. - * - * @see ES5, 15.2.3.12 - */ - public static isFrozen(obj: Object): boolean - /** - * Returns true, if the extensible flag is true, false otherwise. - * - * @see ES5, 15.2.3.13 - */ - public static isExtensible(obj: Object): boolean - /** - * Returns only the names of enumerable properties and methods. To get the names of all - * enumerable and unenumerable properties you have to call Object.getOwnPropertyNames. - * - * @see ES5, 15.2.3.14 - */ - public static keys(obj: Object): Array - - - /** - * Standard built-in Object-constructor. - * @see ES5, 15.2.4.1 - */ - public constructor(value: any = undefined): void - /** - * Returns either "[object undefined]", "[object null]" or "[object " + class + and "]" - * - * @see ES5, 15.2.4.2 - */ - public toString(): string - /** - * Delegates here only to toString. Sub classes may implement this method specifically. - * Currently, Array, Number, and Date provide their own locale-sensitive toLocaleString methods. - * - * @see ES5, 15.2.4.3 - */ - public toLocaleString(): string - /** - * Calls ToObject with this argument. Either the object or the host object used to call the constructor is returned. - * - * @see ES5, 15.2.4.4 - */ - public valueOf(): any // any as inherited by sub classes as well - /** - * Returns true, if for the given property name a property descriptor can be found at the current object. - * - * @param string propertyName
- * @return boolean

- * - * @see ES5, 15.2.4.5 - */ - public hasOwnProperty(propertyName: union{string, symbol}): boolean - /** - * Returns true, if the given object is equal to the prototype of the current object (this method has been invoked on). - * - * @param Object o
- * @return Object

- * - * @see ES5, 15.2.4.6 - */ - public isPrototypeOf(o: Object): boolean - /** - * Returns the enumerable flag of the property descriptor found for the given property name, or if there is no descriptor, return false. - * - * @return boolean

- * - * @see ES5, 15.2.4.7 - */ - public propertyIsEnumerable(propertyName: string): boolean - - // since ECMAScript 6 - -// // 15.2.3.15, ECMAScript 6 -// public static getOwnPropertyKeys(obj: Object): Array -// // 15.2.3.16, ECMAScript 6 - public static is(value1: any, value2: any): boolean -// // 15.2.3.17, ECMAScript 6 -// public static assign(target: Object, Object... source): Object -// // 15.2.3.19, ECMAScript 6 -// public static setPrototypeOf(object: Object, proto: Object): Object - - -} - - -/** - * A representation of a function - * - *

API description is copied from - * ECMAScript Language Specification / ISO/IEC. Geneva, Switzerland, June 2011 (ECMA-262, 5.1 Edition). - * International Standard. [URL] - *
Copyright (C) 2011 Ecma International - *
(see license documents (about/license) for complete copyright notice) - * - * @see ES5, 15.3 Function Objects, page 117 (PDF: 129) [ECMA5] - */ -export external public class Function extends Object { - - /** - * The Function prototype object is itself a Function object (its [[Class]] is "Function") that, when invoked, accepts any arguments and returns undefined. - * - */ - @Override public static get prototype(): Function - - /** - * The value of the prototype property is used to initialize the [[Prototype]] internal property of a newly created object before the Function object is invoked as a constructor for that newly created object. This property has the attribute { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }. - * NOTE Function objects created using Function.prototype.bind do not have a prototype property. - * - * @see ES5 15.3.5.2 - */ - public get prototype(): Object - - /** - * Invoking 'Function' directly has the same effect as creating an instance with 'new'. See documentation of - * constructor for more details. - */ - (... args: string): Function - - /** - * The last argument specifies the body (executable code) of a function; any preceding arguments specify formal - * parameters. - * - * @see ES5, 15.3.4.1 - * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function#Syntax - */ - // in WebStorm: new Function(args: Arguments = undefined) - // in TypeScript: new Function(...args : string[]) - public constructor (...args: string) // note: keep this signature (except return type) aligned with the callable constructor above - - // toString: inherited - // @see ES5, 15.3.4.2 - - /** - * Call each argArray element, collect the results inside a list and return the list - * The length property of the apply method is 2 - * - * @see ES5, 15.3.4.3 - */ - public apply(thisArg: any, argArray: Array): any - /** - * If this method was called with more than one argument then in left to right order starting with arg1 append - * each argument as the last element of argList - * Return the result providing thisArg as the this value and argList as the list of arguments. - * The length property of the call method is 1 - * - * @see ES5, 15.3.4.4 - */ - // in WebStorm: call(thisArg: Object, any... args): any - // in TypeScript: call(thisArg : any, ...args : any[]) : any - public call(thisArg: any, ...args: any): any - - /** - * The bind method takes one or more arguments, thisArg and (optionally) arg1, arg2, etc, and returns a new - * function object - * - * @see ES5, 15.3.4.5 - */ - // TODO: support annotation in type systems - // in WebStorm: bind(thisArg: T, any... args): function(this:%T%) - // in TypeScript: bind(thisArg : any, ...args : any[]) : any - public bind(thisArg: any, ...args: any): {function(... args: any): any} - - /** - * The value of the length property is an integer that indicates the ―typical‖ number of arguments expected by - * the function. However, the language permits the function to be invoked with some other number of arguments. - * The behavior of a function when invoked on a number of arguments other than the number specified by its - * length property depends on the function. - * - * @see ES5, 15.3.5.1 - */ - public get length(): number - - // prototype: inherited - // @see ES5, 15.3.5.2 - - /** - * Arguments of a Function as array-like object - */ - public get arguments(): any -} - -/** - * Array objects give special treatment to a certain class of property names. A property name P (in the form of a - * String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to - * 2^32 - 1. A property whose property name is an array index is also called an element. Every Array object has a - * length property whose value is always a nonnegative integer less than 2^32. The value of the length - * property is numerically greater than the name of every property whose name is an array index; whenever a - * property of an Array object is created or changed, other properties are adjusted as necessary to maintain this - * invariant. Specifically, whenever a property is added whose name is an array index, the length property is - * changed, if necessary, to be one more than the numeric value of that array index; and whenever the length - * property is changed, every property whose name is an array index whose value is not smaller than the new - * length is automatically deleted. This constraint applies only to own properties of an Array object and is - * unaffected by length or array index properties that may be inherited from its prototypes. - * - *

API description is copied from - * ECMAScript Language Specification / ISO/IEC. Geneva, Switzerland, June 2011 (ECMA-262, 5.1 Edition). - * International Standard. [URL] - *
Copyright (C) 2011 Ecma International - *
(see license documents (about/license) for complete copyright notice) - * - * @see ES5, 15.4 Array Objects, page 122 (PDF: 134) [ECMA5] - */ -export external public class Array extends Object { - - /** - * The initial value of Array.prototype is the Array prototype object (15.4.4). - * - * @see ES5 15.4.3.1 - */ - @Override public static get prototype(): Array - - /* - * The isArray function takes one argument arg, and returns the Boolean value true if the argument is an object - * whose class internal property is "Array"; otherwise it returns false. - * - * @see ES5, 15.4.3.2 - */ - public static isArray(obj: any): boolean - - /** - * Initializes an array either with a certain length or with the given list of items. - * - * @see ES5, 15.4.4.1 - */ - // in WebStorm: new Array(...*) - // in TypeScript: new Array(arrayLength) or new Array(...items : any[]) - public constructor(first: union{number, T} = undefined, ...items: T) // TODO: signature is type unsafe, allows to create arrays with elements of wrong type, new Array(5, "x", "y"), but cannot write constructor(items : union {number, T... items} = undefined) - - // 15.4.4.2 Array.prototype.toString ( ) inherited - // 15.4.4.3 Array.prototype.toLocaleString ( ) inherited - - - /** - * When the concat method is called with zero or more arguments item1, item2, etc., it returns an array - * containing the array elements of the object followed by the array elements of each argument in order. - * - * @see ES5, 15.4.4.4 - */ - public concat(...items: union {T, Array}): Array - /** - * The elements of the array are converted to Strings, and these Strings are then concatenated, separated by - * occurrences of the separator. If no separator is provided, a single comma is used as the separator. - * - * @see ES5, 15.4.4.5 - */ - public join(separator: string = undefined): string - /** - * The last element of the array is removed from the array and returned. - * - * @see ES5, 15.4.4.6 - */ - public pop(): T - /** - * The arguments are appended to the end of the array, in the order in which they appear. The new length of the - * array is returned as the result of the call. - * - * @see ES5, 15.4.4.7 - */ - public push(...items: T): number - /** - * The elements of the array are rearranged so as to reverse their order. The object is returned as the result of the call. - * - * @see ES5, 15.4.4.8 - */ - public reverse(): Array - /** - * The first element of the array is removed from the array and returned. - * - * @see ES5, 15.4.4.9 - */ - public shift(): T - /** - * The slice method takes two arguments, start and end, and returns an array containing the elements of the - * array from element start up to, but not including, element end (or through the end of the array if end is - * undefined). If start is negative, it is treated as length + start where length is the length of the array. If end is - * negative, it is treated as length + end where length is the length of the array. - * - * @see ES5, 15.4.4.10 - */ - public slice(start: number = undefined, end: number = undefined): Array - /** - * The elements of this array are sorted. The sort is not necessarily stable (that is, elements that compare equal - * do not necessarily remain in their original order). If compareFn is not undefined, it should be a function that - * accepts two arguments x and y and returns a negative value if x < y, zero if x = y, or a positive value if x > y. - * - * @see ES5, 15.4.4.11 - */ - public sort(compareFn: {function (x: T, y: T) : number} = undefined): Array - /** - * When the splice method is called with two or more arguments start, deleteCount and (optionally) item1, item2, - * etc., the deleteCount elements of the array starting at array index start are replaced by the arguments item1, - * item2, etc. An Array object containing the deleted elements (if any) is returned. - * - * @see ES5, 15.4.4.12 - */ - public splice(start: number = undefined, deleteCount: number = undefined, ...items: T): Array - /** - * The arguments are prepended to the start of the array, such that their order within the array is the same as the - * order in which they appear in the argument list. - * - * @see ES5, 15.4.4.13 - */ - public unshift(...items: T): number - - /** - * indexOf compares searchElement to the elements of the array, in ascending order, using the internal Strict - * Equality Comparison Algorithm (11.9.6), and if found at one or more positions, returns the index of the first - * such position; otherwise, -1 is returned. - *

The optional second argument fromIndex defaults to 0 (i.e. the whole array is searched). If it is greater than or - * equal to the length of the array, -1 is returned, i.e. the array will not be searched. If it is negative, it is used as - * the offset from the end of the array to compute fromIndex. If the computed index is less than 0, the whole array - * will be searched. - * - * @see ES5, 15.4.4.14 - */ - public indexOf(searchElement: any, fromIndex: number = undefined): number - /** - * lastIndexOf compares searchElement to the elements of the array in descending order using the internal - * Strict Equality Comparison Algorithm (11.9.6), and if found at one or more positions, returns the index of the - * last such position; otherwise, -1 is returned. - *

The optional second argument fromIndex defaults to the array's length minus one (i.e. the whole array is - * searched). If it is greater than or equal to the length of the array, the whole array will be searched. If it is - * negative, it is used as the offset from the end of the array to compute fromIndex. If the computed index is less - * than 0, -1 is returned. - * - * @see ES5, 15.4.4.15 - */ - public lastIndexOf(searchElement: any, fromIndex: number = undefined): number - /** - * callback should be a function that accepts three arguments and returns a value that is coercible to the - * Boolean value true or false. every calls callback once for each element present in the array, in ascending - * order, until it finds one where callback returns false. If such an element is found, every immediately returns - * false. Otherwise, if callback returned true for all elements, every will return true. callback is called only for - * elements of the array which actually exist; it is not called for missing elements of the array. - *

If a thisArg parameter is provided, it will be used as the this value for each invocation of callback. If it is not - * provided, undefined is used instead. - *

callback is called with three arguments: the value of the element, the index of the element, and the object - * being traversed. - *

every does not directly mutate the object on which it is called but the object may be mutated by the calls to - * callback. - *

The range of elements processed by every is set before the first call to callback. Elements which are - * appended to the array after the call to every begins will not be visited by callback. If existing elements of the - * array are changed, their value as passed to callback will be the value at the time every visits them; - * elements that are deleted after the call to every begins and before being visited are not visited. every acts - * like the "for all" quantifier in mathematics. In particular, for an empty array, it returns true. - * - * @see ES5, 15.4.4.16 - */ - public every(callback: {function(value: T, index: number, traversedObject: Array)}, thisObject: ThisT = undefined): boolean - /** - * callback should be a function that accepts three arguments and returns a value that is coercible to the - * Boolean value true or false. some calls callback once for each element present in the array, in ascending - * order, until it finds one where callback returns true. If such an element is found, some immediately returns - * true. Otherwise, some returns false. callback is called only for elements of the array which actually exist; it is - * not called for missing elements of the array. - *

If a thisArg parameter is provided, it will be used as the this value for each invocation of callback. If it is not - * provided, undefined is used instead. - *

callback is called with three arguments: the value of the element, the index of the element, and the object - * being traversed. - *

some does not directly mutate the object on which it is called but the object may be mutated by the calls to - * callback. - *

The range of elements processed by some is set before the first call to callback. Elements that are appended - * to the array after the call to some begins will not be visited by callback. If existing elements of the array are - * changed, their value as passed to callback will be the value at the time that some visits them; elements that - * are deleted after the call to some begins and before being visited are not visited. some acts like the "exists" - * quantifier in mathematics. In particular, for an empty array, it returns false. - * - * @see ES5, 15.4.4.17 - */ - public some(callback: {function(value: T, index: number, traversedObject: Array) : boolean}, thisObject: ThisT = undefined): boolean - /** - * callback should be a function that accepts three arguments. forEach calls callback once for each element - * present in the array, in ascending order. callback is called only for elements of the array which actually exist; - * it is not called for missing elements of the array. - *

If a thisArg parameter is provided, it will be used as the this value for each invocation of callback. If it is not - * provided, undefined is used instead. - *

callback is called with three arguments: the value of the element, the index of the element, and the object - * being traversed. - *

forEach does not directly mutate the object on which it is called but the object may be mutated by the calls to - * callback. - *

The range of elements processed by forEach is set before the first call to callback. Elements which are - * appended to the array after the call to forEach begins will not be visited by callback. If existing elements of - * the array are changed, their value as passed to callback will be the value at the time forEach visits them; - * elements that are deleted after the call to forEach begins and before being visited are not visited. - * - * @see ES5, 15.4.4.18 - */ - public forEach(callback: {function(value: T, index: number, traversedObject: Array) : void}, thisObject: ThisT = undefined): void - /** - * callback should be a function that accepts three arguments. map calls callback once for each element in the - * array, in ascending order, and constructs a new Array from the results. callback is called only for elements of - * the array which actually exist; it is not called for missing elements of the array. - *

If a thisArg parameter is provided, it will be used as the this value for each invocation of callback. If it is not - * provided, undefined is used instead. - *

callback is called with three arguments: the value of the element, the index of the element, and the object - * being traversed. - *

map does not directly mutate the object on which it is called but the object may be mutated by the calls to - * callback. - *

The range of elements processed by map is set before the first call to callback. Elements which are - * appended to the array after the call to map begins will not be visited by callback. If existing elements of the - * array are changed, their value as passed to callback will be the value at the time map visits them; elements - * that are deleted after the call to map begins and before being visited are not visited. - * - * @see ES5, 15.4.4.19 - */ - public map(callback: {function(value: T, index: number, traversedObject: Array) : U}, thisObject: ThisT = undefined): Array - - /** - * callback should be a function that accepts three arguments and returns a value that is coercible to the - * Boolean value true or false. filter calls callback once for each element in the array, in ascending order, - * and constructs a new array of all the values for which callback returns true. callback is called only for - * elements of the array which actually exist; it is not called for missing elements of the array. - * If a thisArg parameter is provided, it will be used as the this value for each invocation of callback. If it is not - * provided, undefined is used instead. - *

callback is called with three arguments: the value of the element, the index of the element, and the object - * being traversed. - *

filter does not directly mutate the object on which it is called but the object may be mutated by the calls to - * callback. - *

The range of elements processed by filter is set before the first call to callback. Elements which are - * appended to the array after the call to filter begins will not be visited by callback. If existing elements of - * the array are changed their value as passed to callback will be the value at the time filter visits them; - * elements that are deleted after the call to filter begins and before being visited are not visited. - * - * @see ES5, 15.4.4.20 - */ - public filter(callback: {function(value: T, index: number, traversedObject: Array) : boolean}, thisObject: ThisT = undefined): Array - // since ECMAScript 5 - - /** - * callback should be a function that takes four arguments. reduce calls the callback, as a function, once for - * each element present in the array, in ascending order. - *

callback is called with four arguments: the previousValue (or value from the previous call to callback), the - * currentValue (value of the current element), the currentIndex, and the object being traversed. The first time - * that callback is called, the previousValue and currentValue can be one of two values. If an initialValue was - * provided in the call to reduce, then previousValue will be equal to initialValue and currentValue will be equal - * to the first value in the array. If no initialValue was provided, then previousValue will be equal to the first value - * in the array and currentValue will be equal to the second. It is a TypeError if the array contains no elements - * and initialValue is not provided. - *

reduce does not directly mutate the object on which it is called but the object may be mutated by the calls to - * callback. - *

The range of elements processed by reduce is set before the first call to callback. Elements that are - * appended to the array after the call to reduce begins will not be visited by callback. If existing elements of - * the array are changed, their value as passed to callback will be the value at the time reduce visits them; - * elements that are deleted after the call to reduce begins and before being visited are not visited. - * - * @see ES5, 15.4.4.21 - */ - public reduce(callback: {function(previousValue: MemoT, currentValue: T, index: number, traversedObject: Array) : MemoT}, initialValue: MemoT = undefined): MemoT - /** - * callback should be a function that takes four arguments. reduceRight calls the callback, as a function, - * once for each element present in the array, in descending order. - *

callback is called with four arguments: the previousValue (or value from the previous call to callback), the - * currentValue (value of the current element), the currentIndex, and the object being traversed. The first time the - * function is called, the previousValue and currentValue can be one of two values. If an initialValue was provided - * in the call to reduceRight, then previousValue will be equal to initialValue and currentValue will be equal to the - * last value in the array. If no initialValue was provided, then previousValue will be equal to the last value in the - * array and currentValue will be equal to the second-to-last value. It is a TypeError if the array contains no - * elements and initialValue is not provided. - *

reduceRight does not directly mutate the object on which it is called but the object may be mutated by the - * calls to callback. - *

The range of elements processed by reduceRight is set before the first call to callback. Elements that are - * appended to the array after the call to reduceRight begins will not be visited by callback. If existing - * elements of the array are changed by callback, their value as passed to callback will be the value at the - * time reduceRight visits them; elements that are deleted after the call to reduceRight begins and before - * being visited are not visited. - * - * @see ES5, 15.4.4.22 - */ - public reduceRight(callback: {function(previousValue: MemoT, currentValue: T, index: number, traversedObject: Array) : MemoT}, initialValue: MemoT = undefined): MemoT - - /** - * The length property of this Array object is a data property whose value is always numerically greater than - * the name of every deletable property whose name is an array index. - * - * @see ES5, 15.4.5.2 - */ - public get length(): number - - /** - * The length property of this Array object is a data property whose value is always numerically greater than the name - * of every deletable property whose name is an array index. - *

NOTE - * Attempting to set the length property of an Array object to a value that is numerically less than or equal to the - * largest numeric property name of an existing array indexed non-deletable property of the array will result in the - * length being set to a numeric value that is one greater than that largest numeric property name. See 15.4.5.1. - * @see ES5, 15.4.5.2 - */ - public set length(length: number) - - /** - * Returns the default iterator for this array. - */ - public [Symbol.iterator](): Iterator -} - -/** - * Representation of a char sequence. - * - *

API description is copied from - * ECMAScript Language Specification / ISO/IEC. Geneva, Switzerland, June 2011 (ECMA-262, 5.1 Edition). - * International Standard. [URL] - *
Copyright (C) 2011 Ecma International - *
(see license documents (about/license) for complete copyright notice) - * - * @see ES5, 15.5 String Objects, page 141 (PDF: 153) [ECMA5] - */ -export external public class String extends Object { - - /** - * TODO finalize signature - */ - (...args: any): string - - // 15.5.3.1 String.prototype inherited (Object) - - /** - * Returns a String value containing as many characters as the number of arguments. Each argument specifies - * one character of the resulting String, with the first argument specifying the first character, and so on, from left - * to right. An argument is converted to a character by applying the operation ToUint16 (9.7) and regarding the - * resulting 16-bit integer as the code unit value of a character. If no arguments are supplied, the result is the - * empty String. - * - * @see ES5, 15.5.3.2 - */ - public static fromCharCode(...chars: number): string - - /** - * When called as function, it returns a String value (not a String object) computed by ToString(value). - * If value is not supplied, the empty String "" is returned. - * - * @see ES5, 15.5.4.1 String.prototype.constructor - */ - public constructor(value: any = undefined) - - // 15.5.4.2 String.prototype.toString ( ) inherited - - /** - * Returns this String value. - * - * @see ES5, 15.5.4.3 - */ - @Override public valueOf(): string - - /** - * Returns a String containing the character at position pos in the String resulting from converting this object to a - * String. If there is no character at that position, the result is the empty String. The result is a String value, not a - * String object. - *

If pos is a value of Number type that is an integer, then the result of x.charAt(pos) is equal to the result of - * x.substring(pos, pos+1). - * - * @see ES5, 15.5.4.4 - */ - public charAt(pos: number): string - /** - * Returns a Number (a nonnegative integer less than 2^16) representing the code unit value of the character at - * position pos in the String resulting from converting this object to a String. If there is no character at that - * position, the result is NaN. - * - * @see ES5, 15.5.4.5 - */ - public charCodeAt(index: number): number - /** - * When the concat method is called with zero or more arguments string1, string2, etc., it returns a String - * consisting of the characters of this object (converted to a String) followed by the characters of each of string1, - * string2, etc. (where each argument is converted to a String). The result is a String value, not a String object. - * - * @see ES5, 15.5.4.6 - */ - public concat(...strings: string): string - /** - * If searchString appears as a substring of the result of converting this object to a String, at one or more positions - * that are greater than or equal to position, then the index of the smallest such position is returned; - * otherwise, -1 is returned. If position is undefined, 0 is assumed, so as to search all of the String. - * - * @see ES5, 15.5.4.7 - */ - public indexOf(searchString: string, position: number = undefined): number - /** - * If searchString appears as a substring of the result of converting this object to a String at one or more positions - * that are smaller than or equal to position, then the index of the greatest such position is returned; - * otherwise, -1 is returned. If position is undefined, the length of the String value is assumed, so as to search - * all of the String. - * - * @see ES5, 15.5.4.8 - */ - public lastIndexOf(searchString: string, position: number = undefined): number - /** - * When the localeCompare method is called with one argument that, it returns a Number other than NaN that - * represents the result of a locale-sensitive String comparison of the this value (converted to a String) with that - * (converted to a String). The two Strings are S and That. The two Strings are compared in an implementation- - * defined fashion. The result is intended to order String values in the sort order specified by the system default - * locale, and will be negative, zero, or positive, depending on whether S comes before That in the sort order, the - * Strings are equal, or S comes after That in the sort order, respectively. - * - * optional parameters see MDN, are declared as "reserved" in ECMAScript 6 - * @see ES5, 15.5.4.9 - */ - public localeCompare(that: string, locales: string = undefined, options: any+ = undefined): number - /** - * Searches the given string for a match against a regular expression and returns the matches as an Array object. - * - * @see ES5, 15.5.4.10 - */ -// TODO use the following after fixing IDEBUG-273: -// public ~Array with {index: number; input: string;} match(regexp: RegExp) - public match(regexp: RegExp): ~Array with { index: number; input: string; groups?: any+; } - /** - * Searches the given string for the replace value string or a regular expression and returns a new - * string where the specified values are replaced. - * - * @see ES5, 15.5.4.11 - */ - public replace(searchValue: union{RegExp, string}, replaceValue: union{string, Function}): string - /** - * Searches the given string for the specified value or regular expression and returns the position - * of the match or -1 if no match is found. - * - * @see ES5, 15.5.4.12 - */ - public search(regexp: any): number - /** - * The slice method takes two arguments, start and end, and returns a substring of the result of converting this - * object to a String, starting from character position start and running to, but not including, character position end - * (or through the end of the String if end is undefined). If start is negative, it is treated as sourceLength+start - * where sourceLength is the length of the String. If end is negative, it is treated as sourceLength+end where - * sourceLength is the length of the String. The result is a String value, not a String object. - * - * @see ES5, 15.5.4.13 - */ - public slice(start: number, end: number = undefined): string - /** - * Returns an Array object into which substrings of the result of converting this object to a String have been - * stored. The substrings are determined by searching from left to right for occurrences of separator; these - * occurrences are not part of any substring in the returned array, but serve to divide up the String value. The - * value of separator may be a String of any length or it may be a RegExp object (i.e., an object whose [[Class]] - * internal property is "RegExp"; see 15.10). - *

The value of separator may be an empty String, an empty regular expression, or a regular expression that can - * match an empty String. In this case, separator does not match the empty substring at the beginning or end of - * the input String, nor does it match the empty substring at the end of the previous separator match. (For - * example, if separator is the empty String, the String is split up into individual characters; the length of the result - * array equals the length of the String, and each substring contains one character.) If separator is a regular - * expression, only the first match at a given position of the this String is considered, even if backtracking could - * yield a non-empty-substring match at that position. - *

If the this object is (or converts to) the empty String, the result depends on whether separator can match the - * empty String. If it can, the result array contains no elements. Otherwise, the result array contains one element, - * which is the empty String. - *

If separator is a regular expression that contains capturing parentheses, then each time separator is matched - * the results (including any undefined results) of the capturing parentheses are spliced into the output array. - *

If separator is undefined, then the result array contains just one String, which is the this value (converted to a - * String). If limit is not undefined, then the output array is truncated so that it contains no more than limit - * elements. - * - * @see ES5, 15.5.4.14 - */ - public split(separator: any, limit: number = undefined): Array - /** - * The substring method takes two arguments, start and end, and returns a substring of the result of converting - * this object to a String, starting from character position start and running to, but not including, character position - * end of the String (or through the end of the String is end is undefined). The result is a String value, not a String - * object. - *

If either argument is NaN or negative, it is replaced with zero; if either argument is larger than the length of the - * String, it is replaced with the length of the String. - *

If start is larger than end, they are swapped. - * - * @see ES5, 15.5.4.15 - */ - public substring(start: number, end: number = undefined): string - /** - * Produces a String where each of its characters are either the Unicode lowercase equivalent of the corresponding - * character in the given String or the actual corresponding character of the given String if no Unicode lowercase equivalent exists. - * - * @host String
- * @return string

- * - * @see ES5, 15.5.4.16 - */ - public toLowerCase(): string - /** - * This function works exactly the same as toLowerCase except that its result is intended to yield the correct - * result for the host environment‘s current locale, rather than a locale-independent result. There will only be a - * difference in the few cases (such as Turkish) where the rules for that language conflict with the regular - * Unicode case mappings. - * - * @see ES5, 15.5.4.17 - */ - public toLocaleLowerCase(): string - /** - * This function behaves in exactly the same way as String.prototype.toLowerCase, except that - * characters are mapped to their uppercase equivalents as specified in the Unicode Character Database. - * - * @see ES5, 15.5.4.18 - */ - public toUpperCase(): string - /** - * This function works exactly the same as toUpperCase except that its result is intended to yield the correct - * result for the host environment‘s current locale, rather than a locale-independent result. There will only be a - * difference in the few cases (such as Turkish) where the rules for that language conflict with the regular - * Unicode case mappings. - * - * @see ES5, 15.5.4.19 - */ - public toLocaleUpperCase(): string - - - // since ECMAScript 5 - - /** - * Removes whitespace from both sides of a string. - * - * @see ES5, 15.5.4.20 - */ - public trim(): string - - /**

The length property represents the length of a string. - *

This property returns the number of code units in the string. UTF-16, - * the string format used by JavaScript, - * uses a single 16-bit code unit to represent the most common characters, but needs to use two code units - * for less commonly-used characters, so it's possible for the value returned by length to not match - * the actual number of characters in the string. - * - * @see ES5, 15.5.5.1 - */ - public get length(): number - -// /** -// * The String.raw function may be called with a variable number of arguments. -// * The first argument is template and the remainder of the arguments form the List substitutions. -// * -// * @see ES6, 21.1.2.4 -// */ -// // TODO actually it should be Array, any... substitutions -// // but therefore we'd need deconstruction of a template in the context of a tagged value -// public static raw(t: Template): string - - /** - * Returns a new Iterator object that iterates over the code points of a String value, returning each code point as - * a String value. - */ - public [Symbol.iterator](): Iterator -} - -/** - * Representation of a boolean value, either true or false. - * - *

API description is copied from - * ECMAScript Language Specification / ISO/IEC. Geneva, Switzerland, June 2011 (ECMA-262, 5.1 Edition). - * International Standard. [URL] - *
Copyright (C) 2011 Ecma International - *
(see license documents (about/license) for complete copyright notice) - * - * @see ES5, 15.6 Boolean Objects, page 152 (PDF: 164) [ECMA5] - */ -export external public class Boolean extends Object { - - /** - * Returns a Boolean value (not a Boolean object) computed by ToBoolean(value). - * - * @see ES5, 15.6.2 - */ - public constructor(value: any = undefined) - - /** - * @see ES5, 15.6.4.3 - */ - @Override public valueOf(): boolean -} - -/** - * Representation of a number. - * - *

API description is copied from - * ECMAScript Language Specification / ISO/IEC. Geneva, Switzerland, June 2011 (ECMA-262, 5.1 Edition). - * International Standard. [URL] - *
Copyright (C) 2011 Ecma International - *
(see license documents (about/license) for complete copyright notice) - * - * @see ES5, 15.7 Number Objects, page 154 (PDF: 166) [ECMA5] - */ -export external public class Number extends Object { - - /** - * TODO finalize signature - */ - (... args: any): number - - /** - * - * @see ES5, 15.7.3.2 - */ - public const MAX_VALUE: number - /** - * @see ES5, 15.7.3.3 - */ - public const MIN_VALUE: number - /** - * @see ES5, 15.7.3.4 - */ - public const NaN: number - /** - * @see ES5, 15.7.3.5 - */ - public const NEGATIVE_INFINITY: number - /** - * @see ES5, 15.7.3.6 - */ - public const POSITIVE_INFINITY: number - - /** - * When called as function, it returns a Number value (not a Number object) computed by - * ToNumber(value) if value was supplied, else returns +0. - * - * @see ES5, 15.7.4.1 - */ - public constructor(value: any = undefined) - /** - * The optional radix should be an integer value in the inclusive range 2 to 36. If radix not present or is undefined - * the Number 10 is used as the value of radix. If ToInteger(radix) is the Number 10 then this Number value is - * given as an argument to the ToString abstract operation; the resulting String value is returned. - *

If ToInteger(radix) is not an integer between 2 and 36 inclusive throw a RangeError exception. If - * ToInteger(radix) is an integer from 2 to 36, but not 10, the result is a String representation of this Number value - * using the specified radix. Letters a-z are used for digits with values 10 through 35. The precise algorithm is - * implementation-dependent if the radix is not 10, however the algorithm should be a generalization of that - * specified in 9.8.1. - * - * @see ES5, 15.7.4.2 - */ - @Override public toString(radix: number = undefined): string - - // 15.7.4.3 Number.prototype.toLocaleString() inherited - - /** - * Returns this Number value. - * - * @see ES5, 15.7.4.4 - */ - @Override public valueOf(): number - /** - * Return a String containing this Number value represented in decimal fixed-point notation with fractionDigits - * digits after the decimal point. If fractionDigits is undefined, 0 is assumed. - * - * @see ES5, 15.7.4.5 - */ - public toFixed(fractionalDigits: number = undefined): string - /** - * Return a String containing this Number value represented in decimal exponential notation with one digit before - * the significand's decimal point and fractionDigits digits after the significand's decimal point. If fractionDigits is - * undefined, include as many significant digits as necessary to uniquely specify the Number (just like in - * ToString except that in this case the Number is always output in exponential notation). - * - * @see ES5, 15.7.4.6 - */ - public toExponential(fractionalDigits: number = undefined): string - - /** - * Return a String containing this Number value represented either in decimal exponential notation with one digit - * before the significand's decimal point and precision–1 digits after the significand's decimal point or in decimal - * fixed notation with precision significand digits. If precision is undefined, call ToString (9.8.1) instead. - * - * @see ES5, 15.7.4.7 - */ - public toPrecision(precision: number = undefined): string - -} - -/** - * See [ECMA6] Section 19.4. - * - * A symbol is a unique and immutable data type and may be used as an identifier for object properties. The symbol - * object is an implicit object wrapper for the symbol primitive data type. - * - * TODO in ES6 this is defined to be a property of the global object and a constructor function - */ -export external public class Symbol extends Object { - - /** - * Creates a new, primitive symbol. - * - * @param description A description of the symbol which can be used for debugging but not to access the symbol itself. - */ - (description: string = undefined): symbol - - /** - * This "well-known" symbol may be used to define the default iterator of an object. - * - * @see ES6, 19.4.2.4 - */ - public const iterator: symbol - - /** - * This "well-known" symbol may be used to define the default asynchronous iterator of an object. - * - * @see ES2018, 19.4.2.1 - */ - public const asyncIterator: symbol - - /** - * This "well-known" symbol may be used to customize the behavior of the 'instanceof' operator. - * - * @see ES6, 19.4.2.2 - */ - public const hasInstance: symbol - - /** - * Returns the shared symbol with the given key from the Javascript engine's shared symbol registry. - * Creates a new symbol if not found. - * - * @see ES6, 19.4.2.1 - */ - public static for(key: string): symbol - - /** - * Returns the key for the given shared symbol if found in the Javascript engine's shared symbol registry. - * Otherwise 'undefined' is returned. - * - * @see ES6, 19.4.2.5 - */ - public static keyFor(sym: symbol): string -} - -/** - * Mathematical attributes and operations. This object has no constructor and thus cannot be called with new. - * - *

API description is copied from - * ECMAScript Language Specification / ISO/IEC. Geneva, Switzerland, June 2011 (ECMA-262, 5.1 Edition). - * International Standard. [URL] - *
Copyright (C) 2011 Ecma International - *
(see license documents (about/license) for complete copyright notice) - * - * @see ES5, 15.8 The Math Object, page 159 (PDF: 171) [ECMA5] - */ -export external public class Math extends Object { - /** - * The Number value for e, the base of the natural logarithms, which is approximately 2.7182818284590452354. - * - * @see ES5, 15.8.1.1 - */ - public const E: number - /** - * The Number value for the natural logarithm of 10, which is approximately 2.302585092994046. - * - * @see ES5, 15.8.1.2 - */ - public const LN10: number - /** - * The Number value for the natural logarithm of 2, which is approximately 0.6931471805599453. - * - * @see ES5, 15.8.1.3 - */ - public const LN2: number - /** - * The Number value for the base-2 logarithm of e, the base of the natural logarithms; this value is approximately - * 1.4426950408889634. - * - * @see ES5, 15.8.1.4 - */ - public const LOG2E: number - /** - * The Number value for the base-10 logarithm of e, the base of the natural logarithms; this value is - * approximately 0.4342944819032518. - * - * @see ES5, 15.8.1.5 - */ - public const LOG10E: number - /** - * The Number value for n, the ratio of the circumference of a circle to its diameter, which is approximately - * 3.1415926535897932. - * - * @see ES5, 15.8.1.6 - */ - public const PI: number - /** - * The Number value for the square root of ½, which is approximately 0.7071067811865476. - * - * @see ES5, 15.8.1.7 - */ - public const SQRT1_2: number - /** - * The Number value for the square root of 2, which is approximately 1.4142135623730951. - * - * @see ES5, 15.8.1.8 - */ - public const SQRT2: number - - /** - * Returns the absolute value of x; the result has the same magnitude as x but has positive sign. - * - * @see ES5, 15.8.2.1 - */ - public static abs(x: number): number - /** - * Returns an implementation-dependent approximation to the arc cosine of x. The result is expressed in radians - * and ranges from +0 to +n. - * - * @see ES5, 15.8.2.2 - */ - public static acos(x: number): number - /** - * Returns an implementation-dependent approximation to the arc sine of x. The result is expressed in radians - * and ranges from -n/2 to +n/2. - * - * @see ES5, 15.8.2.3 - */ - public static asin(x: number): number - /** - * Returns an implementation-dependent approximation to the arc tangent of x. The result is expressed in - * radians and ranges from -n/2 to +n/2. - * - * @see ES5, 15.8.2.4 - */ - public static atan(x: number): number - /** - * Returns an implementation-dependent approximation to the arc tangent of the quotient y/x of the arguments y - * and x, where the signs of y and x are used to determine the quadrant of the result. Note that it is intentional - * and traditional for the two-argument arc tangent function that the argument named y be first and the argument - * named x be second. The result is expressed in radians and ranges from -n to +n. - * - * @see ES5, 15.8.2.5 - */ - public static atan2(x: number, y: number): number - /** - * Returns the smallest (closest to negative infinity) Number value that is not less than x and is equal to a mathematical - * integer. If x is already an integer, the result is x. - * - * @see ES5, 15.8.2.6 - */ - public static ceil(x: number): number - /** - * Returns an implementation-dependent approximation to the cosine of x. The argument is expressed in radians. - * - * @see ES5, 15.8.2.7 - */ - public static cos(x: number): number - /** - * Returns an implementation-dependent approximation to the exponential function of x (e raised to the power of - * x, where e is the base of the natural logarithms). - * - * @see ES5, 15.8.2.8 - */ - public static exp(x: number): number - /** - * Returns the greatest (closest to positive infinity) Number value that is not greater than x and is equal to a mathematical - * integer. If x is already an integer, the result is x. - * - * @see ES5, 15.8.2.9 - */ - public static floor(x: number): number - /** - * Returns an implementation-dependent approximation to the natural logarithm of x. - * - * @see ES5, 15.8.2.10 - */ - public static log(x: number): number - /** - * Given zero or more arguments, calls ToNumber on each of the arguments and returns the largest of the - * resulting values. - * - * @see ES5, 15.8.2.11 - */ - public static max(...x: number): number - /** - * Given zero or more arguments, calls ToNumber on each of the arguments and returns the smallest of the - * resulting values. - * - * @see ES5, 15.8.2.12 - */ - public static min(...x: number): number - /** - * Returns an implementation-dependent approximation to the result of raising x to the power y. - * - * @see ES5, 15.8.2.13 - */ - public static pow(x: number, y: number): number - /** - * Returns a Number value with positive sign, greater than or equal to 0 but less than 1, chosen randomly or - * pseudo randomly with approximately uniform distribution over that range, using an implementation-dependent - * algorithm or strategy. This function takes no arguments. - * - * @see ES5, 15.8.2.14 - */ - public static random(): number - /** - * Returns the Number value that is closest to x and is equal to a mathematical integer. If two integer Number - * values are equally close to x, then the result is the Number value that is closer to +. If x is already an integer, - * the result is x. - * - * @see ES5, 15.8.2.15 - */ - public static round(x: number): number - /** - * Returns an implementation-dependent approximation to the sine of x. The argument is expressed in radians. - * - * @see ES5, 15.8.2.16 - */ - public static sin(x: number): number - /** - * Returns an implementation-dependent approximation to the square root of x. - * - * @see ES5, 15.8.2.17 - */ - public static sqrt(x: number): number - /** - * Returns an implementation-dependent approximation to the tangent of x. - * - * @see ES5, 15.8.2.18 - */ - public static tan(x: number): number - -} - -/* - *

The following functions are abstract operations that operate on time values. - * - *

API description is copied from - * ECMAScript Language Specification / ISO/IEC. Geneva, Switzerland, June 2011 (ECMA-262, 5.1 Edition). - * International Standard. [URL] - *
Copyright (C) 2011 Ecma International - *
(see license documents (about/license) for complete copyright notice) - * - * @see ES5, 15.9 The Date Object, page 165 (PDF: 177) [ECMA5] - */ -export external public class Date extends Object { - - /** - * TODO finalize signature - */ - (... args: any): string - - /** - * The parse function applies the ToString operator to its argument and interprets the resulting String as a date - * and time; it returns a Number, the UTC time value corresponding to the date and time. The String may be - * interpreted as a local time, a UTC time, or a time in some other time zone, depending on the contents of the - * String. The function first attempts to parse the format of the String according to the rules called out in Date - * Time String Format (15.9.1.15). If the String does not conform to that format the function may fall back to any - * implementation-specific heuristics or implementation-specific date formats. Unrecognizable Strings or dates - * containing illegal element values in the format String shall cause Date.parse to return NaN. - * - * @see ES5, 15.9.3.2 - */ - public static parse(dateString: string): number - /** - * When the UTC function is called with fewer than two arguments, the behavior is implementation-dependent. - * When the UTC function is called with two to seven arguments, it computes the date from year, month and - * (optionally) date, hours, minutes, seconds and ms. - * - * - * @see ES5, 15.9.3.3 - */ - public static UTC(year: number, month: number, date: number = undefined, hours: number = undefined, minutes: number = undefined, seconds: number = undefined, milliseconds: number = undefined): number - - // since ECMAScript 5 - /** - * The now function return a Number value that is the time value designating the UTC date and time of the - * occurrence of the call to now. - * - * @host Date
- * @return number

- * - * @see ES5, 15.9.3.4 - */ - public static now(): number - -// public constructor(): void -// public constructor(value: number): void -// public constructor(value: string): void -// public constructor(year: number, month: number = undefined, day: number = undefined, hours: number = undefined, minutes: number = undefined, seconds: number = undefined, ms: number = undefined): void - /* - *

TODO: is it correctly defined? - see single line comments above?: answer: no - only one optional parameter allowed and no record types - * - * @see ES5, 15.9.5.1 - */ - public constructor(numberOrStringOrYear: union{string, number} = undefined, month: number = undefined, date: number = undefined, hours: number = undefined, minutes: number = undefined, seconds: number = undefined, ms: number = undefined) - /** - * This function returns a String value. The contents of the String are implementation-dependent, but are - * intended to represent the Date in the current time zone in a convenient, human-readable form. - * - * @see ES5, 15.9.5.2 - */ - @Override public toString(): string - /** - * This function returns a String value. The contents of the String are implementation-dependent, but are - * intended to represent the ―date‖ portion of the Date in the current time zone in a convenient, human-readable - * form. - * - * @see ES5, 15.9.5.3 - */ - public toDateString(): string - /** - * This function returns a String value. The contents of the String are implementation-dependent, but are - * intended to represent the ―time‖ portion of the Date in the current time zone in a convenient, human-readable - * form. - * - * @see ES5, 15.9.5.4 - */ - public toTimeString(): string - /** - * This function returns a String value. The contents of the String are implementation-dependent, but are - * intended to represent the Date in the current time zone in a convenient, human-readable form that - * corresponds to the conventions of the host environment‘s current locale. - * - * The first parameter to this function is likely to be used in a future version of this standard; - * it is recommended that implementations do not use this parameter position for anything else. - * - * ES6: The meaning of the optional parameters to this method are defined in the ECMA-402 specification; - * implementations that do not include ECMA-402 support must not use those parameter positions for anything else. - * - * @see ES5, 15.9.5.5 - */ - @Override public toLocaleString(): string - /** - * This function returns a String value. The contents of the String are implementation-dependent, but are - * intended to represent the ―date‖ portion of the Date in the current time zone in a convenient, human-readable - * form that corresponds to the conventions of the host environment‘s current locale. - * - * The first parameter to this function is likely to be used in a future version of this standard; - * it is recommended that implementations do not use this parameter position for anything else. - * - * ES6: The meaning of the optional parameters to this method are defined in the ECMA-402 specification; - * implementations that do not include ECMA-402 support must not use those parameter positions for anything else. - * - * @see ES5, 15.9.5.6 - */ - public toLocaleDateString(): string - /** - * This function returns a String value. The contents of the String are implementation-dependent, but are - * intended to represent the ―time‖ portion of the Date in the current time zone in a convenient, human-readable - * form that corresponds to the conventions of the host environment‘s current locale. - * - * optional parameters: see MDN - * - * @see ES5, 15.9.5.7 - */ - public toLocaleTimeString(): string - /** - * The valueOf function returns a Number, which is this time value. - * - * @see ES5, 15.9.5.8 - */ - @Override public valueOf(): number - /** - * @see ES5, 15.9.5.9 - */ - public getTime(): number - /** - * @see ES5, 15.9.5.10 - */ - public getFullYear(): number - /** - * @see ES5, 15.9.5.11 - */ - public getUTCFullYear(): number - /** - * @see ES5, 15.9.5.12 - */ - public getMonth(): number - /** - * @see ES5, 15.9.5.13 - */ - public getUTCMonth(): number - /** - * @see ES5, 15.9.5.14 - */ - public getDate(): number - /** - * @see ES5, 15.9.5.15 - */ - public getUTCDate(): number - /** - * @see ES5, 15.9.5.16 - */ - public getDay(): number - /** - * @see ES5, 15.9.5.17 - */ - public getUTCDay(): number - /** - * @see ES5, 15.9.5.18 - */ - public getHours(): number - /** - * @see ES5, 15.9.5.19 - */ - public getUTCHours(): number - /** - * @see ES5, 15.9.5.20 - */ - public getMinutes(): number - /** - * @see ES5, 15.9.5.21 - */ - public getUTCMinutes(): number - /** - * @see ES5, 15.9.5.22 - */ - public getSeconds(): number - /** - * @see ES5, 15.9.5.23 - */ - public getUTCSeconds(): number - /** - * @see ES5, 15.9.5.24 - */ - public getMilliseconds(): number - /** - * @see ES5, 15.9.5.25 - */ - public getUTCMilliseconds(): number - /** - * @see ES5, 15.9.5.26 - */ - public getTimezoneOffset(): number - /** - * @see ES5, 15.9.5.27 - */ - public setTime(value: number): number - /** - * @see ES5, 15.9.5.28 - */ - public setMilliseconds(ms: number): number - /** - * @see ES5, 15.9.5.29 - */ - public setUTCMilliseconds(ms: number): number - /* - * @see ES5, 15.9.5.30 - */ - public setSeconds(sec: number, ms: number = undefined): number - /** - * @see ES5, 15.9.5.31 - */ - public setUTCSeconds(sec: number, ms: number = undefined): number - /** - * @see ES5, 15.9.5.32 - */ - public setMinutes(min: number, sec: number = undefined, ms: number = undefined): number - /** - * @see ES5, 15.9.5.33 - */ - public setUTCMinutes(min: number, sec: number = undefined, ms: number = undefined): number - /** - * @see ES5, 15.9.5.34 - */ - public setHours(hour: number, min: number = undefined, sec: number = undefined, ms: number = undefined): number - /** - * @see ES5, 15.9.5.35 - */ - public setUTCHours(hour: number, min: number = undefined, sec: number = undefined, ms: number = undefined): number - /** - * @see ES5, 15.9.5.36 - */ - public setDate(date: number): number - /** - * @see ES5, 15.9.5.37 - */ - public setUTCDate(date: number): number - /** - * @see ES5, 15.9.5.38 - */ - public setMonth(month: number, date: number = undefined): number - /** - * @see ES5, 15.9.5.39 - */ - public setUTCMonth(month: number, date: number = undefined): number +@@Global @@ProvidedByRuntime + +export external public type PropertyKey = string | number | symbol; + +export external public interface ~PropertyDescriptor { + configurable?: boolean; + enumerable?: boolean; + value?: any; + writable?: boolean; + get?: ()=>any; + set?: (value: any)=>void; +} + +export external public interface ~PropertyDescriptorMap {} + +export external public class Object { + public toString(): string; + public toLocaleString(): string; + public valueOf(): any + public hasOwnProperty(v: PropertyKey): boolean; + public isPrototypeOf(v: Object): boolean; + public propertyIsEnumerable(v: PropertyKey): boolean; + public constructor(value: any = ); + (...args: any): Object; + public static getPrototypeOf(o: any): Object; + public static getOwnPropertyDescriptor(o: any, p: PropertyKey): PropertyDescriptor; + public static getOwnPropertyNames(o: any): Array; + public static create(proto: Object, props: Object = undefined): Object; + public static defineProperty(o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType): T; + public static defineProperties(o: T, properties: PropertyDescriptorMap & ThisType): T; + public static seal(o: T): T; + public static freeze(obj: T): T; + public static preventExtensions(o: T): T; + public static isSealed(o: any): boolean; + public static isFrozen(o: any): boolean; + public static isExtensible(o: any): boolean; + public static keys(o: Object): Array; /** - * @see ES5, 15.9.5.40 + * The built-in ES5 property "__proto__", here modeled as a read-only property (i.e. no setter provided), because + * changing an object's prototype after creation is strongly discouraged in todays Javascript engines. */ - public setFullYear(year: number, month: number = undefined, date: number = undefined): number + public get __proto__(): Object; /** - * @see ES5, 15.9.5.41 + * The initial value of Object.prototype is the standard built-in Object prototype object (15.2.4). + * + * Remark: Modeled as getter to emulate const and to allow for overriding. + * @see ES5, 15.2.3.1 */ - public setUTCFullYear(year: number, month: number = undefined, date: number = undefined): number + public static get prototype(): Object; +} + +export external public type ObjectConstructor = constructor{Object}; + +export external public class Function { + public apply(thisArg: any, argArray: any = ): any; + public call(thisArg: any, ...argArray: any): any; + public bind(thisArg: any, ...args: any): {function(... args: any): any} + @Override + public toString(): string; + public get length(): number; + public arguments: any; + public caller: Function; + public constructor(...args: string); + (...args: string): Function; /** - * This function returns a String value. The contents of the String are implementation-dependent, but are - * intended to represent the Date in a convenient, human-readable form in UTC. - * - * @see ES5, 15.9.5.42 + * The Function prototype object is itself a Function object (its [[Class]] is "Function") that, when invoked, accepts any arguments and returns undefined. */ - public toUTCString(): string + @Override public static get prototype(): Function; /** - * This function returns a String value represent the instance in time represented by this Date object. The format - * of the String is the Date Time string format defined in 15.9.1.15. All fields are present in the String. The time - * zone is always UTC, denoted by the suffix Z. If the time value of this object is not a finite Number a - * RangeError exception is thrown. - * - * @see ES5, 15.9.5.43 + * The value of the prototype property is used to initialize the [[Prototype]] internal property of a newly created object before the Function object is invoked as a constructor for that newly created object. This property has the attribute { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }. + * NOTE Function objects created using Function.prototype.bind do not have a prototype property. + * + * @see ES5 15.3.5.2 */ - public toISOString(): string + public get prototype(): Object; +} + +export external public type FunctionConstructor = constructor{Function}; + +export external public interface ~IArguments { + length: number; + callee: Function; +} + +export external public class String { + @Override + public toString(): string; + public charAt(pos: number): string; + public charCodeAt(index: number): number; + public concat(...strings: string): string; + public indexOf(searchString: string, position: number = ): number; + public lastIndexOf(searchString: string, position: number = ): number; + public localeCompare(that: string, locales: string = undefined, options: any+ = undefined): number; + public match(regexp: string | RegExp): RegExpMatchArray; + public replace(searchValue: union{RegExp, string}, replaceValue: union{string, Function}): string; + public search(regexp: string | RegExp): number; + public slice(start: number = , end: number = ): string; + public split(separator: string | RegExp, limit: number = ): Array; + public substring(start: number, end: number = ): string; + public toLowerCase(): string; + public toLocaleLowerCase(locales: string | Array = ): string; + public toUpperCase(): string; + public toLocaleUpperCase(locales: string | Array = ): string; + public trim(): string; + public get length(): number; + public substr(from: number, length: number = ): string; + @Override + public valueOf(): string; + public constructor(value: any = ); + (value: any = ): string; + public static fromCharCode(...codes: number): string; /** - * This function provides a String representation of a Date object for use by JSON.stringify. - * - * Note: the argument is ignored! - * - * @see ES5, 15.9.5.44 + * Returns a new Iterator object that iterates over the code points of a String value, returning each code point as + * a String value. */ - public toJSON(key: any = undefined): string + public [Symbol.iterator](): Iterator +} + +export external public type StringConstructor = constructor{String}; + +export external public class Boolean { + @Override + public valueOf(): boolean; + public constructor(value: any = ); + (value: any+ = ): boolean; +} +export external public type BooleanConstructor = constructor{Boolean}; + +export external public class Number { + @Override + public toString(radix: number = ): string; + public toFixed(fractionDigits: number = ): string; + public toExponential(fractionDigits: number = ): string; + public toPrecision(precision: number = ): string; + @Override + public valueOf(): number; + @Override + public toLocaleString(locales: string | Array = , options: Object = ): string; + public constructor(value: any = ); + (value: any = ): number; + public static get MAX_VALUE(): number; + public static get MIN_VALUE(): number; + public static get NaN(): number; + public static get NEGATIVE_INFINITY(): number; + public static get POSITIVE_INFINITY(): number; +} - // Additional properties of prototype - // http://en.wikipedia.org/wiki/Comparison_of_layout_engines_%28ECMAScript%29#Date_object - // public getYear(): number - // public setYear(value: number): void - // public toGMTString(): string +export external public type NumberConstructor = constructor{Number}; +export external public interface ~ImportMeta {} +export external public interface ~ImportCallOptions { + assert?: ImportAssertions; } -/** - * A RegExp object contains a regular expression and the associated flags. - * - *

API description is copied from - * ECMAScript Language Specification / ISO/IEC. Geneva, Switzerland, June 2011 (ECMA-262, 5.1 Edition). - * International Standard. [URL] - *
Copyright (C) 2011 Ecma International - *
(see license documents (about/license) for complete copyright notice) - * - * @see ES5, 15.10 RegExp (Regular Expression) Objects, page 180 (PDF: 192) [ECMA5] - */ -export external public class RegExp extends Object { +export external public interface ~ImportAssertions {} + +export external public class Math { + public static get E(): number; + public static get LN10(): number; + public static get LN2(): number; + public static get LOG2E(): number; + public static get LOG10E(): number; + public static get PI(): number; + public static get SQRT1_2(): number; + public static get SQRT2(): number; + public static abs(x: number): number; + public static acos(x: number): number; + public static asin(x: number): number; + public static atan(x: number): number; + public static atan2(y: number, x: number): number; + public static ceil(x: number): number; + public static cos(x: number): number; + public static exp(x: number): number; + public static floor(x: number): number; + public static log(x: number): number; + public static max(...values: number): number; + public static min(...values: number): number; + public static pow(x: number, y: number): number; + public static random(): number; + public static round(x: number): number; + public static sin(x: number): number; + public static sqrt(x: number): number; + public static tan(x: number): number; +} + +export external public class Date { + @Override + public toString(): string; + public toDateString(): string; + public toTimeString(): string; + @Override + public toLocaleString(...args: any+): any+; // overloading not supported + public toLocaleDateString(...args: any+): any+; // overloading not supported + public toLocaleTimeString(...args: any+): any+; // overloading not supported + @Override + public valueOf(): number; + public getTime(): number; + public getFullYear(): number; + public getUTCFullYear(): number; + public getMonth(): number; + public getUTCMonth(): number; + public getDate(): number; + public getUTCDate(): number; + public getDay(): number; + public getUTCDay(): number; + public getHours(): number; + public getUTCHours(): number; + public getMinutes(): number; + public getUTCMinutes(): number; + public getSeconds(): number; + public getUTCSeconds(): number; + public getMilliseconds(): number; + public getUTCMilliseconds(): number; + public getTimezoneOffset(): number; + public setTime(time: number): number; + public setMilliseconds(ms: number): number; + public setUTCMilliseconds(ms: number): number; + public setSeconds(sec: number, ms: number = ): number; + public setUTCSeconds(sec: number, ms: number = ): number; + public setMinutes(min: number, sec: number = , ms: number = ): number; + public setUTCMinutes(min: number, sec: number = , ms: number = ): number; + public setHours(hours: number, min: number = , sec: number = , ms: number = ): number; + public setUTCHours(hours: number, min: number = , sec: number = , ms: number = ): number; + public setDate(date: number): number; + public setUTCDate(date: number): number; + public setMonth(month: number, date: number = ): number; + public setUTCMonth(month: number, date: number = ): number; + public setFullYear(year: number, month: number = , date: number = ): number; + public setUTCFullYear(year: number, month: number = , date: number = ): number; + public toUTCString(): string; + public toISOString(): string; + public toJSON(key: any = ): string; + public constructor(numberOrStringOrYear: union{string, number} = undefined, month: number = undefined, date: number = undefined, hours: number = undefined, minutes: number = undefined, seconds: number = undefined, ms: number = undefined); + (): string; + public static parse(s: string): number; + public static UTC(year: number, month: number, date: number = , hours: number = , minutes: number = , seconds: number = , ms: number = ): number; + public static now(): number; +} +export external public type DateConstructor = constructor{Date}; +export external public class ~RegExpMatchArray extends Array { + public index?: number; + public input?: string; +} - // in TypeScript it is provided from $1 until $9, in JetBrains WebStorm it is $1 until $5, ES specification says $1 until $99 - /** - * Returns match at index 1 - */ +export external public class ~RegExpExecArray extends Array { + public index: number; + public input: string; +} + +export external public class RegExp { + public exec(string: string): RegExpExecArray; + public test(string: string): boolean; + public get source(): string; + public get global(): boolean; + public get ignoreCase(): boolean; + public get multiline(): boolean; + public lastIndex: number; + public compile(pattern: string, flags: string = ): this; + public constructor(pattern: string = undefined, flags: string = undefined); + (...args: any+): any+; // overloading not supported public static $1: string; - /** - * Returns match at index 2 - * - */ public static $2: string; - /** - * Returns match at index 3 - */ public static $3: string; - /** - * Returns match at index 4 - */ public static $4: string; - /** - * Returns match at index 5 - */ public static $5: string; - /** - * Returns match at index 6 - */ public static $6: string; - /** - * Returns match at index 7 - */ public static $7: string; - /** - * Returns match at index 8 - */ public static $8: string; - /** - * Returns match at index 9 - */ public static $9: string; + public static input: string; + public static $_: string; + public static lastMatch: string; + public static "$&": string; + public static lastParen: string; + public static "$+": string; + public static leftContext: string; + public static "$`": string; + public static rightContext: string; + public static "$'": string; +} - /** - * Regular expression pattern and flags like 'g', 'i', 'm' (resp. a combination of them) - * - * @see ES5, 15.10.6.1 - */ - public constructor(pattern: string = undefined, flags: string = undefined) - /** - * Performs a regular expression match of string against the regular expression and returns an Array object - * containing the results of the match, or null if string did not match. - * - * @see ES5, 15.10.6.2 - */ - // in TypeScript return value is RegExpExecArray, in JetBrains WebStorm it is Array|{index : number input : string} -// TODO use the following after fixing IDEBUG-273: -// public ~Array with {index: number; input: string;} exec(str: string = undefined) - public exec(str: string = undefined): ~Array with { index: number; input: string; groups?: any+; } +export external public type RegExpConstructor = constructor{RegExp}; - /** - * Executes exec with given str and returns true, if matched, false otherwise. - * - * @see ES5, 15.10.6.3 - */ - public test(str: string = undefined): boolean - /** - * Return the String value formed by concatenating the Strings "/", the String value of the source property of - * this RegExp object, and "/"; plus "g" if the global property is true, "i" if the ignoreCase property is true, - * and "m" if the multiline property is true. - * - * @see ES5, 15.10.6.4 - */ - @Override public toString(): string +export external public class Error { + public name: string; + public message: string; + public stack?: string; + public constructor(message: string = ); + (message: string = ): Error; +} - /** - * The value of the source property is a String in the form of a Pattern representing the current regular - * expression. - * - * @see ES5, 15.10.7.1 - */ - public source: string - /** - * The value of the global property is a Boolean value indicating whether the flags contained the character "g". - * - * @see ES5, 15.10.7.2 - */ - public get global(): boolean - /** - * The value of the ignoreCase property is a Boolean value indicating whether the flags contained the character "i". - * - * @see ES5, 15.10.7.3 - */ - public get ignoreCase(): boolean - /** - * The value of the multiline property is a Boolean value indicating whether the flags contained the character "m". - * - * @see ES5, 15.10.7.4 - */ - public multiline: boolean - /** - * The value of the lastIndex property specifies the String position at which to start the next match. It is - * coerced to an integer when used (see 15.10.6.2). - * - * @see ES5, 15.10.7.5 - */ - public lastIndex: number +export external public type ErrorConstructor = constructor{Error}; +export external public class EvalError extends Error { + public constructor(message: string = ); + (message: string = ): EvalError; } -// TODO: to be used as return parameter of RegExp.exec(str: string = undefined) ??? -// project object RegExpExecArray extends Array { -// public input: string -// } +export external public type EvalErrorConstructor = constructor{EvalError}; -/** - * Instances of Error objects are thrown as exceptions when runtime errors occur. The Error objects may also - * serve as base objects for user-defined exception classes. - * - *

The function call Error(...) is same to object creation new Error(...). - * - *

API description is copied from - * ECMAScript Language Specification / ISO/IEC. Geneva, Switzerland, June 2011 (ECMA-262, 5.1 Edition). - * International Standard. [URL] - *
Copyright (C) 2011 Ecma International - *
(see license documents (about/license) for complete copyright notice) - * - * @see ES 5, 15.11 Error Objects, page 197 (PDF: 209) [ECMA5] - */ -export external public class Error extends Object { +export external public class RangeError extends Error { + public constructor(message: string = ); + (message: string = ): RangeError; +} - /** - * @see ES 5, 15.11.4.1 - */ - public constructor(message: string = undefined) +export external public type RangeErrorConstructor = constructor{RangeError}; +export external public class ReferenceError extends Error { + public constructor(message: string = ); + (message: string = ): ReferenceError; +} + +export external public type ReferenceErrorConstructor = constructor{ReferenceError}; + +export external public class SyntaxError extends Error { + public constructor(message: string = ); + (message: string = ): SyntaxError; +} + +export external public type SyntaxErrorConstructor = constructor{SyntaxError}; + +export external public class TypeError extends Error { + public constructor(message: string = ); + (message: string = ): TypeError; +} + +export external public type TypeErrorConstructor = constructor{TypeError}; + +export external public class URIError extends Error { + public constructor(message: string = ); + (message: string = ): URIError; +} + +export external public type URIErrorConstructor = constructor{URIError}; + +export external public class JSON { + public static parse(text: string, reviver: {@This(any) function(key: string, value: any): any} = ): any; + public static stringify(value: any, replacer: union{Array, {function(key: string, value: any) : any} } = undefined, space: union{number , string} = undefined): string; +} + +export external public interface ~ConcatArray { + get length(): number; + join(separator: string = ): string; + slice(start: number = , end: number = ): Array; +} + +export external public class Array { + public length: number; + @Override + public toString(): string; + @Override + public toLocaleString(): string; + public pop(): T; + public push(...items: T): number; + public concat(...items: union {T, Array}): Array; + public join(separator: string = ): string; + public reverse(): Array; + public shift(): T; + public slice(start: number = , end: number = ): Array; + public sort(compareFn: (a: T, b: T)=>number = ): this; + public splice(start: number = undefined, deleteCount: number = undefined, ...items: T): Array; + public unshift(...items: T): number; + public indexOf(searchElement: any, fromIndex: number = ): number; + public lastIndexOf(searchElement: any, fromIndex: number = ): number; + public every(callback: {function(value: T, index: number, traversedObject: Array)}, thisObject: ThisT = undefined): boolean; + public some(predicate: (value: T, index: number, array: Array)=>any+, thisArg: any = ): boolean; + public forEach(callbackfn: (value: T, index: number, array: Array)=>void, thisArg: any = ): void; + public map(callback: {function(value: T, index: number, traversedObject: Array) : U}, thisObject: ThisT = undefined): Array; + public filter(callback: {function(value: T, index: number, traversedObject: Array) : boolean}, thisObject: ThisT = undefined): Array; + public reduce(callback: {function(previousValue: MemoT, currentValue: T, index: number, traversedObject: Array) : MemoT}, initialValue: MemoT = undefined): MemoT; + public reduceRight(callback: {function(previousValue: MemoT, currentValue: T, index: number, traversedObject: Array) : MemoT}, initialValue: MemoT = undefined): MemoT; + public constructor(first: union{number, T} = undefined, ...items: T); // TODO: signature is type unsafe, allows to create arrays with elements of wrong type, new Array(5, 'x', 'y'), but cannot write constructor(items : union {number, T... items} = undefined) + (...args: any+): any+; // overloading not supported + public static isArray(arg: any): boolean; + public [Symbol.iterator](): Iterator; /** - * The id of this error type, the initial value is "Error". - * - * @see ES 5, 15.11.4.2 - */ - public name?: string /* = "Error";*/ - /** - * The explaining error message, the initial value is the empty string. + * The initial value of Array.prototype is the Array prototype object (15.4.4). * - * @see ES 5, 15.11.4.3 + * @see ES5 15.4.3.1 */ - public message?: string /* = "";*/ + @Override public static get prototype(): Array +} - /** - * @see ES5, 15.11.4.4 - */ - @Override public toString(): string +export external public type ArrayConstructor = constructor{Array}; + +export external public interface ~TypedPropertyDescriptor { + enumerable?: boolean; + configurable?: boolean; + writable?: boolean; + value?: T; + get?: ()=>T; + set?: (value: T)=>void; } -/** - * This exception is not currently used within this specification. This object remains for compatibility with previous - * editions of this specification. - * - *

API description is copied from - * ECMAScript Language Specification / ISO/IEC. Geneva, Switzerland, June 2011 (ECMA-262, 5.1 Edition). - * International Standard. [URL] - *
Copyright (C) 2011 Ecma International - *
(see license documents (about/license) for complete copyright notice) - * - * @see ES5, 15.11.6.1 EvalError - */ -export external public class EvalError extends Error { } +export external public interface ~PromiseLike { + then(onfulfilled: ((value: T)=>(TResult1 | PromiseLike)) = , onrejected: ((reason: any)=>(TResult2 | PromiseLike)) = ): PromiseLike; +} -/** - * Indicates a numeric value has exceeded the allowable range. - * - *

API description is copied from - * ECMAScript Language Specification / ISO/IEC. Geneva, Switzerland, June 2011 (ECMA-262, 5.1 Edition). - * International Standard. [URL] - *
Copyright (C) 2011 Ecma International - *
(see license documents (about/license) for complete copyright notice) - * - * @see ES5, 15.11.6.2 RangeError - */ -export external public class RangeError extends Error { } +export external public interface ~ArrayLike { + get length(): number; +} -/** - * Indicate that an invalid reference value has been detected. - * - *

API description is copied from - * ECMAScript Language Specification / ISO/IEC. Geneva, Switzerland, June 2011 (ECMA-262, 5.1 Edition). - * International Standard. [URL] - *
Copyright (C) 2011 Ecma International - *
(see license documents (about/license) for complete copyright notice) - * - * @see ES5, 15.11.6.3 ReferenceError - */ -export external public class ReferenceError extends Error { } +export external public interface ~ThisType {} -/** - * Indicates that a parsing error has occurred. - * - *

API description is copied from - * ECMAScript Language Specification / ISO/IEC. Geneva, Switzerland, June 2011 (ECMA-262, 5.1 Edition). - * International Standard. [URL] - *
Copyright (C) 2011 Ecma International - *
(see license documents (about/license) for complete copyright notice) - * - * @see ES5, 15.11.6.4 SyntaxError - */ -export external public class SyntaxError extends Error { } +export external public class ArrayBuffer { + public get byteLength(): number; + public slice(begin: number, end: number = ): ArrayBuffer; + public constructor(byteLength: number); + public static isView(arg: any): boolean; +} -/** - * Indicates the actual type of an operand is different than the expected type. - * - *

API description is copied from - * ECMAScript Language Specification / ISO/IEC. Geneva, Switzerland, June 2011 (ECMA-262, 5.1 Edition). - * International Standard. [URL] - *
Copyright (C) 2011 Ecma International - *
(see license documents (about/license) for complete copyright notice) - * - * @see ES5, 15.11.6.5 TypeError - */ -export external public class TypeError extends Error { } +export external public type ArrayBufferConstructor = constructor{ArrayBuffer}; -/** - * Indicates that one of the global URI handling functions was used in a way that is incompatible with its - * definition. - * - *

API description is copied from - * ECMAScript Language Specification / ISO/IEC. Geneva, Switzerland, June 2011 (ECMA-262, 5.1 Edition). - * International Standard. [URL] - *
Copyright (C) 2011 Ecma International - *
(see license documents (about/license) for complete copyright notice) - * - * @see ES5, 15.11.6.6 URIError - */ -export external public class URIError extends Error { } +export external public interface ~ArrayBufferTypes { + ArrayBuffer: ArrayBuffer; +} -/** -*

API description is copied from - * ECMAScript Language Specification / ISO/IEC. Geneva, Switzerland, June 2011 (ECMA-262, 5.1 Edition). - * International Standard. [URL] - *
Copyright (C) 2011 Ecma International - *
(see license documents (about/license) for complete copyright notice) - * - * @see ES5, 15.12 The JSON Object, page 201 (PDF: 213) [ECMA5] - */ -export external public class JSON extends Object { - - // since ECMAScript 5 - - // syntax in TypeScript: - // var json: JSON = null; - // var value : any = null - // var reviver1: (key : string, value : any) => any = null - // var replacer: any[] = null - // var space1 : any - // json.stringify(value) - // json.stringify(value, reviver1) - // json.stringify(value, replacer) - // json.stringify(value, reviver1, space1) - // json.stringify(value, replacer, space1) +export external public type ArrayBufferLike = any+; + +export external public class DataView { + public get buffer(): ArrayBuffer; + public get byteLength(): number; + public get byteOffset(): number; + public getFloat32(byteOffset: number, littleEndian: boolean = ): number; + public getFloat64(byteOffset: number, littleEndian: boolean = ): number; + public getInt8(byteOffset: number): number; + public getInt16(byteOffset: number, littleEndian: boolean = ): number; + public getInt32(byteOffset: number, littleEndian: boolean = ): number; + public getUint8(byteOffset: number): number; + public getUint16(byteOffset: number, littleEndian: boolean = ): number; + public getUint32(byteOffset: number, littleEndian: boolean = ): number; + public setFloat32(byteOffset: number, value: number, littleEndian: boolean = ): void; + public setFloat64(byteOffset: number, value: number, littleEndian: boolean = ): void; + public setInt8(byteOffset: number, value: number): void; + public setInt16(byteOffset: number, value: number, littleEndian: boolean = ): void; + public setInt32(byteOffset: number, value: number, littleEndian: boolean = ): void; + public setUint8(byteOffset: number, value: number): void; + public setUint16(byteOffset: number, value: number, littleEndian: boolean = ): void; + public setUint32(byteOffset: number, value: number, littleEndian: boolean = ): void; + public constructor(buffer: ArrayBufferLike, byteOffset: number = , byteLength: number = ); +} - /** - * The parse function parses a JSON text (a JSON-formatted String) and produces an ECMAScript value. The - * JSON format is a restricted form of ECMAScript literal. JSON objects are realized as ECMAScript objects. - * JSON arrays are realized as ECMAScript arrays. JSON strings, numbers, booleans, and null are realized as - * ECMAScript Strings, Numbers, Booleans, and null. JSON uses a more limited set of white space characters - * than WhiteSpace and allows Unicode code points U+2028 and U+2029 to directly appear in JSONString literals - * without using an escape sequence. The process of parsing is similar to 11.1.4 and 11.1.5 as constrained by - * the JSON grammar. - *

The optional reviver parameter is a function that takes two parameters, (key and value). It can filter and - * transform the results. It is called with each of the key/value pairs produced by the parse, and its return value is - * used instead of the original value. If it returns what it received, the structure is not modified. If it returns - * undefined then the property is deleted from the result. - * - * @see 15.12.2 - */ - public static parse(jsonString: string, reviver: {function(key: any, value: any) : any} = undefined): any +export external public type DataViewConstructor = constructor{DataView}; + +export external public class Int8Array { + public get BYTES_PER_ELEMENT(): number; + public get buffer(): ArrayBufferLike; + public get byteLength(): number; + public get byteOffset(): number; + public copyWithin(target: number, start: number, end: number = ): this; + public every(predicate: (value: number, index: number, array: Int8Array)=>any+, thisArg: any = ): boolean; + public fill(value: number, start: number = , end: number = ): this; + public filter(predicate: (value: number, index: number, array: Int8Array)=>any, thisArg: any = ): Int8Array; + public find(predicate: (value: number, index: number, obj: Int8Array)=>boolean, thisArg: any = ): number; + public findIndex(predicate: (value: number, index: number, obj: Int8Array)=>boolean, thisArg: any = ): number; + public forEach(callbackfn: (value: number, index: number, array: Int8Array)=>void, thisArg: any = ): void; + public indexOf(searchElement: number, fromIndex: number = ): number; + public join(separator: string = ): string; + public lastIndexOf(searchElement: number, fromIndex: number = ): number; + public get length(): number; + public map(callbackfn: (value: number, index: number, array: Int8Array)=>number, thisArg: any = ): Int8Array; + public reduce(...args: any+): any+; // overloading not supported + public reduceRight(...args: any+): any+; // overloading not supported + public reverse(): Int8Array; + public set(array: ArrayLike, offset: number = ): void; + public slice(start: number = , end: number = ): Int8Array; + public some(predicate: (value: number, index: number, array: Int8Array)=>any+, thisArg: any = ): boolean; + public sort(compareFn: (a: number, b: number)=>number = ): this; + public subarray(begin: number = , end: number = ): Int8Array; + @Override + public toLocaleString(): string; + @Override + public toString(): string; + @Override + public valueOf(): Int8Array; + public constructor(...args: any+); // overloading not supported + public static get BYTES_PER_ELEMENT(): number; + public static of(...items: number): Int8Array; + public static from(...args: any+): any+; // overloading not supported +} - // https://developer.mozilla.org/en-US/docs/Using_native_JSON#The_replacer_parameter - /** - * The stringify function returns a String in JSON format representing an ECMAScript value. It can take three - * parameters. The first parameter is required. The value parameter is an ECMAScript value, which is usually an - * object or array, although it can also be a String, Boolean, Number or null. The optional replacer parameter is - * either a function that alters the way objects and arrays are stringified, or an array of Strings and Numbers that - * acts as a white list for selecting the object properties that will be stringified. The optional space parameter is a - * String or Number that allows the result to have white space injected into it to improve human readability. - * - * @see 15.12.3 - */ - public static stringify(value: any, replacer: union{Array, {function(key: string, value: any) : any} } = undefined, space: union{number , string} = undefined): string +export external public type Int8ArrayConstructor = constructor{Int8Array}; + +export external public class Uint8Array { + public get BYTES_PER_ELEMENT(): number; + public get buffer(): ArrayBufferLike; + public get byteLength(): number; + public get byteOffset(): number; + public copyWithin(target: number, start: number, end: number = ): this; + public every(predicate: (value: number, index: number, array: Uint8Array)=>any+, thisArg: any = ): boolean; + public fill(value: number, start: number = , end: number = ): this; + public filter(predicate: (value: number, index: number, array: Uint8Array)=>any, thisArg: any = ): Uint8Array; + public find(predicate: (value: number, index: number, obj: Uint8Array)=>boolean, thisArg: any = ): number; + public findIndex(predicate: (value: number, index: number, obj: Uint8Array)=>boolean, thisArg: any = ): number; + public forEach(callbackfn: (value: number, index: number, array: Uint8Array)=>void, thisArg: any = ): void; + public indexOf(searchElement: number, fromIndex: number = ): number; + public join(separator: string = ): string; + public lastIndexOf(searchElement: number, fromIndex: number = ): number; + public get length(): number; + public map(callbackfn: (value: number, index: number, array: Uint8Array)=>number, thisArg: any = ): Uint8Array; + public reduce(...args: any+): any+; // overloading not supported + public reduceRight(...args: any+): any+; // overloading not supported + public reverse(): Uint8Array; + public set(array: ArrayLike, offset: number = ): void; + public slice(start: number = , end: number = ): Uint8Array; + public some(predicate: (value: number, index: number, array: Uint8Array)=>any+, thisArg: any = ): boolean; + public sort(compareFn: (a: number, b: number)=>number = ): this; + public subarray(begin: number = , end: number = ): Uint8Array; + @Override + public toLocaleString(): string; + @Override + public toString(): string; + @Override + public valueOf(): Uint8Array; + public constructor(...args: any+); // overloading not supported + public static get BYTES_PER_ELEMENT(): number; + public static of(...items: number): Uint8Array; + public static from(...args: any+): any+; // overloading not supported +} + +export external public type Uint8ArrayConstructor = constructor{Uint8Array}; + +export external public class Uint8ClampedArray { + public get BYTES_PER_ELEMENT(): number; + public get buffer(): ArrayBufferLike; + public get byteLength(): number; + public get byteOffset(): number; + public copyWithin(target: number, start: number, end: number = ): this; + public every(predicate: (value: number, index: number, array: Uint8ClampedArray)=>any+, thisArg: any = ): boolean; + public fill(value: number, start: number = , end: number = ): this; + public filter(predicate: (value: number, index: number, array: Uint8ClampedArray)=>any, thisArg: any = ): Uint8ClampedArray; + public find(predicate: (value: number, index: number, obj: Uint8ClampedArray)=>boolean, thisArg: any = ): number; + public findIndex(predicate: (value: number, index: number, obj: Uint8ClampedArray)=>boolean, thisArg: any = ): number; + public forEach(callbackfn: (value: number, index: number, array: Uint8ClampedArray)=>void, thisArg: any = ): void; + public indexOf(searchElement: number, fromIndex: number = ): number; + public join(separator: string = ): string; + public lastIndexOf(searchElement: number, fromIndex: number = ): number; + public get length(): number; + public map(callbackfn: (value: number, index: number, array: Uint8ClampedArray)=>number, thisArg: any = ): Uint8ClampedArray; + public reduce(...args: any+): any+; // overloading not supported + public reduceRight(...args: any+): any+; // overloading not supported + public reverse(): Uint8ClampedArray; + public set(array: ArrayLike, offset: number = ): void; + public slice(start: number = , end: number = ): Uint8ClampedArray; + public some(predicate: (value: number, index: number, array: Uint8ClampedArray)=>any+, thisArg: any = ): boolean; + public sort(compareFn: (a: number, b: number)=>number = ): this; + public subarray(begin: number = , end: number = ): Uint8ClampedArray; + @Override + public toLocaleString(): string; + @Override + public toString(): string; + @Override + public valueOf(): Uint8ClampedArray; + public constructor(...args: any+); // overloading not supported + public static get BYTES_PER_ELEMENT(): number; + public static of(...items: number): Uint8ClampedArray; + public static from(...args: any+): any+; // overloading not supported +} + +export external public type Uint8ClampedArrayConstructor = constructor{Uint8ClampedArray}; + +export external public class Int16Array { + public get BYTES_PER_ELEMENT(): number; + public get buffer(): ArrayBufferLike; + public get byteLength(): number; + public get byteOffset(): number; + public copyWithin(target: number, start: number, end: number = ): this; + public every(predicate: (value: number, index: number, array: Int16Array)=>any+, thisArg: any = ): boolean; + public fill(value: number, start: number = , end: number = ): this; + public filter(predicate: (value: number, index: number, array: Int16Array)=>any, thisArg: any = ): Int16Array; + public find(predicate: (value: number, index: number, obj: Int16Array)=>boolean, thisArg: any = ): number; + public findIndex(predicate: (value: number, index: number, obj: Int16Array)=>boolean, thisArg: any = ): number; + public forEach(callbackfn: (value: number, index: number, array: Int16Array)=>void, thisArg: any = ): void; + public indexOf(searchElement: number, fromIndex: number = ): number; + public join(separator: string = ): string; + public lastIndexOf(searchElement: number, fromIndex: number = ): number; + public get length(): number; + public map(callbackfn: (value: number, index: number, array: Int16Array)=>number, thisArg: any = ): Int16Array; + public reduce(...args: any+): any+; // overloading not supported + public reduceRight(...args: any+): any+; // overloading not supported + public reverse(): Int16Array; + public set(array: ArrayLike, offset: number = ): void; + public slice(start: number = , end: number = ): Int16Array; + public some(predicate: (value: number, index: number, array: Int16Array)=>any+, thisArg: any = ): boolean; + public sort(compareFn: (a: number, b: number)=>number = ): this; + public subarray(begin: number = , end: number = ): Int16Array; + @Override + public toLocaleString(): string; + @Override + public toString(): string; + @Override + public valueOf(): Int16Array; + public constructor(...args: any+); // overloading not supported + public static get BYTES_PER_ELEMENT(): number; + public static of(...items: number): Int16Array; + public static from(...args: any+): any+; // overloading not supported +} + +export external public type Int16ArrayConstructor = constructor{Int16Array}; + +export external public class Uint16Array { + public get BYTES_PER_ELEMENT(): number; + public get buffer(): ArrayBufferLike; + public get byteLength(): number; + public get byteOffset(): number; + public copyWithin(target: number, start: number, end: number = ): this; + public every(predicate: (value: number, index: number, array: Uint16Array)=>any+, thisArg: any = ): boolean; + public fill(value: number, start: number = , end: number = ): this; + public filter(predicate: (value: number, index: number, array: Uint16Array)=>any, thisArg: any = ): Uint16Array; + public find(predicate: (value: number, index: number, obj: Uint16Array)=>boolean, thisArg: any = ): number; + public findIndex(predicate: (value: number, index: number, obj: Uint16Array)=>boolean, thisArg: any = ): number; + public forEach(callbackfn: (value: number, index: number, array: Uint16Array)=>void, thisArg: any = ): void; + public indexOf(searchElement: number, fromIndex: number = ): number; + public join(separator: string = ): string; + public lastIndexOf(searchElement: number, fromIndex: number = ): number; + public get length(): number; + public map(callbackfn: (value: number, index: number, array: Uint16Array)=>number, thisArg: any = ): Uint16Array; + public reduce(...args: any+): any+; // overloading not supported + public reduceRight(...args: any+): any+; // overloading not supported + public reverse(): Uint16Array; + public set(array: ArrayLike, offset: number = ): void; + public slice(start: number = , end: number = ): Uint16Array; + public some(predicate: (value: number, index: number, array: Uint16Array)=>any+, thisArg: any = ): boolean; + public sort(compareFn: (a: number, b: number)=>number = ): this; + public subarray(begin: number = , end: number = ): Uint16Array; + @Override + public toLocaleString(): string; + @Override + public toString(): string; + @Override + public valueOf(): Uint16Array; + public constructor(...args: any+); // overloading not supported + public static get BYTES_PER_ELEMENT(): number; + public static of(...items: number): Uint16Array; + public static from(...args: any+): any+; // overloading not supported +} + +export external public type Uint16ArrayConstructor = constructor{Uint16Array}; + +export external public class Int32Array { + public get BYTES_PER_ELEMENT(): number; + public get buffer(): ArrayBufferLike; + public get byteLength(): number; + public get byteOffset(): number; + public copyWithin(target: number, start: number, end: number = ): this; + public every(predicate: (value: number, index: number, array: Int32Array)=>any+, thisArg: any = ): boolean; + public fill(value: number, start: number = , end: number = ): this; + public filter(predicate: (value: number, index: number, array: Int32Array)=>any, thisArg: any = ): Int32Array; + public find(predicate: (value: number, index: number, obj: Int32Array)=>boolean, thisArg: any = ): number; + public findIndex(predicate: (value: number, index: number, obj: Int32Array)=>boolean, thisArg: any = ): number; + public forEach(callbackfn: (value: number, index: number, array: Int32Array)=>void, thisArg: any = ): void; + public indexOf(searchElement: number, fromIndex: number = ): number; + public join(separator: string = ): string; + public lastIndexOf(searchElement: number, fromIndex: number = ): number; + public get length(): number; + public map(callbackfn: (value: number, index: number, array: Int32Array)=>number, thisArg: any = ): Int32Array; + public reduce(...args: any+): any+; // overloading not supported + public reduceRight(...args: any+): any+; // overloading not supported + public reverse(): Int32Array; + public set(array: ArrayLike, offset: number = ): void; + public slice(start: number = , end: number = ): Int32Array; + public some(predicate: (value: number, index: number, array: Int32Array)=>any+, thisArg: any = ): boolean; + public sort(compareFn: (a: number, b: number)=>number = ): this; + public subarray(begin: number = , end: number = ): Int32Array; + @Override + public toLocaleString(): string; + @Override + public toString(): string; + @Override + public valueOf(): Int32Array; + public constructor(...args: any+); // overloading not supported + public static get BYTES_PER_ELEMENT(): number; + public static of(...items: number): Int32Array; + public static from(...args: any+): any+; // overloading not supported +} + +export external public type Int32ArrayConstructor = constructor{Int32Array}; + +export external public class Uint32Array { + public get BYTES_PER_ELEMENT(): number; + public get buffer(): ArrayBufferLike; + public get byteLength(): number; + public get byteOffset(): number; + public copyWithin(target: number, start: number, end: number = ): this; + public every(predicate: (value: number, index: number, array: Uint32Array)=>any+, thisArg: any = ): boolean; + public fill(value: number, start: number = , end: number = ): this; + public filter(predicate: (value: number, index: number, array: Uint32Array)=>any, thisArg: any = ): Uint32Array; + public find(predicate: (value: number, index: number, obj: Uint32Array)=>boolean, thisArg: any = ): number; + public findIndex(predicate: (value: number, index: number, obj: Uint32Array)=>boolean, thisArg: any = ): number; + public forEach(callbackfn: (value: number, index: number, array: Uint32Array)=>void, thisArg: any = ): void; + public indexOf(searchElement: number, fromIndex: number = ): number; + public join(separator: string = ): string; + public lastIndexOf(searchElement: number, fromIndex: number = ): number; + public get length(): number; + public map(callbackfn: (value: number, index: number, array: Uint32Array)=>number, thisArg: any = ): Uint32Array; + public reduce(...args: any+): any+; // overloading not supported + public reduceRight(...args: any+): any+; // overloading not supported + public reverse(): Uint32Array; + public set(array: ArrayLike, offset: number = ): void; + public slice(start: number = , end: number = ): Uint32Array; + public some(predicate: (value: number, index: number, array: Uint32Array)=>any+, thisArg: any = ): boolean; + public sort(compareFn: (a: number, b: number)=>number = ): this; + public subarray(begin: number = , end: number = ): Uint32Array; + @Override + public toLocaleString(): string; + @Override + public toString(): string; + @Override + public valueOf(): Uint32Array; + public constructor(...args: any+); // overloading not supported + public static get BYTES_PER_ELEMENT(): number; + public static of(...items: number): Uint32Array; + public static from(...args: any+): any+; // overloading not supported +} +export external public type Uint32ArrayConstructor = constructor{Uint32Array}; + +export external public class Float32Array { + public get BYTES_PER_ELEMENT(): number; + public get buffer(): ArrayBufferLike; + public get byteLength(): number; + public get byteOffset(): number; + public copyWithin(target: number, start: number, end: number = ): this; + public every(predicate: (value: number, index: number, array: Float32Array)=>any+, thisArg: any = ): boolean; + public fill(value: number, start: number = , end: number = ): this; + public filter(predicate: (value: number, index: number, array: Float32Array)=>any, thisArg: any = ): Float32Array; + public find(predicate: (value: number, index: number, obj: Float32Array)=>boolean, thisArg: any = ): number; + public findIndex(predicate: (value: number, index: number, obj: Float32Array)=>boolean, thisArg: any = ): number; + public forEach(callbackfn: (value: number, index: number, array: Float32Array)=>void, thisArg: any = ): void; + public indexOf(searchElement: number, fromIndex: number = ): number; + public join(separator: string = ): string; + public lastIndexOf(searchElement: number, fromIndex: number = ): number; + public get length(): number; + public map(callbackfn: (value: number, index: number, array: Float32Array)=>number, thisArg: any = ): Float32Array; + public reduce(...args: any+): any+; // overloading not supported + public reduceRight(...args: any+): any+; // overloading not supported + public reverse(): Float32Array; + public set(array: ArrayLike, offset: number = ): void; + public slice(start: number = , end: number = ): Float32Array; + public some(predicate: (value: number, index: number, array: Float32Array)=>any+, thisArg: any = ): boolean; + public sort(compareFn: (a: number, b: number)=>number = ): this; + public subarray(begin: number = , end: number = ): Float32Array; + @Override + public toLocaleString(): string; + @Override + public toString(): string; + @Override + public valueOf(): Float32Array; + public constructor(...args: any+); // overloading not supported + public static get BYTES_PER_ELEMENT(): number; + public static of(...items: number): Float32Array; + public static from(...args: any+): any+; // overloading not supported +} +export external public type Float32ArrayConstructor = constructor{Float32Array}; + +export external public class Float64Array { + public get BYTES_PER_ELEMENT(): number; + public get buffer(): ArrayBufferLike; + public get byteLength(): number; + public get byteOffset(): number; + public copyWithin(target: number, start: number, end: number = ): this; + public every(predicate: (value: number, index: number, array: Float64Array)=>any+, thisArg: any = ): boolean; + public fill(value: number, start: number = , end: number = ): this; + public filter(predicate: (value: number, index: number, array: Float64Array)=>any, thisArg: any = ): Float64Array; + public find(predicate: (value: number, index: number, obj: Float64Array)=>boolean, thisArg: any = ): number; + public findIndex(predicate: (value: number, index: number, obj: Float64Array)=>boolean, thisArg: any = ): number; + public forEach(callbackfn: (value: number, index: number, array: Float64Array)=>void, thisArg: any = ): void; + public indexOf(searchElement: number, fromIndex: number = ): number; + public join(separator: string = ): string; + public lastIndexOf(searchElement: number, fromIndex: number = ): number; + public get length(): number; + public map(callbackfn: (value: number, index: number, array: Float64Array)=>number, thisArg: any = ): Float64Array; + public reduce(...args: any+): any+; // overloading not supported + public reduceRight(...args: any+): any+; // overloading not supported + public reverse(): Float64Array; + public set(array: ArrayLike, offset: number = ): void; + public slice(start: number = , end: number = ): Float64Array; + public some(predicate: (value: number, index: number, array: Float64Array)=>any+, thisArg: any = ): boolean; + public sort(compareFn: (a: number, b: number)=>number = ): this; + public subarray(begin: number = , end: number = ): Float64Array; + @Override + public toString(): string; + @Override + public valueOf(): Float64Array; + public constructor(...args: any+); // overloading not supported + public static get BYTES_PER_ELEMENT(): number; + public static of(...items: number): Float64Array; + public static from(...args: any+): any+; // overloading not supported } -// see also B.2 Additional Properties (page 232 resp. 244 in PDF) for properties that have been removed in ECMAScript 5 +export external public type Float64ArrayConstructor = constructor{Float64Array}; +export external public type ReadonlyArray = Array; /** - * Type of all implicit arguments-variables in function/method/function-expression bodies. - * The arguments are accessible through index-access in the order they are passed in at function call time. - * Cf. §10.6 Arguments Object, page 60 (PDF: 72) [ECMA5] + * See [ECMA6] Section 19.4. + * + * A symbol is a unique and immutable data type and may be used as an identifier for object properties. The symbol + * object is an implicit object wrapper for the symbol primitive data type. + * + * TODO in ES6 this is defined to be a property of the global object and a constructor function */ -export external public interface ~IArguments { +export external public class Symbol extends Object { + /** - * number of actually passed in arguments of a function/method call. may be modified. - * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments/length - * */ - public length: number; + * Creates a new, primitive symbol. + * + * @param description A description of the symbol which can be used for debugging but not to access the symbol itself. + */ + (description: string = undefined): symbol + /** - * @deprecated forbidden in strict mode of ES5. - * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments/callee + * This "well-known" symbol may be used to define the default iterator of an object. + * + * @see ES6, 19.4.2.4 */ - public callee: any; + public const iterator: symbol + + // well-known symbols moved here from file 'es2015.symbol.wellknown.d.ts' + public const hasInstance: symbol; + public const isConcatSpreadable: symbol; + public const match: symbol; + public const replace: symbol; + public const search: symbol; + public const species: symbol; + public const split: symbol; + public const toPrimitive: symbol; + public const toStringTag: symbol; + public const unscopables: symbol; + // well-known symbols moved here from file 'es2018.asynciterable.d.ts' + public const asyncIterator: symbol; + // well-known symbols moved here from file 'es2020.symbol.wellknown.d.ts' + public const matchAll: symbol; + /** - * @deprecated since ever - * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments/caller + * Returns the shared symbol with the given key from the Javascript engine's shared symbol registry. + * Creates a new symbol if not found. + * + * @see ES6, 19.4.2.1 */ - //public caller: any; -} + public static for(key: string): symbol + /** + * Returns the key for the given shared symbol if found in the Javascript engine's shared symbol registry. + * Otherwise 'undefined' is returned. + * + * @see ES6, 19.4.2.5 + */ + public static keyFor(sym: symbol): string +} /** * An iterator over a collection, defining a standard way to produce a sequence of values (either finite @@ -2115,3 +1118,23 @@ export external public class Promise extends Object { public static all(iterable: Iterable, T}>): Promise, any> public static race(iterable: Iterable, T}>): Promise } + +export external public type PromiseConstructor = constructor{Promise}; + + +export external public interface ~ArrayBufferView { + /** + * The ArrayBuffer instance referenced by the array. + */ + get buffer(): ArrayBufferLike; + + /** + * The length in bytes of the array. + */ + get byteLength(): number; + + /** + * The offset in bytes of the array. + */ + get byteOffset(): number; +} diff --git a/plugins/org.eclipse.n4js/src/org/eclipse/n4js/validation/utils/MemberCube.java b/plugins/org.eclipse.n4js/src/org/eclipse/n4js/validation/utils/MemberCube.java index d36daa84dd..6f441e04ca 100644 --- a/plugins/org.eclipse.n4js/src/org/eclipse/n4js/validation/utils/MemberCube.java +++ b/plugins/org.eclipse.n4js/src/org/eclipse/n4js/validation/utils/MemberCube.java @@ -16,6 +16,9 @@ import java.util.Map.Entry; import java.util.Set; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.resource.Resource; +import org.eclipse.n4js.resource.N4JSResource; import org.eclipse.n4js.ts.types.TClass; import org.eclipse.n4js.ts.types.TClassifier; import org.eclipse.n4js.ts.types.TMember; @@ -49,6 +52,7 @@ public MemberCube(TClassifier tClassifier, MemberCollector memberCollector) { private void addMembers(int source, List members) { for (TMember member : members) { + ensureResolution(member); NameStaticPair nsp = NameStaticPair.of(member); MemberMatrix memberMatrix = memberMatrixesByName.get(nsp); if (memberMatrix == null) { @@ -59,6 +63,24 @@ private void addMembers(int source, List members) { } } + /** + * TEMPORARY WORK-AROUND + * + * This is required to avoid exceptions when compiling n4js-libs. + * + * TODO GH-2235 find a better place to ensure resolution of polyfilled members + */ + private void ensureResolution(EObject obj) { + // ensure we do not use types from resources that are only partially resolved + Resource polyfillResource = obj.eResource(); + if (polyfillResource instanceof N4JSResource) { + // Note: the following call will be a no-op if + // 1) the resource was already post-processed, or + // 2) the resource was loaded from the index. + ((N4JSResource) polyfillResource).performPostProcessing(); + } + } + /** * @see java.util.Map#entrySet() */ diff --git a/plugins/org.eclipse.n4js/src/org/eclipse/n4js/validation/validators/N4JSTypeValidator.xtend b/plugins/org.eclipse.n4js/src/org/eclipse/n4js/validation/validators/N4JSTypeValidator.xtend index 8404a16f70..6a02a6ad9e 100644 --- a/plugins/org.eclipse.n4js/src/org/eclipse/n4js/validation/validators/N4JSTypeValidator.xtend +++ b/plugins/org.eclipse.n4js/src/org/eclipse/n4js/validation/validators/N4JSTypeValidator.xtend @@ -47,6 +47,7 @@ import org.eclipse.n4js.n4JS.TypeReferenceNode import org.eclipse.n4js.n4JS.UnaryExpression import org.eclipse.n4js.n4JS.UnaryOperator import org.eclipse.n4js.n4JS.VariableDeclaration +import org.eclipse.n4js.packagejson.projectDescription.ProjectType import org.eclipse.n4js.scoping.N4JSScopeProvider import org.eclipse.n4js.scoping.builtin.BuiltInTypeScope import org.eclipse.n4js.scoping.members.TypingStrategyFilter @@ -89,6 +90,7 @@ import org.eclipse.n4js.utils.N4JSLanguageUtils import org.eclipse.n4js.validation.AbstractN4JSDeclarativeValidator import org.eclipse.n4js.validation.IssueCodes import org.eclipse.n4js.validation.JavaScriptVariantHelper +import org.eclipse.n4js.workspace.WorkspaceAccess import org.eclipse.n4js.xtext.scoping.IEObjectDescriptionWithError import org.eclipse.xtext.EcoreUtil2 import org.eclipse.xtext.naming.QualifiedName @@ -122,6 +124,9 @@ class N4JSTypeValidator extends AbstractN4JSDeclarativeValidator { @Inject private JavaScriptVariantHelper jsVariantHelper; + @Inject + private WorkspaceAccess workspaceAccess; + /** * NEEDED * @@ -285,8 +290,21 @@ class N4JSTypeValidator extends AbstractN4JSDeclarativeValidator { val typeRef = tsh.resolveTypeAliasFlat(G, typeRefInAST); if (typeRef.declaredType === bits.symbolObjectType) { // we have a type reference to 'Symbol' - addIssue(IssueCodes.getMessageForBIT_SYMBOL_INVALID_USE, typeRefInAST, BIT_SYMBOL_INVALID_USE); + val isAllowed = isExtendsClauseInRuntimeLibrary(typeRefInAST); + if (!isAllowed) { + addIssue(IssueCodes.getMessageForBIT_SYMBOL_INVALID_USE, typeRefInAST, BIT_SYMBOL_INVALID_USE); + } + } + } + + def private boolean isExtendsClauseInRuntimeLibrary(TypeRef typeRefInAST) { + if (typeRefInAST.eContainer?.eContainmentFeature === N4JSPackage.Literals.N4_CLASS_DEFINITION__SUPER_CLASS_REF) { + val project = workspaceAccess.findProjectContaining(typeRefInAST); + if (project !== null && project.type === ProjectType.RUNTIME_LIBRARY) { + return true; + } } + return false; } /* diff --git a/releng/org.eclipse.n4js.libs.build/src/org/eclipse/n4js/libs/build/BuildN4jsLibs.java b/releng/org.eclipse.n4js.libs.build/src/org/eclipse/n4js/libs/build/BuildN4jsLibs.java index 2d7201810f..5fdc17079d 100644 --- a/releng/org.eclipse.n4js.libs.build/src/org/eclipse/n4js/libs/build/BuildN4jsLibs.java +++ b/releng/org.eclipse.n4js.libs.build/src/org/eclipse/n4js/libs/build/BuildN4jsLibs.java @@ -25,6 +25,7 @@ import org.eclipse.n4js.cli.N4jscMain; import org.eclipse.n4js.cli.helper.CliCompileResult; import org.eclipse.n4js.cli.helper.CliTools; +import org.eclipse.n4js.cli.helper.CliTools.CliException; import org.eclipse.n4js.utils.UtilN4; import org.eclipse.n4js.utils.io.FileDeleter; @@ -92,6 +93,7 @@ private static void removeNodeModulesFolders(File... foldersContainingProjectFol } private static void compile(Path n4jsLibsRootPath) { + CliCompileResult compileResult = new CliCompileResult(); try { CliTools cliTools = new CliTools(); cliTools.setInheritIO(true); @@ -99,10 +101,16 @@ private static void compile(Path n4jsLibsRootPath) { cliTools.yarnInstall(n4jsLibsRootPath); - CliCompileResult compileResult = new CliCompileResult(); cliTools.callN4jscInprocess(COMPILE(n4jsLibsRootPath.toFile()), false, compileResult); - } catch (Exception e) { + if (e instanceof CliException && compileResult.getErrs() > 0) { + // this happens when there are compile errors in the n4js-libs + // --> the below code would emit the entire output of n4jsc several times leading to excessive output + // (also, the compile errors were already reported by n4jsc to the console), so we exit early in this + // case: + throw new RuntimeException("errors while compiling n4js-libs"); + } + println("EXCEPTION while compiling n4js-libs:"); e.printStackTrace(); diff --git a/releng/utils/scripts/generate-built-in-types.sh b/releng/utils/scripts/generate-built-in-types.sh new file mode 100755 index 0000000000..b5f4387ba3 --- /dev/null +++ b/releng/utils/scripts/generate-built-in-types.sh @@ -0,0 +1,96 @@ +#!/bin/bash +# +# Copyright (c) 2021 NumberFour AG. +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v1.0 +# which accompanies this distribution, and is available at +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# NumberFour AG - Initial API and implementation +# +set -eo pipefail +# use the following for excessive logging: +#set -x + + +# The first parameter is the location of the source .d.ts files +if [ -z "$1" ]; then + echo "The location of the source .d.ts files (usually folder /src/lib of the TypeScript repository) must be specified as the first parameter." + exit 1 +else + SOURCE_DIR="$1" +fi + +if [[ ! -d "${SOURCE_DIR}" ]]; then + echo "Given location of the source .d.ts files does not exist:" + echo "${SOURCE_DIR}" + exit 1 +fi + + +# Set working directory to root folder of repository +# (we assume this script is located in folder /releng/utils/scripts) +cd `dirname $0` +cd ../../.. +REPO_ROOT_DIR=`pwd -P` + + +GENERATOR_DIR="${REPO_ROOT_DIR}/n4js-tools/n4jsd-generator" +if [[ ! -d "${GENERATOR_DIR}/node_modules" || ! -f "${GENERATOR_DIR}/src-gen/generator.js" ]]; then + echo "ERROR: the n4jsd-generator must be built before running this script!" + exit 1 +fi + + +BUILD_DIR="${REPO_ROOT_DIR}/target/built-in-types" +mkdir -p "${BUILD_DIR}" +cd "${BUILD_DIR}" + + +# STEP #1: CLEAN UP + +# temporary work-around: remove this when deleting deprecated file Iterator.n4jsd in 'n4js-runtime-es2015' +mv "${REPO_ROOT_DIR}"/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Iterator.n4jsd "${REPO_ROOT_DIR}"/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Iterator.n4jsd_ + +rm -f "${REPO_ROOT_DIR}"/plugins/org.eclipse.n4js/src-env/env/builtin_js.n4jsd +rm -f "${REPO_ROOT_DIR}"/n4js-libs/packages/n4js-runtime-es2015/src/n4js/*.n4jsd +rm -f "${REPO_ROOT_DIR}"/n4js-libs/packages/n4js-runtime-esnext/src/n4js/*.n4jsd +#rm -f "${REPO_ROOT_DIR}"/n4js-libs/packages/n4js-runtime-html5/src/n4js/*.n4jsd + +# temporary work-around: remove this when deleting deprecated file Iterator.n4jsd in 'n4js-runtime-es2015' +mv "${REPO_ROOT_DIR}"/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Iterator.n4jsd_ "${REPO_ROOT_DIR}"/n4js-libs/packages/n4js-runtime-es2015/src/n4js/Iterator.n4jsd + + +# STEP #2: GENERATE .n4jsd FILES FROM .d.ts FILES + +rm -rf "src-dts" +mkdir "src-dts" +cp "${SOURCE_DIR}/es5.d.ts" "src-dts" +cp "${SOURCE_DIR}"/es20*.d.ts "src-dts" +#cp "${SOURCE_DIR}"/dom*.d.ts "src-dts" + +# delete some files we do not need/want to convert +# (they only contain triple slash directives, for the most part): +rm src-dts/*.full.d.ts +rm src-dts/es20??.d.ts +rm src-dts/es2021*.d.ts + +rm -rf "out" +mkdir "out" +pushd "${GENERATOR_DIR}" > /dev/null +node -r esm "${GENERATOR_DIR}/bin/dts2n4jsd.js" --runtime-libs --copy-type-refs --no-doc --force --output "${BUILD_DIR}/out" "${BUILD_DIR}/src-dts" +popd > /dev/null + + +# STEP #3: DEPLOY .n4jsd FILES + +cd "out/@n4jsd/src-dts" +cp es5.n4jsd "${REPO_ROOT_DIR}/plugins/org.eclipse.n4js/src-env/env/builtin_js.n4jsd" +cp es2015*.n4jsd "${REPO_ROOT_DIR}/n4js-libs/packages/n4js-runtime-es2015/src/n4js" +cp es2016*.n4jsd "${REPO_ROOT_DIR}/n4js-libs/packages/n4js-runtime-esnext/src/n4js" +cp es2017*.n4jsd "${REPO_ROOT_DIR}/n4js-libs/packages/n4js-runtime-esnext/src/n4js" +cp es2018*.n4jsd "${REPO_ROOT_DIR}/n4js-libs/packages/n4js-runtime-esnext/src/n4js" +cp es2019*.n4jsd "${REPO_ROOT_DIR}/n4js-libs/packages/n4js-runtime-esnext/src/n4js" +cp es2020*.n4jsd "${REPO_ROOT_DIR}/n4js-libs/packages/n4js-runtime-esnext/src/n4js" +#cp dom*.n4jsd "${REPO_ROOT_DIR}/n4js-libs/packages/n4js-runtime-html5/src/n4js" diff --git a/tests/org.eclipse.n4js.bugreports.tests/bugreports-tests/GH_1257_InvalidStaticPolyfillOfBuiltInType.n4js.xt b/tests/org.eclipse.n4js.bugreports.tests/bugreports-tests/GH_1257_InvalidStaticPolyfillOfBuiltInType.n4js.xt index a6469c73bc..3e937f4f7e 100644 --- a/tests/org.eclipse.n4js.bugreports.tests/bugreports-tests/GH_1257_InvalidStaticPolyfillOfBuiltInType.n4js.xt +++ b/tests/org.eclipse.n4js.bugreports.tests/bugreports-tests/GH_1257_InvalidStaticPolyfillOfBuiltInType.n4js.xt @@ -18,7 +18,7 @@ export public class Date extends Date { public foo() { - // XPECT type of 'super.hasOwnProperty' --> {function(union{string,symbol}):boolean} + // XPECT type of 'super.hasOwnProperty' --> {function(PropertyKey):boolean} super.hasOwnProperty("dummy"); } } diff --git a/tests/org.eclipse.n4js.bugreports.tests/bugreports-tests/IDEBUG_0324_WrongSignatureOfRegExpMethodsExecMatch.n4js.xt b/tests/org.eclipse.n4js.bugreports.tests/bugreports-tests/IDEBUG_0324_WrongSignatureOfRegExpMethodsExecMatch.n4js.xt index 26a2b31f77..d15a5e70b4 100644 --- a/tests/org.eclipse.n4js.bugreports.tests/bugreports-tests/IDEBUG_0324_WrongSignatureOfRegExpMethodsExecMatch.n4js.xt +++ b/tests/org.eclipse.n4js.bugreports.tests/bugreports-tests/IDEBUG_0324_WrongSignatureOfRegExpMethodsExecMatch.n4js.xt @@ -14,4 +14,4 @@ var r : ~Array with {index: number; input: string;}; // XPECT noerrors --> -r = /foo/.exec(); +r = /foo/.exec(""); diff --git a/tests/org.eclipse.n4js.bugreports.tests/bugreports-tests/IDEBUG_0606_TranspilerIssuesInCustomErrorTypeCtor.n4js.xt b/tests/org.eclipse.n4js.bugreports.tests/bugreports-tests/IDEBUG_0606_TranspilerIssuesInCustomErrorTypeCtor.n4js.xt index 281af2760d..e4ef3d8c5b 100644 --- a/tests/org.eclipse.n4js.bugreports.tests/bugreports-tests/IDEBUG_0606_TranspilerIssuesInCustomErrorTypeCtor.n4js.xt +++ b/tests/org.eclipse.n4js.bugreports.tests/bugreports-tests/IDEBUG_0606_TranspilerIssuesInCustomErrorTypeCtor.n4js.xt @@ -78,5 +78,5 @@ console.log() console.log('C: ' + new C(42, 'message for ctor C').message) console.log() -console.log('D: ' + new D({n: 42, message: 'message for ctor D'}).message) +console.log('D: ' + new D({n: 42, name: 'ErrorD', message: 'message for ctor D', stack: undefined}).message) console.log() diff --git a/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/object/object_defineProperty.n4js.xt b/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/object/object_defineProperty.n4js.xt index 603e0fbcd2..ab51cdc142 100644 --- a/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/object/object_defineProperty.n4js.xt +++ b/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/object/object_defineProperty.n4js.xt @@ -11,16 +11,29 @@ /* XPECT_SETUP org.eclipse.n4js.expectmatrix.tests.N4JSExpectMatrixTest END_SETUP */ +/* + IDE-2140: If you get a failure here (because the error does no longer show up), then perform the following clean up: + 1) remove all unnecessary casts in all invocations of Object#defineProperty() in this file and all other files in this folder + 2) check for similar situations in other test files in repository "n4js" and in stdlib/OPR + 3) remove this comment and the line "const temp: ...". + */ +// XPECT errors --> "~Object with { value: int } is not a subtype of intersection{PropertyDescriptor,ThisType}." at "{ value: 42 }" +const temp: PropertyDescriptor & ThisType = { value: 42 }; + // Object.defineProperty() // Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty var o : Object = {}; // Creates a new object // Example of an object property added with defineProperty with a data property descriptor -Object.defineProperty(o, "a", {value : 37, - writable : true, - enumerable : true, - configurable : true}); +// IDE-2140 XPECT warnings --> "Unnecessary cast from 37 to any" at "37 as any" +Object.defineProperty(o, "a", {value : 37 as any, + // IDE-2140 XPECT warnings --> "Unnecessary cast from true to boolean" at "true as boolean" + writable : true as boolean, + // IDE-2140 XPECT warnings --> "Unnecessary cast from true to boolean" at "true as boolean" + enumerable : true as boolean, + // IDE-2140 XPECT warnings --> "Unnecessary cast from true to boolean" at "true as boolean" + configurable : true as boolean}); // 'a' property exists in the o object and its value is 37 console.log(JSON.stringify(o)); @@ -28,9 +41,11 @@ console.log(JSON.stringify(o)); // Example of an object property added with defineProperty with an accessor property descriptor var bValue = 38; Object.defineProperty(o, "b", {get : function(){ return bValue; }, - set : function(newValue : number){ bValue = newValue; }, - enumerable : true, - configurable : true}); + set : function(newValue : any){ bValue = newValue as number; }, + // IDE-2140 XPECT warnings --> "Unnecessary cast from true to boolean" at "true as boolean" + enumerable : true as boolean, + // IDE-2140 XPECT warnings --> "Unnecessary cast from true to boolean" at "true as boolean" + configurable : true as boolean}); console.log("38 = " + o["b"]); // 38 // 'b' property exists in the o object and its value is 38 // The value of o.b is now always identical to bValue, unless o.b is redefined @@ -38,7 +53,8 @@ console.log("38 = " + o["b"]); // 38 // You cannot try to mix both : function fail () { try { - Object.defineProperty(o, "conflict", { value: 0x9f91102, get: function() { return 0xdeadbeef; } }); + // IDE-2140 XPECT warnings --> "Unnecessary cast from 167317762 to any" at "0x9f91102 as any" + Object.defineProperty(o, "conflict", { value: 0x9f91102 as any, get: function() { return 0xdeadbeef; } }); } catch (e) { console.log((e as Object).toString()); } } diff --git a/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/object/object_freeze.n4js.xt b/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/object/object_freeze.n4js.xt index e52aa0d73a..bed2f6cb14 100644 --- a/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/object/object_freeze.n4js.xt +++ b/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/object/object_freeze.n4js.xt @@ -53,12 +53,14 @@ function fail(){ // Attempted changes through Object.defineProperty will also throw TypeError function attemptChanges() { try { - Object.defineProperty(obj, "ohai", { value: 17 }); // throws a TypeError + // IDE-2140 XPECT warnings --> "Unnecessary cast from 17 to any" at "17 as any" + Object.defineProperty(obj, "ohai", { value: 17 as any }); // throws a TypeError } catch (e) { console.log((e as Object).toString()); } try { - Object.defineProperty(obj, "foo", { value: "eit" }); // throws a TypeError + // IDE-2140 XPECT warnings --> "Unnecessary cast from "eit" to any" at ""eit" as any" + Object.defineProperty(obj, "foo", { value: "eit" as any }); // throws a TypeError } catch (e1) { console.log((e1 as Object).toString());} } diff --git a/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/object/object_getOwnPropertyDescriptor.n4js.xt b/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/object/object_getOwnPropertyDescriptor.n4js.xt index af74375a6f..887a5a079b 100644 --- a/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/object/object_getOwnPropertyDescriptor.n4js.xt +++ b/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/object/object_getOwnPropertyDescriptor.n4js.xt @@ -23,7 +23,12 @@ d = Object.getOwnPropertyDescriptor(o, "bar"); console.log(d); o = {}; -Object.defineProperty(o, "baz", { value: 8675309, writable: false, enumerable: false }); +// IDE-2140 XPECT warnings --> "Unnecessary cast from 8675309 to any" at "8675309 as any" +Object.defineProperty(o, "baz", { value: 8675309 as any, + // IDE-2140 XPECT warnings --> "Unnecessary cast from false to boolean" at "false as boolean" + writable: false as boolean, + // IDE-2140 XPECT warnings --> "Unnecessary cast from false to boolean" at "false as boolean" + enumerable: false as boolean }); d = Object.getOwnPropertyDescriptor(o, "baz"); console.log(d); diff --git a/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/object/object_isFrozen.n4js.xt b/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/object/object_isFrozen.n4js.xt index 3a3065fb16..0de51e3651 100644 --- a/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/object/object_isFrozen.n4js.xt +++ b/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/object/object_isFrozen.n4js.xt @@ -41,22 +41,26 @@ console.log("4 frozen = " + (Object.isFrozen(oneProp) === true)); var nonWritable = { e: "plep" }; // IDEBUG-124 XPECT noerrors --> "IDEBUG-124: preventExtensions" Object.preventExtensions(nonWritable); -Object.defineProperty(nonWritable, "e", { writable: false }); // make non-writable +// IDE-2140 XPECT warnings --> "Unnecessary cast from false to boolean" at "false as boolean" +Object.defineProperty(nonWritable, "e", { writable: false as boolean }); // make non-writable console.log("5 not frozen = " + (Object.isFrozen(nonWritable) === false)); // Changing that property to non-configurable then makes the object frozen. -Object.defineProperty(nonWritable, "e", { configurable: false }); // make non-configurable +// IDE-2140 XPECT warnings --> "Unnecessary cast from false to boolean" at "false as boolean" +Object.defineProperty(nonWritable, "e", { configurable: false as boolean }); // make non-configurable console.log("6 frozen = " + (Object.isFrozen(nonWritable) === true)); // A non-extensible object with a non-configurable but still writable property also isn't frozen. var nonConfigurable = { release: "the kraken!" }; // IDEBUG-124 XPECT noerrors --> "IDEBUG-124: preventExtensions" Object.preventExtensions(nonConfigurable); -Object.defineProperty(nonConfigurable, "release", { configurable: false }); +// IDE-2140 XPECT warnings --> "Unnecessary cast from false to boolean" at "false as boolean" +Object.defineProperty(nonConfigurable, "release", { configurable: false as boolean }); console.log("7 not frozen = " + (Object.isFrozen(nonConfigurable) === false)); // Changing that property to non-writable then makes the object frozen. -Object.defineProperty(nonConfigurable, "release", { writable: false }); +// IDE-2140 XPECT warnings --> "Unnecessary cast from false to boolean" at "false as boolean" +Object.defineProperty(nonConfigurable, "release", { writable: false as boolean }); console.log("8 frozen = " + (Object.isFrozen(nonConfigurable) === true)); // A non-extensible object with a configurable accessor property isn't frozen. @@ -66,7 +70,8 @@ Object.preventExtensions(accessor); console.log("9 not frozen = " + (Object.isFrozen(accessor) === false)); // ...but make that property non-configurable and it becomes frozen. -Object.defineProperty(accessor, "food", { configurable: false }); +// IDE-2140 XPECT warnings --> "Unnecessary cast from false to boolean" at "false as boolean" +Object.defineProperty(accessor, "food", { configurable: false as boolean }); console.log("10 frozen = " + (Object.isFrozen(accessor) === true)); // But the easiest way for an object to be frozen is if Object.freeze has been called on it. diff --git a/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/object/object_isSealed.n4js.xt b/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/object/object_isSealed.n4js.xt index f7a904d1d3..e08aa9aaeb 100644 --- a/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/object/object_isSealed.n4js.xt +++ b/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/object/object_isSealed.n4js.xt @@ -30,7 +30,8 @@ Object.preventExtensions(hasProp); console.log("2 not sealed = " + (Object.isSealed(hasProp) === false)); // But make them all non-configurable and the object becomes sealed. -Object.defineProperty(hasProp, "foo", { configurable: false }); +// IDE-2140 XPECT warnings --> "Unnecessary cast from false to boolean" at "false as boolean" +Object.defineProperty(hasProp, "foo", { configurable: false as boolean }); console.log("3 sealed = " + (Object.isSealed(hasProp) === true)); diff --git a/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/object/object_seal.n4js.xt b/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/object/object_seal.n4js.xt index 9d51cf99bd..e247c1d626 100644 --- a/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/object/object_seal.n4js.xt +++ b/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/object/object_seal.n4js.xt @@ -70,14 +70,16 @@ fail2(); // Attempted additions through Object.defineProperty will also throw function fail3 () { try { - Object.defineProperty(obj, "ohai", { value: 17 }); // throws a TypeError + // IDE-2140 XPECT warnings --> "Unnecessary cast from 17 to any" at "17 as any" + Object.defineProperty(obj, "ohai", { value: 17 as any }); // throws a TypeError } catch (e) { console.log((e as Object).toString());} } fail3(); -Object.defineProperty(obj, "foo", { value: "eit" }); // changes existing property value +// IDE-2140 XPECT warnings --> "Unnecessary cast from "eit" to any" at ""eit" as any" +Object.defineProperty(obj, "foo", { value: "eit" as any }); // changes existing property value console.log(obj.foo); diff --git a/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/string/string_search.n4js.xt b/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/string/string_search.n4js.xt index b01219274a..be6e601597 100644 --- a/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/string/string_search.n4js.xt +++ b/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/string/string_search.n4js.xt @@ -14,7 +14,7 @@ // String.prototype.search() // Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search -function testinput(re, str : string){ +function testinput(re: RegExp, str : string){ var midstring; if (str.search(re) != -1){ midstring = " contains "; diff --git a/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/string/string_split.n4js.xt b/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/string/string_split.n4js.xt index e0c16c632c..d5a51a5381 100644 --- a/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/string/string_split.n4js.xt +++ b/tests/org.eclipse.n4js.expectmatrix.tests/xpect-tests/builtin_js/string/string_split.n4js.xt @@ -21,7 +21,7 @@ console.log(tempestString.split(" ")); console.log(tempestString.split(" ", 4)); // Complex example -function splitString(stringToSplit : string, separator) { +function splitString(stringToSplit : string, separator : string) { var arrayOfStrings = stringToSplit.split(separator); console.log('The original string is: "' + stringToSplit + '"'); diff --git a/tests/org.eclipse.n4js.ide.tests/src/org/eclipse/n4js/ide/tests/contentassist/CamelCaseCompletionTest.java b/tests/org.eclipse.n4js.ide.tests/src/org/eclipse/n4js/ide/tests/contentassist/CamelCaseCompletionTest.java index 4e3668ca61..deeee76130 100644 --- a/tests/org.eclipse.n4js.ide.tests/src/org/eclipse/n4js/ide/tests/contentassist/CamelCaseCompletionTest.java +++ b/tests/org.eclipse.n4js.ide.tests/src/org/eclipse/n4js/ide/tests/contentassist/CamelCaseCompletionTest.java @@ -20,7 +20,8 @@ public class CamelCaseCompletionTest extends AbstractCompletionTest { /***/ @Test public void testCamelCasePrefix_01() { - testAtCursor("EvE<|>", "(EvalError, Class, EvalError, , , 00000, , , , ([0:0 - 0:3], EvalError), [], [], , )"); + testAtCursor("EvE<|>", "(EvalError, Class, EvalError, , , 00000, , , , ([0:0 - 0:3], EvalError), [], [], , )\n" + + "(EvalErrorConstructor, Text, EvalErrorConstructor, , , 00001, , , , ([0:0 - 0:3], EvalErrorConstructor), [], [], , )"); } /***/ diff --git a/tests/org.eclipse.n4js.ide.tests/src/org/eclipse/n4js/ide/tests/contentassist/CompletionWithImportsTest.xtend b/tests/org.eclipse.n4js.ide.tests/src/org/eclipse/n4js/ide/tests/contentassist/CompletionWithImportsTest.xtend index 99a465ed69..b955cc4388 100644 --- a/tests/org.eclipse.n4js.ide.tests/src/org/eclipse/n4js/ide/tests/contentassist/CompletionWithImportsTest.xtend +++ b/tests/org.eclipse.n4js.ide.tests/src/org/eclipse/n4js/ide/tests/contentassist/CompletionWithImportsTest.xtend @@ -238,6 +238,7 @@ public class CompletionWithImportsTest extends AbstractCompletionTest { Obj<|> ''', ''' (Object, Class, Object, , , 00000, , , , ([0:0 - 0:3], Object), [], [], , ) + (ObjectConstructor, Text, ObjectConstructor, , , 00001, , , , ([0:0 - 0:3], ObjectConstructor), [], [], , ) '''); } @@ -278,9 +279,16 @@ public class CompletionWithImportsTest extends AbstractCompletionTest { (Array7, Class, Array7, , , 00010, , , , ([0:8 - 0:9], Array7), [], [], , ) (Array8, Class, Array8, , , 00011, , , , ([0:8 - 0:9], Array8), [], [], , ) (Array9, Class, Array9, , , 00012, , , , ([0:8 - 0:9], Array9), [], [], , ) - (AsyncGenerator, Interface, AsyncGenerator, , , 00013, , , , ([0:8 - 0:9], AsyncGenerator), [], [], , ) - (AsyncIterable, Interface, AsyncIterable, , , 00014, , , , ([0:8 - 0:9], AsyncIterable), [], [], , ) - (AsyncIterator, Interface, AsyncIterator, , , 00015, , , , ([0:8 - 0:9], AsyncIterator), [], [], , ) + (ArrayBuffer, Class, ArrayBuffer, , , 00013, , , , ([0:8 - 0:9], ArrayBuffer), [], [], , ) + (ArrayBufferConstructor, Text, ArrayBufferConstructor, , , 00014, , , , ([0:8 - 0:9], ArrayBufferConstructor), [], [], , ) + (ArrayBufferLike, Text, ArrayBufferLike, , , 00015, , , , ([0:8 - 0:9], ArrayBufferLike), [], [], , ) + (ArrayBufferTypes, Interface, ArrayBufferTypes, , , 00016, , , , ([0:8 - 0:9], ArrayBufferTypes), [], [], , ) + (ArrayBufferView, Interface, ArrayBufferView, , , 00017, , , , ([0:8 - 0:9], ArrayBufferView), [], [], , ) + (ArrayConstructor, Text, ArrayConstructor, , , 00018, , , , ([0:8 - 0:9], ArrayConstructor), [], [], , ) + (ArrayLike, Interface, ArrayLike, , , 00019, , , , ([0:8 - 0:9], ArrayLike), [], [], , ) + (AsyncGenerator, Interface, AsyncGenerator, , , 00020, , , , ([0:8 - 0:9], AsyncGenerator), [], [], , ) + (AsyncIterable, Interface, AsyncIterable, , , 00021, , , , ([0:8 - 0:9], AsyncIterable), [], [], , ) + (AsyncIterator, Interface, AsyncIterator, , , 00022, , , , ([0:8 - 0:9], AsyncIterator), [], [], , ) '''); } @@ -302,9 +310,16 @@ public class CompletionWithImportsTest extends AbstractCompletionTest { (Array7, Class, Array7, , , 00010, , , , ([0:8 - 0:9], Array7), [], [], , ) (Array8, Class, Array8, , , 00011, , , , ([0:8 - 0:9], Array8), [], [], , ) (Array9, Class, Array9, , , 00012, , , , ([0:8 - 0:9], Array9), [], [], , ) - (AsyncGenerator, Interface, AsyncGenerator, , , 00013, , , , ([0:8 - 0:9], AsyncGenerator), [], [], , ) - (AsyncIterable, Interface, AsyncIterable, , , 00014, , , , ([0:8 - 0:9], AsyncIterable), [], [], , ) - (AsyncIterator, Interface, AsyncIterator, , , 00015, , , , ([0:8 - 0:9], AsyncIterator), [], [], , ) + (ArrayBuffer, Class, ArrayBuffer, , , 00013, , , , ([0:8 - 0:9], ArrayBuffer), [], [], , ) + (ArrayBufferConstructor, Text, ArrayBufferConstructor, , , 00014, , , , ([0:8 - 0:9], ArrayBufferConstructor), [], [], , ) + (ArrayBufferLike, Text, ArrayBufferLike, , , 00015, , , , ([0:8 - 0:9], ArrayBufferLike), [], [], , ) + (ArrayBufferTypes, Interface, ArrayBufferTypes, , , 00016, , , , ([0:8 - 0:9], ArrayBufferTypes), [], [], , ) + (ArrayBufferView, Interface, ArrayBufferView, , , 00017, , , , ([0:8 - 0:9], ArrayBufferView), [], [], , ) + (ArrayConstructor, Text, ArrayConstructor, , , 00018, , , , ([0:8 - 0:9], ArrayConstructor), [], [], , ) + (ArrayLike, Interface, ArrayLike, , , 00019, , , , ([0:8 - 0:9], ArrayLike), [], [], , ) + (AsyncGenerator, Interface, AsyncGenerator, , , 00020, , , , ([0:8 - 0:9], AsyncGenerator), [], [], , ) + (AsyncIterable, Interface, AsyncIterable, , , 00021, , , , ([0:8 - 0:9], AsyncIterable), [], [], , ) + (AsyncIterator, Interface, AsyncIterator, , , 00022, , , , ([0:8 - 0:9], AsyncIterator), [], [], , ) '''); } diff --git a/tests/org.eclipse.n4js.ide.tests/src/org/eclipse/n4js/ide/tests/symbol/DefinitionTest.java b/tests/org.eclipse.n4js.ide.tests/src/org/eclipse/n4js/ide/tests/symbol/DefinitionTest.java index fbe4b44a08..5d1e1b8942 100644 --- a/tests/org.eclipse.n4js.ide.tests/src/org/eclipse/n4js/ide/tests/symbol/DefinitionTest.java +++ b/tests/org.eclipse.n4js.ide.tests/src/org/eclipse/n4js/ide/tests/symbol/DefinitionTest.java @@ -32,6 +32,11 @@ */ public class DefinitionTest extends AbstractDefinitionTest { + /** + * Zero-based line number of getter "length" in type "String" in file "builtin_js.n4jsd". + */ + public static final int STRING_LENGTH_LINE = 104; + /***/ @Test public void testDefinition_01() throws Exception { @@ -53,7 +58,7 @@ public void testDefinition_02() throws Exception { public void testDefinition_03() throws Exception { testAtCursor( "var s: string = ''; s.le<|>ngth;", - "(n4scheme:/builtin_js.n4jsd, [839:12 - 839:18])"); + "(n4scheme:/builtin_js.n4jsd, [" + STRING_LENGTH_LINE + ":12 - " + STRING_LENGTH_LINE + ":18])"); } /***/ @@ -65,14 +70,15 @@ public void testDefinition_04() throws Exception { DefinitionParams definitionParams = new DefinitionParams(); definitionParams.setTextDocument(new TextDocumentIdentifier("n4scheme:/builtin_js.n4jsd")); // see position from test above - definitionParams.setPosition(new Position(839, 12)); + definitionParams.setPosition(new Position(STRING_LENGTH_LINE, 12)); CompletableFuture, List>> definitionsFuture = languageServer .definition(definitionParams); Either, List> definitions = definitionsFuture.get(); File root = getRoot(); String actualSignatureHelp = new StringLSP4J(root).toString4(definitions); - assertEquals("(n4scheme:/builtin_js.n4jsd, [839:12 - 839:18])", actualSignatureHelp.trim()); + assertEquals("(n4scheme:/builtin_js.n4jsd, [" + STRING_LENGTH_LINE + ":12 - " + STRING_LENGTH_LINE + ":18])", + actualSignatureHelp.trim()); } } diff --git a/tests/org.eclipse.n4js.ide.tests/src/org/eclipse/n4js/ide/tests/symbol/ImplementationTest.java b/tests/org.eclipse.n4js.ide.tests/src/org/eclipse/n4js/ide/tests/symbol/ImplementationTest.java index 7c322cbb1a..55ada990b2 100644 --- a/tests/org.eclipse.n4js.ide.tests/src/org/eclipse/n4js/ide/tests/symbol/ImplementationTest.java +++ b/tests/org.eclipse.n4js.ide.tests/src/org/eclipse/n4js/ide/tests/symbol/ImplementationTest.java @@ -64,15 +64,16 @@ public void testDefinition_04() throws Exception { DefinitionParams definitionParams = new DefinitionParams(); definitionParams.setTextDocument(new TextDocumentIdentifier("n4scheme:/builtin_js.n4jsd")); - // see position from test above - definitionParams.setPosition(new Position(839, 12)); + // see position from test in DefinitionTest.java + definitionParams.setPosition(new Position(DefinitionTest.STRING_LENGTH_LINE, 12)); CompletableFuture, List>> definitionsFuture = languageServer .definition(definitionParams); Either, List> definitions = definitionsFuture.get(); File root = getRoot(); String actualSignatureHelp = new StringLSP4J(root).toString4(definitions); - assertEquals("(n4scheme:/builtin_js.n4jsd, [839:12 - 839:18])", actualSignatureHelp.trim()); + assertEquals("(n4scheme:/builtin_js.n4jsd, [" + DefinitionTest.STRING_LENGTH_LINE + ":12 - " + + DefinitionTest.STRING_LENGTH_LINE + ":18])", actualSignatureHelp.trim()); } } diff --git a/tests/org.eclipse.n4js.lang.tests/src/org/eclipse/n4js/scoping/builtin/BuiltInTypesDefinitionTest.xtend b/tests/org.eclipse.n4js.lang.tests/src/org/eclipse/n4js/scoping/builtin/BuiltInTypesDefinitionTest.xtend index 5e09470933..a63732ea8b 100644 --- a/tests/org.eclipse.n4js.lang.tests/src/org/eclipse/n4js/scoping/builtin/BuiltInTypesDefinitionTest.xtend +++ b/tests/org.eclipse.n4js.lang.tests/src/org/eclipse/n4js/scoping/builtin/BuiltInTypesDefinitionTest.xtend @@ -14,10 +14,13 @@ import com.google.inject.Inject import com.google.inject.Provider import org.eclipse.emf.common.util.URI import org.eclipse.emf.ecore.EObject +import org.eclipse.emf.ecore.resource.Resource import org.eclipse.n4js.N4JSInjectorProvider import org.eclipse.n4js.n4JS.N4JSPackage import org.eclipse.n4js.n4JS.Script +import org.eclipse.n4js.resource.N4JSResource import org.eclipse.n4js.validation.IssueCodes +import org.eclipse.xtext.diagnostics.Severity import org.eclipse.xtext.resource.XtextResourceSet import org.eclipse.xtext.testing.InjectWith import org.eclipse.xtext.testing.XtextRunner @@ -53,24 +56,38 @@ class BuiltInTypesDefinitionTest { doValidatePredefinedTypes(rs, true) } - protected def doValidatePredefinedTypes(XtextResourceSet rs, boolean loadOnDemand) { + private def doValidatePredefinedTypes(XtextResourceSet rs, boolean loadOnDemand) { val predefined = newArrayList(BuiltInTypeScope.FILE_NAMES) predefined.addAll(GlobalObjectScope.FILE_NAMES) for (filename: predefined) { val URI uri = N4Scheme.N4URI.create(filename); - val resource = rs.getResource(uri, loadOnDemand) - assertNotNull(uri.toString + " not in " + rs.resources.map[uri], resource) - assertEquals("Predefined types file must contain two objects", 2, resource.contents.size); - val EObject content = resource.contents.head; - assertTrue("Predefined types file must contain Script, but was " + content.eClass.name, content instanceof Script); + val resource = rs.getResource(uri, loadOnDemand); + val resourceName = "built-in types resource for \"" + filename + "\""; + + assertNotNull(uri.toString + " not in " + rs.resources.map[uri], resource); + assertEquals(resourceName + " must contain two objects", 2, resource.contents.size); + + val EObject ast = resource.contents.head; + assertTrue(resourceName + " must contain a Script as AST root, but was " + ast.eClass.name, ast instanceof Script); + assertTrue(resourceName + " must not contain syntax errors, but got:\n " + errorsAsString(resource, "\n "), resource.errors.empty); + + (resource as N4JSResource).performPostProcessing(); + + val allIssues = validationTestHelper.validate(resource); if (filename == "builtin_js.n4jsd") { // unfortunately this file contains an error we cannot get rid of: + assertTrue(resourceName + " is expected to contain only a single warning, but got:\n " + allIssues.join("\n "), + allIssues.size === 1 && allIssues.get(0).severity === Severity.WARNING); validationTestHelper.assertWarning(resource, N4JSPackage.Literals.N4_FIELD_DECLARATION, IssueCodes.CLF_NO_FINAL_INTERFACE_MEMBER, "In interfaces, only methods may be declared final."); } else { - validationTestHelper.assertNoIssues(resource) + assertTrue(resourceName + " must not contain any validation issues, but got:\n " + allIssues.join("\n "), allIssues.empty); } } } + + private def errorsAsString(Resource resource, String separator) { + return resource.errors.map[diagnostic | "line " + diagnostic.line + ": " + diagnostic.message ].join(separator); + } } diff --git a/tests/org.eclipse.n4js.lang.tests/src/org/eclipse/n4js/tests/scoping/N4JSScopingTestWithIndexTest.xtend b/tests/org.eclipse.n4js.lang.tests/src/org/eclipse/n4js/tests/scoping/N4JSScopingTestWithIndexTest.xtend index 85f41c5d18..55975c3815 100644 --- a/tests/org.eclipse.n4js.lang.tests/src/org/eclipse/n4js/tests/scoping/N4JSScopingTestWithIndexTest.xtend +++ b/tests/org.eclipse.n4js.lang.tests/src/org/eclipse/n4js/tests/scoping/N4JSScopingTestWithIndexTest.xtend @@ -91,7 +91,7 @@ class N4JSScopingTestWithIndexTest { - + diff --git a/tests/org.eclipse.n4js.lang.tests/src/org/eclipse/n4js/tests/typesbuilder/ClassWithMethodsTypesBuilderTest.xtend b/tests/org.eclipse.n4js.lang.tests/src/org/eclipse/n4js/tests/typesbuilder/ClassWithMethodsTypesBuilderTest.xtend index 67fd8034c4..2f3e0d5310 100644 --- a/tests/org.eclipse.n4js.lang.tests/src/org/eclipse/n4js/tests/typesbuilder/ClassWithMethodsTypesBuilderTest.xtend +++ b/tests/org.eclipse.n4js.lang.tests/src/org/eclipse/n4js/tests/typesbuilder/ClassWithMethodsTypesBuilderTest.xtend @@ -92,7 +92,7 @@ class ClassWithMethodsTypesBuilderTest extends AbstractTypesBuilderTest { val type = assertTypeRefOfTField(phase, tField, newN4jsResource) - assertBuiltinTypeFragmentURI(phase, newN4jsResource, type, "/1/@topLevelTypes.5") + assertBuiltinTypeFragmentURI(phase, newN4jsResource, type, "/1/@topLevelTypes.12") } def private assertFirstTMethod(String phase, TClass tClass, Resource newN4jsResource) { @@ -142,7 +142,7 @@ class ClassWithMethodsTypesBuilderTest extends AbstractTypesBuilderTest { val type = assertFirstN4Field(phase, n4Class, resource) - assertBuiltinTypeFragmentURI(phase, resource, type, "/1/@topLevelTypes.5") + assertBuiltinTypeFragmentURI(phase, resource, type, "/1/@topLevelTypes.12") assertFirstN4Method(phase, n4Class, resource) diff --git a/tests/org.eclipse.n4js.lang.tests/src/org/eclipse/n4js/tests/typesbuilder/ClassesGetterSetterTypesBuilderTest.xtend b/tests/org.eclipse.n4js.lang.tests/src/org/eclipse/n4js/tests/typesbuilder/ClassesGetterSetterTypesBuilderTest.xtend index ed7e797ace..861a7587fc 100644 --- a/tests/org.eclipse.n4js.lang.tests/src/org/eclipse/n4js/tests/typesbuilder/ClassesGetterSetterTypesBuilderTest.xtend +++ b/tests/org.eclipse.n4js.lang.tests/src/org/eclipse/n4js/tests/typesbuilder/ClassesGetterSetterTypesBuilderTest.xtend @@ -82,7 +82,7 @@ class ClassesGetterSetterTypesBuilderTest extends AbstractTypesBuilderTest { assertTSetter(phase, tClass, newN4jsResource, "c", "newC", "/1/@topLevelTypes.4") - assertTSetter(phase, tClass, newN4jsResource, "d", "newD", "/1/@topLevelTypes.3") + assertTSetter(phase, tClass, newN4jsResource, "d", "newD", "/1/@topLevelTypes.8") } def private assertTField(String phase, TClass tClass, Resource newN4jsResource, String expectedName, String expectedTypeFragmentURI) { @@ -127,7 +127,7 @@ class ClassesGetterSetterTypesBuilderTest extends AbstractTypesBuilderTest { assertN4Getter(phase, n4Class, resource, "d", "/1/@topLevelTypes.4") assertN4Setter(phase, n4Class, resource, "c", "newC", "/1/@topLevelTypes.4") - assertN4Setter(phase, n4Class, resource, "d", "newD", "/1/@topLevelTypes.3") + assertN4Setter(phase, n4Class, resource, "d", "newD", "/1/@topLevelTypes.8") } def private void assertN4Field(String phase, N4ClassDeclaration n4Class, Resource resource, String expectedName, String expectedTypeFragmentURI) { diff --git a/tests/org.eclipse.n4js.lang.tests/src/org/eclipse/n4js/tests/typesbuilder/FunctionsTypesBuilderTest.xtend b/tests/org.eclipse.n4js.lang.tests/src/org/eclipse/n4js/tests/typesbuilder/FunctionsTypesBuilderTest.xtend index 0ba84997ef..9e601e5288 100644 --- a/tests/org.eclipse.n4js.lang.tests/src/org/eclipse/n4js/tests/typesbuilder/FunctionsTypesBuilderTest.xtend +++ b/tests/org.eclipse.n4js.lang.tests/src/org/eclipse/n4js/tests/typesbuilder/FunctionsTypesBuilderTest.xtend @@ -83,15 +83,15 @@ class FunctionsTypesBuilderTest extends AbstractTypesBuilderTest { val type = assertReturnTypeRef(phase, tFunction, newN4jsResource) - assertBuiltinTypeFragmentURI(phase, newN4jsResource, type, "/1/@topLevelTypes.3") + assertBuiltinTypeFragmentURI(phase, newN4jsResource, type, "/1/@topLevelTypes.8") val firstParameterType = assertParameter(phase, tFunction, newN4jsResource, "input", false) - assertBuiltinTypeFragmentURI(phase, newN4jsResource, firstParameterType, "/1/@topLevelTypes.3") + assertBuiltinTypeFragmentURI(phase, newN4jsResource, firstParameterType, "/1/@topLevelTypes.8") val secondParameterType = assertParameter(phase, tFunction, newN4jsResource, "hint", false) - assertBuiltinTypeFragmentURI(phase, newN4jsResource, secondParameterType, "/1/@topLevelTypes.3") + assertBuiltinTypeFragmentURI(phase, newN4jsResource, secondParameterType, "/1/@topLevelTypes.8") } def assertSecondTFunction(String phase, Resource newN4jsResource) { @@ -118,15 +118,15 @@ class FunctionsTypesBuilderTest extends AbstractTypesBuilderTest { val type = assertReturnTypeRef(phase, n4Function, resource) - assertBuiltinTypeFragmentURI(phase, resource, type, "/1/@topLevelTypes.3") + assertBuiltinTypeFragmentURI(phase, resource, type, "/1/@topLevelTypes.8") val firstParameterType = assertParameter(phase, n4Function, resource, "input", false) - assertBuiltinTypeFragmentURI(phase, resource, firstParameterType, "/1/@topLevelTypes.3") + assertBuiltinTypeFragmentURI(phase, resource, firstParameterType, "/1/@topLevelTypes.8") val secondParameterType = assertParameter(phase, n4Function, resource, "hint", false) - assertBuiltinTypeFragmentURI(phase, resource, secondParameterType, "/1/@topLevelTypes.3") + assertBuiltinTypeFragmentURI(phase, resource, secondParameterType, "/1/@topLevelTypes.8") } def assertSecondFunction(String phase, Resource resource, ExportableElement exportableElement) { diff --git a/tests/org.eclipse.n4js.lang.tests/src/org/eclipse/n4js/tests/typesbuilder/ObjectLiteralGetterSetterTypesBuilderTest.xtend b/tests/org.eclipse.n4js.lang.tests/src/org/eclipse/n4js/tests/typesbuilder/ObjectLiteralGetterSetterTypesBuilderTest.xtend index a305c43a21..f240a3d5c7 100644 --- a/tests/org.eclipse.n4js.lang.tests/src/org/eclipse/n4js/tests/typesbuilder/ObjectLiteralGetterSetterTypesBuilderTest.xtend +++ b/tests/org.eclipse.n4js.lang.tests/src/org/eclipse/n4js/tests/typesbuilder/ObjectLiteralGetterSetterTypesBuilderTest.xtend @@ -76,7 +76,7 @@ class ObjectLiteralGetterSetterTypesBuilderTest extends AbstractTypesBuilderTest val firstVariable = assertTVariable(phase, newN4jsResource, 0, "callee", false) val firstVariableType = assertTypeRef(phase, firstVariable, newN4jsResource) - assertBuiltinTypeFragmentURI(phase, newN4jsResource, firstVariableType, "/1/@topLevelTypes.0") // any + assertBuiltinTypeFragmentURI(phase, newN4jsResource, firstVariableType, "/1/@topLevelTypes.3") // any } override assertExampleJSStructure(String phase, Resource resource) { diff --git a/tests/org.eclipse.n4js.spec.tests/xpect-tests/Ch17__JavaScriptObjects/Error/Error_optionalFields.n4js.xt b/tests/org.eclipse.n4js.spec.tests/xpect-tests/Ch17__JavaScriptObjects/Error/Error_optionalFields.n4js.xt index af49a805cb..08f6746550 100644 --- a/tests/org.eclipse.n4js.spec.tests/xpect-tests/Ch17__JavaScriptObjects/Error/Error_optionalFields.n4js.xt +++ b/tests/org.eclipse.n4js.spec.tests/xpect-tests/Ch17__JavaScriptObjects/Error/Error_optionalFields.n4js.xt @@ -18,12 +18,14 @@ Msg --- */ var e = new Error(); -console.log("Name", e.name); -console.log("Msg", e.message); +console.log("Name", e.name); // name is optional, set to "Error" by default +console.log("Msg", e.message); // message is optional, set to empty string by default // XPECT noerrors --> "all members are defined" var se2 : ~Error = { name: "n", message: "m"}; -// XPECT noerrors --> "message is optional, set to empty string by default" +// message is optional in the constructor, but not in the type +// XPECT errors --> "~Object with { name: string } is not a structural subtype of ~Error: missing field message." at "{ name: "n"}" var se1 : ~Error = { name: "n"}; -// XPECT noerrors --> "name is optional as well, set to error by default" +// name is optional in the constructor, but not in the type +// XPECT errors --> "~Object is not a structural subtype of ~Error: missing field message and 1 more." at "{}" var se0 : ~Error = {}; diff --git a/tests/org.eclipse.n4js.spec.tests/xt-tests/Ch11_04__Polyfill_Definitions/Req152_Polyfill/src/Req152_PolyfillConstructor.n4jsd.xt b/tests/org.eclipse.n4js.spec.tests/xt-tests/Ch11_04__Polyfill_Definitions/Req152_Polyfill/src/Req152_PolyfillConstructor.n4jsd.xt index 3a6b3cde95..6c2ec7b4b7 100644 --- a/tests/org.eclipse.n4js.spec.tests/xt-tests/Ch11_04__Polyfill_Definitions/Req152_Polyfill/src/Req152_PolyfillConstructor.n4jsd.xt +++ b/tests/org.eclipse.n4js.spec.tests/xt-tests/Ch11_04__Polyfill_Definitions/Req152_Polyfill/src/Req152_PolyfillConstructor.n4jsd.xt @@ -30,6 +30,6 @@ @Polyfill export external public class Object extends Object { - // XPECT errors --> "Signature of constructor of class Object (line 34) does not conform to overridden constructor of class Object (line 141): {function(number)} is not a subtype of {function(any=…)}." at "constructor" + // XPECT errors --> "Signature of constructor of class Object (line 34) does not conform to overridden constructor of class Object (line 23): {function(number)} is not a subtype of {function(any=…)}." at "constructor" constructor(n : number) } diff --git a/tests/org.eclipse.n4js.transpiler.es5.tests/testdata/_new_/memberPatching/delegation_ifc2ifc.n4js.xt b/tests/org.eclipse.n4js.transpiler.es5.tests/testdata/_new_/memberPatching/delegation_ifc2ifc.n4js.xt index b9faf2da64..db678f6374 100644 --- a/tests/org.eclipse.n4js.transpiler.es5.tests/testdata/_new_/memberPatching/delegation_ifc2ifc.n4js.xt +++ b/tests/org.eclipse.n4js.transpiler.es5.tests/testdata/_new_/memberPatching/delegation_ifc2ifc.n4js.xt @@ -46,14 +46,14 @@ console.log('========================================'); // assert that a delegate to I#m() was added to J var j : any+ = J; -Object.getOwnPropertyDescriptor(j.$defaultMembers as Object, 'm')['value'](); -Object.getOwnPropertyDescriptor(j.$defaultMembers as Object, 'g')['get'](); -Object.getOwnPropertyDescriptor(j.$defaultMembers as Object, 's')['set']('hello setter!'); +(Object.getOwnPropertyDescriptor(j.$defaultMembers as Object, 'm').value as Function)(); +Object.getOwnPropertyDescriptor(j.$defaultMembers as Object, 'g').get(); +Object.getOwnPropertyDescriptor(j.$defaultMembers as Object, 's').set('hello setter!'); // assert that a delegate to I#m() was added to K var k : any+ = K; -Object.getOwnPropertyDescriptor(k.$defaultMembers as Object, 'm')['value'](); -Object.getOwnPropertyDescriptor(k.$defaultMembers as Object, 'g')['get'](); -Object.getOwnPropertyDescriptor(k.$defaultMembers as Object, 's')['set']('hello setter!'); +(Object.getOwnPropertyDescriptor(k.$defaultMembers as Object, 'm').value as Function)(); +Object.getOwnPropertyDescriptor(k.$defaultMembers as Object, 'g').get(); +Object.getOwnPropertyDescriptor(k.$defaultMembers as Object, 's').set('hello setter!'); console.log('========================================'); diff --git a/tests/org.eclipse.n4js.xpect.tests/xpect-tests/scopingSimple/Scoping_StaticMembersInInterfaces.n4js.xt b/tests/org.eclipse.n4js.xpect.tests/xpect-tests/scopingSimple/Scoping_StaticMembersInInterfaces.n4js.xt index 32587ca4ac..5f425ecdce 100644 --- a/tests/org.eclipse.n4js.xpect.tests/xpect-tests/scopingSimple/Scoping_StaticMembersInInterfaces.n4js.xt +++ b/tests/org.eclipse.n4js.xpect.tests/xpect-tests/scopingSimple/Scoping_StaticMembersInInterfaces.n4js.xt @@ -42,7 +42,7 @@ class C implements I { // f, g, s, m, propI, // __proto__, constructor, create, defineProperties, // defineProperty, freeze, getOwnPropertyDescriptor, getOwnPropertyNames, getPrototypeOf, -// hasOwnProperty, is, isExtensible, isFrozen, isPrototypeOf, isSealed, keys, n4type, +// hasOwnProperty, isExtensible, isFrozen, isPrototypeOf, isSealed, keys, n4type, // preventExtensions, propertyIsEnumerable, prototype, seal, toLocaleString, toString, valueOf // --- I.propI; @@ -52,7 +52,7 @@ I.propI; // propI2, // __proto__, constructor, create, defineProperties, // defineProperty, freeze, getOwnPropertyDescriptor, getOwnPropertyNames, getPrototypeOf, -// hasOwnProperty, is, isExtensible, isFrozen, isPrototypeOf, isSealed, keys, n4type, +// hasOwnProperty, isExtensible, isFrozen, isPrototypeOf, isSealed, keys, n4type, // preventExtensions, propertyIsEnumerable, prototype, seal, toLocaleString, toString, valueOf // --- I2.propI2; @@ -60,9 +60,9 @@ I2.propI2; // XPECT scope at 'C.|propC' --- // propC, -// __proto__, apply, arguments, bind, call, constructor, create, defineProperties, +// __proto__, apply, arguments, bind, call, caller, constructor, create, defineProperties, // defineProperty, freeze, getOwnPropertyDescriptor, getOwnPropertyNames, getPrototypeOf, -// hasOwnProperty, is, isExtensible, isFrozen, isPrototypeOf, isSealed, keys, length, n4type, +// hasOwnProperty, isExtensible, isFrozen, isPrototypeOf, isSealed, keys, length, n4type, // preventExtensions, propertyIsEnumerable, prototype, prototype, seal, toLocaleString, // toString, valueOf // --- diff --git a/tests/org.eclipse.n4js.xpect.tests/xpect-tests/scopingSimple/predefined_properties.n4js.xt b/tests/org.eclipse.n4js.xpect.tests/xpect-tests/scopingSimple/predefined_properties.n4js.xt index d26502898c..933b491b83 100644 --- a/tests/org.eclipse.n4js.xpect.tests/xpect-tests/scopingSimple/predefined_properties.n4js.xt +++ b/tests/org.eclipse.n4js.xpect.tests/xpect-tests/scopingSimple/predefined_properties.n4js.xt @@ -27,7 +27,7 @@ myConstr = myObject1.constructor var myFunction : Function = function myFun(a : number, b : number) { return a + b; } /* XPECT scope at 'myFunction.|apply' --- - __proto__, apply, arguments, bind, call, constructor, hasOwnProperty, isPrototypeOf, + __proto__, apply, arguments, bind, call, caller, constructor, hasOwnProperty, isPrototypeOf, length, propertyIsEnumerable, prototype, toLocaleString, toString, valueOf --- */ var myResult : any = myFunction.apply(null, [1, 2]) @@ -35,25 +35,25 @@ var myResult : any = myFunction.apply(null, [1, 2]) var myArray : Array = new Array() /* XPECT scope at 'myArray.|concat' --- #iterator, __proto__, concat, constructor, every, filter, forEach, hasOwnProperty, - indexOf, isPrototypeOf, join, lastIndexOf, length, length, map, pop, + indexOf, isPrototypeOf, join, lastIndexOf, length, map, pop, propertyIsEnumerable, push, reduce, reduceRight, reverse, shift, slice, some, sort, splice, toLocaleString, toString, unshift, valueOf --- */ var myFilledArray : Array = myArray.concat("1", "2", "3") /* XPECT scope at 'Array.|isArray' --- - __proto__, apply, arguments, bind, call, constructor, create, defineProperties, + __proto__, apply, arguments, bind, call, caller, constructor, create, defineProperties, defineProperty, freeze, getOwnPropertyDescriptor, getOwnPropertyNames, getPrototypeOf, - hasOwnProperty, is, isArray, isExtensible, isFrozen, isPrototypeOf, isSealed, keys, length, + hasOwnProperty, isArray, isExtensible, isFrozen, isPrototypeOf, isSealed, keys, length, preventExtensions, propertyIsEnumerable, prototype, prototype, seal, toLocaleString, toString, valueOf --- */ var myIsArray : boolean = Array.isArray(myFilledArray) /* XPECT scope at 'String.|fromCharCode' --- - __proto__, apply, arguments, bind, call, constructor, create, defineProperties, + __proto__, apply, arguments, bind, call, caller, constructor, create, defineProperties, defineProperty, freeze, fromCharCode, getOwnPropertyDescriptor, getOwnPropertyNames, - getPrototypeOf, hasOwnProperty, is, isExtensible, isFrozen, isPrototypeOf, isSealed, keys, + getPrototypeOf, hasOwnProperty, isExtensible, isFrozen, isPrototypeOf, isSealed, keys, length, preventExtensions, propertyIsEnumerable, prototype, prototype, seal, toLocaleString, toString, valueOf --- */ @@ -61,7 +61,7 @@ var myString : string = String.fromCharCode(10) /* XPECT scope at 'myString.|charAt' --- #iterator, __proto__, charAt, charCodeAt, concat, constructor, hasOwnProperty, indexOf, isPrototypeOf, lastIndexOf, length, localeCompare, match, propertyIsEnumerable, - replace, search, slice, split, substring, toLocaleLowerCase, toLocaleString, + replace, search, slice, split, substr, substring, toLocaleLowerCase, toLocaleString, toLocaleUpperCase, toLowerCase, toString, toUpperCase, trim, valueOf --- */ var myCharacterFound : string = myString.charAt(0) @@ -69,15 +69,15 @@ var myCharacterFound : string = myString.charAt(0) /* XPECT scope at 'myCharacterFound.|charAt' --- #iterator, __proto__, charAt, charCodeAt, concat, constructor, hasOwnProperty, indexOf, isPrototypeOf, lastIndexOf, length, localeCompare, match, propertyIsEnumerable, - replace, search, slice, split, substring, toLocaleLowerCase, toLocaleString, + replace, search, slice, split, substr, substring, toLocaleLowerCase, toLocaleString, toLocaleUpperCase, toLowerCase, toString, toUpperCase, trim, valueOf --- */ myCharacterFound = myCharacterFound.charAt(0) /* XPECT scope at 'String.|fromCharCode' --- -__proto__, apply, arguments, bind, call, constructor, create, defineProperties, +__proto__, apply, arguments, bind, call, caller, constructor, create, defineProperties, defineProperty, freeze, fromCharCode, getOwnPropertyDescriptor, getOwnPropertyNames, -getPrototypeOf, hasOwnProperty, is, isExtensible, isFrozen, isPrototypeOf, isSealed, keys, +getPrototypeOf, hasOwnProperty, isExtensible, isFrozen, isPrototypeOf, isSealed, keys, length, preventExtensions, propertyIsEnumerable, prototype, prototype, seal, toLocaleString, toString, valueOf --- */ @@ -106,8 +106,8 @@ var myFixedNumber : string = myMaxValue.toFixed() /* XPECT scope at 'Number.|MAX_VALUE' --- __proto__, MAX_VALUE, MIN_VALUE, NEGATIVE_INFINITY, NaN, POSITIVE_INFINITY, apply, -arguments, bind, call, constructor, create, defineProperties, defineProperty, freeze, -getOwnPropertyDescriptor, getOwnPropertyNames, getPrototypeOf, hasOwnProperty, is, isExtensible, +arguments, bind, call, caller, constructor, create, defineProperties, defineProperty, freeze, +getOwnPropertyDescriptor, getOwnPropertyNames, getPrototypeOf, hasOwnProperty, isExtensible, isFrozen, isPrototypeOf, isSealed, keys, length, preventExtensions, propertyIsEnumerable, prototype, prototype, seal, toLocaleString, toString, valueOf --- */ @@ -115,9 +115,9 @@ Number.MAX_VALUE /* XPECT scope at 'Math.|abs' --- __proto__, E, LN10, LN2, LOG10E, LOG2E, PI, SQRT1_2, SQRT2, abs, acos, apply, arguments, - asin, atan, atan2, bind, call, ceil, constructor, cos, create, defineProperties, + asin, atan, atan2, bind, call, caller, ceil, constructor, cos, create, defineProperties, defineProperty, exp, floor, freeze, getOwnPropertyDescriptor, getOwnPropertyNames, - getPrototypeOf, hasOwnProperty, is, isExtensible, isFrozen, isPrototypeOf, isSealed, keys, + getPrototypeOf, hasOwnProperty, isExtensible, isFrozen, isPrototypeOf, isSealed, keys, length, log, max, min, pow, preventExtensions, propertyIsEnumerable, prototype, prototype, random, round, seal, sin, sqrt, tan, toLocaleString, toString, valueOf --- */ @@ -146,9 +146,9 @@ var myDate : Date = new Date(Date.now()) var myDateAsNumber : number = myDate.getDate() /* XPECT scope at 'Date.|parse' --- -__proto__, UTC, apply, arguments, bind, call, constructor, create, defineProperties, +__proto__, UTC, apply, arguments, bind, call, caller, constructor, create, defineProperties, defineProperty, freeze, getOwnPropertyDescriptor, getOwnPropertyNames, getPrototypeOf, -hasOwnProperty, is, isExtensible, isFrozen, isPrototypeOf, isSealed, keys, length, now, parse, +hasOwnProperty, isExtensible, isFrozen, isPrototypeOf, isSealed, keys, length, now, parse, preventExtensions, propertyIsEnumerable, prototype, prototype, seal, toLocaleString, toString, valueOf --- */ @@ -156,7 +156,7 @@ Date.parse("04.02.2014") var myRegexp : RegExp = new RegExp() /* XPECT scope at 'myRegexp.|global' --- - __proto__, constructor, exec, global, hasOwnProperty, ignoreCase, isPrototypeOf, + __proto__, constructor, compile, exec, global, hasOwnProperty, ignoreCase, isPrototypeOf, lastIndex, multiline, propertyIsEnumerable, source, test, toLocaleString, toString, valueOf --- */ @@ -164,57 +164,57 @@ myRegexp.global var myError : Error = new Error() /* XPECT scope at 'myError.|message' --- - __proto__, constructor, hasOwnProperty, isPrototypeOf, message, name, + __proto__, constructor, hasOwnProperty, isPrototypeOf, message, name, stack, propertyIsEnumerable, toLocaleString, toString, valueOf --- */ var myErrorMessage : string = myError.message var myEvalError : EvalError = new EvalError() /* XPECT scope at 'myEvalError.|message' --- - __proto__, constructor, hasOwnProperty, isPrototypeOf, message, name, + __proto__, constructor, hasOwnProperty, isPrototypeOf, message, name, stack, propertyIsEnumerable, toLocaleString, toString, valueOf --- */ var myEvalErrorMessage : string = myEvalError.message var myRangeError : RangeError = new RangeError() /* XPECT scope at 'myRangeError.|message' --- - __proto__, constructor, hasOwnProperty, isPrototypeOf, message, name, + __proto__, constructor, hasOwnProperty, isPrototypeOf, message, name, stack, propertyIsEnumerable, toLocaleString, toString, valueOf --- */ var myRangeErrorMessage : string = myRangeError.message var myReferenceError : ReferenceError = new ReferenceError() /* XPECT scope at 'myReferenceError.|message' --- - __proto__, constructor, hasOwnProperty, isPrototypeOf, message, name, + __proto__, constructor, hasOwnProperty, isPrototypeOf, message, name, stack, propertyIsEnumerable, toLocaleString, toString, valueOf --- */ var myReferenceErrorMessage : string = myReferenceError.message var mySyntaxError : SyntaxError = new SyntaxError() /* XPECT scope at 'mySyntaxError.|message' --- - __proto__, constructor, hasOwnProperty, isPrototypeOf, message, name, + __proto__, constructor, hasOwnProperty, isPrototypeOf, message, name, stack, propertyIsEnumerable, toLocaleString, toString, valueOf --- */ var mySyntaxErrorMessage : string = mySyntaxError.message var myTypeError : TypeError = new TypeError() /* XPECT scope at 'myTypeError.|message' --- - __proto__, constructor, hasOwnProperty, isPrototypeOf, message, name, + __proto__, constructor, hasOwnProperty, isPrototypeOf, message, name, stack, propertyIsEnumerable, toLocaleString, toString, valueOf --- */ var myTypeErrorMessage : string = myTypeError.message var myUriError : URIError = new URIError() /* XPECT scope at 'myUriError.|message' --- - __proto__, constructor, hasOwnProperty, isPrototypeOf, message, name, + __proto__, constructor, hasOwnProperty, isPrototypeOf, message, name, stack, propertyIsEnumerable, toLocaleString, toString, valueOf --- */ var myUriErrorMessage : string = myUriError.message /* XPECT scope at 'JSON.|parse("bla")' --- - __proto__, apply, arguments, bind, call, constructor, create, defineProperties, + __proto__, apply, arguments, bind, call, caller, constructor, create, defineProperties, defineProperty, freeze, getOwnPropertyDescriptor, getOwnPropertyNames, getPrototypeOf, - hasOwnProperty, is, isExtensible, isFrozen, isPrototypeOf, isSealed, keys, length, parse, + hasOwnProperty, isExtensible, isFrozen, isPrototypeOf, isSealed, keys, length, parse, preventExtensions, propertyIsEnumerable, prototype, prototype, seal, stringify, toLocaleString, toString, valueOf --- */ @@ -227,9 +227,9 @@ var someJson : JSON; someJson.constructor /* XPECT scope at 'JSON.|parse' --- -__proto__, apply, arguments, bind, call, constructor, create, defineProperties, +__proto__, apply, arguments, bind, call, caller, constructor, create, defineProperties, defineProperty, freeze, getOwnPropertyDescriptor, getOwnPropertyNames, getPrototypeOf, -hasOwnProperty, is, isExtensible, isFrozen, isPrototypeOf, isSealed, keys, length, parse, +hasOwnProperty, isExtensible, isFrozen, isPrototypeOf, isSealed, keys, length, parse, preventExtensions, propertyIsEnumerable, prototype, prototype, seal, stringify, toLocaleString, toString, valueOf --- */ @@ -241,7 +241,7 @@ var myTypeNamePrimitive : typeName = "MyType" /* XPECT scope at 'myTypeNamePrimitive.|toString' --- #iterator, __proto__, charAt, charCodeAt, concat, constructor, hasOwnProperty, indexOf, isPrototypeOf, lastIndexOf, length, localeCompare, match, propertyIsEnumerable, - replace, search, slice, split, substring, toLocaleLowerCase, toLocaleString, + replace, search, slice, split, substr, substring, toLocaleLowerCase, toLocaleString, toLocaleUpperCase, toLowerCase, toString, toUpperCase, trim, valueOf --- */ var myTypeNameStr = myTypeNamePrimitive.toString() @@ -252,7 +252,7 @@ var myPathSelectorPrimitive : pathSelector = "a/b/c[x]" /* XPECT scope at 'myPathSelectorPrimitive.|toString' --- #iterator, __proto__, charAt, charCodeAt, concat, constructor, hasOwnProperty, indexOf, isPrototypeOf, lastIndexOf, length, localeCompare, match, propertyIsEnumerable, - replace, search, slice, split, substring, toLocaleLowerCase, toLocaleString, + replace, search, slice, split, substr, substring, toLocaleLowerCase, toLocaleString, toLocaleUpperCase, toLowerCase, toString, toUpperCase, trim, valueOf --- */ var myPathSelectorStr = myPathSelectorPrimitive.toString() @@ -263,7 +263,7 @@ var myI18NKeyPrimitive : i18nKey = "bundle.message" /* XPECT scope at 'myI18NKeyPrimitive.|toString' --- #iterator, __proto__, charAt, charCodeAt, concat, constructor, hasOwnProperty, indexOf, isPrototypeOf, lastIndexOf, length, localeCompare, match, propertyIsEnumerable, - replace, search, slice, split, substring, toLocaleLowerCase, toLocaleString, + replace, search, slice, split, substr, substring, toLocaleLowerCase, toLocaleString, toLocaleUpperCase, toLowerCase, toString, toUpperCase, trim, valueOf --- */ var myI18NKeyStr = myI18NKeyPrimitive.toString() @@ -277,9 +277,9 @@ var myN4Object : N4Object = new N4Object() var myN4ObjectStr = myN4Object.toString() /* XPECT scope at 'N4Object.|isFrozen' --- -__proto__, apply, arguments, bind, call, constructor, create, defineProperties, +__proto__, apply, arguments, bind, call, caller, constructor, create, defineProperties, defineProperty, freeze, getOwnPropertyDescriptor, getOwnPropertyNames, getPrototypeOf, -hasOwnProperty, is, isExtensible, isFrozen, isPrototypeOf, isSealed, keys, length, n4type, +hasOwnProperty, isExtensible, isFrozen, isPrototypeOf, isSealed, keys, length, n4type, preventExtensions, propertyIsEnumerable, prototype, prototype, seal, toLocaleString, toString, valueOf --- */ diff --git a/tests/org.eclipse.n4js.xpect.tests/xt-tests/polyfill/ref_to_filled_type_scoping.n4js.xt b/tests/org.eclipse.n4js.xpect.tests/xt-tests/polyfill/ref_to_filled_type_scoping.n4js.xt index 791a95c3cd..9df8bb4d16 100644 --- a/tests/org.eclipse.n4js.xpect.tests/xt-tests/polyfill/ref_to_filled_type_scoping.n4js.xt +++ b/tests/org.eclipse.n4js.xpect.tests/xt-tests/polyfill/ref_to_filled_type_scoping.n4js.xt @@ -28,14 +28,14 @@ @Polyfill export external public class Array extends Array { - // XPECT linkedFragment at 'Array' --> n4scheme:/builtin_js.n4jsd#/1/@topLevelTypes.2 + // XPECT linkedFragment at 'Array' --> n4scheme:/builtin_js.n4jsd#/1/@topLevelTypes.40 member: Array; // correctly scoped to Array in builtin_js.n4jsd } -// XPECT linkedFragment at 'Array' --> n4scheme:/builtin_js.n4jsd#/1/@topLevelTypes.2 +// XPECT linkedFragment at 'Array' --> n4scheme:/builtin_js.n4jsd#/1/@topLevelTypes.40 const K : Array = null; class SomeClass { - // XPECT linkedFragment at 'Array' --> n4scheme:/builtin_js.n4jsd#/1/@topLevelTypes.2 + // XPECT linkedFragment at 'Array' --> n4scheme:/builtin_js.n4jsd#/1/@topLevelTypes.40 someMethod(): Array; // make sure: not incorrectly scoped to Array in this module } diff --git a/tests/org.eclipse.n4js.xpect.tests/xt-tests/scoping/Sister.n4js.xt b/tests/org.eclipse.n4js.xpect.tests/xt-tests/scoping/Sister.n4js.xt index 02f4b9f89d..58fa499bee 100644 --- a/tests/org.eclipse.n4js.xpect.tests/xt-tests/scoping/Sister.n4js.xt +++ b/tests/org.eclipse.n4js.xpect.tests/xt-tests/scoping/Sister.n4js.xt @@ -40,20 +40,32 @@ import { Child } from "scoping/Child"; export class Sister { /* XPECT scope at ': <|>Brother' --- -Array, Array2, Array3, Array4, Array5, Array6, Array7, Array8, Array9, -AsyncGenerator, AsyncIterable, AsyncIterator, Boolean, Brother, Child, Date, Error, EvalError, Function, Generator, -IArguments, +Array, Array2, Array3, Array4, Array5, Array6, Array7, Array8, Array9, +ArrayBuffer, ArrayBufferConstructor, ArrayBufferLike, ArrayBufferTypes, ArrayBufferView, ArrayConstructor, ArrayLike, +AsyncGenerator, AsyncIterable, AsyncIterator, Boolean, BooleanConstructor, Brother, Child, ConcatArray, DataView, DataViewConstructor, +Date, DateConstructor, Error, ErrorConstructor, EvalError, EvalErrorConstructor, +Float32Array, Float32ArrayConstructor, Float64Array, Float64ArrayConstructor, +Function, FunctionConstructor, Generator, +IArguments, ImportAssertions, ImportCallOptions, ImportMeta, +Int16Array, Int16ArrayConstructor, Int32Array, Int32ArrayConstructor, Int8Array, Int8ArrayConstructor, Iterable, Iterable2, Iterable3, Iterable4, Iterable5, Iterable6, Iterable7, Iterable8, Iterable9, Iterator, IteratorEntry, JSON, Math, -N4Accessor, N4Annotation, N4Class, N4Classifier, N4DataField, N4Element, N4Enum, -N4EnumType, N4Interface, N4Member, N4Method, N4NamedElement, N4Object, N4Provider, -N4NumberBasedEnum, N4StringBasedEnum, -N4Type, N4ApiNotImplementedError, -Number, Object, Promise, RangeError, ReferenceError, RegExp, Sister, String, Symbol, -SyntaxError, TypeError, URIError, any, boolean, console, i18nKey, number, int, pathSelector, -scoping.Brother.Brother, scoping.Child.Child, scoping.Sister.Sister, string, symbol, typeName, +N4Accessor, N4Annotation, N4ApiNotImplementedError, N4Class, N4Classifier, N4DataField, N4Element, +N4Enum, N4EnumType, N4Interface, N4Member, N4Method, N4NamedElement, N4NumberBasedEnum, +N4Object, N4Provider, N4StringBasedEnum, +N4Type, +Number, NumberConstructor, Object, ObjectConstructor, Promise, PromiseConstructor, PromiseLike, +PropertyDescriptor, PropertyDescriptorMap, PropertyKey, RangeError, RangeErrorConstructor, ReadonlyArray, +ReferenceError, ReferenceErrorConstructor, RegExp, RegExpConstructor, RegExpExecArray, RegExpMatchArray, +Sister, String, StringConstructor, Symbol, +SyntaxError, SyntaxErrorConstructor, ThisType, TypeError, TypeErrorConstructor, TypedPropertyDescriptor, +URIError, URIErrorConstructor, +Uint16Array, Uint16ArrayConstructor, Uint32Array, Uint32ArrayConstructor, Uint8Array, Uint8ArrayConstructor, Uint8ClampedArray, Uint8ClampedArrayConstructor, +any, boolean, console, i18nKey, int, number, pathSelector, +scoping.Brother.Brother, scoping.Child.Child, scoping.Sister.Sister, +string, symbol, typeName, undefined, void ---*/ project getBrother() : Brother { return null; } diff --git a/tests/org.eclipse.n4js.xpect.tests/xt-tests/scoping/enums/EnumUser.n4js.xt b/tests/org.eclipse.n4js.xpect.tests/xt-tests/scoping/enums/EnumUser.n4js.xt index 7c9d61081d..878c3aae3e 100644 --- a/tests/org.eclipse.n4js.xpect.tests/xt-tests/scoping/enums/EnumUser.n4js.xt +++ b/tests/org.eclipse.n4js.xpect.tests/xt-tests/scoping/enums/EnumUser.n4js.xt @@ -40,7 +40,7 @@ import { MyEnum } from "scoping/enums/MyEnum" toLocaleString, toString, valueOf, create, defineProperties, defineProperty, freeze, getOwnPropertyDescriptor, getOwnPropertyNames, - getPrototypeOf, is, isExtensible, + getPrototypeOf, isExtensible, isFrozen, isSealed, keys, preventExtensions, prototype, seal --- */ diff --git a/tests/org.eclipse.n4js.xpect.tests/xt-tests/scoping/n4jsx/ClassComponentDescriptions.n4jsx.xt b/tests/org.eclipse.n4js.xpect.tests/xt-tests/scoping/n4jsx/ClassComponentDescriptions.n4jsx.xt index 43d26feb26..6c7a60e691 100644 --- a/tests/org.eclipse.n4js.xpect.tests/xt-tests/scoping/n4jsx/ClassComponentDescriptions.n4jsx.xt +++ b/tests/org.eclipse.n4js.xpect.tests/xt-tests/scoping/n4jsx/ClassComponentDescriptions.n4jsx.xt @@ -53,20 +53,27 @@ export public class MyComponent extends React.Component<~React.ComponentProps wi public render() : React.ReactElement{ const constText = "some text"; /* XPECT scope at 'Lower<|>Component' --- - Array, Array2, Array3, Array4, Array5, Array6, Array7, Array8, Array9, - AsyncGenerator, AsyncIterable, AsyncIterator, Boolean, Date, Error, EvalError, - Function, Generator, IArguments, Infinity, Iterable, Iterable2, Iterable3, Iterable4, - Iterable5, Iterable6, Iterable7, Iterable8, Iterable9, Iterator, IteratorEntry, JSON, + Array, Array2, Array3, Array4, Array5, Array6, Array7, Array8, Array9, + ArrayBuffer, ArrayBufferConstructor, ArrayBufferLike, ArrayBufferTypes, ArrayBufferView, ArrayConstructor, ArrayLike, + AsyncGenerator, AsyncIterable, AsyncIterator, Boolean, BooleanConstructor, ConcatArray, DataView, DataViewConstructor, + Date, DateConstructor, Error, ErrorConstructor, EvalError, EvalErrorConstructor, + Float32Array, Float32ArrayConstructor, Float64Array, Float64ArrayConstructor, + Function, FunctionConstructor, Generator, IArguments, ImportAssertions, ImportCallOptions, ImportMeta, Infinity, + Int16Array, Int16ArrayConstructor, Int32Array, Int32ArrayConstructor, Int8Array, Int8ArrayConstructor, + Iterable, Iterable2, Iterable3, Iterable4, Iterable5, Iterable6, Iterable7, Iterable8, Iterable9, + Iterator, IteratorEntry, JSON, LowerComponent, Math, MyComponent, N4Accessor, N4Annotation, N4ApiNotImplementedError, N4Class, N4Classifier, N4DataField, N4Element, - N4Enum, N4EnumType, N4Interface, N4Member, N4Method, N4NamedElement, N4Object, - N4Provider, N4NumberBasedEnum, N4StringBasedEnum, N4Type, NaN, Number, Object, Promise, - RangeError, React, ReferenceError, RegExp, - String, Symbol, SyntaxError, TypeError, URIError, + N4Enum, N4EnumType, N4Interface, N4Member, N4Method, N4NamedElement, N4NumberBasedEnum, N4Object, + N4Provider, N4StringBasedEnum, N4Type, NaN, Number, NumberConstructor, Object, ObjectConstructor, Promise, PromiseConstructor, PromiseLike, PropertyDescriptor, PropertyDescriptorMap, PropertyKey, + RangeError, RangeErrorConstructor, React, ReadonlyArray, ReferenceError, ReferenceErrorConstructor, RegExp, RegExpConstructor, RegExpExecArray, RegExpMatchArray, + String, StringConstructor, Symbol, SyntaxError, SyntaxErrorConstructor, ThisType, TypeError, TypeErrorConstructor, TypedPropertyDescriptor, + URIError, URIErrorConstructor, + Uint16Array, Uint16ArrayConstructor, Uint32Array, Uint32ArrayConstructor, Uint8Array, Uint8ArrayConstructor, Uint8ClampedArray, Uint8ClampedArrayConstructor, __proto__, arguments, console, constText, constructor, decodeURI, decodeURIComponent, encodeURI, encodeURIComponent, eval, hasOwnProperty, - index.Component, index.ComponentProps, index.ReactElement, index.Fragment, index.PropConstraint, - index.PropType, index.PropTypes, index.PureComponent, index.cloneElement, index.createElement, + index.Component, index.ComponentProps, index.Fragment, index.PropConstraint, + index.PropType, index.PropTypes, index.PureComponent, index.ReactElement, index.cloneElement, index.createElement, index.isValidElement, index.renderToStaticMarkup, index.renderToString, isFinite, isNaN, isPrototypeOf, null, parseFloat, parseInt, propertyIsEnumerable, scoping.ClassComponentDescriptions.LowerComponent, diff --git a/tests/org.eclipse.n4js.xpect.tests/xt-tests/scoping/object_literals.n4js.xt b/tests/org.eclipse.n4js.xpect.tests/xt-tests/scoping/object_literals.n4js.xt index 11eaa1569e..006c4cccdf 100644 --- a/tests/org.eclipse.n4js.xpect.tests/xt-tests/scoping/object_literals.n4js.xt +++ b/tests/org.eclipse.n4js.xpect.tests/xt-tests/scoping/object_literals.n4js.xt @@ -27,18 +27,25 @@ var myObjectLiteral = { /* XPECT scope at '<|>any name' --- -Array, Array2, Array3, Array4, Array5, Array6, Array7, Array8, Array9, -AsyncGenerator, AsyncIterable, AsyncIterator, Boolean, Date, Error, EvalError, Function, Generator, -IArguments, +Array, Array2, Array3, Array4, Array5, Array6, Array7, Array8, Array9, +ArrayBuffer, ArrayBufferConstructor, ArrayBufferLike, ArrayBufferTypes, ArrayBufferView, ArrayConstructor, ArrayLike, +AsyncGenerator, AsyncIterable, AsyncIterator, Boolean, BooleanConstructor, ConcatArray, DataView, DataViewConstructor, +Date, DateConstructor, Error, ErrorConstructor, EvalError, EvalErrorConstructor, +Float32Array, Float32ArrayConstructor, Float64Array, Float64ArrayConstructor, Function, FunctionConstructor, Generator, +IArguments, ImportAssertions, ImportCallOptions, ImportMeta, +Int16Array, Int16ArrayConstructor, Int32Array, Int32ArrayConstructor, Int8Array, Int8ArrayConstructor, Iterable, Iterable2, Iterable3, Iterable4, Iterable5, Iterable6, Iterable7, Iterable8, Iterable9, Iterator, IteratorEntry, JSON, Math, -N4Accessor, N4Annotation, N4Class, N4Classifier, N4DataField, N4Element, N4Enum, N4EnumType, -N4Interface, N4Member, N4Method, N4NamedElement, N4Object, N4Provider, N4NumberBasedEnum, N4StringBasedEnum, -N4Type, N4ApiNotImplementedError, -Number, Object, Promise, RangeError, ReferenceError, RegExp, String, Symbol, SyntaxError, TypeError, URIError, -any, undefined, boolean, console, i18nKey, number, int, pathSelector, string, symbol, typeName +N4Accessor, N4Annotation, N4ApiNotImplementedError, N4Class, N4Classifier, N4DataField, N4Element, N4Enum, N4EnumType, +N4Interface, N4Member, N4Method, N4NamedElement, N4NumberBasedEnum, N4Object, N4Provider, N4StringBasedEnum, N4Type, +Number, NumberConstructor, Object, ObjectConstructor, Promise, PromiseConstructor, PromiseLike, +PropertyDescriptor, PropertyDescriptorMap, PropertyKey, RangeError, RangeErrorConstructor, ReadonlyArray, ReferenceError, ReferenceErrorConstructor, +RegExp, RegExpConstructor, RegExpExecArray, RegExpMatchArray, +String, StringConstructor, Symbol, SyntaxError, SyntaxErrorConstructor, ThisType, TypeError, TypeErrorConstructor, TypedPropertyDescriptor, +URIError, URIErrorConstructor, Uint16Array, Uint16ArrayConstructor, Uint32Array, Uint32ArrayConstructor, Uint8Array, Uint8ArrayConstructor, Uint8ClampedArray, Uint8ClampedArrayConstructor, +any, boolean, console, i18nKey, int, number, pathSelector, string, symbol, typeName, undefined ---*/ any name: "o", complex: function() { diff --git a/version.json b/version.json index 1aa022039c..9bf5ccba45 100644 --- a/version.json +++ b/version.json @@ -1,5 +1,5 @@ { "major": "0", - "minor": "28", + "minor": "29", "tag": "" } \ No newline at end of file