Skip to content

Commit

Permalink
Merge pull request #165 from ghy511024/fair_release_3.0
Browse files Browse the repository at this point in the history
dart2js 模块拆分
  • Loading branch information
yancechen authored Oct 21, 2022
2 parents d876809 + fd0f505 commit 91a362a
Show file tree
Hide file tree
Showing 77 changed files with 2,462 additions and 15 deletions.
11 changes: 10 additions & 1 deletion dart2js/README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
# fair_dart2js

fair_compiler 的配套编译器,用于将 Dart 转为 JS。
fair_compiler 的配套编译器,用于将 Dart 转为 JS。

### 开发功能记录
* try、catch
* 不支持 on 函数 例如 on Exception catch (e,s),此类写法将会抛弃处理,请直接写 catch (e)

### 待开发
#### 原生函数转换
* print
* Exception
4 changes: 3 additions & 1 deletion dart2js/lib/index.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
* found in the LICENSE file.
*/
import 'dart:async';
import './src/convertor.dart' show convertWidgetStateFile;

import 'src/convertorV2.dart';


Future<String> convertFile(String input, [bool compress = false]) async {
return convertWidgetStateFile(input, compress);
Expand Down
22 changes: 22 additions & 0 deletions dart2js/lib/src/__test_data__/tryCatch/tryTest.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import 'package:fair_dart2js/src/covert/convertFunction.dart';
/**
* 正常测试 try catch
* */

String a = convertFunction('''
void testTry() {
try {
int a=1;
int b=2;
int c=a+b;
print("1");
throw FormatException('Expected at least 1 section');
} catch (e,s) {
print('111'+e);
}
}
''');

void main() {
print(a);
}
25 changes: 25 additions & 0 deletions dart2js/lib/src/__test_data__/tryCatch/tryTest2.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import 'package:fair_dart2js/src/covert/convertFunction.dart';

/**
* 测试 on 函数将被丢弃
* */

String a = convertFunction('''
void testTry() {
try {
int a=1;
int b=2;
int c=a+b;
print("1");
throw FormatException('Expected at least 1 section');
} on Exception catch (e,s) {
print('111'+e);
} catch (e) {
print('222'+e);
}
}
''');

void main() {
print(a);
}
21 changes: 21 additions & 0 deletions dart2js/lib/src/__test_data__/tryCatch/tryTest3.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import 'package:fair_dart2js/src/covert/convertFunction.dart';

/**
* 测试 finally 处理
* */

String a = convertFunction('''
void testTry() {
try {
int a=1;
} catch (e,s) {
print('catch:'+e);
} finally{
print('finally...');
}
}
''');

void main() {
print(a);
}
2 changes: 2 additions & 0 deletions dart2js/lib/src/convertor.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1754,3 +1754,5 @@ String uglify(String str) {
}
return buf.toString();
}


14 changes: 14 additions & 0 deletions dart2js/lib/src/convertorV2.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export 'covert/convertClassString.dart';
export 'covert/convertExpression.dart';
export 'covert/convertFunction.dart';
export 'covert/convertArrayFuncExpression.dart';
export 'covert/convertBlock.dart';
export 'covert/convertFunctionExpression.dart';
export 'covert/convertStatements.dart';
export 'covert/convertWidgetStateFile.dart';
export 'covert/convertFunctionFromData.dart';
export 'declaration/ClassDeclarationData.dart';
export 'declaration/FieldDeclarationData.dart';
export 'declaration/MethodDeclarationData.dart';


43 changes: 30 additions & 13 deletions dart2js/lib/src/convertor_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
* Use of this source code is governed by a BSD type license that can be
* found in the LICENSE file.
*/
import 'convertor.dart';
import 'convertorV2.dart';
import 'dart:io' show Platform;
import 'package:fair_dart2js/src/visitor/UniqueNameGenerator.dart';
import 'package:path/path.dart' show dirname;

