mirror of
https://github.com/cincheo/jsweet.git
synced 2025-12-15 07:19:22 +00:00
licensing and readme for new structure + candy generator
This commit is contained in:
parent
2a214cf999
commit
9af61ee45a
@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
|
||||
<wb-module deploy-name="jsweet">
|
||||
<wb-resource deploy-path="/" source-path="/src/main/java"/>
|
||||
<wb-resource deploy-path="/" source-path="/src/main/resources"/>
|
||||
</wb-module>
|
||||
</project-modules>
|
||||
@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<faceted-project>
|
||||
<runtime name="GlassFish 4"/>
|
||||
<installed facet="java" version="1.8"/>
|
||||
<installed facet="jst.utility" version="1.0"/>
|
||||
</faceted-project>
|
||||
203
LICENSE
203
LICENSE
@ -1,202 +1 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright {yyyy} {name of copyright owner}
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
Each project has its own licensing, we therefore invite you to check each one individually.
|
||||
|
||||
187
README.md
187
README.md
@ -1,183 +1,12 @@
|
||||
# JSweet: a Java to JavaScript transpiler [](https://travis-ci.org/cincheo/jsweet)
|
||||
# Welcome on the JSweet repository!
|
||||
|
||||
JSweet leverages TypeScript to write rich and responsive Web applications in Java through the use of JavaScript libraries and frameworks. With JSweet, Java programs are transpiled (source-to-source compiled) to TypeScript and JavaScript for being run in browsers, mobile Web views, or in Node.js.
|
||||
|
||||
* JSweet is safe and reliable. It provides web applications with type-checking and generates fully type-checked JavaScript programs. It stands on Oracle's Java Compiler (javac) and on Microsoft's TypeScript (tsc).
|
||||
* JSweet allows you to use your favorite JS library ([JSweet+Angular2](https://github.com/cincheo/jsweet-angular2-quickstart), [JSweet+threejs](https://github.com/cincheo/jsweet-examples-threejs), [IONIC/Cordova](https://github.com/lgrignon/jsweet-cordova-ionic-example), ...).
|
||||
* JSweet enables code sharing between server-side Java and client-side JavaScript. JSweet provides implementations for the core Java libraries for code sharing and legacy Java migration purpose.
|
||||
* JSweet is fast, lightweight and fully JavaScript-interoperable. The generated code is regular JavaScript code, which implies no overhead compared to JavaScript, and can directly interoperate with existing JavaScript programs and libraries.
|
||||
|
||||
How does it work? JSweet depends on well-typed descriptions of JavaScript APIs, so-called "candies", most of them being automatically generated from TypeScript definition files. These API descriptions in Java can be seen as headers (similarly to *.h header files in C) to bridge JavaSript libraries from Java. There are several sources of candies for existing libraries and you can easily build a candy for any library out there (see [more details](http://www.jsweet.org/jsweet-candies/)).
|
||||
|
||||
With JSweet, you take advantage of all the Java tooling (IDE's, Maven, ...) to program real JavaScript applications using the latest JavaScript libraries.
|
||||
|
||||
## Java -> TypeScript -> JavaScript
|
||||
|
||||
Here is a first taste of what you get by using JSweet. Consider this simple Java program:
|
||||
|
||||
```java
|
||||
package org.jsweet;
|
||||
|
||||
import static jsweet.dom.Globals.*;
|
||||
|
||||
/**
|
||||
* This is a very simple example that just shows an alert.
|
||||
*/
|
||||
public class HelloWorld {
|
||||
public static void main(String[] args) {
|
||||
alert("Hi there!");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Transpiling with JSweet gives the following TypeScript program:
|
||||
|
||||
```TypeScript
|
||||
namespace org.jsweet {
|
||||
/**
|
||||
* This is a very simple example that just shows an alert.
|
||||
*/
|
||||
export class HelloWorld {
|
||||
public static main(args : string[]) {
|
||||
alert("Hi there!");
|
||||
}
|
||||
}
|
||||
}
|
||||
org.jsweet.HelloWorld.main(null);
|
||||
```
|
||||
|
||||
Which in turn produces the following JavaScript output:
|
||||
|
||||
```JavaScript
|
||||
var org;
|
||||
(function (org) {
|
||||
var jsweet;
|
||||
(function (jsweet) {
|
||||
/**
|
||||
* This is a very simple example that just shows an alert.
|
||||
*/
|
||||
var HelloWorld = (function () {
|
||||
function HelloWorld() {
|
||||
}
|
||||
HelloWorld.main = function (args) {
|
||||
alert("Hi there!");
|
||||
};
|
||||
return HelloWorld;
|
||||
}());
|
||||
jsweet.HelloWorld = HelloWorld;
|
||||
})(jsweet = org.jsweet || (org.jsweet = {}));
|
||||
})(org || (org = {}));
|
||||
org.jsweet.HelloWorld.main(null);
|
||||
```
|
||||
|
||||
More with the [live sandbox](http://www.jsweet.org/jsweet-live-sandbox/).
|
||||
|
||||
## Features
|
||||
|
||||
- Full syntax mapping between Java and TypeScript, including classes, interfaces, functional types, union types, tuple types, object types, string types, and so on.
|
||||
- Extensive support of Java constructs and semantics added since [version 1.1.0](https://github.com/cincheo/jsweet/releases/tag/v1.1.0) (inner classes, anonymous classes, final fields, method overloading, instanceof operator, static initializers, ...).
|
||||
- *Over 1000 JavaScript libraries*, frameworks and plugins to write Web and Mobile HTML5 applications (JQuery, Underscore, Angular, Backbone, Cordova, Node.js, and much [more](http://www.jsweet.org/candies-snapshots/)).
|
||||
- A [Maven repository](http://repository.jsweet.org/artifactory) containing all the available libraries in Maven artifacts (a.k.a. candies).
|
||||
- Support for Java basic APIs as the [J4TS](https://github.com/cincheo/j4ts) candy (forked from the GWT's JRE emulation).
|
||||
- An [Eclipse plugin](https://github.com/cincheo/jsweet-eclipse-plugin) for easy installation and use.
|
||||
- A [Maven plugin](https://github.com/lgrignon/jsweet-maven-plugin) to use JSweet from any other IDE or from the command line.
|
||||
- A debug mode to enable Java code debugging within your favorite browser.
|
||||
- A set of nice [WEB/Mobile HTML5 examples](https://github.com/cincheo/jsweet-examples) to get started and get used to JSweet and the most common JavaScript APIs (even more examples in the Examples section).
|
||||
- Support for bundles to run the generated programs in the most simple way.
|
||||
- Support for JavaScript modules (commonjs, amd, umd). JSweet programs *can* run in a browser or in Node.js.
|
||||
- Support for various EcmaScript target versions (ES3 to ES6).
|
||||
- ...
|
||||
|
||||
For more details, go to the [language specifications](https://github.com/cincheo/jsweet/blob/master/doc/jsweet-language-specifications.md) ([PDF](https://github.com/cincheo/jsweet/raw/master/doc/jsweet-language-specifications.pdf)).
|
||||
|
||||
## Getting started
|
||||
|
||||
- Step 1: Install (or check that you have installed) [Git](https://git-scm.com/downloads), [Node.js](https://nodejs.org) and [Maven](https://maven.apache.org/) (commands `git`, `node`, `npm` and `mvn` should be in your path).
|
||||
- Step 2: Clone the [jsweet-quickstart](https://github.com/cincheo/jsweet-quickstart) project from Github:
|
||||
```
|
||||
> git clone https://github.com/cincheo/jsweet-quickstart.git
|
||||
```
|
||||
- Step 3: Run the transpiler to generate the JavaScript code:
|
||||
```
|
||||
> cd jsweet-quickstart
|
||||
> mvn generate-sources
|
||||
```
|
||||
- Step 4: Check out the result in your browser:
|
||||
```
|
||||
> firefox webapp/index.html
|
||||
```
|
||||
- Step 5: Edit the project and start programming:
|
||||
- Checkout the examples to see various use cases
|
||||
- Get access to hundreds of [libs (candies)](http://www.jsweet.org/jsweet-candies/)
|
||||
- Refer to the [language specifications](https://github.com/cincheo/jsweet/blob/master/doc/jsweet-language-specifications.md) to know more about programming with JSweet
|
||||
- Eclipse users: install the [Eclipse plugin](http://www.jsweet.org/eclipse-plugin/) to get inline error reporting, build-on-save, and easy configuration UI
|
||||
|
||||
More info at http://www.jsweet.org.
|
||||
|
||||
## Examples
|
||||
|
||||
- Simple examples illustrating the use of various frameworks in Java (jQuery, Underscore, Backbone, AngularJS, Knockout): https://github.com/cincheo/jsweet-examples
|
||||
- Simple examples illustrating the use of the Threejs framework in Java: https://github.com/cincheo/jsweet-examples-threejs)
|
||||
- Node.js + Socket.IO + AngularJS: https://github.com/lgrignon/jsweet-node-example
|
||||
- Some simple examples to get started with React.js: https://github.com/cincheo/jsweet-examples-react
|
||||
- JSweet JAX-RS server example (how to share a Java model between client and server): https://github.com/lgrignon/jsweet-jaxrs-server-example
|
||||
- JSweet Cordova / Polymer example: https://github.com/lgrignon/jsweet-cordova-polymer-example
|
||||
- JSweet Cordova / Ionic example: https://github.com/lgrignon/jsweet-cordova-ionic-example
|
||||
- JSweet Angular 2 example: https://github.com/cincheo/jsweet-angular2-quickstart
|
||||
- JSweet Angular 2 + PrimeNG: https://github.com/cincheo/jsweet-primeng-quickstart
|
||||
|
||||
## Tooling
|
||||
|
||||
- [Eclipse plugin](https://github.com/cincheo/jsweet-eclipse-plugin)
|
||||
- [Maven plugin](https://github.com/lgrignon/jsweet-maven-plugin)
|
||||
- [Gradle plugin](https://github.com/lgrignon/jsweet-gradle-plugin)
|
||||
|
||||
## News and more information
|
||||
|
||||
Most information is available on the http://www.jsweet.org. Developers, check out the [wiki](https://github.com/cincheo/jsweet/wiki).
|
||||
|
||||
## How to build
|
||||
|
||||
Prerequisites: `node` and `npm` executables must be in the path (https://nodejs.org). Note that there seem to be an issue with the `node` executable on some Unix-based machines, which should be fixed (see for instance: http://askubuntu.com/questions/235655/node-js-conflicts-sbin-node-vs-usr-bin-node).
|
||||
|
||||
To build the `jsweet-transpiler` jars (in the project's directory):
|
||||
|
||||
```
|
||||
> mvn package
|
||||
```
|
||||
|
||||
To install the `jsweet-transpiler` artifact in your local Maven repository:
|
||||
|
||||
```
|
||||
> mvn install
|
||||
```
|
||||
|
||||
Note that current JUnit tests launch a Node.js instance for each test and will be quite slow (this will be improved). In order to easily test some changes locally without having to run all the tests, use the following command:
|
||||
|
||||
```
|
||||
> mvn package -Dmaven.test.skip=true
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```
|
||||
> mvn install -Dmaven.test.skip=true
|
||||
```
|
||||
|
||||
To generate the markdown language specifications from the Latex source file with [Pandoc](http://pandoc.org/):
|
||||
|
||||
```
|
||||
> cd doc
|
||||
> pandoc -r latex -w markdown_github --base-header-level=2 -s --toc --number-sections -B header.md -o jsweet-language-specifications.md jsweet-language-specifications.tex
|
||||
```
|
||||
|
||||
Note that the following command will output the document in HTML:
|
||||
|
||||
```
|
||||
> pandoc -r latex -w html5 --base-header-level=3 -o jsweet-language-specifications.html jsweet-language-specifications.tex
|
||||
```
|
||||
Let us take you to the project you are looking for:
|
||||
* [JSweet transpiler](https://github.com/cincheo/jsweet/tree/master/jsweet-transpiler)
|
||||
* [JSweet documentation](https://github.com/cincheo/jsweet/tree/master/doc)
|
||||
* [JSweet core candy](https://github.com/cincheo/jsweet/tree/master/jsweet-core)
|
||||
* [JDK runtime for TypeScript](https://github.com/cincheo/jsweet/tree/master/j4ts)
|
||||
* [JSweet candy generator](https://github.com/cincheo/jsweet/tree/master/jsweet-candy-generator)
|
||||
|
||||
## License
|
||||
|
||||
JSweet is under the Apache 2.0 Open Source license.
|
||||
Each project has its own licensing, we therefore invite you to check each one individually.
|
||||
|
||||
|
||||
359
doc/LICENSE
Normal file
359
doc/LICENSE
Normal file
@ -0,0 +1,359 @@
|
||||
Creative Commons Legal Code
|
||||
|
||||
Attribution-ShareAlike 3.0 Unported
|
||||
|
||||
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
|
||||
LEGAL SERVICES. DISTRIBUTION OF THIS LICENSE DOES NOT CREATE AN
|
||||
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
|
||||
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
|
||||
REGARDING THE INFORMATION PROVIDED, AND DISCLAIMS LIABILITY FOR
|
||||
DAMAGES RESULTING FROM ITS USE.
|
||||
|
||||
License
|
||||
|
||||
THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE
|
||||
COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY
|
||||
COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS
|
||||
AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.
|
||||
|
||||
BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE
|
||||
TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY
|
||||
BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS
|
||||
CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND
|
||||
CONDITIONS.
|
||||
|
||||
1. Definitions
|
||||
|
||||
a. "Adaptation" means a work based upon the Work, or upon the Work and
|
||||
other pre-existing works, such as a translation, adaptation,
|
||||
derivative work, arrangement of music or other alterations of a
|
||||
literary or artistic work, or phonogram or performance and includes
|
||||
cinematographic adaptations or any other form in which the Work may be
|
||||
recast, transformed, or adapted including in any form recognizably
|
||||
derived from the original, except that a work that constitutes a
|
||||
Collection will not be considered an Adaptation for the purpose of
|
||||
this License. For the avoidance of doubt, where the Work is a musical
|
||||
work, performance or phonogram, the synchronization of the Work in
|
||||
timed-relation with a moving image ("synching") will be considered an
|
||||
Adaptation for the purpose of this License.
|
||||
b. "Collection" means a collection of literary or artistic works, such as
|
||||
encyclopedias and anthologies, or performances, phonograms or
|
||||
broadcasts, or other works or subject matter other than works listed
|
||||
in Section 1(f) below, which, by reason of the selection and
|
||||
arrangement of their contents, constitute intellectual creations, in
|
||||
which the Work is included in its entirety in unmodified form along
|
||||
with one or more other contributions, each constituting separate and
|
||||
independent works in themselves, which together are assembled into a
|
||||
collective whole. A work that constitutes a Collection will not be
|
||||
considered an Adaptation (as defined below) for the purposes of this
|
||||
License.
|
||||
c. "Creative Commons Compatible License" means a license that is listed
|
||||
at https://creativecommons.org/compatiblelicenses that has been
|
||||
approved by Creative Commons as being essentially equivalent to this
|
||||
License, including, at a minimum, because that license: (i) contains
|
||||
terms that have the same purpose, meaning and effect as the License
|
||||
Elements of this License; and, (ii) explicitly permits the relicensing
|
||||
of adaptations of works made available under that license under this
|
||||
License or a Creative Commons jurisdiction license with the same
|
||||
License Elements as this License.
|
||||
d. "Distribute" means to make available to the public the original and
|
||||
copies of the Work or Adaptation, as appropriate, through sale or
|
||||
other transfer of ownership.
|
||||
e. "License Elements" means the following high-level license attributes
|
||||
as selected by Licensor and indicated in the title of this License:
|
||||
Attribution, ShareAlike.
|
||||
f. "Licensor" means the individual, individuals, entity or entities that
|
||||
offer(s) the Work under the terms of this License.
|
||||
g. "Original Author" means, in the case of a literary or artistic work,
|
||||
the individual, individuals, entity or entities who created the Work
|
||||
or if no individual or entity can be identified, the publisher; and in
|
||||
addition (i) in the case of a performance the actors, singers,
|
||||
musicians, dancers, and other persons who act, sing, deliver, declaim,
|
||||
play in, interpret or otherwise perform literary or artistic works or
|
||||
expressions of folklore; (ii) in the case of a phonogram the producer
|
||||
being the person or legal entity who first fixes the sounds of a
|
||||
performance or other sounds; and, (iii) in the case of broadcasts, the
|
||||
organization that transmits the broadcast.
|
||||
h. "Work" means the literary and/or artistic work offered under the terms
|
||||
of this License including without limitation any production in the
|
||||
literary, scientific and artistic domain, whatever may be the mode or
|
||||
form of its expression including digital form, such as a book,
|
||||
pamphlet and other writing; a lecture, address, sermon or other work
|
||||
of the same nature; a dramatic or dramatico-musical work; a
|
||||
choreographic work or entertainment in dumb show; a musical
|
||||
composition with or without words; a cinematographic work to which are
|
||||
assimilated works expressed by a process analogous to cinematography;
|
||||
a work of drawing, painting, architecture, sculpture, engraving or
|
||||
lithography; a photographic work to which are assimilated works
|
||||
expressed by a process analogous to photography; a work of applied
|
||||
art; an illustration, map, plan, sketch or three-dimensional work
|
||||
relative to geography, topography, architecture or science; a
|
||||
performance; a broadcast; a phonogram; a compilation of data to the
|
||||
extent it is protected as a copyrightable work; or a work performed by
|
||||
a variety or circus performer to the extent it is not otherwise
|
||||
considered a literary or artistic work.
|
||||
i. "You" means an individual or entity exercising rights under this
|
||||
License who has not previously violated the terms of this License with
|
||||
respect to the Work, or who has received express permission from the
|
||||
Licensor to exercise rights under this License despite a previous
|
||||
violation.
|
||||
j. "Publicly Perform" means to perform public recitations of the Work and
|
||||
to communicate to the public those public recitations, by any means or
|
||||
process, including by wire or wireless means or public digital
|
||||
performances; to make available to the public Works in such a way that
|
||||
members of the public may access these Works from a place and at a
|
||||
place individually chosen by them; to perform the Work to the public
|
||||
by any means or process and the communication to the public of the
|
||||
performances of the Work, including by public digital performance; to
|
||||
broadcast and rebroadcast the Work by any means including signs,
|
||||
sounds or images.
|
||||
k. "Reproduce" means to make copies of the Work by any means including
|
||||
without limitation by sound or visual recordings and the right of
|
||||
fixation and reproducing fixations of the Work, including storage of a
|
||||
protected performance or phonogram in digital form or other electronic
|
||||
medium.
|
||||
|
||||
2. Fair Dealing Rights. Nothing in this License is intended to reduce,
|
||||
limit, or restrict any uses free from copyright or rights arising from
|
||||
limitations or exceptions that are provided for in connection with the
|
||||
copyright protection under copyright law or other applicable laws.
|
||||
|
||||
3. License Grant. Subject to the terms and conditions of this License,
|
||||
Licensor hereby grants You a worldwide, royalty-free, non-exclusive,
|
||||
perpetual (for the duration of the applicable copyright) license to
|
||||
exercise the rights in the Work as stated below:
|
||||
|
||||
a. to Reproduce the Work, to incorporate the Work into one or more
|
||||
Collections, and to Reproduce the Work as incorporated in the
|
||||
Collections;
|
||||
b. to create and Reproduce Adaptations provided that any such Adaptation,
|
||||
including any translation in any medium, takes reasonable steps to
|
||||
clearly label, demarcate or otherwise identify that changes were made
|
||||
to the original Work. For example, a translation could be marked "The
|
||||
original work was translated from English to Spanish," or a
|
||||
modification could indicate "The original work has been modified.";
|
||||
c. to Distribute and Publicly Perform the Work including as incorporated
|
||||
in Collections; and,
|
||||
d. to Distribute and Publicly Perform Adaptations.
|
||||
e. For the avoidance of doubt:
|
||||
|
||||
i. Non-waivable Compulsory License Schemes. In those jurisdictions in
|
||||
which the right to collect royalties through any statutory or
|
||||
compulsory licensing scheme cannot be waived, the Licensor
|
||||
reserves the exclusive right to collect such royalties for any
|
||||
exercise by You of the rights granted under this License;
|
||||
ii. Waivable Compulsory License Schemes. In those jurisdictions in
|
||||
which the right to collect royalties through any statutory or
|
||||
compulsory licensing scheme can be waived, the Licensor waives the
|
||||
exclusive right to collect such royalties for any exercise by You
|
||||
of the rights granted under this License; and,
|
||||
iii. Voluntary License Schemes. The Licensor waives the right to
|
||||
collect royalties, whether individually or, in the event that the
|
||||
Licensor is a member of a collecting society that administers
|
||||
voluntary licensing schemes, via that society, from any exercise
|
||||
by You of the rights granted under this License.
|
||||
|
||||
The above rights may be exercised in all media and formats whether now
|
||||
known or hereafter devised. The above rights include the right to make
|
||||
such modifications as are technically necessary to exercise the rights in
|
||||
other media and formats. Subject to Section 8(f), all rights not expressly
|
||||
granted by Licensor are hereby reserved.
|
||||
|
||||
4. Restrictions. The license granted in Section 3 above is expressly made
|
||||
subject to and limited by the following restrictions:
|
||||
|
||||
a. You may Distribute or Publicly Perform the Work only under the terms
|
||||
of this License. You must include a copy of, or the Uniform Resource
|
||||
Identifier (URI) for, this License with every copy of the Work You
|
||||
Distribute or Publicly Perform. You may not offer or impose any terms
|
||||
on the Work that restrict the terms of this License or the ability of
|
||||
the recipient of the Work to exercise the rights granted to that
|
||||
recipient under the terms of the License. You may not sublicense the
|
||||
Work. You must keep intact all notices that refer to this License and
|
||||
to the disclaimer of warranties with every copy of the Work You
|
||||
Distribute or Publicly Perform. When You Distribute or Publicly
|
||||
Perform the Work, You may not impose any effective technological
|
||||
measures on the Work that restrict the ability of a recipient of the
|
||||
Work from You to exercise the rights granted to that recipient under
|
||||
the terms of the License. This Section 4(a) applies to the Work as
|
||||
incorporated in a Collection, but this does not require the Collection
|
||||
apart from the Work itself to be made subject to the terms of this
|
||||
License. If You create a Collection, upon notice from any Licensor You
|
||||
must, to the extent practicable, remove from the Collection any credit
|
||||
as required by Section 4(c), as requested. If You create an
|
||||
Adaptation, upon notice from any Licensor You must, to the extent
|
||||
practicable, remove from the Adaptation any credit as required by
|
||||
Section 4(c), as requested.
|
||||
b. You may Distribute or Publicly Perform an Adaptation only under the
|
||||
terms of: (i) this License; (ii) a later version of this License with
|
||||
the same License Elements as this License; (iii) a Creative Commons
|
||||
jurisdiction license (either this or a later license version) that
|
||||
contains the same License Elements as this License (e.g.,
|
||||
Attribution-ShareAlike 3.0 US)); (iv) a Creative Commons Compatible
|
||||
License. If you license the Adaptation under one of the licenses
|
||||
mentioned in (iv), you must comply with the terms of that license. If
|
||||
you license the Adaptation under the terms of any of the licenses
|
||||
mentioned in (i), (ii) or (iii) (the "Applicable License"), you must
|
||||
comply with the terms of the Applicable License generally and the
|
||||
following provisions: (I) You must include a copy of, or the URI for,
|
||||
the Applicable License with every copy of each Adaptation You
|
||||
Distribute or Publicly Perform; (II) You may not offer or impose any
|
||||
terms on the Adaptation that restrict the terms of the Applicable
|
||||
License or the ability of the recipient of the Adaptation to exercise
|
||||
the rights granted to that recipient under the terms of the Applicable
|
||||
License; (III) You must keep intact all notices that refer to the
|
||||
Applicable License and to the disclaimer of warranties with every copy
|
||||
of the Work as included in the Adaptation You Distribute or Publicly
|
||||
Perform; (IV) when You Distribute or Publicly Perform the Adaptation,
|
||||
You may not impose any effective technological measures on the
|
||||
Adaptation that restrict the ability of a recipient of the Adaptation
|
||||
from You to exercise the rights granted to that recipient under the
|
||||
terms of the Applicable License. This Section 4(b) applies to the
|
||||
Adaptation as incorporated in a Collection, but this does not require
|
||||
the Collection apart from the Adaptation itself to be made subject to
|
||||
the terms of the Applicable License.
|
||||
c. If You Distribute, or Publicly Perform the Work or any Adaptations or
|
||||
Collections, You must, unless a request has been made pursuant to
|
||||
Section 4(a), keep intact all copyright notices for the Work and
|
||||
provide, reasonable to the medium or means You are utilizing: (i) the
|
||||
name of the Original Author (or pseudonym, if applicable) if supplied,
|
||||
and/or if the Original Author and/or Licensor designate another party
|
||||
or parties (e.g., a sponsor institute, publishing entity, journal) for
|
||||
attribution ("Attribution Parties") in Licensor's copyright notice,
|
||||
terms of service or by other reasonable means, the name of such party
|
||||
or parties; (ii) the title of the Work if supplied; (iii) to the
|
||||
extent reasonably practicable, the URI, if any, that Licensor
|
||||
specifies to be associated with the Work, unless such URI does not
|
||||
refer to the copyright notice or licensing information for the Work;
|
||||
and (iv) , consistent with Ssection 3(b), in the case of an
|
||||
Adaptation, a credit identifying the use of the Work in the Adaptation
|
||||
(e.g., "French translation of the Work by Original Author," or
|
||||
"Screenplay based on original Work by Original Author"). The credit
|
||||
required by this Section 4(c) may be implemented in any reasonable
|
||||
manner; provided, however, that in the case of a Adaptation or
|
||||
Collection, at a minimum such credit will appear, if a credit for all
|
||||
contributing authors of the Adaptation or Collection appears, then as
|
||||
part of these credits and in a manner at least as prominent as the
|
||||
credits for the other contributing authors. For the avoidance of
|
||||
doubt, You may only use the credit required by this Section for the
|
||||
purpose of attribution in the manner set out above and, by exercising
|
||||
Your rights under this License, You may not implicitly or explicitly
|
||||
assert or imply any connection with, sponsorship or endorsement by the
|
||||
Original Author, Licensor and/or Attribution Parties, as appropriate,
|
||||
of You or Your use of the Work, without the separate, express prior
|
||||
written permission of the Original Author, Licensor and/or Attribution
|
||||
Parties.
|
||||
d. Except as otherwise agreed in writing by the Licensor or as may be
|
||||
otherwise permitted by applicable law, if You Reproduce, Distribute or
|
||||
Publicly Perform the Work either by itself or as part of any
|
||||
Adaptations or Collections, You must not distort, mutilate, modify or
|
||||
take other derogatory action in relation to the Work which would be
|
||||
prejudicial to the Original Author's honor or reputation. Licensor
|
||||
agrees that in those jurisdictions (e.g. Japan), in which any exercise
|
||||
of the right granted in Section 3(b) of this License (the right to
|
||||
make Adaptations) would be deemed to be a distortion, mutilation,
|
||||
modification or other derogatory action prejudicial to the Original
|
||||
Author's honor and reputation, the Licensor will waive or not assert,
|
||||
as appropriate, this Section, to the fullest extent permitted by the
|
||||
applicable national law, to enable You to reasonably exercise Your
|
||||
right under Section 3(b) of this License (right to make Adaptations)
|
||||
but not otherwise.
|
||||
|
||||
5. Representations, Warranties and Disclaimer
|
||||
|
||||
UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR
|
||||
OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY
|
||||
KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE,
|
||||
INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF
|
||||
LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS,
|
||||
WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION
|
||||
OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.
|
||||
|
||||
6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE
|
||||
LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR
|
||||
ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES
|
||||
ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS
|
||||
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
7. Termination
|
||||
|
||||
a. This License and the rights granted hereunder will terminate
|
||||
automatically upon any breach by You of the terms of this License.
|
||||
Individuals or entities who have received Adaptations or Collections
|
||||
from You under this License, however, will not have their licenses
|
||||
terminated provided such individuals or entities remain in full
|
||||
compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will
|
||||
survive any termination of this License.
|
||||
b. Subject to the above terms and conditions, the license granted here is
|
||||
perpetual (for the duration of the applicable copyright in the Work).
|
||||
Notwithstanding the above, Licensor reserves the right to release the
|
||||
Work under different license terms or to stop distributing the Work at
|
||||
any time; provided, however that any such election will not serve to
|
||||
withdraw this License (or any other license that has been, or is
|
||||
required to be, granted under the terms of this License), and this
|
||||
License will continue in full force and effect unless terminated as
|
||||
stated above.
|
||||
|
||||
8. Miscellaneous
|
||||
|
||||
a. Each time You Distribute or Publicly Perform the Work or a Collection,
|
||||
the Licensor offers to the recipient a license to the Work on the same
|
||||
terms and conditions as the license granted to You under this License.
|
||||
b. Each time You Distribute or Publicly Perform an Adaptation, Licensor
|
||||
offers to the recipient a license to the original Work on the same
|
||||
terms and conditions as the license granted to You under this License.
|
||||
c. If any provision of this License is invalid or unenforceable under
|
||||
applicable law, it shall not affect the validity or enforceability of
|
||||
the remainder of the terms of this License, and without further action
|
||||
by the parties to this agreement, such provision shall be reformed to
|
||||
the minimum extent necessary to make such provision valid and
|
||||
enforceable.
|
||||
d. No term or provision of this License shall be deemed waived and no
|
||||
breach consented to unless such waiver or consent shall be in writing
|
||||
and signed by the party to be charged with such waiver or consent.
|
||||
e. This License constitutes the entire agreement between the parties with
|
||||
respect to the Work licensed here. There are no understandings,
|
||||
agreements or representations with respect to the Work not specified
|
||||
here. Licensor shall not be bound by any additional provisions that
|
||||
may appear in any communication from You. This License may not be
|
||||
modified without the mutual written agreement of the Licensor and You.
|
||||
f. The rights granted under, and the subject matter referenced, in this
|
||||
License were drafted utilizing the terminology of the Berne Convention
|
||||
for the Protection of Literary and Artistic Works (as amended on
|
||||
September 28, 1979), the Rome Convention of 1961, the WIPO Copyright
|
||||
Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996
|
||||
and the Universal Copyright Convention (as revised on July 24, 1971).
|
||||
These rights and subject matter take effect in the relevant
|
||||
jurisdiction in which the License terms are sought to be enforced
|
||||
according to the corresponding provisions of the implementation of
|
||||
those treaty provisions in the applicable national law. If the
|
||||
standard suite of rights granted under applicable copyright law
|
||||
includes additional rights not granted under this License, such
|
||||
additional rights are deemed to be included in the License; this
|
||||
License is not intended to restrict the license of any rights under
|
||||
applicable law.
|
||||
|
||||
|
||||
Creative Commons Notice
|
||||
|
||||
Creative Commons is not a party to this License, and makes no warranty
|
||||
whatsoever in connection with the Work. Creative Commons will not be
|
||||
liable to You or any party on any legal theory for any damages
|
||||
whatsoever, including without limitation any general, special,
|
||||
incidental or consequential damages arising in connection to this
|
||||
license. Notwithstanding the foregoing two (2) sentences, if Creative
|
||||
Commons has expressly identified itself as the Licensor hereunder, it
|
||||
shall have all rights and obligations of Licensor.
|
||||
|
||||
Except for the limited purpose of indicating to the public that the
|
||||
Work is licensed under the CCPL, Creative Commons does not authorize
|
||||
the use by either party of the trademark "Creative Commons" or any
|
||||
related trademark or logo of Creative Commons without the prior
|
||||
written consent of Creative Commons. Any permitted use will be in
|
||||
compliance with Creative Commons' then-current trademark usage
|
||||
guidelines, as may be published on its website or otherwise made
|
||||
available upon request from time to time. For the avoidance of doubt,
|
||||
this trademark restriction does not form part of the License.
|
||||
|
||||
Creative Commons may be contacted at https://creativecommons.org/.
|
||||
8
jsweet-candy-generator/.gitignore
vendored
Normal file
8
jsweet-candy-generator/.gitignore
vendored
Normal file
@ -0,0 +1,8 @@
|
||||
/target/
|
||||
/bin/
|
||||
/.classpath
|
||||
/.project
|
||||
/.settings/
|
||||
/js/
|
||||
/.jsweet/
|
||||
typings
|
||||
26
jsweet-candy-generator/CONTRIBUTING.md
Normal file
26
jsweet-candy-generator/CONTRIBUTING.md
Normal file
@ -0,0 +1,26 @@
|
||||
|
||||
## What to contribute?
|
||||
|
||||
Check out the issues and [wiki](https://github.com/cincheo/jsweet/wiki) for bugs, sub-projects and features where your contributions could be useful.
|
||||
|
||||
## Your contributions
|
||||
|
||||
Your contributions are most welcome. Bugs and features should be first reported in the Github issues space, so that we all know who is working on what, and so that we avoid duplicate efforts.
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Bug fixes should come with the corresponding test(s) if possible.
|
||||
|
||||
### Features
|
||||
|
||||
Please make sure that contributed new features has been discussed thoroughly first (check out existing issues and the Wiki). It is important that they come with the appropriate test case(s) if possible.
|
||||
|
||||
|
||||
## Contribution License Agreement
|
||||
|
||||
By contributing through a pull request, you acknowledge that you fully own your Contribution and that you are legally entitled to make it available to the JSweet project under the terms and conditions of the Apache 2.0 license. This license implies that you grant the JSweet project, and those who receive the code directly or indirectly from the JSweet project, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the Contribution to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute your Contribution and such derivative works, and to sublicense any or all of the foregoing rights to third parties.
|
||||
|
||||
Your execution and/or acceptance of this agreement does not influence any of your right and title to use and distribute your own Contribution.
|
||||
|
||||
|
||||
|
||||
674
jsweet-candy-generator/LICENSE
Normal file
674
jsweet-candy-generator/LICENSE
Normal file
@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
2
jsweet-candy-generator/README.md
Normal file
2
jsweet-candy-generator/README.md
Normal file
@ -0,0 +1,2 @@
|
||||
# JSweet candy generator
|
||||
This tool is a helper to scaffold & package candy starting from a TypeScript definition file
|
||||
66
jsweet-candy-generator/build.xml
Normal file
66
jsweet-candy-generator/build.xml
Normal file
@ -0,0 +1,66 @@
|
||||
<project name="jsweet-def-translators" basedir="." default="install-toolsjar">
|
||||
|
||||
<property environment="env" />
|
||||
|
||||
<condition property="maven.bin" value="${env.MAVEN_HOME}\bin\mvn.bat" else="${env.MAVEN_HOME}/bin/mvn">
|
||||
<os family="winnt" />
|
||||
</condition>
|
||||
|
||||
<property name="maven.repository" value="${env.M2_HOME}/repository" />
|
||||
<property name="jflex.jar" value="${maven.repository}/de/jflex/jflex/1.3.5/jflex-1.3.5.jar" />
|
||||
<property name="java-cup.jar" value="${maven.repository}/edu/princeton/cup/java-cup/10k/java-cup-10k.jar" />
|
||||
<property name="commons-lang3.jar" value="${maven.repository}/org/apache/commons/commons-lang3/3.3.2/commons-lang3-3.3.2.jar" />
|
||||
<property name="jsweet-api.jar" value="${maven.repository}/org/jsweet/jsweet-api-bundle-frameworks/0.0.2-SNAPSHOT/jsweet-api-bundle-frameworks-0.0.2-SNAPSHOT.jar" />
|
||||
<property name="tools.jar" value="${maven.repository}/com/sun/tools/8/tools-8.jar" />
|
||||
|
||||
<target name="install-toolsjar">
|
||||
<property name="lib.path" value="${env.JAVA_HOME}/lib/tools.jar">
|
||||
</property>
|
||||
<echo>installing local tools.jar in local maven: ${lib.path}</echo>
|
||||
<echo>WARNING: this script requires that your JAVA_HOME environment variable points to the Java 8 JDK (not JRE)</echo>
|
||||
<echo>note that under Eclipse, you can locally set your JAVA_HOME variable in "External tools configuration -> Environment"</echo>
|
||||
<property name="lib.name" value="tools">
|
||||
</property>
|
||||
<property name="lib.version" value="8">
|
||||
</property>
|
||||
<exec executable="${maven.bin}" failonerror="true">
|
||||
<arg line="install:install-file -Dfile='${lib.path}' -DgroupId=com.sun -DartifactId=${lib.name} -Dpackaging=jar -Dversion=${lib.version}" />
|
||||
</exec>
|
||||
<echo>WARNING: a successful build does not necessarily mean that you installed the right version of tools.jar</echo>
|
||||
</target>
|
||||
|
||||
<target name="translate-defs">
|
||||
<java classname="org.cincheo.jsweet.input.typescriptdef.TypescriptDef2Java" fork="true">
|
||||
<arg value="tsdef" />
|
||||
<arg value="javadef" />
|
||||
<classpath>
|
||||
<pathelement path="./target/classes" />
|
||||
</classpath>
|
||||
</java>
|
||||
</target>
|
||||
|
||||
<target name="gen-parser">
|
||||
<echo>Generating TSDef API parser...</echo>
|
||||
<echo message="compile classpath: ${compile_classpath}" />
|
||||
<java classname="java_cup.Main" fork="true" failonerror="true" classpath="${compile_classpath}">
|
||||
<arg value="-expect" />
|
||||
<arg value="0" />
|
||||
<arg value="-package" />
|
||||
<arg value="org.jsweet.input.typescriptdef.parser" />
|
||||
<arg value="-parser" />
|
||||
<arg value="TypescriptDefParser" />
|
||||
<arg value="src/org/jsweet/input/typescriptdef/parser/typescriptdef.cup" />
|
||||
</java>
|
||||
<move file="TypescriptDefParser.java" todir="src/org/jsweet/input/typescriptdef/parser" overwrite="true">
|
||||
</move>
|
||||
<move file="sym.java" todir="src/org/jsweet/input/typescriptdef/parser" overwrite="true">
|
||||
</move>
|
||||
<echo>Generating TSDef API lexer...</echo>
|
||||
<java classname="JFlex.Main" fork="true" failonerror="true" classpath="${compile_classpath}">
|
||||
<arg value="src/org/jsweet/input/typescriptdef/parser/typescriptdef.lex" />
|
||||
</java>
|
||||
|
||||
</target>
|
||||
|
||||
|
||||
</project>
|
||||
16
jsweet-candy-generator/copyright.txt
Normal file
16
jsweet-candy-generator/copyright.txt
Normal file
@ -0,0 +1,16 @@
|
||||
/*
|
||||
* JSweet - http://www.jsweet.org
|
||||
* Copyright (C) 2015 CINCHEO SAS <renaud.pawlak@cincheo.fr>
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
206
jsweet-candy-generator/pom.xml
Normal file
206
jsweet-candy-generator/pom.xml
Normal file
@ -0,0 +1,206 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>org.jsweet</groupId>
|
||||
<artifactId>jsweet-candy-generator</artifactId>
|
||||
<version>2.0.0-SNAPSHOT</version>
|
||||
<name>JSweet candy generator</name>
|
||||
<developers>
|
||||
<developer>
|
||||
<id>rpawlak</id>
|
||||
<name>Renaud Pawlak</name>
|
||||
<email>renaud.pawlak@gmail.com</email>
|
||||
</developer>
|
||||
<developer>
|
||||
<id>lgrignon</id>
|
||||
<name>Louis Grignon</name>
|
||||
<email>louis.grignon@gmail.com</email>
|
||||
</developer>
|
||||
</developers>
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>jsweet-central</id>
|
||||
<name>libs-release</name>
|
||||
<url>http://repository.jsweet.org/artifactory/libs-release-local</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<snapshots />
|
||||
<id>jsweet-snapshots</id>
|
||||
<name>libs-snapshot</name>
|
||||
<url>http://repository.jsweet.org/artifactory/libs-snapshot-local</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>jsweet-external</id>
|
||||
<name>libs-release</name>
|
||||
<url>http://repository.jsweet.org/artifactory/ext-release-local</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<releases />
|
||||
<snapshots />
|
||||
<id>cincheo</id>
|
||||
<name>cincheo</name>
|
||||
<url>http://repository.jsweet.org/artifactory/cincheo</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
<build>
|
||||
<sourceDirectory>src/main/java</sourceDirectory>
|
||||
<testSourceDirectory>src/test/java</testSourceDirectory>
|
||||
<testResources>
|
||||
<testResource>
|
||||
<directory>src/test/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</testResource>
|
||||
</testResources>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.1</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<artifactId>maven-antrun-plugin</artifactId>
|
||||
<version>1.7</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>generate-sources</phase>
|
||||
<configuration>
|
||||
<target>
|
||||
<property name="compile_classpath" refid="maven.compile.classpath" />
|
||||
<property name="outputDir" value="${project.build.outputDirectory}" />
|
||||
<property name="sourceDir" value="${project.build.sourceDirectory}" />
|
||||
<ant antfile="${basedir}/build.xml" target="gen-parser" />
|
||||
</target>
|
||||
</configuration>
|
||||
<goals>
|
||||
<goal>run</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<!--This plugin's configuration is used to store Eclipse m2e settings
|
||||
only. It has no influence on the Maven build itself. -->
|
||||
<plugin>
|
||||
<groupId>org.eclipse.m2e</groupId>
|
||||
<artifactId>lifecycle-mapping</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<configuration>
|
||||
<lifecycleMappingMetadata>
|
||||
<pluginExecutions>
|
||||
<pluginExecution>
|
||||
<pluginExecutionFilter>
|
||||
<groupId>
|
||||
org.apache.maven.plugins
|
||||
</groupId>
|
||||
<artifactId>
|
||||
maven-antrun-plugin
|
||||
</artifactId>
|
||||
<versionRange>
|
||||
[1.7,)
|
||||
</versionRange>
|
||||
<goals>
|
||||
<goal>run</goal>
|
||||
</goals>
|
||||
</pluginExecutionFilter>
|
||||
<action>
|
||||
<ignore></ignore>
|
||||
</action>
|
||||
</pluginExecution>
|
||||
</pluginExecutions>
|
||||
</lifecycleMappingMetadata>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.martiansoftware</groupId>
|
||||
<artifactId>jsap</artifactId>
|
||||
<version>2.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>edu.princeton.cup</groupId>
|
||||
<artifactId>java-cup</artifactId>
|
||||
<version>10k</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>de.jflex</groupId>
|
||||
<artifactId>jflex</artifactId>
|
||||
<version>1.3.5</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>1.2.17</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.3.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>2.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jsoup</groupId>
|
||||
<artifactId>jsoup</artifactId>
|
||||
<version>1.7.2</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.jsweet</groupId>
|
||||
<artifactId>jsweet-core</artifactId>
|
||||
<version>5-SNAPSHOT</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>2.2.4</version>
|
||||
<scope>compile</scope>
|
||||
<optional>false</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<organization>
|
||||
<name>JSweet</name>
|
||||
<url>http://www.jsweet.org</url>
|
||||
</organization>
|
||||
<description>A project that defines translators that translate Javascript API definitions such as Typescript or IDL to Candies: JSweet defition APIs.</description>
|
||||
|
||||
<distributionManagement>
|
||||
<repository>
|
||||
<id>cincheo</id>
|
||||
<name>cincheo</name>
|
||||
<url>http://repository.jsweet.org/artifactory/cincheo</url>
|
||||
</repository>
|
||||
<snapshotRepository>
|
||||
<id>cincheo</id>
|
||||
<name>cincheo</name>
|
||||
<url>http://repository.jsweet.org/artifactory/cincheo</url>
|
||||
</snapshotRepository>
|
||||
</distributionManagement>
|
||||
|
||||
</project>
|
||||
@ -0,0 +1,255 @@
|
||||
package org.jsweet;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.HashSet;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* This class contains static constants and utilities.
|
||||
*
|
||||
* @author Renaud Pawlak
|
||||
*/
|
||||
public abstract class JSweetDefTranslatorConfig {
|
||||
|
||||
private JSweetDefTranslatorConfig() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The properties coming from application.properties.
|
||||
*/
|
||||
public static Properties APPLICATION_PROPERTIES = new Properties();
|
||||
|
||||
static {
|
||||
try (InputStream in = JSweetDefTranslatorConfig.class.getResourceAsStream("/application.properties")) {
|
||||
APPLICATION_PROPERTIES.load(in);
|
||||
in.close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the version number (not including suffix).
|
||||
*/
|
||||
public static String getVersionNumber() {
|
||||
return APPLICATION_PROPERTIES.getProperty("application.version").split("-")[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* The Maven group id where candies are deployed.
|
||||
*/
|
||||
public final static String MAVEN_CANDIES_GROUP = "org.jsweet.candies";
|
||||
|
||||
private final static String JAVA_PACKAGE = "java";
|
||||
public final static String ROOT_PACKAGE = "jsweet";
|
||||
/** The constant for the JSweet lang package. */
|
||||
public final static String LANG_PACKAGE = ROOT_PACKAGE + ".lang";
|
||||
/** The constant for the JSweet util package. */
|
||||
public final static String UTIL_PACKAGE = ROOT_PACKAGE + ".util";
|
||||
/**
|
||||
* The constant for the JSweet lib package (where the definitions need to
|
||||
* be).
|
||||
*/
|
||||
public final static String LIBS_PACKAGE = "def";
|
||||
/** The constant for the JSweet dom package. */
|
||||
public final static String DOM_PACKAGE = ROOT_PACKAGE + ".dom";
|
||||
/**
|
||||
* The constant for the package generates top-level classes (one cannot use
|
||||
* unnamed package in Java).
|
||||
*/
|
||||
public static final String GLOBALS_PACKAGE_NAME = "globals";
|
||||
/**
|
||||
* The constant for the classes where members are generated as top-level
|
||||
* elements (global variables and functions).
|
||||
*/
|
||||
public static final String GLOBALS_CLASS_NAME = "Globals";
|
||||
/** The constant for predefined utilities. */
|
||||
public static final String UTIL_CLASSNAME = UTIL_PACKAGE + ".Globals";
|
||||
/**
|
||||
* The constant for the interface name that contains all the generated
|
||||
* string types (short name).
|
||||
*/
|
||||
public static final String STRING_TYPES_INTERFACE_NAME = "StringTypes";
|
||||
/** The constant for the function classes package. */
|
||||
public static final String FUNCTION_CLASSES_PACKAGE = UTIL_PACKAGE + ".function";
|
||||
/** The constant for the tuple classes package. */
|
||||
public static final String TUPLE_CLASSES_PACKAGE = UTIL_PACKAGE + ".tuple";
|
||||
/** The constant for the tuple classes prefix. */
|
||||
public static final String TUPLE_CLASSES_PREFIX = "Tuple";
|
||||
/** The constant for the package containing union types. */
|
||||
public static final String UNION_PACKAGE = UTIL_PACKAGE + ".union";
|
||||
/** The constant for the Union core class full name. */
|
||||
public static final String UNION_CLASS_NAME = UNION_PACKAGE + ".Union";
|
||||
/** The constant for indexed access function. */
|
||||
public static final String INDEXED_GET_FUCTION_NAME = "$get";
|
||||
/** The constant for indexed assignment function. */
|
||||
public static final String INDEXED_SET_FUCTION_NAME = "$set";
|
||||
public static final String INDEXED_DELETE_FUCTION_NAME = "$delete";
|
||||
public static final String NEW_FUNCTION_NAME = "$new";
|
||||
public static final String ANONYMOUS_FUNCTION_NAME = "apply";
|
||||
public static final String ANONYMOUS_STATIC_FUNCTION_NAME = "applyStatic";
|
||||
|
||||
/**
|
||||
* Default name of the directory where the TypeScript definition files can
|
||||
* be found.
|
||||
*/
|
||||
public static final String TS_LIBS_DIR_NAME = "typings";
|
||||
|
||||
/**
|
||||
* The constant for main functions (translate to global code, which is
|
||||
* executed when the file is loaded).
|
||||
*/
|
||||
public static final String MAIN_FUNCTION_NAME = "main";
|
||||
|
||||
public static final String OBJECT_CLASSNAME = JSweetDefTranslatorConfig.LANG_PACKAGE + ".Object";
|
||||
|
||||
public static final String ANNOTATION_DISABLED = JSweetDefTranslatorConfig.LANG_PACKAGE + ".Disabled";
|
||||
public static final String ANNOTATION_ERASED = JSweetDefTranslatorConfig.LANG_PACKAGE + ".Erased";
|
||||
public static final String ANNOTATION_AMBIENT = JSweetDefTranslatorConfig.LANG_PACKAGE + ".Ambient";
|
||||
public static final String ANNOTATION_MIXIN = JSweetDefTranslatorConfig.LANG_PACKAGE + ".Mixin";
|
||||
public static final String ANNOTATION_OBJECT_TYPE = JSweetDefTranslatorConfig.LANG_PACKAGE + ".ObjectType";
|
||||
public static final String ANNOTATION_INTERFACE = JSweetDefTranslatorConfig.LANG_PACKAGE + ".Interface";
|
||||
public static final String ANNOTATION_OPTIONAL = JSweetDefTranslatorConfig.LANG_PACKAGE + ".Optional";
|
||||
public static final String ANNOTATION_STRING_TYPE = JSweetDefTranslatorConfig.LANG_PACKAGE + ".StringType";
|
||||
public static final String ANNOTATION_MODULE = JSweetDefTranslatorConfig.LANG_PACKAGE + ".Module";
|
||||
public static final String ANNOTATION_ROOT = JSweetDefTranslatorConfig.LANG_PACKAGE + ".Root";
|
||||
public static final String ANNOTATION_NAME = JSweetDefTranslatorConfig.LANG_PACKAGE + ".Name";
|
||||
public static final String ANNOTATION_EXTENDS = JSweetDefTranslatorConfig.LANG_PACKAGE + ".Extends";
|
||||
public static final String ANNOTATION_FUNCTIONAL_INTERFACE = FunctionalInterface.class.getName();
|
||||
|
||||
/**
|
||||
* This map contains the Java keywords that are taken into account in the
|
||||
* generation for avoiding keyword clashes.
|
||||
*/
|
||||
public static final Set<String> JAVA_KEYWORDS = new HashSet<String>();
|
||||
|
||||
public static final Set<String> JAVA_TS_KEYWORDS = new HashSet<String>();
|
||||
|
||||
/**
|
||||
* This map contains the JS keywords that are taken into account in the
|
||||
* generation for avoiding keyword clashes.
|
||||
*/
|
||||
public static final Set<String> JS_KEYWORDS = new HashSet<String>();
|
||||
|
||||
static {
|
||||
// note TS keywords are removed from that list
|
||||
JAVA_KEYWORDS.add("abstract");
|
||||
JAVA_KEYWORDS.add("assert");
|
||||
// JAVA_KEYWORDS.add("boolean");
|
||||
JAVA_KEYWORDS.add("break");
|
||||
JAVA_KEYWORDS.add("byte");
|
||||
JAVA_KEYWORDS.add("case");
|
||||
JAVA_KEYWORDS.add("catch");
|
||||
JAVA_KEYWORDS.add("char");
|
||||
// JAVA_KEYWORDS.add("class");
|
||||
JAVA_KEYWORDS.add("const");
|
||||
JAVA_KEYWORDS.add("continue");
|
||||
JAVA_KEYWORDS.add("default");
|
||||
JAVA_KEYWORDS.add("do");
|
||||
JAVA_KEYWORDS.add("double");
|
||||
JAVA_KEYWORDS.add("else");
|
||||
// JAVA_KEYWORDS.add("enum");
|
||||
JAVA_KEYWORDS.add("extends");
|
||||
JAVA_KEYWORDS.add("final");
|
||||
JAVA_KEYWORDS.add("finally");
|
||||
JAVA_KEYWORDS.add("float");
|
||||
JAVA_KEYWORDS.add("for");
|
||||
JAVA_KEYWORDS.add("goto");
|
||||
JAVA_KEYWORDS.add("if");
|
||||
// JAVA_KEYWORDS.add("implements");
|
||||
JAVA_KEYWORDS.add("import");
|
||||
JAVA_KEYWORDS.add("instanceof");
|
||||
JAVA_KEYWORDS.add("int");
|
||||
// JAVA_KEYWORDS.add("interface");
|
||||
JAVA_KEYWORDS.add("long");
|
||||
JAVA_KEYWORDS.add("native");
|
||||
JAVA_KEYWORDS.add("new");
|
||||
JAVA_KEYWORDS.add("package");
|
||||
JAVA_KEYWORDS.add("private");
|
||||
JAVA_KEYWORDS.add("protected");
|
||||
JAVA_KEYWORDS.add("public");
|
||||
JAVA_KEYWORDS.add("return");
|
||||
JAVA_KEYWORDS.add("short");
|
||||
JAVA_KEYWORDS.add("static");
|
||||
JAVA_KEYWORDS.add("strictfp");
|
||||
JAVA_KEYWORDS.add("super");
|
||||
JAVA_KEYWORDS.add("switch");
|
||||
JAVA_KEYWORDS.add("synchronized");
|
||||
JAVA_KEYWORDS.add("this");
|
||||
JAVA_KEYWORDS.add("throw");
|
||||
JAVA_KEYWORDS.add("throws");
|
||||
JAVA_KEYWORDS.add("transient");
|
||||
JAVA_KEYWORDS.add("try");
|
||||
// JAVA_KEYWORDS.add("void");
|
||||
JAVA_KEYWORDS.add("volatile");
|
||||
JAVA_KEYWORDS.add("while");
|
||||
|
||||
JAVA_TS_KEYWORDS.add("boolean");
|
||||
JAVA_TS_KEYWORDS.add("class");
|
||||
JAVA_TS_KEYWORDS.add("enum");
|
||||
JAVA_TS_KEYWORDS.add("implements");
|
||||
JAVA_TS_KEYWORDS.add("interface");
|
||||
JAVA_TS_KEYWORDS.add("void");
|
||||
|
||||
JS_KEYWORDS.add("function");
|
||||
JS_KEYWORDS.add("var");
|
||||
JS_KEYWORDS.add("typeof");
|
||||
}
|
||||
|
||||
/**
|
||||
* This function return a Javascript-friendly identifier from a
|
||||
* Java-formatted one.
|
||||
*
|
||||
* @param identifier
|
||||
* the Java-formatted identifier
|
||||
* @return the Javascript-friendly identifier
|
||||
*/
|
||||
public static String toJsIdentifier(String identifier) {
|
||||
if (!identifier.isEmpty() && Character.isUpperCase(identifier.charAt(0))
|
||||
&& JSweetDefTranslatorConfig.JAVA_KEYWORDS.contains(identifier.toLowerCase())) {
|
||||
return identifier.toLowerCase();
|
||||
}
|
||||
// TODO: translate $$
|
||||
// if (Character.isDigit(identifier.charAt(0))) {
|
||||
// return "$$" + identifier.charAt(0) + "$$" + identifier.substring(1);
|
||||
// }
|
||||
return identifier;
|
||||
}
|
||||
|
||||
public static boolean isJDKReplacementMode() {
|
||||
return "java.lang".equals(LANG_PACKAGE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the JSweet object's fully qualified name.
|
||||
*/
|
||||
public static String getObjectClassName() {
|
||||
return LANG_PACKAGE + ".Object";
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if this qualified name belongs to the JDK (starts with
|
||||
* {@value #JAVA_PACKAGE}).
|
||||
*/
|
||||
public static boolean isJDKPath(String qualifiedName) {
|
||||
return qualifiedName.startsWith(JAVA_PACKAGE + ".");
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if this qualified name belongs to any TypeScript library definition
|
||||
* (starts with {@value #LIBS_PACKAGE}).
|
||||
*/
|
||||
public static boolean isLibPath(String qualifiedName) {
|
||||
return qualifiedName.startsWith(LIBS_PACKAGE + ".");
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if this qualified name belongs to one of the JSweet core package
|
||||
* (starts with {@value #ROOT_PACKAGE}).
|
||||
*/
|
||||
public static boolean isJSweetPath(String qualifiedName) {
|
||||
return qualifiedName.startsWith(ROOT_PACKAGE + ".");
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,457 @@
|
||||
package org.jsweet.input.typescriptdef;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.jsweet.JSweetDefTranslatorConfig;
|
||||
import org.jsweet.input.typescriptdef.ast.CompilationUnit;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.parser.TypescriptDefParser;
|
||||
import org.jsweet.input.typescriptdef.util.Util;
|
||||
import org.jsweet.input.typescriptdef.visitor.ConstructorInterfacesMerger;
|
||||
import org.jsweet.input.typescriptdef.visitor.ConstructorTypeReferenceReplacer;
|
||||
import org.jsweet.input.typescriptdef.visitor.DeclarationBinder;
|
||||
import org.jsweet.input.typescriptdef.visitor.DocFiller;
|
||||
import org.jsweet.input.typescriptdef.visitor.DuplicateMethodsCleaner;
|
||||
import org.jsweet.input.typescriptdef.visitor.DynamicTypeParametersExpander;
|
||||
import org.jsweet.input.typescriptdef.visitor.EmptyConstructorAdder;
|
||||
import org.jsweet.input.typescriptdef.visitor.EmptyModulesCleaner;
|
||||
import org.jsweet.input.typescriptdef.visitor.FactoryMethodsCreator;
|
||||
import org.jsweet.input.typescriptdef.visitor.FieldTypeFunctionInjector;
|
||||
import org.jsweet.input.typescriptdef.visitor.ForEachClashRemover;
|
||||
import org.jsweet.input.typescriptdef.visitor.FunctionKindAdapter;
|
||||
import org.jsweet.input.typescriptdef.visitor.FunctionTypeOfReplacer;
|
||||
import org.jsweet.input.typescriptdef.visitor.FunctionalInterfacesCreator;
|
||||
import org.jsweet.input.typescriptdef.visitor.GlobalsCreator;
|
||||
import org.jsweet.input.typescriptdef.visitor.ImportedAndExportedReferenceExpander;
|
||||
import org.jsweet.input.typescriptdef.visitor.IterableInjector;
|
||||
import org.jsweet.input.typescriptdef.visitor.JavaDefModelPrinter;
|
||||
import org.jsweet.input.typescriptdef.visitor.ModuleToTypeMerger;
|
||||
import org.jsweet.input.typescriptdef.visitor.NameAdapter;
|
||||
import org.jsweet.input.typescriptdef.visitor.NameChecker;
|
||||
import org.jsweet.input.typescriptdef.visitor.ObjectTypeCreator;
|
||||
import org.jsweet.input.typescriptdef.visitor.ObjectTypeDuplicateMerger;
|
||||
import org.jsweet.input.typescriptdef.visitor.OptionalParametersExpander;
|
||||
import org.jsweet.input.typescriptdef.visitor.OptionalParametersInFunctionalTypesExpander;
|
||||
import org.jsweet.input.typescriptdef.visitor.PackageOrganizer;
|
||||
import org.jsweet.input.typescriptdef.visitor.ParentMethodReturnTypeSusbtitutor;
|
||||
import org.jsweet.input.typescriptdef.visitor.SerializableHandler;
|
||||
import org.jsweet.input.typescriptdef.visitor.StringTypeCreator;
|
||||
import org.jsweet.input.typescriptdef.visitor.SuperTypesMerger;
|
||||
import org.jsweet.input.typescriptdef.visitor.TupleTypeCreator;
|
||||
import org.jsweet.input.typescriptdef.visitor.TypeKindChooser;
|
||||
import org.jsweet.input.typescriptdef.visitor.TypeMacroReplacer;
|
||||
import org.jsweet.input.typescriptdef.visitor.TypeMerger;
|
||||
import org.jsweet.input.typescriptdef.visitor.TypeParametersSubstitutor;
|
||||
import org.jsweet.input.typescriptdef.visitor.TypeReferenceChecker;
|
||||
import org.jsweet.input.typescriptdef.visitor.TypeReferenceExpander;
|
||||
import org.jsweet.input.typescriptdef.visitor.UnionInterfacesCreator;
|
||||
import org.jsweet.input.typescriptdef.visitor.UnionTypesEraser;
|
||||
import org.jsweet.input.typescriptdef.visitor.UnionTypesExpander;
|
||||
|
||||
public class TypescriptDef2Java {
|
||||
|
||||
private final static Logger logger = Logger.getLogger(TypescriptDef2Java.class);
|
||||
|
||||
public static final String TS_CORE_LIB_DIR = "lib.core";
|
||||
public static final String TS_DOM_LIB_DIR = "lib.dom";
|
||||
public static boolean generateMissingTypes = false;
|
||||
|
||||
private static void addTsDefFiles(File input, ArrayList<File> files, Predicate<File> libFilter) {
|
||||
if (input.isDirectory()) {
|
||||
File[] subFiles = input.listFiles();
|
||||
if (subFiles != null) {
|
||||
for (File file : subFiles) {
|
||||
addTsDefFiles(file, files, libFilter);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (input.getName().endsWith(".d.ts") && !input.getPath().contains("legacy") && libFilter.test(input)) {
|
||||
files.add(input);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static void scan(CompilationUnit compilationUnit, Scanner scanner) {
|
||||
try {
|
||||
scanner.scan(compilationUnit);
|
||||
} catch (Exception e) {
|
||||
scanner.printStackTrace(System.err);
|
||||
logger.error(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void scan(List<CompilationUnit> compilationUnits, Scanner... scanners) {
|
||||
scan(null, compilationUnits, scanners);
|
||||
}
|
||||
|
||||
private static void scan(BiConsumer<CompilationUnit, Scanner> onScannedCallback,
|
||||
List<CompilationUnit> compilationUnits, Scanner... scanners) {
|
||||
for (Scanner scanner : scanners) {
|
||||
scanner.onScanStart();
|
||||
}
|
||||
for (CompilationUnit compilationUnit : compilationUnits) {
|
||||
for (Scanner scanner : scanners) {
|
||||
scan(compilationUnit, scanner);
|
||||
if (onScannedCallback != null) {
|
||||
onScannedCallback.accept(compilationUnit, scanner);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (Scanner scanner : scanners) {
|
||||
scanner.onScanEnded();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
translate( //
|
||||
asList(new File("typings/globals/jquery/index.d.ts")), //
|
||||
asList(new File("typings/lib.core/lib.core.d.ts"), new File("typings/lib.core/lib.core.ext.d.ts"),
|
||||
new File("typings/lib.core/lib.dom.d.ts")), //
|
||||
new File("OUT"), //
|
||||
null, //
|
||||
false);
|
||||
}
|
||||
|
||||
private static Pattern refPattern = Pattern.compile("^///\\p{Blank}*<.*$");
|
||||
|
||||
private static void grabReferences(CompilationUnit cu) throws IOException {
|
||||
for (String s : FileUtils.readLines(cu.getFile())) {
|
||||
Matcher m = refPattern.matcher(s);
|
||||
if (m.matches()) {
|
||||
cu.addReference(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
private static final Map<String, String[]> IGNORED_REFERENCES = new HashMap<String, String[]>() {
|
||||
{
|
||||
put("cordova/cordova.d.ts", new String[] { "plugins/.*" });
|
||||
}
|
||||
};
|
||||
|
||||
private static void parse(Context context, File f) throws IOException {
|
||||
// context.compilationUnits.stream().map((cu) -> { return
|
||||
// cu.getFile();}).
|
||||
if (context.compilationUnits.contains(new CompilationUnit(f))) {
|
||||
// logger.info("skipping: " + f);
|
||||
return;
|
||||
}
|
||||
logger.info("parsing: " + f);
|
||||
TypescriptDefParser parser = TypescriptDefParser.parseFile(f);
|
||||
context.compilationUnits.add(parser.compilationUnit);
|
||||
grabReferences(parser.compilationUnit);
|
||||
for (String reference : parser.compilationUnit.getReferences()) {
|
||||
String path = Util.getLibPathFromReference(reference);
|
||||
if (path != null) {
|
||||
File dep = new File(f.getParent(), path);
|
||||
if (!dep.exists()) {
|
||||
context.reportError("dependency '" + dep + "' does not exist");
|
||||
} else {
|
||||
File tsDefFile = parser.compilationUnit.getFile();
|
||||
boolean ignored = isIgnoredReference(tsDefFile, path);
|
||||
if (dep.getPath().contains("..")) {
|
||||
try {
|
||||
Path currentPath = new File("").getAbsoluteFile().toPath();
|
||||
Path depPath = dep.getCanonicalFile().toPath();
|
||||
logger.debug("depPath: " + depPath);
|
||||
Path relPath = currentPath.relativize(depPath);
|
||||
if (!relPath.toString().contains("..")) {
|
||||
dep = relPath.toFile();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
logger.info("handling dependency: " + dep);
|
||||
if (ignored) {
|
||||
context.getDependenciesDefinitions().add(dep);
|
||||
} else {
|
||||
parse(context, dep);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isIgnoredReference(File tsDefFile, String path) {
|
||||
|
||||
for (Map.Entry<String, String[]> ignoredReferenceEntry : IGNORED_REFERENCES.entrySet()) {
|
||||
|
||||
if (tsDefFile.getPath().endsWith(ignoredReferenceEntry.getKey())) {
|
||||
|
||||
String[] ignoredPaths = ignoredReferenceEntry.getValue();
|
||||
for (String ignoredPathRegex : ignoredPaths) {
|
||||
if (Pattern.matches(ignoredPathRegex, path)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static Context translate( //
|
||||
File inputDir, //
|
||||
File outputDir, //
|
||||
String cacheDirPath, //
|
||||
boolean fetchJavadoc, //
|
||||
Predicate<File> libFilter, //
|
||||
Predicate<File> dependenciesFilter) throws Throwable {
|
||||
|
||||
logger.info("typings directory: " + inputDir);
|
||||
logger.info("output directory: " + outputDir);
|
||||
|
||||
ArrayList<File> tsDefFiles = new ArrayList<File>();
|
||||
addTsDefFiles(inputDir, tsDefFiles, libFilter);
|
||||
|
||||
ArrayList<File> tsDefDependencies = new ArrayList<File>();
|
||||
addTsDefFiles(inputDir, tsDefDependencies, dependenciesFilter);
|
||||
|
||||
File cacheDir = null;
|
||||
if (cacheDirPath != null) {
|
||||
cacheDir = new File(cacheDirPath);
|
||||
}
|
||||
|
||||
return translate(tsDefFiles, tsDefDependencies, outputDir, cacheDir, fetchJavadoc);
|
||||
}
|
||||
|
||||
public static Context translate( //
|
||||
List<File> tsDefFiles, //
|
||||
List<File> tsDefDependencies, //
|
||||
File outputDir, //
|
||||
File cacheDir, //
|
||||
boolean fetchJavadoc) throws Throwable {
|
||||
|
||||
// comp.compile(fileObjects);
|
||||
logger.info("input files: " + tsDefFiles);
|
||||
logger.info("dependencies: " + tsDefDependencies);
|
||||
logger.info("output directory: " + outputDir);
|
||||
|
||||
outputDir.mkdirs();
|
||||
|
||||
Context context = new Context(tsDefFiles, tsDefDependencies, fetchJavadoc);
|
||||
context.verbose = false;
|
||||
context.cacheDir = cacheDir;
|
||||
|
||||
logger.info("all definitions: " + context.getAllDefinitions());
|
||||
|
||||
for (File f : context.getAllDefinitions()) {
|
||||
parse(context, f);
|
||||
}
|
||||
|
||||
translateAst(context);
|
||||
|
||||
printAst(outputDir, context);
|
||||
|
||||
// copies core built-in srcs
|
||||
// if (context.getLibrariesDefinitions()
|
||||
// .contains(new File(JSweetDefTranslatorConfig.TS_LIBS_DIR_NAME +
|
||||
// "/lib.core/lib.core.d.ts"))) {
|
||||
// logger.info("copying built-in core '" + getBuiltInDir() + "' -> '" +
|
||||
// outputDir);
|
||||
// FileUtils.copyDirectory(new File(getBuiltInDir()), outputDir, new
|
||||
// FileFilter() {
|
||||
//
|
||||
// @Override
|
||||
// public boolean accept(File file) {
|
||||
// return !file.getName().startsWith(".");
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
|
||||
// copies core packages' package-info if necessary
|
||||
// File jsweetRootPackageDir = new File(outputDir, "jsweet");
|
||||
// if (jsweetRootPackageDir.isDirectory()) {
|
||||
// for (File jsweetSubSourceDir : jsweetRootPackageDir.listFiles()) {
|
||||
// File packageInfo = new File(BUILT_IN_DIR,
|
||||
// "jsweet/" + jsweetSubSourceDir.getName() + "/package-info.java");
|
||||
// logger.info("copying package-info for '" + jsweetSubSourceDir + "'
|
||||
// from " + packageInfo);
|
||||
// FileUtils.copyFileToDirectory(packageInfo, jsweetSubSourceDir);
|
||||
// }
|
||||
// }
|
||||
|
||||
// =====
|
||||
File tsdefDir = new File(outputDir, JSweetDefTranslatorConfig.TS_LIBS_DIR_NAME);
|
||||
logger.info("copying tsdef: '" + context.getAllDefinitions() + "' -> '" + tsdefDir);
|
||||
tsdefDir.mkdirs();
|
||||
|
||||
for (File tsDefFile : context.getAllDefinitions()) {
|
||||
|
||||
File destDir = new File( //
|
||||
tsdefDir, //
|
||||
tsDefFile.getParentFile().getName() + "_" + tsDefFile.getName());
|
||||
FileUtils.copyFileToDirectory(tsDefFile, destDir);
|
||||
File extFile = new File(tsDefFile.getParentFile(), tsDefFile.getName().replace(".d.ts", ".ext.d.ts"));
|
||||
if (extFile.isFile() && extFile.canRead()) {
|
||||
FileUtils.copyFileToDirectory(tsDefFile, destDir);
|
||||
logger.info("ext file '" + extFile + "' copied as well");
|
||||
}
|
||||
}
|
||||
|
||||
mergeExtFiles(tsdefDir);
|
||||
// createLibFile(tsdefDir);
|
||||
// mergeDomToCore(tsdefDir);
|
||||
|
||||
return context;
|
||||
}
|
||||
|
||||
public static void printAst(File outputDir, Context context) {
|
||||
outputDir.mkdirs();
|
||||
try {
|
||||
FileUtils.cleanDirectory(outputDir);
|
||||
} catch (IOException e) {
|
||||
logger.error("did not clean output directory: " + outputDir, e);
|
||||
}
|
||||
scan((cu, scanner) -> {
|
||||
logger.info("translated " + cu);
|
||||
}, context.compilationUnits, new JavaDefModelPrinter(context, outputDir));
|
||||
}
|
||||
|
||||
public static void translateAst(Context context) {
|
||||
|
||||
// List<QualifiedDeclaration<TypeDeclaration>> l =
|
||||
// context.findDeclarations(TypeDeclaration.class, "*.HTMLAttributes");
|
||||
// System.out.println();
|
||||
|
||||
scan(context.compilationUnits, new NameChecker(context));
|
||||
|
||||
scan(context.compilationUnits, new FunctionTypeOfReplacer(context));
|
||||
|
||||
scan(context.compilationUnits, new ImportedAndExportedReferenceExpander(context, false));
|
||||
scan(context.compilationUnits, new ImportedAndExportedReferenceExpander(context, true));
|
||||
|
||||
scan(context.compilationUnits, new EmptyModulesCleaner(context));
|
||||
|
||||
// assign module names
|
||||
scan(context.compilationUnits, new PackageOrganizer(context), new TypeKindChooser(context),
|
||||
new DeclarationBinder(context));
|
||||
|
||||
context.checkConsistency();
|
||||
|
||||
logger.info("dumping initial state");
|
||||
context.dump(logger);
|
||||
|
||||
try {
|
||||
Util.createDependencyGraph(context);
|
||||
logger.info("dependency graph: " + context.dependencyGraph);
|
||||
} catch (IOException e) {
|
||||
logger.error("error when contructing dependency graph", e);
|
||||
}
|
||||
|
||||
// scan(context.compilationUnits, new GlobalsCreator(context));
|
||||
|
||||
scan(context.compilationUnits, new ModuleToTypeMerger(context));
|
||||
scan(context.compilationUnits, new ObjectTypeCreator(context), new ObjectTypeDuplicateMerger(context));
|
||||
scan(context.compilationUnits, new ConstructorInterfacesMerger(context));
|
||||
scan(context.compilationUnits, new TypeMerger(context));
|
||||
|
||||
scan(context.compilationUnits, new SuperTypesMerger(context));
|
||||
// does not work (prototype clashing)
|
||||
// scan(context.compilationUnits, new
|
||||
// FunctionalParametersExpander(context));
|
||||
scan(context.compilationUnits, new TypeReferenceExpander(context));
|
||||
|
||||
context.calculateArrayTypes();
|
||||
|
||||
scan(context.compilationUnits, new TypeMacroReplacer(context));
|
||||
|
||||
scan(context.compilationUnits, new UnionTypesEraser(context));
|
||||
|
||||
// scan(context.compilationUnits, new TypeReferenceChecker(context));
|
||||
|
||||
scan(context.compilationUnits, new OptionalParametersExpander(context),
|
||||
new OptionalParametersInFunctionalTypesExpander(context), new UnionTypesExpander(context),
|
||||
new StringTypeCreator(context), new FunctionalInterfacesCreator(context),
|
||||
new TypeParametersSubstitutor(context), new DynamicTypeParametersExpander(context),
|
||||
new TupleTypeCreator(context));
|
||||
|
||||
// optional parameters must have been fully expanded in super classes
|
||||
scan(context.compilationUnits, new ParentMethodReturnTypeSusbtitutor(context));
|
||||
|
||||
scan(context.compilationUnits, new GlobalsCreator(context), new FieldTypeFunctionInjector(context));
|
||||
|
||||
// binds declarations again to grab newly created inner types
|
||||
scan(context.compilationUnits, new DeclarationBinder(context));
|
||||
|
||||
scan(context.compilationUnits, new FactoryMethodsCreator(context));
|
||||
|
||||
// run type expansion again for partial names that would reference an
|
||||
// import
|
||||
scan(context.compilationUnits, new TypeReferenceExpander(context));
|
||||
|
||||
// context.dump(System.out);
|
||||
scan(context.compilationUnits, new NameAdapter(context), new DeclarationBinder(context));
|
||||
// TODO : this should be the last and it should ignore java.util.* and
|
||||
// so on
|
||||
scan(context.compilationUnits, new TypeReferenceChecker(context));
|
||||
|
||||
scan(context.compilationUnits, new IterableInjector(context));
|
||||
|
||||
scan(context.compilationUnits, new FunctionKindAdapter(context));
|
||||
|
||||
scan(context.compilationUnits, new UnionInterfacesCreator(context));
|
||||
|
||||
scan(context.compilationUnits, new EmptyConstructorAdder(context), new SerializableHandler(context));
|
||||
|
||||
scan(context.compilationUnits, new ConstructorTypeReferenceReplacer(context));
|
||||
|
||||
scan(context.compilationUnits, new DuplicateMethodsCleaner(context));
|
||||
|
||||
scan(context.compilationUnits, new ForEachClashRemover(context));
|
||||
|
||||
if (context.fetchJavadoc) {
|
||||
scan(context.compilationUnits, new DocFiller(context));
|
||||
}
|
||||
|
||||
// l = context.findDeclarations(TypeDeclaration.class,
|
||||
// "*.HTMLAttributes");
|
||||
// System.out.println();
|
||||
|
||||
context.checkConsistency();
|
||||
|
||||
logger.info("dumping final state");
|
||||
context.dump(logger);
|
||||
|
||||
}
|
||||
|
||||
private static void mergeExtFiles(File dir) {
|
||||
for (File f : dir.listFiles()) {
|
||||
if (f.isDirectory()) {
|
||||
mergeExtFiles(f);
|
||||
} else {
|
||||
if (f.getName().endsWith(".ext.d.ts")) {
|
||||
logger.info("merging ext file: " + f);
|
||||
File target = new File(dir, f.getName().replace(".ext.d.ts", ".d.ts"));
|
||||
if (target.exists()) {
|
||||
try {
|
||||
FileUtils.writeByteArrayToFile(target, FileUtils.readFileToByteArray(f), true);
|
||||
FileUtils.deleteQuietly(f);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,46 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
public abstract class AbstractAstNode implements AstNode {
|
||||
|
||||
private Token token;
|
||||
public int nodeTypeId = -1;
|
||||
private boolean hidden = false;
|
||||
|
||||
public AbstractAstNode(Token token) {
|
||||
super();
|
||||
// if(token==null) {
|
||||
// throw new RuntimeException("token cannot be null");
|
||||
// }
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Token getToken() {
|
||||
return token;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getLocation() {
|
||||
if (token != null) {
|
||||
return token.getLocation();
|
||||
} else {
|
||||
return "<unknown location>";
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return token == null ? "null" : token.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isHidden() {
|
||||
return hidden;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setHidden(boolean hidden) {
|
||||
this.hidden = hidden;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,302 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
|
||||
public abstract class AbstractDeclaration extends AbstractAstNode implements Declaration {
|
||||
protected String name;
|
||||
protected String originalName;
|
||||
protected String documentation;
|
||||
private Set<String> modifiers;
|
||||
private Map<Class<? extends Annotation>, Annotation[]> annotationMap;
|
||||
private List<String> stringAnnotations;
|
||||
protected boolean quotedName = false;
|
||||
|
||||
public AbstractDeclaration(Token token, String name) {
|
||||
super(token);
|
||||
setName(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> getModifiers() {
|
||||
return modifiers;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setModifiers(Set<String> modifiers) {
|
||||
this.modifiers = modifiers;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setName(String name) {
|
||||
if (name != null && (name.contains("\"") || name.contains("'"))) {
|
||||
this.name = name.replace("\"", "").replace("'", "");
|
||||
setQuotedName(true);
|
||||
} else {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDocumentation() {
|
||||
return documentation;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setDocumentation(String documentation) {
|
||||
this.documentation = documentation;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addModifier(String modifier) {
|
||||
if (modifiers == null) {
|
||||
modifiers = new HashSet<String>();
|
||||
}
|
||||
if (modifier.contains(" ")) {
|
||||
for (String s : modifier.split(" ")) {
|
||||
modifiers.add(s);
|
||||
}
|
||||
} else {
|
||||
modifiers.add(modifier);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeModifier(String modifier) {
|
||||
if (modifiers != null) {
|
||||
modifiers.remove(modifier);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasModifier(String modifier) {
|
||||
if (modifiers != null) {
|
||||
return modifiers.contains(modifier);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAnonymous() {
|
||||
return name == null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null) {
|
||||
return false;
|
||||
}
|
||||
if (!o.getClass().equals(getClass())) {
|
||||
return false;
|
||||
}
|
||||
Declaration d = (Declaration) o;
|
||||
if (d.getName() == null && getName() != null) {
|
||||
return false;
|
||||
}
|
||||
if (!d.getName().equals(getName())) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isInputAnnotatedWith(String annotation) {
|
||||
return getDocumentation() != null && getDocumentation().contains("@" + annotation);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addStringAnnotation(String annotation) {
|
||||
if (stringAnnotations == null) {
|
||||
stringAnnotations = new ArrayList<String>();
|
||||
}
|
||||
stringAnnotations.add(annotation);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeStringAnnotation(String annotation) {
|
||||
if (stringAnnotations == null) {
|
||||
return;
|
||||
}
|
||||
for (String a : new ArrayList<>(stringAnnotations)) {
|
||||
if (a.startsWith(annotation)) {
|
||||
stringAnnotations.remove(a);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getStringAnnotations() {
|
||||
return stringAnnotations;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasStringAnnotation(String annotation) {
|
||||
if (stringAnnotations == null) {
|
||||
return false;
|
||||
}
|
||||
for (String a : stringAnnotations) {
|
||||
if (a.startsWith(annotation)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getStringAnnotation(String annotation) {
|
||||
if (stringAnnotations == null) {
|
||||
return null;
|
||||
}
|
||||
for (String a : stringAnnotations) {
|
||||
if (a.startsWith(annotation)) {
|
||||
return a;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addAnnotation(Annotation annotation) {
|
||||
if (annotationMap == null) {
|
||||
annotationMap = new HashMap<Class<? extends Annotation>, Annotation[]>();
|
||||
}
|
||||
Class<? extends Annotation> annotationClass = annotation.annotationType();
|
||||
Annotation[] annotations = annotationMap.get(annotationClass);
|
||||
if (annotations == null) {
|
||||
annotations = new Annotation[0];
|
||||
}
|
||||
annotations = ArrayUtils.add(annotations, annotation);
|
||||
annotationMap.put(annotationClass, annotations);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
|
||||
if (annotationMap == null) {
|
||||
return null;
|
||||
}
|
||||
Annotation[] annotations = annotationMap.get(annotationClass);
|
||||
if (annotations != null && annotations.length > 0) {
|
||||
@SuppressWarnings("unchecked")
|
||||
T annotation = (T) annotations[0];
|
||||
return annotation;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends Annotation> T removeAnnotation(Class<T> annotationClass) {
|
||||
if (annotationMap == null) {
|
||||
return null;
|
||||
}
|
||||
Annotation[] annotations = annotationMap.get(annotationClass);
|
||||
if (annotations != null && annotations.length > 0) {
|
||||
@SuppressWarnings("unchecked")
|
||||
T annotation = (T) annotations[0];
|
||||
|
||||
annotations = ArrayUtils.removeElement(annotations, annotation);
|
||||
annotationMap.put(annotationClass, annotations);
|
||||
|
||||
return annotation;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Annotation[] getAnnotations() {
|
||||
if (annotationMap == null) {
|
||||
return new Annotation[0];
|
||||
}
|
||||
List<Annotation> l = new ArrayList<Annotation>();
|
||||
for (Annotation[] annotations : annotationMap.values()) {
|
||||
l.addAll(Arrays.asList(annotations));
|
||||
}
|
||||
return l.toArray(new Annotation[0]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Annotation[] getDeclaredAnnotations() {
|
||||
return getAnnotations();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
|
||||
if (annotationMap == null) {
|
||||
return false;
|
||||
}
|
||||
return annotationMap.containsKey(annotationClass);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
|
||||
if (annotationMap == null || !annotationMap.containsKey(annotationClass)) {
|
||||
@SuppressWarnings("unchecked")
|
||||
T[] r = (T[]) new Annotation[0];
|
||||
return r;
|
||||
}
|
||||
@SuppressWarnings("unchecked")
|
||||
T[] r = (T[]) annotationMap.get(annotationClass);
|
||||
return r;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends Annotation> T getDeclaredAnnotation(Class<T> annotationClass) {
|
||||
return getAnnotation(annotationClass);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationClass) {
|
||||
return getAnnotationsByType(annotationClass);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setStringAnnotations(List<String> stringAnnotations) {
|
||||
this.stringAnnotations = stringAnnotations;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isQuotedName() {
|
||||
return quotedName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setQuotedName(boolean quotedName) {
|
||||
this.quotedName = quotedName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getOriginalName() {
|
||||
if (originalName == null) {
|
||||
return name;
|
||||
}
|
||||
return originalName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setOriginalName(String originalName) {
|
||||
this.originalName = originalName;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,127 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
import static org.apache.commons.lang3.StringUtils.isBlank;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
|
||||
import org.jsweet.input.typescriptdef.util.Util;
|
||||
|
||||
public abstract class AbstractPrinter extends Scanner {
|
||||
|
||||
private static final String INDENT = " ";
|
||||
|
||||
private StringBuilder out = new StringBuilder();
|
||||
|
||||
private int indent = 0;
|
||||
|
||||
private int currentLine = 1;
|
||||
|
||||
private int currentColumn = 0;
|
||||
|
||||
public AbstractPrinter(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
protected void clearOutput() {
|
||||
out = new StringBuilder();
|
||||
}
|
||||
|
||||
public AbstractPrinter print(Visitable element) {
|
||||
scan(element);
|
||||
return this;
|
||||
}
|
||||
|
||||
protected String getIndent() {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for (int i = 0; i < indent; i++) {
|
||||
sb.append(INDENT);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public AbstractPrinter printIndent() {
|
||||
return print(getIndent());
|
||||
}
|
||||
|
||||
public AbstractPrinter startIndent() {
|
||||
indent++;
|
||||
return this;
|
||||
}
|
||||
|
||||
public AbstractPrinter endIndent() {
|
||||
indent--;
|
||||
return this;
|
||||
}
|
||||
|
||||
public AbstractPrinter print(CharSequence string) {
|
||||
out.append(string);
|
||||
currentColumn += string.length();
|
||||
return this;
|
||||
}
|
||||
|
||||
public AbstractPrinter space() {
|
||||
return print(" ");
|
||||
}
|
||||
|
||||
public AbstractPrinter removeLastChar() {
|
||||
out.deleteCharAt(out.length() - 1);
|
||||
currentColumn--;
|
||||
return this;
|
||||
}
|
||||
|
||||
public AbstractPrinter removeLastChars(int count) {
|
||||
if (count > 0) {
|
||||
out.delete(out.length() - count, out.length());
|
||||
}
|
||||
currentColumn -= count;
|
||||
return this;
|
||||
}
|
||||
|
||||
public AbstractPrinter removeLastIndent() {
|
||||
removeLastChars(INDENT.length());
|
||||
return this;
|
||||
}
|
||||
|
||||
public AbstractPrinter println() {
|
||||
out.append("\n");
|
||||
currentLine++;
|
||||
currentColumn = 0;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getResult() {
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
public int getCurrentLine() {
|
||||
return currentLine;
|
||||
}
|
||||
|
||||
public int getCurrentColumn() {
|
||||
return currentColumn;
|
||||
}
|
||||
|
||||
public AbstractPrinter printAnnotations(Declaration declaration) {
|
||||
CharSequence annos = annotationsToString(declaration);
|
||||
if (!isBlank(annos)) {
|
||||
print(annos);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public CharSequence annotationsToString(Declaration declaration) {
|
||||
StringBuilder annosDecls = new StringBuilder();
|
||||
for (Annotation annotation : declaration.getAnnotations()) {
|
||||
annosDecls.append(getIndent());
|
||||
annosDecls.append(Util.toString(annotation) + "\n");
|
||||
}
|
||||
if (declaration.getStringAnnotations() != null) {
|
||||
for (String annotation : declaration.getStringAnnotations()) {
|
||||
annosDecls.append(getIndent());
|
||||
annosDecls.append("@" + annotation + "\n");
|
||||
}
|
||||
}
|
||||
|
||||
return annosDecls;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,29 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
public abstract class AbstractTypedDeclaration extends AbstractDeclaration implements TypedDeclaration {
|
||||
|
||||
private TypeReference type;
|
||||
|
||||
public AbstractTypedDeclaration(Token token, String name, TypeReference type) {
|
||||
super(token, name);
|
||||
if (type == null) {
|
||||
this.type = new TypeReference(null, "any", null);
|
||||
} else {
|
||||
this.type = type;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return super.toString() + ":" + type;
|
||||
}
|
||||
|
||||
public TypeReference getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(TypeReference type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,87 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
public class ArrayTypeReference extends TypeReference {
|
||||
|
||||
TypeReference componentType;
|
||||
boolean disableArray = false;
|
||||
|
||||
public ArrayTypeReference(Token token, TypeReference componentType) {
|
||||
super(token, (String) null, null);
|
||||
this.componentType = componentType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
if (componentType == null) {
|
||||
return "any[]";
|
||||
}
|
||||
return componentType.toString() + "[]";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(Visitor visitor) {
|
||||
visitor.visitArrayTypeReference(this);
|
||||
}
|
||||
|
||||
public TypeReference getComponentType() {
|
||||
return componentType;
|
||||
}
|
||||
|
||||
public void setComponentType(TypeReference componentType) {
|
||||
this.componentType = componentType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (!obj.getClass().equals(getClass())) {
|
||||
return false;
|
||||
}
|
||||
ArrayTypeReference tr = (ArrayTypeReference) obj;
|
||||
return tr.getComponentType().equals(getComponentType());
|
||||
}
|
||||
|
||||
public boolean isDisableArray() {
|
||||
return disableArray;
|
||||
}
|
||||
|
||||
public void setDisableArray(boolean disableArray) {
|
||||
this.disableArray = disableArray;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ArrayTypeReference copy(boolean copyDeclarations) {
|
||||
ArrayTypeReference copy = new ArrayTypeReference(null,
|
||||
getComponentType() == null ? null : getComponentType().copy(copyDeclarations));
|
||||
copy.disableArray = disableArray;
|
||||
return copy;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ArrayTypeReference copy() {
|
||||
return copy(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isArray() {
|
||||
return true && !disableArray;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSubtypeOf(TypeReference type) {
|
||||
if (type.isArray()) {
|
||||
return componentType.isSubtypeOf(type.getComponentType());
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean substituteTypeReference(TypeReference targetType, TypeReference newType) {
|
||||
if (componentType == targetType) {
|
||||
componentType = newType;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,23 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
public interface AstNode extends Visitable {
|
||||
|
||||
static String toString2() {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the corresponding parser token.
|
||||
*/
|
||||
Token getToken();
|
||||
|
||||
/**
|
||||
* Returns the location in the parsed file.
|
||||
*/
|
||||
String getLocation();
|
||||
|
||||
// String toString();
|
||||
|
||||
boolean equals(Object object);
|
||||
|
||||
}
|
||||
@ -0,0 +1,195 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.jsweet.JSweetDefTranslatorConfig;
|
||||
|
||||
public class CompilationUnit implements Visitable, DeclarationContainer {
|
||||
|
||||
protected List<String> references = new ArrayList<String>();
|
||||
|
||||
protected File file;
|
||||
|
||||
protected Declaration[] declarations;
|
||||
|
||||
private boolean hidden = false;
|
||||
|
||||
private ModuleDeclaration mainModule;
|
||||
|
||||
private boolean external = false;
|
||||
|
||||
public CompilationUnit(File file) {
|
||||
super();
|
||||
this.file = file;
|
||||
}
|
||||
|
||||
public File getFile() {
|
||||
return file;
|
||||
}
|
||||
|
||||
public void setFile(File file) {
|
||||
this.file = file;
|
||||
}
|
||||
|
||||
public Declaration[] getDeclarations() {
|
||||
return declarations;
|
||||
}
|
||||
|
||||
public void setDeclarations(Declaration[] declarations) {
|
||||
this.declarations = declarations;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(Visitor visitor) {
|
||||
visitor.visitCompilationUnit(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return file.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Declaration[] getMembers() {
|
||||
return getDeclarations();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addMember(Declaration declaration) {
|
||||
declarations = DeclarationHelper.addMember(this, declaration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeMember(Declaration declaration) {
|
||||
declarations = DeclarationHelper.removeMember(this, declaration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void replaceMember(Declaration existingDeclaration, Declaration withNewDeclaration) {
|
||||
declarations = DeclarationHelper.replaceMember(this, existingDeclaration, withNewDeclaration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearMembers() {
|
||||
declarations = new Declaration[0];
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isHidden() {
|
||||
return hidden;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setHidden(boolean hidden) {
|
||||
this.hidden = hidden;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FunctionDeclaration findFirstFunction(String name) {
|
||||
return DeclarationHelper.findFirstFunction(this, name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<FunctionDeclaration> findFunctions(String name) {
|
||||
return DeclarationHelper.findFunctions(this, name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public VariableDeclaration findVariable(String name) {
|
||||
return DeclarationHelper.findVariable(this, name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public VariableDeclaration findVariableIgnoreCase(String name) {
|
||||
return DeclarationHelper.findVariableIgnoreCase(this, name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TypeDeclaration findType(String name) {
|
||||
TypeDeclaration typeDecl = DeclarationHelper.findType(this, name);
|
||||
if (typeDecl == null) {
|
||||
typeDecl = getMainModule().findType(name);
|
||||
}
|
||||
|
||||
return typeDecl;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TypeDeclaration findTypeIgnoreCase(String name) {
|
||||
TypeDeclaration typeDecl = DeclarationHelper.findTypeIgnoreCase(this, name);
|
||||
if (typeDecl == null) {
|
||||
typeDecl = getMainModule().findTypeIgnoreCase(name);
|
||||
}
|
||||
|
||||
return typeDecl;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Declaration findDeclaration(String name) {
|
||||
Declaration declaration = DeclarationHelper.findDeclaration(this, name);
|
||||
if (declaration == null) {
|
||||
ModuleDeclaration mainModule = getMainModule();
|
||||
if (mainModule != null) {
|
||||
declaration = mainModule.findDeclaration(name);
|
||||
}
|
||||
}
|
||||
|
||||
return declaration;
|
||||
}
|
||||
|
||||
public ModuleDeclaration getMainModule() {
|
||||
if (mainModule == null) {
|
||||
for (Declaration decl : declarations) {
|
||||
if (decl instanceof ModuleDeclaration && (JSweetDefTranslatorConfig.isLibPath(decl.getName())
|
||||
|| JSweetDefTranslatorConfig.isJSweetPath(decl.getName()))) {
|
||||
mainModule = (ModuleDeclaration) decl;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return mainModule;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addMembers(Declaration[] declarations) {
|
||||
DeclarationHelper.addMembers(this, declarations);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Declaration findDeclaration(Declaration declaration) {
|
||||
return DeclarationHelper.findDeclaration(this, declaration);
|
||||
}
|
||||
|
||||
public void addReference(String reference) {
|
||||
references.add(reference.replace('\r', ' ').replace('\n', ' ').trim());
|
||||
}
|
||||
|
||||
public List<String> getReferences() {
|
||||
return references;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return file.hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (!(obj instanceof CompilationUnit)) {
|
||||
return false;
|
||||
} else {
|
||||
return file.equals(((CompilationUnit) obj).file);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isExternal() {
|
||||
return external;
|
||||
}
|
||||
|
||||
public void setExternal(boolean external) {
|
||||
this.external = external;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,615 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
import org.jsweet.JSweetDefTranslatorConfig;
|
||||
import org.jsweet.input.typescriptdef.util.DeclarationFinder;
|
||||
import org.jsweet.input.typescriptdef.util.DirectedGraph;
|
||||
|
||||
public class Context {
|
||||
|
||||
private final static Logger logger = Logger.getLogger(Context.class);
|
||||
|
||||
private List<File> dependenciesDefinitions;
|
||||
private List<File> librariesDefinitions;
|
||||
|
||||
// contructor type -> target type
|
||||
public Map<TypeDeclaration, TypeDeclaration> mergedContructors = new HashMap<TypeDeclaration, TypeDeclaration>();
|
||||
|
||||
public Context(List<File> libraries, List<File> dependencies, boolean fetchJavadoc) {
|
||||
this.librariesDefinitions = libraries;
|
||||
this.dependenciesDefinitions = dependencies;
|
||||
this.fetchJavadoc = fetchJavadoc;
|
||||
initCoreTypes();
|
||||
}
|
||||
|
||||
public boolean verbose;
|
||||
|
||||
public File cacheDir = new File("cache");
|
||||
|
||||
public List<CompilationUnit> compilationUnits = new ArrayList<CompilationUnit>();
|
||||
|
||||
public DirectedGraph<String> dependencyGraph;
|
||||
|
||||
public List<String> libModules = new ArrayList<String>();
|
||||
|
||||
public Map<String, CompilationUnit> libModulesCompilationUnits = new HashMap<>();
|
||||
|
||||
/**
|
||||
* Lib module names -> Mixin declaration.
|
||||
*/
|
||||
public Map<String, List<TypeDeclaration>> mixins = new HashMap<>();
|
||||
|
||||
public Map<String, String> moduleDocumentations = new HashMap<>();
|
||||
|
||||
private Map<String, TypeDeclaration> types = new HashMap<String, TypeDeclaration>();
|
||||
|
||||
private Set<String> clashingWithModulesTypes = new HashSet<String>();
|
||||
|
||||
private Map<TypeDeclaration, String> typeNames = new HashMap<TypeDeclaration, String>();
|
||||
|
||||
private Map<ModuleDeclaration, String> moduleNames = new HashMap<ModuleDeclaration, String>();
|
||||
|
||||
public Map<DeclarationContainer, List<TypeDeclaration>> generatedObjectTypes = new HashMap<>();
|
||||
|
||||
/**
|
||||
* Holds the (fully qualified module names -> original name) that are
|
||||
* external (can be imported with require).
|
||||
*/
|
||||
public Map<String, String> externalModules = new HashMap<>();
|
||||
|
||||
public List<TypeDeclaration> arrayTypes = new ArrayList<TypeDeclaration>();
|
||||
|
||||
public Map<FullFunctionDeclaration, FullFunctionDeclaration> overrides = new HashMap<FullFunctionDeclaration, FullFunctionDeclaration>();
|
||||
public Map<FullFunctionDeclaration, FullFunctionDeclaration> overridens = new HashMap<FullFunctionDeclaration, FullFunctionDeclaration>();
|
||||
public List<Set<FullFunctionDeclaration>> duplicates = new ArrayList<Set<FullFunctionDeclaration>>();
|
||||
|
||||
private List<String> errors = new ArrayList<>();
|
||||
private List<String> warnings = new ArrayList<>();
|
||||
|
||||
public final boolean fetchJavadoc;
|
||||
|
||||
public void reportError(String errorMessage) {
|
||||
errors.add(errorMessage);
|
||||
logger.error(errorMessage, new Exception());
|
||||
}
|
||||
|
||||
public void reportError(String errorMessage, Throwable cause) {
|
||||
errors.add(errorMessage);
|
||||
logger.error(errorMessage, cause);
|
||||
}
|
||||
|
||||
public void reportWarning(String errorMessage) {
|
||||
warnings.add(errorMessage);
|
||||
logger.warn(errorMessage);
|
||||
}
|
||||
|
||||
public int getErrorCount() {
|
||||
return errors.size();
|
||||
}
|
||||
|
||||
public int getWarningCount() {
|
||||
return warnings.size();
|
||||
}
|
||||
|
||||
public List<String> getErrors() {
|
||||
return errors;
|
||||
}
|
||||
|
||||
public List<String> getWarnings() {
|
||||
return warnings;
|
||||
}
|
||||
|
||||
public void registerType(String name, TypeDeclaration declaration) {
|
||||
typeNames.put(declaration, name);
|
||||
// first type wins (duplicate declarations will merge to the first
|
||||
// one, see TypeMerger)
|
||||
if (!types.containsKey(name)) {
|
||||
types.put(name, declaration);
|
||||
}
|
||||
}
|
||||
|
||||
public void unregisterType(TypeDeclaration declaration) {
|
||||
String typeName = getTypeName(declaration);
|
||||
if (declaration == types.get(typeName)) {
|
||||
types.remove(typeName);
|
||||
}
|
||||
typeNames.remove(declaration);
|
||||
}
|
||||
|
||||
public List<CompilationUnit> getTranslatedCompilationUnits() {
|
||||
List<CompilationUnit> compUnits = new LinkedList<>();
|
||||
for (CompilationUnit candidate : compilationUnits) {
|
||||
if (!isDependency(candidate)) {
|
||||
compUnits.add(candidate);
|
||||
}
|
||||
}
|
||||
|
||||
return compUnits;
|
||||
}
|
||||
|
||||
public TypeDeclaration getTypeDeclaration(String name) {
|
||||
return types.get(name);
|
||||
}
|
||||
|
||||
public boolean setTypeClashingWithModule(String typeName) {
|
||||
return clashingWithModulesTypes.add(typeName);
|
||||
}
|
||||
|
||||
public boolean isTypeClashingWithModule(String typeName) {
|
||||
return clashingWithModulesTypes.contains(typeName);
|
||||
}
|
||||
|
||||
public String getTypeName(TypeDeclaration typeDeclaration) {
|
||||
return typeNames.get(typeDeclaration);
|
||||
}
|
||||
|
||||
public String getModuleName(ModuleDeclaration moduleDeclaration) {
|
||||
return moduleNames.get(moduleDeclaration);
|
||||
}
|
||||
|
||||
public String getTypeModule(TypeDeclaration typeDeclaration) {
|
||||
String name = typeNames.get(typeDeclaration);
|
||||
if (name == null) {
|
||||
return null;
|
||||
}
|
||||
int i = name.lastIndexOf('.');
|
||||
return i > 0 ? name.substring(0, i) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that all modules and types are registered in the context
|
||||
*/
|
||||
public void checkConsistency() {
|
||||
logger.info("context consistency check");
|
||||
for (QualifiedDeclaration<ModuleDeclaration> m : findDeclarations(ModuleDeclaration.class, "*")) {
|
||||
if (getModuleName(m.getDeclaration()) == null) {
|
||||
reportError("unregistered module: " + m);
|
||||
}
|
||||
}
|
||||
for (QualifiedDeclaration<TypeDeclaration> t : findDeclarations(TypeDeclaration.class, "*")) {
|
||||
if (!t.getDeclaration().isAnonymous() && getTypeName(t.getDeclaration()) == null) {
|
||||
reportError("unregistered type: " + t + " at " + t.getDeclaration().getLocation());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void dump(Logger logger) {
|
||||
List<QualifiedDeclaration<ModuleDeclaration>> modules = findDeclarations(ModuleDeclaration.class, "*");
|
||||
logger.info(modules.size() + " module" + (modules.size() > 1 ? "s" : "") + " and " + types.size() + " type"
|
||||
+ (types.size() > 1 ? "s" : "") + " found.");
|
||||
logger.info("modules: ");
|
||||
for (QualifiedDeclaration<ModuleDeclaration> m : modules) {
|
||||
logger.info(" * " + getModuleName(m.getDeclaration()));
|
||||
}
|
||||
// logger.info("types: ");
|
||||
// for (TypeDeclaration t : findDeclarations(TypeDeclaration.class,
|
||||
// "*")) {
|
||||
// if (!t.isAnonymous()) {
|
||||
// logger.info(" * " + getTypeName(t));
|
||||
// }
|
||||
// }
|
||||
// logger.info("registered types: ");
|
||||
// for (TypeDeclaration t : types.values()) {
|
||||
// logger.info(" * " + getTypeName(t));
|
||||
// }
|
||||
}
|
||||
|
||||
public void calculateArrayTypes() {
|
||||
for (TypeDeclaration t : types.values()) {
|
||||
if (t.getTypeParameters() == null || t.getTypeParameters().length != 1) {
|
||||
continue;
|
||||
}
|
||||
Declaration length = t.findDeclaration("length");
|
||||
if (length == null) {
|
||||
continue;
|
||||
}
|
||||
Declaration get = t.findDeclaration(JSweetDefTranslatorConfig.INDEXED_GET_FUCTION_NAME);
|
||||
if (get == null || !(get instanceof FunctionDeclaration)) {
|
||||
continue;
|
||||
}
|
||||
FunctionDeclaration getFunction = (FunctionDeclaration) get;
|
||||
if (getFunction.getParameters().length == 1
|
||||
&& "number".equals(getFunction.getParameters()[0].getType().getName())) {
|
||||
if (t.getTypeParameters()[0].getName() != null
|
||||
&& t.getTypeParameters()[0].getName().equals(getFunction.getType().getName())) {
|
||||
// System.out.println("found array type: " + getTypeName(t)
|
||||
// + " - " + Arrays.asList(t.getMembers()));
|
||||
arrayTypes.add(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected void initCoreTypes() {
|
||||
if (JSweetDefTranslatorConfig.isJDKReplacementMode()) {
|
||||
registerType("java.util.function.Function", TypeDeclaration.createExternalTypeDeclaration("Function"));
|
||||
registerType("java.util.function.BiFunction", TypeDeclaration.createExternalTypeDeclaration("BiFunction"));
|
||||
registerType("java.util.function.TriFunction",
|
||||
TypeDeclaration.createExternalTypeDeclaration("TriFunction"));
|
||||
registerType("java.util.function.Supplier", TypeDeclaration.createExternalTypeDeclaration("Supplier"));
|
||||
registerType("java.util.function.Consumer", TypeDeclaration.createExternalTypeDeclaration("Consumer"));
|
||||
registerType("java.util.function.BiConsumer", TypeDeclaration.createExternalTypeDeclaration("BiConsumer"));
|
||||
registerType("java.util.function.TriConsumer",
|
||||
TypeDeclaration.createExternalTypeDeclaration("TriConsumer"));
|
||||
} else {
|
||||
registerType("java.lang.Object", TypeDeclaration.createExternalTypeDeclaration("Object"));
|
||||
registerType("java.lang.Boolean", TypeDeclaration.createExternalTypeDeclaration("Boolean"));
|
||||
registerType("java.lang.String", TypeDeclaration.createExternalTypeDeclaration("String"));
|
||||
registerType("java.util.function.Function", TypeDeclaration.createExternalTypeDeclaration("Function"));
|
||||
registerType("java.util.function.BiFunction", TypeDeclaration.createExternalTypeDeclaration("BiFunction"));
|
||||
registerType("jsweet.util.function.TriFunction",
|
||||
TypeDeclaration.createExternalTypeDeclaration("TriFunction"));
|
||||
registerType("java.util.function.Supplier", TypeDeclaration.createExternalTypeDeclaration("Supplier"));
|
||||
registerType("java.util.function.Consumer", TypeDeclaration.createExternalTypeDeclaration("Consumer"));
|
||||
registerType("java.util.function.BiConsumer", TypeDeclaration.createExternalTypeDeclaration("BiConsumer"));
|
||||
registerType("jsweet.util.function.TriConsumer",
|
||||
TypeDeclaration.createExternalTypeDeclaration("TriConsumer"));
|
||||
}
|
||||
registerType("java.lang.Double", TypeDeclaration.createExternalTypeDeclaration("Double"));
|
||||
registerType("java.lang.Runnable", TypeDeclaration.createExternalTypeDeclaration("Runnable"));
|
||||
registerType("java.lang.Void", TypeDeclaration.createExternalTypeDeclaration("Void"));
|
||||
registerType("double", TypeDeclaration.createExternalTypeDeclaration("double"));
|
||||
registerType("boolean", TypeDeclaration.createExternalTypeDeclaration("boolean"));
|
||||
registerType("void", TypeDeclaration.createExternalTypeDeclaration("void"));
|
||||
registerType("any", TypeDeclaration.createExternalTypeDeclaration("any"));
|
||||
registerType("string", TypeDeclaration.createExternalTypeDeclaration("string"));
|
||||
registerType("number", TypeDeclaration.createExternalTypeDeclaration("number"));
|
||||
registerType("symbol", TypeDeclaration.createExternalTypeDeclaration("symbol"));
|
||||
registerType(JSweetDefTranslatorConfig.UNION_CLASS_NAME,
|
||||
TypeDeclaration.createExternalTypeDeclaration("interface", "Union"));
|
||||
for (int i = 2; i <= 6; i++) {
|
||||
registerType(
|
||||
JSweetDefTranslatorConfig.TUPLE_CLASSES_PACKAGE + "."
|
||||
+ JSweetDefTranslatorConfig.TUPLE_CLASSES_PREFIX + i,
|
||||
TypeDeclaration.createExternalTypeDeclaration(JSweetDefTranslatorConfig.TUPLE_CLASSES_PREFIX + i));
|
||||
}
|
||||
}
|
||||
|
||||
public void addDuplicate(FullFunctionDeclaration function1, FullFunctionDeclaration function2) {
|
||||
boolean added = false;
|
||||
for (Set<FullFunctionDeclaration> s : duplicates) {
|
||||
if (s.contains(function1) || s.contains(function2)) {
|
||||
s.add(function1);
|
||||
s.add(function2);
|
||||
added = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!added) {
|
||||
Set<FullFunctionDeclaration> s = new HashSet<FullFunctionDeclaration>();
|
||||
s.add(function1);
|
||||
s.add(function2);
|
||||
duplicates.add(s);
|
||||
}
|
||||
}
|
||||
|
||||
public void addOverride(FullFunctionDeclaration override, FullFunctionDeclaration overridden) {
|
||||
overrides.put(override, overridden);
|
||||
overridens.put(overridden, override);
|
||||
}
|
||||
|
||||
public String getFullTypeNameNoErasure(TypeReference t) {
|
||||
if (t.isArray()) {
|
||||
return getFullTypeNameNoErasure(t.getComponentType()) + "[]";
|
||||
} else {
|
||||
Type type = t.getDeclaration();
|
||||
if (type instanceof TypeDeclaration) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(((TypeDeclaration) type).getName());
|
||||
if (t.getTypeArguments() != null) {
|
||||
sb.append("<");
|
||||
for (int i = 0; i < t.getTypeArguments().length; i++) {
|
||||
sb.append(getFullTypeNameNoErasure(t.getTypeArguments()[i]));
|
||||
if (i < t.getTypeArguments().length) {
|
||||
sb.append(",");
|
||||
}
|
||||
}
|
||||
if (t.getTypeArguments().length > 0) {
|
||||
sb.deleteCharAt(sb.length() - 1);
|
||||
}
|
||||
sb.append(">");
|
||||
}
|
||||
return sb.toString();
|
||||
} else if (type instanceof TypeParameterDeclaration) {
|
||||
return type.getName();
|
||||
} else {
|
||||
return t.getWrappingTypeName();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public String getShortTypeNameNoErasure(TypeReference t) {
|
||||
if (t.isArray()) {
|
||||
return getShortTypeNameNoErasure(t.getComponentType()) + "[]";
|
||||
} else {
|
||||
Type type = t.getDeclaration();
|
||||
if (type instanceof TypeDeclaration) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String s = ((TypeDeclaration) type).getName();
|
||||
// todo: wrap type (no primitive types)
|
||||
sb.append(s);
|
||||
if (t.getTypeArguments() != null) {
|
||||
sb.append("<");
|
||||
for (int i = 0; i < t.getTypeArguments().length; i++) {
|
||||
sb.append(getShortTypeNameNoErasure(t.getTypeArguments()[i]));
|
||||
if (i < t.getTypeArguments().length) {
|
||||
sb.append(",");
|
||||
}
|
||||
}
|
||||
if (t.getTypeArguments().length > 0) {
|
||||
sb.deleteCharAt(sb.length() - 1);
|
||||
}
|
||||
sb.append(">");
|
||||
}
|
||||
return sb.toString();
|
||||
} else if (type instanceof TypeParameterDeclaration) {
|
||||
return type.getName();
|
||||
} else {
|
||||
return t.getWrappingTypeName();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public String getShortTypeNameErased(TypeReference t) {
|
||||
if (t.isArray()) {
|
||||
return getShortTypeNameErased(t.getComponentType()) + "[]";
|
||||
} else {
|
||||
Type type = t.getDeclaration();
|
||||
if (type instanceof TypeDeclaration) {
|
||||
// todo: wrap type (no primitive types)
|
||||
return ((TypeDeclaration) type).getName();
|
||||
} else if (type instanceof TypeParameterDeclaration) {
|
||||
return type.getName();
|
||||
} else {
|
||||
return t.getWrappingTypeName();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public String getTypeNameErased(TypeReference t) {
|
||||
if (t.isArray()) {
|
||||
return getTypeNameErased(t.getComponentType()) + "[]";
|
||||
}
|
||||
if (t instanceof FunctionalTypeReference) {
|
||||
throw new RuntimeException("invalid functional type" + t);
|
||||
}
|
||||
if ("any".equals(t.getName())) {
|
||||
return "java.lang.Object";
|
||||
}
|
||||
Type type = t.getDeclaration();
|
||||
if (type instanceof TypeDeclaration) {
|
||||
return getTypeName((TypeDeclaration) type);
|
||||
} else if (type instanceof TypeParameterDeclaration) {
|
||||
TypeParameterDeclaration tpd = (TypeParameterDeclaration) type;
|
||||
if (tpd.getUpperBound() == null) {
|
||||
return "java.lang.Object";
|
||||
} else {
|
||||
return getTypeNameErased(tpd.getUpperBound());
|
||||
}
|
||||
} else {
|
||||
return t.getWrappingTypeName();
|
||||
// Token token = getCurrentToken();
|
||||
// System.err.println("ERROR: invalid type "+t.getName() + (token ==
|
||||
// null ? "" : " at " + token.getLocation()));
|
||||
// throw new RuntimeException("invalid type");
|
||||
}
|
||||
}
|
||||
|
||||
public String getSignature(FunctionDeclaration function) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(function.getName());
|
||||
sb.append("(");
|
||||
for (ParameterDeclaration p : function.getParameters()) {
|
||||
sb.append(getFullTypeNameNoErasure(p.getType()));
|
||||
sb.append(",");
|
||||
}
|
||||
if (function.getParameters().length > 0) {
|
||||
sb.deleteCharAt(sb.length() - 1);
|
||||
}
|
||||
sb.append(")");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public List<File> getDependenciesDefinitions() {
|
||||
return dependenciesDefinitions;
|
||||
}
|
||||
|
||||
public List<File> getLibrariesDefinitions() {
|
||||
return librariesDefinitions;
|
||||
}
|
||||
|
||||
public List<File> getAllDefinitions() {
|
||||
List<File> allFiles = new LinkedList<>(getDependenciesDefinitions());
|
||||
allFiles.addAll(getLibrariesDefinitions());
|
||||
|
||||
return allFiles;
|
||||
}
|
||||
|
||||
public boolean isDependency(CompilationUnit compilationUnit) {
|
||||
String currentLibPath = compilationUnit.getFile().getAbsolutePath();
|
||||
for (File dependencyFile : getLibrariesDefinitions()) {
|
||||
if (currentLibPath.equals(dependencyFile.getAbsolutePath())) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public void registerModule(String name, ModuleDeclaration moduleDeclaration) {
|
||||
moduleNames.put(moduleDeclaration, name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the module that contains the belonging Javascript library definition
|
||||
* from a fully qualified name. If the given name does not belong to any
|
||||
* library, returns null.
|
||||
*
|
||||
* @param qualifiedName
|
||||
* ex: def.xxx
|
||||
*/
|
||||
public String getLibModule(String qualifiedName) {
|
||||
if (libModules.contains(qualifiedName)) {
|
||||
return qualifiedName;
|
||||
}
|
||||
// TODO: we need a faster way
|
||||
for (String m : libModules) {
|
||||
if (qualifiedName.startsWith(m + ".")) {
|
||||
return m;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public String getLibRelativePath(String qualifiedName) {
|
||||
if (JSweetDefTranslatorConfig.isLibPath(qualifiedName)) {
|
||||
String m = getLibModule(qualifiedName);
|
||||
if (m != null) {
|
||||
if (qualifiedName.length() > m.length()) {
|
||||
return qualifiedName.substring(m.length() + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
return qualifiedName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds in the AST all the declarations for a given type and matching the
|
||||
* given full name.
|
||||
*
|
||||
* <p>
|
||||
* A declaration expression supports the * wildcard to allow any path in the
|
||||
* expression. Examples of declaration expressions:
|
||||
* <ul>
|
||||
* <li>"a.d.c": matches all declarations having this exact full name</li>
|
||||
* <li>"*.c": matches all the declarations named "c"</li>
|
||||
* <li>"a.*": matches all the declarations in the "a" container</li>
|
||||
* <li>"a.*.c": matches all the declarations named "c" in the "a" container,
|
||||
* with any path between "a" and "c"</li>
|
||||
* </ul>
|
||||
*
|
||||
* @param type
|
||||
* the declarations type
|
||||
* @param declExpression
|
||||
* an expression to match the full name, supporting wildcards
|
||||
* @param compilationUnits
|
||||
* the compilation unit(s) to search in (search in all available
|
||||
* compilation units if omitted)
|
||||
* @return the list of all matching declarations by match order
|
||||
*/
|
||||
public <T extends Declaration> List<QualifiedDeclaration<T>> findDeclarations(Class<T> type, String declFullName,
|
||||
CompilationUnit... compilationUnits) {
|
||||
|
||||
final Pattern pattern = declFullName.contains("*")
|
||||
? Pattern.compile(declFullName.replace(".", "\\.").replace("*", ".*")) : null;
|
||||
|
||||
DeclarationFinder<T> finder = new DeclarationFinder<>(this, new DeclarationFinder.Matcher<T>() {
|
||||
@Override
|
||||
public void matches(DeclarationFinder<T> scanner, Visitable node) {
|
||||
String declarationName = scanner.getCurrentDeclarationName();
|
||||
if (pattern != null) {
|
||||
if (type.isInstance(node) && pattern.matcher(declarationName).matches()) {
|
||||
scanner.setMatchState(true, true);
|
||||
} else {
|
||||
scanner.setMatchState(false, true);
|
||||
}
|
||||
} else {
|
||||
if (declFullName.equals(declarationName)) {
|
||||
if (type.isInstance(node)) {
|
||||
scanner.setMatchState(true, false);
|
||||
} else {
|
||||
scanner.setMatchState(false, false);
|
||||
}
|
||||
} else if (declFullName.startsWith(declarationName)) {
|
||||
scanner.setMatchState(false, true);
|
||||
} else {
|
||||
scanner.setMatchState(false, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
finder.scan(compilationUnits.length == 0 ? this.compilationUnits : Arrays.asList(compilationUnits));
|
||||
return finder.getMatches();
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds in the AST the first declaration for a given type and matching the
|
||||
* given full name.
|
||||
*
|
||||
* <p>
|
||||
* A declaration expression supports the * wildcard to allow any path in the
|
||||
* expression. Examples of declaration expressions:
|
||||
* <ul>
|
||||
* <li>"a.d.c": matches all declarations having this exact full name</li>
|
||||
* <li>"*.c": matches all the declarations named "c"</li>
|
||||
* <li>"a.*": matches all the declarations in the "a" container</li>
|
||||
* <li>"a.*.c": matches all the declarations named "c" in the "a" container,
|
||||
* with any path between "a" and "c"</li>
|
||||
* </ul>
|
||||
*
|
||||
* @param type
|
||||
* the declarations type
|
||||
* @param declExpression
|
||||
* an expression to match the full name, supporting wildcards
|
||||
* @param compilationUnits
|
||||
* the compilation unit(s) to search in (search in all available
|
||||
* compilation units if omitted)
|
||||
* @return the first matching declaration
|
||||
*/
|
||||
public <T extends Declaration> QualifiedDeclaration<T> findFirstDeclaration(Class<T> type, String declFullName,
|
||||
CompilationUnit... compilationUnits) {
|
||||
List<QualifiedDeclaration<T>> matches = findDeclarations(type, declFullName, compilationUnits);
|
||||
if (matches.isEmpty()) {
|
||||
return null;
|
||||
} else {
|
||||
return matches.get(0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a mixin (type declaration) for a given lib. Registered mixins
|
||||
* will be reflected in the @Root annotation of the lib.
|
||||
*/
|
||||
public void resiterMixin(String libModule, TypeDeclaration typeDeclaration) {
|
||||
List<TypeDeclaration> mixinsForLib = mixins.get(libModule);
|
||||
if (mixinsForLib == null) {
|
||||
mixinsForLib = new ArrayList<>();
|
||||
mixins.put(libModule, mixinsForLib);
|
||||
}
|
||||
mixinsForLib.add(typeDeclaration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the registered mixins for the given lib.
|
||||
*/
|
||||
public List<TypeDeclaration> getMixins(String libModule) {
|
||||
return mixins.get(libModule);
|
||||
}
|
||||
|
||||
public CompilationUnit getCompilationUnit(File tsDefFile) {
|
||||
for (CompilationUnit compilUnit : compilationUnits) {
|
||||
if (tsDefFile.equals(compilUnit.file)) {
|
||||
return compilUnit;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public final Map<TypeDeclaration, String> getTypeNames() {
|
||||
return typeNames;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,48 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.AnnotatedElement;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
public interface Declaration extends AstNode, NamedElement, AnnotatedElement {
|
||||
|
||||
String getDocumentation();
|
||||
|
||||
void setDocumentation(String documentation);
|
||||
|
||||
void addModifier(String modifier);
|
||||
|
||||
void removeModifier(String modifier);
|
||||
|
||||
boolean hasModifier(String modifier);
|
||||
|
||||
Set<String> getModifiers();
|
||||
|
||||
void setModifiers(Set<String> modifiers);
|
||||
|
||||
Declaration copy();
|
||||
|
||||
boolean isInputAnnotatedWith(String annotation);
|
||||
|
||||
void addAnnotation(Annotation annotation);
|
||||
|
||||
<T extends Annotation> T removeAnnotation(Class<T> annotationClass);
|
||||
|
||||
void addStringAnnotation(String annotation);
|
||||
|
||||
void removeStringAnnotation(String annotation);
|
||||
|
||||
List<String> getStringAnnotations();
|
||||
|
||||
void setStringAnnotations(List<String> stringAnnotations);
|
||||
|
||||
boolean hasStringAnnotation(String annotation);
|
||||
|
||||
String getStringAnnotation(String annotation);
|
||||
|
||||
boolean isQuotedName();
|
||||
|
||||
void setQuotedName(boolean quotedName);
|
||||
|
||||
}
|
||||
@ -0,0 +1,35 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public interface DeclarationContainer extends Visitable {
|
||||
|
||||
Declaration[] getMembers();
|
||||
|
||||
void addMember(Declaration declaration);
|
||||
|
||||
void replaceMember(Declaration existingDeclaration, Declaration withNewDeclaration);
|
||||
|
||||
void removeMember(Declaration declaration);
|
||||
|
||||
void clearMembers();
|
||||
|
||||
FunctionDeclaration findFirstFunction(String name);
|
||||
|
||||
List<FunctionDeclaration> findFunctions(String name);
|
||||
|
||||
VariableDeclaration findVariable(String name);
|
||||
|
||||
VariableDeclaration findVariableIgnoreCase(String name);
|
||||
|
||||
TypeDeclaration findType(String name);
|
||||
|
||||
TypeDeclaration findTypeIgnoreCase(String name);
|
||||
|
||||
Declaration findDeclaration(String name);
|
||||
|
||||
Declaration findDeclaration(Declaration declaration);
|
||||
|
||||
void addMembers(Declaration[] declarations);
|
||||
}
|
||||
@ -0,0 +1,411 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.jsweet.JSweetDefTranslatorConfig;
|
||||
|
||||
public abstract class DeclarationHelper {
|
||||
|
||||
public static final Map<String, int[]> JAVA_OBJECT_METHODS = new HashMap<String, int[]>();
|
||||
// public static final Set<String> JAVA_FINAL_OBJECT_METHODS = new
|
||||
// HashSet<String>();
|
||||
// public static final Set<String> JAVA_OBJECT_METHOD_NAMES = new
|
||||
// HashSet<String>();
|
||||
public static final Set<String> JS_OBJECT_METHOD_NAMES = new HashSet<String>();
|
||||
public static final Set<String> JS_PRIMITIVE_TYPE_NAMES = new HashSet<String>();
|
||||
|
||||
static {
|
||||
JS_OBJECT_METHOD_NAMES.add("toString");
|
||||
|
||||
JS_PRIMITIVE_TYPE_NAMES.add("boolean");
|
||||
JS_PRIMITIVE_TYPE_NAMES.add("number");
|
||||
|
||||
if (!JSweetDefTranslatorConfig.isJDKReplacementMode()) {
|
||||
// toString is common to Java and Javascript
|
||||
// JAVA_OBJECT_METHOD_NAMES.add("finalize");
|
||||
// JAVA_OBJECT_METHOD_NAMES.add("clone");
|
||||
// JAVA_OBJECT_METHOD_NAMES.add("equals");
|
||||
// JAVA_OBJECT_METHOD_NAMES.add("hashCode");
|
||||
// JAVA_OBJECT_METHOD_NAMES.add("notify");
|
||||
// JAVA_OBJECT_METHOD_NAMES.add("notifyAll");
|
||||
// JAVA_OBJECT_METHOD_NAMES.add("getClass");
|
||||
|
||||
JAVA_OBJECT_METHODS.put("finalize", new int[] { 0 });
|
||||
JAVA_OBJECT_METHODS.put("clone", new int[] { 0 });
|
||||
JAVA_OBJECT_METHODS.put("equals", new int[] { 1 });
|
||||
JAVA_OBJECT_METHODS.put("hashCode", new int[] { 0 });
|
||||
JAVA_OBJECT_METHODS.put("notify", new int[] { 0 });
|
||||
JAVA_OBJECT_METHODS.put("notifyAll", new int[] { 0 });
|
||||
JAVA_OBJECT_METHODS.put("getClass", new int[] { 0 });
|
||||
JAVA_OBJECT_METHODS.put("wait", new int[] { 0, 1, 2 });
|
||||
|
||||
// JAVA_FINAL_OBJECT_METHODS.add("notify():void");
|
||||
// JAVA_FINAL_OBJECT_METHODS.add("notifyAll():void");
|
||||
// JAVA_FINAL_OBJECT_METHODS.add("wait():void");
|
||||
// JAVA_FINAL_OBJECT_METHODS.add("wait(long):void");
|
||||
// JAVA_FINAL_OBJECT_METHODS.add("wait(long,int):void");
|
||||
// JAVA_FINAL_OBJECT_METHODS.add("getClass():java.lang.Class");
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isPrimitiveType(String name) {
|
||||
return JS_PRIMITIVE_TYPE_NAMES.contains(name);
|
||||
}
|
||||
|
||||
public static String getActualFunctionName(FunctionDeclaration function) {
|
||||
if (JAVA_OBJECT_METHODS.keySet().contains(function.getName())) {
|
||||
if (ArrayUtils.contains(JAVA_OBJECT_METHODS.get(function.getName()), function.getParameters().length)) {
|
||||
return StringUtils.capitalize(function.getName());
|
||||
}
|
||||
}
|
||||
return function.getName();
|
||||
}
|
||||
|
||||
public static String toJavaIdentifier(String identifier) {
|
||||
if (JSweetDefTranslatorConfig.JAVA_KEYWORDS.contains(identifier)) {
|
||||
return StringUtils.capitalize(identifier);
|
||||
}
|
||||
if (JSweetDefTranslatorConfig.JAVA_TS_KEYWORDS.contains(identifier)) {
|
||||
return StringUtils.capitalize(identifier);
|
||||
}
|
||||
|
||||
// TODO: this is not what happens... it must have been transformed
|
||||
// before
|
||||
if (Character.isDigit(identifier.charAt(0))) {
|
||||
return "$$" + identifier.charAt(0) + "$$" + identifier.substring(1);
|
||||
}
|
||||
return identifier;
|
||||
}
|
||||
|
||||
public static Declaration[] addMember(DeclarationContainer container, Declaration declaration) {
|
||||
return ArrayUtils.add(container.getMembers(), declaration);
|
||||
}
|
||||
|
||||
public static Declaration[] replaceMember(DeclarationContainer container, Declaration existingDeclaration,
|
||||
Declaration withNewDeclaration) {
|
||||
int index = ArrayUtils.indexOf(container.getMembers(), existingDeclaration);
|
||||
if (index >= 0) {
|
||||
container.getMembers()[index] = withNewDeclaration;
|
||||
}
|
||||
return container.getMembers();
|
||||
}
|
||||
|
||||
public static Declaration[] removeMember(DeclarationContainer container, Declaration declaration) {
|
||||
int index = ArrayUtils.indexOf(container.getMembers(), declaration);
|
||||
if (index < 0) {
|
||||
return container.getMembers();
|
||||
}
|
||||
return ArrayUtils.remove(container.getMembers(), index);
|
||||
}
|
||||
|
||||
public static List<FunctionDeclaration> findConstructors(TypeDeclaration typeDeclaration) {
|
||||
if (typeDeclaration.getMembers() == null) {
|
||||
return null;
|
||||
}
|
||||
List<FunctionDeclaration> constructors = new ArrayList<FunctionDeclaration>();
|
||||
for (Declaration m : typeDeclaration.getMembers()) {
|
||||
if (m instanceof FunctionDeclaration) {
|
||||
if (((FunctionDeclaration) m).isConstructor()) {
|
||||
constructors.add((FunctionDeclaration) m);
|
||||
}
|
||||
}
|
||||
}
|
||||
return constructors;
|
||||
}
|
||||
|
||||
public static FunctionDeclaration findFirstConstructor(TypeDeclaration typeDeclaration) {
|
||||
if (typeDeclaration.getMembers() == null) {
|
||||
return null;
|
||||
}
|
||||
for (Declaration m : typeDeclaration.getMembers()) {
|
||||
if (m instanceof FunctionDeclaration) {
|
||||
if (((FunctionDeclaration) m).isConstructor()) {
|
||||
return (FunctionDeclaration) m;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static boolean isStatic(TypeDeclaration typeDeclaration) {
|
||||
if (typeDeclaration.getMembers() == null) {
|
||||
return true;
|
||||
}
|
||||
if (!typeDeclaration.isInterface()) {
|
||||
return false;
|
||||
}
|
||||
for (Declaration m : typeDeclaration.getMembers()) {
|
||||
if (!m.hasModifier("static")) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static TypeReference[] toTypeArguments(TypeParameterDeclaration[] typeParameterDeclarations) {
|
||||
if (typeParameterDeclarations == null) {
|
||||
return null;
|
||||
}
|
||||
TypeReference[] args = new TypeReference[typeParameterDeclarations.length];
|
||||
for (int i = 0; i < typeParameterDeclarations.length; i++) {
|
||||
args[i] = new TypeReference(null, typeParameterDeclarations[i].getName(), null);
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
public static List<FunctionDeclaration> findFunctions(DeclarationContainer container, String name) {
|
||||
if (container.getMembers() == null) {
|
||||
return null;
|
||||
}
|
||||
List<FunctionDeclaration> functions = new ArrayList<FunctionDeclaration>();
|
||||
for (Declaration m : container.getMembers()) {
|
||||
if (m instanceof FunctionDeclaration) {
|
||||
if (((FunctionDeclaration) m).getName().equals(name)) {
|
||||
functions.add((FunctionDeclaration) m);
|
||||
}
|
||||
}
|
||||
}
|
||||
return functions;
|
||||
}
|
||||
|
||||
public static FunctionDeclaration findFirstFunction(DeclarationContainer container, String name) {
|
||||
if (container.getMembers() == null) {
|
||||
return null;
|
||||
}
|
||||
for (Declaration m : container.getMembers()) {
|
||||
if (m instanceof FunctionDeclaration) {
|
||||
if (((FunctionDeclaration) m).getName().equals(name)) {
|
||||
return (FunctionDeclaration) m;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static VariableDeclaration findVariable(DeclarationContainer container, String name) {
|
||||
if (container.getMembers() == null) {
|
||||
return null;
|
||||
}
|
||||
for (Declaration m : container.getMembers()) {
|
||||
if (m instanceof VariableDeclaration) {
|
||||
if (((VariableDeclaration) m).getName().equals(name)) {
|
||||
return (VariableDeclaration) m;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static VariableDeclaration findVariableIgnoreCase(DeclarationContainer container, String name) {
|
||||
if (container.getMembers() == null) {
|
||||
return null;
|
||||
}
|
||||
for (Declaration m : container.getMembers()) {
|
||||
if (m instanceof VariableDeclaration) {
|
||||
if (((VariableDeclaration) m).getName().equalsIgnoreCase(name)) {
|
||||
return (VariableDeclaration) m;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static TypeDeclaration findType(DeclarationContainer container, String name) {
|
||||
if (container.getMembers() == null) {
|
||||
return null;
|
||||
}
|
||||
for (Declaration m : container.getMembers()) {
|
||||
if (m instanceof TypeDeclaration) {
|
||||
if (((TypeDeclaration) m).getName().equals(name)) {
|
||||
return (TypeDeclaration) m;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static TypeDeclaration findTypeIgnoreCase(DeclarationContainer container, String name) {
|
||||
if (container.getMembers() == null) {
|
||||
return null;
|
||||
}
|
||||
for (Declaration m : container.getMembers()) {
|
||||
if (m instanceof TypeDeclaration) {
|
||||
if (((TypeDeclaration) m).getName().equalsIgnoreCase(name)) {
|
||||
return (TypeDeclaration) m;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static ModuleDeclaration findModule(DeclarationContainer container, String name) {
|
||||
if (container.getMembers() == null) {
|
||||
return null;
|
||||
}
|
||||
for (Declaration m : container.getMembers()) {
|
||||
if (m instanceof ModuleDeclaration) {
|
||||
if (((ModuleDeclaration) m).getName().equals(name)) {
|
||||
return (ModuleDeclaration) m;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Declaration findDeclaration(DeclarationContainer container, String name) {
|
||||
if (container.getMembers() == null) {
|
||||
return null;
|
||||
}
|
||||
for (Declaration d : container.getMembers()) {
|
||||
if (d.getName().equals(name)) {
|
||||
return d;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Declaration findDeclaration(DeclarationContainer container, Declaration declaration) {
|
||||
if (container.getMembers() == null) {
|
||||
return null;
|
||||
}
|
||||
int i = ArrayUtils.indexOf(container.getMembers(), declaration);
|
||||
if (i < 0) {
|
||||
return null;
|
||||
} else {
|
||||
return container.getMembers()[i];
|
||||
}
|
||||
}
|
||||
|
||||
public static Declaration[] findAllVisibleDeclarations(DeclarationContainer container, Declaration declaration) {
|
||||
Declaration[] result = {};
|
||||
if (container.getMembers() == null) {
|
||||
return result;
|
||||
}
|
||||
for (Declaration d : container.getMembers()) {
|
||||
if (!d.isHidden() && d.equals(declaration)) {
|
||||
result = ArrayUtils.add(result, d);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void addMembers(DeclarationContainer targetContainer, Declaration[] declarations) {
|
||||
for (Declaration d : declarations) {
|
||||
if (findDeclaration(targetContainer, d) == null) {
|
||||
targetContainer.addMember(d);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean areDeclarationsEqual(Declaration[] declarations1, Declaration[] declarations2) {
|
||||
for (Declaration d : declarations1) {
|
||||
if (!ArrayUtils.contains(declarations2, d)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
for (Declaration d : declarations2) {
|
||||
if (!ArrayUtils.contains(declarations1, d)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T extends Declaration> T[] copy(T[] declarations) {
|
||||
if (declarations == null) {
|
||||
return null;
|
||||
}
|
||||
T[] to = Arrays.copyOf(declarations, declarations.length);
|
||||
for (int i = 0; i < declarations.length; i++) {
|
||||
to[i] = (T) declarations[i].copy();
|
||||
}
|
||||
return (T[]) to;
|
||||
}
|
||||
|
||||
public static <T extends TypeReference> T[] copyReferences(T[] references) {
|
||||
return copyReferences(references, false);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T extends TypeReference> T[] copyReferences(T[] references, boolean copyDeclarations) {
|
||||
if (references == null) {
|
||||
return null;
|
||||
}
|
||||
T[] to = Arrays.copyOf(references, references.length);
|
||||
for (int i = 0; i < references.length; i++) {
|
||||
to[i] = (T) references[i].copy(copyDeclarations);
|
||||
}
|
||||
return (T[]) to;
|
||||
}
|
||||
|
||||
public static <T extends Type> TypeReference[] toReferences(T[] types) {
|
||||
if (types == null) {
|
||||
return null;
|
||||
}
|
||||
TypeReference[] to = new TypeReference[types.length];
|
||||
for (int i = 0; i < types.length; i++) {
|
||||
to[i] = new TypeReference(null, types[i], null);
|
||||
}
|
||||
return to;
|
||||
}
|
||||
|
||||
public static TypeDeclaration createFunctionalType(String name, int parameterCount, boolean hasResult,
|
||||
boolean disambiguation) {
|
||||
TypeDeclaration functionalType = null;
|
||||
TypeParameterDeclaration[] typeParameters = new TypeParameterDeclaration[parameterCount];
|
||||
for (int i = 0; i < parameterCount; i++) {
|
||||
typeParameters[i] = new TypeParameterDeclaration(null, "T" + (i + 1));
|
||||
}
|
||||
TypeParameterDeclaration resultType = new TypeParameterDeclaration(null, "R");
|
||||
ParameterDeclaration[] parameters = new ParameterDeclaration[typeParameters.length];
|
||||
for (int i = 0; i < typeParameters.length; i++) {
|
||||
parameters[i] = new ParameterDeclaration(null, "p" + (i + 1),
|
||||
new TypeReference(null, typeParameters[i], null), false, false);
|
||||
}
|
||||
FunctionDeclaration newFunction = new FunctionDeclaration(null,
|
||||
JSweetDefTranslatorConfig.ANONYMOUS_FUNCTION_NAME,
|
||||
hasResult ? new TypeReference(null, resultType, null) : new TypeReference(null, "void", null),
|
||||
parameters, null);
|
||||
|
||||
if (hasResult) {
|
||||
typeParameters = ArrayUtils.add(typeParameters, resultType);
|
||||
}
|
||||
functionalType = new TypeDeclaration(null, "interface", name, typeParameters, null,
|
||||
new FunctionDeclaration[] { newFunction });
|
||||
functionalType.addAnnotation(new FunctionalInterface() {
|
||||
@Override
|
||||
public Class<? extends Annotation> annotationType() {
|
||||
return FunctionalInterface.class;
|
||||
}
|
||||
});
|
||||
if (disambiguation) {
|
||||
functionalType.setDocumentation(
|
||||
"/** This functional interface should be used for disambiguating lambdas in function parameters (by casting to this interface)."
|
||||
+ "<p>It was automatically generated for functions (taking lambdas) that lead to the same erased signature. */");
|
||||
} else {
|
||||
functionalType.setDocumentation(
|
||||
"/** This functional interface was automatically generated for allowing lambdas taking "
|
||||
+ parameterCount + " parameters " + (hasResult ? " and returning a result." : ".") + " */");
|
||||
}
|
||||
return functionalType;
|
||||
}
|
||||
|
||||
public static Type getTypeOrComponentType(TypeReference typeReference) {
|
||||
if (typeReference.isArray()) {
|
||||
return getTypeOrComponentType(typeReference.getComponentType());
|
||||
} else {
|
||||
return typeReference.getDeclaration();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,35 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
|
||||
public class FullFunctionDeclaration {
|
||||
|
||||
public FullFunctionDeclaration(ModuleDeclaration declaringModule, TypeDeclaration declaringType, FunctionDeclaration function) {
|
||||
super();
|
||||
this.declaringType = declaringType;
|
||||
this.function = function;
|
||||
}
|
||||
|
||||
public TypeDeclaration declaringType;
|
||||
public ModuleDeclaration declaringModule;
|
||||
public FunctionDeclaration function;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return (declaringModule == null ? "" : declaringModule.getName() + ".") + (declaringType == null ? "" : declaringType.getName() + ".") + function;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (!(obj instanceof FullFunctionDeclaration)) {
|
||||
return false;
|
||||
}
|
||||
FullFunctionDeclaration d = (FullFunctionDeclaration) obj;
|
||||
return this.function == d.function;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return function.hashCode();
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,121 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
|
||||
import org.jsweet.JSweetDefTranslatorConfig;
|
||||
|
||||
public class FunctionDeclaration extends AbstractTypedDeclaration implements TypeParameterizedElement {
|
||||
|
||||
public static final String NEW_FUNCTION_RESERVED_NAME = JSweetDefTranslatorConfig.NEW_FUNCTION_NAME;
|
||||
public static final String ANONYMOUS_FUNCTION_RESERVED_NAME = JSweetDefTranslatorConfig.ANONYMOUS_FUNCTION_NAME;
|
||||
public static final String INDEXSIG_RESERVED_NAME = JSweetDefTranslatorConfig.INDEXED_GET_FUCTION_NAME;
|
||||
|
||||
ParameterDeclaration[] parameters;
|
||||
TypeParameterDeclaration[] typeParameters;
|
||||
|
||||
public FunctionDeclaration(Token token, String name, TypeReference type, ParameterDeclaration[] parameters,
|
||||
TypeParameterDeclaration[] typeParameters) {
|
||||
super(token, name, type);
|
||||
this.parameters = parameters;
|
||||
this.typeParameters = typeParameters;
|
||||
|
||||
// System.out.println("new " + this);
|
||||
}
|
||||
|
||||
public boolean isConstructor() {
|
||||
return "new".equals(name) || "constructor".equals(name) || NEW_FUNCTION_RESERVED_NAME.equals(name);
|
||||
}
|
||||
|
||||
public boolean isIndexSignature() {
|
||||
return INDEXSIG_RESERVED_NAME.equals(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAnonymous() {
|
||||
return super.isAnonymous() || ANONYMOUS_FUNCTION_RESERVED_NAME.equals(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(super.toString());
|
||||
sb.append("(");
|
||||
for (ParameterDeclaration p : parameters) {
|
||||
sb.append(p.name);
|
||||
sb.append(":");
|
||||
sb.append(p.getType().toString());
|
||||
sb.append(",");
|
||||
}
|
||||
if (parameters.length > 0) {
|
||||
sb.deleteCharAt(sb.length() - 1);
|
||||
}
|
||||
sb.append(")");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(Visitor v) {
|
||||
v.visitFunctionDeclaration(this);
|
||||
}
|
||||
|
||||
public ParameterDeclaration[] getParameters() {
|
||||
return parameters;
|
||||
}
|
||||
|
||||
public void setParameters(ParameterDeclaration[] parameters) {
|
||||
this.parameters = parameters;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TypeParameterDeclaration[] getTypeParameters() {
|
||||
return this.typeParameters;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTypeParameters(TypeParameterDeclaration[] typeParameters) {
|
||||
this.typeParameters = typeParameters;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (!o.getClass().equals(getClass())) {
|
||||
return false;
|
||||
}
|
||||
FunctionDeclaration fd = (FunctionDeclaration) o;
|
||||
String name1 = getName();
|
||||
if ("constructor".equals(name1)) {
|
||||
name1 = "new";
|
||||
}
|
||||
String name2 = fd.getName();
|
||||
if ("constructor".equals(name2)) {
|
||||
name2 = "new";
|
||||
}
|
||||
if (name2 == null && name1 != null) {
|
||||
return false;
|
||||
}
|
||||
if (!name2.equals(name1)) {
|
||||
return false;
|
||||
}
|
||||
if (fd.parameters.length != parameters.length) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < fd.parameters.length; i++) {
|
||||
if (!parameters[i].getType().equals(fd.parameters[i].getType())) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FunctionDeclaration copy() {
|
||||
FunctionDeclaration copy = new FunctionDeclaration(null, name, getType() == null ? null : getType().copy(),
|
||||
DeclarationHelper.copy(parameters), DeclarationHelper.copy(typeParameters));
|
||||
copy.setDocumentation(getDocumentation());
|
||||
copy.setModifiers(this.getModifiers() == null ? null : new HashSet<String>(getModifiers()));
|
||||
copy.setStringAnnotations(this.getStringAnnotations() == null ? null : new ArrayList<String>(
|
||||
getStringAnnotations()));
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,102 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
public class FunctionalTypeReference extends TypeReference implements TypeParameterizedElement {
|
||||
|
||||
private ParameterDeclaration[] parameters;
|
||||
private TypeReference returnType;
|
||||
private boolean constructor;
|
||||
private TypeParameterDeclaration[] typeParameters;
|
||||
|
||||
public FunctionalTypeReference(Token token, TypeReference returnType, ParameterDeclaration[] parameters,
|
||||
TypeParameterDeclaration[] typeParameters) {
|
||||
this(token, false, returnType, parameters, typeParameters);
|
||||
}
|
||||
|
||||
public FunctionalTypeReference(Token token, boolean constructor, TypeReference returnType,
|
||||
ParameterDeclaration[] parameters, TypeParameterDeclaration[] typeParameters) {
|
||||
super(token, (String) null, null);
|
||||
this.parameters = parameters;
|
||||
this.returnType = returnType;
|
||||
this.constructor = constructor;
|
||||
this.typeParameters = typeParameters;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return StringUtils.join(parameters, ",") + "=>" + returnType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(Visitor visitor) {
|
||||
visitor.visitFunctionalTypeReference(this);
|
||||
}
|
||||
|
||||
public ParameterDeclaration[] getParameters() {
|
||||
return parameters;
|
||||
}
|
||||
|
||||
public void setParameters(ParameterDeclaration[] parameters) {
|
||||
this.parameters = parameters;
|
||||
}
|
||||
|
||||
public TypeReference getReturnType() {
|
||||
return returnType;
|
||||
}
|
||||
|
||||
public void setReturnType(TypeReference returnType) {
|
||||
this.returnType = returnType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (!obj.getClass().equals(getClass())) {
|
||||
return false;
|
||||
}
|
||||
FunctionalTypeReference ft = (FunctionalTypeReference) obj;
|
||||
if (!getReturnType().equals(ft.getReturnType())) {
|
||||
return false;
|
||||
}
|
||||
if (parameters.length != ft.parameters.length) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < ft.parameters.length; i++) {
|
||||
if (!parameters[i].getType().equals(ft.parameters[i].getType())) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FunctionalTypeReference copy(boolean copyDeclarations) {
|
||||
FunctionalTypeReference copy = new FunctionalTypeReference(null, isConstructor(),
|
||||
getReturnType().copy(copyDeclarations), DeclarationHelper.copy(getParameters()),
|
||||
DeclarationHelper.copy(getTypeParameters()));
|
||||
return copy;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FunctionalTypeReference copy() {
|
||||
return copy(false);
|
||||
}
|
||||
|
||||
public boolean isConstructor() {
|
||||
return constructor;
|
||||
}
|
||||
|
||||
public void setConstructor(boolean constructor) {
|
||||
this.constructor = constructor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TypeParameterDeclaration[] getTypeParameters() {
|
||||
return typeParameters;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTypeParameters(TypeParameterDeclaration[] typeParameters) {
|
||||
this.typeParameters = typeParameters;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,30 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
|
||||
public class Literal extends AbstractAstNode {
|
||||
|
||||
public Literal(Token token, String value) {
|
||||
super(token);
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
protected String value;
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(Visitor visitor) {
|
||||
visitor.visitLiteral(this);
|
||||
}
|
||||
|
||||
public Literal copy() {
|
||||
return new Literal(null, this.value);
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,117 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
public class ModuleDeclaration extends AbstractDeclaration implements DeclarationContainer {
|
||||
|
||||
Declaration[] members;
|
||||
|
||||
public static ModuleDeclaration createQualifiedModuleDeclaration(Token token, String qualifiedName,
|
||||
Declaration[] members) {
|
||||
|
||||
String[] subNames = qualifiedName.startsWith("\"") ? new String[] { qualifiedName }
|
||||
: qualifiedName.split("\\.");
|
||||
ModuleDeclaration module = new ModuleDeclaration(token, subNames[subNames.length - 1], members);
|
||||
if (subNames.length > 1) {
|
||||
return createQualifiedModuleDeclaration(token,
|
||||
StringUtils.join(ArrayUtils.subarray(subNames, 0, subNames.length - 1), "."),
|
||||
new Declaration[] { module });
|
||||
} else {
|
||||
return module;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public ModuleDeclaration(Token token, String name, Declaration[] members) {
|
||||
super(token, name);
|
||||
this.members = members;
|
||||
// System.out.println("new " + this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(Visitor v) {
|
||||
v.visitModuleDeclaration(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Declaration[] getMembers() {
|
||||
return members;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addMember(Declaration declaration) {
|
||||
members = DeclarationHelper.addMember(this, declaration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeMember(Declaration declaration) {
|
||||
members = DeclarationHelper.removeMember(this, declaration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void replaceMember(Declaration existingDeclaration, Declaration withNewDeclaration) {
|
||||
members = DeclarationHelper.replaceMember(this, existingDeclaration, withNewDeclaration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearMembers() {
|
||||
members = new Declaration[0];
|
||||
}
|
||||
|
||||
public FunctionDeclaration findFirstFunction(String name) {
|
||||
return DeclarationHelper.findFirstFunction(this, name);
|
||||
}
|
||||
|
||||
public List<FunctionDeclaration> findFunctions(String name) {
|
||||
return DeclarationHelper.findFunctions(this, name);
|
||||
}
|
||||
|
||||
public VariableDeclaration findVariable(String name) {
|
||||
return DeclarationHelper.findVariable(this, name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public VariableDeclaration findVariableIgnoreCase(String name) {
|
||||
return DeclarationHelper.findVariableIgnoreCase(this, name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TypeDeclaration findType(String name) {
|
||||
return DeclarationHelper.findType(this, name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TypeDeclaration findTypeIgnoreCase(String name) {
|
||||
return DeclarationHelper.findTypeIgnoreCase(this, name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Declaration findDeclaration(String name) {
|
||||
return DeclarationHelper.findDeclaration(this, name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addMembers(Declaration[] declarations) {
|
||||
DeclarationHelper.addMembers(this, declarations);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Declaration findDeclaration(Declaration declaration) {
|
||||
return DeclarationHelper.findDeclaration(this, declaration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ModuleDeclaration copy() {
|
||||
ModuleDeclaration copy = new ModuleDeclaration(null, getName(), DeclarationHelper.copy(members));
|
||||
copy.setStringAnnotations(
|
||||
this.getStringAnnotations() == null ? null : new ArrayList<String>(getStringAnnotations()));
|
||||
copy.quotedName = this.quotedName;
|
||||
copy.originalName = this.originalName;
|
||||
return copy;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,15 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
public interface NamedElement {
|
||||
|
||||
boolean isAnonymous();
|
||||
|
||||
String getName();
|
||||
|
||||
void setName(String name);
|
||||
|
||||
String getOriginalName();
|
||||
|
||||
void setOriginalName(String name);
|
||||
|
||||
}
|
||||
@ -0,0 +1,38 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
|
||||
public class ParameterDeclaration extends VariableDeclaration {
|
||||
|
||||
private boolean varargs = false;
|
||||
|
||||
public ParameterDeclaration(Token token, String name, TypeReference type, boolean optional, boolean varargs) {
|
||||
super(token, name, type, optional, false);
|
||||
this.varargs = varargs;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(Visitor v) {
|
||||
v.visitParameterDeclaration(this);
|
||||
}
|
||||
|
||||
public boolean isVarargs() {
|
||||
return varargs;
|
||||
}
|
||||
|
||||
public void setVarargs(boolean varargs) {
|
||||
this.varargs = varargs;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ParameterDeclaration copy() {
|
||||
ParameterDeclaration copy = new ParameterDeclaration(null, name, getType().copy(), isOptional(), isVarargs());
|
||||
copy.setModifiers(this.getModifiers() == null ? null : new HashSet<String>(this.getModifiers()));
|
||||
copy.setStringAnnotations(this.getStringAnnotations() == null ? null : new ArrayList<String>(
|
||||
getStringAnnotations()));
|
||||
copy.setDocumentation(this.getDocumentation());
|
||||
return copy;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,35 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
import org.jsweet.input.typescriptdef.util.Util;
|
||||
|
||||
public class QualifiedDeclaration<T extends Declaration> {
|
||||
private T declaration;
|
||||
private String qualifiedDeclarationName;
|
||||
|
||||
public QualifiedDeclaration(T declaration, String qualifiedDeclarationName) {
|
||||
this.declaration = declaration;
|
||||
this.qualifiedDeclarationName = qualifiedDeclarationName;
|
||||
}
|
||||
|
||||
public T getDeclaration() {
|
||||
return declaration;
|
||||
}
|
||||
|
||||
public String getQualifiedDeclarationName() {
|
||||
return qualifiedDeclarationName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return qualifiedDeclarationName;
|
||||
}
|
||||
|
||||
public String getQualifier() {
|
||||
return Util.getQualifier(qualifiedDeclarationName);
|
||||
}
|
||||
|
||||
public String getSimpleName() {
|
||||
return Util.getSimpleName(qualifiedDeclarationName);
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,55 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
import static org.apache.commons.lang3.StringUtils.strip;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
public class ReferenceDeclaration extends AbstractDeclaration {
|
||||
|
||||
private String referencedName;
|
||||
|
||||
public ReferenceDeclaration(Token token, String alias, String referencedName) {
|
||||
super(token, alias);
|
||||
|
||||
this.referencedName = strip(referencedName, "[\"']");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(Visitor v) {
|
||||
v.visitReferenceDeclaration(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Declaration copy() {
|
||||
ReferenceDeclaration copy = new ReferenceDeclaration(null, name, referencedName);
|
||||
copy.setDocumentation(getDocumentation());
|
||||
copy.name = name;
|
||||
copy.referencedName = referencedName;
|
||||
return copy;
|
||||
}
|
||||
|
||||
public String getReferencedName() {
|
||||
return referencedName;
|
||||
}
|
||||
|
||||
public boolean isImport() {
|
||||
return !isExport();
|
||||
}
|
||||
|
||||
public boolean isExport() {
|
||||
return StringUtils.isBlank(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
if (isExport()) {
|
||||
return "export = " + referencedName;
|
||||
} else {
|
||||
return "import " + name + " = " + referencedName;
|
||||
}
|
||||
}
|
||||
|
||||
public void setReferencedName(String referencedName) {
|
||||
this.referencedName = referencedName;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,743 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
import java.io.PrintStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.Stack;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.jsweet.JSweetDefTranslatorConfig;
|
||||
|
||||
public abstract class Scanner implements Visitor {
|
||||
|
||||
private Stack<Visitable> stack = new Stack<Visitable>();
|
||||
|
||||
protected final Logger logger = Logger.getLogger(getClass());
|
||||
|
||||
protected Context context;
|
||||
|
||||
public Scanner(Context context) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public Scanner(Scanner parentScanner) {
|
||||
this.context = parentScanner.context;
|
||||
this.stack = (Stack<Visitable>) parentScanner.stack.clone();
|
||||
}
|
||||
|
||||
public void onScanStart() {
|
||||
}
|
||||
|
||||
public void onScanEnded() {
|
||||
}
|
||||
|
||||
protected String getCurrentContainerName() {
|
||||
return getContainerNameAtIndex(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the container name at the stack.size()-i level.
|
||||
*
|
||||
* @param i
|
||||
* the reversed index (0=top of the stack)
|
||||
*/
|
||||
protected String getContainerNameAtIndex(int i) {
|
||||
List<String> modules = new ArrayList<String>();
|
||||
for (int j = 0; j < getStack().size() - i; j++) {
|
||||
Visitable v = getStack().get(j);
|
||||
if (v instanceof ModuleDeclaration) {
|
||||
modules.add(((ModuleDeclaration) v).getName());
|
||||
}
|
||||
if (v instanceof TypeDeclaration && !((TypeDeclaration) v).isAnonymous()) {
|
||||
modules.add(((TypeDeclaration) v).getName());
|
||||
}
|
||||
}
|
||||
return StringUtils.join(modules.iterator(), ".");
|
||||
}
|
||||
|
||||
protected String getCurrentModuleName() {
|
||||
List<String> modules = new ArrayList<String>();
|
||||
for (Visitable v : getStack()) {
|
||||
if (v instanceof ModuleDeclaration) {
|
||||
modules.add(((ModuleDeclaration) v).getName());
|
||||
}
|
||||
}
|
||||
return StringUtils.join(modules.iterator(), ".");
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if the given declaration belongs to the current scanning stack.
|
||||
*/
|
||||
protected boolean isInScope(Declaration declaration) {
|
||||
boolean inScope = false;
|
||||
for (int i = 0; i < getStack().size(); i++) {
|
||||
if (getStack().get(i) == declaration) {
|
||||
inScope = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return inScope;
|
||||
}
|
||||
|
||||
protected String getCurrentDeclarationName() {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for (Visitable v : getStack()) {
|
||||
if (v instanceof Declaration) {
|
||||
sb.append(((Declaration) v).getName());
|
||||
sb.append('.');
|
||||
}
|
||||
}
|
||||
if (!getStack().isEmpty() && !(sb.length() == 0)) {
|
||||
sb.deleteCharAt(sb.length() - 1);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
protected Visitable getRoot() {
|
||||
if (getStack().isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return getStack().get(0);
|
||||
}
|
||||
|
||||
protected QualifiedDeclaration<TypeDeclaration> lookupTypeDeclaration(String name) {
|
||||
if (name == null) {
|
||||
return null;
|
||||
}
|
||||
// NOTE: it is possible to search using the context find methods... it
|
||||
// would be nicer but it may be slower, so we do it this way... to be
|
||||
// thought of
|
||||
Set<String> possibleNames = new LinkedHashSet<String>();
|
||||
String mainModuleName = "";
|
||||
if (getRoot() instanceof CompilationUnit) {
|
||||
mainModuleName = ((CompilationUnit) getRoot()).getMainModule().getName();
|
||||
}
|
||||
|
||||
// lookup in current compilation unit
|
||||
for (int i = 0; i < getStack().size(); i++) {
|
||||
String containerName = getContainerNameAtIndex(i);
|
||||
String declFullName = StringUtils.isBlank(containerName) ? name : containerName + "." + name;
|
||||
if (declFullName.startsWith(mainModuleName)) {
|
||||
possibleNames.add(declFullName.substring(mainModuleName.length() + 1));
|
||||
}
|
||||
TypeDeclaration match = context.getTypeDeclaration(declFullName);
|
||||
if (match != null) {
|
||||
return new QualifiedDeclaration<>(match, declFullName);
|
||||
}
|
||||
}
|
||||
|
||||
// lookup in all compilation units
|
||||
for (CompilationUnit compilUnit : context.compilationUnits) {
|
||||
for (String rootRelativeName : possibleNames) {
|
||||
TypeDeclaration match = context
|
||||
.getTypeDeclaration(compilUnit.getMainModule().getName() + "." + rootRelativeName);
|
||||
if (match != null) {
|
||||
return new QualifiedDeclaration<>(match,
|
||||
compilUnit.getMainModule().getName() + "." + rootRelativeName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
protected QualifiedDeclaration<ModuleDeclaration> lookupModuleDeclaration(String name) {
|
||||
Set<String> possibleNames = new LinkedHashSet<String>();
|
||||
String mainModuleName = "";
|
||||
if (getRoot() instanceof CompilationUnit) {
|
||||
mainModuleName = ((CompilationUnit) getRoot()).getMainModule().getName();
|
||||
}
|
||||
|
||||
// lookup in current compilation unit
|
||||
for (int i = 0; i < getStack().size(); i++) {
|
||||
String containerName = getContainerNameAtIndex(i);
|
||||
String declFullName = StringUtils.isBlank(containerName) ? name : containerName + "." + name;
|
||||
|
||||
if (declFullName.startsWith(mainModuleName)) {
|
||||
possibleNames.add(declFullName.substring(mainModuleName.length() + 1));
|
||||
}
|
||||
List<QualifiedDeclaration<ModuleDeclaration>> matches = context.findDeclarations(ModuleDeclaration.class,
|
||||
declFullName);
|
||||
for (QualifiedDeclaration<ModuleDeclaration> m : matches) {
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
// lookup in all compilation units
|
||||
for (CompilationUnit compilUnit : context.compilationUnits) {
|
||||
for (String rootRelativeName : possibleNames) {
|
||||
List<QualifiedDeclaration<ModuleDeclaration>> matches = context.findDeclarations(
|
||||
ModuleDeclaration.class, compilUnit.getMainModule().getName() + "." + rootRelativeName);
|
||||
for (QualifiedDeclaration<ModuleDeclaration> m : matches) {
|
||||
return m;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
protected Type lookupType(TypeReference reference) {
|
||||
return lookupType(reference, null, false, false);
|
||||
}
|
||||
|
||||
protected Type lookupType(TypeReference reference, String modName) {
|
||||
return lookupType(reference, modName, false, false);
|
||||
}
|
||||
|
||||
protected boolean isFunctionalTypeReference(TypeReference typeReference) {
|
||||
Type t = lookupType(typeReference, null);
|
||||
if (t == null || !(t instanceof TypeDeclaration)) {
|
||||
return false;
|
||||
}
|
||||
TypeDeclaration td = (TypeDeclaration) t;
|
||||
if (context.getTypeName(td).startsWith(JSweetDefTranslatorConfig.FUNCTION_CLASSES_PACKAGE)
|
||||
|| context.getTypeName(td).startsWith("java.util.function")) {
|
||||
return true;
|
||||
}
|
||||
if (td.isAnnotationPresent(FunctionalInterface.class)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
protected boolean isSuperTypeReference(TypeReference typeReference) {
|
||||
if (!(getParent() instanceof TypeDeclaration)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
TypeDeclaration parentDeclaration = (TypeDeclaration) getParent();
|
||||
if (!ArrayUtils.contains(parentDeclaration.getSuperTypes(), typeReference)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
protected boolean isTypeArgumentTypeReference(TypeReference typeReference) {
|
||||
if (!(getParent() instanceof TypeReference)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
TypeReference parentReference = (TypeReference) getParent();
|
||||
if (!ArrayUtils.contains(parentReference.typeArguments, typeReference)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
protected TypeDeclaration extraLookup(TypeReference reference, String modName) {
|
||||
if (reference.getName() == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
QualifiedDeclaration<TypeDeclaration> type = context.findFirstDeclaration(TypeDeclaration.class,
|
||||
reference.getName(), getParent(CompilationUnit.class));
|
||||
if (type != null) {
|
||||
return type.getDeclaration();
|
||||
}
|
||||
type = context.findFirstDeclaration(TypeDeclaration.class, "*." + reference.getName(),
|
||||
getParent(CompilationUnit.class));
|
||||
if (type != null) {
|
||||
return type.getDeclaration();
|
||||
}
|
||||
return null;
|
||||
|
||||
// return lookupInLibModules(context.getLibModule(modName),
|
||||
// context.getLibRelativePath(modName), reference);
|
||||
}
|
||||
|
||||
protected Type lookupType(TypeReference reference, String modName, boolean createIfNotFound,
|
||||
boolean verboseIfNotFound) {
|
||||
if (reference.getDeclaration() != null) {
|
||||
return reference.getDeclaration();
|
||||
}
|
||||
if (reference.isTypeOf()) {
|
||||
return null;
|
||||
}
|
||||
if (reference.isObjectType()) {
|
||||
reference.setDeclaration(reference.getObjectType());
|
||||
return reference.getObjectType();
|
||||
} else {
|
||||
// lookup in the global type repository
|
||||
if (modName == null) {
|
||||
modName = getCurrentModuleName();
|
||||
}
|
||||
TypeDeclaration t = context.getTypeDeclaration(modName + "." + reference.getName());
|
||||
if (t == null) {
|
||||
t = context.getTypeDeclaration(reference.getName());
|
||||
if (t == null) {
|
||||
String containerName = getCurrentContainerName();
|
||||
t = context.getTypeDeclaration(containerName + "." + reference.getName());
|
||||
if (t == null) {
|
||||
if (!JSweetDefTranslatorConfig.isJDKReplacementMode()) {
|
||||
t = context.getTypeDeclaration("java.lang." + reference.getName());
|
||||
}
|
||||
if (t == null) {
|
||||
t = context.getTypeDeclaration(
|
||||
JSweetDefTranslatorConfig.GLOBALS_PACKAGE_NAME + "." + reference.getName());
|
||||
if (t == null) {
|
||||
t = context.getTypeDeclaration(
|
||||
JSweetDefTranslatorConfig.LANG_PACKAGE + "." + reference.getName());
|
||||
if (t == null) {
|
||||
t = context.getTypeDeclaration(
|
||||
JSweetDefTranslatorConfig.DOM_PACKAGE + "." + reference.getName());
|
||||
if (t == null) {
|
||||
String[] subNames = modName.split("\\.");
|
||||
String partialModName;
|
||||
for (int i = subNames.length - 1; i > 0; i--) {
|
||||
String[] a = ArrayUtils.subarray(subNames, 0, i);
|
||||
partialModName = StringUtils.join(a, ".");
|
||||
t = context.getTypeDeclaration(partialModName + "." + reference.getName());
|
||||
if (t != null) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// lookup in type parameters
|
||||
if (t == null) {
|
||||
TypeParameterizedElement tpe = getParent(TypeParameterizedElement.class, true);
|
||||
while (tpe != null) {
|
||||
if (tpe.getTypeParameters() != null) {
|
||||
for (TypeParameterDeclaration d : tpe.getTypeParameters()) {
|
||||
if (d.getName() != null && d.getName().equals(reference.getName())) {
|
||||
reference.setDeclaration(d);
|
||||
return d;
|
||||
}
|
||||
}
|
||||
}
|
||||
tpe = getParent(TypeParameterizedElement.class, tpe);
|
||||
}
|
||||
}
|
||||
|
||||
if (t == null) {
|
||||
t = extraLookup(reference, modName);
|
||||
}
|
||||
|
||||
if (t == null) {
|
||||
QualifiedDeclaration<TypeDeclaration> match = lookupTypeDeclaration(reference.getName());
|
||||
if (match != null) {
|
||||
t = match.getDeclaration();
|
||||
}
|
||||
}
|
||||
|
||||
if (t == null) {
|
||||
if (createIfNotFound) {
|
||||
Token token = getCurrentToken();
|
||||
System.err.println("WARNING: creating unknown reference " + reference + " at "
|
||||
+ (token == null ? "" : token.getLocation()));
|
||||
String[] names = reference.getName().split("\\.");
|
||||
TypeDeclaration type = new TypeDeclaration(null, "class", names[names.length - 1], null, null,
|
||||
null);
|
||||
ModuleDeclaration module;
|
||||
if (names.length > 1) {
|
||||
module = new ModuleDeclaration(null,
|
||||
StringUtils.join(ArrayUtils.subarray(names, 0, names.length - 1), "."),
|
||||
new Declaration[] { type });
|
||||
context.registerModule(module.getName(), module);
|
||||
} else {
|
||||
module = new ModuleDeclaration(null, JSweetDefTranslatorConfig.GLOBALS_PACKAGE_NAME,
|
||||
new Declaration[] { type });
|
||||
}
|
||||
context.compilationUnits.get(0).addMember(module);
|
||||
context.registerType(module.getName() + "." + type.getName(), type);
|
||||
} else {
|
||||
if (verboseIfNotFound) {
|
||||
Token token = getCurrentToken();
|
||||
context.reportError("cannot find reference " + reference + " (" + getCurrentContainerName()
|
||||
+ "." + reference.getName() + ")" + " at "
|
||||
+ (token == null ? "" : token.getLocation()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
reference.setDeclaration(t);
|
||||
return t;
|
||||
}
|
||||
}
|
||||
|
||||
protected QualifiedDeclaration<FunctionDeclaration> lookupFunctionDeclaration(String name) {
|
||||
Set<String> possibleNames = new LinkedHashSet<String>();
|
||||
String mainModuleName = "";
|
||||
if (getRoot() instanceof CompilationUnit) {
|
||||
ModuleDeclaration mainModule = ((CompilationUnit) getRoot()).getMainModule();
|
||||
if (mainModule != null) {
|
||||
mainModuleName = mainModule.getName();
|
||||
}
|
||||
}
|
||||
|
||||
// lookup in current compilation unit
|
||||
for (int i = 0; i < getStack().size(); i++) {
|
||||
String containerName = getContainerNameAtIndex(i);
|
||||
String declFullName = StringUtils.isBlank(containerName) ? name : containerName + "." + name;
|
||||
|
||||
if (declFullName.startsWith(mainModuleName)) {
|
||||
possibleNames.add(declFullName.substring(mainModuleName.length() + 1));
|
||||
}
|
||||
List<QualifiedDeclaration<FunctionDeclaration>> matches = context
|
||||
.findDeclarations(FunctionDeclaration.class, declFullName);
|
||||
if (matches.size() > 0) {
|
||||
return matches.get(0);
|
||||
}
|
||||
}
|
||||
|
||||
// lookup in all compilation units
|
||||
for (CompilationUnit compilUnit : context.compilationUnits) {
|
||||
if (compilUnit.getMainModule() == null) {
|
||||
continue;
|
||||
}
|
||||
for (String rootRelativeName : possibleNames) {
|
||||
List<QualifiedDeclaration<FunctionDeclaration>> matches = context.findDeclarations(
|
||||
FunctionDeclaration.class, compilUnit.getMainModule().getName() + "." + rootRelativeName);
|
||||
if (matches.size() > 0) {
|
||||
return matches.get(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
protected QualifiedDeclaration<VariableDeclaration> lookupVariableDeclaration(String name) {
|
||||
Set<String> possibleNames = new LinkedHashSet<String>();
|
||||
String mainModuleName = "";
|
||||
if (getRoot() instanceof CompilationUnit) {
|
||||
ModuleDeclaration mainModule = ((CompilationUnit) getRoot()).getMainModule();
|
||||
if (mainModule != null) {
|
||||
mainModuleName = mainModule.getName();
|
||||
}
|
||||
}
|
||||
|
||||
// lookup in current compilation unit
|
||||
for (int i = 0; i < getStack().size(); i++) {
|
||||
String containerName = getContainerNameAtIndex(i);
|
||||
String declFullName = StringUtils.isBlank(containerName) ? name : containerName + "." + name;
|
||||
|
||||
if (declFullName.startsWith(mainModuleName)) {
|
||||
possibleNames.add(declFullName.substring(mainModuleName.length() + 1));
|
||||
}
|
||||
List<QualifiedDeclaration<VariableDeclaration>> matches = context
|
||||
.findDeclarations(VariableDeclaration.class, declFullName);
|
||||
if (matches.size() > 0) {
|
||||
return matches.get(0);
|
||||
}
|
||||
}
|
||||
|
||||
// lookup in all compilation units
|
||||
for (CompilationUnit compilUnit : context.compilationUnits) {
|
||||
if (compilUnit.getMainModule() == null) {
|
||||
continue;
|
||||
}
|
||||
for (String rootRelativeName : possibleNames) {
|
||||
List<QualifiedDeclaration<VariableDeclaration>> matches = context.findDeclarations(
|
||||
VariableDeclaration.class, compilUnit.getMainModule().getName() + "." + rootRelativeName);
|
||||
if (matches.size() > 0) {
|
||||
return matches.get(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
protected FunctionDeclaration lookupFunctionDeclaration(TypeReference typeReference, String name,
|
||||
TypeReference... argTypes) {
|
||||
TypeDeclaration type = (TypeDeclaration) lookupType(typeReference, null);
|
||||
if (type == null) {
|
||||
return null;
|
||||
}
|
||||
boolean found = false;
|
||||
for (Declaration d : type.getMembers()) {
|
||||
if (name.equals(d.getName())) {
|
||||
if (d instanceof FunctionDeclaration) {
|
||||
FunctionDeclaration function = (FunctionDeclaration) d;
|
||||
if (argTypes.length == function.getParameters().length) {
|
||||
found = true;
|
||||
for (int i = 0; i < argTypes.length; i++) {
|
||||
if (!argTypes[i].equals(function.getParameters()[i].getType())) {
|
||||
found = false;
|
||||
}
|
||||
}
|
||||
if (found) {
|
||||
return function;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (type.getSuperTypes() != null) {
|
||||
for (TypeReference t : type.getSuperTypes()) {
|
||||
FunctionDeclaration f = lookupFunctionDeclaration(t, name, argTypes);
|
||||
if (f != null) {
|
||||
return f;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void printStackTrace(PrintStream out) {
|
||||
out.println("Dumping scanner stack: " + this.getClass().getSimpleName() + " - " + stack.size());
|
||||
for (int i = stack.size() - 1; i >= 0; i--) {
|
||||
if (stack.get(i) instanceof AstNode) {
|
||||
AstNode node = (AstNode) stack.get(i);
|
||||
out.println(" " + node.getClass().getSimpleName() + " - "
|
||||
+ (node.getToken() == null ? "N/A" : node.getToken() + " " + node.getToken().getLocation()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Token getCurrentToken() {
|
||||
for (int i = stack.size() - 1; i >= 0; i--) {
|
||||
if (stack.get(i) instanceof AstNode) {
|
||||
AstNode node = (AstNode) stack.get(i);
|
||||
if (node.getToken() != null) {
|
||||
return node.getToken();
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
protected void enter(Visitable element) {
|
||||
if (!stack.isEmpty() && stack.peek() == element) {
|
||||
printStackTrace(System.err);
|
||||
logger.error("FATAL ERROR: duplicate entry: " + element);
|
||||
throw new RuntimeException("FATAL ERROR: duplicate entry: " + element);
|
||||
}
|
||||
stack.push(element);
|
||||
}
|
||||
|
||||
protected void exit() {
|
||||
stack.pop();
|
||||
}
|
||||
|
||||
public Stack<Visitable> getStack() {
|
||||
return this.stack;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current parent AST node from the stack.
|
||||
*/
|
||||
public Visitable getParent() {
|
||||
return this.stack.get(this.stack.size() - 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the nth level parent AST node from the stack (getParent(1) ==
|
||||
* getParent()).
|
||||
*/
|
||||
public Visitable getParent(int level) {
|
||||
return this.stack.get(this.stack.size() - (level + 1));
|
||||
}
|
||||
|
||||
public <T extends Visitable> T getParent(Predicate<Visitable> predicate) {
|
||||
return getParent(predicate, false);
|
||||
}
|
||||
|
||||
public <T extends Visitable> T getParent(Class<T> type) {
|
||||
return getParent(type, false);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T extends Visitable> T getParent(Class<T> type, boolean includeCurrent) {
|
||||
for (int i = this.stack.size() - (includeCurrent ? 1 : 2); i >= 0; i--) {
|
||||
if (type.isAssignableFrom(this.stack.get(i).getClass())) {
|
||||
return (T) this.stack.get(i);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public <T extends Visitable> List<T> getParents(Class<T> type) {
|
||||
List<T> parents = new ArrayList<T>();
|
||||
for (int i = this.stack.size() - 1; i >= 0; i--) {
|
||||
if (type.isAssignableFrom(this.stack.get(i).getClass())) {
|
||||
@SuppressWarnings("unchecked")
|
||||
T t = (T) this.stack.get(i);
|
||||
parents.add(t);
|
||||
}
|
||||
}
|
||||
return parents;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T extends Visitable> List<T> getParents(Predicate<Visitable> predicate) {
|
||||
List<T> parents = new ArrayList<T>();
|
||||
for (int i = this.stack.size() - 1; i >= 0; i--) {
|
||||
if (predicate.test(this.stack.get(i))) {
|
||||
T t = (T) this.stack.get(i);
|
||||
parents.add(t);
|
||||
}
|
||||
}
|
||||
return parents;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T extends Visitable> T getParent(Predicate<Visitable> predicate, boolean includeCurrent) {
|
||||
for (int i = this.stack.size() - (includeCurrent ? 1 : 2); i >= 0; i--) {
|
||||
if (predicate.test(this.stack.get(i))) {
|
||||
return (T) this.stack.get(i);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T extends Visitable> T getParent(Class<T> type, Visitable from) {
|
||||
for (int i = this.stack.size() - 1; i >= 0; i--) {
|
||||
if (this.stack.get(i) == from) {
|
||||
for (int j = i - 1; j >= 0; j--) {
|
||||
if (type.isAssignableFrom(this.stack.get(j).getClass())) {
|
||||
return (T) this.stack.get(j);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T extends Visitable> T getParent(Predicate<Visitable> predicate, Visitable from) {
|
||||
for (int i = this.stack.size() - 1; i >= 0; i--) {
|
||||
if (this.stack.get(i) == from) {
|
||||
for (int j = i - 1; j >= 0; j--) {
|
||||
if (predicate.test(this.stack.get(j))) {
|
||||
return (T) this.stack.get(j);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void scan(Visitable visitable) {
|
||||
if (visitable != null && !visitable.isHidden()) {
|
||||
enter(visitable);
|
||||
try {
|
||||
visitable.accept(this);
|
||||
} finally {
|
||||
exit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void scan(Visitable[] visitables) {
|
||||
if (visitables != null) {
|
||||
for (Visitable visitable : visitables) {
|
||||
scan(visitable);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void scan(List<? extends Visitable> visitables) {
|
||||
if (visitables != null) {
|
||||
for (Visitable visitable : visitables) {
|
||||
scan(visitable);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitCompilationUnit(CompilationUnit compilationUnit) {
|
||||
scan(compilationUnit.getDeclarations());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitModuleDeclaration(ModuleDeclaration moduleDeclaration) {
|
||||
scan(moduleDeclaration.getMembers());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeDeclaration(TypeDeclaration typeDeclaration) {
|
||||
scan(typeDeclaration.getTypeParameters());
|
||||
scan(typeDeclaration.getSuperTypes());
|
||||
scan(typeDeclaration.getMergedSuperTypes());
|
||||
scan(typeDeclaration.getMembers());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionDeclaration(FunctionDeclaration functionDeclaration) {
|
||||
scan(functionDeclaration.getTypeParameters());
|
||||
scan(functionDeclaration.getType());
|
||||
scan(functionDeclaration.getParameters());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitVariableDeclaration(VariableDeclaration variableDeclaration) {
|
||||
scan(variableDeclaration.getType());
|
||||
scan(variableDeclaration.getInitializer());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitParameterDeclaration(ParameterDeclaration parameterDeclaration) {
|
||||
scan(parameterDeclaration.getType());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeReference(TypeReference typeReference) {
|
||||
scan(typeReference.getObjectType());
|
||||
scan(typeReference.getTypeArguments());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeMacro(TypeMacroDeclaration typeMacroDeclaration) {
|
||||
scan(typeMacroDeclaration.getTypeParameters());
|
||||
scan(typeMacroDeclaration.getType());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionalTypeReference(FunctionalTypeReference functionalTypeReference) {
|
||||
scan(functionalTypeReference.getReturnType());
|
||||
scan(functionalTypeReference.getParameters());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitArrayTypeReference(ArrayTypeReference arrayTypeReference) {
|
||||
scan(arrayTypeReference.getComponentType());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitUnionTypeReference(UnionTypeReference unionTypeReference) {
|
||||
switch (unionTypeReference.getSelected()) {
|
||||
case LEFT:
|
||||
scan(unionTypeReference.getLeftType());
|
||||
break;
|
||||
case RIGHT:
|
||||
scan(unionTypeReference.getRightType());
|
||||
break;
|
||||
default:
|
||||
scan(unionTypeReference.getLeftType());
|
||||
scan(unionTypeReference.getRightType());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration) {
|
||||
scan(typeParameterDeclaration.getUpperBound());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitLiteral(Literal literal) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitReferenceDeclaration(ReferenceDeclaration referenceDeclaration) {
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,80 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
/**
|
||||
* @author Renaud Pawlak
|
||||
*/
|
||||
public class Token {
|
||||
|
||||
public int type;
|
||||
|
||||
/**
|
||||
* Creates a new token
|
||||
*
|
||||
* @param type
|
||||
* the type as defined in the lexer
|
||||
* @param fileName
|
||||
* the name of the file from where the token was extracted
|
||||
* @param text
|
||||
* the text of the token
|
||||
* @param line
|
||||
* the line number where the token appears in the file
|
||||
* @param charBegin
|
||||
* the character where it begins in the file
|
||||
* @param charEnd
|
||||
* the character where it ends in the file
|
||||
*/
|
||||
public Token(int type, String fileName, String text, int line,
|
||||
int charBegin, int charEnd) {
|
||||
|
||||
this.type = type;
|
||||
this.fileName = fileName;
|
||||
this.text = text;
|
||||
this.line = line;
|
||||
this.charBegin = charBegin;
|
||||
this.charEnd = charEnd;
|
||||
}
|
||||
|
||||
public String getLocation() {
|
||||
return "" + fileName + ":" + line + "(" + charBegin + ")";
|
||||
}
|
||||
|
||||
String fileName;
|
||||
String text;
|
||||
int line;
|
||||
int charBegin;
|
||||
int charEnd;
|
||||
|
||||
// public boolean equals(Object o) {
|
||||
// System.err.println("equals("+this+","+o+")");
|
||||
// return text.equals(o.toString());
|
||||
// }
|
||||
|
||||
public String toString() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public int getCharBegin() {
|
||||
return charBegin;
|
||||
}
|
||||
|
||||
public int getCharEnd() {
|
||||
return charEnd;
|
||||
}
|
||||
|
||||
public int getLine() {
|
||||
return line;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public String getFileName() {
|
||||
return fileName;
|
||||
}
|
||||
|
||||
public int getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,9 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
public interface Type {
|
||||
|
||||
String getName();
|
||||
|
||||
boolean isSubtypeOf(Type type);
|
||||
|
||||
}
|
||||
@ -0,0 +1,247 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
|
||||
public class TypeDeclaration extends AbstractDeclaration
|
||||
implements Type, TypeParameterizedElement, DeclarationContainer {
|
||||
|
||||
private Declaration[] members;
|
||||
private TypeReference[] superTypes;
|
||||
private TypeReference[] mergedSuperTypes;
|
||||
private TypeParameterDeclaration[] typeParameters;
|
||||
private String kind;
|
||||
private String originalKind;
|
||||
private boolean external = false;
|
||||
|
||||
public static TypeDeclaration createExternalTypeDeclaration(String simpleName) {
|
||||
return createExternalTypeDeclaration("class", simpleName);
|
||||
}
|
||||
|
||||
public static TypeDeclaration createExternalTypeDeclaration(String kind, String simpleName) {
|
||||
TypeDeclaration t = new TypeDeclaration(null, kind, simpleName, null, null, new Declaration[0]);
|
||||
t.setExternal(true);
|
||||
return t;
|
||||
}
|
||||
|
||||
public static TypeDeclaration createTypeDeclaration(String simpleName) {
|
||||
TypeDeclaration t = new TypeDeclaration(null, "class", simpleName, null, null, new Declaration[0]);
|
||||
return t;
|
||||
}
|
||||
|
||||
public TypeDeclaration(Token token, String kind, String name, TypeParameterDeclaration[] typeParameters,
|
||||
TypeReference[] superTypes, Declaration[] members) {
|
||||
super(token, name);
|
||||
this.kind = this.originalKind = kind;
|
||||
this.typeParameters = typeParameters;
|
||||
this.setSuperTypes(superTypes);
|
||||
if (members != null) {
|
||||
this.members = members;
|
||||
} else {
|
||||
this.members = new Declaration[0];
|
||||
}
|
||||
// System.out.println("new TypeDeclaration: " + this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(Visitor v) {
|
||||
v.visitTypeDeclaration(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Declaration[] getMembers() {
|
||||
return members;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addMember(Declaration declaration) {
|
||||
members = DeclarationHelper.addMember(this, declaration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeMember(Declaration declaration) {
|
||||
members = DeclarationHelper.removeMember(this, declaration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void replaceMember(Declaration existingDeclaration, Declaration withNewDeclaration) {
|
||||
members = DeclarationHelper.replaceMember(this, existingDeclaration, withNewDeclaration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearMembers() {
|
||||
members = new Declaration[0];
|
||||
}
|
||||
|
||||
public TypeReference[] getSuperTypes() {
|
||||
return superTypes;
|
||||
}
|
||||
|
||||
public void setSuperTypes(TypeReference[] superTypes) {
|
||||
this.superTypes = superTypes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TypeParameterDeclaration[] getTypeParameters() {
|
||||
return this.typeParameters;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTypeParameters(TypeParameterDeclaration[] typeParameters) {
|
||||
this.typeParameters = typeParameters;
|
||||
}
|
||||
|
||||
public FunctionDeclaration findFirstConstructor() {
|
||||
return DeclarationHelper.findFirstConstructor(this);
|
||||
}
|
||||
|
||||
public List<FunctionDeclaration> findConstructors() {
|
||||
return DeclarationHelper.findConstructors(this);
|
||||
}
|
||||
|
||||
public boolean isStatic() {
|
||||
return DeclarationHelper.isStatic(this);
|
||||
}
|
||||
|
||||
public FunctionDeclaration findFirstFunction(String name) {
|
||||
return DeclarationHelper.findFirstFunction(this, name);
|
||||
}
|
||||
|
||||
public List<FunctionDeclaration> findFunctions(String name) {
|
||||
return DeclarationHelper.findFunctions(this, name);
|
||||
}
|
||||
|
||||
public VariableDeclaration findVariable(String name) {
|
||||
return DeclarationHelper.findVariable(this, name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public VariableDeclaration findVariableIgnoreCase(String name) {
|
||||
return DeclarationHelper.findVariableIgnoreCase(this, name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TypeDeclaration findType(String name) {
|
||||
return DeclarationHelper.findType(this, name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TypeDeclaration findTypeIgnoreCase(String name) {
|
||||
return DeclarationHelper.findTypeIgnoreCase(this, name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Declaration findDeclaration(String name) {
|
||||
return DeclarationHelper.findDeclaration(this, name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addMembers(Declaration[] declarations) {
|
||||
DeclarationHelper.addMembers(this, declarations);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Declaration findDeclaration(Declaration declaration) {
|
||||
return DeclarationHelper.findDeclaration(this, declaration);
|
||||
}
|
||||
|
||||
public String getKind() {
|
||||
return kind;
|
||||
}
|
||||
|
||||
public void setKind(String kind) {
|
||||
this.originalKind = this.kind;
|
||||
this.kind = kind;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TypeDeclaration copy() {
|
||||
TypeDeclaration copy = new TypeDeclaration(null, getKind(), getName(),
|
||||
DeclarationHelper.copy(getTypeParameters()), DeclarationHelper.copyReferences(superTypes),
|
||||
DeclarationHelper.copy(members));
|
||||
copy.setDocumentation(getDocumentation());
|
||||
copy.setModifiers(this.getModifiers() == null ? null : new HashSet<String>(getModifiers()));
|
||||
copy.setStringAnnotations(
|
||||
this.getStringAnnotations() == null ? null : new ArrayList<String>(getStringAnnotations()));
|
||||
copy.originalKind = this.originalKind;
|
||||
return copy;
|
||||
}
|
||||
|
||||
public boolean isExternal() {
|
||||
boolean external = this.external || (getDocumentation() != null && isInputAnnotatedWith("External"));
|
||||
return external;
|
||||
}
|
||||
|
||||
public void setExternal(boolean external) {
|
||||
this.external = external;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSubtypeOf(Type type) {
|
||||
if (type == null) {
|
||||
return false;
|
||||
}
|
||||
if (getSuperTypes() != null) {
|
||||
for (TypeReference tref : getSuperTypes()) {
|
||||
TypeDeclaration t = (TypeDeclaration) tref.getDeclaration();
|
||||
if (type == t) {
|
||||
return true;
|
||||
} else {
|
||||
if (t != null) {
|
||||
return t.isSubtypeOf(type);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
|
||||
}
|
||||
|
||||
public boolean isInterface() {
|
||||
return getKind() != null && getKind().equals("interface");
|
||||
}
|
||||
|
||||
public boolean isFunctionalInterface() {
|
||||
return isInterface() && getMembers().length == 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
if (name != null) {
|
||||
return super.toString();
|
||||
} else {
|
||||
// print inlined toString (probably an object type)
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("{");
|
||||
for (Declaration d : getMembers()) {
|
||||
sb.append(d.toString()).append(";");
|
||||
}
|
||||
sb.append("}");
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public TypeReference[] getMergedSuperTypes() {
|
||||
return mergedSuperTypes;
|
||||
}
|
||||
|
||||
public void setMergedSuperTypes(TypeReference[] mergedSuperTypes) {
|
||||
this.mergedSuperTypes = mergedSuperTypes;
|
||||
}
|
||||
|
||||
public void addMergedSuperType(TypeReference mergedSuperType) {
|
||||
if (this.mergedSuperTypes == null) {
|
||||
this.mergedSuperTypes = new TypeReference[] { mergedSuperType };
|
||||
} else {
|
||||
this.mergedSuperTypes = ArrayUtils.add(mergedSuperTypes, mergedSuperType);
|
||||
}
|
||||
}
|
||||
|
||||
public final String getOriginalKind() {
|
||||
return originalKind;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,45 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
import java.util.HashSet;
|
||||
|
||||
public class TypeMacroDeclaration extends TypeDeclaration implements TypedDeclaration {
|
||||
|
||||
private TypeReference type;
|
||||
|
||||
public TypeMacroDeclaration(Token token, String aliasName, TypeParameterDeclaration[] typeParameters, TypeReference type) {
|
||||
super(token, "type", aliasName, typeParameters, null, null);
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(Visitor v) {
|
||||
v.visitTypeMacro(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TypeMacroDeclaration copy() {
|
||||
TypeMacroDeclaration copy = new TypeMacroDeclaration(null, getName(), getTypeParameters(), getType());
|
||||
copy.setDocumentation(getDocumentation());
|
||||
copy.setModifiers(this.getModifiers() == null ? null : new HashSet<String>(getModifiers()));
|
||||
return copy;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSubtypeOf(Type type) {
|
||||
if (type == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return type.isSubtypeOf(getType().getDeclaration());
|
||||
}
|
||||
|
||||
@Override
|
||||
public TypeReference getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setType(TypeReference type) {
|
||||
this.type = type;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,47 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
|
||||
public class TypeParameterDeclaration extends AbstractDeclaration implements Type, TypedDeclaration {
|
||||
|
||||
protected TypeReference upperBound;
|
||||
|
||||
public TypeParameterDeclaration(Token token, String name) {
|
||||
super(token, name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(Visitor visitor) {
|
||||
visitor.visitTypeParameterDeclaration(this);
|
||||
}
|
||||
|
||||
public TypeReference getUpperBound() {
|
||||
return upperBound;
|
||||
}
|
||||
|
||||
public void setUpperBound(TypeReference upperBound) {
|
||||
this.upperBound = upperBound;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TypeParameterDeclaration copy() {
|
||||
TypeParameterDeclaration copy = new TypeParameterDeclaration(null, getName());
|
||||
copy.upperBound = upperBound == null ? null : upperBound.copy();
|
||||
return copy;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setType(TypeReference type) {
|
||||
upperBound = type;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TypeReference getType() {
|
||||
return upperBound;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSubtypeOf(Type type) {
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,9 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
public interface TypeParameterizedElement extends AstNode {
|
||||
|
||||
TypeParameterDeclaration[] getTypeParameters();
|
||||
|
||||
void setTypeParameters(TypeParameterDeclaration[] typeParameters);
|
||||
|
||||
}
|
||||
@ -0,0 +1,231 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.jsweet.JSweetDefTranslatorConfig;
|
||||
import org.jsweet.input.typescriptdef.util.Util;
|
||||
|
||||
public class TypeReference extends AbstractAstNode implements NamedElement {
|
||||
|
||||
protected TypeReference[] typeArguments;
|
||||
protected String name;
|
||||
protected TypeDeclaration objectType;
|
||||
// cache to the declaration
|
||||
transient private Type declaration;
|
||||
private boolean typeOf = false;
|
||||
|
||||
public boolean isTypeOf() {
|
||||
return typeOf;
|
||||
}
|
||||
|
||||
public void setTypeOf(boolean typeOf) {
|
||||
this.typeOf = typeOf;
|
||||
}
|
||||
|
||||
public TypeReference(Token token, String name, TypeReference[] typeArguments) {
|
||||
super(token);
|
||||
if ("$tuple$".equals(name)) {
|
||||
name = JSweetDefTranslatorConfig.TUPLE_CLASSES_PACKAGE + "."
|
||||
+ JSweetDefTranslatorConfig.TUPLE_CLASSES_PREFIX + typeArguments.length;
|
||||
}
|
||||
this.name = name;
|
||||
this.typeArguments = typeArguments;
|
||||
}
|
||||
|
||||
public TypeReference(Token token, Type type, TypeReference[] typeArguments) {
|
||||
super(token);
|
||||
this.name = type.getName();
|
||||
this.typeArguments = typeArguments;
|
||||
this.declaration = type;
|
||||
}
|
||||
|
||||
public TypeReference(Token token, Declaration[] members) {
|
||||
super(token);
|
||||
this.objectType = new TypeDeclaration(token, "object_type", null, null, null, members);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (objectType != null) {
|
||||
sb.append(objectType.toString());
|
||||
} else {
|
||||
sb.append(name);
|
||||
if (typeArguments != null && typeArguments.length > 0) {
|
||||
sb.append("<");
|
||||
for (TypeReference t : typeArguments) {
|
||||
sb.append(t);
|
||||
sb.append(",");
|
||||
}
|
||||
sb.deleteCharAt(sb.length() - 1);
|
||||
sb.append(">");
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(Visitor visitor) {
|
||||
visitor.visitTypeReference(this);
|
||||
}
|
||||
|
||||
public TypeReference[] getTypeArguments() {
|
||||
return this.typeArguments;
|
||||
}
|
||||
|
||||
public void setTypeArguments(TypeReference[] typeArguments) {
|
||||
this.typeArguments = typeArguments;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public boolean isObjectType() {
|
||||
return objectType != null;
|
||||
}
|
||||
|
||||
public TypeDeclaration getObjectType() {
|
||||
return objectType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAnonymous() {
|
||||
return name == null;
|
||||
}
|
||||
|
||||
public boolean isStringType() {
|
||||
return name != null && (name.startsWith("\"") && name.endsWith("\""));
|
||||
}
|
||||
|
||||
public boolean isPrimitive() {
|
||||
return DeclarationHelper.isPrimitiveType(name);
|
||||
}
|
||||
|
||||
public String getWrappingTypeName() {
|
||||
if ("any".equals(name)) {
|
||||
return "java.lang.Object";
|
||||
} else if (isPrimitive()) {
|
||||
return StringUtils.capitalize(name);
|
||||
} else {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
|
||||
public String getSimpleName() {
|
||||
return Util.getSimpleName(name);
|
||||
}
|
||||
|
||||
public String getQualifier() {
|
||||
return Util.getQualifier(name);
|
||||
}
|
||||
|
||||
public boolean isQualified() {
|
||||
return Util.isQualified(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (!obj.getClass().equals(getClass())) {
|
||||
return false;
|
||||
}
|
||||
TypeReference tr = (TypeReference) obj;
|
||||
if (name == null && tr.name == null) {
|
||||
if (objectType != null && tr.objectType != null) {
|
||||
return DeclarationHelper.areDeclarationsEqual(objectType.getMembers(), tr.objectType.getMembers());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (name == null && tr.name != null) {
|
||||
return false;
|
||||
}
|
||||
if (!name.equals(tr.name)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public TypeReference copy(boolean copyDeclarations) {
|
||||
TypeReference copy = new TypeReference(null, getName(), DeclarationHelper.copyReferences(typeArguments, copyDeclarations));
|
||||
if (objectType != null) {
|
||||
copy.objectType = objectType.copy();
|
||||
}
|
||||
if (copyDeclarations) {
|
||||
copy.declaration = declaration;
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
|
||||
public TypeReference copy() {
|
||||
return copy(false);
|
||||
}
|
||||
|
||||
public Type getDeclaration() {
|
||||
return declaration;
|
||||
}
|
||||
|
||||
public void setDeclaration(Type type) {
|
||||
this.declaration = type;
|
||||
}
|
||||
|
||||
public boolean isArray() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public TypeReference getComponentType() {
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean isSubtypeOf(TypeReference type) {
|
||||
if (declaration == null) {
|
||||
throw new RuntimeException("unattributed type reference: " + this);
|
||||
}
|
||||
if (!type.isArray() && type.declaration == null) {
|
||||
throw new RuntimeException("unattributed type reference: " + type);
|
||||
}
|
||||
return declaration.isSubtypeOf(type.declaration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Substitutes a type reference if found in the node.
|
||||
*
|
||||
* @param targetType
|
||||
* the type reference to be substituted, if found in the node
|
||||
* @param newType
|
||||
* the new type reference that will be substituted to target type
|
||||
* @return true if the target type was found and substituted
|
||||
*/
|
||||
public boolean substituteTypeReference(TypeReference targetType, TypeReference newType) {
|
||||
if (typeArguments != null) {
|
||||
for (int i = 0; i < typeArguments.length; i++) {
|
||||
if (typeArguments[i] == targetType) {
|
||||
typeArguments[i] = newType;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getOriginalName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setOriginalName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public boolean isTuple() {
|
||||
return name != null && name.startsWith(
|
||||
JSweetDefTranslatorConfig.TUPLE_CLASSES_PACKAGE + "." + JSweetDefTranslatorConfig.TUPLE_CLASSES_PREFIX);
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,10 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
public interface TypedDeclaration extends Declaration {
|
||||
|
||||
TypeReference getType();
|
||||
|
||||
void setType(TypeReference type);
|
||||
|
||||
|
||||
}
|
||||
@ -0,0 +1,352 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
public class UnionTypeReference extends TypeReference {
|
||||
|
||||
public enum Selected {
|
||||
NONE, PENDING, LEFT, RIGHT;
|
||||
public Selected inverse() {
|
||||
switch (this) {
|
||||
case LEFT:
|
||||
return RIGHT;
|
||||
case RIGHT:
|
||||
return LEFT;
|
||||
default:
|
||||
return NONE;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private TypeReference leftType;
|
||||
private TypeReference rightType;
|
||||
private Selected selected = Selected.NONE;
|
||||
private boolean intersection = false;
|
||||
|
||||
public UnionTypeReference(Token token, TypeReference leftType, TypeReference rightType) {
|
||||
this(token, leftType, rightType, false);
|
||||
}
|
||||
|
||||
public UnionTypeReference(Token token, TypeReference leftType, TypeReference rightType, boolean intersection) {
|
||||
super(token, intersection ? "&" : "|", null);
|
||||
setLeftType(leftType);
|
||||
setRightType(rightType);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(Visitor visitor) {
|
||||
visitor.visitUnionTypeReference(this);
|
||||
}
|
||||
|
||||
public TypeReference getLeftType() {
|
||||
return leftType;
|
||||
}
|
||||
|
||||
public void setLeftType(TypeReference leftType) {
|
||||
this.leftType = leftType;
|
||||
if (leftType != null && leftType.getName() != null && leftType.getName().equals("void")) {
|
||||
selected = Selected.RIGHT;
|
||||
}
|
||||
}
|
||||
|
||||
public TypeReference getRightType() {
|
||||
return rightType;
|
||||
}
|
||||
|
||||
public void setRightType(TypeReference rightType) {
|
||||
this.rightType = rightType;
|
||||
if (rightType != null && rightType.getName() != null && rightType.getName().equals("void")) {
|
||||
selected = Selected.LEFT;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public UnionTypeReference copy(boolean copyDeclarations) {
|
||||
UnionTypeReference copy = new UnionTypeReference(null, leftType.copy(copyDeclarations),
|
||||
rightType.copy(copyDeclarations));
|
||||
copy.typeArguments = DeclarationHelper.copyReferences(typeArguments, copyDeclarations);
|
||||
copy.selected = this.selected;
|
||||
return copy;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UnionTypeReference copy() {
|
||||
return copy(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
switch (selected) {
|
||||
case LEFT:
|
||||
return leftType.toString();
|
||||
case RIGHT:
|
||||
return rightType.toString();
|
||||
case PENDING:
|
||||
return leftType.toString() + " |? " + rightType.toString();
|
||||
default:
|
||||
return leftType.toString() + " | " + rightType.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public Selected getSelected() {
|
||||
// if (leftT)
|
||||
|
||||
return selected;
|
||||
}
|
||||
|
||||
public void setSelected(Selected selected) {
|
||||
this.selected = selected;
|
||||
}
|
||||
|
||||
public TypeReference getOperand(Selected selected) {
|
||||
switch (selected) {
|
||||
case LEFT:
|
||||
return leftType;
|
||||
case RIGHT:
|
||||
return rightType;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public TypeReference getSelectedType() {
|
||||
switch (selected) {
|
||||
case LEFT:
|
||||
return leftType;
|
||||
case RIGHT:
|
||||
return rightType;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public List<TypeReference> getTypes() {
|
||||
List<TypeReference> types = new LinkedList<>();
|
||||
TypeReference selectedType = getSelectedType();
|
||||
if (selectedType != null) {
|
||||
if (selectedType instanceof UnionTypeReference) {
|
||||
types.addAll(((UnionTypeReference) selectedType).getTypes());
|
||||
} else {
|
||||
types.add(selectedType);
|
||||
}
|
||||
} else {
|
||||
// add both types if union hasn't been resolved
|
||||
if (leftType instanceof UnionTypeReference) {
|
||||
types.addAll(((UnionTypeReference) leftType).getTypes());
|
||||
} else {
|
||||
types.add(leftType);
|
||||
}
|
||||
|
||||
if (rightType instanceof UnionTypeReference) {
|
||||
types.addAll(((UnionTypeReference) rightType).getTypes());
|
||||
} else {
|
||||
types.add(rightType);
|
||||
}
|
||||
}
|
||||
|
||||
return types;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Type getDeclaration() {
|
||||
switch (selected) {
|
||||
case LEFT:
|
||||
return leftType.getDeclaration();
|
||||
case RIGHT:
|
||||
return rightType.getDeclaration();
|
||||
default:
|
||||
return super.getDeclaration();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
switch (selected) {
|
||||
case LEFT:
|
||||
return leftType.getName();
|
||||
case RIGHT:
|
||||
return rightType.getName();
|
||||
default:
|
||||
return super.getName();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleName() {
|
||||
switch (selected) {
|
||||
case LEFT:
|
||||
return leftType.getSimpleName();
|
||||
case RIGHT:
|
||||
return rightType.getSimpleName();
|
||||
default:
|
||||
return super.getSimpleName();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public TypeDeclaration getObjectType() {
|
||||
switch (selected) {
|
||||
case LEFT:
|
||||
return leftType.getObjectType();
|
||||
case RIGHT:
|
||||
return rightType.getObjectType();
|
||||
default:
|
||||
return super.getObjectType();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public TypeReference[] getTypeArguments() {
|
||||
switch (selected) {
|
||||
case LEFT:
|
||||
return leftType.getTypeArguments();
|
||||
case RIGHT:
|
||||
return rightType.getTypeArguments();
|
||||
default:
|
||||
return super.getTypeArguments();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getWrappingTypeName() {
|
||||
switch (selected) {
|
||||
case LEFT:
|
||||
return leftType.getWrappingTypeName();
|
||||
case RIGHT:
|
||||
return rightType.getWrappingTypeName();
|
||||
default:
|
||||
return super.getWrappingTypeName();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAnonymous() {
|
||||
switch (selected) {
|
||||
case LEFT:
|
||||
return leftType.isAnonymous();
|
||||
case RIGHT:
|
||||
return rightType.isAnonymous();
|
||||
default:
|
||||
return super.isAnonymous();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isHidden() {
|
||||
switch (selected) {
|
||||
case LEFT:
|
||||
return leftType.isHidden();
|
||||
case RIGHT:
|
||||
return rightType.isHidden();
|
||||
default:
|
||||
return super.isHidden();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isObjectType() {
|
||||
switch (selected) {
|
||||
case LEFT:
|
||||
return leftType.isObjectType();
|
||||
case RIGHT:
|
||||
return rightType.isObjectType();
|
||||
default:
|
||||
return super.isObjectType();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPrimitive() {
|
||||
switch (selected) {
|
||||
case LEFT:
|
||||
return leftType.isPrimitive();
|
||||
case RIGHT:
|
||||
return rightType.isPrimitive();
|
||||
default:
|
||||
return super.isPrimitive();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isStringType() {
|
||||
switch (selected) {
|
||||
case LEFT:
|
||||
return leftType.isStringType();
|
||||
case RIGHT:
|
||||
return rightType.isStringType();
|
||||
default:
|
||||
return super.isStringType();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isArray() {
|
||||
switch (selected) {
|
||||
case LEFT:
|
||||
return leftType.isArray();
|
||||
case RIGHT:
|
||||
return rightType.isArray();
|
||||
default:
|
||||
return super.isArray();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public TypeReference getComponentType() {
|
||||
switch (selected) {
|
||||
case LEFT:
|
||||
return leftType.getComponentType();
|
||||
case RIGHT:
|
||||
return rightType.getComponentType();
|
||||
default:
|
||||
return super.getComponentType();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSubtypeOf(TypeReference type) {
|
||||
switch (selected) {
|
||||
case LEFT:
|
||||
return leftType.isSubtypeOf(type);
|
||||
case RIGHT:
|
||||
return rightType.isSubtypeOf(type);
|
||||
default:
|
||||
return super.isSubtypeOf(type);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean substituteTypeReference(TypeReference targetType, TypeReference newType) {
|
||||
if (getLeftType() == targetType) {
|
||||
setLeftType(newType);
|
||||
return true;
|
||||
}
|
||||
if (getRightType() == targetType) {
|
||||
setRightType(newType);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
switch (selected) {
|
||||
case LEFT:
|
||||
return leftType.equals(obj);
|
||||
case RIGHT:
|
||||
return rightType.equals(obj);
|
||||
default:
|
||||
return super.equals(obj);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isIntersection() {
|
||||
return intersection;
|
||||
}
|
||||
|
||||
public void setIntersection(boolean intersection) {
|
||||
this.intersection = intersection;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,59 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
|
||||
public class VariableDeclaration extends AbstractTypedDeclaration {
|
||||
|
||||
private boolean optional = false;
|
||||
private boolean readonly = false;
|
||||
private Literal initializer = null;
|
||||
|
||||
public VariableDeclaration(Token token, String name, TypeReference type, boolean optional, boolean readonly) {
|
||||
super(token, name, type);
|
||||
this.optional = optional;
|
||||
this.readonly = readonly;
|
||||
// System.out.println("new VariableDeclaration: " + this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(Visitor v) {
|
||||
v.visitVariableDeclaration(this);
|
||||
}
|
||||
|
||||
public boolean isOptional() {
|
||||
return optional;
|
||||
}
|
||||
|
||||
public void setOptional(boolean optional) {
|
||||
this.optional = optional;
|
||||
}
|
||||
|
||||
@Override
|
||||
public VariableDeclaration copy() {
|
||||
VariableDeclaration copy = new VariableDeclaration(null, name, getType().copy(), optional, readonly);
|
||||
copy.setModifiers(this.getModifiers() == null ? null : new HashSet<String>(this.getModifiers()));
|
||||
copy.setStringAnnotations(
|
||||
this.getStringAnnotations() == null ? null : new ArrayList<String>(getStringAnnotations()));
|
||||
copy.setDocumentation(this.getDocumentation());
|
||||
copy.setInitializer(initializer == null ? null : initializer.copy());
|
||||
return copy;
|
||||
}
|
||||
|
||||
public Literal getInitializer() {
|
||||
return initializer;
|
||||
}
|
||||
|
||||
public void setInitializer(Literal initializer) {
|
||||
this.initializer = initializer;
|
||||
}
|
||||
|
||||
public final boolean isReadonly() {
|
||||
return readonly;
|
||||
}
|
||||
|
||||
public final void setReadonly(boolean readonly) {
|
||||
this.readonly = readonly;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,12 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
|
||||
public interface Visitable {
|
||||
|
||||
void setHidden(boolean hidden);
|
||||
|
||||
boolean isHidden();
|
||||
|
||||
void accept(Visitor visitor);
|
||||
|
||||
}
|
||||
@ -0,0 +1,33 @@
|
||||
package org.jsweet.input.typescriptdef.ast;
|
||||
|
||||
|
||||
public interface Visitor {
|
||||
|
||||
void visitCompilationUnit(CompilationUnit compilationUnit);
|
||||
|
||||
void visitModuleDeclaration(ModuleDeclaration moduleDeclaration);
|
||||
|
||||
void visitReferenceDeclaration(ReferenceDeclaration referenceDeclaration);
|
||||
|
||||
void visitTypeDeclaration(TypeDeclaration typeDeclaration);
|
||||
|
||||
void visitFunctionDeclaration(FunctionDeclaration functionDeclaration);
|
||||
|
||||
void visitVariableDeclaration(VariableDeclaration variableDeclaration);
|
||||
|
||||
void visitParameterDeclaration(ParameterDeclaration parameterDeclaration);
|
||||
|
||||
void visitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration);
|
||||
|
||||
void visitTypeReference(TypeReference typeReference);
|
||||
|
||||
void visitFunctionalTypeReference(FunctionalTypeReference functionalTypeReference);
|
||||
|
||||
void visitArrayTypeReference(ArrayTypeReference arrayTypeReference);
|
||||
|
||||
void visitUnionTypeReference(UnionTypeReference unionTypeReference);
|
||||
|
||||
void visitLiteral(Literal literal);
|
||||
|
||||
void visitTypeMacro(TypeMacroDeclaration typeMacroDeclaration);
|
||||
}
|
||||
@ -0,0 +1,11 @@
|
||||
package org.jsweet.input.typescriptdef.parser;
|
||||
|
||||
public class GenParser {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
java_cup.Main.main(new String[] { "-expect", "0", "-package", "org.jsweet.input.typescriptdef.parser", "-expect", "0", "-parser", "TypescriptDefParser",
|
||||
"typescriptdef.cup" });
|
||||
JFlex.Main.main(new String[] { "typescriptdef.lex" });
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,34 @@
|
||||
package org.jsweet.input.typescriptdef.parser;
|
||||
|
||||
import java.io.PrintStream;
|
||||
|
||||
import org.jsweet.input.typescriptdef.ast.Token;
|
||||
|
||||
public class SyntaxError {
|
||||
|
||||
public Token origin;
|
||||
public String message;
|
||||
public Exception exception;
|
||||
|
||||
public SyntaxError(Token origin, String message) {
|
||||
super();
|
||||
this.origin = origin;
|
||||
this.message = message;
|
||||
this.exception = new Exception();
|
||||
//this.exception.printStackTrace();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "SYNTAX ERROR"
|
||||
+ ": "
|
||||
+ message
|
||||
+ (origin != null ? " at '" + origin.toString() + "'" + " "
|
||||
+ origin.getLocation() : "");
|
||||
}
|
||||
|
||||
public void printStackTrace(PrintStream stream) {
|
||||
exception.printStackTrace(stream);
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,11 @@
|
||||
package org.jsweet.input.typescriptdef.parser;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public class TestParser {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
TypescriptDefParser.parseFile(new File("test.d.ts"));
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,88 @@
|
||||
|
||||
//----------------------------------------------------
|
||||
// The following code was generated by CUP v0.10k
|
||||
// Sun Jul 24 16:44:06 CEST 2016
|
||||
//----------------------------------------------------
|
||||
|
||||
package org.jsweet.input.typescriptdef.parser;
|
||||
|
||||
/** CUP generated class containing symbol constants. */
|
||||
public class sym {
|
||||
/* terminals */
|
||||
public static final int AT = 37;
|
||||
public static final int AS = 69;
|
||||
public static final int IDENTIFIER = 43;
|
||||
public static final int FROM = 70;
|
||||
public static final int GT = 18;
|
||||
public static final int TYPEOF = 66;
|
||||
public static final int IMPLEMENTS = 63;
|
||||
public static final int CONST = 67;
|
||||
public static final int EXPORT = 47;
|
||||
public static final int DECLARE_MODULE = 54;
|
||||
public static final int SEMI = 7;
|
||||
public static final int DECLARE_FUNCTION = 55;
|
||||
public static final int ENUM = 71;
|
||||
public static final int LPAREN_FUNC = 73;
|
||||
public static final int SQUARE = 14;
|
||||
public static final int COMMA = 3;
|
||||
public static final int RPAREN = 9;
|
||||
public static final int LT = 15;
|
||||
public static final int ANDAND = 31;
|
||||
public static final int OROR = 30;
|
||||
public static final int DECLARE = 53;
|
||||
public static final int LPAREN = 8;
|
||||
public static final int PROTECTED = 50;
|
||||
public static final int FALSE = 42;
|
||||
public static final int NOT = 33;
|
||||
public static final int DOTDOTDOT = 6;
|
||||
public static final int LF = 72;
|
||||
public static final int TYPE_MACRO = 58;
|
||||
public static final int RCPAREN = 11;
|
||||
public static final int VAR = 61;
|
||||
public static final int NOTEQUALS = 21;
|
||||
public static final int LCPAREN = 10;
|
||||
public static final int DECLARE_ENUM = 57;
|
||||
public static final int NUM = 40;
|
||||
public static final int DOLLAR = 45;
|
||||
public static final int CLASS = 60;
|
||||
public static final int ABSTRACT = 52;
|
||||
public static final int TUBE = 34;
|
||||
public static final int TRUE = 41;
|
||||
public static final int MATCHES = 36;
|
||||
public static final int PLUS = 26;
|
||||
public static final int QUESTION = 44;
|
||||
public static final int EXTENDS = 62;
|
||||
public static final int ASSIGN = 19;
|
||||
public static final int INTERFACE = 59;
|
||||
public static final int RPAREN_FUNC = 74;
|
||||
public static final int DIV = 23;
|
||||
public static final int PUBLIC = 51;
|
||||
public static final int MULT = 22;
|
||||
public static final int DOTDOT = 5;
|
||||
public static final int DOT = 4;
|
||||
public static final int INT = 39;
|
||||
public static final int LTE = 16;
|
||||
public static final int REFERENCE = 29;
|
||||
public static final int EOF = 0;
|
||||
public static final int COL = 2;
|
||||
public static final int FUNCTION = 48;
|
||||
public static final int DOC = 28;
|
||||
public static final int IMPORT = 46;
|
||||
public static final int RSPAREN = 13;
|
||||
public static final int IS = 68;
|
||||
public static final int MINUS = 24;
|
||||
public static final int ARROW_RIGHT = 38;
|
||||
public static final int error = 1;
|
||||
public static final int GTE = 17;
|
||||
public static final int MINUSMINUS = 25;
|
||||
public static final int LSPAREN = 12;
|
||||
public static final int PLUSPLUS = 27;
|
||||
public static final int NEW = 64;
|
||||
public static final int DECLARE_CLASS = 56;
|
||||
public static final int AND = 32;
|
||||
public static final int PRIVATE = 49;
|
||||
public static final int IMPLIES = 35;
|
||||
public static final int STATIC = 65;
|
||||
public static final int EQUALS = 20;
|
||||
}
|
||||
|
||||
108
jsweet-candy-generator/src/main/java/org/jsweet/input/typescriptdef/parser/test.d.ts
vendored
Normal file
108
jsweet-candy-generator/src/main/java/org/jsweet/input/typescriptdef/parser/test.d.ts
vendored
Normal file
@ -0,0 +1,108 @@
|
||||
|
||||
enum StatusEnum {
|
||||
connected, connecting,
|
||||
failed, waiting, offline
|
||||
}
|
||||
|
||||
interface NodeListOf<TNode extends Node> extends NodeList, T, U {
|
||||
length: {
|
||||
}
|
||||
item(index: number /** Buffer **/ ): TNode;
|
||||
[index: number]: TNode;
|
||||
static : number;
|
||||
static: number;
|
||||
extends: string;
|
||||
extends : string;
|
||||
/**
|
||||
* test
|
||||
*/
|
||||
}
|
||||
|
||||
class Model extends ModelBase {
|
||||
|
||||
object<T>(...keyValuePairs: any[][]): T;
|
||||
|
||||
/**
|
||||
* Do not use, prefer TypeScript's extend functionality.
|
||||
**/
|
||||
private static extend(properties: any, classProperties?: any): any;
|
||||
|
||||
attributes: any;
|
||||
changed: any[];
|
||||
cid: string;
|
||||
collection: Collection<any>;
|
||||
}
|
||||
|
||||
module 'm' {
|
||||
|
||||
// test
|
||||
|
||||
type T = string | number;
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// SCEService
|
||||
// see http://docs.angularjs.org/api/ng.$sce
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* titi
|
||||
*/
|
||||
interface ISCEService {
|
||||
getTrusted(type: string, mayBeTrusted: any): any;
|
||||
}
|
||||
|
||||
interface Tinytest {
|
||||
add(name:string, func:Function):any;
|
||||
addAsync(name:string, func:Function):any;
|
||||
}
|
||||
|
||||
enum StatusEnum {
|
||||
connected,
|
||||
connecting,
|
||||
failed,
|
||||
waiting,
|
||||
offline
|
||||
}
|
||||
|
||||
export = i;
|
||||
|
||||
/** the * promise of the original server interaction that created this instance. ** **/
|
||||
interface I2<{ test: string; }> extends I {
|
||||
|
||||
/** The notify function can either be passed a string or an object. */
|
||||
|
||||
(translationId: string[], interpolateParams?: any, interpolationId?: string): ng.IPromise<{ [key: string]: string }>;
|
||||
|
||||
var test: string;
|
||||
|
||||
a(b: any, c : number): string;
|
||||
|
||||
b<T>(f : ((n: number) => void )[]) : t.x.y;
|
||||
|
||||
[a : number] : T;
|
||||
|
||||
(b: any, c: number): string;
|
||||
|
||||
a2(b: { p1: P1; f(x:number):string; } [], c : number): string;
|
||||
|
||||
function getLevel(nameOrValue: string): webdriver.logging.Level;
|
||||
|
||||
sendKeys(...var_args: string[]): webdriver.promise.Promise;
|
||||
}
|
||||
|
||||
module logging {
|
||||
var Preferences: any;
|
||||
|
||||
class LevelName extends webdriver.logging.LevelName { }
|
||||
class Type extends webdriver.logging.Type { }
|
||||
class Level extends webdriver.logging.Level { }
|
||||
class Entry extends webdriver.logging.Entry { }
|
||||
|
||||
function getLevel(nameOrValue: string): webdriver.logging.Level;
|
||||
function getLevel(nameOrValue: number): webdriver.logging.Level;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
// TODO: support object_type @tsdef\angular-http-auth\angular-http-auth.d.ts
|
||||
@ -0,0 +1,628 @@
|
||||
|
||||
/*
|
||||
* This source code file is the exclusive property of its author. No copy or
|
||||
* usage of the source code is permitted unless the author contractually
|
||||
* allows it under the terms of a well-defined agreement.
|
||||
*/
|
||||
|
||||
import java.util.*;
|
||||
import java.io.*;
|
||||
import org.apache.commons.lang3.*;
|
||||
import org.jsweet.input.typescriptdef.ast.*;
|
||||
|
||||
parser code {:
|
||||
|
||||
public PrintStream out = System.out;
|
||||
public PrintStream err = System.err;
|
||||
public CompilationUnit compilationUnit;
|
||||
public Stack<Token[]> comments = new Stack<Token[]>();
|
||||
|
||||
protected static TypescriptDefParser createParser(File file) throws java.io.FileNotFoundException {
|
||||
TypescriptDefScanner scanner= new TypescriptDefScanner(new java.io.FileReader(file));
|
||||
scanner.setFileName(file.getPath());
|
||||
TypescriptDefParser parser= new TypescriptDefParser(scanner);
|
||||
parser.compilationUnit = new CompilationUnit(file);
|
||||
return parser;
|
||||
}
|
||||
|
||||
public static TypescriptDefParser parseFile(File file) throws java.io.FileNotFoundException {
|
||||
TypescriptDefParser parser= createParser(file);
|
||||
try {
|
||||
parser.parse();
|
||||
} catch(Exception e) {
|
||||
e.printStackTrace();
|
||||
parser.errors.add(new SyntaxError(null, "internal parser error"));
|
||||
}
|
||||
return parser;
|
||||
}
|
||||
|
||||
public List<SyntaxError> errors = new ArrayList<SyntaxError>();
|
||||
|
||||
public void syntax_error(java_cup.runtime.Symbol current) {
|
||||
//errors.add(new SyntaxError("syntax error: '"+current.value + "' is not expected", at " + (current.left+1)+"("+(current.right+1)+")" );
|
||||
SyntaxError e = new SyntaxError((Token)current.value, "'"+current.value + "' is not expected");
|
||||
errors.add(e);
|
||||
System.err.println(e);
|
||||
}
|
||||
|
||||
public void syntax_error(Token current) {
|
||||
SyntaxError e = new SyntaxError(current, "'"+current + "' is not expected");
|
||||
errors.add(e);
|
||||
System.err.println(e);
|
||||
}
|
||||
|
||||
public void unrecovered_syntax_error(java_cup.runtime.Symbol current) {
|
||||
System.err.println("unable to recover from previous error(s)... giving up!");
|
||||
}
|
||||
|
||||
public void printErrors(PrintStream out) {
|
||||
for (SyntaxError error : errors) {
|
||||
out.println(error.toString());
|
||||
}
|
||||
}
|
||||
|
||||
public boolean hasErrors() {
|
||||
return !errors.isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
:};
|
||||
|
||||
terminal COL, COMMA, DOT, DOTDOT, DOTDOTDOT, SEMI;
|
||||
terminal LPAREN, RPAREN, LCPAREN, RCPAREN, LSPAREN, RSPAREN, SQUARE;
|
||||
terminal LT, LTE, GTE, GT, ASSIGN, EQUALS, NOTEQUALS, MULT, DIV, MINUS, MINUSMINUS, PLUS, PLUSPLUS;
|
||||
terminal DOC, REFERENCE;
|
||||
|
||||
terminal OROR, ANDAND, AND, NOT, TUBE, IMPLIES, MATCHES;
|
||||
terminal AT, ARROW_RIGHT;
|
||||
terminal INT, NUM, TRUE, FALSE;
|
||||
terminal IDENTIFIER;
|
||||
terminal QUESTION, DOLLAR;
|
||||
// keywords
|
||||
terminal IMPORT, EXPORT, FUNCTION, PRIVATE, PROTECTED, PUBLIC, ABSTRACT;
|
||||
terminal DECLARE, /*DECLARE_VAR,*/ DECLARE_MODULE, DECLARE_FUNCTION, DECLARE_CLASS, DECLARE_ENUM, TYPE_MACRO;
|
||||
terminal INTERFACE, CLASS, VAR, EXTENDS, IMPLEMENTS, NEW;
|
||||
//terminal MODULE;
|
||||
terminal STATIC, TYPEOF, CONST, IS, AS, FROM;
|
||||
terminal ENUM;
|
||||
terminal LF;
|
||||
terminal LPAREN_FUNC, RPAREN_FUNC;
|
||||
|
||||
non terminal comp_unit, declaration_list_opt, declaration_list, declaration_with_error, declaration, declaration_nodoc;
|
||||
non terminal type_macro, type_decl, type_kind, var_decl, module_decl, func_decl, constructor_decl, index_sig_decl, export_decl, import_decl;
|
||||
non terminal param_list_opt, param_list, param, optional_opt, varargs_opt;
|
||||
non terminal member_list_opt, member_list, member_elt_with_error, member_elt, member_elt_nodoc;
|
||||
non terminal enum_decl, enum_member_list, enum_member_list_opt, enum_member_elt_with_error, enum_member_elt, enum_member_elt_nodoc;
|
||||
non terminal type_annotation_opt, type_annotation, type, basic_type, union_type, intersection_type, array_type, functional_type, new_functional_type, simple_type, object_type, typeof_type, is_type, tuple_type;
|
||||
non terminal declare_opt, var_opt, const_opt;
|
||||
non terminal qual_id;
|
||||
non terminal import_spec;
|
||||
non terminal type_param_list_opt, type_param_list, type_param;
|
||||
non terminal type_arg_list_opt, type_arg_list, type_arg_and;
|
||||
non terminal extends_opt, implements_opt;
|
||||
non terminal lf, semi_or_lf, semi_or_lf_opt, lf_opt, semi_or_comma_or_lf, semi_or_comma_or_lf_opt;
|
||||
non terminal type_list;
|
||||
non terminal doc_list, doc_list_opt, doc_opt;
|
||||
non terminal literal, export_opt, var_or_const, abstract_opt, export_element_list, export_element;
|
||||
|
||||
precedence left AND, TUBE;
|
||||
precedence right LF;
|
||||
precedence right COMMA;
|
||||
precedence right DOC;
|
||||
|
||||
start with comp_unit;
|
||||
|
||||
/***************************************************************/
|
||||
/*** TYPESCRIPT DEFINITION FILES GRAMMAR **/
|
||||
/***************************************************************/
|
||||
|
||||
comp_unit ::= declaration_list_opt:decls {: parser.compilationUnit.setDeclarations((Declaration[])decls); :};
|
||||
|
||||
declaration_list_opt ::= lf_opt declaration_list:l semi_or_lf_opt {:
|
||||
parser.comments.pop();
|
||||
RESULT = l;
|
||||
:} | lf_opt {: RESULT = new Declaration[0]; :};
|
||||
|
||||
declaration_list ::= declaration_list:l semi_or_lf declaration_with_error:d
|
||||
{:
|
||||
if(d instanceof Declaration) {
|
||||
Declaration[] list = (Declaration[])l;
|
||||
Token doc = parser.comments.peek()[0];
|
||||
if(doc!=null) {
|
||||
((Declaration)d).setDocumentation(doc.toString());
|
||||
parser.comments.peek()[0]=null;
|
||||
}
|
||||
RESULT = ArrayUtils.add(list, (Declaration)d);
|
||||
} else {
|
||||
if(d instanceof Token) {
|
||||
parser.comments.peek()[0] = (Token)d;
|
||||
}
|
||||
RESULT = l;
|
||||
}
|
||||
:}
|
||||
| declaration_with_error:d {:
|
||||
if(d instanceof Declaration) {
|
||||
parser.comments.push(new Token[] { null });
|
||||
RESULT = new Declaration[] { (Declaration)d };
|
||||
} else {
|
||||
parser.comments.push(new Token[] { (Token)d });
|
||||
RESULT = new Declaration[0];
|
||||
}
|
||||
:}
|
||||
;
|
||||
|
||||
declaration_with_error ::= declaration:d {: RESULT=d; :} | error;
|
||||
|
||||
declaration ::= declaration_nodoc:d {: RESULT=d; :}
|
||||
| DOC:d {:
|
||||
RESULT=d;
|
||||
:}
|
||||
;
|
||||
|
||||
declaration_nodoc ::=
|
||||
type_macro:d {: RESULT=d; :}
|
||||
| type_decl:d {: RESULT=d; :}
|
||||
| enum_decl:d {: RESULT=d; :}
|
||||
| module_decl:d {: RESULT=d; :}
|
||||
| var_decl:d {: RESULT=d; :}
|
||||
| func_decl:d {: RESULT=d; :}
|
||||
| export_decl:d {: RESULT=d; :}
|
||||
| import_decl:d {: RESULT=d; :}
|
||||
;
|
||||
|
||||
export_decl ::= EXPORT ASSIGN IDENTIFIER:exportedIdentifier lf_opt
|
||||
{:
|
||||
RESULT = new ReferenceDeclaration((Token)exportedIdentifier, null, exportedIdentifier.toString());
|
||||
:}
|
||||
| EXPORT LCPAREN export_element_list RCPAREN lf_opt
|
||||
;
|
||||
|
||||
export_element_list ::= export_element_list:l COMMA lf_opt export_element:t
|
||||
| export_element:t
|
||||
;
|
||||
|
||||
export_element ::= IDENTIFIER | IDENTIFIER AS IDENTIFIER;
|
||||
|
||||
export_opt ::= EXPORT |;
|
||||
|
||||
import_decl ::=
|
||||
export_opt IMPORT import_spec:s
|
||||
{:
|
||||
RESULT = s;
|
||||
:}
|
||||
;
|
||||
|
||||
import_spec ::=
|
||||
MULT AS IDENTIFIER:alias FROM qual_id:imported
|
||||
{:
|
||||
RESULT = new ReferenceDeclaration((Token)alias, alias.toString(), imported.toString());
|
||||
:}
|
||||
| IDENTIFIER:alias ASSIGN qual_id:imported
|
||||
{:
|
||||
RESULT = new ReferenceDeclaration((Token)alias, alias.toString(), imported.toString());
|
||||
:}
|
||||
| IDENTIFIER:alias ASSIGN IDENTIFIER:require LPAREN qual_id:imported RPAREN
|
||||
{:
|
||||
if(!"require".equals(require.toString())) {
|
||||
parser.syntax_error((Token)require);
|
||||
} else {
|
||||
RESULT = new ReferenceDeclaration((Token)alias, alias.toString(), imported.toString());
|
||||
}
|
||||
:}
|
||||
|
||||
;
|
||||
|
||||
type_macro ::= TYPE_MACRO IDENTIFIER:alias type_param_list_opt:tparams ASSIGN lf_opt type:type
|
||||
{:
|
||||
RESULT = new TypeMacroDeclaration((Token)alias, alias.toString(), (TypeParameterDeclaration[])tparams, (TypeReference)type);
|
||||
:}
|
||||
|
|
||||
EXPORT TYPE_MACRO IDENTIFIER:alias type_param_list_opt:tparams ASSIGN type:type
|
||||
{:
|
||||
RESULT = new TypeMacroDeclaration((Token)alias, alias.toString(), (TypeParameterDeclaration[])tparams, (TypeReference)type);
|
||||
:}
|
||||
;
|
||||
|
||||
type_decl ::= declare_opt abstract_opt type_kind:def IDENTIFIER:name type_param_list_opt:tparams extends_opt:t implements_opt:t2 lf_opt LCPAREN member_list_opt:members RCPAREN
|
||||
{:
|
||||
RESULT = new TypeDeclaration((Token)name,def.toString(),name.toString(),(TypeParameterDeclaration[])tparams,t==null?(TypeReference[])t2:ArrayUtils.addAll((TypeReference[])t,(TypeReference[])t2),(Declaration[])members);
|
||||
:} | declare_opt DECLARE_CLASS IDENTIFIER:name type_param_list_opt:tparams extends_opt:t implements_opt:t2 lf_opt LCPAREN member_list_opt:members RCPAREN
|
||||
{:
|
||||
RESULT = new TypeDeclaration((Token)name,"class",name.toString(),(TypeParameterDeclaration[])tparams,t==null?(TypeReference[])t2:ArrayUtils.addAll((TypeReference[])t,(TypeReference[])t2),(Declaration[])members);
|
||||
:}
|
||||
;
|
||||
|
||||
const_opt ::= CONST {: RESULT = true; :} | {: RESULT = false; :};
|
||||
|
||||
abstract_opt ::= ABSTRACT {: RESULT = "abstract"; :} | ;
|
||||
|
||||
enum_decl ::= declare_opt DECLARE_ENUM IDENTIFIER:name type_param_list_opt:tparams lf_opt LCPAREN enum_member_list_opt:members RCPAREN
|
||||
{:
|
||||
RESULT = new TypeDeclaration((Token)name,"enum",name.toString(),(TypeParameterDeclaration[])tparams,null,(Declaration[])members);
|
||||
:}
|
||||
| declare_opt const_opt ENUM IDENTIFIER:name type_param_list_opt:tparams lf_opt LCPAREN enum_member_list_opt:members RCPAREN
|
||||
{:
|
||||
RESULT = new TypeDeclaration((Token)name,"enum",name.toString(),(TypeParameterDeclaration[])tparams,null,(Declaration[])members);
|
||||
:}
|
||||
;
|
||||
|
||||
enum_member_list_opt ::= lf_opt enum_member_list:l lf_opt {: RESULT = l; :}
|
||||
| lf_opt {: RESULT = new Declaration[0]; :};
|
||||
|
||||
enum_member_list ::= enum_member_list:l COMMA lf_opt enum_member_elt_with_error:e
|
||||
{:
|
||||
if(e!=null) {
|
||||
Declaration[] list = (Declaration[])l;
|
||||
RESULT = ArrayUtils.add(list, (Declaration)e);
|
||||
} else {
|
||||
RESULT=l;
|
||||
}
|
||||
:}
|
||||
| enum_member_elt_with_error:e
|
||||
{:
|
||||
if(e!=null) {
|
||||
RESULT=new Declaration[] { (Declaration)e };
|
||||
} else {
|
||||
RESULT=new Declaration[0];
|
||||
}
|
||||
:}
|
||||
| enum_member_list:l COMMA lf_opt
|
||||
{:
|
||||
RESULT=l;
|
||||
:}
|
||||
| enum_member_list:l lf_opt doc_list lf_opt
|
||||
{:
|
||||
RESULT=l;
|
||||
:}
|
||||
| enum_member_list:l COMMA lf_opt doc_list lf_opt
|
||||
{:
|
||||
RESULT=l;
|
||||
:}
|
||||
;
|
||||
|
||||
enum_member_elt_with_error ::= enum_member_elt:d {: RESULT=d; :} | error;
|
||||
|
||||
enum_member_elt ::= doc_list:doc lf_opt enum_member_elt_nodoc:d
|
||||
{:
|
||||
if(d!=null) {
|
||||
Declaration decl = (Declaration)d;
|
||||
decl.setDocumentation(doc.toString());
|
||||
RESULT=d;
|
||||
}
|
||||
:}
|
||||
| enum_member_elt_nodoc:d
|
||||
{:
|
||||
RESULT=d;
|
||||
:}
|
||||
;
|
||||
|
||||
enum_member_elt_nodoc ::= IDENTIFIER:name {:
|
||||
RESULT = new VariableDeclaration((Token)name, name.toString(), null, false, true);
|
||||
:}
|
||||
| IDENTIFIER:name ASSIGN literal:value {:
|
||||
Literal literal = new Literal((Token)value, value.toString());
|
||||
VariableDeclaration var = new VariableDeclaration((Token)name, name.toString(), null, false, true);
|
||||
var.setInitializer(literal);
|
||||
RESULT = var;
|
||||
:}
|
||||
;
|
||||
|
||||
literal ::= INT:i {: RESULT=i; :};
|
||||
|
||||
type_kind ::= INTERFACE:def {: RESULT=def; :} | CLASS:def {: RESULT=def; :};
|
||||
|
||||
extends_opt ::= EXTENDS type_list:t {: RESULT = t; :} | ;
|
||||
|
||||
implements_opt ::= IMPLEMENTS lf_opt type_list:t {: RESULT = t; :} | ;
|
||||
|
||||
type_list ::= type_list:l COMMA lf_opt type:t
|
||||
{:
|
||||
TypeReference[] list = (TypeReference[])l;
|
||||
RESULT = ArrayUtils.add(list, (TypeReference)t);
|
||||
:}
|
||||
| type:t
|
||||
{:
|
||||
RESULT=new TypeReference[] { (TypeReference)t };
|
||||
:}
|
||||
;
|
||||
|
||||
member_list_opt ::= lf_opt member_list:l semi_or_comma_or_lf_opt {:
|
||||
parser.comments.pop();
|
||||
RESULT = l;
|
||||
:}
|
||||
| lf_opt {: RESULT = new Declaration[0]; :};
|
||||
|
||||
lf ::= lf LF | LF;
|
||||
|
||||
lf_opt ::= lf |;
|
||||
|
||||
semi_or_lf ::= SEMI lf | SEMI | lf;
|
||||
|
||||
semi_or_lf_opt ::= semi_or_lf |;
|
||||
|
||||
semi_or_comma_or_lf ::= SEMI lf | SEMI | COMMA lf | COMMA | lf;
|
||||
|
||||
semi_or_comma_or_lf_opt ::= semi_or_comma_or_lf |;
|
||||
|
||||
member_list ::= member_list:l semi_or_comma_or_lf member_elt_with_error:d
|
||||
{:
|
||||
if(d instanceof Declaration) {
|
||||
Declaration[] list = (Declaration[])l;
|
||||
Token doc = parser.comments.peek()[0];
|
||||
if(doc!=null) {
|
||||
((Declaration)d).setDocumentation(doc.toString());
|
||||
parser.comments.peek()[0]=null;
|
||||
}
|
||||
RESULT = ArrayUtils.add(list, (Declaration)d);
|
||||
} else {
|
||||
if(d instanceof Token) {
|
||||
parser.comments.peek()[0] = (Token)d;
|
||||
}
|
||||
RESULT=l;
|
||||
}
|
||||
:}
|
||||
| member_elt_with_error:d
|
||||
{:
|
||||
if(d instanceof Declaration) {
|
||||
parser.comments.push(new Token[] { null });
|
||||
RESULT = new Declaration[] { (Declaration)d };
|
||||
} else {
|
||||
parser.comments.push(new Token[] { (Token)d });
|
||||
RESULT = new Declaration[0];
|
||||
}
|
||||
:}
|
||||
;
|
||||
|
||||
member_elt_with_error ::= member_elt:d {: RESULT=d; :} | error;
|
||||
|
||||
member_elt ::= member_elt_nodoc:d
|
||||
{:
|
||||
RESULT=d;
|
||||
:}
|
||||
| DOC:doc
|
||||
{:
|
||||
RESULT=doc;
|
||||
:}
|
||||
;
|
||||
|
||||
doc_list ::= DOC:doc lf_opt doc_list {: RESULT=doc; :} | DOC:doc lf_opt {: RESULT=doc; :};
|
||||
|
||||
doc_list_opt ::= doc_list:l {: RESULT=l; :} |;
|
||||
|
||||
doc_opt ::= DOC | ;
|
||||
|
||||
member_elt_nodoc ::=
|
||||
var_decl:d {: RESULT=d; :}
|
||||
| func_decl:d {: RESULT=d; :}
|
||||
| index_sig_decl:d {: RESULT=d; :}
|
||||
| constructor_decl:d {: RESULT=d; :}
|
||||
;
|
||||
|
||||
module_decl ::= declare_opt IDENTIFIER:t qual_id:name lf_opt LCPAREN declaration_list_opt:declarations RCPAREN
|
||||
{:
|
||||
if(!(t.toString().equals("module")||t.toString().equals("namespace"))) {
|
||||
parser.syntax_error((Token)t);
|
||||
}
|
||||
RESULT = ModuleDeclaration.createQualifiedModuleDeclaration((Token)t,name.toString(),(Declaration[])declarations);
|
||||
:}
|
||||
| DECLARE_MODULE:t qual_id:name lf_opt LCPAREN declaration_list_opt:declarations RCPAREN
|
||||
{:
|
||||
RESULT = ModuleDeclaration.createQualifiedModuleDeclaration((Token)t,name.toString(),(Declaration[])declarations);
|
||||
:}
|
||||
;
|
||||
|
||||
var_or_const ::= VAR {: RESULT=false; :} | CONST {: RESULT = true; :};
|
||||
|
||||
var_decl ::= declare_opt:mod var_or_const:readonly IDENTIFIER:name optional_opt:opt lf_opt type_annotation_opt:t
|
||||
{:
|
||||
VariableDeclaration var = new VariableDeclaration((Token)name,name.toString(),(TypeReference)t, (Boolean)opt, (Boolean)readonly);
|
||||
if(mod!=null) var.addModifier((String)mod);
|
||||
var.setHidden(var.hasModifier("private"));
|
||||
RESULT = var;
|
||||
:}
|
||||
| declare_opt:mod IDENTIFIER:name optional_opt:opt lf_opt type_annotation_opt:t
|
||||
{:
|
||||
VariableDeclaration var = new VariableDeclaration((Token)name,name.toString(),(TypeReference)t, (Boolean)opt, false);
|
||||
if(mod!=null) var.addModifier((String)mod);
|
||||
var.setHidden(var.hasModifier("private"));
|
||||
RESULT = var;
|
||||
:}
|
||||
| declare_opt:mod INT:name optional_opt:opt lf_opt type_annotation_opt:t
|
||||
{:
|
||||
VariableDeclaration var = new VariableDeclaration((Token)name,name.toString(),(TypeReference)t, (Boolean)opt, false);
|
||||
if(mod!=null) var.addModifier((String)mod);
|
||||
var.setHidden(var.hasModifier("private"));
|
||||
RESULT = var;
|
||||
:}
|
||||
// case of a variable called 'new'
|
||||
| declare_opt:mod NEW:name optional_opt:opt lf_opt type_annotation_opt:t
|
||||
{:
|
||||
VariableDeclaration var = new VariableDeclaration((Token)name,name.toString(),(TypeReference)t, (Boolean)opt, false);
|
||||
if(mod!=null) var.addModifier((String)mod);
|
||||
var.setHidden(var.hasModifier("private"));
|
||||
RESULT = var;
|
||||
:}
|
||||
// | DECLARE_VAR IDENTIFIER:name optional_opt:opt type_annotation_opt:t
|
||||
// {:
|
||||
// RESULT = new VariableDeclaration((Token)name,name.toString(),(TypeReference)t, (Boolean)opt);
|
||||
// :}
|
||||
;
|
||||
|
||||
optional_opt ::= QUESTION {: RESULT=true; :} | {: RESULT=false; :};
|
||||
|
||||
func_decl ::= declare_opt:mod IDENTIFIER:name optional_opt:opt type_param_list_opt:tparams LPAREN param_list_opt:params RPAREN type_annotation_opt:t
|
||||
{:
|
||||
//System.err.println("1");
|
||||
FunctionDeclaration func = new FunctionDeclaration((Token)name,name.toString(),(TypeReference)t, (ParameterDeclaration[])params, (TypeParameterDeclaration[])tparams);
|
||||
if(mod!=null) func.addModifier((String)mod);
|
||||
func.setHidden(func.hasModifier("private"));
|
||||
RESULT = func;
|
||||
:}
|
||||
| declare_opt:mod FUNCTION IDENTIFIER:name optional_opt:opt type_param_list_opt:tparams LPAREN param_list_opt:params RPAREN type_annotation_opt:t
|
||||
{:
|
||||
//System.err.println("2");
|
||||
FunctionDeclaration func = new FunctionDeclaration((Token)name,name.toString(),(TypeReference)t, (ParameterDeclaration[])params, (TypeParameterDeclaration[])tparams);
|
||||
if(mod!=null) func.addModifier((String)mod);
|
||||
func.setHidden(func.hasModifier("private"));
|
||||
RESULT = func;
|
||||
:}
|
||||
| DECLARE_FUNCTION IDENTIFIER:name optional_opt:opt type_param_list_opt:tparams LPAREN param_list_opt:params RPAREN type_annotation_opt:t
|
||||
{:
|
||||
//System.err.println("3");
|
||||
RESULT = new FunctionDeclaration((Token)name,name.toString(),(TypeReference)t, (ParameterDeclaration[])params, (TypeParameterDeclaration[])tparams);
|
||||
:}
|
||||
;
|
||||
|
||||
constructor_decl ::= declare_opt:mod type_param_list_opt:tparams LPAREN:token param_list_opt:params RPAREN type_annotation_opt:t
|
||||
{:
|
||||
//System.err.println("4");
|
||||
RESULT = new FunctionDeclaration((Token)token,FunctionDeclaration.ANONYMOUS_FUNCTION_RESERVED_NAME,(TypeReference)t, (ParameterDeclaration[])params, (TypeParameterDeclaration[])tparams);
|
||||
:}
|
||||
| declare_opt:mod NEW type_param_list_opt:tparams LPAREN:token param_list_opt:params RPAREN type_annotation_opt:t
|
||||
{:
|
||||
//System.err.println("5");
|
||||
RESULT = new FunctionDeclaration((Token)token,FunctionDeclaration.NEW_FUNCTION_RESERVED_NAME,(TypeReference)t, (ParameterDeclaration[])params, (TypeParameterDeclaration[])tparams);
|
||||
:}
|
||||
;
|
||||
|
||||
index_sig_decl ::= declare_opt type_param_list_opt:tparams LSPAREN:token param:param RSPAREN type_annotation_opt:t
|
||||
{:
|
||||
RESULT = new FunctionDeclaration((Token)token,FunctionDeclaration.INDEXSIG_RESERVED_NAME,(TypeReference)t, new ParameterDeclaration[] {(ParameterDeclaration)param}, (TypeParameterDeclaration[])tparams);
|
||||
:} |
|
||||
declare_opt CONST:readonly type_param_list_opt:tparams LSPAREN:token param:param RSPAREN type_annotation_opt:t
|
||||
{:
|
||||
RESULT = new FunctionDeclaration((Token)token,FunctionDeclaration.INDEXSIG_RESERVED_NAME,(TypeReference)t, new ParameterDeclaration[] {(ParameterDeclaration)param}, (TypeParameterDeclaration[])tparams);
|
||||
:}
|
||||
;
|
||||
|
||||
param_list_opt ::= lf_opt param_list:l lf_opt {: RESULT = l; :}
|
||||
| lf_opt {: RESULT = new ParameterDeclaration[0]; :}
|
||||
;
|
||||
|
||||
param_list ::= param_list:l lf_opt COMMA lf_opt param:p
|
||||
{:
|
||||
ParameterDeclaration[] list = (ParameterDeclaration[])l;
|
||||
RESULT = ArrayUtils.add(list, (ParameterDeclaration)p);
|
||||
:}
|
||||
| param:p
|
||||
{:
|
||||
RESULT=new ParameterDeclaration[] { (ParameterDeclaration)p };
|
||||
:}
|
||||
;
|
||||
|
||||
param ::= doc_opt lf_opt varargs_opt:varargs IDENTIFIER:i optional_opt:opt type_annotation_opt:t doc_opt lf_opt
|
||||
{:
|
||||
RESULT = new ParameterDeclaration( (Token)i, i.toString(), (TypeReference)t, (Boolean)opt, varargs!=null);
|
||||
:}
|
||||
;
|
||||
|
||||
varargs_opt ::= DOTDOTDOT:varargs {: RESULT=varargs; :} | ;
|
||||
|
||||
type_annotation_opt ::= type_annotation:t {: RESULT=t; :} |
|
||||
;
|
||||
|
||||
type_annotation ::= COL lf_opt doc_opt lf_opt type:t {: RESULT=t; :}
|
||||
;
|
||||
|
||||
type ::=
|
||||
functional_type:t {: RESULT=t; :}
|
||||
| typeof_type:t {: RESULT=t; :}
|
||||
| is_type:t {: RESULT=t; :}
|
||||
| union_type:t {: RESULT=t; :}
|
||||
| intersection_type:t {: RESULT=t; :}
|
||||
| object_type:t {: RESULT=t; :}
|
||||
| array_type:t {: RESULT=t; :}
|
||||
| simple_type:t {: RESULT=t; :}
|
||||
| tuple_type:t {: RESULT=t; :}
|
||||
;
|
||||
|
||||
union_type ::= type:t1 TUBE:t lf_opt type:t2 {: RESULT=new UnionTypeReference((Token)t, (TypeReference)t1, (TypeReference)t2); :}
|
||||
| LPAREN union_type:t RPAREN {: RESULT=t; :}
|
||||
;
|
||||
|
||||
intersection_type ::= type:t1 AND:t lf_opt type:t2 {: RESULT=new UnionTypeReference((Token)t, (TypeReference)t1, (TypeReference)t2, true); :}
|
||||
| LPAREN intersection_type:t RPAREN {: RESULT=t; :}
|
||||
;
|
||||
|
||||
simple_type ::= qual_id:q type_arg_list_opt:tparams {: RESULT=new TypeReference(null, (String)q, (TypeReference[])tparams); :};
|
||||
|
||||
tuple_type ::=
|
||||
LSPAREN type_list:types RSPAREN {: RESULT=new TypeReference(null, "$tuple$", (TypeReference[])types); :}
|
||||
;
|
||||
|
||||
array_type ::=
|
||||
simple_type:t SQUARE {: RESULT=new ArrayTypeReference( null, (TypeReference)t); :}
|
||||
| object_type:t SQUARE {: RESULT=new ArrayTypeReference( null, (TypeReference)t); :}
|
||||
| tuple_type:t SQUARE {: RESULT=new ArrayTypeReference( null, (TypeReference)t); :}
|
||||
| LPAREN functional_type:t RPAREN SQUARE {: RESULT=new ArrayTypeReference(null, (TypeReference)t); :}
|
||||
| array_type:t SQUARE {: RESULT=new ArrayTypeReference(null, (TypeReference)t); :}
|
||||
| LPAREN union_type:t RPAREN SQUARE {: RESULT=new ArrayTypeReference(null, (TypeReference)t); :}
|
||||
;
|
||||
|
||||
functional_type ::=
|
||||
type_param_list_opt:tparams LPAREN_FUNC:token param_list_opt:params RPAREN_FUNC IMPLIES type:t {:
|
||||
RESULT=new FunctionalTypeReference((Token)token, (TypeReference)t, (ParameterDeclaration[])params, (TypeParameterDeclaration[])tparams);
|
||||
:}
|
||||
| NEW:i type_param_list_opt:tparams LPAREN_FUNC param_list_opt:params RPAREN_FUNC IMPLIES type:t {:
|
||||
RESULT=new FunctionalTypeReference((Token)i, true, (TypeReference)t, (ParameterDeclaration[])params, (TypeParameterDeclaration[])tparams);
|
||||
:}
|
||||
| LPAREN functional_type:t RPAREN {: RESULT=t; :}
|
||||
;
|
||||
|
||||
object_type ::= LCPAREN:token member_list_opt:members RCPAREN {: RESULT=new TypeReference((Token)token, (Declaration[])members); :}
|
||||
| LPAREN object_type:t RPAREN {: RESULT=t; :}
|
||||
;
|
||||
|
||||
typeof_type ::= TYPEOF qual_id:name {: TypeReference t = new TypeReference(null, (String)name, null); t.setTypeOf(true); RESULT=t; :}
|
||||
| LPAREN TYPEOF qual_id:name RPAREN {: TypeReference t = new TypeReference(null, (String)name, null); t.setTypeOf(true); RESULT=t; :}
|
||||
;
|
||||
|
||||
is_type ::= IDENTIFIER IS type {: RESULT=new TypeReference(null, "boolean", null); :}
|
||||
| LPAREN IDENTIFIER IS type RPAREN {: RESULT=new TypeReference(null, "boolean", null); :}
|
||||
;
|
||||
|
||||
declare_opt ::= EXPORT | DECLARE | STATIC {: RESULT = "static"; :} | PRIVATE {: RESULT = "private"; :} | PROTECTED {: RESULT = "protected"; :} | PRIVATE STATIC {: RESULT = "private static"; :} | PROTECTED STATIC {: RESULT = "protected static"; :} | PUBLIC {: RESULT = "public"; :} | PUBLIC STATIC {: RESULT = "public static"; :} | ;
|
||||
//declare_opt ::= DECLARE | EXPORT | ;
|
||||
//declare_opt ::= IDENTIFIER:i {: if(!i.toString().equals("declare") || !i.toString().equals("declare")) { throw new RuntimeException("declare or export expected: "); } RESULT=i; :} | ;
|
||||
|
||||
qual_id ::= IDENTIFIER:i {: RESULT=i.toString(); :}
|
||||
| IDENTIFIER:i DOT qual_id:q {: RESULT=i.toString()+"."+q.toString(); :}
|
||||
;
|
||||
|
||||
type_arg_list_opt ::= LT type_arg_list:tparams GT {: RESULT = tparams; :} | ;
|
||||
|
||||
type_arg_list ::= type_arg_list:l COMMA type:p
|
||||
{:
|
||||
TypeReference[] list = (TypeReference[])l;
|
||||
RESULT = ArrayUtils.add(list, (TypeReference)p);
|
||||
:}
|
||||
| type:p
|
||||
{:
|
||||
RESULT=new TypeReference[] { (TypeReference)p };
|
||||
:}
|
||||
;
|
||||
|
||||
type_param_list_opt ::= LT type_param_list:tparams GT {: RESULT = tparams; :} | ;
|
||||
|
||||
type_param_list ::= type_param_list:l COMMA type_param:p
|
||||
{:
|
||||
TypeParameterDeclaration[] list = (TypeParameterDeclaration[])l;
|
||||
RESULT = ArrayUtils.add(list, (TypeParameterDeclaration)p);
|
||||
:}
|
||||
| type_param:p
|
||||
{:
|
||||
RESULT=new TypeParameterDeclaration[] { (TypeParameterDeclaration)p };
|
||||
:}
|
||||
;
|
||||
|
||||
type_param ::= type:t
|
||||
{:
|
||||
RESULT=new TypeParameterDeclaration(((TypeReference)t).getToken(), ((TypeReference)t).getName());
|
||||
:}
|
||||
| type:t EXTENDS type:s
|
||||
{:
|
||||
RESULT=new TypeParameterDeclaration(((TypeReference)t).getToken(), ((TypeReference)t).getName());
|
||||
((TypeParameterDeclaration)RESULT).setUpperBound((TypeReference)s);
|
||||
:}
|
||||
;
|
||||
@ -0,0 +1,225 @@
|
||||
|
||||
/*
|
||||
* This source code file is the exclusive property of its author. No copy or
|
||||
* usage of the source code is permitted unless the author contractually
|
||||
* allows it under the terms of a well-defined agreement.
|
||||
*/
|
||||
|
||||
package org.jsweet.input.typescriptdef.parser;
|
||||
|
||||
import java_cup.runtime.*;
|
||||
import org.jsweet.input.typescriptdef.ast.Token;
|
||||
import java.util.*;
|
||||
|
||||
%%
|
||||
|
||||
%class TypescriptDefScanner
|
||||
%unicode
|
||||
%cup
|
||||
%line
|
||||
%column
|
||||
%state STRING
|
||||
%state CHAR
|
||||
%state TYPE_MACRO
|
||||
%state EOL_COMMENT
|
||||
|
||||
%{
|
||||
StringBuffer string=new StringBuffer();
|
||||
String fileName;
|
||||
public void setFileName(String name) {
|
||||
fileName=name;
|
||||
}
|
||||
public String getFileName() {
|
||||
return fileName;
|
||||
}
|
||||
private Symbol symbol(int type) {
|
||||
return new Symbol(type,yyline,yycolumn,
|
||||
new Token(type,fileName,yytext(),
|
||||
yyline+1,yycolumn+1,
|
||||
yycolumn+1+yytext().length()));
|
||||
}
|
||||
private Symbol symbol(int type, String value) {
|
||||
return new Symbol(type,yyline,yycolumn,
|
||||
new Token(type,fileName,value,
|
||||
yyline+1,yycolumn+1,
|
||||
yycolumn+1+yytext().length()));
|
||||
}
|
||||
private Stack<Symbol> openParens = new Stack<Symbol>();
|
||||
%}
|
||||
|
||||
LineTerminator= \r|\n|\r\n
|
||||
InputCharacter = [^\r\n]
|
||||
WhiteSpace = {LineTerminator} | [ \t\f]
|
||||
WhiteSpaceChar = [ \t\f]
|
||||
Comment = {TraditionalComment} | {EndOfLineComment}
|
||||
|
||||
StringText=(\\\"|[^\n\"]|\\{WhiteSpaceChar}*\\)*
|
||||
|
||||
TraditionalComment = "/*" ~"*/"
|
||||
// Comment can be the last line of the file, without line terminator.
|
||||
//MetaComment = "///" {WhiteSpaceChar}* "<" {InputCharacter}* {LineTerminator}?
|
||||
EndOfLineComment = "//" {InputCharacter}* {LineTerminator}
|
||||
DocumentationComment = "/**" {CommentContent} [^*] "*/"
|
||||
CommentContent = ( [^*] | \*+ [^/*] )*
|
||||
O = [^()]*
|
||||
FunctionalTypeEnding = {O} ({O} "(" {O} ({O} "(" {O} ({O} "(" {O} ")" {O})* {O} ")" {O})* {O} ")" {O})* {O} ")" {WhiteSpaceChar}* "=>"
|
||||
|
||||
Identifier = [A-Za-z0-9_$]*
|
||||
|
||||
DecIntegerLiteral = [0-9] | [1-9][0-9]*
|
||||
HexDigit = [0-9A-Fa-f]
|
||||
Sign = ("+"|"-")
|
||||
DecFloatLiteral = {DecIntegerLiteral}\.{DecIntegerLiteral}
|
||||
|
||||
KeywordEnding = {WhiteSpaceChar}+ [\'\"A-Za-z0-9_$/]
|
||||
SpecialKeywordEnding = {WhiteSpaceChar}+ [\'\"\[A-Za-z0-9_$/]
|
||||
//KeywordEnding = {WhiteSpaceChar}?[ ]?[^:(;]
|
||||
|
||||
%%
|
||||
|
||||
<YYINITIAL> {
|
||||
/* keywords */
|
||||
"interface" / {KeywordEnding} { return symbol(sym.INTERFACE); }
|
||||
"class" / {KeywordEnding} { return symbol(sym.CLASS); }
|
||||
//"declare" {WhiteSpace}* "var" { return symbol(sym.DECLARE_VAR); }
|
||||
//"declare" {WhiteSpace}* "let" { return symbol(sym.DECLARE_VAR); }
|
||||
//"declare" {WhiteSpace}* "const" { return symbol(sym.DECLARE_VAR); }
|
||||
"declare" {WhiteSpace}* "module" { return symbol(sym.DECLARE_MODULE); }
|
||||
"declare" {WhiteSpace}* "namespace" { return symbol(sym.DECLARE_MODULE); }
|
||||
"declare" {WhiteSpace}* "function" { return symbol(sym.DECLARE_FUNCTION); }
|
||||
"declare" {WhiteSpace}* "class" { return symbol(sym.DECLARE_CLASS); }
|
||||
"declare" {WhiteSpace}* "enum" { return symbol(sym.DECLARE_ENUM); }
|
||||
{LineTerminator} {WhiteSpaceChar}* "type" / {KeywordEnding} { yypushback(yylength()); yybegin(TYPE_MACRO); }
|
||||
{LineTerminator} {WhiteSpaceChar}* "export" {WhiteSpace}* "type" / {KeywordEnding} { yypushback(yylength()); yybegin(TYPE_MACRO); }
|
||||
{LineTerminator} {WhiteSpaceChar}* "declare" {WhiteSpace}* "type" / {KeywordEnding} { yypushback(yylength()); yybegin(TYPE_MACRO); }
|
||||
// {MetaComment} { return symbol(sym.REFERENCE); }
|
||||
// most keyword can be used as identifiers, so we differentiate them with special ending
|
||||
"declare" / {KeywordEnding} { return symbol(sym.DECLARE); }
|
||||
"var" / {KeywordEnding} { return symbol(sym.VAR); }
|
||||
"let" / {KeywordEnding} { return symbol(sym.VAR); }
|
||||
//"const" / {KeywordEnding} { return symbol(sym.VAR); }
|
||||
"static" / {KeywordEnding} { return symbol(sym.STATIC); }
|
||||
"abstract" / {KeywordEnding} { return symbol(sym.ABSTRACT); }
|
||||
"extends" / {KeywordEnding} { return symbol(sym.EXTENDS); }
|
||||
"extends" / {WhiteSpaceChar}* "{" { return symbol(sym.EXTENDS); }
|
||||
"extends" / {WhiteSpaceChar}* "(" {FunctionalTypeEnding} { return symbol(sym.EXTENDS); }
|
||||
"implements" / {KeywordEnding} { return symbol(sym.IMPLEMENTS); }
|
||||
"import" / {KeywordEnding} { return symbol(sym.IMPORT); }
|
||||
"import" / {WhiteSpaceChar}* "*" { return symbol(sym.IMPORT); }
|
||||
"export" / {KeywordEnding} { return symbol(sym.EXPORT); }
|
||||
"export" / {WhiteSpace}* "=" { return symbol(sym.EXPORT); }
|
||||
"export" / {WhiteSpace}* "{" { return symbol(sym.EXPORT); }
|
||||
"private" / {KeywordEnding} { return symbol(sym.PRIVATE); }
|
||||
"protected" / {KeywordEnding} { return symbol(sym.PROTECTED); }
|
||||
"public" / {KeywordEnding} { return symbol(sym.PUBLIC); }
|
||||
"function" / {KeywordEnding} { return symbol(sym.FUNCTION); }
|
||||
"typeof" / {KeywordEnding} { return symbol(sym.TYPEOF); }
|
||||
"enum" / {KeywordEnding} { return symbol(sym.ENUM); }
|
||||
"const" / {KeywordEnding} { return symbol(sym.CONST); }
|
||||
"readonly" / {SpecialKeywordEnding} { return symbol(sym.CONST); }
|
||||
"is" / {KeywordEnding} { return symbol(sym.IS); }
|
||||
"as" / {KeywordEnding} { return symbol(sym.AS); }
|
||||
"from" / {KeywordEnding} { return symbol(sym.FROM); }
|
||||
"new" { return symbol(sym.NEW); }
|
||||
|
||||
{Sign}? {DecIntegerLiteral} { return symbol(sym.INT); }
|
||||
[0][xX]{HexDigit}+ { return symbol(sym.INT); }
|
||||
// {DecFloatLiteral} { return symbol(sym.NUM); }
|
||||
{Identifier} { return symbol(sym.IDENTIFIER); }
|
||||
":" { return symbol(sym.COL); }
|
||||
// hack to allow lf before : (would lead to hard disambiguation problem in the parser)
|
||||
{LineTerminator} {WhiteSpaceChar}* ":" { return symbol(sym.COL); }
|
||||
";" { return symbol(sym.SEMI); }
|
||||
"(" / {FunctionalTypeEnding} { return symbol(sym.LPAREN_FUNC); }
|
||||
")" / {WhiteSpaceChar}* "=>" { return symbol(sym.RPAREN_FUNC); }
|
||||
"(" { return symbol(sym.LPAREN); }
|
||||
")" { return symbol(sym.RPAREN); }
|
||||
"{" { return symbol(sym.LCPAREN); }
|
||||
"}" { return symbol(sym.RCPAREN); }
|
||||
"[" {WhiteSpaceChar}* "]" { return symbol(sym.SQUARE); }
|
||||
"[" { return symbol(sym.LSPAREN); }
|
||||
"]" { return symbol(sym.RSPAREN); }
|
||||
"<" { return symbol(sym.LT); }
|
||||
">" { return symbol(sym.GT); }
|
||||
"<=" { return symbol(sym.LTE); }
|
||||
">=" { return symbol(sym.GTE); }
|
||||
"," { return symbol(sym.COMMA); }
|
||||
"." { return symbol(sym.DOT); }
|
||||
"=" { return symbol(sym.ASSIGN); }
|
||||
"==" { return symbol(sym.EQUALS); }
|
||||
"!=" { return symbol(sym.NOTEQUALS); }
|
||||
"~" { return symbol(sym.MATCHES); }
|
||||
"||" { return symbol(sym.OROR); }
|
||||
"?" { return symbol(sym.QUESTION); }
|
||||
"&" { return symbol(sym.AND); }
|
||||
"&&" { return symbol(sym.ANDAND); }
|
||||
"=>" { return symbol(sym.IMPLIES); }
|
||||
"!" { return symbol(sym.NOT); }
|
||||
"+" { return symbol(sym.PLUS); }
|
||||
"++" { return symbol(sym.PLUSPLUS); }
|
||||
"-" { return symbol(sym.MINUS); }
|
||||
"--" { return symbol(sym.MINUSMINUS); }
|
||||
"/" { return symbol(sym.DIV); }
|
||||
"*" { return symbol(sym.MULT); }
|
||||
// hack to allow lf after | (would lead to hard disambiguation problem in the parser)
|
||||
"|" {WhiteSpaceChar}* {LineTerminator} { return symbol(sym.TUBE); }
|
||||
"|" { return symbol(sym.TUBE); }
|
||||
// hack to allow lf before | (would lead to hard disambiguation problem in the parser)
|
||||
{LineTerminator} {WhiteSpaceChar}* "|" {WhiteSpaceChar}* {LineTerminator}? { return symbol(sym.TUBE); }
|
||||
"..." { return symbol(sym.DOTDOTDOT); }
|
||||
".." { return symbol(sym.DOTDOT); }
|
||||
"@" { return symbol(sym.AT); }
|
||||
"'" { string.setLength(0); yybegin(CHAR); }
|
||||
\" { string.setLength(0); yybegin(STRING); }
|
||||
{DocumentationComment} { return symbol(sym.DOC); }
|
||||
{TraditionalComment} { /*System.err.println("COMMENT: "+yytext());*/ /* ignore */ }
|
||||
"//" { yybegin(EOL_COMMENT); }
|
||||
{LineTerminator} { /*System.err.println("LF");*/ return symbol(sym.LF); }
|
||||
{WhiteSpaceChar} { /* ignore */ }
|
||||
//{WhiteSpace} { /* ignore */ }
|
||||
[] { /* ignore */ }
|
||||
}
|
||||
|
||||
<STRING> {
|
||||
\" { yybegin(YYINITIAL);
|
||||
return symbol(sym.IDENTIFIER,
|
||||
"\""+string.toString()+"\""); }
|
||||
[^\n\r\"\\]+ { string.append( yytext() ); }
|
||||
\\t { string.append('\t'); }
|
||||
\\n { string.append('\n'); }
|
||||
|
||||
\\r { string.append('\r'); }
|
||||
\\\" { string.append('\"'); }
|
||||
\\\\ { string.append('\\'); }
|
||||
\\ { string.append('\\'); }
|
||||
}
|
||||
|
||||
<CHAR> {
|
||||
\' { yybegin(YYINITIAL);
|
||||
return symbol(sym.IDENTIFIER,
|
||||
"\""+string.toString()+"\""); }
|
||||
[^\n\r\'\\]+ { string.append( yytext() ); }
|
||||
\\t { string.append('\t'); }
|
||||
\\n { string.append('\n'); }
|
||||
|
||||
\\r { string.append('\r'); }
|
||||
\\\' { string.append('\''); }
|
||||
\\\\ { string.append('\\'); }
|
||||
\\ { string.append('\\'); }
|
||||
}
|
||||
|
||||
<TYPE_MACRO> {
|
||||
{LineTerminator} ({WhiteSpace}* | {Comment})* { return symbol(sym.LF); }
|
||||
"type" { yybegin(YYINITIAL); return symbol(sym.TYPE_MACRO); }
|
||||
"export" { /* ignore */ }
|
||||
"declare" { /* ignore */ }
|
||||
{WhiteSpaceChar}* { /* ignore */ }
|
||||
}
|
||||
|
||||
<EOL_COMMENT> {
|
||||
{LineTerminator} { yybegin(YYINITIAL); yypushback(yylength()); }
|
||||
<<EOF>> { yybegin(YYINITIAL); }
|
||||
[^] { /* ignore */ }
|
||||
}
|
||||
|
||||
.|\n { System.out.println("unmatched:"+yytext()); }
|
||||
@ -0,0 +1,57 @@
|
||||
package org.jsweet.input.typescriptdef.util;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
|
||||
public class CopyrightHelper {
|
||||
|
||||
public static void main(String[] args) {
|
||||
if (args.length < 2) {
|
||||
System.err.println("usage: CopyrightHelper <copyright-file> <root-java-dir>");
|
||||
System.exit(1);
|
||||
}
|
||||
File processedDir;
|
||||
processedDir = new File(args[1]);
|
||||
File copyrightFile = new File(args[0]);
|
||||
if (!copyrightFile.exists()) {
|
||||
System.err.println(copyrightFile + " does not exist");
|
||||
System.err.println("current directory: "+ new File("").getAbsolutePath());
|
||||
System.exit(1);
|
||||
}
|
||||
try {
|
||||
String copyrightText = FileUtils.readFileToString(copyrightFile);
|
||||
insertCopyright(processedDir, copyrightText);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
System.exit(1);
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
private static void insertCopyright(File file, String licenceText) throws Exception {
|
||||
for (File f : file.listFiles()) {
|
||||
if (f.isDirectory()) {
|
||||
insertCopyright(f, licenceText);
|
||||
} else {
|
||||
if (f.getName().endsWith(".java")) {
|
||||
System.out.println("inserting copyright in " + f);
|
||||
String text = FileUtils.readFileToString(f);
|
||||
int insertIndex = text.indexOf("package");
|
||||
int otherIndex = text.indexOf("/**");
|
||||
if (otherIndex != -1) {
|
||||
insertIndex = Math.min(insertIndex, otherIndex);
|
||||
}
|
||||
otherIndex = text.indexOf("@");
|
||||
if (otherIndex != -1) {
|
||||
insertIndex = Math.min(insertIndex, otherIndex);
|
||||
}
|
||||
text = text.substring(insertIndex);
|
||||
FileUtils.write(f, licenceText + "\n");
|
||||
FileUtils.write(f, text, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,71 @@
|
||||
package org.jsweet.input.typescriptdef.util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.Declaration;
|
||||
import org.jsweet.input.typescriptdef.ast.QualifiedDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.Visitable;
|
||||
|
||||
public class DeclarationFinder<T extends Declaration> extends Scanner {
|
||||
|
||||
public interface Matcher<T extends Declaration> {
|
||||
void matches(DeclarationFinder<T> finder, Visitable visitable);
|
||||
}
|
||||
|
||||
protected List<QualifiedDeclaration<T>> matches = new ArrayList<>();
|
||||
private Matcher<T> matcher;
|
||||
private boolean match = false;
|
||||
private boolean stopScan = false;
|
||||
|
||||
public DeclarationFinder(Context context, Matcher<T> matcher) {
|
||||
super(context);
|
||||
this.matcher = matcher;
|
||||
}
|
||||
|
||||
public DeclarationFinder(Scanner parentScanner, Matcher<T> matcher) {
|
||||
super(parentScanner);
|
||||
this.matcher = matcher;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void scan(Visitable visitable) {
|
||||
if (visitable != null && !visitable.isHidden()) {
|
||||
enter(visitable);
|
||||
try {
|
||||
matcher.matches(this, visitable);
|
||||
if (match) {
|
||||
@SuppressWarnings("unchecked")
|
||||
T match = (T) visitable;
|
||||
matches.add(new QualifiedDeclaration<T>(match, getCurrentDeclarationName()));
|
||||
}
|
||||
if (!stopScan) {
|
||||
visitable.accept(this);
|
||||
}
|
||||
} finally {
|
||||
exit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public List<QualifiedDeclaration<T>> getMatches() {
|
||||
return matches;
|
||||
}
|
||||
|
||||
/**
|
||||
* To be called by a matcher to set the current match state of this finder.
|
||||
*
|
||||
* @param match
|
||||
* tells is the matcher matches the current node
|
||||
* @param continueScanning
|
||||
* tells if the matcher want to continue scanning or stop at the
|
||||
* current node
|
||||
*/
|
||||
public void setMatchState(boolean match, boolean continueScanning) {
|
||||
this.match = match;
|
||||
this.stopScan = !continueScanning;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,503 @@
|
||||
package org.jsweet.input.typescriptdef.util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* This class defines a directed graph collection type, that is to say a set of
|
||||
* elements (aka nodes) linked together with directed edges. It is particularly
|
||||
* useful for the <i>topological sort</i>, which is implemented as depicted in
|
||||
* Wikipedia and this <a href=
|
||||
* "http://stackoverflow.com/questions/2739392/sample-directed-graph-and-topological-sort-code"
|
||||
* >StackOverflow thread</a>
|
||||
*
|
||||
* <p>
|
||||
* Example of use:
|
||||
*
|
||||
* <pre>
|
||||
* Graph<Integer> g = new Graph<Integer>();
|
||||
* g.add(7, 5, 3, 11, 8, 2, 9, 10);
|
||||
* g.buildEdges(new Comparator<Integer>() {
|
||||
* @Override
|
||||
* public int compare(Integer o1, Integer o2) {
|
||||
* if (o1 == 5 && o2 == 3) {
|
||||
* return 1;
|
||||
* }
|
||||
* return 0;
|
||||
* }
|
||||
* });
|
||||
* System.out.println(g.topologicalSort());
|
||||
* </pre>
|
||||
*
|
||||
* <p>
|
||||
* Prints out: <code>[11, 10, 8, 7, 2, 3, 5, 9]</code> (5 is always after 3,
|
||||
* because of the edge built by the comparator, however, the remainder is in
|
||||
* random order).
|
||||
*
|
||||
* @author Renaud Pawlak
|
||||
*
|
||||
* @param <T>
|
||||
* the types of the nodes in the graph
|
||||
*/
|
||||
public class DirectedGraph<T> implements Collection<T> {
|
||||
|
||||
private Map<T, Node<T>> nodes = new HashMap<T, Node<T>>();
|
||||
|
||||
/**
|
||||
* Constructs an empty graph collection.
|
||||
*/
|
||||
public DirectedGraph() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a set of elements to the nodes of this graph.
|
||||
*/
|
||||
@Override
|
||||
public boolean addAll(Collection<? extends T> elements) {
|
||||
for (T element : elements) {
|
||||
add(element);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an element to the nodes.
|
||||
*/
|
||||
@Override
|
||||
public boolean add(T element) {
|
||||
// logger.info("adding node: " + element);
|
||||
Node<T> node = new Node<T>(this, element);
|
||||
nodes.put(element, node);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears all the nodes of this graph.
|
||||
*/
|
||||
@Override
|
||||
public void clear() {
|
||||
nodes.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if this graph contains the given object as a node.
|
||||
*/
|
||||
@Override
|
||||
public boolean contains(Object o) {
|
||||
return nodes.containsKey(o);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if this graph contains the given collection as a node.
|
||||
*/
|
||||
@Override
|
||||
public boolean containsAll(Collection<?> c) {
|
||||
for (Object o : c) {
|
||||
if (!contains(o)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Equals two graphs.
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (!(obj instanceof DirectedGraph)) {
|
||||
return false;
|
||||
} else {
|
||||
return nodes.equals(((DirectedGraph<?>) obj).nodes);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return nodes.hashCode();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if this graph has no nodes.
|
||||
*/
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return nodes.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an iterator to iterate on graph nodes.
|
||||
*/
|
||||
@Override
|
||||
public Iterator<T> iterator() {
|
||||
return nodes.keySet().iterator();
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes an object from the graph nodes (if exists).
|
||||
*/
|
||||
@Override
|
||||
public boolean remove(Object o) {
|
||||
return nodes.remove(o) != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes all the objects from the graph nodes (if exists).
|
||||
*/
|
||||
@Override
|
||||
public boolean removeAll(Collection<?> c) {
|
||||
for (Object o : c) {
|
||||
remove(o);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps only the elements of the given collection in the graph.
|
||||
*/
|
||||
@Override
|
||||
public boolean retainAll(Collection<?> c) {
|
||||
boolean b = false;
|
||||
for (T element : nodes.keySet()) {
|
||||
if (!c.contains(element)) {
|
||||
remove(element);
|
||||
b = true;
|
||||
}
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the nodes count in this graph.
|
||||
*/
|
||||
@Override
|
||||
public int size() {
|
||||
return nodes.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the graph's nodes as an array (not sorted).
|
||||
*/
|
||||
@Override
|
||||
public Object[] toArray() {
|
||||
return nodes.keySet().toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the graph's nodes as a well-typed array (not sorted).
|
||||
*/
|
||||
@Override
|
||||
public <U> U[] toArray(U[] a) {
|
||||
return toArray(a);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a set of elements to the nodes of this graph.
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public void add(T... elements) {
|
||||
for (T element : elements) {
|
||||
add(element);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an edge between the given elements (nodes).
|
||||
*
|
||||
* @param sourceElement
|
||||
* the source element/node
|
||||
* @param destinationElement
|
||||
* the destination element/node
|
||||
*/
|
||||
public void addEdge(T sourceElement, T destinationElement) {
|
||||
if (sourceElement.equals(destinationElement)) {
|
||||
// logger.info("cannot define edge on self: " + sourceElement +
|
||||
// " == "
|
||||
// + destinationElement);
|
||||
return;
|
||||
}
|
||||
if (hasEdge(sourceElement, destinationElement)) {
|
||||
// logger.info("edge already defined: " + sourceElement + " -> "
|
||||
// + destinationElement);
|
||||
return;
|
||||
}
|
||||
|
||||
// logger.info("adding edge: " + sourceElement + " -> "
|
||||
// + destinationElement);
|
||||
nodes.get(sourceElement).addEdge(destinationElement);
|
||||
// logger.info("edges: " + nodes.get(sourceElement).outEdges);
|
||||
}
|
||||
|
||||
/**
|
||||
* Automatically builds the edges between all the nodes of the graph by
|
||||
* using the given comparator. If the comparator returns 0, then no edge is
|
||||
* constructor between the compared nodes.
|
||||
*
|
||||
* @param nodeComparator
|
||||
* a comparator which is used to build the edges
|
||||
*/
|
||||
public <U extends T> void buildEdges(Comparator<U> nodeComparator) {
|
||||
for (T e1 : nodes.keySet()) {
|
||||
for (T e2 : nodes.keySet()) {
|
||||
@SuppressWarnings("unchecked")
|
||||
int i = nodeComparator.compare((U) e1, (U) e2);
|
||||
if (i < 0) {
|
||||
addEdge(e1, e2);
|
||||
}
|
||||
if (i > 0) {
|
||||
addEdge(e2, e1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds some edges form the source elements to the given destination
|
||||
* elements.
|
||||
*
|
||||
* @param sourceElement
|
||||
* the source of the edges
|
||||
* @param destinationElements
|
||||
* the destination elements of the edges
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public void addEdges(T sourceElement, T... destinationElements) {
|
||||
nodes.get(sourceElement).addEdges(destinationElements);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if this graph contains an edge between the given source and the
|
||||
* destination elements/nodes.
|
||||
*
|
||||
* @param sourceElement
|
||||
* the source node
|
||||
* @param destinationElement
|
||||
* the destination node
|
||||
* @return true if an edge is found, false otherwise
|
||||
*/
|
||||
public boolean hasEdge(T sourceElement, T destinationElement) {
|
||||
if (nodes.get(sourceElement) == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (Edge<T> edge : nodes.get(sourceElement).outEdges) {
|
||||
if (edge.to.element == destinationElement) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public List<T> getDestinationElements(T sourceElement) {
|
||||
List<T> l = new ArrayList<T>();
|
||||
if (nodes.get(sourceElement) == null) {
|
||||
return null;
|
||||
}
|
||||
for (Edge<T> edge : nodes.get(sourceElement).outEdges) {
|
||||
l.add(edge.to.element);
|
||||
}
|
||||
return l;
|
||||
}
|
||||
|
||||
public List<T> getSourceElements(T destinationElement) {
|
||||
if (nodes.get(destinationElement) == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
List<T> l = new ArrayList<T>();
|
||||
for (Edge<T> edge : nodes.get(destinationElement).inEdges) {
|
||||
l.add(edge.from.element);
|
||||
}
|
||||
return l;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuffer s = new StringBuffer();
|
||||
s.append("[");
|
||||
for (T element : nodes.keySet()) {
|
||||
s.append(element.toString());
|
||||
s.append("->");
|
||||
s.append(getDestinationElements(element));
|
||||
s.append(",");
|
||||
}
|
||||
if (!nodes.isEmpty()) {
|
||||
s.deleteCharAt(s.length() - 1);
|
||||
}
|
||||
s.append("]");
|
||||
return s.toString();
|
||||
}
|
||||
|
||||
public static class Node<T> {
|
||||
private DirectedGraph<T> graph;
|
||||
public final T element;
|
||||
public final HashSet<Edge<T>> inEdges;
|
||||
public final HashSet<Edge<T>> usedInEdges;
|
||||
public final HashSet<Edge<T>> outEdges;
|
||||
public final HashSet<Edge<T>> usedOutEdges;
|
||||
|
||||
public Node(DirectedGraph<T> graph, T element) {
|
||||
this.graph = graph;
|
||||
this.element = element;
|
||||
inEdges = new HashSet<Edge<T>>();
|
||||
usedInEdges = new HashSet<Edge<T>>();
|
||||
outEdges = new HashSet<Edge<T>>();
|
||||
usedOutEdges = new HashSet<Edge<T>>();
|
||||
}
|
||||
|
||||
public void addEdge(T destinationElement) {
|
||||
Node<T> node = graph.nodes.get(destinationElement);
|
||||
if (node == null) {
|
||||
graph.add(destinationElement);
|
||||
node = graph.nodes.get(destinationElement);
|
||||
}
|
||||
Edge<T> e = new Edge<T>(this, node);
|
||||
outEdges.add(e);
|
||||
node.inEdges.add(e);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public void addEdges(T... destinationElements) {
|
||||
for (T destinationElement : destinationElements) {
|
||||
addEdge(destinationElement);
|
||||
}
|
||||
}
|
||||
|
||||
public void useInEdge(Edge<T> edge) {
|
||||
if (inEdges.remove(edge)) {
|
||||
usedInEdges.add(edge);
|
||||
}
|
||||
}
|
||||
|
||||
public void useOutEdge(Edge<T> edge) {
|
||||
if (outEdges.remove(edge)) {
|
||||
usedOutEdges.add(edge);
|
||||
}
|
||||
}
|
||||
|
||||
public void resetEdges() {
|
||||
inEdges.addAll(usedInEdges);
|
||||
usedInEdges.clear();
|
||||
outEdges.addAll(usedOutEdges);
|
||||
usedOutEdges.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Node[" + element + "]";
|
||||
}
|
||||
}
|
||||
|
||||
public static class Edge<T> {
|
||||
public final Node<T> from;
|
||||
public final Node<T> to;
|
||||
|
||||
public Edge(Node<T> from, Node<T> to) {
|
||||
this.from = from;
|
||||
this.to = to;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Edge[" + from + "->" + to + "]";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Edge<T> e = (Edge<T>) obj;
|
||||
return e.from == from && e.to == to;
|
||||
}
|
||||
}
|
||||
|
||||
private List<T> toElements(List<Node<T>> nodes) {
|
||||
List<T> elements = new ArrayList<T>();
|
||||
for (Node<T> node : nodes) {
|
||||
elements.add(node.element);
|
||||
}
|
||||
return elements;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts this graph using a topological sort algorithm given in this <a
|
||||
* href=
|
||||
* "http://stackoverflow.com/questions/2739392/sample-directed-graph-and-topological-sort-code"
|
||||
* >StackOverflow thread</a>.
|
||||
*
|
||||
* @return the list of nodes, sorted according to the topological sort
|
||||
* @throws CycleFoundException
|
||||
* thrown if a cycle is found in the graph (in that case no
|
||||
* topological sort is possible)
|
||||
*/
|
||||
public List<T> topologicalSort(Consumer<Node<T>> cycleHandler) {
|
||||
List<Node<T>> allNodes = new ArrayList<Node<T>>(nodes.values());
|
||||
// L <- Empty list that will contain the sorted elements
|
||||
ArrayList<Node<T>> L = new ArrayList<Node<T>>();
|
||||
|
||||
// S <- Set of all nodes with no incoming edges
|
||||
HashSet<Node<T>> S = new HashSet<Node<T>>();
|
||||
for (Node<T> n : allNodes) {
|
||||
if (n.inEdges.size() == 0) {
|
||||
S.add(n);
|
||||
}
|
||||
}
|
||||
|
||||
// while S is non-empty do
|
||||
while (!S.isEmpty()) {
|
||||
// remove a node n from S
|
||||
Node<T> n = S.iterator().next();
|
||||
S.remove(n);
|
||||
|
||||
// insert n into L
|
||||
L.add(n);
|
||||
|
||||
// for each node m with an edge e from n to m do
|
||||
for (Iterator<Edge<T>> it = new ArrayList<>(n.outEdges).iterator(); it.hasNext();) {
|
||||
// remove edge e from the graph
|
||||
Edge<T> e = it.next();
|
||||
Node<T> m = e.to;
|
||||
n.useOutEdge(e); // Remove edge from n
|
||||
m.useInEdge(e); // Remove edge from m
|
||||
|
||||
// if m has no other incoming edges then insert m into S
|
||||
if (m.inEdges.isEmpty()) {
|
||||
S.add(m);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Check to see if all edges are removed
|
||||
for (Node<T> n : allNodes) {
|
||||
if (!n.inEdges.isEmpty()) {
|
||||
if (cycleHandler != null) {
|
||||
cycleHandler.accept(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (Node<T> n : allNodes) {
|
||||
n.resetEdges();
|
||||
}
|
||||
return toElements(L);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
DirectedGraph<Integer> g = new DirectedGraph<Integer>();
|
||||
g.add(7, 5, 3, 11, 8, 2, 9, 10);
|
||||
g.buildEdges(new Comparator<Integer>() {
|
||||
@Override
|
||||
public int compare(Integer o1, Integer o2) {
|
||||
if (o1 == 5 && o2 == 3) {
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
});
|
||||
System.out.println(g.topologicalSort(null));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,26 @@
|
||||
package org.jsweet.input.typescriptdef.util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
public class NameUtils {
|
||||
|
||||
public static String getDiff(String referenceFullSignature, String targetFullSignature) {
|
||||
List<String> referenceSegments = new ArrayList<String>(
|
||||
Arrays.asList(referenceFullSignature.replace("[]", "s").split("[<>,\\(\\)]")));
|
||||
String[] targetSegments = targetFullSignature.replace("[]", "s").split("[<>,\\(\\)]");
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < targetSegments.length; i++) {
|
||||
if (!referenceSegments.contains(targetSegments[i])) {
|
||||
sb.append(StringUtils.capitalize(targetSegments[i]));
|
||||
} else {
|
||||
referenceSegments.remove(targetSegments[i]);
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,69 @@
|
||||
package org.jsweet.input.typescriptdef.util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.Visitable;
|
||||
|
||||
public class NodeFinder<T extends Visitable> extends Scanner {
|
||||
|
||||
public interface Matcher<T extends Visitable> {
|
||||
void matches(NodeFinder<T> finder, Visitable visitable);
|
||||
}
|
||||
|
||||
protected List<T> matches = new ArrayList<>();
|
||||
private Matcher<T> matcher;
|
||||
private boolean match = false;
|
||||
private boolean stopScan = false;
|
||||
|
||||
public NodeFinder(Context context, Matcher<T> matcher) {
|
||||
super(context);
|
||||
this.matcher = matcher;
|
||||
}
|
||||
|
||||
public NodeFinder(Scanner parentScanner, Matcher<T> matcher) {
|
||||
super(parentScanner);
|
||||
this.matcher = matcher;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void scan(Visitable visitable) {
|
||||
if (visitable != null && !visitable.isHidden()) {
|
||||
enter(visitable);
|
||||
try {
|
||||
matcher.matches(this, visitable);
|
||||
if (match) {
|
||||
@SuppressWarnings("unchecked")
|
||||
T match = (T) visitable;
|
||||
matches.add(match);
|
||||
}
|
||||
if (!stopScan) {
|
||||
visitable.accept(this);
|
||||
}
|
||||
} finally {
|
||||
exit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public List<T> getMatches() {
|
||||
return matches;
|
||||
}
|
||||
|
||||
/**
|
||||
* To be called by a matcher to set the current match state of this finder.
|
||||
*
|
||||
* @param match
|
||||
* tells is the matcher matches the current node
|
||||
* @param continueScanning
|
||||
* tells if the matcher want to continue scanning or stop at the
|
||||
* current node
|
||||
*/
|
||||
public void setMatchState(boolean match, boolean continueScanning) {
|
||||
this.match = match;
|
||||
this.stopScan = !continueScanning;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,82 @@
|
||||
package org.jsweet.input.typescriptdef.util;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
public class ProcessUtil {
|
||||
private final static Logger logger = Logger.getLogger("process");
|
||||
|
||||
public static String TSD_COMMAND = "tsd";
|
||||
public static String MVN_COMMAND = "mvn";
|
||||
public static String BOWER_COMMAND = "bower";
|
||||
public static String EXTRA_PATH;
|
||||
|
||||
public static void init() {
|
||||
// hack for Eclipse under Mac OSX
|
||||
if (!System.getenv("PATH").contains("/usr/local/bin") && new File("/usr/local/bin/tsd").exists()) {
|
||||
ProcessUtil.EXTRA_PATH = "/usr/local/bin";
|
||||
ProcessUtil.TSD_COMMAND = "/usr/local/bin/tsd";
|
||||
ProcessUtil.MVN_COMMAND = "/usr/local/bin/mvn";
|
||||
ProcessUtil.BOWER_COMMAND = "/usr/local/bin/bower";
|
||||
}
|
||||
}
|
||||
|
||||
public static void runCmd(Consumer<String> stdoutConsumer, String... cmd) {
|
||||
runCmd(null, stdoutConsumer, cmd);
|
||||
}
|
||||
|
||||
public static void runCmd(File directory, Consumer<String> stdoutConsumer, String... cmd) {
|
||||
System.out.println("run command: " + StringUtils.join(cmd, " "));
|
||||
|
||||
String[] args;
|
||||
if (System.getProperty("os.name").startsWith("Windows")) {
|
||||
args = new String[] { "cmd", "/c" };
|
||||
} else {
|
||||
args = new String[0];
|
||||
}
|
||||
args = ArrayUtils.addAll(args, cmd);
|
||||
|
||||
System.out.println("run command: '" + StringUtils.join(args, " ") + "' in directory " + directory);
|
||||
// logger.fine("run command: " + StringUtils.join(args, " "));
|
||||
int code = -1;
|
||||
try {
|
||||
|
||||
ProcessBuilder processBuilder = new ProcessBuilder(args);
|
||||
processBuilder.redirectErrorStream(true);
|
||||
if (directory != null) {
|
||||
processBuilder.directory(directory);
|
||||
}
|
||||
if (!StringUtils.isBlank(EXTRA_PATH)) {
|
||||
processBuilder.environment().put("PATH", processBuilder.environment().get("PATH") + File.pathSeparator + EXTRA_PATH);
|
||||
}
|
||||
|
||||
Process process = processBuilder.start();
|
||||
|
||||
try (BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
|
||||
String line;
|
||||
while ((line = in.readLine()) != null) {
|
||||
if (stdoutConsumer != null) {
|
||||
stdoutConsumer.accept(line);
|
||||
} else {
|
||||
logger.info("OUT:" + line);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
code = process.waitFor();
|
||||
if (code != 0) {
|
||||
throw new RuntimeException("error while exectuting: " + StringUtils.join(args, " ") + ", error code: "
|
||||
+ code);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,367 @@
|
||||
package org.jsweet.input.typescriptdef.util;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Stack;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* A tree is an element container that can have several child trees.
|
||||
*
|
||||
* @author Renaud Pawlak
|
||||
*
|
||||
* @param <E>
|
||||
* the type of the element attached to the tree
|
||||
* @param <ID>
|
||||
* the type of the id attached to the tree
|
||||
*/
|
||||
public class Tree<E, ID> {
|
||||
|
||||
private E element;
|
||||
private ID id;
|
||||
private Tree<E, ID> parentTree;
|
||||
private List<Tree<E, ID>> childTrees = new ArrayList<Tree<E, ID>>();
|
||||
|
||||
/**
|
||||
* A default scanner, to be overriden to perform recursive operations on a
|
||||
* tree.
|
||||
*
|
||||
* @author Renaud Pawlak
|
||||
*/
|
||||
public static class Scanner<E, ID> {
|
||||
protected Stack<Tree<E, ID>> stack = new Stack<>();
|
||||
|
||||
public final void scan(Tree<E, ID> tree) {
|
||||
if (!enter(tree)) {
|
||||
return;
|
||||
}
|
||||
stack.push(tree);
|
||||
try {
|
||||
for (Tree<E, ID> childTree : tree.getChildTrees()) {
|
||||
scan(childTree);
|
||||
}
|
||||
} finally {
|
||||
stack.pop();
|
||||
exit(tree);
|
||||
}
|
||||
}
|
||||
|
||||
protected boolean enter(Tree<E, ID> tree) {
|
||||
return true;
|
||||
}
|
||||
|
||||
protected void exit(Tree<E, ID> tree) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A helper to match a tree or a path on the to-stringed values of its
|
||||
* elements.
|
||||
*
|
||||
* @author Renaud Pawlak
|
||||
*/
|
||||
public static class Matcher {
|
||||
protected String[] expressions;
|
||||
|
||||
/**
|
||||
* Each expression is a matcher for an element in the tested path.
|
||||
* <p>
|
||||
* Not operators are allowed with expressions starting with !.
|
||||
* <p>
|
||||
* A path will match if all the first elements match each expressions of
|
||||
* the matcher.
|
||||
*/
|
||||
public Matcher(String... expressions) {
|
||||
this.expressions = expressions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if this matcher matches the given tree (i.e. if one path
|
||||
* starting from that tree matches).
|
||||
*/
|
||||
public boolean matches(Tree<?, ?> tree) {
|
||||
return matches(Arrays.asList(this.expressions), tree);
|
||||
}
|
||||
|
||||
private static boolean matches(List<String> expressions, Tree<?, ?> tree) {
|
||||
if (expressions.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
String expr = expressions.get(0);
|
||||
if (expr.startsWith("!")) {
|
||||
expr = expr.substring(1);
|
||||
if (("" + tree.getElement()).equals(expr)) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
if (!("" + tree.getElement()).equals(expr)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (tree.getChildTrees().isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
for (Tree<?, ?> child : tree.getChildTrees()) {
|
||||
if (matches(expressions.subList(1, expressions.size()), child)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if this matcher matches the given path.
|
||||
*/
|
||||
public boolean matches(List<?> path) {
|
||||
return matches(Arrays.asList(this.expressions), path);
|
||||
}
|
||||
|
||||
private static boolean matches(List<String> expressions, List<?> path) {
|
||||
if (expressions.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
if (path.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String expr = expressions.get(0);
|
||||
if (expr.startsWith("!")) {
|
||||
expr = expr.substring(1);
|
||||
if (("" + path.get(0)).equals(expr)) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
if (!("" + path.get(0)).equals(expr)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return matches(expressions.subList(1, expressions.size()), path.subList(1, path.size()));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a tree with a single element (no parent, no children).
|
||||
*/
|
||||
public Tree(E element) {
|
||||
this.element = element;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the id attached to this tree (optional).
|
||||
*/
|
||||
public ID getID() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the id attached to this tree.
|
||||
*/
|
||||
public void setID(ID id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add some children elements to this tree.
|
||||
*
|
||||
* @param element
|
||||
* the element to add children to (root node if null)
|
||||
* @param childElements
|
||||
* the elements to add to the parent
|
||||
*/
|
||||
public void addChildElements(List<E> childElements) {
|
||||
for (E child : childElements) {
|
||||
Tree<E, ID> childTree = new Tree<E, ID>(child);
|
||||
childTree.parentTree = this;
|
||||
this.childTrees.add(childTree);
|
||||
}
|
||||
}
|
||||
|
||||
public void clearChildTrees() {
|
||||
this.childTrees.clear();
|
||||
}
|
||||
|
||||
public void addChildTrees(List<Tree<E, ID>> childTrees) {
|
||||
for (Tree<E, ID> childTree : childTrees) {
|
||||
childTree.parentTree = this;
|
||||
this.childTrees.add(childTree);
|
||||
}
|
||||
}
|
||||
|
||||
public void addChildTree(Tree<E, ID> childTree) {
|
||||
childTree.parentTree = this;
|
||||
this.childTrees.add(childTree);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a child to this tree (add the end of the current children).
|
||||
*/
|
||||
public Tree<E, ID> addChildElement(E childElement) {
|
||||
Tree<E, ID> childTree = new Tree<E, ID>(childElement);
|
||||
childTree.parentTree = this;
|
||||
this.childTrees.add(childTree);
|
||||
return childTree;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the parent tree of this tree.
|
||||
*/
|
||||
public Tree<E, ID> getParentTree() {
|
||||
return parentTree;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the parent of this tree.
|
||||
*/
|
||||
public E getParentElement() {
|
||||
return parentTree != null ? parentTree.element : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the children of this tree.
|
||||
*/
|
||||
public List<Tree<E, ID>> getChildTrees() {
|
||||
return this.childTrees;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the child trees that match the given element.
|
||||
*/
|
||||
public List<Tree<E, ID>> getChildTrees(E e) {
|
||||
return childTrees.stream().filter(t -> e.equals(t.element)).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the elements attached to the child trees.
|
||||
*/
|
||||
public List<E> getChildElements() {
|
||||
return childTrees.stream().map(t -> t.element).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the element contained in this tree.
|
||||
*/
|
||||
public E getElement() {
|
||||
return this.element;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the element contained in this tree;
|
||||
*/
|
||||
public void setElement(E element) {
|
||||
this.element = element;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a path to the current tree.
|
||||
*/
|
||||
final public Tree<E, ID> addPath(List<E> path) {
|
||||
if (path.size() == 0) {
|
||||
return this;
|
||||
}
|
||||
List<E> childElements = getChildElements();
|
||||
int index = childElements.indexOf(path.get(0));
|
||||
Tree<E, ID> nextTree;
|
||||
if (index < 0) {
|
||||
nextTree = addChildElement(path.get(0));
|
||||
} else {
|
||||
nextTree = getChildTrees().get(index);
|
||||
}
|
||||
return nextTree.addPath(path.subList(1, path.size()));
|
||||
}
|
||||
|
||||
public boolean isLeaf() {
|
||||
return childTrees.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
final StringBuffer output = new StringBuffer();
|
||||
new Tree.Scanner<E, ID>() {
|
||||
protected boolean enter(Tree<E, ID> tree) {
|
||||
output.append("[");
|
||||
output.append(tree.getElement());
|
||||
if (tree.getID() != null) {
|
||||
output.append("*");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
protected void exit(Tree<E, ID> tree) {
|
||||
output.append("]");
|
||||
}
|
||||
}.scan(this);
|
||||
return output.toString();
|
||||
}
|
||||
|
||||
public List<List<Tree<E, ID>>> findElement(final E element) {
|
||||
final List<List<Tree<E, ID>>> result = new ArrayList<>();
|
||||
final List<Tree<E, ID>> path = new ArrayList<>();
|
||||
new Tree.Scanner<E, ID>() {
|
||||
protected boolean enter(Tree<E, ID> tree) {
|
||||
if (element.equals(tree.getElement())) {
|
||||
path.clear();
|
||||
for (Tree<E, ID> t : stack) {
|
||||
path.add(t);
|
||||
}
|
||||
path.add(tree);
|
||||
result.add(new ArrayList<>(path));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}.scan(this);
|
||||
return result;
|
||||
}
|
||||
|
||||
public List<Tree<E, ID>> findFirstElement(final E element) {
|
||||
final List<Tree<E, ID>> path = new ArrayList<>();
|
||||
new Tree.Scanner<E, ID>() {
|
||||
protected boolean enter(Tree<E, ID> tree) {
|
||||
if (!path.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
if (element.equals(tree.getElement())) {
|
||||
path.clear();
|
||||
for (Tree<E, ID> t : stack) {
|
||||
path.add(t);
|
||||
}
|
||||
path.add(tree);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}.scan(this);
|
||||
return path;
|
||||
}
|
||||
|
||||
public List<Tree<E, ID>> find(final ID id) {
|
||||
final List<Tree<E, ID>> path = new ArrayList<>();
|
||||
new Tree.Scanner<E, ID>() {
|
||||
protected boolean enter(Tree<E, ID> tree) {
|
||||
if (!path.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
if (id.equals(tree.getID())) {
|
||||
for (Tree<E, ID> t : stack) {
|
||||
path.add(t);
|
||||
}
|
||||
path.add(tree);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}.scan(this);
|
||||
return path;
|
||||
}
|
||||
|
||||
public static List<String> toStringPath(List<Tree<String, File>> path) {
|
||||
return path.stream().map(t -> t.getElement()).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,636 @@
|
||||
package org.jsweet.input.typescriptdef.util;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.AbstractMap;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.lang3.AnnotationUtils;
|
||||
import org.apache.commons.lang3.ClassUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.builder.ToStringBuilder;
|
||||
import org.apache.commons.lang3.builder.ToStringStyle;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.jsoup.helper.StringUtil;
|
||||
import org.jsweet.JSweetDefTranslatorConfig;
|
||||
import org.jsweet.input.typescriptdef.ast.ArrayTypeReference;
|
||||
import org.jsweet.input.typescriptdef.ast.AstNode;
|
||||
import org.jsweet.input.typescriptdef.ast.CompilationUnit;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.Declaration;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationContainer;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.ModuleDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.ParameterDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.Type;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeParameterDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeParameterizedElement;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeReference;
|
||||
import org.jsweet.input.typescriptdef.ast.TypedDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Visitable;
|
||||
|
||||
public class Util {
|
||||
|
||||
protected final static Logger logger = Logger.getLogger(Util.class);
|
||||
public static Map<String, String> coreTypeMap = new HashMap<String, String>();
|
||||
public static Map<String, String> wrapTypeMap = new HashMap<String, String>();
|
||||
|
||||
static {
|
||||
coreTypeMap.put("any", "Object");
|
||||
coreTypeMap.put("string", "String");
|
||||
coreTypeMap.put("boolean", "Boolean");
|
||||
coreTypeMap.put("String", "String");
|
||||
coreTypeMap.put("Boolean", "Boolean");
|
||||
coreTypeMap.put("Object", "Object");
|
||||
}
|
||||
|
||||
static {
|
||||
wrapTypeMap.put("any", "java.lang.Object");
|
||||
wrapTypeMap.put("string", "java.lang.String");
|
||||
wrapTypeMap.put("String", "java.lang.String");
|
||||
wrapTypeMap.put("Boolean", "java.lang.Boolean");
|
||||
wrapTypeMap.put("boolean", "java.lang.Boolean");
|
||||
wrapTypeMap.put("double", "java.lang.Double");
|
||||
wrapTypeMap.put("number", "java.lang.Double");
|
||||
wrapTypeMap.put("int", "java.lang.Integer");
|
||||
wrapTypeMap.put("float", "java.lang.Float");
|
||||
wrapTypeMap.put("Object", "java.lang.Object");
|
||||
}
|
||||
|
||||
public static <T extends AstNode> T wrapTypeReferences(T node) {
|
||||
// new Scanner((Context) null) {
|
||||
// @Override
|
||||
// public void visitTypeReference(TypeReference typeReference) {
|
||||
// typeReference.setName(typeReference.getWrappingTypeName());
|
||||
// }
|
||||
// }.scan(node);
|
||||
// return node;
|
||||
return subtituteTypeReferenceNames(node, wrapTypeMap);
|
||||
}
|
||||
|
||||
public static <T extends AstNode> T subtituteTypeReferenceNames(T node, final Map<String, String> nameMap) {
|
||||
new Scanner((Context) null) {
|
||||
@Override
|
||||
public void visitTypeReference(TypeReference typeReference) {
|
||||
if (nameMap.containsKey(typeReference.getName())) {
|
||||
typeReference.setName(nameMap.get(typeReference.getName()));
|
||||
}
|
||||
}
|
||||
}.scan(node);
|
||||
return node;
|
||||
}
|
||||
|
||||
public static <T extends AstNode> T subtituteTypeReferences(T node, final Map<String, TypeReference> nameMap) {
|
||||
new Scanner((Context) null) {
|
||||
@Override
|
||||
public void visitTypeReference(TypeReference typeReference) {
|
||||
if (nameMap.containsKey(typeReference.getName())) {
|
||||
TypeReference targetTypeReference = nameMap.get(typeReference.getName());
|
||||
if (getParent() instanceof TypedDeclaration
|
||||
&& ((TypedDeclaration) getParent()).getType() == typeReference) {
|
||||
((TypedDeclaration) getParent()).setType(targetTypeReference.copy());
|
||||
} else {
|
||||
if (typeReference instanceof ArrayTypeReference) {
|
||||
logger.error("cannot substitute array type reference");
|
||||
} else {
|
||||
typeReference.setName(targetTypeReference.getName());
|
||||
typeReference.setTypeArguments(targetTypeReference.getTypeArguments());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}.scan(node);
|
||||
return node;
|
||||
}
|
||||
|
||||
public static boolean hasTypeParameterReferences(Context context, AstNode node) {
|
||||
List<TypeParameterDeclaration> l = new ArrayList<TypeParameterDeclaration>();
|
||||
new Scanner(context) {
|
||||
@Override
|
||||
public void visitTypeReference(TypeReference typeReference) {
|
||||
Type t = lookupType(typeReference);
|
||||
if (t instanceof TypeParameterDeclaration) {
|
||||
l.add((TypeParameterDeclaration) t);
|
||||
}
|
||||
super.visitTypeReference(typeReference);
|
||||
}
|
||||
}.scan(node);
|
||||
return !l.isEmpty();
|
||||
}
|
||||
|
||||
public static boolean substituteTypeReference(Scanner scanner, TypedDeclaration targetTypedElement,
|
||||
TypeReference targetType, TypeReference newType) {
|
||||
Visitable node = null;
|
||||
do {
|
||||
if (node == null) {
|
||||
node = scanner.getParent();
|
||||
} else {
|
||||
node = scanner.getParent(Visitable.class, node);
|
||||
}
|
||||
if (node instanceof TypeReference) {
|
||||
if (((TypeReference) node).substituteTypeReference(targetType, newType)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} while (!scanner.getStack().isEmpty() && node != targetTypedElement);
|
||||
if (node == targetTypedElement) {
|
||||
targetTypedElement.setType(newType);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static Pattern referencePathMatcher = Pattern.compile("/// *<reference .*path *= *\"(.*)\".*");
|
||||
|
||||
public static String getLibPathFromReference(String reference) {
|
||||
Matcher m = referencePathMatcher.matcher(reference);
|
||||
if (m.matches()) {
|
||||
return m.group(1);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the relative path that links the two given paths.
|
||||
*
|
||||
* <pre>
|
||||
* assertEquals("../c", Util.getRelativePath("/a/b", "/a/c"));
|
||||
* assertEquals("..", Util.getRelativePath("/a/b", "/a"));
|
||||
* assertEquals("../e", Util.getRelativePath("/a/b/c", "/a/b/e"));
|
||||
* assertEquals("d", Util.getRelativePath("/a/b/c", "/a/b/c/d"));
|
||||
* assertEquals("d/e", Util.getRelativePath("/a/b/c", "/a/b/c/d/e"));
|
||||
* assertEquals("../../../d/e/f", Util.getRelativePath("/a/b/c", "/d/e/f"));
|
||||
* assertEquals("../..", Util.getRelativePath("/a/b/c", "/a"));
|
||||
* assertEquals("..", Util.getRelativePath("/a/b/c", "/a/b"));
|
||||
* </pre>
|
||||
*
|
||||
* <p>
|
||||
* Thanks to:
|
||||
* http://mrpmorris.blogspot.com/2007/05/convert-absolute-path-to-relative-
|
||||
* path.html
|
||||
*
|
||||
* <p>
|
||||
* Bug fix: Renaud Pawlak
|
||||
*
|
||||
* @param fromPath
|
||||
* the path to start from
|
||||
* @param toPath
|
||||
* the path to reach
|
||||
*/
|
||||
public static String getRelativePath(String fromPath, String toPath) {
|
||||
StringBuilder relativePath = null;
|
||||
|
||||
fromPath = fromPath.replaceAll("\\\\", "/");
|
||||
toPath = toPath.replaceAll("\\\\", "/");
|
||||
|
||||
if (!fromPath.equals(toPath)) {
|
||||
String[] fromSegments = fromPath.split("/");
|
||||
String[] toSegments = toPath.split("/");
|
||||
|
||||
// Get the shortest of the two paths
|
||||
int length = fromSegments.length < toSegments.length ? fromSegments.length : toSegments.length;
|
||||
|
||||
// Use to determine where in the loop we exited
|
||||
int lastCommonRoot = -1;
|
||||
int index;
|
||||
|
||||
// Find common root
|
||||
for (index = 0; index < length; index++) {
|
||||
if (fromSegments[index].equals(toSegments[index])) {
|
||||
lastCommonRoot = index;
|
||||
} else {
|
||||
break;
|
||||
// If we didn't find a common prefix then throw
|
||||
}
|
||||
}
|
||||
if (lastCommonRoot != -1) {
|
||||
// Build up the relative path
|
||||
relativePath = new StringBuilder();
|
||||
// Add on the ..
|
||||
for (index = lastCommonRoot + 1; index < fromSegments.length; index++) {
|
||||
if (fromSegments[index].length() > 0) {
|
||||
relativePath.append("../");
|
||||
}
|
||||
}
|
||||
for (index = lastCommonRoot + 1; index < toSegments.length - 1; index++) {
|
||||
relativePath.append(toSegments[index] + "/");
|
||||
}
|
||||
if (!fromPath.startsWith(toPath)) {
|
||||
relativePath.append(toSegments[toSegments.length - 1]);
|
||||
} else {
|
||||
if (relativePath.length() > 0) {
|
||||
relativePath.deleteCharAt(relativePath.length() - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return relativePath == null ? null : relativePath.toString();
|
||||
}
|
||||
|
||||
private static String getReferenceMainModuleName(Context context, CompilationUnit compilationUnit, String reference)
|
||||
throws IOException {
|
||||
if (reference == null) {
|
||||
return null;
|
||||
}
|
||||
File referenceFile = new File(reference);
|
||||
if (!referenceFile.isAbsolute()) {
|
||||
referenceFile = new File(compilationUnit.getFile().getParentFile(), reference);
|
||||
referenceFile = referenceFile.getCanonicalFile();
|
||||
}
|
||||
CompilationUnit referencedCompilationUnit = null;
|
||||
for (CompilationUnit cu : context.compilationUnits) {
|
||||
if (cu.getFile().getCanonicalFile().equals(referenceFile)) {
|
||||
referencedCompilationUnit = cu;
|
||||
}
|
||||
}
|
||||
return referencedCompilationUnit == null ? null : referencedCompilationUnit.getMainModule().getName();
|
||||
}
|
||||
|
||||
public static void createDependencyGraph(Context context) throws IOException {
|
||||
DirectedGraph<String> dependencyGraph = new DirectedGraph<String>();
|
||||
for (CompilationUnit compilationUnit : context.compilationUnits) {
|
||||
String lib = compilationUnit.getMainModule().getName();
|
||||
if (lib == null) {
|
||||
continue;
|
||||
}
|
||||
if (!dependencyGraph.contains(lib)) {
|
||||
dependencyGraph.add(lib);
|
||||
}
|
||||
for (String ref : compilationUnit.getReferences()) {
|
||||
String refLib = getReferenceMainModuleName(context, compilationUnit, Util.getLibPathFromReference(ref));
|
||||
if (refLib == null) {
|
||||
continue;
|
||||
}
|
||||
if (refLib.equals(lib)) {
|
||||
// ignore self references
|
||||
continue;
|
||||
}
|
||||
if (!dependencyGraph.contains(refLib)) {
|
||||
dependencyGraph.add(refLib);
|
||||
}
|
||||
dependencyGraph.addEdge(lib, refLib);
|
||||
}
|
||||
}
|
||||
context.dependencyGraph = dependencyGraph;
|
||||
}
|
||||
|
||||
public static String toJavaName(String name) {
|
||||
return toJavaName(name, false);
|
||||
}
|
||||
|
||||
public static String toJavaName(String name, boolean forceLowerCase) {
|
||||
if (name == null) {
|
||||
return null;
|
||||
}
|
||||
if (forceLowerCase) {
|
||||
if (!StringUtils.isAllLowerCase(name)) {
|
||||
name = name.toLowerCase();
|
||||
}
|
||||
}
|
||||
if (name.contains("-") || name.contains("/")) {
|
||||
return name.replace('/', '_').replace('-', '_');
|
||||
}
|
||||
if (Character.isDigit(name.charAt(0))) {
|
||||
return "_" + name;
|
||||
}
|
||||
if (JSweetDefTranslatorConfig.JAVA_KEYWORDS.contains(name)) {
|
||||
if (forceLowerCase) {
|
||||
return "_" + name;
|
||||
} else {
|
||||
return StringUtils.capitalize(name);
|
||||
}
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Generate a string representation of an Annotation, as suggested by
|
||||
* {@link Annotation#toString()}.
|
||||
* </p>
|
||||
*
|
||||
* @param a
|
||||
* the annotation of which a string representation is desired
|
||||
* @return the standard string representation of an annotation, not
|
||||
* {@code null}
|
||||
*/
|
||||
public static String toString(final Annotation a) {
|
||||
final ToStringBuilder builder = new ToStringBuilder(a, TO_STRING_STYLE);
|
||||
for (final Method m : a.annotationType().getDeclaredMethods()) {
|
||||
if (m.getParameterTypes().length > 0) {
|
||||
continue; // wtf?
|
||||
}
|
||||
try {
|
||||
Object val = m.invoke(a);
|
||||
if (val instanceof String) {
|
||||
val = "\"" + val + "\"";
|
||||
}
|
||||
builder.append(m.getName(), val);
|
||||
} catch (final RuntimeException ex) {
|
||||
throw ex;
|
||||
} catch (final Exception ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
private static final ToStringStyle TO_STRING_STYLE = new ToStringStyle() {
|
||||
/** Serialization version */
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
{
|
||||
setDefaultFullDetail(true);
|
||||
setArrayContentDetail(true);
|
||||
setUseClassName(true);
|
||||
setUseShortClassName(true);
|
||||
setUseIdentityHashCode(false);
|
||||
setContentStart("(");
|
||||
setContentEnd(")");
|
||||
setFieldSeparator(", ");
|
||||
setArrayStart("[");
|
||||
setArrayEnd("]");
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
protected String getShortClassName(final java.lang.Class<?> cls) {
|
||||
Class<? extends Annotation> annotationType = null;
|
||||
for (final Class<?> iface : ClassUtils.getAllInterfaces(cls)) {
|
||||
if (Annotation.class.isAssignableFrom(iface)) {
|
||||
@SuppressWarnings("unchecked")
|
||||
// OK because we just checked the assignability
|
||||
final Class<? extends Annotation> found = (Class<? extends Annotation>) iface;
|
||||
annotationType = found;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return new StringBuilder(annotationType == null ? "" : annotationType.getName()).insert(0, '@').toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
protected void appendDetail(final StringBuffer buffer, final String fieldName, Object value) {
|
||||
if (value instanceof Annotation) {
|
||||
value = AnnotationUtils.toString((Annotation) value);
|
||||
}
|
||||
super.appendDetail(buffer, fieldName, value);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
public static void checkAndAdjustDeclarationName(Declaration declaration) {
|
||||
checkAndAdjustDeclarationName(declaration, false);
|
||||
}
|
||||
|
||||
public static void checkAndAdjustDeclarationName(Declaration declaration, boolean forceLowerCase) {
|
||||
String oldName = declaration.getName();
|
||||
|
||||
if (StringUtil.isBlank(oldName)) {
|
||||
return;
|
||||
}
|
||||
String newName = toJavaName(oldName, forceLowerCase);
|
||||
if (declaration.isQuotedName() && newName.contains(".")) {
|
||||
newName = newName.replace('.', '_');
|
||||
}
|
||||
if (!oldName.equals(newName)) {
|
||||
declaration.removeStringAnnotation(JSweetDefTranslatorConfig.ANNOTATION_NAME);
|
||||
declaration.addStringAnnotation(JSweetDefTranslatorConfig.ANNOTATION_NAME + "(\"" + oldName + "\")");
|
||||
declaration.setOriginalName(declaration.getName());
|
||||
declaration.setName(newName);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the container or any subnode of that AST contains the
|
||||
* exact given node object. Note that this function uses object reference
|
||||
* comparison (==).
|
||||
*/
|
||||
public static boolean containsAstNode(AstNode container, AstNode node) {
|
||||
final boolean[] result = { false };
|
||||
new Scanner((Context) null) {
|
||||
@Override
|
||||
public void scan(Visitable visitable) {
|
||||
if (node == visitable) {
|
||||
result[0] = true;
|
||||
} else {
|
||||
super.scan(visitable);
|
||||
}
|
||||
}
|
||||
}.scan(container);
|
||||
return result[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the qualifier of the given qualified name.
|
||||
*/
|
||||
public static String getQualifier(String qualifiedName) {
|
||||
if (qualifiedName == null) {
|
||||
return null;
|
||||
}
|
||||
int index = qualifiedName.lastIndexOf('.');
|
||||
if (index < 0) {
|
||||
return null;
|
||||
}
|
||||
return qualifiedName.substring(0, qualifiedName.lastIndexOf('.'));
|
||||
}
|
||||
|
||||
public static boolean isQualified(String name) {
|
||||
return name.indexOf('.') != -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the simple name of the given qualified name.
|
||||
*/
|
||||
public static String getSimpleName(String qualifiedName) {
|
||||
return qualifiedName == null ? null : qualifiedName.substring(qualifiedName.lastIndexOf('.') + 1);
|
||||
}
|
||||
|
||||
private static TypeDeclaration createGlobalsClass(String name) {
|
||||
TypeDeclaration globalsClass = new TypeDeclaration(null, "class", name, null, null, new Declaration[0]);
|
||||
globalsClass.addModifier("final");
|
||||
FunctionDeclaration constructor = new FunctionDeclaration(null, "constructor", null,
|
||||
new ParameterDeclaration[0], null);
|
||||
constructor.addModifier("private");
|
||||
globalsClass.addMember(constructor);
|
||||
return globalsClass;
|
||||
}
|
||||
|
||||
public static TypeDeclaration getOrCreateGlobalsType(Context context, ModuleDeclaration moduleDeclaration,
|
||||
DeclarationContainer container) {
|
||||
String modName = moduleDeclaration.getName();
|
||||
TypeDeclaration globalsClass = null;
|
||||
if (container != null && Util.elligibleToClass(moduleDeclaration)) {
|
||||
globalsClass = container.findType(modName);
|
||||
if (globalsClass == null) {
|
||||
globalsClass = createGlobalsClass(modName);
|
||||
context.registerType(
|
||||
((container instanceof ModuleDeclaration)
|
||||
? context.getModuleName((ModuleDeclaration) container) + "." : "") + modName,
|
||||
globalsClass);
|
||||
globalsClass.setDocumentation("/** Utility class. */");
|
||||
container.addMember(globalsClass);
|
||||
}
|
||||
} else {
|
||||
globalsClass = context.getTypeDeclaration(
|
||||
context.getModuleName(moduleDeclaration) + "." + JSweetDefTranslatorConfig.GLOBALS_CLASS_NAME);
|
||||
if (globalsClass == null) {
|
||||
globalsClass = createGlobalsClass(JSweetDefTranslatorConfig.GLOBALS_CLASS_NAME);
|
||||
context.registerType(
|
||||
context.getModuleName(moduleDeclaration) + "." + JSweetDefTranslatorConfig.GLOBALS_CLASS_NAME,
|
||||
globalsClass);
|
||||
globalsClass.setDocumentation("/** This class holds all the global functions and variables of the "
|
||||
+ moduleDeclaration.getName() + " package. */");
|
||||
moduleDeclaration.addMember(globalsClass);
|
||||
}
|
||||
}
|
||||
return globalsClass;
|
||||
}
|
||||
|
||||
public static TypeParameterDeclaration[] findTypeParameters(Scanner parent, Visitable visitable) {
|
||||
return new TypeParameterFinder(parent).find(visitable);
|
||||
}
|
||||
|
||||
public static TypeParameterDeclaration[] findTypeParameters(Context context,
|
||||
TypeParameterizedElement typeParameterHolder, Visitable visitable) {
|
||||
return findTypeParameters(context, typeParameterHolder, visitable, null);
|
||||
}
|
||||
|
||||
public static TypeParameterDeclaration[] findTypeParameters(Context context,
|
||||
TypeParameterizedElement typeParameterHolder, Visitable visitable,
|
||||
BiConsumer<TypeReference, TypeParameterDeclaration> referenceHandler) {
|
||||
return new TypeParameterFinder2(context, typeParameterHolder, referenceHandler).find(visitable);
|
||||
}
|
||||
|
||||
public static String[] findTypeParameterNames(Context context, TypeParameterizedElement typeParameterHolder,
|
||||
Visitable visitable) {
|
||||
return Arrays.asList(findTypeParameters(context, typeParameterHolder, visitable)).stream().map(t -> t.getName())
|
||||
.toArray(size -> new String[size]);
|
||||
}
|
||||
|
||||
static class TypeParameterFinder extends Scanner {
|
||||
private List<TypeParameterDeclaration> declarations = new ArrayList<TypeParameterDeclaration>();
|
||||
|
||||
public TypeParameterFinder(Scanner parent) {
|
||||
super(parent);
|
||||
}
|
||||
|
||||
public TypeParameterDeclaration[] find(Visitable visitable) {
|
||||
visitable.accept(this);
|
||||
return declarations.toArray(new TypeParameterDeclaration[0]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeReference(TypeReference typeReference) {
|
||||
Type t = lookupType(typeReference, null);
|
||||
if (t instanceof TypeParameterDeclaration) {
|
||||
if (!declarations.contains(t)) {
|
||||
declarations.add((TypeParameterDeclaration) t);
|
||||
}
|
||||
}
|
||||
super.visitTypeReference(typeReference);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static class TypeParameterFinder2 extends Scanner {
|
||||
private List<TypeParameterDeclaration> declarations = new ArrayList<TypeParameterDeclaration>();
|
||||
|
||||
private TypeParameterizedElement typeParameterHolder;
|
||||
|
||||
private BiConsumer<TypeReference, TypeParameterDeclaration> referenceHandler;
|
||||
|
||||
public TypeParameterFinder2(Context context, TypeParameterizedElement typeParameterHolder,
|
||||
BiConsumer<TypeReference, TypeParameterDeclaration> referenceHandler) {
|
||||
super(context);
|
||||
this.typeParameterHolder = typeParameterHolder;
|
||||
this.referenceHandler = referenceHandler;
|
||||
}
|
||||
|
||||
public TypeParameterDeclaration[] find(Visitable visitable) {
|
||||
if (typeParameterHolder.getTypeParameters() != null && typeParameterHolder.getTypeParameters().length > 0) {
|
||||
visitable.accept(this);
|
||||
}
|
||||
return declarations.toArray(new TypeParameterDeclaration[0]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeReference(TypeReference typeReference) {
|
||||
for (TypeParameterDeclaration t : typeParameterHolder.getTypeParameters()) {
|
||||
if (typeReference.getName().equals(t.getName())) {
|
||||
if (referenceHandler != null) {
|
||||
referenceHandler.accept(typeReference, t);
|
||||
}
|
||||
if (!declarations.contains(t)) {
|
||||
declarations.add(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
super.visitTypeReference(typeReference);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static Entry<String, Integer> splitIntSuffix(String string) {
|
||||
for (int i = 0; i < string.length(); i++) {
|
||||
try {
|
||||
int suffix = Integer.parseInt(string.substring(i));
|
||||
return new AbstractMap.SimpleEntry<String, Integer>(string.substring(0, i), suffix);
|
||||
} catch (NumberFormatException e) {
|
||||
// swallow
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static boolean elligibleToClass(ModuleDeclaration module) {
|
||||
if (Character.isUpperCase(module.getName().charAt(0)) && !StringUtils.isAllUpperCase(module.getName())) {
|
||||
for (Declaration declaration : module.getMembers()) {
|
||||
if (declaration instanceof TypeDeclaration || declaration instanceof ModuleDeclaration) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getLibPackageNameFromTsDefFile(File libFile) {
|
||||
File parent = libFile.getParentFile();
|
||||
String pack = parent.getName().toLowerCase().replaceAll("[.-]", "_");
|
||||
parent = parent.getParentFile();
|
||||
|
||||
String packageName;
|
||||
if (parent.getParentFile() != null
|
||||
&& !parent.getName().equals("test")
|
||||
&& !parent.getName().equals("typings")
|
||||
&& !parent.getName().equals("globals")) {
|
||||
pack = parent.getName().toLowerCase().replaceAll("[.-]", "_") + (pack == null ? "" : "." + pack);
|
||||
packageName = JSweetDefTranslatorConfig.LIBS_PACKAGE + "." + pack;
|
||||
} else {
|
||||
packageName = JSweetDefTranslatorConfig.LIBS_PACKAGE + "."
|
||||
+ libFile.getParentFile().getName().toLowerCase().replaceAll("[.-]", "_");
|
||||
}
|
||||
|
||||
logger.debug(libFile.getPath() + " ==> " + packageName);
|
||||
|
||||
return packageName;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,80 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import org.jsweet.JSweetDefTranslatorConfig;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.Declaration;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationContainer;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.Type;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
|
||||
public class ConstructorInterfacesMerger extends Scanner {
|
||||
|
||||
public ConstructorInterfacesMerger(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
protected void makeAllMembersStatic(TypeDeclaration typeDeclaration) {
|
||||
for (Declaration member : typeDeclaration.getMembers()) {
|
||||
member.addModifier("static");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeDeclaration(TypeDeclaration typeDeclaration) {
|
||||
// TODO
|
||||
// if a variable V exists in the same module with the same name then
|
||||
// -- if V is of the type of typeDeclaration then
|
||||
// ---- if there is no constructor in typeDeclaration (or supertypes)
|
||||
// then
|
||||
// ------ typeDeclaration moves all its functions and variables to
|
||||
// static ones
|
||||
// ---- end
|
||||
// -- else if V is of a type T (can be anonymous - object type) that
|
||||
// declares a constructor then
|
||||
// ---- 1. typeDeclaration is not abstract anymore
|
||||
// ---- 2. all the functions and variables (including constructors) of T
|
||||
// are injected into typeDeclaration
|
||||
// ---- 3. all the functions of typeDeclaration are not abstract anymore
|
||||
// ---- 4. V is deleted from the current modules' members
|
||||
// ---- 5. T is deleted only if T is not anonymous
|
||||
// -- end
|
||||
// end
|
||||
VariableDeclaration v = getParent(DeclarationContainer.class).findVariable(typeDeclaration.getName());
|
||||
if (v != null) {
|
||||
Type t = lookupType(v.getType(), null);
|
||||
if (t instanceof TypeDeclaration) {
|
||||
TypeDeclaration variableType = (TypeDeclaration) t;
|
||||
if (typeDeclaration.equals(variableType)) {
|
||||
if (typeDeclaration.findFirstConstructor() == null) {
|
||||
makeAllMembersStatic(typeDeclaration);
|
||||
typeDeclaration.removeStringAnnotation(JSweetDefTranslatorConfig.ANNOTATION_OBJECT_TYPE);
|
||||
v.setHidden(true);
|
||||
}
|
||||
} else {
|
||||
for (Declaration declaration : variableType.getMembers()) {
|
||||
if ((declaration instanceof FunctionDeclaration)
|
||||
&& ((FunctionDeclaration) declaration).isConstructor()) {
|
||||
continue;
|
||||
// declaration.setName("constructor");
|
||||
} else {
|
||||
declaration.addModifier("static");
|
||||
}
|
||||
}
|
||||
typeDeclaration.removeStringAnnotation(JSweetDefTranslatorConfig.ANNOTATION_INTERFACE);
|
||||
typeDeclaration.addMembers(variableType.getMembers());
|
||||
typeDeclaration.removeModifier("abstract");
|
||||
v.setHidden(true);
|
||||
if (!variableType.isAnonymous()) {
|
||||
context.mergedContructors.put(variableType, typeDeclaration);
|
||||
variableType.setHidden(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// super.visitTypeDeclaration(typeDeclaration);
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,34 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeReference;
|
||||
|
||||
/**
|
||||
* @author Renaud Pawlak
|
||||
*/
|
||||
public class ConstructorTypeReferenceReplacer extends Scanner {
|
||||
|
||||
public ConstructorTypeReferenceReplacer(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeReference(TypeReference typeReference) {
|
||||
if (context.mergedContructors.containsKey(typeReference.getDeclaration())) {
|
||||
// TODO: not very well typed but otherwise would require method
|
||||
// disambiguation... better typing could be quite easily achieved
|
||||
|
||||
// typeReference.setTypeArguments(new TypeReference[] { new
|
||||
// TypeReference(null,
|
||||
// context.getTypeName(context.mergedContructors.get(typeReference.getDeclaration())),
|
||||
// null) });
|
||||
typeReference.setTypeArguments(new TypeReference[] { new TypeReference(null, "any", null) });
|
||||
typeReference.setName(Class.class.getName());
|
||||
typeReference.setDeclaration(context.getTypeDeclaration(Class.class.getName()));
|
||||
} else {
|
||||
super.visitTypeReference(typeReference);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,38 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.ModuleDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeMacroDeclaration;
|
||||
|
||||
public class DeclarationBinder extends Scanner {
|
||||
|
||||
public DeclarationBinder(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
public DeclarationBinder(Scanner parentScanner) {
|
||||
super(parentScanner);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitModuleDeclaration(ModuleDeclaration moduleDeclaration) {
|
||||
context.registerModule(getCurrentContainerName(), moduleDeclaration);
|
||||
super.visitModuleDeclaration(moduleDeclaration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeDeclaration(TypeDeclaration typeDeclaration) {
|
||||
if (!typeDeclaration.isAnonymous()) {
|
||||
context.registerType(getCurrentContainerName(), typeDeclaration);
|
||||
}
|
||||
super.visitTypeDeclaration(typeDeclaration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeMacro(TypeMacroDeclaration typeMacroDeclaration) {
|
||||
context.registerType(getCurrentContainerName(), typeMacroDeclaration);
|
||||
super.visitTypeMacro(typeMacroDeclaration);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,400 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import java.io.File;
|
||||
import java.net.URL;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.jsoup.Jsoup;
|
||||
import org.jsoup.nodes.Document;
|
||||
import org.jsoup.nodes.Node;
|
||||
import org.jsoup.nodes.TextNode;
|
||||
import org.jsoup.select.NodeTraversor;
|
||||
import org.jsoup.select.NodeVisitor;
|
||||
import org.jsweet.JSweetDefTranslatorConfig;
|
||||
import org.jsweet.input.typescriptdef.ast.CompilationUnit;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.Declaration;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
|
||||
/**
|
||||
* This scanner tries to fill the documentation from external sources, when it
|
||||
* does not pre-exist in the definition file.
|
||||
*
|
||||
* @author Renaud Pawlak
|
||||
*/
|
||||
public class DocFiller extends Scanner {
|
||||
|
||||
private final static Logger logger = Logger.getLogger(DocFiller.class);
|
||||
|
||||
int domDocsCount = 0;
|
||||
int domDescriptionDocsCount = 0;
|
||||
int langDocsCount = 0;
|
||||
int langDescriptionDocsCount = 0;
|
||||
String currentModule;
|
||||
|
||||
public DocFiller(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitCompilationUnit(CompilationUnit compilationUnit) {
|
||||
if (context.isDependency(compilationUnit)) {
|
||||
return;
|
||||
}
|
||||
|
||||
super.visitCompilationUnit(compilationUnit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionDeclaration(FunctionDeclaration functionDeclaration) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitVariableDeclaration(VariableDeclaration variableDeclaration) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeDeclaration(TypeDeclaration typeDeclaration) {
|
||||
if (typeDeclaration.getDocumentation() == null) {
|
||||
String moduleName = getCurrentModuleName();
|
||||
if (JSweetDefTranslatorConfig.LANG_PACKAGE.equals(moduleName)
|
||||
|| JSweetDefTranslatorConfig.DOM_PACKAGE.equals(moduleName)) {
|
||||
this.currentModule = moduleName;
|
||||
|
||||
String content = getTypeContent(context.cacheDir, "mdn", moduleName, typeDeclaration.getName());
|
||||
if (content != null) {
|
||||
try {
|
||||
Document doc = Jsoup.parse(content, "UTF-8");
|
||||
NodeTraversor traversor;
|
||||
traversor = new NodeTraversor(new MdnTableFormatGrabber(this, typeDeclaration));
|
||||
traversor.traverse(doc.body());
|
||||
traversor = new NodeTraversor(new MdnDefinitionListFormatGrabber(this, typeDeclaration));
|
||||
traversor.traverse(doc.body());
|
||||
traversor = new NodeTraversor(new MdnMainDescriptionGrabber(this, typeDeclaration));
|
||||
traversor.traverse(doc.body());
|
||||
} catch (Throwable t) {
|
||||
context.reportError("cannot fill documentation for " + context.getTypeName(typeDeclaration), t);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void countDoc(boolean description) {
|
||||
if (JSweetDefTranslatorConfig.LANG_PACKAGE.equals(currentModule)) {
|
||||
if (description) {
|
||||
langDescriptionDocsCount++;
|
||||
} else {
|
||||
langDocsCount++;
|
||||
}
|
||||
} else {
|
||||
if (description) {
|
||||
domDescriptionDocsCount++;
|
||||
} else {
|
||||
domDocsCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static String getTypeContent(File cacheDir, String provider, String moduleName, String typeName) {
|
||||
String content = null;
|
||||
try {
|
||||
File cachedFile = cacheDir == null ? null : new File(cacheDir, provider + File.separator + typeName);
|
||||
if (cachedFile != null && cachedFile.exists()) {
|
||||
content = FileUtils.readFileToString(cachedFile);
|
||||
} else {
|
||||
try {
|
||||
if (JSweetDefTranslatorConfig.DOM_PACKAGE.equals(moduleName)) {
|
||||
content = IOUtils
|
||||
.toString(new URL("https://developer.mozilla.org/en-US/docs/Web/API/" + typeName));
|
||||
}
|
||||
if (JSweetDefTranslatorConfig.LANG_PACKAGE.equals(moduleName)) {
|
||||
content = IOUtils.toString(
|
||||
new URL("https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/"
|
||||
+ typeName));
|
||||
}
|
||||
logger.info("content downloaded for " + moduleName + "." + typeName);
|
||||
} catch (Exception e) {
|
||||
content = "";
|
||||
}
|
||||
if (cachedFile != null) {
|
||||
logger.info("writing cache to " + cachedFile);
|
||||
FileUtils.write(cachedFile, content, false);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return content;
|
||||
}
|
||||
|
||||
public static String removeTags(String html) {
|
||||
return removeTags(html, new String[] { "a", "body" });
|
||||
}
|
||||
|
||||
public static String removeTags(String html, String[] tagsToBeRemoved) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
NodeTraversor traversor = new NodeTraversor(new TagRemover(sb, tagsToBeRemoved));
|
||||
traversor.traverse(Jsoup.parse(html).body());
|
||||
return sb.toString().replace("<p></p>", "");
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println(removeTags("Ceci est un test <a href=\"tutu\">slurp</a> hop <code>arlgs</code>.",
|
||||
new String[] { "a", "body" }));
|
||||
String content = getTypeContent(null, "mdn", JSweetDefTranslatorConfig.LANG_PACKAGE, "Array");
|
||||
Document doc = Jsoup.parse(content, "UTF-8");
|
||||
System.out.println(doc.toString());
|
||||
}
|
||||
|
||||
static <T> void addToMap(Map<String, List<T>> map, String key, T value) {
|
||||
List<T> l = map.get(key);
|
||||
if (l == null) {
|
||||
l = new ArrayList<>();
|
||||
map.put(key, l);
|
||||
}
|
||||
l.add(value);
|
||||
}
|
||||
|
||||
static List<Node> getSiblingTags(Node node) {
|
||||
List<Node> siblings = new ArrayList<>();
|
||||
for (Node n : node.siblingNodes()) {
|
||||
if (!(n instanceof TextNode)) {
|
||||
siblings.add(n);
|
||||
}
|
||||
}
|
||||
return siblings;
|
||||
}
|
||||
|
||||
static boolean isLastSiblingTag(Node node) {
|
||||
List<Node> siblings = new ArrayList<>();
|
||||
for (Node n : node.parent().childNodes()) {
|
||||
if (!(n instanceof TextNode)) {
|
||||
siblings.add(n);
|
||||
}
|
||||
}
|
||||
return (node == siblings.get(siblings.size() - 1));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onScanEnded() {
|
||||
System.out.println("Package lang: " + langDescriptionDocsCount + " type descriptions and " + langDocsCount
|
||||
+ " member docs added.");
|
||||
System.out.println("Package dom: " + domDescriptionDocsCount + " type descriptions and " + domDocsCount
|
||||
+ " member docs added.");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class MdnTableFormatGrabber implements NodeVisitor {
|
||||
|
||||
private Map<String, List<Declaration>> members = new HashMap<>();
|
||||
private DocFiller docFiller;
|
||||
|
||||
public MdnTableFormatGrabber(DocFiller docFiller, TypeDeclaration typeDeclaration) {
|
||||
this.docFiller = docFiller;
|
||||
for (Declaration member : typeDeclaration.getMembers()) {
|
||||
if (member.getDocumentation() != null
|
||||
|| member.hasStringAnnotation(org.jsweet.JSweetDefTranslatorConfig.ANNOTATION_STRING_TYPE)) {
|
||||
continue;
|
||||
}
|
||||
DocFiller.addToMap(members, member.getName(), member);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void head(Node node, int depth) {
|
||||
if (node instanceof TextNode) {
|
||||
String text = ((TextNode) node).text().trim();
|
||||
if (members.containsKey(text)) {
|
||||
Node parent = node.parent();
|
||||
if (parent != null && !"td".equals(parent.nodeName())) {
|
||||
parent = parent.parent();
|
||||
}
|
||||
if (parent != null && !"td".equals(parent.nodeName())) {
|
||||
parent = parent.parent();
|
||||
}
|
||||
if (parent != null && "td".equals(parent.nodeName())) {
|
||||
List<Node> siblings = parent.parent().childNodes();
|
||||
List<Node> tdSiblings = new ArrayList<Node>();
|
||||
siblings.forEach(n -> {
|
||||
if ("td".equals(n.nodeName()))
|
||||
tdSiblings.add(n);
|
||||
});
|
||||
|
||||
if (tdSiblings.get(0) == parent && tdSiblings.size() == 3) {
|
||||
Node td = tdSiblings.get(2);
|
||||
String s = td.toString();
|
||||
String doc = "/** " + DocFiller.removeTags(s.substring(4, s.length() - 5)) + " */";
|
||||
for (Declaration d : members.get(text)) {
|
||||
d.setDocumentation(doc);
|
||||
}
|
||||
docFiller.countDoc(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tail(Node node, int depth) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class MdnDefinitionListFormatGrabber implements NodeVisitor {
|
||||
|
||||
private Map<String, List<Declaration>> members = new HashMap<>();
|
||||
private DocFiller docFiller;
|
||||
|
||||
public MdnDefinitionListFormatGrabber(DocFiller docFiller, TypeDeclaration typeDeclaration) {
|
||||
this.docFiller = docFiller;
|
||||
for (Declaration member : typeDeclaration.getMembers()) {
|
||||
if (member.getDocumentation() != null
|
||||
|| member.hasStringAnnotation(JSweetDefTranslatorConfig.ANNOTATION_STRING_TYPE)) {
|
||||
continue;
|
||||
}
|
||||
if (member instanceof FunctionDeclaration) {
|
||||
DocFiller.addToMap(members, typeDeclaration.getName() + "." + member.getName() + "()", member);
|
||||
} else {
|
||||
DocFiller.addToMap(members, typeDeclaration.getName() + "." + member.getName(), member);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void head(Node node, int depth) {
|
||||
if (node instanceof TextNode) {
|
||||
String text = ((TextNode) node).text().trim();
|
||||
if (members.containsKey(text)) {
|
||||
Node parent = node.parent();
|
||||
if (parent != null && !"dt".equals(parent.nodeName())) {
|
||||
parent = parent.parent();
|
||||
}
|
||||
if (parent != null && !"dt".equals(parent.nodeName())) {
|
||||
parent = parent.parent();
|
||||
}
|
||||
if (parent != null && "dt".equals(parent.nodeName())) {
|
||||
List<Node> siblings = parent.parent().childNodes();
|
||||
List<Node> dlSiblings = new ArrayList<Node>();
|
||||
siblings.forEach(n -> {
|
||||
if ("dt".equals(n.nodeName()) || "dd".equals(n.nodeName()))
|
||||
dlSiblings.add(n);
|
||||
});
|
||||
for (int i = 0; i < dlSiblings.size(); i++) {
|
||||
if (dlSiblings.get(i) == parent) {
|
||||
if (i < dlSiblings.size() - 1 && "dd".equals(dlSiblings.get(i + 1).nodeName())) {
|
||||
String s = dlSiblings.get(i + 1).toString();
|
||||
String doc = "/** " + DocFiller.removeTags(s.substring(4, s.length() - 5)) + " */";
|
||||
for (Declaration d : members.get(text)) {
|
||||
d.setDocumentation(doc);
|
||||
}
|
||||
docFiller.countDoc(false);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tail(Node node, int depth) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class MdnMainDescriptionGrabber implements NodeVisitor {
|
||||
|
||||
private StringBuffer description = new StringBuffer();
|
||||
private boolean found = false;
|
||||
private TypeDeclaration typeDeclaration;
|
||||
private DocFiller docFiller;
|
||||
|
||||
public MdnMainDescriptionGrabber(DocFiller docFiller, TypeDeclaration typeDeclaration) {
|
||||
this.docFiller = docFiller;
|
||||
this.typeDeclaration = typeDeclaration;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void head(Node node, int depth) {
|
||||
if (!found) {
|
||||
if (node.attr("id") != null && node.attr("id").equalsIgnoreCase("Quick_Links")) {
|
||||
found = true;
|
||||
while (DocFiller.isLastSiblingTag(node)) {
|
||||
node = node.parent();
|
||||
}
|
||||
|
||||
Node n = node;
|
||||
|
||||
while ((n = n.nextSibling()) != null && !("h2".equals(n.nodeName()) || "h3".equals(n.nodeName()))) {
|
||||
description.append(n.outerHtml());
|
||||
}
|
||||
|
||||
String s = Jsoup.parse(description.toString()).text();
|
||||
if ("".equals(s.trim())) {
|
||||
if (n == null) {
|
||||
n = node;
|
||||
}
|
||||
while ((n = n.nextSibling()) != null && !("h2".equals(n.nodeName()) || "h3".equals(n.nodeName()))) {
|
||||
description.append(n.outerHtml());
|
||||
}
|
||||
}
|
||||
|
||||
typeDeclaration.setDocumentation("/** " + DocFiller.removeTags(description.toString()) + " */");
|
||||
docFiller.countDoc(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tail(Node node, int depth) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class TagRemover implements NodeVisitor {
|
||||
|
||||
private StringBuilder out;
|
||||
private Set<String> tagsToBeRemoved;
|
||||
|
||||
public TagRemover(StringBuilder out, String[] tagsToBeRemoved) {
|
||||
this.out = out;
|
||||
this.tagsToBeRemoved = new HashSet<String>(Arrays.asList(tagsToBeRemoved));
|
||||
}
|
||||
|
||||
public void head(Node node, int depth) {
|
||||
String name = node.nodeName();
|
||||
if (!tagsToBeRemoved.contains(name)) {
|
||||
if (node instanceof TextNode) {
|
||||
TextNode tn = (TextNode) node;
|
||||
out.append(tn.toString());
|
||||
} else {
|
||||
out.append("<" + name + ">");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void tail(Node node, int depth) {
|
||||
String name = node.nodeName();
|
||||
if (!tagsToBeRemoved.contains(name)) {
|
||||
if (!(node instanceof TextNode)) {
|
||||
out.append("</" + name + ">");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,645 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.jsweet.JSweetDefTranslatorConfig;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.Declaration;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationHelper;
|
||||
import org.jsweet.input.typescriptdef.ast.FullFunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.ParameterDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeParameterDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeReference;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
import org.jsweet.input.typescriptdef.util.NameUtils;
|
||||
import org.jsweet.input.typescriptdef.util.Util;
|
||||
|
||||
/**
|
||||
* This scanner hides duplicate method (real duplicates but also the ones with
|
||||
* the same type erasure).
|
||||
*
|
||||
* @author Renaud Pawlak
|
||||
*/
|
||||
public class DuplicateMethodsCleaner extends Scanner {
|
||||
|
||||
private int hiddenMethodCount = 0;
|
||||
|
||||
private boolean dump = false;
|
||||
|
||||
private final static String NO_OVERRIDE = "";
|
||||
|
||||
public enum Strategy {
|
||||
USER_FRIENDLY, FULL;
|
||||
}
|
||||
|
||||
private final static int MAX_NAME_LENGTH = 40;
|
||||
|
||||
public DuplicateMethodsCleaner(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
private void hideDuplicatesInDeclarations(TypeDeclaration originalDeclaringType,
|
||||
FunctionDeclaration functionDeclaration, TypeDeclaration declaringType) {
|
||||
Declaration[] declarations = declaringType.getMembers();
|
||||
if (declarations == null) {
|
||||
return;
|
||||
}
|
||||
for (Declaration d : declarations) {
|
||||
if (d instanceof FunctionDeclaration) {
|
||||
FunctionDeclaration f = (FunctionDeclaration) d;
|
||||
if (f != functionDeclaration && !f.isHidden()
|
||||
&& (f.getName().equals(functionDeclaration.getName())
|
||||
|| (f.isConstructor() && functionDeclaration.isConstructor()))
|
||||
&& f.getParameters().length == functionDeclaration.getParameters().length) {
|
||||
boolean duplicate = true;
|
||||
boolean checkReturnType = true;
|
||||
// static methods can never be overloaded
|
||||
// if (!(!functionDeclaration.hasModifier("static") &&
|
||||
// f.hasModifier("static"))) {
|
||||
|
||||
for (int i = 0; i < f.getParameters().length; i++) {
|
||||
ParameterDeclaration d1 = functionDeclaration.getParameters()[i];
|
||||
ParameterDeclaration d2 = f.getParameters()[i];
|
||||
String erasedName1 = context.getTypeNameErased(d1.getType());
|
||||
String erasedName2 = context.getTypeNameErased(d2.getType());
|
||||
|
||||
try {
|
||||
if (!erasedName1.equals(erasedName2)) {
|
||||
duplicate = false;
|
||||
break;
|
||||
} else {
|
||||
checkReturnType = context.getFullTypeNameNoErasure(d1.getType())
|
||||
.equals(context.getFullTypeNameNoErasure(d2.getType()));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
boolean incompatibleReturnType = false;
|
||||
if (duplicate && checkReturnType && originalDeclaringType != declaringType
|
||||
&& !f.hasModifier("static")) {
|
||||
// String name1 =
|
||||
// functionDeclaration.getType().getName();
|
||||
// String name2 = f.getType().getName();
|
||||
// if (name1 != null && !name1.equals(name2)) {
|
||||
// duplicate = false;
|
||||
// }
|
||||
try {
|
||||
if (!Object.class.getName().equals(f.getType().getName())
|
||||
&& !"Object".equals(f.getType().getName())
|
||||
&& !functionDeclaration.getType().equals(f.getType())
|
||||
&& !functionDeclaration.getType().isSubtypeOf(f.getType())) {
|
||||
// duplicate = false;
|
||||
incompatibleReturnType = true;
|
||||
logger.debug("incompatible return types: " + functionDeclaration + " - "
|
||||
+ functionDeclaration.getType() + " / " + f);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
context.reportError("unattributed type ref for " + f + " at " + f.getLocation()
|
||||
+ ", declaring type: " + declaringType + " at " + declaringType.getLocation());
|
||||
}
|
||||
}
|
||||
if (duplicate) {
|
||||
boolean isErased = false;
|
||||
for (int i = 0; i < functionDeclaration.getParameters().length; i++) {
|
||||
ParameterDeclaration d1 = functionDeclaration.getParameters()[i];
|
||||
ParameterDeclaration d2 = f.getParameters()[i];
|
||||
if (!context.getFullTypeNameNoErasure(d1.getType())
|
||||
.equals(context.getFullTypeNameNoErasure(d2.getType()))) {
|
||||
isErased = true;
|
||||
}
|
||||
}
|
||||
boolean staticDuplicate = (f.hasModifier("static") != functionDeclaration
|
||||
.hasModifier("static"));
|
||||
if (!incompatibleReturnType && originalDeclaringType != declaringType && !staticDuplicate) {
|
||||
context.addOverride(
|
||||
new FullFunctionDeclaration(null, originalDeclaringType, functionDeclaration),
|
||||
new FullFunctionDeclaration(null, declaringType, f));
|
||||
} else if (isErased && !staticDuplicate) {
|
||||
context.addDuplicate(
|
||||
new FullFunctionDeclaration(null, originalDeclaringType, functionDeclaration),
|
||||
new FullFunctionDeclaration(null, declaringType, f));
|
||||
} else {
|
||||
if (context.verbose) {
|
||||
logger.debug("WARNING: removing duplicate " + f
|
||||
+ (f.getToken() == null ? "" : " at " + f.getToken().getLocation()) + ", type "
|
||||
+ declaringType.getName());
|
||||
}
|
||||
hiddenMethodCount++;
|
||||
functionDeclaration.setHidden(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionDeclaration(FunctionDeclaration functionDeclaration) {
|
||||
TypeDeclaration declaringType = getParent(TypeDeclaration.class);
|
||||
TypeDeclaration orgType = declaringType;
|
||||
while (declaringType != null) {
|
||||
hideDuplicatesInDeclarations(orgType, functionDeclaration, declaringType);
|
||||
if (!functionDeclaration.isConstructor()) {
|
||||
if (declaringType.getSuperTypes() != null && declaringType.getSuperTypes().length > 0) {
|
||||
declaringType = (TypeDeclaration) lookupType(declaringType.getSuperTypes()[0], null);
|
||||
} else if ("class".equals(declaringType.getKind())
|
||||
&& !JSweetDefTranslatorConfig.getObjectClassName().equals(context.getTypeName(declaringType))) {
|
||||
declaringType = context.getTypeDeclaration(JSweetDefTranslatorConfig.getObjectClassName());
|
||||
} else {
|
||||
declaringType = null;
|
||||
}
|
||||
} else {
|
||||
declaringType = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitVariableDeclaration(VariableDeclaration variableDeclaration) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onScanEnded() {
|
||||
handleDuplicates();
|
||||
if (hiddenMethodCount > 0) {
|
||||
logger.debug(hiddenMethodCount + " method(s) hidden.");
|
||||
}
|
||||
}
|
||||
|
||||
private void dumpDuplicates(List<Set<FullFunctionDeclaration>> duplicatesList) {
|
||||
if (dump) {
|
||||
for (Set<FullFunctionDeclaration> s : duplicatesList) {
|
||||
TypeDeclaration type = s.iterator().next().declaringType;
|
||||
System.out.println(" -- " + context.getTypeName(type));
|
||||
for (FullFunctionDeclaration d : s) {
|
||||
System.out.println(" * " + d);
|
||||
if (context.overrides.get(d) != null) {
|
||||
System.out.println(" -> overrides: " + context.overrides.get(d));
|
||||
}
|
||||
if (context.overridens.get(d) != null) {
|
||||
System.out.println(" -> overridens: " + context.overridens.get(d));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void handleDuplicates() {
|
||||
dumpDuplicates(context.duplicates);
|
||||
List<Set<FullFunctionDeclaration>> newDuplicatesList = new ArrayList<Set<FullFunctionDeclaration>>();
|
||||
for (Set<FullFunctionDeclaration> duplicates : context.duplicates) {
|
||||
Set<FullFunctionDeclaration> newDuplicates = new HashSet<FullFunctionDeclaration>(duplicates);
|
||||
for (FullFunctionDeclaration f : duplicates) {
|
||||
if (context.overrides.containsKey(f)) {
|
||||
for (Set<FullFunctionDeclaration> duplicates2 : context.duplicates) {
|
||||
if (duplicates2.contains(context.overrides.get(f))) {
|
||||
newDuplicates.addAll(duplicates2);
|
||||
newDuplicatesList.remove(duplicates2);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
newDuplicatesList.add(newDuplicates);
|
||||
}
|
||||
dumpDuplicates(newDuplicatesList);
|
||||
|
||||
for (Set<FullFunctionDeclaration> duplicates : newDuplicatesList) {
|
||||
Map<FullFunctionDeclaration, List<String>> nameMatrix = null;
|
||||
// System.out.println("disambiguation for " + duplicates);
|
||||
nameMatrix = calculateNames(duplicates, Strategy.USER_FRIENDLY);
|
||||
dumpNameMatrix(nameMatrix);
|
||||
if (hasDuplicate(nameMatrix)) {
|
||||
// System.out.println("found duplicate!");
|
||||
nameMatrix = calculateNames(duplicates, Strategy.FULL);
|
||||
dumpNameMatrix(nameMatrix);
|
||||
}
|
||||
applyDisambiguation(duplicates, nameMatrix);
|
||||
}
|
||||
}
|
||||
|
||||
private void dumpNameMatrix(Map<FullFunctionDeclaration, List<String>> nameMatrix) {
|
||||
if (dump) {
|
||||
System.out.println("Dumping name matrix:");
|
||||
for (Entry<FullFunctionDeclaration, List<String>> e : nameMatrix.entrySet()) {
|
||||
System.out.println("# " + e.getKey() + " ---> " + e.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean hasDuplicate(Map<FullFunctionDeclaration, List<String>> nameMatrix) {
|
||||
Map<FullFunctionDeclaration, List<String>> m = new HashMap<FullFunctionDeclaration, List<String>>(nameMatrix);
|
||||
for (FullFunctionDeclaration f : nameMatrix.keySet()) {
|
||||
if (context.overridens.get(f) != null && m.containsKey(context.overridens.get(f))) {
|
||||
m.remove(f);
|
||||
}
|
||||
}
|
||||
// System.out.println("TESTING DUPLICATES ON:");
|
||||
// dumpNameMatrix(m);
|
||||
List<String> signatures = new ArrayList<String>();
|
||||
for (List<String> l : m.values()) {
|
||||
String s = l.toString();
|
||||
if (signatures.contains(s)) {
|
||||
return true;
|
||||
}
|
||||
signatures.add(s);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private Map<FullFunctionDeclaration, List<String>> calculateNames(Set<FullFunctionDeclaration> duplicates,
|
||||
Strategy strategy) {
|
||||
Map<FullFunctionDeclaration, List<String>> nameMatrix = new HashMap<FullFunctionDeclaration, List<String>>();
|
||||
List<FullFunctionDeclaration> l = new ArrayList<FullFunctionDeclaration>(duplicates);
|
||||
TypeDeclaration highestTypeDeclaration = getHighestSuperType(duplicates);
|
||||
|
||||
for (int paramIndex = 0; paramIndex < l.get(0).function.getParameters().length; paramIndex++) {
|
||||
final int i = paramIndex;
|
||||
l.sort(new Comparator<FullFunctionDeclaration>() {
|
||||
@Override
|
||||
public int compare(FullFunctionDeclaration f1, FullFunctionDeclaration f2) {
|
||||
int diff = context.getShortTypeNameNoErasure(f1.function.getParameters()[i].getType()).length()
|
||||
- context.getShortTypeNameNoErasure(f2.function.getParameters()[i].getType()).length();
|
||||
if (diff == 0) {
|
||||
return context.getShortTypeNameNoErasure(f1.function.getParameters()[i].getType())
|
||||
.compareTo(context.getShortTypeNameNoErasure(f2.function.getParameters()[i].getType()));
|
||||
} else {
|
||||
return diff;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
List<String> names;
|
||||
boolean functionalDisambiguation = isFunctionalTypeReference(
|
||||
l.get(0).function.getParameters()[i].getType());
|
||||
if (functionalDisambiguation) {
|
||||
if (!isFunctionalTypeReference(l.get(0).function.getParameters()[i].getType())
|
||||
|| context.getShortTypeNameNoErasure(l.get(0).function.getParameters()[i].getType())
|
||||
.equals(context.getShortTypeNameNoErasure(
|
||||
l.get(l.size() - 1).function.getParameters()[i].getType()))) {
|
||||
// no erasure conflict comes form parameter i (by convention
|
||||
// we set an empty name)
|
||||
names = new ArrayList<String>(Collections.nCopies(l.size(), NO_OVERRIDE));
|
||||
} else {
|
||||
names = calculateNames(highestTypeDeclaration, strategy, functionalDisambiguation, l,
|
||||
l.get(0).function, i);
|
||||
}
|
||||
} else {
|
||||
if (context.getShortTypeNameNoErasure(l.get(0).function.getParameters()[i].getType()).equals(
|
||||
context.getShortTypeNameNoErasure(l.get(l.size() - 1).function.getParameters()[i].getType()))) {
|
||||
// no erasure conflict comes form parameter i (by convention
|
||||
// we set an empty name)
|
||||
names = new ArrayList<String>(Collections.nCopies(l.size(), NO_OVERRIDE));
|
||||
} else {
|
||||
names = calculateNames(highestTypeDeclaration, strategy, functionalDisambiguation, l,
|
||||
l.get(0).function, i);
|
||||
}
|
||||
}
|
||||
for (int j = 0; j < l.size(); j++) {
|
||||
List<String> paramNames = nameMatrix.get(l.get(j));
|
||||
if (paramNames == null) {
|
||||
paramNames = new ArrayList<String>();
|
||||
nameMatrix.put(l.get(j), paramNames);
|
||||
}
|
||||
paramNames.add(names.get(j));
|
||||
}
|
||||
}
|
||||
return nameMatrix;
|
||||
}
|
||||
|
||||
private void applyDisambiguation(Set<FullFunctionDeclaration> duplicates,
|
||||
Map<FullFunctionDeclaration, List<String>> nameMatrix) {
|
||||
TypeDeclaration highestTypeDeclaration = getHighestSuperType(duplicates);
|
||||
List<FullFunctionDeclaration> l = new ArrayList<FullFunctionDeclaration>(duplicates);
|
||||
for (int paramIndex = 0; paramIndex < l.get(0).function.getParameters().length; paramIndex++) {
|
||||
final int i = paramIndex;
|
||||
for (FullFunctionDeclaration f : l) {
|
||||
String newTypeName = nameMatrix.get(f).get(i);
|
||||
if (newTypeName == NO_OVERRIDE) {
|
||||
continue;
|
||||
}
|
||||
|
||||
ParameterDeclaration parameter = f.function.getParameters()[i];
|
||||
TypeDeclaration newType = null;
|
||||
boolean alreadyCreated = false;
|
||||
|
||||
if (newType == null && (newType = highestTypeDeclaration.findType(newTypeName)) != null) {
|
||||
alreadyCreated = true;
|
||||
}
|
||||
|
||||
boolean functionalDisambiguation = isFunctionalTypeReference(
|
||||
l.get(0).function.getParameters()[i].getType());
|
||||
if (functionalDisambiguation) {
|
||||
if (f.function.isConstructor()) {
|
||||
if (!alreadyCreated) {
|
||||
boolean hasResult = ((TypeDeclaration) parameter.getType().getDeclaration()).getName()
|
||||
.contains("Function");
|
||||
newType = DeclarationHelper.createFunctionalType(newTypeName,
|
||||
parameter.getType().getTypeArguments().length - (hasResult ? 1 : 0), hasResult,
|
||||
true);
|
||||
newType.addStringAnnotation(JSweetDefTranslatorConfig.ANNOTATION_ERASED);
|
||||
highestTypeDeclaration.addMember(newType);
|
||||
context.registerType(context.getTypeName(highestTypeDeclaration) + "." + newType.getName(),
|
||||
newType);
|
||||
}
|
||||
parameter.setType(new TypeReference(null, newType,
|
||||
DeclarationHelper.copyReferences(parameter.getType().getTypeArguments())));
|
||||
} else {
|
||||
if (!f.function.hasStringAnnotation(JSweetDefTranslatorConfig.ANNOTATION_NAME)) {
|
||||
f.function.addStringAnnotation(
|
||||
JSweetDefTranslatorConfig.ANNOTATION_NAME + "(\"" + f.function.getName() + "\")");
|
||||
f.function.setName(f.function.getName() + newTypeName);
|
||||
} else {
|
||||
if (!StringUtils.isBlank(newTypeName)) {
|
||||
f.function.setName(StringUtils.uncapitalize(f.function.getName()) + newTypeName);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
TypeParameterDeclaration[] typeParameters = Util.findTypeParameters(this, parameter);
|
||||
if (typeParameters.length == 0) {
|
||||
typeParameters = null;
|
||||
}
|
||||
if (!alreadyCreated) {
|
||||
FunctionDeclaration newConstructor = new FunctionDeclaration(null, "constructor", null,
|
||||
new ParameterDeclaration[] { parameter.copy() }, null);
|
||||
newType = new TypeDeclaration(null, "class", newTypeName,
|
||||
DeclarationHelper.copy(typeParameters), null, new Declaration[] { newConstructor });
|
||||
newType.setDocumentation(
|
||||
"/** This class was automatically generated for disambiguating erased method signatures. */");
|
||||
if (newType.getTypeParameters() != null) {
|
||||
for (TypeParameterDeclaration t : newType.getTypeParameters()) {
|
||||
t.setUpperBound(null);
|
||||
}
|
||||
}
|
||||
newType.addModifier("static");
|
||||
newType.addStringAnnotation(JSweetDefTranslatorConfig.ANNOTATION_ERASED);
|
||||
highestTypeDeclaration.addMember(newType);
|
||||
context.registerType(context.getTypeName(highestTypeDeclaration) + "." + newType.getName(),
|
||||
newType);
|
||||
}
|
||||
parameter.setType(new TypeReference(null, newType, DeclarationHelper.toReferences(typeParameters)));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String resolveNameClash(boolean functionalDisambiguation, TypeDeclaration highestTypeDeclaration,
|
||||
TypeReference parameterType, String newTypeName) {
|
||||
TypeDeclaration resolved = highestTypeDeclaration.findType(newTypeName);
|
||||
if (resolved == null) {
|
||||
return newTypeName;
|
||||
} else {
|
||||
if (resolved.getTypeParameters() == null && parameterType.getTypeArguments() == null) {
|
||||
return newTypeName;
|
||||
}
|
||||
if (!functionalDisambiguation) {
|
||||
if (resolved.getTypeParameters() != null && parameterType.getTypeArguments() != null
|
||||
&& resolved.getTypeParameters().length == parameterType.getTypeArguments().length) {
|
||||
return newTypeName;
|
||||
}
|
||||
FunctionDeclaration constructor = resolved.findFirstConstructor();
|
||||
if (constructor != null && constructor.getParameters() != null
|
||||
&& constructor.getParameters().length == 1
|
||||
&& constructor.getParameters()[0].getType().equals(parameterType)) {
|
||||
return newTypeName;
|
||||
}
|
||||
} else {
|
||||
FunctionDeclaration apply = resolved
|
||||
.findFirstFunction(JSweetDefTranslatorConfig.ANONYMOUS_FUNCTION_NAME);
|
||||
if (apply != null && resolved.getTypeParameters() != null && parameterType.getTypeArguments() != null
|
||||
&& resolved.getTypeParameters().length == parameterType.getTypeArguments().length) {
|
||||
if (parameterType.getName().endsWith("Consumer") && "void".equals(apply.getType().getName())) {
|
||||
return newTypeName;
|
||||
}
|
||||
if (parameterType.getName().endsWith("Provider") && apply.getParameters().length == 0) {
|
||||
return newTypeName;
|
||||
}
|
||||
if (parameterType.getName().endsWith("Function") && apply.getParameters().length > 0
|
||||
&& !"void".equals(apply.getType().getName())) {
|
||||
return newTypeName;
|
||||
}
|
||||
}
|
||||
}
|
||||
Map.Entry<String, Integer> intSuffix = Util.splitIntSuffix(newTypeName);
|
||||
if (intSuffix == null) {
|
||||
return resolveNameClash(functionalDisambiguation, highestTypeDeclaration, parameterType,
|
||||
newTypeName + 2);
|
||||
} else {
|
||||
return resolveNameClash(functionalDisambiguation, highestTypeDeclaration, parameterType,
|
||||
intSuffix.getKey() + (intSuffix.getValue() + 1));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> calculateNames(TypeDeclaration highestTypeDeclaration, Strategy strategy,
|
||||
boolean functionalDisambiguation, List<FullFunctionDeclaration> l, FunctionDeclaration reference,
|
||||
int paramIndex) {
|
||||
List<String> names = new ArrayList<String>();
|
||||
switch (strategy) {
|
||||
case USER_FRIENDLY:
|
||||
if (functionalDisambiguation) {
|
||||
// apply a diff strategy (more user friendly in some cases)
|
||||
for (FullFunctionDeclaration f : l) {
|
||||
String newInterfaceName = StringUtils.capitalize(reference.getParameters()[paramIndex].getName())
|
||||
+ NameUtils.getDiff(
|
||||
context.getShortTypeNameNoErasure(reference.getParameters()[paramIndex].getType()),
|
||||
context.getShortTypeNameNoErasure(
|
||||
f.function.getParameters()[paramIndex].getType()));
|
||||
if (newInterfaceName.length() > MAX_NAME_LENGTH) {
|
||||
newInterfaceName = StringUtils.capitalize(reference.getParameters()[paramIndex].getName())
|
||||
+ names.size();
|
||||
}
|
||||
TypeReference parameterType = reference.getParameters()[paramIndex].getType();
|
||||
if (parameterType.getName().contains("Consumer")) {
|
||||
switch (parameterType.getTypeArguments().length) {
|
||||
case 1:
|
||||
newInterfaceName += "Consumer";
|
||||
break;
|
||||
case 2:
|
||||
newInterfaceName += "BiConsumer";
|
||||
break;
|
||||
case 3:
|
||||
newInterfaceName += "TriConsumer";
|
||||
break;
|
||||
default:
|
||||
newInterfaceName += "Consumer";
|
||||
newInterfaceName += parameterType.getTypeArguments().length;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (parameterType.getName().contains("Function")) {
|
||||
switch (parameterType.getTypeArguments().length) {
|
||||
case 2:
|
||||
newInterfaceName += "Function";
|
||||
break;
|
||||
case 3:
|
||||
newInterfaceName += "BiFunction";
|
||||
break;
|
||||
case 4:
|
||||
newInterfaceName += "TriFunction";
|
||||
break;
|
||||
default:
|
||||
newInterfaceName += "Function";
|
||||
newInterfaceName += parameterType.getTypeArguments().length - 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (parameterType.getName().contains("Supplier")) {
|
||||
newInterfaceName += "Supplier";
|
||||
}
|
||||
// this naming convention seems to avoid all name clashes
|
||||
// newInterfaceName =
|
||||
// resolveNameClash(functionalDisambiguation,
|
||||
// highestTypeDeclaration,
|
||||
// f.function.getParameters()[paramIndex].getType(),
|
||||
// newInterfaceName);
|
||||
names.add(newInterfaceName);
|
||||
}
|
||||
} else {
|
||||
for (FullFunctionDeclaration f : l) {
|
||||
// TODO: the parameter happens to clash sometime (so full
|
||||
// strategy from scratch until we find a better way)
|
||||
// SEE: underscore: _._Chain.map(...) methods
|
||||
// String newInterfaceName =
|
||||
// StringUtils.capitalize(reference.getParameters()[paramIndex].getName());
|
||||
|
||||
String newInterfaceName = null;
|
||||
if (DeclarationHelper.getTypeOrComponentType(
|
||||
reference.getParameters()[paramIndex].getType()) instanceof TypeParameterDeclaration) {
|
||||
newInterfaceName = StringUtils.capitalize(reference.getParameters()[paramIndex].getName());
|
||||
} else {
|
||||
newInterfaceName = StringUtils.capitalize(
|
||||
context.getShortTypeNameErased(reference.getParameters()[paramIndex].getType())
|
||||
.replace("[]", "s"));
|
||||
}
|
||||
if (f.function.getParameters()[paramIndex].getType().getTypeArguments() != null) {
|
||||
for (TypeReference t : f.function.getParameters()[paramIndex].getType().getTypeArguments()) {
|
||||
String[] tokens = context.getShortTypeNameNoErasure(t).split("[<>,]");
|
||||
for (String token : tokens) {
|
||||
newInterfaceName += StringUtils.capitalize(token).replace("[]", "s");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
String[] tokens = context
|
||||
.getShortTypeNameNoErasure(f.function.getParameters()[paramIndex].getType())
|
||||
.split("[<>,]");
|
||||
for (String token : tokens) {
|
||||
newInterfaceName += StringUtils.capitalize(token).replace("[]", "s");
|
||||
}
|
||||
}
|
||||
if (newInterfaceName.length() > MAX_NAME_LENGTH) {
|
||||
newInterfaceName = StringUtils.capitalize(reference.getParameters()[paramIndex].getName())
|
||||
+ names.size();
|
||||
}
|
||||
newInterfaceName = resolveNameClash(functionalDisambiguation, highestTypeDeclaration,
|
||||
f.function.getParameters()[paramIndex].getType(), newInterfaceName);
|
||||
names.add(newInterfaceName);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case FULL:
|
||||
// apply a whole name strategy
|
||||
if (functionalDisambiguation) {
|
||||
for (FullFunctionDeclaration f : l) {
|
||||
String newInterfaceName = StringUtils.capitalize(reference.getParameters()[paramIndex].getName());
|
||||
if (f.function.getParameters()[paramIndex].getType().getTypeArguments() != null) {
|
||||
for (TypeReference t : f.function.getParameters()[paramIndex].getType().getTypeArguments()) {
|
||||
String[] tokens = context.getShortTypeNameNoErasure(t).split("[<>,]");
|
||||
for (String token : tokens) {
|
||||
newInterfaceName += StringUtils.capitalize(token).replace("[]", "s");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
String[] tokens = context
|
||||
.getShortTypeNameNoErasure(f.function.getParameters()[paramIndex].getType())
|
||||
.split("[<>,]");
|
||||
for (String token : tokens) {
|
||||
newInterfaceName += StringUtils.capitalize(token).replace("[]", "s");
|
||||
}
|
||||
}
|
||||
if (newInterfaceName.length() > MAX_NAME_LENGTH) {
|
||||
newInterfaceName = StringUtils.capitalize(reference.getParameters()[paramIndex].getName())
|
||||
+ names.size();
|
||||
}
|
||||
newInterfaceName = resolveNameClash(functionalDisambiguation, highestTypeDeclaration,
|
||||
f.function.getParameters()[paramIndex].getType(), newInterfaceName);
|
||||
names.add(newInterfaceName);
|
||||
}
|
||||
} else {
|
||||
for (FullFunctionDeclaration f : l) {
|
||||
String newInterfaceName = StringUtils
|
||||
.capitalize(context.getShortTypeNameErased(reference.getParameters()[paramIndex].getType())
|
||||
.replace("[]", "s"));
|
||||
if (f.function.getParameters()[paramIndex].getType().getTypeArguments() != null) {
|
||||
for (TypeReference t : f.function.getParameters()[paramIndex].getType().getTypeArguments()) {
|
||||
String[] tokens = context.getShortTypeNameNoErasure(t).split("[<>,]");
|
||||
for (String token : tokens) {
|
||||
newInterfaceName += StringUtils.capitalize(token).replace("[]", "s");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
String[] tokens = context
|
||||
.getShortTypeNameNoErasure(f.function.getParameters()[paramIndex].getType())
|
||||
.split("[<>,]");
|
||||
for (String token : tokens) {
|
||||
newInterfaceName += StringUtils.capitalize(token).replace("[]", "s");
|
||||
}
|
||||
}
|
||||
if (newInterfaceName.length() > MAX_NAME_LENGTH) {
|
||||
newInterfaceName = StringUtils.capitalize(reference.getParameters()[paramIndex].getName())
|
||||
+ names.size();
|
||||
}
|
||||
newInterfaceName = resolveNameClash(functionalDisambiguation, highestTypeDeclaration,
|
||||
f.function.getParameters()[paramIndex].getType(), newInterfaceName);
|
||||
names.add(newInterfaceName);
|
||||
}
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
private boolean isTypePresent(TypeDeclaration t, Set<FullFunctionDeclaration> duplicates) {
|
||||
if (t == null) {
|
||||
return false;
|
||||
}
|
||||
for (FullFunctionDeclaration f : duplicates) {
|
||||
if (t.equals(f.declaringType)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private TypeDeclaration getHighestSuperType(Set<FullFunctionDeclaration> duplicates) {
|
||||
FullFunctionDeclaration first = duplicates.iterator().next();
|
||||
TypeDeclaration hightest = first.declaringType;
|
||||
TypeDeclaration t = hightest;
|
||||
while (t.getSuperTypes() != null && t.getSuperTypes().length > 0) {
|
||||
TypeDeclaration st = (TypeDeclaration) lookupType(t.getSuperTypes()[0], null);
|
||||
if (st == null) {
|
||||
context.reportError("undefined type " + t.getSuperTypes()[0]);
|
||||
}
|
||||
if (isTypePresent(st, duplicates)) {
|
||||
hightest = st;
|
||||
}
|
||||
t = st;
|
||||
}
|
||||
return hightest;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,74 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.jsweet.input.typescriptdef.ast.ArrayTypeReference;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationContainer;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationHelper;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.ParameterDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @author Renaud Pawlak
|
||||
*/
|
||||
public class DynamicTypeParametersExpander extends Scanner {
|
||||
|
||||
private int expandedParameterCount = 0;
|
||||
|
||||
public DynamicTypeParametersExpander(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionDeclaration(FunctionDeclaration functionDeclaration) {
|
||||
super.visitFunctionDeclaration(functionDeclaration);
|
||||
DeclarationContainer container = getParent(DeclarationContainer.class);
|
||||
if (container instanceof TypeDeclaration && ((TypeDeclaration) container).isFunctionalInterface()) {
|
||||
// do not expand method signature if container is a functional
|
||||
// interface
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = functionDeclaration.getParameters().length - 1; i >= 0; i--) {
|
||||
if (functionDeclaration.getParameters()[i].getType().getTypeArguments() != null
|
||||
&& functionDeclaration.getParameters()[i].getType().getTypeArguments().length == 1
|
||||
&& context.arrayTypes.contains(lookupType(functionDeclaration.getParameters()[i].getType(), null))) {
|
||||
expandedParameterCount++;
|
||||
if (context.verbose) {
|
||||
logger.debug("expanding dynamic type for: " + functionDeclaration);
|
||||
}
|
||||
FunctionDeclaration newFunction = new FunctionDeclaration(functionDeclaration.getToken(),
|
||||
functionDeclaration.getName(), functionDeclaration.getType(),
|
||||
DeclarationHelper.copy(functionDeclaration.getParameters()),
|
||||
functionDeclaration.getTypeParameters());
|
||||
newFunction.setDocumentation(functionDeclaration.getDocumentation());
|
||||
newFunction.setModifiers(functionDeclaration.getModifiers());
|
||||
newFunction.getParameters()[i] = new ParameterDeclaration(null,
|
||||
functionDeclaration.getParameters()[i].getName(), new ArrayTypeReference(null,
|
||||
functionDeclaration.getParameters()[i].getType().getTypeArguments()[0]),
|
||||
functionDeclaration.getParameters()[i].isOptional(),
|
||||
functionDeclaration.getParameters()[i].isVarargs());
|
||||
if (!ArrayUtils.contains(container.getMembers(), newFunction)) {
|
||||
container.addMember(newFunction);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitVariableDeclaration(VariableDeclaration variableDeclaration) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onScanEnded() {
|
||||
if (expandedParameterCount > 0) {
|
||||
logger.debug(expandedParameterCount + " parameter(s) expanded.");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,58 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.ParameterDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeMacroDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
|
||||
/**
|
||||
* This scanner adds an empty protected constructor in classes that have
|
||||
* non-empty constructors, so that subclasses can define constructors without
|
||||
* having to explicitly invoke a superclass constructor.
|
||||
*
|
||||
* @author Renaud Pawlak
|
||||
*/
|
||||
public class EmptyConstructorAdder extends Scanner {
|
||||
|
||||
public EmptyConstructorAdder(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeDeclaration(TypeDeclaration typeDeclaration) {
|
||||
boolean hasEmptyConstructor = false;
|
||||
boolean hasNonEmptyConstructor = false;
|
||||
for (FunctionDeclaration func : typeDeclaration.findConstructors()) {
|
||||
if (func.isHidden()) {
|
||||
continue;
|
||||
}
|
||||
if (func.getParameters().length == 0) {
|
||||
hasEmptyConstructor = true;
|
||||
} else {
|
||||
hasNonEmptyConstructor = true;
|
||||
}
|
||||
}
|
||||
if (hasNonEmptyConstructor && !hasEmptyConstructor) {
|
||||
FunctionDeclaration constructor = new FunctionDeclaration(null,
|
||||
FunctionDeclaration.NEW_FUNCTION_RESERVED_NAME, null, new ParameterDeclaration[0], null);
|
||||
constructor.addModifier("protected");
|
||||
typeDeclaration.addMember(constructor);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionDeclaration(FunctionDeclaration functionDeclaration) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitVariableDeclaration(VariableDeclaration variableDeclaration) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeMacro(TypeMacroDeclaration typeMacroDeclaration) {
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,51 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.Declaration;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.ModuleDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.ReferenceDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeMacroDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
|
||||
/**
|
||||
* This scanner hides the module that don't have visible members.
|
||||
*
|
||||
* @author Renaud Pawlak
|
||||
*/
|
||||
public class EmptyModulesCleaner extends Scanner {
|
||||
|
||||
public EmptyModulesCleaner(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitModuleDeclaration(ModuleDeclaration moduleDeclaration) {
|
||||
for (Declaration d : moduleDeclaration.getMembers()) {
|
||||
if (!d.isHidden() && !(d instanceof ReferenceDeclaration)) {
|
||||
super.visitModuleDeclaration(moduleDeclaration);
|
||||
return;
|
||||
}
|
||||
}
|
||||
moduleDeclaration.setHidden(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionDeclaration(FunctionDeclaration functionDeclaration) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitVariableDeclaration(VariableDeclaration variableDeclaration) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeDeclaration(TypeDeclaration typeDeclaration) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeMacro(TypeMacroDeclaration typeMacroDeclaration) {
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,58 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.Type;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
|
||||
/**
|
||||
* This scanner creates factory methods out of anonymous ones when they return a
|
||||
* different type than the declaring type (otherwise, they are just
|
||||
* constructors).
|
||||
*
|
||||
* @author Renaud Pawlak
|
||||
*/
|
||||
public class FactoryMethodsCreator extends Scanner {
|
||||
|
||||
private int createdMethodCount = 0;
|
||||
|
||||
public FactoryMethodsCreator(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionDeclaration(FunctionDeclaration functionDeclaration) {
|
||||
if (!functionDeclaration.isAnonymous()) {
|
||||
return;
|
||||
}
|
||||
TypeDeclaration declaringType = getParent(TypeDeclaration.class);
|
||||
if (declaringType != null) {
|
||||
if (!"any".equals(functionDeclaration.getType().getName())) {
|
||||
Type t = lookupType(functionDeclaration.getType(), null);
|
||||
if (t != declaringType) {
|
||||
createdMethodCount++;
|
||||
if (context.verbose) {
|
||||
String location = functionDeclaration.getToken() == null ? "?" : functionDeclaration.getToken()
|
||||
.getLocation();
|
||||
logger.debug("creating factory method at " + location);
|
||||
functionDeclaration.setName("_create");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitVariableDeclaration(VariableDeclaration variableDeclaration) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onScanEnded() {
|
||||
if (createdMethodCount > 0) {
|
||||
logger.debug(createdMethodCount + " factory method(s) created.");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,149 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.jsweet.JSweetDefTranslatorConfig;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.Declaration;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationHelper;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.ParameterDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.Type;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeParameterDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeReference;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
import org.jsweet.input.typescriptdef.util.Util;
|
||||
|
||||
public class FieldTypeFunctionInjector extends Scanner {
|
||||
|
||||
public FieldTypeFunctionInjector(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionDeclaration(FunctionDeclaration functionDeclaration) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitVariableDeclaration(VariableDeclaration variableDeclaration) {
|
||||
|
||||
if ("constructor".equals(variableDeclaration.getName())
|
||||
|| JSweetDefTranslatorConfig.ANONYMOUS_FUNCTION_NAME.equals(variableDeclaration.getName())
|
||||
|| JSweetDefTranslatorConfig.NEW_FUNCTION_NAME.equals(variableDeclaration.getName())) {
|
||||
return;
|
||||
}
|
||||
|
||||
Type type = lookupType(variableDeclaration.getType());
|
||||
boolean candidate = (type instanceof TypeDeclaration) && (getParent() instanceof TypeDeclaration);
|
||||
|
||||
if (candidate) {
|
||||
TypeDeclaration typeDeclaration = (TypeDeclaration) type;
|
||||
TypeDeclaration parentTypeDeclaration = (TypeDeclaration) getParent();
|
||||
|
||||
if ("Function".equals(typeDeclaration.getName())) {
|
||||
String typeName = context.getTypeName(typeDeclaration);
|
||||
if ((JSweetDefTranslatorConfig.LANG_PACKAGE + ".Function").equals(typeName)
|
||||
|| "Function".equals(context.getLibRelativePath(context.getTypeName(typeDeclaration)))) {
|
||||
FunctionDeclaration newFunction = new FunctionDeclaration(null, variableDeclaration.getName(),
|
||||
new TypeReference(null, Object.class.getName(), null),
|
||||
new ParameterDeclaration[] { new ParameterDeclaration(null, "args",
|
||||
new TypeReference(null, Object.class.getName(), null), false, true) },
|
||||
null);
|
||||
if (variableDeclaration.hasModifier("static")) {
|
||||
newFunction.addModifier("static");
|
||||
}
|
||||
if (variableDeclaration.getStringAnnotations() != null) {
|
||||
newFunction.setStringAnnotations(
|
||||
new ArrayList<String>(variableDeclaration.getStringAnnotations()));
|
||||
}
|
||||
parentTypeDeclaration.addMember(newFunction);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
for (Declaration d : typeDeclaration.getMembers()) {
|
||||
if (d instanceof FunctionDeclaration && ((FunctionDeclaration) d).isAnonymous()
|
||||
&& !((FunctionDeclaration) d).hasModifier("static")) {
|
||||
FunctionDeclaration anonymousFunction = (FunctionDeclaration) d;
|
||||
FunctionDeclaration newFunction = new FunctionDeclaration(null, variableDeclaration.getName(),
|
||||
anonymousFunction.getType().copy(),
|
||||
DeclarationHelper.copy(anonymousFunction.getParameters()),
|
||||
DeclarationHelper.copy(anonymousFunction.getTypeParameters()));
|
||||
newFunction.setDocumentation(anonymousFunction.getDocumentation());
|
||||
if (variableDeclaration.hasModifier("static")) {
|
||||
newFunction.addModifier("static");
|
||||
}
|
||||
if (variableDeclaration.getStringAnnotations() != null) {
|
||||
if (anonymousFunction.getStringAnnotations() != null) {
|
||||
List<String> annotations = new ArrayList<String>(
|
||||
variableDeclaration.getStringAnnotations());
|
||||
annotations.addAll(anonymousFunction.getStringAnnotations());
|
||||
newFunction.setStringAnnotations(annotations);
|
||||
} else {
|
||||
newFunction.setStringAnnotations(
|
||||
new ArrayList<String>(variableDeclaration.getStringAnnotations()));
|
||||
}
|
||||
}
|
||||
// expand type references in the
|
||||
// function since it is not always
|
||||
// copied in the same module
|
||||
new Scanner(this) {
|
||||
@Override
|
||||
public void visitTypeReference(TypeReference typeReference) {
|
||||
Type t = null;
|
||||
// created inner type case (object type for
|
||||
// instance)
|
||||
t = typeDeclaration.findType(typeReference.getName());
|
||||
if (t == null) {
|
||||
t = lookupType(typeReference, context.getTypeModule(typeDeclaration));
|
||||
}
|
||||
if (t instanceof TypeDeclaration) {
|
||||
TypeDeclaration typeDeclaration = (TypeDeclaration) t;
|
||||
String typeName = context.getTypeName(typeDeclaration);
|
||||
if (!typeName.equals(typeReference.getName())) {
|
||||
if (context.verbose) {
|
||||
logger.debug("WARNING: rewriting type ref " + typeReference.getName() + " -> "
|
||||
+ typeName + " at "
|
||||
+ (getCurrentToken() == null ? "?" : getCurrentToken().getLocation()));
|
||||
}
|
||||
typeReference.setName(typeName);
|
||||
}
|
||||
}
|
||||
}
|
||||
}.visitFunctionDeclaration(newFunction);
|
||||
// substitute type parameters
|
||||
TypeParameterDeclaration[] usedTypeParametersInType = Util.findTypeParameters(context,
|
||||
typeDeclaration, anonymousFunction);
|
||||
String[] usedTypeParametersInFunction = Util.findTypeParameterNames(context, anonymousFunction,
|
||||
anonymousFunction);
|
||||
|
||||
if (usedTypeParametersInType.length > 0) {
|
||||
Map<String, TypeReference> typeMapping = new HashMap<>();
|
||||
for (TypeParameterDeclaration usedTypeParameter : usedTypeParametersInType) {
|
||||
if (ArrayUtils.contains(usedTypeParametersInFunction, usedTypeParameter.getName())) {
|
||||
// type parameter is hidden by local type
|
||||
// parameter
|
||||
continue;
|
||||
}
|
||||
int index = ArrayUtils.indexOf(typeDeclaration.getTypeParameters(), usedTypeParameter);
|
||||
if (index >= 0) {
|
||||
typeMapping.put(usedTypeParameter.getName(),
|
||||
variableDeclaration.getType().getTypeArguments()[index]);
|
||||
}
|
||||
}
|
||||
Util.subtituteTypeReferences(newFunction, typeMapping);
|
||||
}
|
||||
parentTypeDeclaration.addMember(newFunction);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,46 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import org.jsweet.JSweetDefTranslatorConfig;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.Type;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeMacroDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
|
||||
/**
|
||||
* Very specific case for JavaScript Array. Will not be necessary if we switch
|
||||
* to Peter's technique.
|
||||
*
|
||||
* @author Renaud Pawlak
|
||||
*/
|
||||
public class ForEachClashRemover extends Scanner {
|
||||
|
||||
public ForEachClashRemover(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionDeclaration(FunctionDeclaration functionDeclaration) {
|
||||
if ("forEach".equals(functionDeclaration.getName()) && functionDeclaration.getParameters().length == 1) {
|
||||
Type t = functionDeclaration.getParameters()[0].getType().getDeclaration();
|
||||
if (t instanceof TypeDeclaration
|
||||
&& Consumer.class.getName().equals(context.getTypeName((TypeDeclaration) t))) {
|
||||
functionDeclaration.getParameters()[0].getType()
|
||||
.setName(JSweetDefTranslatorConfig.FUNCTION_CLASSES_PACKAGE + ".Consumer");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitVariableDeclaration(VariableDeclaration variableDeclaration) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeMacro(TypeMacroDeclaration typeMacroDeclaration) {
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,49 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import org.jsweet.JSweetDefTranslatorConfig;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeReference;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
|
||||
public class FunctionKindAdapter extends Scanner {
|
||||
|
||||
public FunctionKindAdapter(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
boolean isInInterface = false;
|
||||
|
||||
@Override
|
||||
public void visitTypeDeclaration(TypeDeclaration typeDeclaration) {
|
||||
isInInterface = "interface".equals(typeDeclaration.getKind())
|
||||
|| typeDeclaration.hasStringAnnotation(JSweetDefTranslatorConfig.ANNOTATION_INTERFACE);
|
||||
super.visitTypeDeclaration(typeDeclaration);
|
||||
isInInterface = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionDeclaration(FunctionDeclaration functionDeclaration) {
|
||||
if (!(getParent() instanceof TypeDeclaration)) {
|
||||
return;
|
||||
}
|
||||
final TypeDeclaration parent = (TypeDeclaration) getParent();
|
||||
if (functionDeclaration.isConstructor() && isInInterface) {
|
||||
functionDeclaration.addModifier("native");
|
||||
functionDeclaration.setName(JSweetDefTranslatorConfig.NEW_FUNCTION_NAME);
|
||||
if (functionDeclaration.getType() == null) {
|
||||
functionDeclaration.setType(new TypeReference(null, parent, null));
|
||||
}
|
||||
} else if (JSweetDefTranslatorConfig.ANONYMOUS_FUNCTION_NAME.equals(functionDeclaration.getName())
|
||||
&& functionDeclaration.hasModifier("static")) {
|
||||
functionDeclaration.setName(JSweetDefTranslatorConfig.ANONYMOUS_STATIC_FUNCTION_NAME);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitVariableDeclaration(VariableDeclaration variableDeclaration) {
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,45 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationContainer;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.QualifiedDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeMacroDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
|
||||
public class FunctionTypeOfReplacer extends Scanner {
|
||||
|
||||
public FunctionTypeOfReplacer(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
public FunctionTypeOfReplacer(Scanner parentScanner) {
|
||||
super(parentScanner);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitVariableDeclaration(VariableDeclaration variableDeclaration) {
|
||||
if (variableDeclaration.getType().isTypeOf()) {
|
||||
QualifiedDeclaration<FunctionDeclaration> function = lookupFunctionDeclaration(
|
||||
variableDeclaration.getType().getName());
|
||||
if (function != null) {
|
||||
DeclarationContainer container = getParent(DeclarationContainer.class);
|
||||
container.removeMember(variableDeclaration);
|
||||
FunctionDeclaration f = function.getDeclaration().copy();
|
||||
f.setName(variableDeclaration.getName());
|
||||
container.addMember(f);
|
||||
}
|
||||
}
|
||||
super.visitVariableDeclaration(variableDeclaration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionDeclaration(FunctionDeclaration functionDeclaration) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeMacro(TypeMacroDeclaration typeMacroDeclaration) {
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,193 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import static org.jsweet.JSweetDefTranslatorConfig.FUNCTION_CLASSES_PACKAGE;
|
||||
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.jsweet.JSweetDefTranslatorConfig;
|
||||
import org.jsweet.input.typescriptdef.ast.ArrayTypeReference;
|
||||
import org.jsweet.input.typescriptdef.ast.CompilationUnit;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.Declaration;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationContainer;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationHelper;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionalTypeReference;
|
||||
import org.jsweet.input.typescriptdef.ast.ModuleDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.ParameterDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.Type;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeParameterDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeReference;
|
||||
import org.jsweet.input.typescriptdef.ast.TypedDeclaration;
|
||||
import org.jsweet.input.typescriptdef.util.Util;
|
||||
|
||||
public class FunctionalInterfacesCreator extends Scanner {
|
||||
|
||||
public static final String RUNNABLE = Runnable.class.getName();
|
||||
public static final String SUPPLIER = Supplier.class.getName();
|
||||
public static final String FUNCTION = Function.class.getName();
|
||||
public static final String BI_FUNCTION = BiFunction.class.getName();
|
||||
public static final String TRI_FUNCTION = FUNCTION_CLASSES_PACKAGE + ".TriFunction";
|
||||
public static final String CONSUMER = Consumer.class.getName();
|
||||
public static final String BI_CONSUMER = BiConsumer.class.getName();;
|
||||
public static final String TRI_CONSUMER = FUNCTION_CLASSES_PACKAGE + ".TriConsumer";
|
||||
|
||||
public FunctionalInterfacesCreator(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionalTypeReference(FunctionalTypeReference functionalTypeReference) {
|
||||
super.visitFunctionalTypeReference(functionalTypeReference);
|
||||
substituteTypeParameters(functionalTypeReference);
|
||||
|
||||
DeclarationContainer container = getParent(DeclarationContainer.class);
|
||||
if (container instanceof TypeDeclaration) {
|
||||
if ("interface".equals(((TypeDeclaration) container).getKind())) {
|
||||
container = getParent(DeclarationContainer.class, container);
|
||||
}
|
||||
}
|
||||
TypedDeclaration currentTypedElement = getParent(TypedDeclaration.class);
|
||||
ParameterDeclaration lastParam = functionalTypeReference.getParameters().length == 0 ? null
|
||||
: functionalTypeReference.getParameters()[functionalTypeReference.getParameters().length - 1];
|
||||
if (lastParam != null && lastParam.isVarargs()) {
|
||||
ParameterDeclaration[] parameters = DeclarationHelper.copy(functionalTypeReference.getParameters());
|
||||
parameters[parameters.length - 1]
|
||||
.setType(((ArrayTypeReference) parameters[parameters.length - 1].getType()).getComponentType());
|
||||
replaceFunctionnalType(container, currentTypedElement, functionalTypeReference, parameters,
|
||||
functionalTypeReference.getReturnType());
|
||||
} else {
|
||||
replaceFunctionnalType(container, currentTypedElement, functionalTypeReference,
|
||||
functionalTypeReference.getParameters(), functionalTypeReference.getReturnType());
|
||||
}
|
||||
}
|
||||
|
||||
private void substituteTypeParameters(final FunctionalTypeReference functionalTypeReference) {
|
||||
if (functionalTypeReference.getTypeParameters() != null) {
|
||||
new Scanner(context) {
|
||||
@Override
|
||||
public void visitTypeReference(TypeReference typeReference) {
|
||||
Type t = lookupType(typeReference);
|
||||
if (t instanceof TypeParameterDeclaration) {
|
||||
typeReference.setDeclaration(null);
|
||||
TypeReference upperBound = ((TypeParameterDeclaration) t).getUpperBound();
|
||||
if (upperBound != null) {
|
||||
typeReference.setName(upperBound.getName());
|
||||
if (upperBound.getTypeArguments() != null) {
|
||||
typeReference.setTypeArguments(DeclarationHelper.copyReferences(upperBound
|
||||
.getTypeArguments()));
|
||||
}
|
||||
} else {
|
||||
typeReference.setName("any");
|
||||
}
|
||||
}
|
||||
super.visitTypeReference(typeReference);
|
||||
}
|
||||
}.scan(functionalTypeReference);
|
||||
;
|
||||
}
|
||||
}
|
||||
|
||||
private void replaceFunctionnalType(DeclarationContainer container, TypedDeclaration currentTypedElement,
|
||||
TypeReference currentType, ParameterDeclaration[] parameters, TypeReference returnType) {
|
||||
if (parameters.length <= 3) {
|
||||
TypeReference functionType = new TypeReference(null, "unamed", null);
|
||||
if (!"void".equals(returnType.getName())) {
|
||||
switch (parameters.length) {
|
||||
case 0:
|
||||
functionType.setName(SUPPLIER);
|
||||
functionType.setTypeArguments(new TypeReference[] { returnType });
|
||||
break;
|
||||
case 1:
|
||||
functionType.setName(FUNCTION);
|
||||
functionType.setTypeArguments(new TypeReference[] { parameters[0].getType(), returnType });
|
||||
break;
|
||||
case 2:
|
||||
functionType.setName(BI_FUNCTION);
|
||||
functionType.setTypeArguments(new TypeReference[] { parameters[0].getType(),
|
||||
parameters[1].getType(), returnType });
|
||||
break;
|
||||
case 3:
|
||||
functionType.setName(TRI_FUNCTION);
|
||||
functionType.setTypeArguments(new TypeReference[] { parameters[0].getType(),
|
||||
parameters[1].getType(), parameters[2].getType(), returnType });
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
switch (parameters.length) {
|
||||
case 0:
|
||||
functionType.setName(RUNNABLE);
|
||||
break;
|
||||
case 1:
|
||||
functionType.setName(CONSUMER);
|
||||
functionType.setTypeArguments(new TypeReference[] { parameters[0].getType() });
|
||||
break;
|
||||
case 2:
|
||||
functionType.setName(BI_CONSUMER);
|
||||
functionType.setTypeArguments(new TypeReference[] { parameters[0].getType(),
|
||||
parameters[1].getType() });
|
||||
break;
|
||||
case 3:
|
||||
functionType.setName(TRI_CONSUMER);
|
||||
functionType.setTypeArguments(new TypeReference[] { parameters[0].getType(),
|
||||
parameters[1].getType(), parameters[2].getType() });
|
||||
break;
|
||||
}
|
||||
}
|
||||
Util.substituteTypeReference(this, currentTypedElement, currentType, functionType);
|
||||
} else {
|
||||
// TODO: generate functions with more than 3 parameters in the
|
||||
// util.function package so that we don't loose override links.
|
||||
// At the moment we choose not to support functions with more than 3
|
||||
// parameteres
|
||||
|
||||
TypeDeclaration t = getOrCreateFunctionalType(parameters, returnType);
|
||||
|
||||
TypeReference[] typeArgs = new TypeReference[parameters.length];
|
||||
for (int i = 0; i < parameters.length; i++) {
|
||||
typeArgs[i] = parameters[i].getType();
|
||||
}
|
||||
if (!"void".equals(returnType.getName())) {
|
||||
typeArgs = ArrayUtils.add(typeArgs, returnType);
|
||||
}
|
||||
|
||||
Util.substituteTypeReference(this, currentTypedElement, currentType, new TypeReference(null, t, typeArgs));
|
||||
|
||||
// // recursively apply to the generated functional interface
|
||||
// scan(newInterface);
|
||||
}
|
||||
}
|
||||
|
||||
private TypeDeclaration getOrCreateFunctionalType(ParameterDeclaration[] parameters, TypeReference returnType) {
|
||||
CompilationUnit cu = getParent(CompilationUnit.class);
|
||||
ModuleDeclaration m = getOrCreateModule(cu, JSweetDefTranslatorConfig.UTIL_PACKAGE);
|
||||
m = getOrCreateModule(m, "function");
|
||||
boolean hasResult = !"void".equals(returnType.getName());
|
||||
String name = (hasResult ? "Function" : "Consumer") + parameters.length;
|
||||
TypeDeclaration functionalType = m.findType(name);
|
||||
if (functionalType == null) {
|
||||
functionalType = DeclarationHelper.createFunctionalType(name, parameters.length, hasResult, false);
|
||||
m.addMember(functionalType);
|
||||
context.registerType(JSweetDefTranslatorConfig.UTIL_PACKAGE + ".function." + functionalType.getName(), functionalType);
|
||||
// recursively apply to the generated functional interface
|
||||
// scan(newInterface);
|
||||
}
|
||||
return functionalType;
|
||||
}
|
||||
|
||||
private ModuleDeclaration getOrCreateModule(DeclarationContainer container, String name) {
|
||||
ModuleDeclaration m = DeclarationHelper.findModule(container, name);
|
||||
if (m == null) {
|
||||
m = new ModuleDeclaration(null, name, new Declaration[0]);
|
||||
container.addMember(m);
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,44 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationContainer;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionalTypeReference;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
|
||||
public class FunctionalParametersExpander extends Scanner {
|
||||
|
||||
public FunctionalParametersExpander(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionDeclaration(FunctionDeclaration functionDeclaration) {
|
||||
super.visitFunctionDeclaration(functionDeclaration);
|
||||
DeclarationContainer container = getParent(DeclarationContainer.class);
|
||||
expandFunctionalParameters(container, functionDeclaration);
|
||||
}
|
||||
|
||||
private void expandFunctionalParameters(DeclarationContainer container, FunctionDeclaration functionDeclaration) {
|
||||
for (int i = functionDeclaration.getParameters().length - 1; i >= 0; i--) {
|
||||
if (functionDeclaration.getParameters()[i].getType() instanceof FunctionalTypeReference) {
|
||||
FunctionalTypeReference p = (FunctionalTypeReference) functionDeclaration.getParameters()[i].getType();
|
||||
if ("any".equals(p.getReturnType().getName())) {
|
||||
FunctionDeclaration newFunction = functionDeclaration.copy();
|
||||
((FunctionalTypeReference) newFunction.getParameters()[i].getType()).getReturnType().setName("void");
|
||||
if (!ArrayUtils.contains(container.getMembers(), newFunction)) {
|
||||
container.addMember(newFunction);
|
||||
expandFunctionalParameters(container, newFunction);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitVariableDeclaration(VariableDeclaration variableDeclaration) {
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,72 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import static org.jsweet.input.typescriptdef.util.Util.getOrCreateGlobalsType;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.Declaration;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationHelper;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.ModuleDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.Type;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
|
||||
public class GlobalsCreator extends Scanner {
|
||||
|
||||
public GlobalsCreator(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitModuleDeclaration(ModuleDeclaration moduleDeclaration) {
|
||||
for (Declaration declaration : moduleDeclaration.getMembers()) {
|
||||
if (declaration.isHidden()) {
|
||||
continue;
|
||||
}
|
||||
if ((declaration instanceof VariableDeclaration) || (declaration instanceof FunctionDeclaration)) {
|
||||
TypeDeclaration globalsClass = getOrCreateGlobalsType(context, moduleDeclaration,
|
||||
getParent(ModuleDeclaration.class));
|
||||
if (DeclarationHelper.JS_OBJECT_METHOD_NAMES.contains(declaration.getName())) {
|
||||
declaration.setName(StringUtils.capitalize(declaration.getName()));
|
||||
}
|
||||
moduleDeclaration.removeMember(declaration);
|
||||
if (declaration instanceof VariableDeclaration) {
|
||||
VariableDeclaration existing = globalsClass.findVariable(declaration.getName());
|
||||
if (existing != null && !existing.isHidden()) {
|
||||
context.reportWarning("skip variable " + declaration + " - already exists in "
|
||||
+ moduleDeclaration + " (" + existing + ")");
|
||||
// variable already exists
|
||||
continue;
|
||||
}
|
||||
}
|
||||
globalsClass.addMember(declaration);
|
||||
declaration.addModifier("static");
|
||||
if (declaration instanceof VariableDeclaration) {
|
||||
VariableDeclaration varDecl = (VariableDeclaration) declaration;
|
||||
Type t = lookupType(varDecl.getType(), null);
|
||||
if (t instanceof TypeDeclaration) {
|
||||
final TypeDeclaration typeDeclaration = (TypeDeclaration) t;
|
||||
if (!typeDeclaration.isExternal() && typeDeclaration.isStatic()) {
|
||||
globalsClass.removeMember(declaration);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
super.visitModuleDeclaration(moduleDeclaration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeDeclaration(TypeDeclaration typeDeclaration) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionDeclaration(FunctionDeclaration functionDeclaration) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitVariableDeclaration(VariableDeclaration variableDeclaration) {
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,504 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.jsweet.JSweetDefTranslatorConfig;
|
||||
import org.jsweet.input.typescriptdef.ast.AstNode;
|
||||
import org.jsweet.input.typescriptdef.ast.CompilationUnit;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.Declaration;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationContainer;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationHelper;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.ModuleDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.QualifiedDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.ReferenceDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeReference;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
import org.jsweet.input.typescriptdef.util.Util;
|
||||
|
||||
/**
|
||||
* This scanner expands the imported / exported references to anything declared.
|
||||
*
|
||||
* @author Louis Grignon
|
||||
* @author Renaud Pawlak
|
||||
*/
|
||||
public class ImportedAndExportedReferenceExpander extends Scanner {
|
||||
|
||||
private int referencesCount = 0;
|
||||
private QualifiedDeclaration<? extends Declaration>[] containerScope;
|
||||
private boolean importMode = false;
|
||||
|
||||
public ImportedAndExportedReferenceExpander(Context context, boolean importMode) {
|
||||
super(context);
|
||||
this.importMode = importMode;
|
||||
}
|
||||
|
||||
public ImportedAndExportedReferenceExpander(Context context,
|
||||
QualifiedDeclaration<? extends Declaration>[] containerScope, boolean importMode) {
|
||||
super(context);
|
||||
this.containerScope = containerScope;
|
||||
logger.trace("searching imports in " + Arrays.asList(containerScope));
|
||||
this.importMode = importMode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Overrides the default implementation because we intend to pass this
|
||||
* scanner before the packages reorganization.
|
||||
*/
|
||||
@Override
|
||||
protected QualifiedDeclaration<ModuleDeclaration> lookupModuleDeclaration(String name) {
|
||||
for (int i = 0; i < getStack().size(); i++) {
|
||||
String containerName = getContainerNameAtIndex(i);
|
||||
String declFullName = StringUtils.isBlank(containerName) ? name : containerName + "." + name;
|
||||
// first search in the current compilation unit
|
||||
List<QualifiedDeclaration<ModuleDeclaration>> matches = context.findDeclarations(ModuleDeclaration.class,
|
||||
declFullName, (CompilationUnit) getRoot());
|
||||
for (QualifiedDeclaration<ModuleDeclaration> m : matches) {
|
||||
if (!m.getDeclaration().isQuotedName()) {
|
||||
return m;
|
||||
}
|
||||
}
|
||||
for (QualifiedDeclaration<ModuleDeclaration> m : matches) {
|
||||
return m;
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < getStack().size(); i++) {
|
||||
String containerName = getContainerNameAtIndex(i);
|
||||
String declFullName = StringUtils.isBlank(containerName) ? name : containerName + "." + name;
|
||||
// search in all compilation units
|
||||
List<QualifiedDeclaration<ModuleDeclaration>> matches = context.findDeclarations(ModuleDeclaration.class,
|
||||
declFullName);
|
||||
for (QualifiedDeclaration<ModuleDeclaration> m : matches) {
|
||||
if (!m.getDeclaration().isQuotedName()) {
|
||||
return m;
|
||||
}
|
||||
}
|
||||
for (QualifiedDeclaration<ModuleDeclaration> m : matches) {
|
||||
return m;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Overrides the default implementation because we intend to pass this
|
||||
* scanner before the packages reorganization.
|
||||
*/
|
||||
@Override
|
||||
protected QualifiedDeclaration<TypeDeclaration> lookupTypeDeclaration(String name) {
|
||||
for (int i = 0; i < getStack().size(); i++) {
|
||||
String containerName = getContainerNameAtIndex(i);
|
||||
String declFullName = StringUtils.isBlank(containerName) ? name : containerName + "." + name;
|
||||
// first search in the current compilation unit
|
||||
QualifiedDeclaration<TypeDeclaration> match = context.findFirstDeclaration(TypeDeclaration.class,
|
||||
declFullName, (CompilationUnit) getRoot());
|
||||
if (match != null) {
|
||||
return match;
|
||||
}
|
||||
// search in all compilation units
|
||||
match = context.findFirstDeclaration(TypeDeclaration.class, declFullName);
|
||||
if (match != null) {
|
||||
return match;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private boolean isInContainerScope(QualifiedDeclaration<? extends Declaration> declaration) {
|
||||
if (containerScope == null) {
|
||||
return false;
|
||||
}
|
||||
for (QualifiedDeclaration<? extends Declaration> d : containerScope) {
|
||||
if (declaration.getDeclaration() == d.getDeclaration()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitReferenceDeclaration(ReferenceDeclaration referenceDeclaration) {
|
||||
if (referenceDeclaration.isExport() && importMode) {
|
||||
return;
|
||||
}
|
||||
if (referenceDeclaration.isImport() && !importMode) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (containerScope != null) {
|
||||
for (QualifiedDeclaration<? extends Declaration> d : containerScope) {
|
||||
if (!isInScope(d.getDeclaration())) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
logger.debug("analysing reference: " + getParent(CompilationUnit.class) + "->" + referenceDeclaration);
|
||||
|
||||
DeclarationContainer container = (DeclarationContainer) getParent();
|
||||
DeclarationContainer parentContainer = getParent(DeclarationContainer.class, container);
|
||||
QualifiedDeclaration<? extends Declaration> foreignDeclaration = lookupModuleDeclaration(
|
||||
referenceDeclaration.getReferencedName());
|
||||
if (foreignDeclaration == null) {
|
||||
foreignDeclaration = lookupTypeDeclaration(referenceDeclaration.getReferencedName());
|
||||
}
|
||||
if (foreignDeclaration == null) {
|
||||
foreignDeclaration = lookupFunctionDeclaration(referenceDeclaration.getReferencedName());
|
||||
}
|
||||
if (foreignDeclaration == null) {
|
||||
foreignDeclaration = lookupVariableDeclaration(referenceDeclaration.getReferencedName());
|
||||
}
|
||||
if (foreignDeclaration != null) {
|
||||
if (isInContainerScope(foreignDeclaration)) {
|
||||
return;
|
||||
}
|
||||
logger.trace((containerScope == null ? "" : "(scope=" + Arrays.asList(containerScope) + ") ")
|
||||
+ "reference found: " + getCurrentContainerName() + "->" + referenceDeclaration + " references => "
|
||||
+ foreignDeclaration);
|
||||
|
||||
// resolve foreign import first
|
||||
if (foreignDeclaration.getDeclaration() instanceof DeclarationContainer) {
|
||||
logger.trace("looking into context for " + foreignDeclaration.getQualifiedDeclarationName());
|
||||
|
||||
ImportedAndExportedReferenceExpander subScanner = new ImportedAndExportedReferenceExpander(context,
|
||||
ArrayUtils.add(containerScope, foreignDeclaration), this.importMode);
|
||||
subScanner.scan(context.compilationUnits);
|
||||
}
|
||||
|
||||
// TODO: this part contains a lot of code duplication (function/var)
|
||||
// because the development is very experimental... consolidate at
|
||||
// some point...
|
||||
|
||||
if (referenceDeclaration.isExport()) {
|
||||
|
||||
String foreignLib = Util.getLibPackageNameFromTsDefFile(
|
||||
new File(foreignDeclaration.getDeclaration().getToken().getFileName()));
|
||||
String currentLib = Util
|
||||
.getLibPackageNameFromTsDefFile(new File(((AstNode) container).getToken().getFileName()));
|
||||
boolean externalReference = !foreignLib.equals(currentLib);
|
||||
|
||||
// FUNCTION or VARIABLE case
|
||||
if (foreignDeclaration.getDeclaration() instanceof FunctionDeclaration
|
||||
|| foreignDeclaration.getDeclaration() instanceof VariableDeclaration) {
|
||||
Declaration declaration = foreignDeclaration.getDeclaration();
|
||||
if (((Declaration) container).isQuotedName()) {
|
||||
if (!declaration.hasStringAnnotation(JSweetDefTranslatorConfig.ANNOTATION_MODULE)) {
|
||||
declaration.addStringAnnotation(JSweetDefTranslatorConfig.ANNOTATION_MODULE + "(\""
|
||||
+ ((Declaration) container).getOriginalName() + "\")");
|
||||
}
|
||||
}
|
||||
Declaration copy = declaration.copy();
|
||||
if (getParent(2) instanceof DeclarationContainer) {
|
||||
copy.setName(((Declaration) container).getName());
|
||||
((DeclarationContainer) getParent(2)).addMember(copy);
|
||||
logger.info("added member " + copy + " to " + (DeclarationContainer) getParent(2));
|
||||
rewriteTypeReferences(getCurrentContainerName(), copy);
|
||||
// make target container external if necessary
|
||||
if (((Declaration) container).isQuotedName()) {
|
||||
if (container.findDeclaration(foreignDeclaration.getDeclaration()) != null) {
|
||||
declaration.setHidden(true);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
copy.setName(JSweetDefTranslatorConfig.ANONYMOUS_FUNCTION_NAME);
|
||||
container.addMember(copy);
|
||||
logger.info("added member " + copy + " to " + container);
|
||||
|
||||
// if function is internal, we assume the actual
|
||||
// function to
|
||||
// export is the one that belongs to container
|
||||
if (!externalReference) {
|
||||
foreignDeclaration.getDeclaration().setHidden(true);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// HEURISTIC: when the exported element is not in the same
|
||||
// lib, then is it external and it should not be exported
|
||||
if (externalReference) {
|
||||
return;
|
||||
}
|
||||
|
||||
// CONTAINER CASE: add members to container directly
|
||||
|
||||
DeclarationContainer foreignDeclarationContainer = (DeclarationContainer) foreignDeclaration
|
||||
.getDeclaration();
|
||||
String name = ((Declaration) container).getName();
|
||||
if (((Declaration) container).isQuotedName()) {
|
||||
if (!foreignDeclaration.getDeclaration()
|
||||
.hasStringAnnotation(JSweetDefTranslatorConfig.ANNOTATION_MODULE)) {
|
||||
foreignDeclaration.getDeclaration()
|
||||
.addStringAnnotation(JSweetDefTranslatorConfig.ANNOTATION_MODULE + "(\""
|
||||
+ ((Declaration) container).getOriginalName() + "\")");
|
||||
}
|
||||
}
|
||||
|
||||
boolean exportInnerNamespace = container.findDeclaration(foreignDeclaration.getDeclaration()) != null;
|
||||
if ((name.equals(foreignDeclaration.getDeclaration().getName()) || (!exportInnerNamespace)
|
||||
|| (container == foreignDeclarationContainer
|
||||
&& foreignDeclaration.getDeclaration().isQuotedName()))) {
|
||||
// useless self exporting (quoted module export non quoted
|
||||
// module of the same name)
|
||||
// referenceDeclaration.setHidden(true);
|
||||
// return;
|
||||
} else {
|
||||
|
||||
logger.info("adding " + foreignDeclarationContainer + " members to " + container + " / "
|
||||
+ getCurrentContainerName());
|
||||
if (foreignDeclarationContainer instanceof ModuleDeclaration) {
|
||||
if (container.findDeclaration(foreignDeclaration.getDeclaration()) != null) {
|
||||
foreignDeclarationContainer.setHidden(true);
|
||||
}
|
||||
}
|
||||
container.addMembers(DeclarationHelper.copy(foreignDeclarationContainer.getMembers()));
|
||||
// absolute path redirector
|
||||
new TypeReferenceRedirector(foreignDeclaration, foreignDeclaration.getQualifiedDeclarationName(),
|
||||
StringUtils.isBlank(getCurrentContainerName()) ? referenceDeclaration.getName()
|
||||
: getCurrentContainerName()).scan(container);
|
||||
// relative path
|
||||
if (foreignDeclaration.getQualifiedDeclarationName().startsWith(name + ".")) {
|
||||
new TypeReferenceRedirector(foreignDeclaration,
|
||||
foreignDeclaration.getQualifiedDeclarationName().substring(name.length() + 1), "")
|
||||
.scan(container);
|
||||
}
|
||||
}
|
||||
|
||||
foreignDeclarationContainer = findContainer(foreignDeclaration);
|
||||
|
||||
// deal with functions and variables
|
||||
List<FunctionDeclaration> functions = foreignDeclarationContainer
|
||||
.findFunctions(foreignDeclaration.getDeclaration().getName());
|
||||
|
||||
for (FunctionDeclaration function : functions) {
|
||||
if (function.isHidden()) {
|
||||
continue;
|
||||
}
|
||||
if (((Declaration) container).isQuotedName()) {
|
||||
if (!function.hasStringAnnotation(JSweetDefTranslatorConfig.ANNOTATION_MODULE)) {
|
||||
function.addStringAnnotation(JSweetDefTranslatorConfig.ANNOTATION_MODULE + "(\""
|
||||
+ ((Declaration) container).getOriginalName() + "\")");
|
||||
}
|
||||
}
|
||||
if (exportInnerNamespace) {
|
||||
logger.debug("renaming function: " + function + " -> " + name);
|
||||
function.setName(name);
|
||||
}
|
||||
if (getParent(2) instanceof DeclarationContainer) {
|
||||
FunctionDeclaration functionCopy = function.copy();
|
||||
((DeclarationContainer) getParent(2)).addMember(functionCopy);
|
||||
if (exportInnerNamespace) {
|
||||
function.setHidden(true);
|
||||
}
|
||||
rewriteTypeReferences(getCurrentContainerName(), functionCopy);
|
||||
}
|
||||
}
|
||||
// TODO: check if this case actually happens (but there is no
|
||||
// reasons why it shouldn't)
|
||||
VariableDeclaration var = foreignDeclarationContainer
|
||||
.findVariable(foreignDeclaration.getDeclaration().getName());
|
||||
if (var != null && !var.isHidden()) {
|
||||
if (((Declaration) container).isQuotedName()) {
|
||||
if (!var.hasStringAnnotation(JSweetDefTranslatorConfig.ANNOTATION_MODULE)) {
|
||||
var.addStringAnnotation(JSweetDefTranslatorConfig.ANNOTATION_MODULE + "(\""
|
||||
+ ((Declaration) container).getOriginalName() + "\")");
|
||||
}
|
||||
}
|
||||
if (exportInnerNamespace) {
|
||||
logger.debug("renaming variable: " + var + " -> " + name);
|
||||
var.setName(name);
|
||||
}
|
||||
if (getParent(2) instanceof DeclarationContainer) {
|
||||
VariableDeclaration varCopy = var.copy();
|
||||
((DeclarationContainer) getParent(2)).addMember(varCopy);
|
||||
if (exportInnerNamespace) {
|
||||
var.setHidden(true);
|
||||
}
|
||||
rewriteTypeReferences(getCurrentContainerName(), varCopy);
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
referenceDeclaration.setName(Util.toJavaName(referenceDeclaration.getName()));
|
||||
// we must do the job in all compilation units
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
List<QualifiedDeclaration<? extends Declaration>> declarations = (List) context.findDeclarations(
|
||||
foreignDeclaration.getDeclaration().getClass(),
|
||||
foreignDeclaration.getQualifiedDeclarationName());
|
||||
for (QualifiedDeclaration<? extends Declaration> declaration : declarations) {
|
||||
// HEURISTIC: if the import imports a module in the same
|
||||
// container, then it is a way to make the module public...
|
||||
// so we just rename the module.
|
||||
String modName = declaration.getQualifier();
|
||||
Declaration d = declaration.getDeclaration();
|
||||
if (parentContainer == null || getCurrentContainerName().equals(modName == null ? "" : modName)) {
|
||||
if (d != null && d instanceof ModuleDeclaration && !d.isQuotedName()) {
|
||||
logger.info("renaming module: " + d + " -> " + referenceDeclaration.getName() + " ("
|
||||
+ referenceDeclaration.getLocation() + ")");
|
||||
for (Declaration currentDecl : container.getMembers()) {
|
||||
if (currentDecl.isQuotedName() && d.getName().equals(currentDecl.getName())) {
|
||||
if (d.isQuotedName()) {
|
||||
d.setOriginalName(d.getOriginalName());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
d.setName(referenceDeclaration.getName());
|
||||
new TypeReferenceRedirector(null, foreignDeclaration.getQualifiedDeclarationName(),
|
||||
StringUtils.isBlank(getCurrentContainerName()) ? referenceDeclaration.getName()
|
||||
: getCurrentContainerName() + "." + referenceDeclaration.getName())
|
||||
.scan(context.compilationUnits);
|
||||
}
|
||||
} else {
|
||||
if (!declaration.getDeclaration().getName().equals(referenceDeclaration.getName())) {
|
||||
logger.info("substituting " + referenceDeclaration.getName() + " -> " + declaration + " ("
|
||||
+ referenceDeclaration.getLocation() + ")");
|
||||
// redirect global members in parent modules
|
||||
// (because global functions are moved there)
|
||||
List<Declaration> declarationsToProcess = Arrays.asList(parentContainer.getMembers())
|
||||
.stream().filter(d2 -> {
|
||||
return d2 == container || !(d2 instanceof ModuleDeclaration);
|
||||
}).collect(Collectors.toList());
|
||||
// qualified
|
||||
new TypeReferenceRedirector(foreignDeclaration,
|
||||
StringUtils.isBlank(getCurrentContainerName()) ? referenceDeclaration.getName()
|
||||
: getCurrentContainerName() + "." + referenceDeclaration.getName(),
|
||||
foreignDeclaration.getQualifiedDeclarationName()).scan(declarationsToProcess);
|
||||
// not qualified
|
||||
new TypeReferenceRedirector(foreignDeclaration, referenceDeclaration.getName(),
|
||||
foreignDeclaration.getQualifiedDeclarationName()).scan(declarationsToProcess);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
referencesCount++;
|
||||
} else {
|
||||
logger.warn("referenced declaration not found in " + getCurrentContainerName() + ": "
|
||||
+ referenceDeclaration.getReferencedName());
|
||||
}
|
||||
|
||||
container.removeMember(referenceDeclaration);
|
||||
}
|
||||
|
||||
private DeclarationContainer findContainer(QualifiedDeclaration<? extends Declaration> foreignDeclaration) {
|
||||
if (!foreignDeclaration.getQualifiedDeclarationName().contains(".")) {
|
||||
return (DeclarationContainer) getStack().get(0);
|
||||
} else {
|
||||
String name = foreignDeclaration.getQualifier();
|
||||
List<QualifiedDeclaration<ModuleDeclaration>> modules = context.findDeclarations(ModuleDeclaration.class,
|
||||
name);
|
||||
for (QualifiedDeclaration<ModuleDeclaration> m : modules) {
|
||||
if (ArrayUtils.contains(m.getDeclaration().getMembers(), foreignDeclaration.getDeclaration())) {
|
||||
return m.getDeclaration();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void rewriteTypeReferences(String initialContainerName, Declaration declaration) {
|
||||
TypeReferenceRewriter rewriter = new TypeReferenceRewriter(context, initialContainerName);
|
||||
rewriter.scan(declaration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onScanEnded() {
|
||||
// if main pass handled results
|
||||
if (containerScope == null && referencesCount > 0) {
|
||||
logger.debug(referencesCount + " imported reference(s) expanded.");
|
||||
}
|
||||
}
|
||||
|
||||
public static class TypeReferenceRedirector extends Scanner {
|
||||
|
||||
private static Logger logger = Logger.getLogger(TypeReferenceRedirector.class);
|
||||
private QualifiedDeclaration<? extends Declaration> initialDeclaration;
|
||||
private String sourcePrefix;
|
||||
private String targetPrefix;
|
||||
|
||||
public TypeReferenceRedirector(QualifiedDeclaration<? extends Declaration> initialDeclaration,
|
||||
String sourcePrefix, String targetPrefix) {
|
||||
super((Context) null);
|
||||
logger.info(sourcePrefix + " -> " + targetPrefix);
|
||||
this.initialDeclaration = initialDeclaration;
|
||||
this.sourcePrefix = sourcePrefix;
|
||||
this.targetPrefix = targetPrefix;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitModuleDeclaration(ModuleDeclaration moduleDeclaration) {
|
||||
if (initialDeclaration == null || moduleDeclaration != initialDeclaration.getDeclaration()) {
|
||||
super.visitModuleDeclaration(moduleDeclaration);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeDeclaration(TypeDeclaration typeDeclaration) {
|
||||
if (initialDeclaration == null || typeDeclaration != initialDeclaration.getDeclaration()) {
|
||||
super.visitTypeDeclaration(typeDeclaration);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeReference(TypeReference typeReference) {
|
||||
if (typeReference.getName() != null && typeReference.getName().startsWith(sourcePrefix + ".")) {
|
||||
typeReference.setDeclaration(null);
|
||||
String newName = typeReference.getName().replaceFirst(sourcePrefix + ".",
|
||||
StringUtils.isBlank(targetPrefix) ? "" : targetPrefix + ".");
|
||||
logger.debug("redirecting type reference: " + typeReference.getName() + " -> " + newName);
|
||||
typeReference.setName(newName);
|
||||
}
|
||||
super.visitTypeReference(typeReference);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitReferenceDeclaration(ReferenceDeclaration referenceDeclaration) {
|
||||
if (referenceDeclaration.isImport() && referenceDeclaration.getReferencedName() != null
|
||||
&& referenceDeclaration.getReferencedName().startsWith(sourcePrefix + ".")) {
|
||||
String newName = referenceDeclaration.getReferencedName().replaceFirst(sourcePrefix + ".",
|
||||
StringUtils.isBlank(targetPrefix) ? "" : targetPrefix + ".");
|
||||
logger.debug("redirecting reference declaration: " + referenceDeclaration.getReferencedName() + " -> "
|
||||
+ newName);
|
||||
referenceDeclaration.setReferencedName(newName);
|
||||
}
|
||||
super.visitReferenceDeclaration(referenceDeclaration);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class TypeReferenceRewriter extends Scanner {
|
||||
|
||||
private static Logger logger = Logger.getLogger(TypeReferenceRedirector.class);
|
||||
private String initialContainerName;
|
||||
|
||||
public TypeReferenceRewriter(Context context, String initialContainerName) {
|
||||
super((Context) context);
|
||||
this.initialContainerName = initialContainerName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeReference(TypeReference typeReference) {
|
||||
QualifiedDeclaration<TypeDeclaration> declaration = context.findFirstDeclaration(TypeDeclaration.class,
|
||||
initialContainerName + "." + typeReference);
|
||||
if (declaration != null) {
|
||||
logger.debug("rewriting type reference: " + typeReference.getName() + " -> "
|
||||
+ declaration.getQualifiedDeclarationName());
|
||||
typeReference.setName(declaration.getQualifiedDeclarationName());
|
||||
}
|
||||
super.visitTypeReference(typeReference);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,82 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.jsweet.JSweetDefTranslatorConfig;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.ParameterDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeReference;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
import org.jsweet.input.typescriptdef.util.Util;
|
||||
|
||||
/**
|
||||
* This scanner injects the java.lang.Iterable interface when possible on
|
||||
* indexed types (it also injects the $set method when not found).
|
||||
*
|
||||
* @author Renaud Pawlak
|
||||
*/
|
||||
public class IterableInjector extends Scanner {
|
||||
|
||||
public IterableInjector(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeDeclaration(TypeDeclaration typeDeclaration) {
|
||||
for (FunctionDeclaration getFunction : typeDeclaration.findFunctions(JSweetDefTranslatorConfig.INDEXED_GET_FUCTION_NAME)) {
|
||||
if (getFunction.isHidden()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// inject the Iterable interface if needed
|
||||
VariableDeclaration var = typeDeclaration.findVariable("length");
|
||||
if (var == null) {
|
||||
return;
|
||||
}
|
||||
if (getFunction.getParameters().length == 1
|
||||
&& "number".equals(getFunction.getParameters()[0].getType().getName())) {
|
||||
// skip if already in a super type
|
||||
if (typeDeclaration.getSuperTypes() != null) {
|
||||
for (TypeReference t : typeDeclaration.getSuperTypes()) {
|
||||
FunctionDeclaration alreadyInSupertype = lookupFunctionDeclaration(t,
|
||||
JSweetDefTranslatorConfig.INDEXED_GET_FUCTION_NAME, new TypeReference(null, "number", null));
|
||||
if (alreadyInSupertype != null) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ("class".equals(typeDeclaration.getKind()) || "interface".equals(typeDeclaration.getKind())) {
|
||||
TypeReference iterableType = new TypeReference(null, "Iterable",
|
||||
new TypeReference[] { Util.wrapTypeReferences(getFunction.getType().copy()) });
|
||||
if (!ArrayUtils.contains(typeDeclaration.getSuperTypes(), iterableType)) {
|
||||
logger.trace("add " + getFunction.getType() + " iterator to "
|
||||
+ context.getTypeName(typeDeclaration));
|
||||
typeDeclaration.setSuperTypes(ArrayUtils.add(typeDeclaration.getSuperTypes(), iterableType));
|
||||
if (!"interface".equals(typeDeclaration.getKind())) {
|
||||
FunctionDeclaration iterator = new FunctionDeclaration(null, "iterator", new TypeReference(
|
||||
null, "java.util.Iterator",
|
||||
new TypeReference[] { Util.wrapTypeReferences(getFunction.getType().copy()) }),
|
||||
new ParameterDeclaration[0], null);
|
||||
iterator.setDocumentation("/** From Iterable, to allow foreach loop (do not use directly). */");
|
||||
iterator.addStringAnnotation(JSweetDefTranslatorConfig.ANNOTATION_ERASED);
|
||||
|
||||
typeDeclaration.addMember(iterator);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionDeclaration(FunctionDeclaration functionDeclaration) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitVariableDeclaration(VariableDeclaration variableDeclaration) {
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,614 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
import static org.apache.commons.lang3.StringUtils.isBlank;
|
||||
import static org.apache.commons.lang3.StringUtils.join;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.PrintWriter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.jsweet.JSweetDefTranslatorConfig;
|
||||
import org.jsweet.input.typescriptdef.ast.AbstractPrinter;
|
||||
import org.jsweet.input.typescriptdef.ast.ArrayTypeReference;
|
||||
import org.jsweet.input.typescriptdef.ast.CompilationUnit;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.Declaration;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationHelper;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionalTypeReference;
|
||||
import org.jsweet.input.typescriptdef.ast.ModuleDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.ParameterDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.QualifiedDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.Type;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeParameterDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeReference;
|
||||
import org.jsweet.input.typescriptdef.ast.UnionTypeReference;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
import org.jsweet.input.typescriptdef.util.Util;
|
||||
|
||||
public class JavaDefModelPrinter extends AbstractPrinter {
|
||||
|
||||
private static Map<String, String> typeMap = new HashMap<String, String>();
|
||||
|
||||
static {
|
||||
typeMap.put("any", "Object");
|
||||
typeMap.put("string", "String");
|
||||
typeMap.put("number", "double");
|
||||
typeMap.put("symbol", "String");
|
||||
}
|
||||
|
||||
private static String toJavaTypeName(String typeName) {
|
||||
if (typeMap.containsKey(typeName)) {
|
||||
return typeMap.get(typeName);
|
||||
} else {
|
||||
return typeName;
|
||||
}
|
||||
}
|
||||
|
||||
private File outputDir;
|
||||
|
||||
public JavaDefModelPrinter(Context context, File outputDir) {
|
||||
super(context);
|
||||
this.outputDir = outputDir;
|
||||
}
|
||||
|
||||
private AbstractPrinter printIdentifier(String identifier) {
|
||||
print(DeclarationHelper.toJavaIdentifier(identifier));
|
||||
return this;
|
||||
}
|
||||
|
||||
private AbstractPrinter printFunctionName(String functionName) {
|
||||
return printIdentifier(functionName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitCompilationUnit(CompilationUnit compilationUnit) {
|
||||
if (context.isDependency(compilationUnit)) {
|
||||
return;
|
||||
}
|
||||
|
||||
super.visitCompilationUnit(compilationUnit);
|
||||
}
|
||||
|
||||
String currentModuleName;
|
||||
|
||||
@Override
|
||||
public void visitModuleDeclaration(ModuleDeclaration moduleDeclaration) {
|
||||
currentModuleName = getCurrentModuleName();
|
||||
String dependenciesNamesString = null;
|
||||
if (context.libModules.contains(currentModuleName)) {
|
||||
|
||||
List<String> dependenciesNames = context.dependencyGraph
|
||||
.getDestinationElements(moduleDeclaration.getName());
|
||||
dependenciesNamesString = "";
|
||||
if (dependenciesNames != null) {
|
||||
for (int i = 0; i < dependenciesNames.size(); i++) {
|
||||
dependenciesNames.set(i, "\"" + dependenciesNames.get(i) + "\"");
|
||||
}
|
||||
dependenciesNamesString = join(dependenciesNames, ",");
|
||||
}
|
||||
}
|
||||
File f = new File(outputDir, currentModuleName.replace('.', '/') + "/package-info.java");
|
||||
f.getParentFile().mkdirs();
|
||||
try {
|
||||
if (dependenciesNamesString != null) {
|
||||
FileUtils.write(f, //
|
||||
"/** This package contains the " + moduleDeclaration.getName()
|
||||
+ " library (source: Definitely Typed). */\n");
|
||||
|
||||
String mixins = "";
|
||||
if (context.getMixins(currentModuleName) != null) {
|
||||
mixins = StringUtils.join(
|
||||
context.getMixins(currentModuleName).stream().map(t -> context.getTypeName(t)).toArray(),
|
||||
".class,") + ".class";
|
||||
}
|
||||
FileUtils.write(f, "@" + JSweetDefTranslatorConfig.ANNOTATION_ROOT + "(dependencies={"
|
||||
+ dependenciesNamesString + "}, mixins={" + mixins + "})\n", true);
|
||||
} else {
|
||||
FileUtils.write(f, //
|
||||
"/** (source: Definitely Typed) */\n");
|
||||
}
|
||||
CharSequence annosDecls = annotationsToString(moduleDeclaration);
|
||||
if (!isBlank(annosDecls)) {
|
||||
FileUtils.write(f, annosDecls, true);
|
||||
}
|
||||
if (context.externalModules.keySet().contains(currentModuleName)) {
|
||||
FileUtils.write(f, "@" + JSweetDefTranslatorConfig.ANNOTATION_MODULE + "(\""
|
||||
+ context.externalModules.get(currentModuleName) + "\")\n", true);
|
||||
}
|
||||
FileUtils.write(f, "package " + currentModuleName + ";\n", true);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
scan(moduleDeclaration.getMembers());
|
||||
}
|
||||
|
||||
private void printDocumentation(Declaration declaration) {
|
||||
if (declaration.getDocumentation() != null) {
|
||||
printIndent().print(declaration.getDocumentation()).println();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeDeclaration(TypeDeclaration typeDeclaration) {
|
||||
// typeDeclaration.setName(toJavaDeclarationName(typeDeclaration.getName()));
|
||||
if (typeDeclaration.isExternal()) {
|
||||
return;
|
||||
}
|
||||
boolean innerType = getParent() instanceof TypeDeclaration;
|
||||
|
||||
StringBuilder mergedSuperTypeList = new StringBuilder();
|
||||
if (typeDeclaration.getMergedSuperTypes() != null) {
|
||||
for (TypeReference type : typeDeclaration.getMergedSuperTypes()) {
|
||||
mergedSuperTypeList.append(type.getName() + ".class,");
|
||||
}
|
||||
if (mergedSuperTypeList.length() > 1) {
|
||||
mergedSuperTypeList.deleteCharAt(mergedSuperTypeList.length() - 1);
|
||||
typeDeclaration.addStringAnnotation(
|
||||
JSweetDefTranslatorConfig.ANNOTATION_EXTENDS + "({" + mergedSuperTypeList.toString() + "})");
|
||||
}
|
||||
}
|
||||
if (!innerType) {
|
||||
clearOutput();
|
||||
currentModuleName = getCurrentModuleName();
|
||||
|
||||
print("package " + currentModuleName + ";").println();
|
||||
|
||||
// dynamically create imports
|
||||
Set<String> imports = new HashSet<String>();
|
||||
new Scanner(this) {
|
||||
@Override
|
||||
public void visitTypeReference(TypeReference typeReference) {
|
||||
TypeDeclaration enclosingTypeDecl = getParent(TypeDeclaration.class);
|
||||
if (typeReference.getName() != null && enclosingTypeDecl != null
|
||||
&& typeReference.getName().equals(enclosingTypeDecl.getName())) {
|
||||
return;
|
||||
}
|
||||
|
||||
Type t = lookupType(typeReference, null);
|
||||
if (t instanceof TypeDeclaration) {
|
||||
TypeDeclaration typeDeclaration = (TypeDeclaration) t;
|
||||
String name = context.getTypeName(typeDeclaration);
|
||||
if (!typeDeclaration.isExternal() && name != null
|
||||
&& !(typeReference.getName().contains(".") && typeReference.getName().equals(name))) {
|
||||
imports.add(name);
|
||||
}
|
||||
}
|
||||
super.visitTypeReference(typeReference);
|
||||
}
|
||||
}.visitTypeDeclaration(typeDeclaration);
|
||||
List<String> importShortNames = imports.stream().map(name -> Util.getSimpleName(name))
|
||||
.collect(Collectors.toList());
|
||||
List<String> clashes = new ArrayList<>();
|
||||
for (String typeName : imports) {
|
||||
if (!typeName.startsWith(currentModuleName + ".")) {
|
||||
if (typeName.contains(".")) {
|
||||
if (Collections.frequency(importShortNames, Util.getSimpleName(typeName)) > 1) {
|
||||
clashes.add(typeName);
|
||||
} else {
|
||||
print("import ").print(typeName).print(";").println();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (String clash : clashes) {
|
||||
new Scanner(this) {
|
||||
@Override
|
||||
public void visitTypeReference(TypeReference typeReference) {
|
||||
TypeDeclaration enclosingTypeDecl = getParent(TypeDeclaration.class);
|
||||
if (typeReference.getName() != null && enclosingTypeDecl != null
|
||||
&& typeReference.getName().equals(enclosingTypeDecl.getName())) {
|
||||
return;
|
||||
}
|
||||
|
||||
Type t = lookupType(typeReference, null);
|
||||
if (t instanceof TypeDeclaration) {
|
||||
TypeDeclaration typeDeclaration = (TypeDeclaration) t;
|
||||
String name = context.getTypeName(typeDeclaration);
|
||||
if (clash.equals(name)) {
|
||||
typeReference.setName(name);
|
||||
}
|
||||
}
|
||||
super.visitTypeReference(typeReference);
|
||||
}
|
||||
}.visitTypeDeclaration(typeDeclaration);
|
||||
}
|
||||
|
||||
printDocumentation(typeDeclaration);
|
||||
printAnnotations(typeDeclaration);
|
||||
print("public ");
|
||||
} else {
|
||||
printDocumentation(typeDeclaration);
|
||||
printAnnotations(typeDeclaration);
|
||||
printIndent().print("public ");
|
||||
}
|
||||
if (typeDeclaration.hasModifier("static")) {
|
||||
print("static ");
|
||||
}
|
||||
if (typeDeclaration.hasModifier("abstract")) {
|
||||
print("abstract ");
|
||||
}
|
||||
if (JSweetDefTranslatorConfig.GLOBALS_CLASS_NAME.equals(typeDeclaration.getName())) {
|
||||
print("final ");
|
||||
}
|
||||
print(typeDeclaration.getKind() + " ");
|
||||
printIdentifier(typeDeclaration.getName());
|
||||
printTypeParameters(typeDeclaration.getTypeParameters(), false);
|
||||
if ("interface".equals(typeDeclaration.getKind())) {
|
||||
if (typeDeclaration.getSuperTypes() != null && typeDeclaration.getSuperTypes().length > 0) {
|
||||
for (TypeReference r : typeDeclaration.getSuperTypes()) {
|
||||
TypeDeclaration t = (TypeDeclaration) lookupType(r, null);
|
||||
if ("interface".equals(t.getKind())) {
|
||||
print(" extends ").print(typeDeclaration.getSuperTypes()[0]);
|
||||
} else {
|
||||
context.reportError("wrong subclassing link between " + typeDeclaration.getName() + " and "
|
||||
+ t.getName() + " at " + typeDeclaration.getToken().getLocation());
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if ("class".equals(typeDeclaration.getKind())) {
|
||||
List<TypeReference> extendList = new ArrayList<TypeReference>();
|
||||
List<TypeReference> implementList = new ArrayList<TypeReference>();
|
||||
if (typeDeclaration.getSuperTypes() != null && typeDeclaration.getSuperTypes().length > 0) {
|
||||
for (TypeReference r : typeDeclaration.getSuperTypes()) {
|
||||
TypeDeclaration t = (TypeDeclaration) lookupType(r, null);
|
||||
if (t != null) {
|
||||
if ("interface".equals(t.getKind())) {
|
||||
implementList.add(r);
|
||||
} else {
|
||||
extendList.add(r);
|
||||
}
|
||||
} else {
|
||||
logger.warn("unresolved inheritance reference: " + r);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (extendList.size() > 1) {
|
||||
|
||||
context.reportError(
|
||||
"multiple inheritance should not appear at this stage for " + typeDeclaration.getName() + " at "
|
||||
+ typeDeclaration.getToken().getLocation() + " extends=" + extendList);
|
||||
} else if (extendList.size() == 1) {
|
||||
print(" extends ").print(extendList.get(0));
|
||||
} else if (!JSweetDefTranslatorConfig.isJDKReplacementMode()
|
||||
&& !((JSweetDefTranslatorConfig.getObjectClassName())
|
||||
.equals(currentModuleName + "." + typeDeclaration.getName()))) {
|
||||
print(" extends ").print(JSweetDefTranslatorConfig.getObjectClassName());
|
||||
}
|
||||
if (!implementList.isEmpty()) {
|
||||
print(" implements ");
|
||||
for (TypeReference r : implementList) {
|
||||
print(r);
|
||||
print(", ");
|
||||
}
|
||||
removeLastChars(2);
|
||||
}
|
||||
}
|
||||
|
||||
print(" {");
|
||||
println().startIndent();
|
||||
scan(typeDeclaration.getMembers());
|
||||
endIndent();
|
||||
printIndent().print("}").println();
|
||||
if (!innerType) {
|
||||
String typeName = currentModuleName + "." + typeDeclaration.getName();
|
||||
File outputFile = new File(outputDir, typeName.replace('.', '/') + ".java");
|
||||
writeToFile(outputFile, getResult());
|
||||
}
|
||||
}
|
||||
|
||||
private void writeToFile(File f, String output) {
|
||||
f.getParentFile().mkdirs();
|
||||
if (f.exists()) {
|
||||
logger.warn(f + " already exists!!");
|
||||
}
|
||||
|
||||
try {
|
||||
try (PrintWriter out = new PrintWriter(f.getPath())) {
|
||||
out.println(output);
|
||||
out.close();
|
||||
logger.trace("wrote " + f);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private JavaDefModelPrinter printTypeParameters(TypeParameterDeclaration[] typeParameters, boolean whitespace) {
|
||||
if (typeParameters != null && typeParameters.length > 0) {
|
||||
print("<");
|
||||
for (TypeParameterDeclaration t : typeParameters) {
|
||||
print(t);
|
||||
print(",");
|
||||
}
|
||||
if (typeParameters.length > 0) {
|
||||
removeLastChar();
|
||||
}
|
||||
print(">");
|
||||
if (whitespace) {
|
||||
print(" ");
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
private String getTypeInitalValue(String typeName) {
|
||||
if (typeName == null) {
|
||||
return "null";
|
||||
}
|
||||
switch (typeName) {
|
||||
case "void":
|
||||
return null;
|
||||
case "boolean":
|
||||
return "false";
|
||||
case "number":
|
||||
return "0";
|
||||
default:
|
||||
return "null";
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionDeclaration(FunctionDeclaration functionDeclaration) {
|
||||
printDocumentation(functionDeclaration);
|
||||
TypeDeclaration owningType = getParent(TypeDeclaration.class);
|
||||
// boolean hasConstructor = owningType != null &&
|
||||
// owningType.hasConstructor;
|
||||
String name = DeclarationHelper.getActualFunctionName(functionDeclaration);
|
||||
if (name != null && !name.equals(functionDeclaration.getName())) {
|
||||
functionDeclaration.addStringAnnotation(
|
||||
JSweetDefTranslatorConfig.ANNOTATION_NAME + "(\"" + functionDeclaration.getName() + "\")");
|
||||
}
|
||||
printAnnotations(functionDeclaration).printIndent();
|
||||
boolean isNative = false;
|
||||
if (owningType != null && !owningType.getKind().equals("interface") && !functionDeclaration.isConstructor()) {
|
||||
print("native ");
|
||||
isNative = true;
|
||||
}
|
||||
if (!functionDeclaration.isConstructor()) {
|
||||
print("public ");
|
||||
}
|
||||
boolean isInterface = (owningType != null && owningType.isInterface());
|
||||
boolean isStatic = false;
|
||||
if (functionDeclaration.hasModifier("static")) {
|
||||
isStatic = true;
|
||||
print("static ");
|
||||
}
|
||||
if (functionDeclaration.isConstructor()) {
|
||||
if (JSweetDefTranslatorConfig.GLOBALS_CLASS_NAME.equals(owningType.getName())) {
|
||||
print("private ");
|
||||
} else {
|
||||
if (functionDeclaration.hasModifier("protected")) {
|
||||
print("protected ");
|
||||
} else if (functionDeclaration.hasModifier("private")) {
|
||||
print("private ");
|
||||
} else {
|
||||
print("public ");
|
||||
}
|
||||
}
|
||||
if (functionDeclaration.getTypeParameters() != null) {
|
||||
List<TypeParameterDeclaration> typeParameters = new ArrayList<>(
|
||||
asList(functionDeclaration.getTypeParameters()));
|
||||
if (owningType.getTypeParameters() != null) {
|
||||
typeParameters.removeAll(asList(owningType.getTypeParameters()));
|
||||
}
|
||||
printTypeParameters(typeParameters.toArray(new TypeParameterDeclaration[0]), true);
|
||||
}
|
||||
print(owningType.getName());
|
||||
} else {
|
||||
printTypeParameters(functionDeclaration.getTypeParameters(), true);
|
||||
switch (functionDeclaration.getName()) {
|
||||
case JSweetDefTranslatorConfig.INDEXED_GET_FUCTION_NAME:
|
||||
case JSweetDefTranslatorConfig.INDEXED_SET_FUCTION_NAME:
|
||||
case JSweetDefTranslatorConfig.INDEXED_DELETE_FUCTION_NAME:
|
||||
if (Util.wrapTypeMap.containsKey(functionDeclaration.getType().getName())) {
|
||||
print(Util.wrapTypeMap.get(functionDeclaration.getType().getName())).print(" ");
|
||||
} else {
|
||||
print(functionDeclaration.getType()).print(" ");
|
||||
}
|
||||
if (isStatic) {
|
||||
print(functionDeclaration.getName() + "Static");
|
||||
} else {
|
||||
printFunctionName(functionDeclaration.getName());
|
||||
}
|
||||
break;
|
||||
default:
|
||||
print(functionDeclaration.getType()).print(" ");
|
||||
printFunctionName(name);
|
||||
}
|
||||
}
|
||||
print("(");
|
||||
for (VariableDeclaration t : functionDeclaration.getParameters()) {
|
||||
print(t);
|
||||
print(", ");
|
||||
}
|
||||
if (functionDeclaration.getParameters().length > 0) {
|
||||
removeLastChars(2);
|
||||
}
|
||||
print(")");
|
||||
if (isNative || (isInterface && !isStatic)) {
|
||||
print(";");
|
||||
} else {
|
||||
if (functionDeclaration.isConstructor()) {
|
||||
print("{}");
|
||||
} else {
|
||||
print("{");
|
||||
String typeName = functionDeclaration.getType().getName();
|
||||
if (typeName == null) {
|
||||
typeName = "Object";
|
||||
}
|
||||
String initialValue = getTypeInitalValue(typeName);
|
||||
if (initialValue != null) {
|
||||
print("return " + initialValue + ";");
|
||||
}
|
||||
print("}");
|
||||
}
|
||||
}
|
||||
println();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitVariableDeclaration(VariableDeclaration variableDeclaration) {
|
||||
TypeDeclaration owningType = getParent(TypeDeclaration.class);
|
||||
printDocumentation(variableDeclaration);
|
||||
printAnnotations(variableDeclaration);
|
||||
if (variableDeclaration.isOptional() && owningType != null) {
|
||||
printIndent().print("@" + JSweetDefTranslatorConfig.ANNOTATION_OPTIONAL).println();
|
||||
}
|
||||
if (owningType != null && "enum".equals(owningType.getKind())) {
|
||||
printIndent().print(variableDeclaration.getName());
|
||||
print(",").println();
|
||||
} else {
|
||||
printIndent().print("public ");
|
||||
if (variableDeclaration.hasModifier("static")) {
|
||||
print("static ");
|
||||
}
|
||||
if (variableDeclaration.isReadonly()) {
|
||||
print("final ");
|
||||
}
|
||||
print(variableDeclaration.getType());
|
||||
print(" ");
|
||||
printIdentifier(variableDeclaration.getName());
|
||||
if (owningType != null && "interface".equals(owningType.getKind()) || variableDeclaration.isReadonly()) {
|
||||
String typeName = variableDeclaration.getType().getName();
|
||||
String initialValue = getTypeInitalValue(typeName);
|
||||
if (initialValue != null) {
|
||||
print("=" + initialValue);
|
||||
}
|
||||
}
|
||||
print(";").println();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitParameterDeclaration(ParameterDeclaration parameterDeclaration) {
|
||||
printDocumentation(parameterDeclaration);
|
||||
if (parameterDeclaration.isVarargs()) {
|
||||
if (Util.hasTypeParameterReferences(context, parameterDeclaration.getType())) {
|
||||
print("@SuppressWarnings(\"unchecked\") ");
|
||||
}
|
||||
if (parameterDeclaration.getType().isArray()) {
|
||||
print(parameterDeclaration.getType().getComponentType());
|
||||
} else {
|
||||
print(parameterDeclaration.getType());
|
||||
}
|
||||
print("...");
|
||||
} else {
|
||||
print(parameterDeclaration.getType());
|
||||
}
|
||||
print(" ");
|
||||
printIdentifier(parameterDeclaration.getName());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration) {
|
||||
String name = toJavaTypeName(typeParameterDeclaration.getName());
|
||||
print(name);
|
||||
if (typeParameterDeclaration.getUpperBound() != null) {
|
||||
print(" extends ").print(typeParameterDeclaration.getUpperBound());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeReference(TypeReference typeReference) {
|
||||
if (typeReference.isObjectType()) {
|
||||
logger.error(
|
||||
"object types are not allowed at this point: " + getCurrentContainerName() + ":" + getParent());
|
||||
return;
|
||||
}
|
||||
if ("this".equals(typeReference.getName())) {
|
||||
print(getParent(TypeDeclaration.class).getName());
|
||||
} else {
|
||||
String name = toJavaTypeName(typeReference.getName());
|
||||
if (Util.coreTypeMap.containsKey(typeReference.getName())
|
||||
&& !JSweetDefTranslatorConfig.isJDKReplacementMode()
|
||||
&& JSweetDefTranslatorConfig.LANG_PACKAGE.equals(currentModuleName)) {
|
||||
print("java.lang.");
|
||||
print(name);
|
||||
} else {
|
||||
print(name);
|
||||
}
|
||||
}
|
||||
if (typeReference.getTypeArguments() != null) {
|
||||
boolean functionalTypeReference = isFunctionalTypeReference(typeReference);
|
||||
boolean superTypeReference = isSuperTypeReference(typeReference);
|
||||
print("<");
|
||||
for (TypeReference t : typeReference.getTypeArguments()) {
|
||||
if (!superTypeReference && !functionalTypeReference && ("any".equals(t.getName())
|
||||
|| (t instanceof UnionTypeReference && "java.lang.Object".equals(t.getName())))) {
|
||||
print("?");
|
||||
} else {
|
||||
print(t);
|
||||
}
|
||||
print(",");
|
||||
}
|
||||
if (typeReference.getTypeArguments().length > 0) {
|
||||
removeLastChar();
|
||||
}
|
||||
print(">");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionalTypeReference(FunctionalTypeReference functionalTypeReference) {
|
||||
// functional interfaces should have been generated at this point
|
||||
print("<functional_type_error>");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitArrayTypeReference(ArrayTypeReference arrayTypeReference) {
|
||||
print(arrayTypeReference.getComponentType());
|
||||
if (!arrayTypeReference.isDisableArray()) {
|
||||
print("[]");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitUnionTypeReference(UnionTypeReference unionTypeReference) {
|
||||
switch (unionTypeReference.getSelected()) {
|
||||
case NONE:
|
||||
case PENDING:
|
||||
// union types should have been expanded at this point
|
||||
print("<union_type_error>");
|
||||
break;
|
||||
case LEFT:
|
||||
print(unionTypeReference.getLeftType());
|
||||
break;
|
||||
case RIGHT:
|
||||
print(unionTypeReference.getRightType());
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onScanEnded() {
|
||||
for (QualifiedDeclaration<ModuleDeclaration> moduleDeclaration : context
|
||||
.findDeclarations(ModuleDeclaration.class, "*")) {
|
||||
String module = context.getModuleName(moduleDeclaration.getDeclaration());
|
||||
if (context.moduleDocumentations.containsKey(module)) {
|
||||
System.out.println("generating package-info.java for " + module);
|
||||
File f = new File(outputDir, module.replace('.', '/') + "/package-info.java");
|
||||
f.getParentFile().mkdirs();
|
||||
try {
|
||||
FileUtils.write(f, context.moduleDocumentations.get(module) + "\npackage " + module + ";", false);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,78 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.Declaration;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.ModuleDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
|
||||
public class ModuleToTypeMerger extends Scanner {
|
||||
|
||||
public ModuleToTypeMerger(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitModuleDeclaration(ModuleDeclaration moduleDeclaration) {
|
||||
if (moduleDeclaration.getName().contains("-")) {
|
||||
context.reportWarning("invalid module name " + moduleDeclaration.getName() + " at "
|
||||
+ moduleDeclaration.getToken().getLocation());
|
||||
moduleDeclaration.setHidden(true);
|
||||
return;
|
||||
}
|
||||
String fullName = getCurrentModuleName();
|
||||
TypeDeclaration type = context.getTypeDeclaration(fullName);
|
||||
boolean hideType = false;
|
||||
boolean hideModule = true;
|
||||
if (type != null) {
|
||||
// for (Declaration declaration : moduleDeclaration.getMembers()) {
|
||||
// if (!(declaration instanceof VariableDeclaration || declaration instanceof FunctionDeclaration
|
||||
// || (declaration instanceof TypeDeclaration))) {
|
||||
// hideType = true;
|
||||
// logger.warn("submodule '" + declaration.getName()
|
||||
// + "' found while merging module into class... erase class and keep modules at "
|
||||
// + declaration.getToken().getLocation());
|
||||
// moduleDeclaration.addMembers(type.getMembers());
|
||||
// type.setHidden(true);
|
||||
// context.unregisterType(type);
|
||||
// hideType = true;
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
if (!hideType) {
|
||||
for (Declaration declaration : moduleDeclaration.getMembers()) {
|
||||
if (declaration instanceof VariableDeclaration || declaration instanceof FunctionDeclaration
|
||||
/*|| (declaration instanceof TypeDeclaration)*/) {
|
||||
type.addMember(declaration);
|
||||
moduleDeclaration.removeMember(declaration);
|
||||
if(!(declaration instanceof TypeDeclaration)) {
|
||||
declaration.addModifier("static");
|
||||
}
|
||||
} else {
|
||||
logger.warn("cannot merge declaration '" + declaration.getName()
|
||||
+ "' "
|
||||
+ declaration.getToken().getLocation());
|
||||
hideModule = false;
|
||||
}
|
||||
}
|
||||
if(hideModule) {
|
||||
moduleDeclaration.setHidden(true);
|
||||
} else {
|
||||
context.setTypeClashingWithModule(context.getTypeName(type));
|
||||
}
|
||||
}
|
||||
}
|
||||
super.visitModuleDeclaration(moduleDeclaration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitVariableDeclaration(VariableDeclaration variableDeclaration) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionDeclaration(FunctionDeclaration functionDeclaration) {
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,66 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import static org.jsweet.JSweetDefTranslatorConfig.STRING_TYPES_INTERFACE_NAME;
|
||||
import static org.jsweet.input.typescriptdef.util.Util.checkAndAdjustDeclarationName;
|
||||
import static org.jsweet.input.typescriptdef.util.Util.toJavaName;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.ModuleDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeReference;
|
||||
|
||||
public class NameAdapter extends Scanner {
|
||||
|
||||
public NameAdapter(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
public NameAdapter(Scanner parentScanner) {
|
||||
super(parentScanner);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitModuleDeclaration(ModuleDeclaration declaration) {
|
||||
checkAndAdjustDeclarationName(declaration, true);
|
||||
if (declaration.isQuotedName()) {
|
||||
context.externalModules.put(getCurrentModuleName(), declaration.getOriginalName());
|
||||
}
|
||||
super.visitModuleDeclaration(declaration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeReference(TypeReference typeReference) {
|
||||
String adaptedName = getAdaptedName(typeReference);
|
||||
if (adaptedName != null) {
|
||||
typeReference.setName(adaptedName);
|
||||
}
|
||||
super.visitTypeReference(typeReference);
|
||||
}
|
||||
|
||||
private String getAdaptedName(TypeReference typeReference) {
|
||||
String simpleName = typeReference.getSimpleName();
|
||||
String qualifier = typeReference.getQualifier();
|
||||
TypeDeclaration type = context.getTypeDeclaration(qualifier);
|
||||
boolean innerType = type != null && !context.isTypeClashingWithModule(qualifier);
|
||||
String newSimpleName = toJavaName(simpleName);
|
||||
if (innerType) {
|
||||
return getAdaptedName(new TypeReference(null, qualifier, null)) + "." + newSimpleName;
|
||||
} else {
|
||||
if (qualifier != null && !qualifier.endsWith(STRING_TYPES_INTERFACE_NAME)) {
|
||||
String newQualifier = null;
|
||||
if (qualifier != null) {
|
||||
newQualifier = Arrays.stream(qualifier.split("\\.")).map(name -> toJavaName(name, true))
|
||||
.collect(Collectors.joining("."));
|
||||
}
|
||||
return newQualifier + "." + newSimpleName;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,91 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import static org.jsweet.input.typescriptdef.util.Util.checkAndAdjustDeclarationName;
|
||||
import static org.jsweet.input.typescriptdef.util.Util.toJavaName;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.ModuleDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.ReferenceDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeParameterDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeReference;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
|
||||
/**
|
||||
* This scanner checks that declaration names are valid Java identifiers and
|
||||
* change the names when not valid. The original names are kept in {@link Name}
|
||||
* annotations, which are added to the modified declarations.
|
||||
*/
|
||||
public class NameChecker extends Scanner {
|
||||
|
||||
public NameChecker(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
public NameChecker(Scanner parentScanner) {
|
||||
super(parentScanner);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitModuleDeclaration(ModuleDeclaration moduleDeclaration) {
|
||||
checkAndAdjustDeclarationName(moduleDeclaration);
|
||||
super.visitModuleDeclaration(moduleDeclaration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeDeclaration(TypeDeclaration typeDeclaration) {
|
||||
checkAndAdjustDeclarationName(typeDeclaration);
|
||||
super.visitTypeDeclaration(typeDeclaration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitVariableDeclaration(VariableDeclaration variableDeclaration) {
|
||||
checkAndAdjustDeclarationName(variableDeclaration);
|
||||
super.visitVariableDeclaration(variableDeclaration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionDeclaration(FunctionDeclaration functionDeclaration) {
|
||||
checkAndAdjustDeclarationName(functionDeclaration);
|
||||
super.visitFunctionDeclaration(functionDeclaration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitReferenceDeclaration(ReferenceDeclaration referenceDeclaration) {
|
||||
referenceDeclaration.setName(toJavaName(referenceDeclaration.getName()));
|
||||
referenceDeclaration.setReferencedName(toJavaName(referenceDeclaration.getReferencedName()));
|
||||
super.visitReferenceDeclaration(referenceDeclaration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration) {
|
||||
typeParameterDeclaration.setName(toJavaName(typeParameterDeclaration.getName()));
|
||||
super.visitTypeParameterDeclaration(typeParameterDeclaration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeReference(TypeReference typeReference) {
|
||||
if (!"this".equals(typeReference.getName())) {
|
||||
String simpleName = typeReference.getSimpleName();
|
||||
String qualifier = typeReference.getQualifier();
|
||||
String newSimpleName = toJavaName(simpleName);
|
||||
if (qualifier == null) {
|
||||
typeReference.setName(newSimpleName);
|
||||
} else {
|
||||
String newQualifier = null;
|
||||
if (qualifier != null) {
|
||||
newQualifier = Arrays.stream(qualifier.split("\\.")).map(name -> toJavaName(name))
|
||||
.collect(Collectors.joining("."));
|
||||
}
|
||||
typeReference.setName(newQualifier + "." + newSimpleName);
|
||||
}
|
||||
}
|
||||
super.visitTypeReference(typeReference);
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,164 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.jsweet.JSweetDefTranslatorConfig;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.Declaration;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationContainer;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationHelper;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeMacroDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeParameterDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeReference;
|
||||
import org.jsweet.input.typescriptdef.ast.TypedDeclaration;
|
||||
import org.jsweet.input.typescriptdef.util.Util;
|
||||
|
||||
public class ObjectTypeCreator extends Scanner {
|
||||
|
||||
public ObjectTypeCreator(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
private class NameConflictFinder extends Scanner {
|
||||
private String name;
|
||||
public boolean conflict = false;
|
||||
|
||||
public NameConflictFinder(Context context, String name) {
|
||||
super(context);
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeReference(TypeReference typeReference) {
|
||||
if (name.equals(typeReference.getName())) {
|
||||
conflict = true;
|
||||
}
|
||||
super.visitTypeReference(typeReference);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeMacro(TypeMacroDeclaration typeMacroDeclaration) {
|
||||
if (name.equals(typeMacroDeclaration.getName())) {
|
||||
conflict = true;
|
||||
}
|
||||
super.visitTypeMacro(typeMacroDeclaration);
|
||||
}
|
||||
};
|
||||
|
||||
private static String[] suffixes = { "Object", "Data", "Dto", "Structure", "Info" };
|
||||
|
||||
private static String getSuffix(int i) {
|
||||
if (i < suffixes.length) {
|
||||
return suffixes[i];
|
||||
} else {
|
||||
return "" + (i + 1 - suffixes.length);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeReference(TypeReference typeReference) {
|
||||
if (typeReference.isObjectType()) {
|
||||
DeclarationContainer container = getParent(t -> {
|
||||
return (t instanceof DeclarationContainer) && !(t instanceof TypeMacroDeclaration);
|
||||
});
|
||||
TypedDeclaration parentDeclaration = getParent(TypedDeclaration.class);
|
||||
if (typeReference.getObjectType().getMembers().length == 0) {
|
||||
Util.substituteTypeReference(this, parentDeclaration, typeReference,
|
||||
new TypeReference(null, Object.class.getName(), null));
|
||||
} else {
|
||||
|
||||
String rootName = StringUtils.capitalize(parentDeclaration.getName());
|
||||
String name = rootName;
|
||||
int i = 1;
|
||||
|
||||
TypeParameterDeclaration[] typeParameters = Util.findTypeParameters(this, typeReference);
|
||||
for (TypeParameterDeclaration p : typeParameters) {
|
||||
if (Util.containsAstNode(typeReference, p)) {
|
||||
typeParameters = ArrayUtils.remove(typeParameters, ArrayUtils.indexOf(typeParameters, p));
|
||||
}
|
||||
}
|
||||
if (typeParameters.length == 0) {
|
||||
typeParameters = null;
|
||||
}
|
||||
TypeDeclaration newClass = null;
|
||||
|
||||
while (newClass == null) {
|
||||
// first check that no type of the same level has the same
|
||||
// name
|
||||
TypeDeclaration conflictingType = container.findType(name);
|
||||
boolean conflict = false;
|
||||
if (conflictingType != null) {
|
||||
for (Declaration member : typeReference.getObjectType().getMembers()) {
|
||||
if (!ArrayUtils.contains(conflictingType.getMembers(), member)) {
|
||||
conflict = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!conflict) {
|
||||
newClass = conflictingType;
|
||||
} else {
|
||||
name = rootName + getSuffix(i++);
|
||||
}
|
||||
} else {
|
||||
// check enclosing types names (in Java, enclosed types
|
||||
// cannot be named like an enclosing one)
|
||||
List<TypeDeclaration> parents = getParents(TypeDeclaration.class);
|
||||
for (TypeDeclaration parent : parents) {
|
||||
if (name.equals(parent.getName())) {
|
||||
conflict = true;
|
||||
}
|
||||
}
|
||||
if (!conflict) {
|
||||
NameConflictFinder finder = new NameConflictFinder(context, name);
|
||||
container.accept(finder);
|
||||
conflict = finder.conflict;
|
||||
}
|
||||
if (conflict) {
|
||||
name = rootName + getSuffix(i++);
|
||||
} else {
|
||||
// finally, no conflict, we create the class
|
||||
newClass = new TypeDeclaration(null, "class", name, DeclarationHelper.copy(typeParameters),
|
||||
null, null);
|
||||
newClass.setDocumentation(
|
||||
"/** This is an automatically generated object type (see the source definition). */");
|
||||
if (container instanceof TypeDeclaration) {
|
||||
newClass.addModifier("static");
|
||||
}
|
||||
newClass.addMembers(typeReference.getObjectType().getMembers());
|
||||
newClass.addStringAnnotation(JSweetDefTranslatorConfig.ANNOTATION_OBJECT_TYPE);
|
||||
container.addMember(newClass);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String objectTypeFullName = getCurrentContainerName() + "." + newClass.getName();
|
||||
|
||||
logger.trace("registering object type: " + objectTypeFullName + " in container " + container + " ("
|
||||
+ container.getClass().getSimpleName() + ")");
|
||||
List<TypeDeclaration> containerGeneratedTypes = context.generatedObjectTypes.get(container);
|
||||
if (containerGeneratedTypes == null) {
|
||||
context.generatedObjectTypes.put(container,
|
||||
containerGeneratedTypes = new LinkedList<TypeDeclaration>());
|
||||
}
|
||||
containerGeneratedTypes.add(newClass);
|
||||
|
||||
// parentDeclaration.setType(new TypeReference(null,
|
||||
// newClass.getName(), DeclarationHelper
|
||||
// .toTypeArguments(typeParameters)));
|
||||
|
||||
Util.substituteTypeReference(this, parentDeclaration, typeReference,
|
||||
new TypeReference(null, newClass.getName(), DeclarationHelper.toTypeArguments(typeParameters)));
|
||||
context.registerType(objectTypeFullName, newClass);
|
||||
// recursively scan the newly created class
|
||||
scan(newClass);
|
||||
}
|
||||
}
|
||||
scan(typeReference.getTypeArguments());
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,164 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import static org.apache.commons.lang3.StringUtils.defaultString;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.jsweet.input.typescriptdef.ast.CompilationUnit;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationContainer;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationHelper;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.Type;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeReference;
|
||||
import org.jsweet.input.typescriptdef.ast.TypedDeclaration;
|
||||
import org.jsweet.input.typescriptdef.util.Util;
|
||||
|
||||
public class ObjectTypeDuplicateMerger extends Scanner {
|
||||
|
||||
public ObjectTypeDuplicateMerger(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
Map<String, TypeDeclaration> duplicatesToReplace;
|
||||
|
||||
@Override
|
||||
public void visitCompilationUnit(CompilationUnit compilationUnit) {
|
||||
DuplicateCollector collector = new DuplicateCollector(context);
|
||||
compilationUnit.accept(collector);
|
||||
duplicatesToReplace = collector.replacements;
|
||||
if (duplicatesToReplace.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
logger.debug(compilationUnit + " object types replacements: " + duplicatesToReplace);
|
||||
|
||||
super.visitCompilationUnit(compilationUnit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeDeclaration(TypeDeclaration typeDeclaration) {
|
||||
String qualifiedName = getCurrentContainerName();
|
||||
TypeDeclaration replacement = duplicatesToReplace.get(qualifiedName);
|
||||
if (replacement != null) {
|
||||
DeclarationContainer container = getParent(DeclarationContainer.class);
|
||||
logger.trace("replace " + qualifiedName + " with " + context.getTypeName(replacement) + " in " + container);
|
||||
container.removeMember(typeDeclaration);
|
||||
} else {
|
||||
super.visitTypeDeclaration(typeDeclaration);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeReference(TypeReference typeReference) {
|
||||
String qualifiedName = getCurrentContainerName() + "." + typeReference.getName();
|
||||
TypeDeclaration replacement = duplicatesToReplace.get(qualifiedName);
|
||||
if (replacement == null) {
|
||||
replacement = duplicatesToReplace.get(qualifiedName = typeReference.getName());
|
||||
}
|
||||
|
||||
if (replacement != null) {
|
||||
logger.trace("replace reference " + qualifiedName + " with " + replacement);
|
||||
TypedDeclaration parentDeclaration = getParent(TypedDeclaration.class);
|
||||
Util.substituteTypeReference(this, parentDeclaration, typeReference, new TypeReference(null, replacement,
|
||||
typeReference.getTypeArguments()));
|
||||
}
|
||||
super.visitTypeReference(typeReference);
|
||||
}
|
||||
|
||||
private class DuplicateCollector extends Scanner {
|
||||
public DuplicateCollector(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
protected Map<String, TypeDeclaration> replacements = new HashMap<>();
|
||||
|
||||
@Override
|
||||
public void visitTypeDeclaration(TypeDeclaration typeDeclaration) {
|
||||
super.visitTypeDeclaration(typeDeclaration);
|
||||
|
||||
// TODO : this only a POC, how to handle duplicates within
|
||||
// moduleDeclaration ????
|
||||
List<TypeDeclaration> objectTypes = context.generatedObjectTypes.get(typeDeclaration);
|
||||
if (objectTypes != null) {
|
||||
for (TypeDeclaration objectType : objectTypes) {
|
||||
String qualifiedName = getCurrentContainerName() + "." + objectType;
|
||||
logger.trace("lookup duplicate of " + qualifiedName);
|
||||
TypeDeclaration match = searchTopMostDuplicateInParentHierarchy(typeDeclaration, objectType);
|
||||
if (match != null) {
|
||||
replacements.put(qualifiedName, match);
|
||||
logger.trace("most relevant match: " + match);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private TypeDeclaration searchTopMostDuplicateInParentHierarchy(TypeDeclaration owner,
|
||||
TypeDeclaration objectType) {
|
||||
if (objectType.getMembers() == null || objectType.getMembers().length == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
TypeDeclaration match = null;
|
||||
|
||||
List<TypeDeclaration> objectTypeMatches = context.generatedObjectTypes.get(owner);
|
||||
if (objectTypeMatches != null) {
|
||||
for (TypeDeclaration matchInCurrent : objectTypeMatches) {
|
||||
if (matchInCurrent != objectType && areObjectTypesEqual(matchInCurrent, objectType)) {
|
||||
match = matchInCurrent;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TypeReference[] superRefs = ((TypeDeclaration) owner).getSuperTypes();
|
||||
if (superRefs != null) {
|
||||
for (TypeReference superRef : superRefs) {
|
||||
Type superType = lookupType(superRef, context.getTypeModule(((TypeDeclaration) owner)));
|
||||
if (superType instanceof TypeDeclaration) {
|
||||
TypeDeclaration matchInSuperType = searchTopMostDuplicateInParentHierarchy(
|
||||
(TypeDeclaration) superType, objectType);
|
||||
if (matchInSuperType != null) {
|
||||
match = matchInSuperType;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return match;
|
||||
}
|
||||
|
||||
// TODO : externalize ???
|
||||
private boolean areObjectTypesEqual(TypeDeclaration left, TypeDeclaration right) {
|
||||
if (!defaultString(left.getName()).equals(defaultString(right.getName()))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
int leftTypeParametersCount = left.getTypeParameters() == null ? 0 : left.getTypeParameters().length;
|
||||
int rightTypeParametersCount = right.getTypeParameters() == null ? 0 : right.getTypeParameters().length;
|
||||
if (leftTypeParametersCount != rightTypeParametersCount) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// TODO : TypeParamDecl equals AND TypedDeclaration equals are not
|
||||
// correctly implemented .... (only name is checked)
|
||||
if (leftTypeParametersCount > 0
|
||||
&& !DeclarationHelper.areDeclarationsEqual(left.getTypeParameters(), right.getTypeParameters())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (left.getMembers() == null || right.getMembers() == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (left.getMembers().length != right.getMembers().length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return DeclarationHelper.areDeclarationsEqual(left.getMembers(), right.getMembers());
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,105 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationContainer;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationHelper;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionalTypeReference;
|
||||
import org.jsweet.input.typescriptdef.ast.ParameterDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeReference;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
|
||||
/**
|
||||
* This scanner makes functional type parameters and return optional in
|
||||
* functions.
|
||||
*
|
||||
* <p>
|
||||
* For instance: <code>f(p:A,B=>C)</code> will generate:
|
||||
*
|
||||
* <ul>
|
||||
* <li><code>f(p:(a:A,b:B)=>C)</code></li>
|
||||
* <li><code>f(p:(a:A,b:B)=>void)</code></li>
|
||||
* <li><code>f(p:()=>C)</code></li>
|
||||
* <li><code>f(p:()=>void)</code></li>
|
||||
* </ul>
|
||||
*
|
||||
* @author Renaud Pawlak
|
||||
*/
|
||||
public class OptionalLambdasParametersExpander extends Scanner {
|
||||
|
||||
int param = 0;
|
||||
|
||||
public OptionalLambdasParametersExpander(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
public OptionalLambdasParametersExpander(Scanner parent, int param) {
|
||||
super(parent);
|
||||
this.param = param;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionDeclaration(FunctionDeclaration functionDeclaration) {
|
||||
super.visitFunctionDeclaration(functionDeclaration);
|
||||
DeclarationContainer container = getParent(DeclarationContainer.class);
|
||||
for (int i = param; i < functionDeclaration.getParameters().length; i++) {
|
||||
if (functionDeclaration.getParameters()[i].getType() instanceof FunctionalTypeReference) {
|
||||
FunctionalTypeReference functionalType = (FunctionalTypeReference) functionDeclaration
|
||||
.getParameters()[i].getType();
|
||||
FunctionDeclaration voidFunction = null;
|
||||
FunctionalTypeReference voidFunctionalType = null;
|
||||
if (!"void".equals(functionalType.getReturnType().getName())) {
|
||||
voidFunctionalType = functionalType.copy();
|
||||
voidFunctionalType.setReturnType(new TypeReference(null, "void", null));
|
||||
voidFunction = createFunction(container, functionDeclaration, voidFunctionalType, i);
|
||||
new OptionalLambdasParametersExpander(this, param + 1).visitFunctionDeclaration(voidFunction);
|
||||
}
|
||||
if (functionalType.getParameters().length > 0) {
|
||||
FunctionalTypeReference truncatedFunctionalType = functionalType.copy();
|
||||
truncatedFunctionalType.setParameters(new ParameterDeclaration[0]);
|
||||
FunctionDeclaration truncatedFunction = createFunction(container, functionDeclaration,
|
||||
truncatedFunctionalType, i);
|
||||
new OptionalLambdasParametersExpander(this, param + 1).visitFunctionDeclaration(truncatedFunction);
|
||||
if (voidFunction != null) {
|
||||
truncatedFunctionalType = voidFunctionalType.copy();
|
||||
truncatedFunctionalType.setParameters(new ParameterDeclaration[0]);
|
||||
truncatedFunction = createFunction(container, functionDeclaration, truncatedFunctionalType, i);
|
||||
new OptionalLambdasParametersExpander(this, param + 1)
|
||||
.visitFunctionDeclaration(truncatedFunction);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitVariableDeclaration(VariableDeclaration variableDeclaration) {
|
||||
}
|
||||
|
||||
private FunctionDeclaration createFunction(DeclarationContainer container, FunctionDeclaration functionDeclaration,
|
||||
FunctionalTypeReference newParamType, int param) {
|
||||
FunctionDeclaration newFunction = new FunctionDeclaration(functionDeclaration.getToken(),
|
||||
functionDeclaration.getName(),
|
||||
functionDeclaration.getType() == null ? null : functionDeclaration.getType().copy(),
|
||||
DeclarationHelper.copy(functionDeclaration.getParameters()),
|
||||
DeclarationHelper.copy(functionDeclaration.getTypeParameters()));
|
||||
newFunction.getParameters()[param].setType(newParamType);
|
||||
newFunction.setDocumentation(functionDeclaration.getDocumentation());
|
||||
newFunction.setModifiers(functionDeclaration.getModifiers() == null ? null
|
||||
: new HashSet<String>(functionDeclaration.getModifiers()));
|
||||
if (functionDeclaration.getStringAnnotations() != null) {
|
||||
newFunction.setStringAnnotations(new ArrayList<>(functionDeclaration.getStringAnnotations()));
|
||||
}
|
||||
if (!ArrayUtils.contains(container.getMembers(), newFunction)) {
|
||||
container.addMember(newFunction);
|
||||
}
|
||||
return newFunction;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,48 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationContainer;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationHelper;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
|
||||
public class OptionalParametersExpander extends Scanner {
|
||||
|
||||
public OptionalParametersExpander(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionDeclaration(FunctionDeclaration functionDeclaration) {
|
||||
super.visitFunctionDeclaration(functionDeclaration);
|
||||
DeclarationContainer container = getParent(DeclarationContainer.class);
|
||||
for (int i = functionDeclaration.getParameters().length - 1; i >= 0; i--) {
|
||||
if (functionDeclaration.getParameters()[i].isOptional()) {
|
||||
FunctionDeclaration newFunction = new FunctionDeclaration(functionDeclaration.getToken(),
|
||||
functionDeclaration.getName(),
|
||||
functionDeclaration.getType() == null ? null : functionDeclaration.getType().copy(),
|
||||
DeclarationHelper.copy(ArrayUtils.subarray(functionDeclaration.getParameters(), 0, i)),
|
||||
DeclarationHelper.copy(functionDeclaration.getTypeParameters()));
|
||||
newFunction.setDocumentation(functionDeclaration.getDocumentation());
|
||||
newFunction.setModifiers(functionDeclaration.getModifiers() == null ? null
|
||||
: new HashSet<String>(functionDeclaration.getModifiers()));
|
||||
if (functionDeclaration.getStringAnnotations() != null) {
|
||||
newFunction.setStringAnnotations(new ArrayList<>(functionDeclaration.getStringAnnotations()));
|
||||
}
|
||||
if (!ArrayUtils.contains(container.getMembers(), newFunction)) {
|
||||
container.addMember(newFunction);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitVariableDeclaration(VariableDeclaration variableDeclaration) {
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,54 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationContainer;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationHelper;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionalTypeReference;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
|
||||
/**
|
||||
* Expands optional parameters in functional types.
|
||||
*
|
||||
* @author Renaud Pawlak
|
||||
*/
|
||||
public class OptionalParametersInFunctionalTypesExpander extends Scanner {
|
||||
|
||||
public OptionalParametersInFunctionalTypesExpander(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionDeclaration(FunctionDeclaration functionDeclaration) {
|
||||
super.visitFunctionDeclaration(functionDeclaration);
|
||||
DeclarationContainer container = getParent(DeclarationContainer.class);
|
||||
for (int i = functionDeclaration.getParameters().length - 1; i >= 0; i--) {
|
||||
if (functionDeclaration.getParameters()[i].getType() instanceof FunctionalTypeReference) {
|
||||
FunctionalTypeReference f = (FunctionalTypeReference) functionDeclaration.getParameters()[i].getType();
|
||||
for (int j = f.getParameters().length - 1; j >= 0; j--) {
|
||||
if (f.getParameters()[j].isOptional()) {
|
||||
FunctionalTypeReference newFunctionalType = new FunctionalTypeReference(null,
|
||||
f.getReturnType(), ArrayUtils.subarray(f.getParameters(), 0, j), null);
|
||||
FunctionDeclaration newFunction = new FunctionDeclaration(functionDeclaration.getToken(),
|
||||
functionDeclaration.getName(), functionDeclaration.getType(),
|
||||
DeclarationHelper.copy(functionDeclaration.getParameters()),
|
||||
functionDeclaration.getTypeParameters());
|
||||
newFunction.getParameters()[i].setType(newFunctionalType);
|
||||
newFunction.setDocumentation(functionDeclaration.getDocumentation());
|
||||
newFunction.setModifiers(functionDeclaration.getModifiers());
|
||||
if (!ArrayUtils.contains(container.getMembers(), newFunction)) {
|
||||
container.addMember(newFunction);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitVariableDeclaration(VariableDeclaration variableDeclaration) {
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,88 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
|
||||
import org.jsweet.JSweetDefTranslatorConfig;
|
||||
import org.jsweet.input.typescriptdef.TypescriptDef2Java;
|
||||
import org.jsweet.input.typescriptdef.ast.CompilationUnit;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.Declaration;
|
||||
import org.jsweet.input.typescriptdef.ast.ModuleDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.util.Util;
|
||||
|
||||
public class PackageOrganizer extends Scanner {
|
||||
|
||||
public PackageOrganizer(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitCompilationUnit(CompilationUnit compilationUnit) {
|
||||
ModuleDeclaration currentModule = null;
|
||||
|
||||
if (compilationUnit.getFile().getParentFile().getName().equals(TypescriptDef2Java.TS_CORE_LIB_DIR)) {
|
||||
// in case all files are placed in the core directory, discriminate
|
||||
// on the file name
|
||||
if (compilationUnit.getFile().getName().startsWith("lib.core")) {
|
||||
currentModule = new ModuleDeclaration(null, JSweetDefTranslatorConfig.LANG_PACKAGE, new Declaration[0]);
|
||||
} else {
|
||||
currentModule = new ModuleDeclaration(null, JSweetDefTranslatorConfig.DOM_PACKAGE, new Declaration[0]);
|
||||
}
|
||||
}
|
||||
if (compilationUnit.getFile().getParentFile().getName().equals(TypescriptDef2Java.TS_DOM_LIB_DIR)) {
|
||||
currentModule = new ModuleDeclaration(null, JSweetDefTranslatorConfig.DOM_PACKAGE, new Declaration[0]);
|
||||
}
|
||||
if (currentModule == null) {
|
||||
String name = Util.getLibPackageNameFromTsDefFile(compilationUnit.getFile());
|
||||
logger.trace("root package found: " + name + " for " + compilationUnit);
|
||||
currentModule = new ModuleDeclaration(null, name, new Declaration[0]);
|
||||
if (compilationUnit.isExternal()) {
|
||||
String filename = compilationUnit.getFile().getName();
|
||||
filename = filename.substring(0, filename.indexOf('.'));
|
||||
currentModule.addStringAnnotation(JSweetDefTranslatorConfig.ANNOTATION_NAME + "(\"" + filename + "\")");
|
||||
currentModule.setQuotedName(true);
|
||||
}
|
||||
if (!context.libModules.contains(name)) {
|
||||
context.libModulesCompilationUnits.put(name, compilationUnit);
|
||||
context.libModules.add(name);
|
||||
context.libModules.sort(new Comparator<String>() {
|
||||
@Override
|
||||
public int compare(String s1, String s2) {
|
||||
return -s1.compareTo(s2);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// this is the case when a group contains several definition
|
||||
// files
|
||||
context.reportWarning("root package has already been registered: " + name);
|
||||
}
|
||||
}
|
||||
|
||||
for (Declaration declaration : compilationUnit.getMembers()) {
|
||||
currentModule.addMember(declaration);
|
||||
}
|
||||
compilationUnit.clearMembers();
|
||||
|
||||
// TODO : the following code was supposed to handle a compilation unit
|
||||
// which would not be any of lang, dom, webworkers or lib
|
||||
// for (Declaration declaration : compilationUnit.getMembers()) {
|
||||
// if (!(declaration instanceof ModuleDeclaration)) {
|
||||
// if (currentModule == null) {
|
||||
// currentModule = new ModuleDeclaration(null,
|
||||
// JSweetConfig.GLOBALS_PACKAGE_NAME,
|
||||
// new Declaration[0]);
|
||||
// }
|
||||
// compilationUnit.removeMember(declaration);
|
||||
// currentModule.addMember(declaration);
|
||||
// }
|
||||
// }
|
||||
if (currentModule != null) {
|
||||
if (context.verbose) {
|
||||
logger.debug("creating module: " + currentModule + " - " + Arrays.asList(currentModule.getMembers()));
|
||||
}
|
||||
compilationUnit.addMember(currentModule);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,86 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.jsweet.JSweetDefTranslatorConfig;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.Type;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeReference;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
|
||||
/**
|
||||
* This scanner substitutes void return types of parent methods with Object.
|
||||
*
|
||||
* <p>
|
||||
* In Typescript, one can override a void method with a method that returns an
|
||||
* object. In Java, it is not possible. So this scanner make sure that the
|
||||
* parent method with actually return an object to avoid Java compile errors.
|
||||
*
|
||||
* @author Renaud Pawlak
|
||||
*/
|
||||
public class ParentMethodReturnTypeSusbtitutor extends Scanner {
|
||||
|
||||
public ParentMethodReturnTypeSusbtitutor(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
private void applyToParentMethod(TypeDeclaration declaringType, FunctionDeclaration childFunction,
|
||||
TypeDeclaration parentType, Consumer<FunctionDeclaration> apply) {
|
||||
int index = -1;
|
||||
if (declaringType != parentType) {
|
||||
index = ArrayUtils.indexOf(parentType.getMembers(), childFunction);
|
||||
}
|
||||
if (index != -1) {
|
||||
apply.accept((FunctionDeclaration) parentType.getMembers()[index]);
|
||||
} else {
|
||||
if (parentType.getSuperTypes() != null && parentType.getSuperTypes().length > 0) {
|
||||
for (TypeReference ref : parentType.getSuperTypes()) {
|
||||
Type decl = lookupType(ref, null);
|
||||
if (decl instanceof TypeDeclaration) {
|
||||
applyToParentMethod(declaringType, childFunction, (TypeDeclaration) decl, apply);
|
||||
}
|
||||
}
|
||||
} else if (!JSweetDefTranslatorConfig.getObjectClassName().equals(context.getTypeName(parentType))) {
|
||||
TypeDeclaration decl = context.getTypeDeclaration(JSweetDefTranslatorConfig.getObjectClassName());
|
||||
if (decl != null) {
|
||||
applyToParentMethod(declaringType, childFunction, (TypeDeclaration) decl, apply);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionDeclaration(FunctionDeclaration functionDeclaration) {
|
||||
TypeDeclaration declaringType = getParent(TypeDeclaration.class);
|
||||
if (declaringType != null && functionDeclaration.getType() != null
|
||||
&& functionDeclaration.getType().getName() != null
|
||||
&& !functionDeclaration.getType().getName().equals("void")) {
|
||||
applyToParentMethod(
|
||||
declaringType,
|
||||
functionDeclaration,
|
||||
declaringType,
|
||||
(function) -> {
|
||||
if (functionDeclaration.getType().isPrimitive() && !function.getType().isPrimitive()) {
|
||||
functionDeclaration.getType().setName(
|
||||
StringUtils.capitalize(functionDeclaration.getType().getName()));
|
||||
} else {
|
||||
if ("void".equals(function.getType().getName())) {
|
||||
System.out.println("modify return type of " + function + ": " + function.getType()
|
||||
+ " -> " + functionDeclaration.getType());
|
||||
function.setType(functionDeclaration.getType());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitVariableDeclaration(VariableDeclaration variableDeclaration) {
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,43 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import org.jsweet.JSweetDefTranslatorConfig;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeMacroDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
|
||||
/**
|
||||
* This scanner makes sure that classes that are sub-types of a serializable
|
||||
* class do not trigger useless compilation warnings.
|
||||
*
|
||||
* @author Renaud Pawlak
|
||||
*/
|
||||
public class SerializableHandler extends Scanner {
|
||||
|
||||
public SerializableHandler(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeDeclaration(TypeDeclaration typeDeclaration) {
|
||||
if (typeDeclaration.isSubtypeOf(context.getTypeDeclaration(JSweetDefTranslatorConfig.LANG_PACKAGE + "."
|
||||
+ RuntimeException.class.getSimpleName()))) {
|
||||
typeDeclaration.addStringAnnotation(SuppressWarnings.class.getName() + "(\"serial\")");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionDeclaration(FunctionDeclaration functionDeclaration) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitVariableDeclaration(VariableDeclaration variableDeclaration) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeMacro(TypeMacroDeclaration typeMacroDeclaration) {
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,126 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import static org.apache.commons.lang3.StringUtils.strip;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.jsweet.JSweetDefTranslatorConfig;
|
||||
import org.jsweet.input.typescriptdef.ast.CompilationUnit;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.Declaration;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationContainer;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationHelper;
|
||||
import org.jsweet.input.typescriptdef.ast.ModuleDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeReference;
|
||||
import org.jsweet.input.typescriptdef.ast.TypedDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
import org.jsweet.input.typescriptdef.util.Util;
|
||||
|
||||
public class StringTypeCreator extends Scanner {
|
||||
|
||||
/**
|
||||
* Dashes can be used in Javascript identifiers, and will be replaced by
|
||||
* this string.
|
||||
*/
|
||||
public static final String DASH_STRING_IN_JAVA_IDENTIFIERS = "_";
|
||||
|
||||
public static String toJavaStringType(String stringType) {
|
||||
String stripped = strip(stringType, "\"");
|
||||
if (Character.isDigit(stripped.charAt(0))) {
|
||||
stripped = "_" + stripped;
|
||||
}
|
||||
stripped = stripped.replaceAll("[-:.!,;]", DASH_STRING_IN_JAVA_IDENTIFIERS);
|
||||
if (JSweetDefTranslatorConfig.JAVA_KEYWORDS.contains(stripped)) {
|
||||
stripped = StringUtils.capitalize(stripped);
|
||||
}
|
||||
return stripped;
|
||||
}
|
||||
|
||||
public StringTypeCreator(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeReference(TypeReference typeReference) {
|
||||
if (typeReference.isStringType()) {
|
||||
TypedDeclaration parentDeclaration = getParent(TypedDeclaration.class);
|
||||
|
||||
String stripped = strip(typeReference.getName(), "['\"]");
|
||||
String name = toJavaStringType(typeReference.getName());
|
||||
|
||||
DeclarationContainer stringsContainer = getStringsDeclarationContainer();
|
||||
TypeDeclaration newInterface = stringsContainer.findTypeIgnoreCase(name);
|
||||
if (newInterface == null) {
|
||||
newInterface = new TypeDeclaration(null, "interface", name, null, null, new Declaration[0]);
|
||||
newInterface.setDocumentation("/**\n" + " * Generated to type the string " + typeReference.getName()
|
||||
+ ".\n" + " * @exclude\n" + " */");
|
||||
stringsContainer.addMember(newInterface);
|
||||
context.registerType(
|
||||
JSweetDefTranslatorConfig.UTIL_PACKAGE + "."
|
||||
+ JSweetDefTranslatorConfig.STRING_TYPES_INTERFACE_NAME + "." + newInterface.getName(),
|
||||
newInterface);
|
||||
if (stripped.equals(name)) {
|
||||
newInterface.addStringAnnotation(JSweetDefTranslatorConfig.ANNOTATION_STRING_TYPE);
|
||||
} else {
|
||||
newInterface.addStringAnnotation(
|
||||
JSweetDefTranslatorConfig.ANNOTATION_STRING_TYPE + "(\"" + stripped + "\")");
|
||||
}
|
||||
}
|
||||
VariableDeclaration var = null;
|
||||
if ((var = stringsContainer.findVariableIgnoreCase(name)) == null) {
|
||||
VariableDeclaration value = new VariableDeclaration(null, name, new TypeReference(null,
|
||||
JSweetDefTranslatorConfig.UTIL_PACKAGE + "."
|
||||
+ JSweetDefTranslatorConfig.STRING_TYPES_INTERFACE_NAME + "." + newInterface.getName(),
|
||||
null), false, false);
|
||||
value.setDocumentation("/**\n" + " * Generated to type the string " + typeReference.getName() + ".\n"
|
||||
+ " * @exclude\n" + " */");
|
||||
value.addModifier("static");
|
||||
stringsContainer.addMember(value);
|
||||
if (stripped.equals(name)) {
|
||||
value.addStringAnnotation(JSweetDefTranslatorConfig.ANNOTATION_STRING_TYPE);
|
||||
} else {
|
||||
value.addStringAnnotation(
|
||||
JSweetDefTranslatorConfig.ANNOTATION_STRING_TYPE + "(\"" + stripped + "\")");
|
||||
}
|
||||
}
|
||||
Util.substituteTypeReference(this, parentDeclaration, typeReference,
|
||||
new TypeReference(null,
|
||||
JSweetDefTranslatorConfig.UTIL_PACKAGE + "."
|
||||
+ JSweetDefTranslatorConfig.STRING_TYPES_INTERFACE_NAME + "."
|
||||
+ (var == null ? name : var.getName()),
|
||||
null));
|
||||
|
||||
}
|
||||
super.visitTypeReference(typeReference);
|
||||
}
|
||||
|
||||
private DeclarationContainer getStringsDeclarationContainer() {
|
||||
// string declarations are all merged in the same package / class:
|
||||
// jsweet util
|
||||
CompilationUnit destinationCompilUnit = context.getTranslatedCompilationUnits().get(0);
|
||||
|
||||
ModuleDeclaration destinationModule = getOrCreateModule(destinationCompilUnit,
|
||||
JSweetDefTranslatorConfig.UTIL_PACKAGE);
|
||||
String name = JSweetDefTranslatorConfig.STRING_TYPES_INTERFACE_NAME;
|
||||
TypeDeclaration candidate = destinationModule.findType(name);
|
||||
if (candidate == null) {
|
||||
candidate = new TypeDeclaration(null, "interface", JSweetDefTranslatorConfig.STRING_TYPES_INTERFACE_NAME,
|
||||
null, null, new Declaration[0]);
|
||||
candidate.addModifier("public");
|
||||
destinationModule.addMember(candidate);
|
||||
context.registerType(destinationModule + "." + name, candidate);
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
private ModuleDeclaration getOrCreateModule(DeclarationContainer container, String name) {
|
||||
ModuleDeclaration m = DeclarationHelper.findModule(container, name);
|
||||
if (m == null) {
|
||||
m = new ModuleDeclaration(null, name, new Declaration[0]);
|
||||
container.addMember(m);
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,53 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.jsweet.JSweetDefTranslatorConfig;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationContainer;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeReference;
|
||||
import org.jsweet.input.typescriptdef.ast.TypedDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
|
||||
public class StringTypeExpander extends Scanner {
|
||||
|
||||
public StringTypeExpander(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionDeclaration(FunctionDeclaration functionDeclaration) {
|
||||
super.visitFunctionDeclaration(functionDeclaration);
|
||||
redirectStringType(functionDeclaration);
|
||||
DeclarationContainer container = getParent(DeclarationContainer.class);
|
||||
expandStringParameters(container, functionDeclaration);
|
||||
}
|
||||
|
||||
private void expandStringParameters(DeclarationContainer container, FunctionDeclaration functionDeclaration) {
|
||||
for (int i = functionDeclaration.getParameters().length - 1; i >= 0; i--) {
|
||||
TypeReference t = functionDeclaration.getParameters()[i].getType();
|
||||
if ("string".equals(t.getName()) || "String".equals(t.getName())) {
|
||||
redirectStringType(functionDeclaration.getParameters()[i]);
|
||||
FunctionDeclaration newFunction = functionDeclaration.copy();
|
||||
newFunction.getParameters()[i].getType().setName(String.class.getName());
|
||||
if (!ArrayUtils.contains(container.getMembers(), newFunction)) {
|
||||
container.addMember(newFunction);
|
||||
expandStringParameters(container, newFunction);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitVariableDeclaration(VariableDeclaration variableDeclaration) {
|
||||
redirectStringType(variableDeclaration);
|
||||
}
|
||||
|
||||
private void redirectStringType(TypedDeclaration declaration) {
|
||||
if (declaration.getType() != null && ("string".equals(declaration.getType().getName()) || "String".equals(declaration.getType().getName()))) {
|
||||
declaration.getType().setName(JSweetDefTranslatorConfig.LANG_PACKAGE + ".String");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,122 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.Declaration;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.Type;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeParameterDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeReference;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
|
||||
public class SuperTypesMerger extends Scanner {
|
||||
|
||||
public SuperTypesMerger(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
private int injectedTypeCount = 0;
|
||||
|
||||
private class TypeParameterSubstitutor extends Scanner {
|
||||
|
||||
Map<String, String> typeArgs;
|
||||
|
||||
public TypeParameterSubstitutor(Context context, Map<String, String> typeArgs) {
|
||||
super(context);
|
||||
this.typeArgs = typeArgs;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeReference(TypeReference typeReference) {
|
||||
if (typeArgs.containsKey(typeReference.getName())) {
|
||||
typeReference.setName(typeArgs.get(typeReference.getName()));
|
||||
}
|
||||
super.visitTypeReference(typeReference);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void injectSuperTypes(TypeDeclaration target) {
|
||||
if (target.getSuperTypes() != null && target.getSuperTypes().length > 1) {
|
||||
TypeReference[] superTypes = ArrayUtils.subarray(target.getSuperTypes(), 1, target.getSuperTypes().length);
|
||||
for (TypeReference superType : superTypes) {
|
||||
TypeDeclaration source = (TypeDeclaration) lookupType(superType, null);
|
||||
if (source != null) {
|
||||
if (target == source) {
|
||||
// this can happen when lower-casing module names
|
||||
// (classes get merged)
|
||||
// this is a sort of potential bug, so we should support
|
||||
// it at some point
|
||||
// example: Express interfaces
|
||||
context.reportWarning("ignore injecting supertype that resolves to the same target type: "
|
||||
+ context.getTypeName(target));
|
||||
continue;
|
||||
}
|
||||
injectSuperTypes(source);
|
||||
target.addMergedSuperType(superType);
|
||||
injectedTypeCount++;
|
||||
if (context.verbose) {
|
||||
logger.debug("injecting supertype " + superType + " into " + target);
|
||||
}
|
||||
Map<String, String> typeArgs = new HashMap<String, String>();
|
||||
if (source.getTypeParameters() != null) {
|
||||
for (int i = 0; i < source.getTypeParameters().length; i++) {
|
||||
Type t = null;
|
||||
if (superType.getTypeArguments() != null && i < superType.getTypeArguments().length) {
|
||||
t = lookupType(superType.getTypeArguments()[i], null);
|
||||
}
|
||||
typeArgs.put(source.getTypeParameters()[i].getName(),
|
||||
t == null ? "java.lang.Object" : t.getName());
|
||||
}
|
||||
}
|
||||
for (Declaration declaration : source.getMembers()) {
|
||||
if (declaration.isAnonymous()
|
||||
|| declaration.isHidden()
|
||||
|| ((declaration instanceof FunctionDeclaration) && ((FunctionDeclaration) declaration)
|
||||
.isConstructor())) {
|
||||
continue;
|
||||
}
|
||||
if ((declaration instanceof VariableDeclaration)
|
||||
&& target.findVariable(declaration.getName()) != null) {
|
||||
continue;
|
||||
}
|
||||
Declaration d = declaration.copy();
|
||||
target.addMember(d);
|
||||
new TypeParameterSubstitutor(context, typeArgs).scan(d);
|
||||
}
|
||||
}
|
||||
}
|
||||
target.setSuperTypes(new TypeReference[] { target.getSuperTypes()[0] });
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeDeclaration(TypeDeclaration typeDeclaration) {
|
||||
injectSuperTypes(typeDeclaration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionDeclaration(FunctionDeclaration functionDeclaration) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitVariableDeclaration(VariableDeclaration variableDeclaration) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onScanEnded() {
|
||||
if (injectedTypeCount > 0) {
|
||||
logger.debug(injectedTypeCount + " supertype(s) injected.");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,89 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import org.jsweet.JSweetDefTranslatorConfig;
|
||||
import org.jsweet.input.typescriptdef.ast.CompilationUnit;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.Declaration;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationContainer;
|
||||
import org.jsweet.input.typescriptdef.ast.DeclarationHelper;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.ModuleDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.ParameterDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeParameterDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeReference;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
|
||||
/**
|
||||
* Generates tuple types on the fly if built in Tuple[2-6] is not enough
|
||||
*
|
||||
* @author Renaud Pawlak
|
||||
*
|
||||
*/
|
||||
public class TupleTypeCreator extends Scanner {
|
||||
|
||||
public TupleTypeCreator(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeReference(TypeReference typeReference) {
|
||||
if (typeReference.isTuple() && typeReference.getTypeArguments().length > 6) {
|
||||
getOrCreateUnionType(typeReference);
|
||||
}
|
||||
super.visitTypeReference(typeReference);
|
||||
}
|
||||
|
||||
private TypeDeclaration getOrCreateUnionType(TypeReference reference) {
|
||||
CompilationUnit compilUnit = getParent(CompilationUnit.class);
|
||||
ModuleDeclaration targetModule = getOrCreateModule(compilUnit, JSweetDefTranslatorConfig.TUPLE_CLASSES_PACKAGE);
|
||||
|
||||
String name = reference.getName();
|
||||
TypeDeclaration tupleType = targetModule.findType(name);
|
||||
if (tupleType == null) {
|
||||
tupleType = createTupleType(reference);
|
||||
targetModule.addMember(tupleType);
|
||||
context.registerType(name, tupleType);
|
||||
}
|
||||
|
||||
return tupleType;
|
||||
}
|
||||
|
||||
private ModuleDeclaration getOrCreateModule(DeclarationContainer container, String name) {
|
||||
ModuleDeclaration m = DeclarationHelper.findModule(container, name);
|
||||
if (m == null) {
|
||||
m = new ModuleDeclaration(null, name, new Declaration[0]);
|
||||
container.addMember(m);
|
||||
context.registerModule(name, m);
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
private TypeDeclaration createTupleType(TypeReference reference) {
|
||||
TypeParameterDeclaration[] typeParameters = new TypeParameterDeclaration[reference.getTypeArguments().length];
|
||||
for (int i = 0; i < reference.getTypeArguments().length; i++) {
|
||||
typeParameters[i] = new TypeParameterDeclaration(null, "T" + i);
|
||||
}
|
||||
|
||||
TypeDeclaration tupleType = new TypeDeclaration(null, "class", reference.getSimpleName(), typeParameters, null,
|
||||
null);
|
||||
for (int i = 0; i < reference.getTypeArguments().length; i++) {
|
||||
tupleType.addMember(
|
||||
new VariableDeclaration(null, "$" + i, new TypeReference(null, typeParameters[i], null), false, false));
|
||||
}
|
||||
|
||||
ParameterDeclaration[] parameters = new ParameterDeclaration[reference.getTypeArguments().length];
|
||||
for (int i = 0; i < reference.getTypeArguments().length; i++) {
|
||||
parameters[i] = new ParameterDeclaration(null, "$" + i, new TypeReference(null, typeParameters[i], null),
|
||||
false, false);
|
||||
}
|
||||
tupleType.addMember(
|
||||
new FunctionDeclaration(null, FunctionDeclaration.NEW_FUNCTION_RESERVED_NAME, null, parameters, null));
|
||||
|
||||
tupleType.setDocumentation("/** This tuple type was automatically generated in order to accept "
|
||||
+ reference.getTypeArguments().length + " types. @see Tuple2 */");
|
||||
return tupleType;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,47 @@
|
||||
package org.jsweet.input.typescriptdef.visitor;
|
||||
|
||||
import org.jsweet.JSweetDefTranslatorConfig;
|
||||
import org.jsweet.input.typescriptdef.ast.Context;
|
||||
import org.jsweet.input.typescriptdef.ast.FunctionDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.Scanner;
|
||||
import org.jsweet.input.typescriptdef.ast.TypeDeclaration;
|
||||
import org.jsweet.input.typescriptdef.ast.VariableDeclaration;
|
||||
|
||||
/**
|
||||
* This scanner decides whether a type should be translated as a Java class or a
|
||||
* Java interface.
|
||||
*
|
||||
* @author Renaud Pawlak
|
||||
*/
|
||||
public class TypeKindChooser extends Scanner {
|
||||
|
||||
public TypeKindChooser(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeDeclaration(TypeDeclaration typeDeclaration) {
|
||||
if (!typeDeclaration.isAnonymous() && !"enum".equals(typeDeclaration.getKind())
|
||||
&& !typeDeclaration.isExternal()) {
|
||||
if (!(typeDeclaration.getKind().equals("interface")
|
||||
&& (typeDeclaration.getSuperTypes() == null || typeDeclaration.getSuperTypes().length == 0)
|
||||
&& typeDeclaration.getMembers().length == 1 && ((typeDeclaration.getMembers()[0] instanceof FunctionDeclaration) && ((FunctionDeclaration) typeDeclaration
|
||||
.getMembers()[0]).isAnonymous()))) {
|
||||
if (typeDeclaration.getKind().equals("interface")) {
|
||||
typeDeclaration.addStringAnnotation(JSweetDefTranslatorConfig.ANNOTATION_INTERFACE);
|
||||
typeDeclaration.addModifier("abstract");
|
||||
}
|
||||
typeDeclaration.setKind("class");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFunctionDeclaration(FunctionDeclaration functionDeclaration) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitVariableDeclaration(VariableDeclaration variableDeclaration) {
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user