refactor: rename js2dart
to transpiler
This commit is contained in:
202
tools/transpiler/LICENSE
Normal file
202
tools/transpiler/LICENSE
Normal file
@ -0,0 +1,202 @@
|
||||
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.
|
||||
|
104
tools/transpiler/gulp-tasks.js
Normal file
104
tools/transpiler/gulp-tasks.js
Normal file
@ -0,0 +1,104 @@
|
||||
var rename = require('gulp-rename');
|
||||
var watch = require('gulp-watch');
|
||||
var gulpTraceur = require('./gulp-traceur');
|
||||
var shell = require('gulp-shell');
|
||||
var clean = require('gulp-rimraf');
|
||||
var mergeStreams = require('event-stream').merge;
|
||||
var ejs = require('gulp-ejs');
|
||||
var glob = require('glob');
|
||||
|
||||
var baseDir = __dirname;
|
||||
var traceurDir = baseDir+'/../traceur';
|
||||
var buildDir = baseDir + '/build';
|
||||
|
||||
var paths = {
|
||||
transpilerSrc: baseDir + '/src/**/*.js',
|
||||
specTranspile: baseDir + '/spec/**/*.js',
|
||||
specTemplates: baseDir + '/spec/**/*.template',
|
||||
specCopy: baseDir + '/spec/**/*.dart'
|
||||
};
|
||||
paths.specSrc = [paths.specTranspile, paths.specTemplates, paths.specCopy];
|
||||
|
||||
module.exports.install = install;
|
||||
module.exports.paths = paths;
|
||||
|
||||
function install(gulp) {
|
||||
var runSequence = require('run-sequence').use(gulp);
|
||||
|
||||
var spec2dartOptions = {
|
||||
annotations: true, // parse annotations
|
||||
types: true, // parse types
|
||||
script: false, // parse as a module
|
||||
outputLanguage: 'dart'
|
||||
};
|
||||
|
||||
gulp.task('transpiler/clean', function() {
|
||||
return gulp.src(buildDir, {read: false})
|
||||
.pipe(clean());
|
||||
});
|
||||
|
||||
gulp.task('transpiler/test/build', function() {
|
||||
return mergeStreams(specTranspile(false), specCopy(false), specRunner(false));
|
||||
});
|
||||
|
||||
gulp.task('transpiler/test/run', shell.task([
|
||||
'cd '+baseDir+' && dart --checked run_specs.dart'
|
||||
]));
|
||||
|
||||
gulp.task('transpiler/test', function(done) {
|
||||
runSequence('transpiler/test/build', 'transpiler/test/run', done);
|
||||
});
|
||||
|
||||
gulp.task('transpiler/src/watch', function(done) {
|
||||
return watch(paths.transpilerSrc, function(changes, done) {
|
||||
gulpTraceur.sourcesChanged();
|
||||
runSequence('transpiler/test', done);
|
||||
});
|
||||
});
|
||||
|
||||
gulp.task('transpiler/test/watch', function(done) {
|
||||
var streams = [];
|
||||
streams.push(specTranspile(true)
|
||||
.on('data', specRunner));
|
||||
streams.push(specCopy(true));
|
||||
streams.push(specRunner(true));
|
||||
streams.forEach(function(stream) {
|
||||
stream.on('error', done);
|
||||
stream.on('data', function() {
|
||||
runSequence('transpiler/test/run');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function specTranspile(isWatch) {
|
||||
var srcFn = isWatch ? watch : gulp.src.bind(gulp);
|
||||
return srcFn(paths.specTranspile)
|
||||
.pipe(gulpTraceur(spec2dartOptions))
|
||||
.pipe(rename({extname: '.dart'}))
|
||||
.pipe(gulp.dest(buildDir+'/spec'));
|
||||
}
|
||||
|
||||
function specCopy(isWatch) {
|
||||
var srcFn = isWatch ? watch : gulp.src.bind(gulp);
|
||||
return srcFn(paths.specCopy).pipe(gulp.dest(buildDir+'/spec'));
|
||||
}
|
||||
|
||||
function specRunner(isWatch) {
|
||||
var srcFn = isWatch ? watch : gulp.src.bind(gulp);
|
||||
var builtSpecFiles = glob.sync('**/*_spec.js', {
|
||||
cwd: baseDir+'/spec'
|
||||
}).map(function(fileName) {
|
||||
return fileName.replace('.js', '.dart');
|
||||
});
|
||||
return srcFn(paths.specTemplates)
|
||||
.pipe(ejs({
|
||||
files: builtSpecFiles
|
||||
}))
|
||||
.pipe(rename(function(path) {
|
||||
path.basename = path.basename.replace(/\..*/g, '');
|
||||
path.extname = '.dart';
|
||||
}))
|
||||
.pipe(gulp.dest(buildDir+'/spec'));
|
||||
}
|
||||
}
|
||||
|
40
tools/transpiler/gulp-traceur.js
Normal file
40
tools/transpiler/gulp-traceur.js
Normal file
@ -0,0 +1,40 @@
|
||||
'use strict';
|
||||
var through = require('through2');
|
||||
var compiler = require('./index');
|
||||
|
||||
module.exports = gulpTraceur;
|
||||
gulpTraceur.RUNTIME_PATH = compiler.RUNTIME_PATH;
|
||||
gulpTraceur.sourcesChanged = compiler.sourcesChanged;
|
||||
|
||||
function gulpTraceur(options, resolveModuleName) {
|
||||
options = options || {};
|
||||
|
||||
return through.obj(function (file, enc, done) {
|
||||
if (file.isNull()) {
|
||||
done();
|
||||
return;
|
||||
}
|
||||
|
||||
if (file.isStream()) {
|
||||
throw new Error('gulp-traceur: Streaming not supported');
|
||||
}
|
||||
|
||||
try {
|
||||
var moduleName = resolveModuleName ? resolveModuleName(file.relative) : null;
|
||||
var compiled = compiler.compile(options, {
|
||||
inputPath: file.relative,
|
||||
outputPath: file.relative,
|
||||
moduleName: moduleName
|
||||
}, file.contents.toString());
|
||||
file.contents = new Buffer(compiled);
|
||||
this.push(file);
|
||||
done();
|
||||
} catch (errors) {
|
||||
if (errors.join) {
|
||||
throw new Error('gulp-traceur: '+errors.join('\n'));
|
||||
} else {
|
||||
throw errors;
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
18
tools/transpiler/gulpfile.js
Normal file
18
tools/transpiler/gulpfile.js
Normal file
@ -0,0 +1,18 @@
|
||||
var gulp = require('gulp');
|
||||
var tasks = require('./gulp-tasks');
|
||||
var runSequence = require('run-sequence');
|
||||
var watch = require('gulp-watch');
|
||||
var mergeStreams = require('event-stream').merge;
|
||||
|
||||
tasks.install(gulp);
|
||||
|
||||
gulp.task('test', function() {
|
||||
return runSequence('transpiler/test');
|
||||
});
|
||||
|
||||
gulp.task('clean', ['transpiler/clean']);
|
||||
|
||||
gulp.task('watch', function(done) {
|
||||
// parallel is important as both streams are infinite!
|
||||
runSequence(['transpiler/test/watch', 'transpiler/src/watch'], done);
|
||||
});
|
85
tools/transpiler/index.js
Normal file
85
tools/transpiler/index.js
Normal file
@ -0,0 +1,85 @@
|
||||
// Entry point for Node.
|
||||
|
||||
var fs = require('fs');
|
||||
var glob = require('glob');
|
||||
var path = require('path');
|
||||
var traceur = require('traceur');
|
||||
|
||||
exports.RUNTIME_PATH = traceur.RUNTIME_PATH;
|
||||
var TRACEUR_PATH = traceur.RUNTIME_PATH.replace('traceur-runtime.js', 'traceur.js');
|
||||
var SELF_SOURCE_REGEX = /transpiler\/src/;
|
||||
var SELF_COMPILE_OPTIONS = {
|
||||
modules: 'register',
|
||||
moduleName: true,
|
||||
script: false // parse as a module
|
||||
};
|
||||
|
||||
var needsReload = true;
|
||||
|
||||
// TODO(vojta): call this if sources changed
|
||||
exports.sourcesChanged = function() {
|
||||
needsReload = true;
|
||||
};
|
||||
|
||||
exports.compile = function compile(options, paths, source) {
|
||||
if (needsReload) {
|
||||
reloadCompiler();
|
||||
needsReload = false;
|
||||
}
|
||||
var inputPath, outputPath, moduleName;
|
||||
if (typeof paths === 'string') {
|
||||
inputPath = outputPath = paths;
|
||||
} else {
|
||||
inputPath = paths.inputPath;
|
||||
outputPath = paths.inputPath;
|
||||
moduleName = paths.moduleName;
|
||||
}
|
||||
outputPath = outputPath || inputPath;
|
||||
moduleName = moduleName || inputPath;
|
||||
moduleName = moduleName.replace(/\.\w*$/, '');
|
||||
|
||||
var localOptions = extend(options, {
|
||||
moduleName: moduleName
|
||||
});
|
||||
var CompilerCls = System.get('transpiler/src/compiler').Compiler;
|
||||
return (new CompilerCls(localOptions)).compile(source, inputPath, outputPath);
|
||||
};
|
||||
|
||||
// Transpile and evaluate the code in `src`.
|
||||
// Use existing traceur to compile our sources.
|
||||
function reloadCompiler() {
|
||||
loadModule(TRACEUR_PATH, false);
|
||||
glob.sync(__dirname + '/src/**/*.js').forEach(function(fileName) {
|
||||
loadModule(fileName, true);
|
||||
});
|
||||
}
|
||||
|
||||
function loadModule(filepath, transpile) {
|
||||
var data = fs.readFileSync(filepath, 'utf8');
|
||||
|
||||
if (!data) {
|
||||
throw new Error('Failed to import ' + filepath);
|
||||
}
|
||||
|
||||
if (transpile) {
|
||||
var moduleName = filepath
|
||||
.replace(__dirname, 'transpiler')
|
||||
.replace(/\.\w*$/, '');
|
||||
data = (new traceur.NodeCompiler(
|
||||
extend(SELF_COMPILE_OPTIONS, { moduleName: moduleName } )
|
||||
)).compile(data, filepath, filepath);
|
||||
}
|
||||
|
||||
('global', eval)(data);
|
||||
}
|
||||
|
||||
function extend(source, props) {
|
||||
var res = {};
|
||||
for (var prop in source) {
|
||||
res[prop] = source[prop];
|
||||
}
|
||||
for (var prop in props) {
|
||||
res[prop] = props[prop];
|
||||
}
|
||||
return res;
|
||||
}
|
37
tools/transpiler/karma-traceur-preprocessor.js
Normal file
37
tools/transpiler/karma-traceur-preprocessor.js
Normal file
@ -0,0 +1,37 @@
|
||||
var transpiler = require('./index.js');
|
||||
|
||||
module.exports = {
|
||||
'preprocessor:traceur': ['factory', createJs2DartPreprocessor]
|
||||
};
|
||||
|
||||
function createJs2DartPreprocessor(logger, basePath, config) {
|
||||
var log = logger.create('traceur');
|
||||
|
||||
return function(content, file, done) {
|
||||
|
||||
try {
|
||||
var moduleName = config.resolveModuleName(file.originalPath);
|
||||
if (config.transformPath) {
|
||||
file.path = config.transformPath(file.originalPath);
|
||||
}
|
||||
done(null, transpiler.compile(config.options, {
|
||||
inputPath: file.originalPath,
|
||||
moduleName: moduleName
|
||||
}, content));
|
||||
} catch (errors) {
|
||||
var errorString;
|
||||
if (errors.forEach) {
|
||||
errors.forEach(function(error) {
|
||||
log.error(error);
|
||||
});
|
||||
errorString = errors.join('\n');
|
||||
} else {
|
||||
log.error(errors);
|
||||
errorString = errors;
|
||||
}
|
||||
done(new Error('TRACEUR COMPILE ERRORS\n' + errorString));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
createJs2DartPreprocessor.$inject = ['logger', 'config.basePath', 'config.traceurPreprocessor'];
|
26
tools/transpiler/package.json
Normal file
26
tools/transpiler/package.json
Normal file
@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "transpiler",
|
||||
"version": "0.0.0",
|
||||
"description": "Compile JavaScript to Dart so that you can compile it back to JavaScript and run.",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "gulp transpiler/test",
|
||||
"postinstall": "pub install"
|
||||
},
|
||||
"author": "Vojta Jina <vojta.jina@gmail.com>",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"gulp": "^3.8.8",
|
||||
"gulp-rename": "^1.2.0",
|
||||
"gulp-shell": "^0.2.9",
|
||||
"gulp-watch": "^1.0.3",
|
||||
"q": "^1.0.1",
|
||||
"through2": "^0.6.1",
|
||||
"event-stream": "^3.1.5",
|
||||
"gulp-rimraf": "^0.1.0",
|
||||
"run-sequence": "^0.3.6",
|
||||
"glob": "^4.0.6",
|
||||
"gulp-ejs": "^0.3.1",
|
||||
"traceur": "^0.0.66"
|
||||
}
|
||||
}
|
10
tools/transpiler/pubspec.yaml
Normal file
10
tools/transpiler/pubspec.yaml
Normal file
@ -0,0 +1,10 @@
|
||||
name: transpiler
|
||||
version: 0.0.0
|
||||
authors:
|
||||
- Vojta Jina <vojta.jina@gmail.com>
|
||||
description: Compile JavaScript to Dart so that you can compile it back to JavaScript and run.
|
||||
environment:
|
||||
sdk: '>=1.4.0'
|
||||
dependencies:
|
||||
dev_dependencies:
|
||||
unittest: '>=0.10.1 <0.12.0'
|
7
tools/transpiler/run_specs.dart
Normal file
7
tools/transpiler/run_specs.dart
Normal file
@ -0,0 +1,7 @@
|
||||
// Note: need this file here so that we can use the packages
|
||||
// in the main folder...
|
||||
import './build/spec/runner.dart' as runner;
|
||||
|
||||
void main() {
|
||||
runner.main();
|
||||
}
|
3
tools/transpiler/spec/a-0-subfolder/library_spec.js
Normal file
3
tools/transpiler/spec/a-0-subfolder/library_spec.js
Normal file
@ -0,0 +1,3 @@
|
||||
function main() {
|
||||
assert(true);
|
||||
}
|
19
tools/transpiler/spec/annotations_spec.js
Normal file
19
tools/transpiler/spec/annotations_spec.js
Normal file
@ -0,0 +1,19 @@
|
||||
import annotations from './fixtures/annotations';
|
||||
|
||||
class Inject {}
|
||||
class Bar {}
|
||||
|
||||
@annotations.Provide('Foo')
|
||||
class Foo {
|
||||
@Inject
|
||||
constructor() {}
|
||||
}
|
||||
|
||||
@annotations.Provide(Foo)
|
||||
function baz() {}
|
||||
|
||||
function annotatedParams(@Inject(Foo) f, @Inject(Bar) b) {}
|
||||
|
||||
function main() {
|
||||
annotations.main();
|
||||
}
|
20
tools/transpiler/spec/classes_spec.js
Normal file
20
tools/transpiler/spec/classes_spec.js
Normal file
@ -0,0 +1,20 @@
|
||||
// Constructor
|
||||
// Define fields
|
||||
class Foo {
|
||||
constructor(a, b) {
|
||||
this.a = a;
|
||||
this.b = b;
|
||||
}
|
||||
|
||||
sum() {
|
||||
return this.a + this.b;
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
var foo = new Foo(2, 3);
|
||||
|
||||
assert(foo.a == 2);
|
||||
assert(foo.b == 3);
|
||||
assert(foo.sum() == 5);
|
||||
}
|
16
tools/transpiler/spec/equals_spec.js
Normal file
16
tools/transpiler/spec/equals_spec.js
Normal file
@ -0,0 +1,16 @@
|
||||
function same(a, b) {
|
||||
return a === b;
|
||||
}
|
||||
|
||||
function notSame(a, b) {
|
||||
if ((a !== a) && (b !== b)) return true;
|
||||
return a !== b;
|
||||
}
|
||||
|
||||
function main() {
|
||||
var obj = {};
|
||||
assert(same({}, {}) == false);
|
||||
assert(same(obj, obj) == true);
|
||||
assert(notSame({}, {}) == true);
|
||||
assert(notSame(obj, obj) == false);
|
||||
}
|
1
tools/transpiler/spec/export.js
Normal file
1
tools/transpiler/spec/export.js
Normal file
@ -0,0 +1 @@
|
||||
export * from './foo';
|
26
tools/transpiler/spec/fixtures/annotations.dart
vendored
Normal file
26
tools/transpiler/spec/fixtures/annotations.dart
vendored
Normal file
@ -0,0 +1,26 @@
|
||||
// This file is not generated,
|
||||
// but should be in the future.
|
||||
//
|
||||
// Problems:
|
||||
// - Dart requires annotations to be const (which makes sense).
|
||||
// Right now, I can't describe that in ES6.
|
||||
// - operator mapping `is`/`instanceof` is not yet implemented
|
||||
import 'dart:mirrors';
|
||||
|
||||
import '../annotations_spec.dart';
|
||||
|
||||
class Provide {
|
||||
final token;
|
||||
const Provide(this.token);
|
||||
}
|
||||
|
||||
readAnnotation(clazz) {
|
||||
return reflectClass(clazz).metadata.first.reflectee;
|
||||
}
|
||||
|
||||
main() {
|
||||
// Assert `Foo` class has `Provide` annotation.
|
||||
// TODO(vojta): test this more.
|
||||
var clazz = readAnnotation(Foo);
|
||||
assert(clazz is Provide);
|
||||
}
|
3
tools/transpiler/spec/fixtures/facade.dart
vendored
Normal file
3
tools/transpiler/spec/fixtures/facade.dart
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
class MapWrapper {
|
||||
|
||||
}
|
2
tools/transpiler/spec/foo.js
Normal file
2
tools/transpiler/spec/foo.js
Normal file
@ -0,0 +1,2 @@
|
||||
export var Foo = 'FOO';
|
||||
export var Bar = 'BAR';
|
7
tools/transpiler/spec/functions_spec.js
Normal file
7
tools/transpiler/spec/functions_spec.js
Normal file
@ -0,0 +1,7 @@
|
||||
function sum(a, b) {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
function main() {
|
||||
assert(sum(1, 2) == 3);
|
||||
}
|
22
tools/transpiler/spec/imports_spec.js
Normal file
22
tools/transpiler/spec/imports_spec.js
Normal file
@ -0,0 +1,22 @@
|
||||
import {Foo, Bar} from './foo';
|
||||
// import {Foo as F} from './fixtures/foo';
|
||||
import fooModule from './foo';
|
||||
|
||||
import {MapWrapper wraps Map} from './fixtures/facade';
|
||||
|
||||
import exportModule from './export';
|
||||
|
||||
import unittest from 'unittest/unittest';
|
||||
|
||||
function main() {
|
||||
assert(Foo == 'FOO');
|
||||
assert(Bar == 'BAR');
|
||||
// assert(F == 'FOO');
|
||||
assert(fooModule.Foo == 'FOO');
|
||||
assert(fooModule.Bar == 'BAR');
|
||||
|
||||
assert(exportModule.Foo == 'FOO');
|
||||
assert(exportModule.Bar == 'BAR');
|
||||
|
||||
assert(unittest.PASS != null);
|
||||
}
|
13
tools/transpiler/spec/runner.dart.template
Normal file
13
tools/transpiler/spec/runner.dart.template
Normal file
@ -0,0 +1,13 @@
|
||||
import 'package:unittest/unittest.dart';
|
||||
|
||||
<% files.forEach(function(file, index) { %>
|
||||
import '<%= file %>' as spec<%=index%>;
|
||||
<% }); %>
|
||||
|
||||
void main() {
|
||||
<% files.forEach(function(file, index) { %>
|
||||
test('<%= file %>', () {
|
||||
spec<%= index %>.main();
|
||||
});
|
||||
<% }); %>
|
||||
}
|
53
tools/transpiler/spec/types_spec.js
Normal file
53
tools/transpiler/spec/types_spec.js
Normal file
@ -0,0 +1,53 @@
|
||||
function sum(a: number, b: number): number {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
function not(a: boolean): boolean {
|
||||
return !a;
|
||||
}
|
||||
|
||||
function generics(a: A<Test>) {
|
||||
|
||||
}
|
||||
|
||||
function namedObjectType({a,b}:{a:A,b:B<C>}) {
|
||||
|
||||
}
|
||||
|
||||
class Bar {
|
||||
constructor({
|
||||
selector,
|
||||
lightDomServices,
|
||||
implementsTypes
|
||||
})
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
class Foo {
|
||||
constructor(a: number, b: number) {
|
||||
this.a = a;
|
||||
this.b = b;
|
||||
}
|
||||
|
||||
sum(): number {
|
||||
return this.a + this.b;
|
||||
}
|
||||
|
||||
typedVariables() {
|
||||
// TODO(vojta): test this
|
||||
var foo:string = 'foo';
|
||||
var typed:bool, untyped;
|
||||
var oneTyped:string = 'one',
|
||||
another: bool = true;
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
// TODO(vojta): test this better.
|
||||
var f = new Foo(1, 2);
|
||||
assert(f.sum() == 3);
|
||||
assert(f instanceof Foo);
|
||||
|
||||
f.typedVariables();
|
||||
}
|
20
tools/transpiler/src/ast/class_field.js
Normal file
20
tools/transpiler/src/ast/class_field.js
Normal file
@ -0,0 +1,20 @@
|
||||
import {ParseTree} from 'traceur/src/syntax/trees/ParseTree';
|
||||
|
||||
var CLASS_FIELD = 'CLASS_FIELD';
|
||||
|
||||
export class ClassFieldParseTree extends ParseTree {
|
||||
constructor(location, identifier, typeAnnotation) {
|
||||
this.location = location;
|
||||
this.identifier = identifier;
|
||||
this.typeAnnotation = typeAnnotation;
|
||||
}
|
||||
get type() {
|
||||
return CLASS_FIELD;
|
||||
}
|
||||
visit(visitor) {
|
||||
visitor.visitClassField(this);
|
||||
}
|
||||
transform(transformer) {
|
||||
return this;
|
||||
}
|
||||
}
|
57
tools/transpiler/src/compiler.js
Normal file
57
tools/transpiler/src/compiler.js
Normal file
@ -0,0 +1,57 @@
|
||||
import {Compiler as TraceurCompiler} from 'traceur/src/Compiler';
|
||||
import {ClassTransformer} from './dart_class_transformer';
|
||||
import {DartTreeWriter} from './dart_writer';
|
||||
import {CollectingErrorReporter} from 'traceur/src/util/CollectingErrorReporter';
|
||||
import {Parser} from './parser';
|
||||
import {SourceFile} from 'traceur/src/syntax/SourceFile';
|
||||
import {
|
||||
options as traceurOptions
|
||||
} from 'traceur/src/Options';
|
||||
|
||||
export class Compiler extends TraceurCompiler {
|
||||
|
||||
constructor(options, sourceRoot) {
|
||||
super(options, sourceRoot);
|
||||
}
|
||||
|
||||
transform(tree, moduleName = undefined) {
|
||||
if (this.options_.outputLanguage.toLowerCase() === 'dart') {
|
||||
var transformer = new ClassTransformer();
|
||||
return transformer.transformAny(tree);
|
||||
} else {
|
||||
return super(tree, moduleName);
|
||||
}
|
||||
}
|
||||
|
||||
write(tree, outputName = undefined, sourceRoot = undefined) {
|
||||
if (this.options_.outputLanguage.toLowerCase() === 'dart') {
|
||||
var writer = new DartTreeWriter(this.options_.moduleName, outputName);
|
||||
writer.visitAny(tree);
|
||||
return writer.toString();
|
||||
} else {
|
||||
return super.write(tree, outputName, sourceRoot);
|
||||
}
|
||||
}
|
||||
|
||||
// Copy of the original method to use our custom Parser
|
||||
parse(content, sourceName) {
|
||||
if (!content) {
|
||||
throw new Error('Compiler: no content to compile.');
|
||||
} else if (!sourceName) {
|
||||
throw new Error('Compiler: no source name for content.');
|
||||
}
|
||||
|
||||
this.sourceMapGenerator_ = null;
|
||||
// Here we mutate the global/module options object to be used in parsing.
|
||||
traceurOptions.setFromObject(this.options_);
|
||||
|
||||
var errorReporter = new CollectingErrorReporter();
|
||||
sourceName = this.sourceName(sourceName);
|
||||
var sourceFile = new SourceFile(sourceName, content);
|
||||
var parser = new Parser(sourceFile, errorReporter);
|
||||
var tree =
|
||||
this.options_.script ? parser.parseScript() : parser.parseModule();
|
||||
this.throwIfErrors(errorReporter);
|
||||
return tree;
|
||||
}
|
||||
}
|
124
tools/transpiler/src/dart_class_transformer.js
Normal file
124
tools/transpiler/src/dart_class_transformer.js
Normal file
@ -0,0 +1,124 @@
|
||||
import {ParseTreeTransformer} from 'traceur/src/codegeneration/ParseTreeTransformer';
|
||||
import {createVariableStatement, createCallExpression, createIdentifierExpression, createArgumentList} from 'traceur/src/codegeneration/ParseTreeFactory';
|
||||
|
||||
// var token = traceur.syntax.TokenType;
|
||||
// var CONSTRUCTOR = token.CONSTRUCTOR;
|
||||
|
||||
import {PROPERTY_METHOD_ASSIGNMENT, MEMBER_EXPRESSION, THIS_EXPRESSION, BINARY_EXPRESSION} from 'traceur/src/syntax/trees/ParseTreeType';
|
||||
import {EQUAL_EQUAL_EQUAL, NOT_EQUAL_EQUAL} from 'traceur/src/syntax/TokenType';
|
||||
import {CONSTRUCTOR} from 'traceur/src/syntax/PredefinedName';
|
||||
|
||||
import {VariableStatement, VariableDeclarationList} from 'traceur/src/syntax/trees/ParseTrees';
|
||||
|
||||
import {propName} from 'traceur/src/staticsemantics/PropName';
|
||||
|
||||
import {ClassFieldParseTree} from './ast/class_field';
|
||||
|
||||
// - rename constructor (name of the class - default Dart constructor)
|
||||
export class ClassTransformer extends ParseTreeTransformer {
|
||||
// Transform multi-var declarations, into multiple statements:
|
||||
// var x, y;
|
||||
// ==>
|
||||
// var x;
|
||||
// var y;
|
||||
// TODO(vojta): move this into a separate transformer.
|
||||
|
||||
// Individual item transformer can return an array of items.
|
||||
// This is used in `transformVariableStatement`.
|
||||
// Otherwise this is copy/pasted from `ParseTreeTransformer`.
|
||||
transformList(list) {
|
||||
var transformedList = [];
|
||||
var transformedItem = null;
|
||||
|
||||
for (var i = 0, ii = list.length; i < ii; i++) {
|
||||
transformedItem = this.transformAny(list[i]);
|
||||
if (Array.isArray(transformedItem)) {
|
||||
transformedList = transformedList.concat(transformedItem);
|
||||
} else {
|
||||
transformedList.push(transformedItem);
|
||||
}
|
||||
}
|
||||
|
||||
return transformedList;
|
||||
}
|
||||
|
||||
transformVariableStatement(tree) {
|
||||
var declarations = tree.declarations.declarations;
|
||||
|
||||
if (declarations.length === 1 || declarations.length === 0) {
|
||||
return tree;
|
||||
}
|
||||
|
||||
// Multiple var declaration, we will split it into multiple statements.
|
||||
// TODO(vojta): We can leave the multi-definition as long as they are all the same type/untyped.
|
||||
return declarations.map(function(declaration) {
|
||||
return new VariableStatement(tree.location, new VariableDeclarationList(tree.location,
|
||||
tree.declarations.declarationType, [declaration]));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// Transform triple equals into identical() call.
|
||||
// TODO(vojta): move to a separate transformer
|
||||
transformBinaryExpression(tree) {
|
||||
tree.left = this.transformAny(tree.left);
|
||||
tree.right = this.transformAny(tree.right);
|
||||
if (tree.operator.type === 'instanceof') {
|
||||
// a instanceof b -> a is b
|
||||
// TODO(vojta): do this in a cleaner way.
|
||||
tree.operator.type = 'is';
|
||||
return tree;
|
||||
} else if (tree.operator.type === EQUAL_EQUAL_EQUAL) {
|
||||
// a === b -> identical(a, b)
|
||||
return createCallExpression(createIdentifierExpression('identical'), createArgumentList([tree.left, tree.right]));
|
||||
} else if (tree.operator.type === NOT_EQUAL_EQUAL) {
|
||||
// a !== b -> !identical(a, b)
|
||||
// TODO(vojta): do this in a cleaner way.
|
||||
return createCallExpression(createIdentifierExpression('!identical'), createArgumentList([tree.left, tree.right]));
|
||||
} else {
|
||||
return tree;
|
||||
}
|
||||
};
|
||||
|
||||
transformClassDeclaration(tree) {
|
||||
var className = tree.name.identifierToken.toString();
|
||||
var argumentTypesMap = {};
|
||||
var fields = [];
|
||||
|
||||
tree.elements.forEach(function(elementTree) {
|
||||
if (elementTree.type === PROPERTY_METHOD_ASSIGNMENT &&
|
||||
!elementTree.isStatic &&
|
||||
propName(elementTree) === CONSTRUCTOR) {
|
||||
|
||||
// Store constructor argument types,
|
||||
// so that we can use them to set the types of simple-assigned fields.
|
||||
elementTree.parameterList.parameters.forEach(function(p) {
|
||||
var binding = p.parameter.binding;
|
||||
if (binding.identifierToken) {
|
||||
argumentTypesMap[binding.identifierToken.value] = p.typeAnnotation;
|
||||
}
|
||||
});
|
||||
|
||||
// Rename "constructor" to the class name.
|
||||
elementTree.name.literalToken.value = className;
|
||||
|
||||
// Collect all fields, defined in the constructor.
|
||||
elementTree.body.statements.forEach(function(statement) {
|
||||
if (statement.expression.type === BINARY_EXPRESSION &&
|
||||
statement.expression.operator.type === '=' &&
|
||||
statement.expression.left.type === MEMBER_EXPRESSION &&
|
||||
statement.expression.left.operand.type === THIS_EXPRESSION) {
|
||||
|
||||
var typeAnnotation = argumentTypesMap[statement.expression.left.memberName.value] || null;
|
||||
fields.push(new ClassFieldParseTree(tree.location, statement.expression.left.memberName, typeAnnotation));
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Add the field definitions to the begining of the class.
|
||||
tree.elements = fields.concat(tree.elements);
|
||||
|
||||
return super(tree);
|
||||
};
|
||||
}
|
251
tools/transpiler/src/dart_writer.js
Normal file
251
tools/transpiler/src/dart_writer.js
Normal file
@ -0,0 +1,251 @@
|
||||
import {CONSTRUCTOR, FROM} from 'traceur/src/syntax/PredefinedName';
|
||||
import {EQUAL_EQUAL_EQUAL, OPEN_PAREN, CLOSE_PAREN, IMPORT, SEMI_COLON, STAR, OPEN_CURLY, CLOSE_CURLY, COMMA, AT, EQUAL} from 'traceur/src/syntax/TokenType';
|
||||
|
||||
import {ParseTreeWriter as JavaScriptParseTreeWriter} from 'traceur/src/outputgeneration/ParseTreeWriter';
|
||||
|
||||
export class DartTreeWriter extends JavaScriptParseTreeWriter {
|
||||
constructor(moduleName, outputPath) {
|
||||
super(outputPath);
|
||||
this.libName = moduleName
|
||||
.replace(/\//g, '.')
|
||||
.replace(/[^\w.]/g, '_');
|
||||
}
|
||||
|
||||
// VARIABLES - types
|
||||
// ```
|
||||
// var foo:bool = true;
|
||||
// ==>
|
||||
// bool foo = true;
|
||||
// ```
|
||||
visitVariableDeclarationList(tree) {
|
||||
// Write `var`, only if no type declaration.
|
||||
if (!tree.declarations[0].typeAnnotation) {
|
||||
this.write_(tree.declarationType);
|
||||
this.writeSpace_();
|
||||
}
|
||||
|
||||
this.writeList_(tree.declarations, COMMA, true, 2);
|
||||
}
|
||||
|
||||
visitVariableDeclaration(tree) {
|
||||
this.writeType_(tree.typeAnnotation);
|
||||
this.visitAny(tree.lvalue);
|
||||
|
||||
if (tree.initializer !== null) {
|
||||
this.writeSpace_();
|
||||
this.write_(EQUAL);
|
||||
this.writeSpace_();
|
||||
this.visitAny(tree.initializer);
|
||||
}
|
||||
}
|
||||
|
||||
// FUNCTIONS
|
||||
// - remove the "function" keyword
|
||||
// - type annotation infront
|
||||
visitFunction_(tree) {
|
||||
this.writeAnnotations_(tree.annotations);
|
||||
if (tree.isAsyncFunction()) {
|
||||
this.write_(tree.functionKind);
|
||||
}
|
||||
|
||||
if (tree.isGenerator()) {
|
||||
this.write_(tree.functionKind);
|
||||
}
|
||||
|
||||
if (tree.name) {
|
||||
this.writeType_(tree.typeAnnotation);
|
||||
this.visitAny(tree.name);
|
||||
}
|
||||
|
||||
this.write_(OPEN_PAREN);
|
||||
this.visitAny(tree.parameterList);
|
||||
this.write_(CLOSE_PAREN);
|
||||
this.writeSpace_();
|
||||
this.visitAny(tree.body);
|
||||
};
|
||||
|
||||
// Class methods.
|
||||
// - type annotation infront
|
||||
visitPropertyMethodAssignment(tree) {
|
||||
this.writeAnnotations_(tree.annotations);
|
||||
|
||||
if (tree.isStatic) {
|
||||
this.write_(STATIC);
|
||||
this.writeSpace_();
|
||||
}
|
||||
|
||||
if (tree.isGenerator()) {
|
||||
this.write_(STAR);
|
||||
}
|
||||
|
||||
if (tree.isAsyncFunction()) {
|
||||
this.write_(ASYNC);
|
||||
}
|
||||
|
||||
this.writeType_(tree.typeAnnotation);
|
||||
this.visitAny(tree.name);
|
||||
this.write_(OPEN_PAREN);
|
||||
this.visitAny(tree.parameterList);
|
||||
this.write_(CLOSE_PAREN);
|
||||
this.writeSpace_();
|
||||
this.visitAny(tree.body);
|
||||
}
|
||||
|
||||
normalizeType_(typeName) {
|
||||
if (typeName === 'number') {
|
||||
return 'int';
|
||||
}
|
||||
|
||||
if (typeName === 'boolean') {
|
||||
return 'bool';
|
||||
}
|
||||
|
||||
if (typeName === 'string') {
|
||||
return 'String';
|
||||
}
|
||||
|
||||
return typeName;
|
||||
}
|
||||
|
||||
// FUNCTION/METHOD ARGUMENTS
|
||||
// - type infront of the arg name
|
||||
visitBindingElement(tree) {
|
||||
// TODO(vojta): This is awful, just copy/pasted from Traceur,
|
||||
// we should still clean it up.
|
||||
var typeAnnotation = this.currentParameterTypeAnnotation_;
|
||||
// resetting type annotation so it doesn't filter down recursively
|
||||
this.currentParameterTypeAnnotation_ = null;
|
||||
|
||||
this.writeType_(typeAnnotation);
|
||||
this.visitAny(tree.binding);
|
||||
|
||||
if (tree.initializer) {
|
||||
this.writeSpace_();
|
||||
this.write_(EQUAL);
|
||||
this.writeSpace_();
|
||||
this.visitAny(tree.initializer);
|
||||
}
|
||||
}
|
||||
|
||||
visitClassField(tree) {
|
||||
this.writeType_(tree.typeAnnotation);
|
||||
|
||||
if (!tree.typeAnnotation) {
|
||||
this.write_('var ');
|
||||
}
|
||||
|
||||
this.write_(tree.identifier);
|
||||
this.write_(SEMI_COLON);
|
||||
}
|
||||
|
||||
writeType_(typeAnnotation) {
|
||||
if (!typeAnnotation) {
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO(vojta): Figure out why `typeAnnotation` has different structure when used with a variable.
|
||||
// This should probably be fixed in Traceur.
|
||||
var typeName = typeAnnotation.typeToken && typeAnnotation.typeToken.value || (typeAnnotation.name && typeAnnotation.name.value) || null;
|
||||
|
||||
if (!typeName) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.write_(this.normalizeType_(typeName));
|
||||
this.writeSpace_();
|
||||
}
|
||||
|
||||
// EXPORTS
|
||||
visitExportDeclaration(tree) {
|
||||
if (tree.declaration.moduleSpecifier) {
|
||||
this.write_('export ');
|
||||
this.visitModuleSpecifier(tree.declaration.moduleSpecifier);
|
||||
this.write_(SEMI_COLON);
|
||||
} else {
|
||||
// remove "export"
|
||||
this.writeAnnotations_(tree.annotations);
|
||||
this.visitAny(tree.declaration);
|
||||
}
|
||||
}
|
||||
|
||||
// visitExportDefault
|
||||
// visitNamedExport
|
||||
// visitExportSpecifier
|
||||
// visitExportSpecifierSet
|
||||
// visitExportStar
|
||||
|
||||
|
||||
// IMPORTS
|
||||
visitImportDeclaration(tree) {
|
||||
this.write_(IMPORT);
|
||||
this.writeSpace_();
|
||||
this.visitAny(tree.moduleSpecifier);
|
||||
|
||||
if (tree.importClause.binding) {
|
||||
// Default import - import the entire module.
|
||||
// import foo from './bar';
|
||||
this.write_(' as ');
|
||||
this.visitAny(tree.importClause.binding);
|
||||
} else {
|
||||
// Regular - import list of members.
|
||||
// import {Foo, Bar} from './baz';
|
||||
this.visitAny(tree.importClause);
|
||||
}
|
||||
|
||||
this.write_(SEMI_COLON);
|
||||
}
|
||||
|
||||
// Translate './foo' -> './foo.dart'
|
||||
transformModuleUrl(url) {
|
||||
var prefix = url.charAt(1) === '.' ? '' : 'package:';
|
||||
return "'" + prefix + url.substring(1, url.length - 1) + ".dart'";
|
||||
}
|
||||
|
||||
visitModuleSpecifier(tree) {
|
||||
this.write_(this.transformModuleUrl(tree.token.value));
|
||||
}
|
||||
|
||||
visitImportSpecifier(tree) {
|
||||
if (tree.name) {
|
||||
throw new Error('"as" syntax not supported');
|
||||
}
|
||||
this.visitAny(tree.binding);
|
||||
}
|
||||
|
||||
visitImportSpecifierSet(tree) {
|
||||
if (tree.specifiers.type == STAR) {
|
||||
throw new Error('"*" syntax not supported');
|
||||
} else {
|
||||
this.write_(' show ');
|
||||
this.writeList_(tree.specifiers, COMMA, false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ANNOTATIONS
|
||||
// TODO(vojta): this is just fixing a bug in Traceur, send a PR.
|
||||
visitAnnotation(tree) {
|
||||
if (tree.name.identifierToken) {
|
||||
var nameValue = tree.name.identifierToken.value;
|
||||
if (nameValue === nameValue.toUpperCase()) {
|
||||
// control annotations for transpiler
|
||||
return;
|
||||
}
|
||||
}
|
||||
this.write_(AT);
|
||||
this.visitAny(tree.name);
|
||||
|
||||
if (tree.args !== null) {
|
||||
this.write_(OPEN_PAREN);
|
||||
this.writeList_(tree.args.args, COMMA, false);
|
||||
this.write_(CLOSE_PAREN);
|
||||
}
|
||||
|
||||
this.writeSpace_()
|
||||
}
|
||||
|
||||
toString() {
|
||||
return "library " + this.libName + ";\n" + super.toString();
|
||||
}
|
||||
}
|
||||
|
64
tools/transpiler/src/parser.js
Normal file
64
tools/transpiler/src/parser.js
Normal file
@ -0,0 +1,64 @@
|
||||
import {Parser as TraceurParser} from 'traceur/src/syntax/Parser';
|
||||
import {SyntaxErrorReporter} from 'traceur/src/util/SyntaxErrorReporter';
|
||||
import {TypeName, ImportSpecifier, ImportedBinding, BindingIdentifier} from 'traceur/src/syntax/trees/ParseTrees';
|
||||
import {PERIOD, IMPORT, STAR, AS, FROM, CLOSE_ANGLE, OPEN_ANGLE, COMMA, OPEN_CURLY, CLOSE_CURLY, COLON} from 'traceur/src/syntax/TokenType';
|
||||
|
||||
var WRAPS = 'wraps';
|
||||
|
||||
export class Parser extends TraceurParser {
|
||||
constructor(file, errorReporter = new SyntaxErrorReporter()) {
|
||||
super(file, errorReporter);
|
||||
}
|
||||
|
||||
parseTypeName_() {
|
||||
// Copy of original implementation
|
||||
var typeName = super.parseTypeName_();
|
||||
var next = this.peekType_();
|
||||
// Generics support
|
||||
if (this.eatIf_(OPEN_ANGLE)) {
|
||||
var generics = [];
|
||||
do {
|
||||
generics.push(this.eatId_());
|
||||
} while(this.eatIf_(COMMA));
|
||||
this.eat_(CLOSE_ANGLE);
|
||||
// TODO: save the generics into the typeName and use them e.g. for assertions, ...
|
||||
}
|
||||
return typeName;
|
||||
}
|
||||
|
||||
parseImportSpecifier_() {
|
||||
// Copy of original implementation
|
||||
var start = this.getTreeStartLocation_();
|
||||
var token = this.peekToken_();
|
||||
var isKeyword = token.isKeyword();
|
||||
var binding;
|
||||
var name = this.eatIdName_();
|
||||
// Support for wraps keywoard
|
||||
if (this.peekToken_().value === WRAPS) {
|
||||
token = this.nextToken_();
|
||||
var wrappedIdentifier = this.eatId_();
|
||||
// TODO: Save the fact that this is a wrapper type and
|
||||
// also the wrapped type
|
||||
}
|
||||
// Copy of original implementation
|
||||
if (isKeyword || this.peekPredefinedString_(AS)) {
|
||||
this.eatId_(AS);
|
||||
binding = this.parseImportedBinding_();
|
||||
} else {
|
||||
binding = new ImportedBinding(name.location, new BindingIdentifier(name.location, name));
|
||||
name = null;
|
||||
}
|
||||
return new ImportSpecifier(this.getTreeLocation_(start), binding, name);
|
||||
}
|
||||
|
||||
parseObjectType_() {
|
||||
//TODO(misko): save the type information
|
||||
this.eat_(OPEN_CURLY);
|
||||
do {
|
||||
var identifier = this.eatId_();
|
||||
this.eat_(COLON);
|
||||
var type = this.parseNamedOrPredefinedType_();
|
||||
} while (this.eatIf_(COMMA));
|
||||
this.eat_(CLOSE_CURLY);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user