bool compare(String testcaseName, String actual, String expected) {
Expand All @@ -13,7 +14,7 @@ bool compare(String testcaseName, String actual, String expected) {
}

var isNotEqual = (actual.isEmpty && expected.isNotEmpty) ||
(actual.isNotEmpty && expected.isEmpty);
(actual.isNotEmpty && expected.isEmpty);
if (isNotEqual) {
print('''$testcaseName Actual: $actual \r\nExpected: $expected''');
return false;
Expand All @@ -31,7 +32,8 @@ bool compare(String testcaseName, String actual, String expected) {
continue;
}
if (actual[i] != expected[j]) {
print('''$testcaseName Actual: $actual \r\nExpected: $expected \r\nat position $i(${actual.substring(i, i+30)}) $j(${expected.substring(j, j+30)})''');
print(
'''$testcaseName Actual: $actual \r\nExpected: $expected \r\nat position $i(${actual.substring(i, i + 30)}) $j(${expected.substring(j, j + 30)})''');
return false;
} else {
i++;
Expand All @@ -43,7 +45,8 @@ bool compare(String testcaseName, String actual, String expected) {
i++;
continue;
} else {
print('''$testcaseName Actual: $actual \r\nExpected: $expected \r\nat position $i(${actual[i]}) $j()''');
print(
'''$testcaseName Actual: $actual \r\nExpected: $expected \r\nat position $i(${actual[i]}) $j()''');
return false;
}
}
Expand All @@ -52,7 +55,8 @@ bool compare(String testcaseName, String actual, String expected) {
j++;
continue;
} else {
print('''$testcaseName Actual: $actual \r\nExpected: $expected \r\nat position $i() $j(${expected[j]})''');
print(
'''$testcaseName Actual: $actual \r\nExpected: $expected \r\nat position $i() $j(${expected[j]})''');
return false;
}
}
Expand Down Expand Up @@ -1002,12 +1006,20 @@ bool testcaseDeclareList() {
}

bool testcaseSuper() {
return compare('testcaseSuper', convertFunctionFromData(MethodDeclarationData('testcaseSuper', '''
return compare(
'testcaseSuper',
convertFunctionFromData(
MethodDeclarationData(
'testcaseSuper',
'''
void testcaseSuper() {
super.initState();
futureBuilderFuture = _generateData(this);
}
''', false), ClassDeclarationData()..parentClass='Parent'), '''
''',
false),
ClassDeclarationData()..parentClass = 'Parent'),
'''
function testcaseSuper() {
const __thiz__ = this;
Expand Down Expand Up @@ -1418,7 +1430,8 @@ res.total = json.total;

bool testcaseClassDeclareFactoryConstructor() {
UniqueNameGenerator().reset();
return compare('testcaseClassDeclareFactoryConstructor', convertClassString(r'''
return compare(
'testcaseClassDeclareFactoryConstructor', convertClassString(r'''
class E {
int e;
Expand Down Expand Up @@ -1472,7 +1485,8 @@ E.ee1 = (str) => E.ee(int.parse(str));

bool testcaseClassDeclareDelegateConstructor() {
UniqueNameGenerator().reset();
return compare('testcaseClassDeclareDelegateConstructor', convertClassString(r'''
return compare(
'testcaseClassDeclareDelegateConstructor', convertClassString(r'''
class E {
int e;
Expand Down Expand Up @@ -1666,7 +1680,7 @@ b = 1;
// print(super.a.b);
// }
// '''), '''

// ''');
// }

Expand Down Expand Up @@ -2474,7 +2488,11 @@ this.g3 = xx;
}

bool testcaseImport() {
return compare('testcaseImport', convertWidgetStateFile(dirname(Platform.script.path) + '/__test_data__/page1/page1.dart'), '''
return compare(
'testcaseImport',
convertWidgetStateFile(
dirname(Platform.script.path) + '/__test_data__/page1/page1.dart'),
'''
GLOBAL['#FairKey#'] = (function(__initProps__) {
const __global__ = this;
defineModule(5, function(__mod__) {
Expand Down Expand Up @@ -2765,7 +2783,6 @@ fairProps = widget._props;
}

void main() {

print('Executing testcases...');
var arr = [
testcaseFor1,
Expand Down Expand Up @@ -2844,4 +2861,4 @@ void main() {
} else {
print('''Testcase total ${arr.length} successful''');
}
}
}
21 changes: 21 additions & 0 deletions dart2js/lib/src/covert/convertArrayFuncExpression.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import 'package:analyzer/dart/ast/ast.dart';

import '../node/ArrowFunctionExpressionNode.dart';
import '../node/GenericStatementNode.dart';
import 'convertExpression.dart';

String convertArrayFuncExpression(FunctionExpression code) {
var body = code.body as ExpressionFunctionBody;
if (body.functionDefinition.toString() == '=>') {
var gnNode = ArrowFunctionExpressionNode();
// TODO: 支持命名参数、可选参数
code.parameters?.parameters.forEach((element) {
gnNode.argumentList.add([element.identifier.toString()]);
});
gnNode.body.push(
GenericStatementNode(convertExpression(body.expression.toString())));
return gnNode.toSource();
} else {
throw 'error';
}
}
22 changes: 22 additions & 0 deletions dart2js/lib/src/covert/convertBlock.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import 'package:analyzer/dart/analysis/utilities.dart';

import '../visitor/SimpleFunctionGenerator.dart';
import '../funs/shouldErrorBeIgnored.dart';

String convertBlock(String code) {
// print("[convertBlock]" + code);
var res = parseString(
content: '''dummy() async $code''', throwIfDiagnostics: false);

if (res.errors.isNotEmpty) {
if (shouldErrorBeIgnored(res.errors)) {
// ignore
} else {
throw ArgumentError();
}
}

var generator = SimpleFunctionGenerator();
res.unit.visitChildren(generator);
return generator.func?.body.toSource() ?? '';
}
12 changes: 12 additions & 0 deletions dart2js/lib/src/covert/convertClassString.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import 'package:analyzer/dart/analysis/features.dart';
import 'package:analyzer/dart/analysis/utilities.dart';

import '../visitor/ClassDeclarationVisitor.dart';

String convertClassString(String content, [bool isDataBean = false]) {
var result =
parseString(content: content, featureSet: FeatureSet.fromEnableFlags([]));
var visitor = ClassDeclarationVisitor(isDataBean);
result.unit.visitChildren(visitor);
return visitor.genJsCode();
}
22 changes: 22 additions & 0 deletions dart2js/lib/src/covert/convertExpression.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import 'convertStatements.dart';

String convertExpression(String code) {
// print("[convertExpression]" + code);
var res = '';
var start = 0;
try {
res = convertStatements(code + ';');
res = res.trim();
} on ArgumentError {
// 有些表达式直接变成语句会报错,例如字典字面量对象
var prefix = 'var __variable__ = ';
res = convertStatements('''$prefix$code;''');
res = res.trim();
start = res.indexOf('=') + 1;
}
var end = res.length - 1;
while (end >= 0 && RegExp(r'[\s\r\n;]', multiLine: false).hasMatch(res[end])) {
end--;
}
return res.substring(start, end + 1);
}
16 changes: 16 additions & 0 deletions dart2js/lib/src/covert/convertFunction.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import 'package:analyzer/dart/analysis/utilities.dart';

import '../visitor/SimpleFunctionGenerator.dart';

String convertFunction(String code,
{bool isArrow = false,
bool isClassMethod = false,
bool classHasStaticFields = false}) {
var res = parseString(content: code);
var generator = SimpleFunctionGenerator(isArrowFunc: isArrow);
res.unit.visitChildren(generator);
generator.func
?..withContext = isClassMethod
..classHasStaticFields = classHasStaticFields;
return generator.func?.toSource() ?? '';
}
6 changes: 6 additions & 0 deletions dart2js/lib/src/covert/convertFunctionExpression.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import 'convertFunction.dart';

String convertFunctionExpression(String code) {
code = 'dummy' + code;
return convertFunction(code);
}
Loading

0 comments on commit 91a362a

Please sign in to comment.