├── .actionScriptProperties
├── .flexLibProperties
├── .gitignore
├── .project
├── .settings
└── org.eclipse.core.resources.prefs
├── ActionScriptInJavaScript.js
├── Demo(cocos).js
├── Demo(egret).js
├── Demo.as
├── Demo.js
├── LICENSE
├── README.md
├── bin
└── ActionScriptToOther.swc
└── src
├── how.js
└── how
└── as2js
├── Config.as
├── Utils.as
├── codeDom
├── CALC.as
├── CodeArray.as
├── CodeAssign.as
├── CodeCallFunction.as
├── CodeClass.as
├── CodeCocos.as
├── CodeDelete.as
├── CodeEgret.as
├── CodeExecutable.as
├── CodeFor.as
├── CodeForSimple.as
├── CodeForeach.as
├── CodeForin.as
├── CodeFunction.as
├── CodeIf.as
├── CodeInstruction.as
├── CodeIsAs.as
├── CodeMember.as
├── CodeNew.as
├── CodeObject.as
├── CodeOperator.as
├── CodeScriptObject.as
├── CodeSuper.as
├── CodeSwitch.as
├── CodeTernary.as
├── CodeThrow.as
├── CodeTry.as
├── CodeVariable.as
├── CodeWhile.as
└── temp
│ ├── TempCase.as
│ ├── TempCondition.as
│ ├── TempData.as
│ └── TempOperator.as
├── compiler
├── LexState.as
├── ScriptLexer.as
├── ScriptParser.as
├── Token.as
└── TokenType.as
├── error
├── ParseError.as
└── StackInfo.as
└── runtime
├── Opcode.as
├── Runtime.as
└── ToJavaScript.as
/.actionScriptProperties:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/.flexLibProperties:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Build and Release Folders
2 | bin/
3 | bin-debug/
4 | bin-release/
5 |
6 | # Other files and folders
7 | .settings/
8 |
9 | # Project files, i.e. `.project`, `.actionScriptProperties` and `.flexProperties`
10 | # should NOT be excluded as they contain compiler settings and other important
11 | # information for Eclipse / Flash Builder.
12 |
--------------------------------------------------------------------------------
/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | ActionScriptToOther
4 |
5 |
6 |
7 |
8 |
9 | com.adobe.flexbuilder.project.flexbuilder
10 |
11 |
12 |
13 |
14 |
15 | com.adobe.flexbuilder.project.flexlibnature
16 | com.adobe.flexbuilder.project.actionscriptnature
17 |
18 |
19 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.core.resources.prefs:
--------------------------------------------------------------------------------
1 | #Wed Nov 25 15:43:08 CST 2015
2 | eclipse.preferences.version=1
3 | encoding/=utf-8
4 |
--------------------------------------------------------------------------------
/Demo(cocos).js:
--------------------------------------------------------------------------------
1 | how = how || {};
2 | how.demo = how.demo || {};
3 | how.demo.Demo = cc.Class.extend({
4 | binds:function(){
5 | this.exec = this.exec.bind(this);
6 | },
7 | target:null,
8 | values:null,
9 | data:2,
10 | init:function (target,values){
11 | this._super();
12 | this.target = target;
13 | this.values = this.values;
14 | this.binds();
15 | },
16 | exec:function (){
17 | this.parseValue("target");
18 | this.parseValue("values");
19 | for(var at in this.values){
20 | this.target.at = this.values.at;
21 | }
22 | this.done();
23 | },
24 | })
25 | how.demo.Demo.data = 1;
--------------------------------------------------------------------------------
/Demo(egret).js:
--------------------------------------------------------------------------------
1 | (function(how){
2 | (function(demo){
3 | Demo = (function (_super) {
4 | __extends(Demo, _super);
5 | var d = __define,c=Demo;p=c.prototype;
6 | p[".init"] = function (){
7 | this.target = null;
8 | this.values = null;
9 | this.data = 2;
10 | };
11 | function Demo(target,values){
12 | _super();
13 | this[".init"]();
14 | this.target = target;
15 | this.values = this.values;
16 | };
17 | p.exec = function (){
18 | this.parseValue("target");
19 | this.parseValue("values");
20 | for(var at in this.values){
21 | this.target.at = this.values.at;
22 | }
23 | this.done();
24 | };
25 | Demo.data = 1;
26 | return Demo;
27 | })();
28 | how.demo.Demo = Demo;
29 | egret.registerClass(Demo,"how.demo.Demo");
30 | })(how.demo || (how.demo = {}));
31 | })(how || (how = {}));
--------------------------------------------------------------------------------
/Demo.as:
--------------------------------------------------------------------------------
1 | 用法:
2 | var scriptLexer:ScriptLexer = new ScriptLexer("Demo.as");
3 | var scriptParser:ScriptParser = new ScriptParser(scriptLexer.GetTokens(),scriptLexer.GetBreviary());
4 | var codeClass:CodeClass;
5 | Config.modol = 0;
6 | try
7 | {
8 | codeClass = scriptParser.Parse();
9 | }
10 | catch(error:Error)
11 | {
12 | if(error is ParseError)
13 | {
14 | trace(error.message);
15 | }
16 | else
17 | {
18 | var token:Token = scriptParser.PeekToken()
19 | var msg:String = " Line:" + (token.SourceLine+1) + " Column:" + token.SourceChar + " Type:" + TokenType.getTypeName(token.Type) + " value[" + token.Lexeme + "] " + error.message;
20 | trace(msg);
21 | }
22 | }
23 | if(codeClass)
24 | {
25 | new Runtime().registerClass(codeClass);//注册类,这样才能知道继承的对象的成员
26 | trace(codeClass.out(1));//把Demo.as转换成egret模式的Demo.js
27 | }
28 | --------------------------------------------------------------------------------------------------------------------------------
29 | "Demo.as":
30 | /**
31 | * 江左梅郎
32 | * @modol 1
33 | * @bind true
34 | */
35 | package how.demo
36 | {
37 | import how.behaviour.Action;
38 | public class Demo
39 | {
40 | private var target: Object;
41 | private var values: Object;
42 | private var data:int = 2;
43 | private static var data:int = 1;
44 | public function Demo(target: Object,values: Object)
45 | {
46 | super();
47 | this.target = target;
48 | this.values = values;
49 | }
50 | public function exec(): void {
51 | this.parseValue("target");
52 | this.parseValue("values");
53 | for(var at in this.values) {
54 | this.target[at] = this.values[at];
55 | }
56 | this.done();
57 | }
58 | }
59 | }
--------------------------------------------------------------------------------
/Demo.js:
--------------------------------------------------------------------------------
1 | how = how || {};
2 | how.demo = how.demo || {};
3 | how.demo.Demo = Class.extend({
4 | binds:function(){
5 | this.exec = this.exec.bind(this);
6 | },
7 | target:null,
8 | values:null,
9 | data:2,
10 | init:function (target,values){
11 | this.base();
12 | this.target = target;
13 | this.values = this.values;
14 | this.binds();
15 | },
16 | exec:function (){
17 | this.parseValue("target");
18 | this.parseValue("values");
19 | for(var at in this.values){
20 | this.target.at = this.values.at;
21 | }
22 | this.done();
23 | },
24 | })
25 | how.demo.Demo.data = 1;
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2015 qibu111
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
23 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ###简要说明
2 |
3 | 可以把ActionScript3.0代码转换成JavaScript代码。
4 |
5 | 配合ActionScriptForUnity框架,可以直接用as3开发egret、cocos和unity游戏。
6 |
7 | 此库是as3写的,开发者可以用Adobe AIR技术迅速开发出代码转换程序。也可以利用本人的行为IDE来转换代码。
8 |
9 | 转换前:https://github.com/qibu111/ActionScriptToOther/blob/master/Demo.as
10 |
11 | 转换后:https://github.com/qibu111/ActionScriptToOther/blob/master/Demo.js
12 |
13 | 转换后:https://github.com/qibu111/ActionScriptToOther/blob/master/Demo(egret).js
14 |
15 | 转换后:https://github.com/qibu111/ActionScriptToOther/blob/master/Demo(cocos).js
16 |
17 | 提供行为IDE来验证实际效果,下载地址:http://pan.baidu.com/s/1i3XvvYd
18 |
19 | 下面的js脚本是可以直接在js的环境动态执行as3代码。原理很简单,就是把这个库直接转换成js的版本。
20 |
21 | 这个js脚本是egret模式导出的,可以在egret引擎里面验证效果:https://github.com/qibu111/ActionScriptToOther/blob/master/ActionScriptInJavaScript.js
22 |
23 | asInjs库里面需要的Vector类等都需要用egret实现一个相关的类
24 |
25 | ----------------------------------------------------------------------------------------------------------------------
26 |
27 | ###暂不支持
28 |
29 | 定义十六进制数据(可用parseInt("0x000fff")暂时代替)
30 |
31 | 强制转换
32 |
33 | use namespace关键字
34 |
35 | 对象作key
36 |
37 | 默认模式和cocos2d-js模式不支持重写get/set,egret模式不支持单独只重写get/set中的某一个
38 |
39 | 默认模式、cocos2d-js模式都不支持super调用父类其他方法和属性,egret完美支持
40 |
41 | ----------------------------------------------------------------------------------------------------------------------
42 |
43 | ###注意事项
44 |
45 | if、else等后面必须带括号
46 |
47 | 如果继承的是egret或者cocos的类,那么必须加this
48 |
49 | 文件开头注释中加入@modol 1可设置导出模式,设置@bind true可绑定成员方法的执行上下文为this
50 |
51 | egret模式可以继承egret引擎中的类,其他模式也一样,模式切换在Config类中
52 |
53 | int、Number、Boolean默认值是null
54 |
55 | js对象的方法都用了 bind(this) 来绑定上下文
56 |
57 | api命名比较乱注释也不齐全,因为是用本人另一个C#版本的as3解释器的核心库翻译过来的,C#版本支持运行as3代码,不支持导出js,地址:http://git.oschina.net/jianyumofa/ActionScriptForUnity/
58 |
59 | 暂时不支持runtime,不能运行时解释as3代码,后续会支持
60 |
61 | 此库是as3版本,可以利用此库编译成js版本
62 |
63 | 暂时只支持导出js,后续会支持ts、c#、java
64 |
65 | 最终是as3可以导出大部分语言、也可以直接运行在cocos、unity3d、egret等引擎上
66 |
67 | 默认模式生成的js文件需要先导入how.js库才能运行
68 |
69 | 可以调用任何H5引擎的api
70 |
71 | ----------------------------------------------------------------------------------------------------------------------
72 |
73 | 附:ActionScriptForUnity地址:http://git.oschina.net/jianyumofa/ActionScriptForUnity/
--------------------------------------------------------------------------------
/bin/ActionScriptToOther.swc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qibu111/ActionScriptToOther/b62f887aa827fcebdaf56b6fe65bf57cbaf20ea7/bin/ActionScriptToOther.swc
--------------------------------------------------------------------------------
/src/how.js:
--------------------------------------------------------------------------------
1 | (function(){
2 | var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\bbase\b/ : /.*/;
3 |
4 | // The base Class implementation (does nothing)
5 | this.Class = function(){};
6 |
7 | // Create a new Class that inherits from this class
8 | Class.extend = function(prop) {
9 | var base = this.prototype;
10 |
11 | // Instantiate a base class (but only create the instance,
12 | // don't run the init constructor)
13 | initializing = true;
14 | var prototype = new this();
15 | initializing = false;
16 |
17 | // Copy the properties over onto the new prototype
18 | for (var name in prop) {
19 | // Check if we're overwriting an existing function
20 | prototype[name] = typeof prop[name] == "function" &&
21 | typeof base[name] == "function" && fnTest.test(prop[name]) ?
22 | (function(name, fn){
23 | return function() {
24 | var tmp = this.base;
25 |
26 | // Add a new .base() method that is the same method
27 | // but on the super-class
28 | this.base = base[name];
29 |
30 | // The method only need to be bound temporarily, so we
31 | // remove it when we're done executing
32 | var ret = fn.apply(this, arguments);
33 | this.base = tmp;
34 |
35 | return ret;
36 | };
37 | })(name, prop[name]) :
38 | prop[name];
39 | }
40 |
41 | // The dummy class constructor
42 | function Class() {
43 | // All construction is actually done in the init method
44 | if ( !initializing && this.init )
45 | this.init.apply(this, arguments);
46 | }
47 |
48 | // Populate our constructed prototype object
49 | Class.prototype = prototype;
50 |
51 | // Enforce the constructor to be what we expect
52 | Class.prototype.constructor = Class;
53 |
54 | // And make this class extendable
55 | Class.extend = arguments.callee;
56 |
57 | return Class;
58 | };
59 | })();
60 | if (!Function.prototype.bind) {
61 | Function.prototype.bind = function(obj) {
62 | var _self = this
63 | ,args = arguments;
64 | return function() {
65 | _self.apply(obj, Array.prototype.slice.call(args, 1));
66 | }
67 | }
68 | }
69 | Array.prototype.indexOf = functoin(){//暂时没空弄
70 | }
--------------------------------------------------------------------------------
/src/how/as2js/Config.as:
--------------------------------------------------------------------------------
1 | package how.as2js
2 | {
3 | public final class Config
4 | {
5 | /**
6 | * 暂时只支持0
7 | * 0:how,1:egret,2:cocos2d-js,3:babel
8 | */
9 | public static var modol:int = 0;
10 | /**
11 | * 是否单行显示
12 | */
13 | public static var oneLine:Boolean = false;
14 | /**
15 | * 制表符,默认4个空格
16 | */
17 | public static var tab:String = " ";
18 | /**
19 | * 换行符
20 | */
21 | public static var nextLine:String = "\n";
22 | /**
23 | * { 是否下一行显示
24 | */
25 | public static var leftBraceNextLine:Boolean = false;
26 | /**
27 | * 是否绑定this
28 | */
29 | public static var bind:Boolean = false;
30 | }
31 | }
--------------------------------------------------------------------------------
/src/how/as2js/Utils.as:
--------------------------------------------------------------------------------
1 | package how.as2js
2 | {
3 | public class Utils
4 | {
5 | private static var es6to5:Class;
6 | public static function IsLetter(str:String):Boolean
7 | {
8 | if (new RegExp("[A-Za-z]").test(str)){
9 | return true;
10 | }else{
11 | return false;
12 | }
13 | }
14 | public static function IsDigit(str:String):Boolean
15 | {
16 | if (new RegExp("[0-9]").test(str)){
17 | return true;
18 | }else{
19 | return false;
20 | }
21 | }
22 | public static function IsNullOrEmpty(str:String):Boolean
23 | {
24 | return str == null || str == "";
25 | }
26 | public static function IsLetterOrDigit(str:String):Boolean
27 | {
28 | if (new RegExp("[A-Za-z0-9]").test(str)){
29 | return true;
30 | }else{
31 | return false;
32 | }
33 | }
34 | }
35 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CALC.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 | public class CALC
4 | {
5 | public static const NONE:int = 0;
6 | public static const PRE_INCREMENT:int = 1; //前置++
7 | public static const POST_INCREMENT:int = 2; //后置++
8 | public static const PRE_DECREMENT:int = 3; //前置--
9 | public static const POST_DECREMENT:int = 4;//后置--
10 | }
11 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CodeArray.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 | public class CodeArray extends CodeObject
4 | {
5 | public var elements:Vector. = new Vector.();
6 | override public function out(tabCount:int):String
7 | {
8 | var result:String = "[";
9 | for (var i:int = 0; i < elements.length; i++)
10 | {
11 | elements[i].owner = owner;
12 | result += elements[i].out(tabCount)+",";
13 | }
14 | result += "]";
15 | return result;
16 | }
17 | }
18 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CodeAssign.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 | import how.as2js.compiler.TokenType;
4 |
5 | public class CodeAssign extends CodeObject
6 | {
7 | public var member:CodeMember;
8 | public var value:CodeObject;
9 | public var assignType:int;
10 | public function CodeAssign(member:CodeMember,value:CodeObject,assignType:int,breviary:String,line:int)
11 | {
12 | this.member = member;
13 | this.value = value;
14 | this.assignType = assignType;
15 | super(breviary, line)
16 | }
17 | override public function out(tabCount:int):String
18 | {
19 | var type:String;
20 | switch (assignType)
21 | {
22 | case TokenType.Assign:type="=";break;
23 | case TokenType.AssignPlus:type="+=";break;
24 | case TokenType.AssignMinus:type="-=";break;
25 | case TokenType.AssignMultiply:type="*=";break;
26 | case TokenType.AssignDivide:type="/=";break;
27 | case TokenType.AssignModulo:type="%=";break;
28 | case TokenType.AssignCombine:type="&=";break;
29 | case TokenType.AssignInclusiveOr:type="|=";break;
30 | case TokenType.AssignXOR:type="^=";break;
31 | case TokenType.AssignShr:type=">>=";break;
32 | case TokenType.AssignShi:type="<<=";break;
33 | default:type="未知运算符";break;
34 | }
35 | var v:String;
36 | member.owner = owner;
37 | value.owner = owner;
38 | v = value.out(tabCount);
39 | return member.out(tabCount) + " "+type+" " + v;
40 | }
41 | }
42 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CodeCallFunction.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 | public class CodeCallFunction extends CodeObject
4 | {
5 | public var member:CodeObject;
6 | public var parameters:Vector.;
7 | override public function outJS(tabCount:int):String
8 | {
9 | member.owner = owner;
10 | var arg:String = "";
11 | for (var i:int = 0; i < parameters.length; i++)
12 | {
13 | parameters[i].owner = owner;
14 | arg += parameters[i].out(tabCount);
15 | if(i != parameters.length - 1)
16 | {
17 | arg += ",";
18 | }
19 | }
20 | return member.out(tabCount) + "(" + arg + ")";
21 | }
22 | override public function outEgret(tabCount:int):String
23 | {
24 | member.owner = owner;
25 | var arg:String = "";
26 | for (var i:int = 0; i < parameters.length; i++)
27 | {
28 | parameters[i].owner = owner;
29 | arg += parameters[i].out(tabCount);
30 | if(i != parameters.length - 1)
31 | {
32 | arg += ",";
33 | }
34 | }
35 | return member.out(tabCount) + insertString + "(" + arg + ")";
36 | }
37 | }
38 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CodeClass.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 | import flash.utils.Dictionary;
4 |
5 | import how.as2js.Config;
6 | import how.as2js.codeDom.temp.TempData;
7 | import how.as2js.runtime.Runtime;
8 |
9 |
10 | public class CodeClass extends CodeObject
11 | {
12 | public var modifierType:int;//修饰符
13 | public var name:String;//类名
14 | public var parent:String;//父类
15 | public var packAge:String;//包名
16 | public var isDynamic:Boolean;//是否是动态类
17 | public var isFinal:Boolean;//是否是终级类
18 | public var imports:Vector. = new Vector.();//导入列表
19 | public var variables:Vector. = new Vector.();
20 | public var functions:Vector. = new Vector.(); //父指令
21 | public var tempData:TempData = new TempData();
22 | protected var runTime:Runtime;
23 | public function get classPath():String
24 | {
25 | if(packAge.length)
26 | {
27 | return packAge+"."+name;
28 | }
29 | else
30 | {
31 | return name;
32 | }
33 | }
34 | public function outClass(runTime:Runtime):String
35 | {
36 | this.runTime = runTime;
37 | return out(0);
38 | }
39 | override public function out(tabCount:int):String
40 | {
41 | tabCount++;
42 | setTempData();
43 | return getBody(tabCount);
44 | }
45 | protected function getBody(tabCount:int):String
46 | {
47 | return toPackage(tabCount-1)+packAge+(packAge.length?".":"")+name+" = "+toParent()+".extend"+(Config.leftBraceNextLine?"\n":"")+"({\n"+toBindFunction(tabCount)+toVariable(tabCount)+toFunction(tabCount)+"})\n"+toGetSetFunction(tabCount-1)+toStaticVariable(tabCount-1)+toStaticFunction(tabCount-1);
48 | }
49 | public function toParent():String
50 | {
51 | if(parent)
52 | {
53 | return tempData.importTempData[parent]?tempData.importTempData[parent]:parent;
54 | }
55 | else
56 | {
57 | return "Class";
58 | }
59 | }
60 | protected function toPackage(tabCount:int):String
61 | {
62 | var result:String = "";
63 | if(packAge.length)
64 | {
65 | var packs:Array = packAge.split(".");
66 | result = ""+packs[0]+" = "+packs[0]+" || {};\n";
67 | tempData.thisTempData[packs[0]] = null;
68 | if(packs.length > 1)
69 | {
70 | var pack:String = packs[0]+".";
71 | for (var i:int = 1; i < packs.length; i++)
72 | {
73 | result = getTab(tabCount)+result + pack+packs[i]+" = "+pack+packs[i]+" || {};\n";
74 | pack += packs[i]+".";
75 | }
76 | }
77 | }
78 | return result;
79 | }
80 | protected function toImport(tabCount:int):String
81 | {
82 | var importString:String = "";
83 | if(packAge)
84 | {
85 | imports.push(packAge+"."+name);
86 | }
87 | for (var i:int = 0; i < imports.length; i++)
88 | {
89 | var importItems:Array = imports[i].split('.');
90 | tempData.importTempData[importItems[importItems.length-1]] = imports[i];
91 | }
92 | return getTab(tabCount)+"import:function()"+getLeftBrace(tabCount)+importString+getTab(tabCount)+"},\n";
93 | }
94 | // protected function toImport2(tabCount:int):String
95 | // {
96 | // var importString:String = "";
97 | // if(packAge)
98 | // {
99 | // imports.push(packAge+"."+name);
100 | // }
101 | // for (var i:int = 0; i < imports.length; i++)
102 | // {
103 | // var importItems:Array = imports[i].split('.');
104 | // tempData.thisTempData[importItems[importItems.length-1]] = null;
105 | // importString += getTab(tabCount+1)+"this."+importItems[importItems.length-1]+" = "+imports[i]+";\n";
106 | // }
107 | // return getTab(tabCount)+"import:function()"+getLeftBrace(tabCount)+importString+getTab(tabCount)+"},\n";
108 | // }
109 | protected function setTempData():void
110 | {
111 | tempData.tempData = new Dictionary();
112 | tempData.thisTempData = new Dictionary();
113 | tempData.staticTempData = new Dictionary();
114 | tempData.importTempData = new Dictionary();
115 | tempData.staticTempData[".this"] = packAge+(packAge.length?".":"")+name;
116 | for (var i:int = 0; i < variables.length; i++)
117 | {
118 | if(!variables[i].isStatic)
119 | {
120 | tempData.thisTempData[variables[i].key] = null;
121 | }
122 | else
123 | {
124 | tempData.staticTempData[variables[i].key] = null;
125 | }
126 | }
127 | for (i = 0; i < functions.length; i++)
128 | {
129 | var funName:String = functions[i].name;
130 | if(!functions[i].IsStatic && functions[i].name != name)
131 | {
132 | if(functions[i].type == CodeFunction.TYPE_GET)
133 | {
134 | tempData.thisTempData[funName.replace(".get","")] = null;
135 | }
136 | else if(functions[i].type == CodeFunction.TYPE_SET)
137 | {
138 | tempData.thisTempData[funName.replace(".get","")] = null;
139 | }
140 | else
141 | {
142 | tempData.thisTempData[funName] = null;
143 | }
144 | }
145 | else
146 | {
147 | if(functions[i].type == CodeFunction.TYPE_GET)
148 | {
149 | tempData.staticTempData[funName.replace(".get","")] = null;
150 | }
151 | else if(functions[i].type == CodeFunction.TYPE_SET)
152 | {
153 | tempData.staticTempData[funName.replace(".get","")] = null;
154 | }
155 | else
156 | {
157 | tempData.staticTempData[funName] = null;
158 | }
159 | }
160 | }
161 | var importString:String = "";
162 | if(packAge)
163 | {
164 | imports.push(packAge+"."+name);
165 | }
166 | for (i = 0; i < imports.length; i++)
167 | {
168 | var importItems:Array = imports[i].split('.');
169 | tempData.importTempData[importItems[importItems.length-1]] = imports[i];
170 | }
171 | var samePackageClass:Vector. = runTime.getClasses(packAge);
172 | for (var j:int = 0; j < samePackageClass.length; j++)
173 | {
174 | tempData.importTempData[samePackageClass[j].name] = samePackageClass[j].classPath;
175 | }
176 | if(parent)
177 | {
178 | this.copyTemData();
179 | }
180 | }
181 | public function copyTemData():void
182 | {
183 | var parentClass:CodeClass = runTime.getClass(tempData.importTempData[parent],parent);
184 | if(!parentClass)
185 | {
186 | return;
187 | }
188 | for (var i:int = 0; i < parentClass.functions.length; i++)
189 | {
190 | if(!tempData.thisTempData.hasOwnProperty(parentClass.functions[i].name) && parentClass.functions[i].name != parentClass.name && !parentClass.functions[i].IsStatic)
191 | {
192 | tempData.thisTempData[parentClass.functions[i].name] = parentClass.functions[i].name;
193 | }
194 | }
195 | for (var j:int = 0; j < parentClass.variables.length; j++)
196 | {
197 | if(!tempData.thisTempData.hasOwnProperty(parentClass.variables[j].key) && !parentClass.variables[j].isStatic)
198 | {
199 | tempData.thisTempData[parentClass.variables[j].key] = parentClass.variables[j].key;
200 | }
201 | }
202 |
203 | }
204 | protected function toVariable(tabCount:int):String
205 | {
206 | var variableString:String = "";
207 | for (var i:int = 0; i < variables.length; i++)
208 | {
209 | if(!variables[i].isStatic)
210 | {
211 | var value:String = variables[i].value?variables[i].value.out(0):"null";
212 | variableString += getTab(tabCount)+variables[i].key+":"+value+",\n";
213 | }
214 | }
215 | return variableString;
216 | }
217 | protected function toFunction(tabCount:int):String
218 | {
219 | var functionString:String = "";
220 | for (var i:int = 0; i < functions.length; i++)
221 | {
222 | if(!functions[i].IsStatic)
223 | {
224 | functions[i].executable.tempData = tempData;
225 | functions[i].isCtor = functions[i].name==name;
226 | if(functions[i].isCtor)
227 | {
228 | functions[i].insertString = toInsertFunction(tabCount+1);
229 | }
230 | var funName:String = functions[i].isCtor?"init":functions[i].name;
231 | funName = functions[i].type == CodeFunction.TYPE_GET || functions[i].type == CodeFunction.TYPE_SET?"\""+funName+"\"":funName;
232 | functionString += getTab(tabCount)+funName+":"+functions[i].out(tabCount)+",\n";
233 | }
234 | }
235 | return functionString;
236 | }
237 | protected function toStaticVariable(tabCount:int):String
238 | {
239 | var variableString:String = "";
240 | for (var i:int = 0; i < variables.length; i++)
241 | {
242 | if(variables[i].isStatic)
243 | {
244 | var value:String = variables[i].value?variables[i].value.out(0):"null";
245 | variableString += getTab(tabCount)+packAge+(packAge.length?".":"")+name+"."+variables[i].key+" = "+value+";\n";
246 | }
247 | }
248 | return variableString;
249 | }
250 | protected function toStaticFunction(tabCount:int):String
251 | {
252 | var functionString:String = "";
253 | for (var i:int = 0; i < functions.length; i++)
254 | {
255 | if(functions[i].IsStatic)
256 | {
257 | functions[i].executable.tempData = new TempData();
258 | functions[i].executable.tempData.staticTempData = new Dictionary();
259 | functions[i].executable.tempData.thisTempData = tempData.staticTempData;
260 | functions[i].executable.tempData.importTempData = tempData.importTempData;
261 | var funName:String = functions[i].name;
262 | functionString += getTab(tabCount)+packAge+(packAge.length?".":"")+name+"[\""+funName+"\"] = "+functions[i].out(tabCount)+"\n";
263 | }
264 | }
265 | return functionString;
266 | }
267 | protected function toBindFunction(tabCount:int):String
268 | {
269 | if(!Config.bind)
270 | {
271 | return "";
272 | }
273 | var bindString:String = "";
274 | for (var i:int = 0; i < functions.length; i++)
275 | {
276 | var funName:String = functions[i].name;
277 | if(functions[i].type == CodeFunction.TYPE_NORMAL && functions[i].name!=name)
278 | {
279 | bindString += getTab(tabCount+1)+"this."+funName+" = "+"this."+funName+".bind(this);\n";
280 | }
281 | }
282 | return getTab(tabCount)+"binds:function()"+getLeftBrace(tabCount)+bindString+getTab(tabCount)+"},\n";
283 | }
284 | protected function toInsertFunction(tabCount:int):String
285 | {
286 | var insertString:String = "";
287 | if(Config.bind)
288 | {
289 | insertString += getTab(tabCount)+"this.binds();\n";
290 | }
291 | return insertString;
292 | }
293 | protected function toGetSetFunction(tabCount:int):String
294 | {
295 | var functionString:String = "";
296 | var gets:Vector. = new Vector.();
297 | var sets:Vector. = new Vector.();
298 | for (var i:int = 0; i < functions.length; i++)
299 | {
300 | var funName:String = functions[i].name;
301 | if(functions[i].type == CodeFunction.TYPE_GET)
302 | {
303 | var getString:String;
304 | if(sets.indexOf(getSetString(tabCount,funName.replace(".get",".set"),functions[i].IsStatic)) != -1)
305 | {
306 | getString = getSetString(tabCount,funName.replace(".get",".set"),functions[i].IsStatic).replace(",null",","+packAge+(packAge.length?".":"")+name+(functions[i].IsStatic?"":".prototype")+"[\""+funName+"\"]");
307 | functionString = functionString.replace(getSetString(tabCount,funName.replace(".get",".set"),functions[i].IsStatic),"");
308 | }
309 | else
310 | {
311 | getString = getGetString(tabCount,funName,functions[i].IsStatic);
312 | }
313 | if(gets.indexOf(getGetString(tabCount,funName,functions[i].IsStatic)) == -1)
314 | {
315 | gets.push(getString);
316 | functionString += getString;
317 | }
318 | }
319 | if(functions[i].type == CodeFunction.TYPE_SET)
320 | {
321 | var setString:String;
322 | if(gets.indexOf(getGetString(tabCount,funName.replace(".set",".get"),functions[i].IsStatic)) != -1)
323 | {
324 | setString = getGetString(tabCount,funName.replace(".set",".get"),functions[i].IsStatic).replace(",null",","+packAge+(packAge.length?".":"")+name+(functions[i].IsStatic?"":".prototype")+"[\""+funName+"\"]");
325 | functionString = functionString.replace(getGetString(tabCount,funName.replace(".set",".get"),functions[i].IsStatic),"");
326 | }
327 | else
328 | {
329 | setString = getSetString(tabCount,funName,functions[i].IsStatic);
330 | }
331 | if(sets.indexOf(getSetString(tabCount,funName,functions[i].IsStatic)) == -1)
332 | {
333 | sets.push(setString);
334 | functionString += setString;
335 | }
336 | }
337 | }
338 | return functionString;
339 | }
340 | private function getGetString(tabCount:int,funName:String,isStatic:Boolean):String
341 | {
342 | return getTab(tabCount)+"Object.defineProperty("+packAge+(packAge.length?".":"")+name+(isStatic?"":".prototype")+",\""+funName.replace(".get","")+"\"," +
343 | packAge+"."+name+".prototype[\""+funName+"\"],null);\n";
344 | }
345 | private function getSetString(tabCount:int,funName:String,isStatic:Boolean):String
346 | {
347 | return getTab(tabCount)+"Object.defineProperty("+packAge+(packAge.length?".":"")+name+(isStatic?"":".prototype")+",\""+funName.replace(".set","")+"\",null," +
348 | packAge+"."+name+".prototype[\""+funName+"\"]);\n";
349 | }
350 | }
351 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CodeCocos.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 | public class CodeCocos extends CodeClass
4 | {
5 | override public function toParent():String
6 | {
7 | if(parent)
8 | {
9 | return tempData.importTempData[parent]?tempData.importTempData[parent]:parent;
10 | }
11 | else
12 | {
13 | return "cc.Class";
14 | }
15 | }
16 | }
17 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CodeDelete.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 | public class CodeDelete extends CodeObject
4 | {
5 | public var deleteObject:CodeObject;
6 | public function CodeDelete(deleteObject:CodeObject)
7 | {
8 | this.deleteObject = deleteObject;
9 | }
10 | override public function out(tabCount:int):String
11 | {
12 | deleteObject.owner = owner;
13 | return "delete " + deleteObject.out(tabCount);
14 | }
15 | }
16 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CodeEgret.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 | import flash.utils.Dictionary;
4 |
5 | import how.as2js.Config;
6 | import how.as2js.codeDom.temp.TempData;
7 |
8 | public class CodeEgret extends CodeClass
9 | {
10 | public function CodeEgret()
11 | {
12 | super();
13 | }
14 | override public function toParent():String
15 | {
16 | if(parent)
17 | {
18 | return tempData.importTempData[parent]?tempData.importTempData[parent]:parent;
19 | }
20 | else
21 | {
22 | return "";
23 | }
24 | }
25 | override public function out(tabCount:int):String
26 | {
27 | setTempData();
28 | var packageData:Array = toEgretPackage(tabCount);
29 | tabCount++;
30 | return packageData[0] + getBody(packageData[2]) + packageData[1];
31 | }
32 | override protected function getBody(tabCount:int):String
33 | {
34 | return getTab(tabCount)+name+" = (function (_super) {\n"+getTab(tabCount+1)+"__extends("+name+", _super);\n"+getTab(tabCount+1)+
35 | "var d = __define,c="+name+";p=c.prototype;\n"+
36 | toFunction(tabCount+1)+toVariable(tabCount+1)+toBindFunction(tabCount+1)+toGetSetFunction(tabCount+1)+
37 | toStaticVariable(tabCount+1)+getTab(tabCount+1)+"return "+name+";\n"+
38 | getTab(tabCount)+"})("+toParent()+");\n"+getTab(tabCount)+(packAge?packAge+(packAge.length?".":"")+
39 | name+" = "+name+";\n":"")+getTab(tabCount)+"egret.registerClass("+name+",\""+packAge+(packAge.length?".":"")+name+"\");";
40 | }
41 | override protected function toVariable(tabCount:int):String
42 | {
43 | var variableString:String = "";
44 | for (var i:int = 0; i < variables.length; i++)
45 | {
46 | if(!variables[i].isStatic)
47 | {
48 | if(variables[i].value)
49 | {
50 | variables[i].value.owner = new CodeExecutable(0);
51 | variables[i].value.owner.tempData = tempData;
52 | }
53 | var value:String = variables[i].value?variables[i].value.out(0):"null";
54 | variableString += getTab(tabCount+1)+"this."+variables[i].key+" = "+value+";\n";
55 | }
56 | }
57 | if(Config.bind)
58 | {
59 | variableString += getTab(tabCount+1)+"this.binds();\n";
60 | }
61 | return getTab(tabCount)+"p[\".init\"] = "+"function ()"+getLeftBrace(tabCount)+
62 | variableString+getTab(tabCount)+"};\n";
63 | }
64 | override protected function toStaticVariable(tabCount:int):String
65 | {
66 | var variableString:String = "";
67 | for (var i:int = 0; i < variables.length; i++)
68 | {
69 | if(variables[i].isStatic)
70 | {
71 | if(variables[i].value)
72 | {
73 | variables[i].value.owner = new CodeExecutable(0);
74 | variables[i].value.owner.tempData = tempData;
75 | }
76 | var value:String = variables[i].value?variables[i].value.out(0):"null";
77 | variableString += getTab(tabCount)+name+"."+variables[i].key+" = "+value+";\n";
78 | }
79 | }
80 | return variableString;
81 | }
82 | override protected function toFunction(tabCount:int):String
83 | {
84 | var functionString:String = "";
85 | for (var i:int = 0; i < functions.length; i++)
86 | {
87 | functions[i].executable.tempData = tempData;
88 | functions[i].isCtor = functions[i].name==name;
89 | var funName:String = functions[i].type == CodeFunction.TYPE_GET || functions[i].type == CodeFunction.TYPE_SET?"[\""+functions[i].name+"\"]":"."+functions[i].name;
90 | if(!functions[i].IsStatic)
91 | {
92 | if(functions[i].isCtor)
93 | {
94 | functions[i].insertString = toVariable(tabCount+1);
95 | functionString += getTab(tabCount)+functions[i].out(tabCount)+";\n";
96 | }
97 | else
98 | {
99 | functionString += getTab(tabCount)+"p"+funName+" = "+functions[i].out(tabCount)+";\n";
100 | }
101 | }
102 | else
103 | {
104 | functions[i].executable.tempData = new TempData();
105 | functions[i].executable.tempData.staticTempData = new Dictionary();
106 | functions[i].executable.tempData.thisTempData = tempData.staticTempData;
107 | functions[i].executable.tempData.importTempData = tempData.importTempData;
108 | functionString += getTab(tabCount)+name+funName+" = "+functions[i].out(tabCount)+";\n";
109 | }
110 | }
111 | return functionString;
112 | }
113 | override protected function toBindFunction(tabCount:int):String
114 | {
115 | if(!Config.bind)
116 | {
117 | return "";
118 | }
119 | var bindString:String = "";
120 | for (var i:int = 0; i < functions.length; i++)
121 | {
122 | var funName:String = functions[i].name;
123 | if(functions[i].type == CodeFunction.TYPE_NORMAL && functions[i].name!=name)
124 | {
125 | bindString += getTab(tabCount+1)+"this."+funName+" = "+"this."+funName+".bind(this);\n";
126 | }
127 | }
128 | return getTab(tabCount)+"p.binds = function()"+getLeftBrace(tabCount)+bindString+getTab(tabCount)+"},\n";
129 | }
130 | protected function toEgretPackage(tabCount:int):Array
131 | {
132 | var frist:String = "";
133 | var last:String = "";
134 | var newTabCount:int = tabCount;
135 | if(packAge.length)
136 | {
137 | var packs:Array = packAge.split(".");
138 | if(packs.length > 1)
139 | {
140 | var pack:String = "";
141 | for (var i:int = 0; i < packs.length; i++)
142 | {
143 | var path:String = pack+packs[i];
144 | frist = frist + getTab(tabCount+i)+"(function(" + packs[i] + "){\n";
145 | last = "\n"+getTab(tabCount+i)+"})(" + path + " || (" + path + " = {}));" + last;
146 | pack += packs[i]+".";
147 | newTabCount++;
148 | }
149 | }
150 | }
151 | return [frist,last,newTabCount];
152 | }
153 | override protected function toGetSetFunction(tabCount:int):String
154 | {
155 | var functionString:String = "";
156 | var gets:Vector. = new Vector.();
157 | var sets:Vector. = new Vector.();
158 | for (var i:int = 0; i < functions.length; i++)
159 | {
160 | var funName:String = functions[i].name;
161 | if(functions[i].type == CodeFunction.TYPE_GET)
162 | {
163 | var getString:String;
164 | if(sets.indexOf(getSetString(tabCount,funName.replace(".get",".set"),functions[i].IsStatic)) != -1)
165 | {
166 | getString = getSetString(tabCount,funName.replace(".get",".set"),functions[i].IsStatic).replace(",null",","+packAge+(packAge.length?".":"")+name+(functions[i].IsStatic?"":".prototype")+"[\""+funName+"\"]");
167 | functionString = functionString.replace(getSetString(tabCount,funName.replace(".get",".set"),functions[i].IsStatic),"");
168 | }
169 | else
170 | {
171 | getString = getGetString(tabCount,funName,functions[i].IsStatic);
172 | }
173 | if(gets.indexOf(getGetString(tabCount,funName,functions[i].IsStatic)) == -1)
174 | {
175 | gets.push(getString);
176 | functionString += getString;
177 | }
178 | }
179 | if(functions[i].type == CodeFunction.TYPE_SET)
180 | {
181 | var setString:String;
182 | if(gets.indexOf(getGetString(tabCount,funName.replace(".set",".get"),functions[i].IsStatic)) != -1)
183 | {
184 | setString = getGetString(tabCount,funName.replace(".set",".get"),functions[i].IsStatic).replace(",null",","+packAge+(packAge.length?".":"")+name+(functions[i].IsStatic?"":".prototype")+"[\""+funName+"\"]");
185 | functionString = functionString.replace(getGetString(tabCount,funName.replace(".set",".get"),functions[i].IsStatic),"");
186 | }
187 | else
188 | {
189 | setString = getSetString(tabCount,funName,functions[i].IsStatic);
190 | }
191 | if(sets.indexOf(getSetString(tabCount,funName,functions[i].IsStatic)) == -1)
192 | {
193 | sets.push(setString);
194 | functionString += setString;
195 | }
196 | }
197 | }
198 | return functionString;
199 | }
200 | private function getGetString(tabCount:int,funName:String,isStatic:Boolean):String
201 | {
202 | return getTab(tabCount)+"d(p"+",\""+funName.replace(".get","")+"\"," +
203 | "p[\""+funName+"\"],null);\n";
204 | }
205 | private function getSetString(tabCount:int,funName:String,isStatic:Boolean):String
206 | {
207 | return getTab(tabCount)+"d(p"+",\""+funName.replace(".set","")+"\",null," +
208 | "p[\""+funName+"\"]);\n";
209 | }
210 | }
211 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CodeExecutable.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 | import how.as2js.codeDom.temp.TempData;
4 |
5 | public class CodeExecutable extends CodeObject
6 | {
7 | public static const Block_Class:int = 0;
8 | public static const Block_None:int = 1;
9 | public static const Block_Block:int = 2;
10 | public static const Block_Function:int = 3;
11 | public static const Block_If:int = 4;
12 | public static const Block_ForBegin:int = 5;
13 | public static const Block_ForLoop:int = 6;
14 | public static const Block_For:int = 7;
15 | public static const Block_Foreach:int = 8;
16 | public static const Block_While:int = 9;
17 | public static const Block_Switch:int = 10;
18 | private var _block:int;
19 |
20 | public function get block():int
21 | {
22 | return _block;
23 | }
24 |
25 | public var instructions:Vector.; //指令列表
26 | private var _count:int;
27 | /**
28 | * 指令数量
29 | */
30 | public function get count():int
31 | {
32 | return _count;
33 | }
34 | public var parent:CodeExecutable; //父指令
35 | public var tempData:TempData;
36 | public var currentIndex:int = 0;
37 | public function CodeExecutable(block:int,parent:CodeExecutable = null)
38 | {
39 | this.parent = parent;
40 | _block = block;
41 | instructions = new Vector.();
42 | }
43 |
44 | //添加一条指令
45 | public function addInstruction(val:CodeInstruction):void
46 | {
47 | val.owner = this;
48 | instructions.push(val);
49 | }
50 | //指令添加完成
51 | public function endInstruction():void {
52 | _count = instructions.length;
53 | }
54 | public function getInstruction(index:int):CodeInstruction
55 | {
56 | return instructions[index];
57 | }
58 | override public function outJS(tabCount:int):String
59 | {
60 | var result:String = "";
61 | for (currentIndex = 0; currentIndex < instructions.length; currentIndex++)
62 | {
63 | result += instructions[currentIndex].out(tabCount);
64 | }
65 | return result;
66 | }
67 | override public function outEgret(tabCount:int):String
68 | {
69 | var result:String = hasSuper()?"":getTab(tabCount)+"this[\".init\"]();\n";
70 | result = "";
71 | for (currentIndex = 0; currentIndex < instructions.length; currentIndex++)
72 | {
73 | result += instructions[currentIndex].out(tabCount);
74 | }
75 | return result;
76 | }
77 | protected function hasSuper():Boolean
78 | {
79 | for (var i:int = 0; i < instructions.length; i++)
80 | {
81 | if(instructions[i].operand0 is CodeSuper)
82 | {
83 | return true;
84 | }
85 | }
86 | return false;
87 | }
88 | }
89 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CodeFor.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 |
4 | public class CodeFor extends CodeObject
5 | {
6 | public var beginExecutable:CodeExecutable; //开始执行
7 | public var condition:CodeObject; //跳出条件
8 | public var loopExecutable:CodeExecutable; //循环执行
9 | public var blockExecutable:CodeExecutable; //for内容
10 | public function CodeFor()
11 | {
12 |
13 | }
14 | public function SetContextExecutable(blockExecutable:CodeExecutable):void
15 | {
16 | this.blockExecutable = blockExecutable;
17 | }
18 | override public function out(tabCount:int):String
19 | {
20 | if(beginExecutable)
21 | {
22 | beginExecutable.parent = owner;
23 | beginExecutable.owner = owner;
24 | beginExecutable.tempData = owner.tempData;
25 | }
26 |
27 | if(condition)
28 | {
29 | condition.owner = owner;
30 | }
31 |
32 | if(loopExecutable)
33 | {
34 | loopExecutable.parent = owner;
35 | loopExecutable.owner = owner;
36 | loopExecutable.tempData = owner.tempData;
37 | }
38 |
39 | if(blockExecutable)
40 | {
41 | blockExecutable.parent = owner;
42 | blockExecutable.owner = owner;
43 | blockExecutable.tempData = owner.tempData;
44 | }
45 | return getTab(tabCount)+"for(" + (beginExecutable?beginExecutable.out(0).replace(";\n",""):"") + ";" + (condition?condition.out(0):"") + ";" + (loopExecutable?loopExecutable.out(0).replace(";\n",""):"")
46 | + ")"+getLeftBrace(tabCount) + (blockExecutable?blockExecutable.out(tabCount+1):"") + getTab(tabCount)+"}";
47 | }
48 | }
49 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CodeForSimple.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 | import flash.utils.Dictionary;
4 |
5 |
6 | public class CodeForSimple extends CodeObject
7 | {
8 | public var identifier:String;
9 | public var begin:CodeObject;
10 | public var finished:CodeObject;
11 | public var step:CodeObject;
12 | public var blockExecutable:CodeExecutable; //for内容
13 | public var variables:Dictionary; //变量
14 | public function CodeForSimple()
15 | {
16 | variables = new Dictionary();
17 | }
18 | public function SetContextExecutable(blockExecutable:CodeExecutable):void
19 | {
20 | blockExecutable = blockExecutable;
21 | }
22 | }
23 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CodeForeach.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 |
4 | public class CodeForeach extends CodeObject
5 | {
6 | public var identifier:String;
7 | public var loopObject:CodeObject;
8 | public var executable:CodeExecutable;
9 | public function CodeForeach()
10 | {
11 |
12 | }
13 | override public function out(tabCount:int):String
14 | {
15 | loopObject.owner = owner;
16 | if(executable)
17 | {
18 | executable.parent = owner;
19 | executable.owner = owner;
20 | executable.tempData = owner.tempData;
21 | }
22 | return getTab(tabCount)+"for each(var " + identifier + " in " + loopObject.out(0) + ")" + getLeftBrace(tabCount) +
23 | (executable?executable.out(tabCount+1):"") + getTab(tabCount) + "}";
24 | }
25 | }
26 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CodeForin.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 |
4 | public class CodeForin extends CodeObject
5 | {
6 | public var identifier:String;
7 | public var loopObject:CodeObject;
8 | public var executable:CodeExecutable;
9 | public function CodeForin()
10 | {
11 |
12 | }
13 | override public function out(tabCount:int):String
14 | {
15 | loopObject.owner = owner;
16 | if(executable)
17 | {
18 | executable.parent = owner;
19 | executable.owner = owner;
20 | executable.tempData = owner.tempData;
21 | }
22 | return getTab(tabCount)+"for(var " + identifier + " in " + loopObject.out(0) + ")" + getLeftBrace(tabCount) +
23 | executable.out(tabCount+1) + getTab(tabCount) + "}";
24 | }
25 | }
26 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CodeFunction.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 | import flash.utils.Dictionary;
4 |
5 | public class CodeFunction extends CodeObject
6 | {
7 | public static const TYPE_NORMAL:int = 0;
8 | public static const TYPE_GET:int = 1;
9 | public static const TYPE_SET:int = 2;
10 | public var type:int;
11 | public var IsStatic:Boolean;
12 | public var listParameters:Vector.; //参数
13 | public var listParameterTypes:Vector.; //参数类型
14 | public var listValues:Vector.;//默认值
15 | public var executable:CodeExecutable;//函数执行命令
16 | private var parameterCount:int; //参数个数
17 | private var params:Boolean; //参数个数
18 | public var name:String;
19 | public var isCtor:Boolean;//是否是构造函数
20 | public function CodeFunction(strName:String,listParameters:Vector.,listParameterTypes:Vector.,listValues:Vector.,executable:CodeExecutable,bParams:Boolean,IsStatic:Boolean,type:int)
21 | {
22 | this.name = strName;
23 | this.type = type;
24 | this.IsStatic = IsStatic;
25 | this.listParameters = listParameters;
26 | this.listParameterTypes = listParameterTypes;
27 | this.listValues = listValues;
28 | this.executable = executable;
29 | this.parameterCount = listParameters.length;
30 | this.params = bParams;
31 | }
32 | override public function outJS(tabCount:int):String
33 | {
34 | if(owner)
35 | {
36 | executable.tempData = owner.tempData;
37 | }
38 | executable.tempData.tempData = new Dictionary();
39 | var valuesString:String = "";
40 | for (var i:int = 0; i < listValues.length; i++)
41 | {
42 | valuesString += getTab(tabCount+1) + listParameters[i] + " = " + listParameters[i]+"!=null||"+listParameters[i]+"!=undefined?"+listParameters[i]+":" + listValues[i].out(0) + ";\n";
43 | }
44 | return "function"+(executable.parent?name:" ")+"("+toParam(tabCount)+")"+getLeftBrace(tabCount)+valuesString+executable.out(tabCount+1)+insertString+getTab(tabCount)+"}";
45 | }
46 | override public function outEgret(tabCount:int):String
47 | {
48 | if(owner)
49 | {
50 | executable.tempData = owner.tempData;
51 | }
52 | executable.tempData.tempData = new Dictionary();
53 | var valuesString:String = "";
54 | for (var i:int = 0; i < listValues.length; i++)
55 | {
56 | valuesString += getTab(tabCount+1) + listParameters[i] + " = " + listParameters[i]+"!=null||"+listParameters[i]+"!=undefined?"+listParameters[i]+":" + listValues[i].out(0) + ";\n";
57 | }
58 | return "function "+(isCtor?name:"")+"("+toParam(tabCount)+")"+getLeftBrace(tabCount)+valuesString+executable.out(tabCount+1)+getTab(tabCount)+"}";
59 | }
60 | protected function toParam(tabCount:int):String
61 | {
62 | var paramString:String = "";
63 | for (var i:int = 0; i < listParameters.length; i++)
64 | {
65 | if(params && i == parameterCount - 1)
66 | {
67 | paramString = paramString + "..." + listParameters[i];
68 | }
69 | else
70 | {
71 | paramString += listParameters[i];
72 | }
73 | executable.tempData.tempData[paramString] = null;
74 | if(i = new Vector.();
10 | public function AddElseIf(con:TempCondition):void
11 | {
12 | ElseIf.push(con);
13 | }
14 | override public function out(tabCount:int):String
15 | {
16 | If.allow.owner = owner;
17 | If.executable.parent = owner;
18 | If.executable.owner = owner;
19 | If.executable.tempData = owner.tempData;
20 | var result:String = getTab(tabCount)+"if("+If.allow.out(tabCount)+")"+getLeftBrace(tabCount)+If.executable.out(tabCount+1)+"\n"+getTab(tabCount)+"}\n";
21 | var elseifString:String = "";
22 | if(ElseIf.length)
23 | {
24 | for (var i:int = 0; i < ElseIf.length; i++)
25 | {
26 | ElseIf[i].allow.owner = owner;
27 | ElseIf[i].executable.parent = owner;
28 | ElseIf[i].executable.owner = owner;
29 | ElseIf[i].executable.tempData = owner.tempData;
30 | elseifString += getTab(tabCount)+"else if("+ElseIf[i].allow.out(tabCount)+")"+getLeftBrace(tabCount)+ElseIf[i].executable.out(tabCount+1)+"\n"+getTab(tabCount)+"}\n";
31 | }
32 |
33 | }
34 | var elseString:String = "";
35 | if(Else)
36 | {
37 | Else.executable.parent = owner;
38 | Else.executable.owner = owner;
39 | Else.executable.tempData = owner.tempData;
40 | elseString = getTab(tabCount)+"else"+getLeftBrace(tabCount)+Else.executable.out(tabCount+1)+"\n"+getTab(tabCount)+"}\n";
41 | }
42 | result += elseifString;
43 | result += elseString;
44 | result = result.substring(0,result.length-1);
45 | return result;
46 | }
47 | }
48 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CodeInstruction.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 | import how.as2js.runtime.Opcode;
4 |
5 | public class CodeInstruction extends CodeObject
6 | {
7 | private var _opcode:int;
8 |
9 | public function get opcode():int
10 | {
11 | return _opcode;
12 | }
13 |
14 | private var _operand0:CodeObject;
15 |
16 | public function get operand0():CodeObject
17 | {
18 | return _operand0;
19 | }
20 |
21 | private var _operand1:CodeObject;
22 |
23 | public function get operand1():CodeObject
24 | {
25 | return _operand1;
26 | }
27 |
28 | private var _value:Object;
29 |
30 | public function get value():Object
31 | {
32 | return _value;
33 | }
34 | public function CodeInstruction(opcode:int,operand0:CodeObject = null,operand1:CodeObject = null,value:Object = null)
35 | {
36 | this._opcode = opcode;
37 | this._operand0 = operand0;
38 | this._operand1 = operand1;
39 | this._value = value;
40 | }
41 |
42 | override public function out(tabCount:int):String
43 | {
44 | var result:String = "";
45 | switch (opcode)
46 | {
47 | case Opcode.VAR: result += convertVar(tabCount); break;
48 | // case Opcode.MOV: ProcessMov(); break;
49 | case Opcode.RET: result += convertRet(tabCount); break;
50 | case Opcode.RESOLVE: result += convertResolve(tabCount); break;
51 | case Opcode.CONTINUE: result += convertContinue(tabCount); break;
52 | case Opcode.BREAK: result += convertBreak(tabCount); break;
53 | case Opcode.CALL_FUNCTION: result += convertCallFunction(tabCount); break;
54 | case Opcode.CALL_IF: result += convertCallIf(tabCount); break;
55 | case Opcode.CALL_FOR: result += convertCallFor(tabCount); break;
56 | case Opcode.CALL_FORSIMPLE: result += convertCallForSimple(tabCount); break;
57 | case Opcode.CALL_FOREACH: result += convertCallForeach(tabCount); break;
58 | case Opcode.CALL_FORIN: result += convertCallForin(tabCount); break;
59 | case Opcode.CALL_WHILE: result += convertCallWhile(tabCount); break;
60 | case Opcode.CALL_SWITCH: result += convertCallSwitch(tabCount); break;
61 | case Opcode.CALL_TRY: result += convertTry(tabCount); break;
62 | case Opcode.THROW: result += convertThrow(tabCount); break;
63 | case Opcode.NEW: result += convertNew(tabCount); break;
64 | case Opcode.SUPER: result += convertSuper(tabCount); break;
65 | case Opcode.DELETE: result += convertDelete(tabCount); break;
66 | }
67 | return result;
68 | }
69 | protected function convertVar(tabCount:int):String
70 | {
71 | var name:String = value+"";
72 | owner.tempData.tempData[name] = null;
73 | var nextInstruction:CodeInstruction = owner.instructions[owner.currentIndex+1];
74 | if(nextInstruction && nextInstruction._operand0 is CodeAssign && ((nextInstruction._operand0 as CodeAssign).member.memberString == name))
75 | {
76 | nextInstruction._operand0.owner = owner;
77 | owner.currentIndex++;
78 | return getTab(tabCount)+"var "+nextInstruction._operand0.out(0)+";\n";
79 | }
80 | else
81 | {
82 | return getTab(tabCount)+"var "+name+" = null;\n";
83 | }
84 | }
85 | protected function convertResolve(tabCount:int):String
86 | {
87 | operand0.owner = owner;
88 | var result:String = getTab(tabCount)+operand0.out(tabCount)+";\n";
89 | return result;
90 | }
91 | protected function convertRet(tabCount:int):String
92 | {
93 | if(operand0)
94 | {
95 | operand0.owner = owner;
96 | return getTab(tabCount)+"return "+operand0.out(tabCount)+";\n";
97 | }
98 | else
99 | {
100 | return getTab(tabCount)+"return;\n";
101 | }
102 | }
103 | protected function convertCallFunction(tabCount:int):String
104 | {
105 | operand0.owner = owner;
106 | return getTab(tabCount)+operand0.out(tabCount)+";\n";
107 | }
108 | protected function convertCallIf(tabCount:int):String
109 | {
110 | operand0.owner = owner;
111 | return operand0.out(tabCount)+"\n";
112 | }
113 | protected function convertCallFor(tabCount:int):String
114 | {
115 | operand0.owner = owner;
116 | return operand0.out(tabCount)+"\n";
117 | }
118 | protected function convertCallForSimple(tabCount:int):String
119 | {
120 | operand0.owner = owner;
121 | return operand0.out(tabCount)+"\n";
122 | }
123 | protected function convertContinue(tabCount:int):String
124 | {
125 | return getTab(tabCount)+"continue;\n";
126 | }
127 | protected function convertBreak(tabCount:int):String
128 | {
129 | return getTab(tabCount)+"break;\n";
130 | }
131 | protected function convertCallWhile(tabCount:int):String
132 | {
133 | operand0.owner = owner;
134 | return operand0.out(tabCount)+"\n";
135 | }
136 | protected function convertCallSwitch(tabCount:int):String
137 | {
138 | operand0.owner = owner;
139 | return operand0.out(tabCount)+"\n";
140 | }
141 | protected function convertCallForeach(tabCount:int):String
142 | {
143 | operand0.owner = owner;
144 | return operand0.out(tabCount)+"\n";
145 | }
146 | protected function convertCallForin(tabCount:int):String
147 | {
148 | operand0.owner = owner;
149 | return operand0.out(tabCount)+"\n";
150 | }
151 | protected function convertTry(tabCount:int):String
152 | {
153 | operand0.owner = owner;
154 | return operand0.out(tabCount)+"\n";
155 | }
156 | protected function convertThrow(tabCount:int):String
157 | {
158 | operand0.owner = owner;
159 | return getTab(tabCount)+operand0.out(tabCount)+";\n";
160 | }
161 | protected function convertNew(tabCount:int):String
162 | {
163 | operand0.owner = owner;
164 | return getTab(tabCount)+operand0.out(tabCount)+";\n";
165 | }
166 | protected function convertSuper(tabCount:int):String
167 | {
168 | operand0.owner = owner;
169 | return getTab(tabCount)+operand0.out(tabCount)+";\n";
170 | }
171 | protected function convertDelete(tabCount:int):String
172 | {
173 | operand0.owner = owner;
174 | return getTab(tabCount)+operand0.out(tabCount)+";\n";
175 | }
176 | }
177 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CodeIsAs.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 | import how.as2js.compiler.TokenType;
4 |
5 | public class CodeIsAs extends CodeObject
6 | {
7 | public var leftObject:CodeObject;
8 | public var rightObject:CodeObject;
9 | public var type:int;
10 | public function CodeIsAs(leftObject:CodeObject,rightObject:CodeObject,type:int)
11 | {
12 | this.leftObject = leftObject;
13 | this.rightObject = rightObject;
14 | this.type = type;
15 | }
16 | override public function out(tabCount:int):String
17 | {
18 | leftObject.owner = owner;
19 | rightObject.owner = owner;
20 | if(type == TokenType.Is)
21 | {
22 | return leftObject.out(0) + " instanceof " + rightObject.out(0);
23 | }
24 | else
25 | {
26 | return "("+leftObject.out(0) + " instanceof " + rightObject.out(0)+")?"+leftObject.out(0)+":null)";
27 | }
28 | }
29 | }
30 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CodeMember.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 | public class CodeMember extends CodeObject
4 | {
5 | public static const TYPE_NULL:int = 0;//空
6 | public static const TYPE_STRING:int = 1;//String
7 | public static const TYPE_NUMBER:int = 2;//Number类型
8 | public static const TYPE_OBJECT:int = 3;//对象类型
9 | public var parent:CodeObject;//父成员
10 | public var memberObject:CodeObject;//成员值,this[object]
11 | public var memberString:String;//成员值,this["key"]
12 | public var memberNumber:Number;//成员值,this[0]
13 | public var type:int = TYPE_NULL;//成员类型
14 | public var calc:int;//前后标识
15 | public var memType:CodeObject;
16 | public function CodeMember(name:String = null,member:CodeObject = null,num:Number = 0,parent:CodeObject = null)
17 | {
18 | if(name)
19 | {
20 | this.parent = parent;
21 | this.memberString = name;
22 | this.type = TYPE_STRING;
23 | }
24 | else if(member)
25 | {
26 | this.parent = parent;
27 | this.memberObject = member;
28 | this.type = TYPE_OBJECT;
29 | }
30 | else
31 | {
32 | this.parent = parent;
33 | this.memberNumber = num;
34 | this.type = TYPE_NUMBER;
35 | }
36 | }
37 | override public function out(tabCount:int):String
38 | {
39 | var thisString:String = "";
40 | if(!parent)
41 | {
42 | if(!owner.tempData.tempData.hasOwnProperty(memberString))
43 | {
44 | if(owner.tempData.thisTempData.hasOwnProperty(memberString))
45 | {
46 | thisString = "this.";
47 | }
48 | else if(owner.tempData.staticTempData.hasOwnProperty(memberString))
49 | {
50 | return owner.tempData.staticTempData[".this"];
51 | }
52 | else if(owner.tempData.importTempData.hasOwnProperty(memberString))
53 | {
54 | return owner.tempData.importTempData[memberString];
55 | }
56 | }
57 | }
58 | else
59 | {
60 | parent.owner = owner;
61 | }
62 | var mem:Object;
63 | if(type == TYPE_STRING)
64 | {
65 | mem = memberString;
66 | }
67 | else if(type == TYPE_OBJECT)
68 | {
69 | var codeMember:CodeMember = memberObject as CodeMember;
70 | if(codeMember)
71 | {
72 | codeMember.owner = owner;
73 | mem = codeMember.out(0);
74 | }
75 | else
76 | {
77 | mem = memberObject;
78 | }
79 | }
80 | else if(type == TYPE_NUMBER)
81 | {
82 | mem = memberNumber;
83 | }
84 | else
85 | {
86 | mem = "";
87 | }
88 | if(calc == CALC.POST_DECREMENT)
89 | {
90 | mem = mem+"--";
91 | }
92 | else if(calc == CALC.PRE_DECREMENT)
93 | {
94 | mem = "--"+mem;
95 | }
96 | else if(calc == CALC.POST_INCREMENT)
97 | {
98 | mem = mem+"++";
99 | }
100 | else if(calc == CALC.PRE_INCREMENT)
101 | {
102 | mem = "++"+mem;
103 | }
104 | if(parent)
105 | {
106 | if(this.type == TYPE_STRING)
107 | {
108 | return parent.out(tabCount)+"."+mem;
109 | }
110 | else
111 | {
112 | return parent.out(tabCount)+"["+mem+"]";
113 | }
114 | }
115 | else
116 | {
117 | return thisString+mem+"";
118 | }
119 | }
120 | }
121 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CodeNew.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 | public class CodeNew extends CodeObject
4 | {
5 | public var newObject:CodeObject;
6 | public function CodeNew()
7 | {
8 | }
9 | override public function out(tabCount:int):String
10 | {
11 | newObject.owner = owner;
12 | return "new " + newObject.out(tabCount);
13 | }
14 | }
15 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CodeObject.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 | import how.as2js.Config;
4 | import how.as2js.error.StackInfo;
5 |
6 | public class CodeObject
7 | {
8 | public var not:Boolean; // ! 标识(非xxx)
9 | public var negative:Boolean; // - 标识(负数)
10 | public var stackInfo:StackInfo; // 堆栈数据
11 | public var owner:CodeExecutable;
12 | public var insertString:String = "";
13 | public function CodeObject(breviary:String = null,line:int = 0)
14 | {
15 | if(breviary)
16 | {
17 | stackInfo = new StackInfo(breviary, line);
18 | }
19 | }
20 | public function outJS(tabCount:int):String
21 | {
22 | return "";
23 | }
24 | public function out(tabCount:int):String
25 | {
26 | if(Config.modol == 0)
27 | {
28 | return this.outJS(tabCount);
29 | }
30 | else if(Config.modol == 1)
31 | {
32 | return this.outEgret(tabCount);
33 | }
34 | else if(Config.modol == 2)
35 | {
36 | return this.outCocos(tabCount);
37 | }
38 | return "";
39 | }
40 | public function outCocos(tabCount:int):String
41 | {
42 | return outJS(tabCount);
43 | }
44 | public function outEgret(tabCount:int):String
45 | {
46 | return outJS(tabCount);
47 | }
48 | protected function getTab(tabCount:int):String
49 | {
50 | var tab:String = "";
51 | if(!Config.oneLine)
52 | {
53 | for (var i:int = 0; i < tabCount; i++)
54 | {
55 | tab += Config.tab;
56 | }
57 | }
58 | return tab;
59 | }
60 | public function getLeftBrace(tabCount:int):String
61 | {
62 | if(Config.leftBraceNextLine)
63 | {
64 | return Config.nextLine+getTab(tabCount)+"{\n";
65 | }
66 | else
67 | {
68 | return "{\n";
69 | }
70 | }
71 | }
72 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CodeOperator.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 | import flash.utils.Dictionary;
4 |
5 | import how.as2js.compiler.TokenType;
6 |
7 | public class CodeOperator extends CodeObject
8 | {
9 | public var left:CodeObject; //左边值
10 | public var right:CodeObject; //右边值
11 | public var operator:int; //符号类型
12 | private static var _operators:Dictionary;
13 | private static function get operators():Dictionary
14 | {
15 | if(!_operators)
16 | {
17 | _operators = new Dictionary();
18 | _operators[TokenType.InclusiveOr] = "|";
19 | _operators[TokenType.Combine] = "&";
20 | _operators[TokenType.XOR] = "^";
21 | _operators[TokenType.Shi] = "<<";
22 | _operators[TokenType.Shr] = ">>";
23 | _operators[TokenType.And] = "&&";
24 | _operators[TokenType.Or] = "||";
25 |
26 | _operators[TokenType.Equal] = "==";
27 | _operators[TokenType.NotEqual] = "!=";
28 | _operators[TokenType.Greater] = ">";
29 | _operators[TokenType.GreaterOrEqual] = ">=";
30 | _operators[TokenType.Less] = "<";
31 | _operators[TokenType.LessOrEqual] = "<=";
32 |
33 | _operators[TokenType.Plus] = "+";
34 | _operators[TokenType.Minus] = "-";
35 |
36 | _operators[TokenType.Multiply] = "*";
37 | _operators[TokenType.Divide] = "/";
38 | _operators[TokenType.Modulo] = "%";
39 | }
40 | return _operators;
41 | }
42 | public function CodeOperator(Right:CodeObject,Left:CodeObject,type:int)
43 | {
44 | this.left = Left;
45 | this.right = Right;
46 | this.operator = type;
47 | }
48 | override public function out(tabCount:int):String
49 | {
50 | left.owner = right.owner = owner;
51 | return left.out(tabCount) + " "+operators[operator]+" " + right.out(tabCount);
52 | }
53 | }
54 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CodeScriptObject.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 | public class CodeScriptObject extends CodeObject
4 | {
5 | public var object:Object;
6 | public function CodeScriptObject(obj:Object)
7 | {
8 | object = obj;
9 | }
10 | override public function out(tabCount:int):String
11 | {
12 | var result:String = "";
13 | if(object is Number)
14 | {
15 | result = parseFloat(object+"")+"";
16 | }
17 | else if(object is String)
18 | {
19 | result = "\""+object+"\"";
20 | var stringRegExp:RegExp = new RegExp("(?<=\").*(?=\")","s");
21 | var regExpResult:Object = stringRegExp.exec(result);
22 | if(regExpResult && regExpResult.length && regExpResult[0].indexOf("\"") != -1)
23 | {
24 | regExpResult[0] = regExpResult[0].replace(new RegExp("\"","g"),"\\\"");
25 | result = "\"" + regExpResult[0] + "\"";
26 | }
27 | result = result.replace(new RegExp("\n","g"),"\\n");
28 | result = result.replace(new RegExp("\r","g"),"\\r");
29 | result = result.replace(new RegExp("\t","g"),"\\t");
30 | }
31 | else
32 | {
33 | result = object+"";
34 | }
35 | return result;
36 | }
37 | }
38 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CodeSuper.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 | public class CodeSuper extends CodeObject
4 | {
5 | public var superObject:CodeObject;
6 | override public function outJS(tabCount:int):String
7 | {
8 | superObject.owner = owner;
9 | if(superObject is CodeCallFunction)
10 | {
11 | return "this.base()";
12 | }
13 | else
14 | {
15 | var result:String = superObject.out(tabCount);
16 | if(result.substring(0,5) != "this.")
17 | {
18 | result = "this."+result;
19 | }
20 | return result;
21 | }
22 | }
23 | override public function outEgret(tabCount:int):String
24 | {
25 | superObject.owner = owner;
26 | var result:String = "";
27 | if(superObject is CodeCallFunction)
28 | {
29 | var member:CodeMember = (superObject as CodeCallFunction).member as CodeMember;
30 | if(member && !member.parent)//说明是构造
31 | {
32 | var superParam:Vector. = (superObject as CodeCallFunction).parameters;
33 | var thisParam:Vector. = new Vector.();
34 | thisParam.push(new CodeMember("this"));
35 | (superObject as CodeCallFunction).parameters = thisParam.concat(superParam);
36 | result = "_super.call" + superObject.out(tabCount)+";\n";
37 | result += getTab(tabCount)+"this[\".init\"]()";
38 | }
39 | else
40 | {
41 | result = "_super.prototype." + superObject.out(tabCount) + ".call(this)";
42 | }
43 | return result;
44 | }
45 | else
46 | {
47 | insertString = ".call";
48 | result = "_super." + superObject.out(tabCount);
49 | return result;
50 | }
51 | }
52 | override public function outCocos(tabCount:int):String
53 | {
54 | superObject.owner = owner;
55 | if(superObject is CodeCallFunction)
56 | {
57 | return "this._super()";
58 | }
59 | else
60 | {
61 | var result:String = superObject.out(tabCount);
62 | if(result.substring(0,5) != "this.")
63 | {
64 | result = "this."+result;
65 | }
66 | return result;
67 | }
68 | }
69 | }
70 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CodeSwitch.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 | import how.as2js.codeDom.temp.TempCase;
4 |
5 | public class CodeSwitch extends CodeObject
6 | {
7 | public var condition:CodeObject;
8 | public var def:TempCase;
9 | public var cases:Vector. = new Vector.();
10 | public function CodeSwitch()
11 | {
12 | }
13 | public function AddCase(con:TempCase):void
14 | {
15 | cases.push(con);
16 | }
17 | override public function out(tabCount:int):String
18 | {
19 | condition.owner = owner;
20 | var caseString:String = "";
21 | var defaultString:String = "";
22 | for (var i:int = 0; i < cases.length; i++)
23 | {
24 | for (var j:int = 0; j < cases[i].allow.length; j++)
25 | {
26 | cases[i].allow[j].owner = owner;
27 | caseString += getTab(tabCount+1)+"case "+cases[i].allow[j].out(tabCount)+":\n";
28 | }
29 | if(cases[i].executable)
30 | {
31 | cases[i].executable.parent = owner;
32 | cases[i].executable.owner = owner;
33 | cases[i].executable.tempData = owner.tempData;
34 | caseString += cases[i].executable.out(tabCount+2);
35 | }
36 | caseString += getTab(tabCount+2)+"break;\n";
37 | }
38 | if(def)
39 | {
40 | defaultString += getTab(tabCount+1)+"default:\n";
41 | def.executable.parent = owner;
42 | def.executable.owner = owner;
43 | def.executable.tempData = owner.tempData;
44 | defaultString += def.executable.out(tabCount+2)+getTab(tabCount+2)+"break;\n";
45 | }
46 | return getTab(tabCount)+"switch("+condition.out(0)+")"+getLeftBrace(tabCount)+caseString+defaultString+"\n"+getTab(tabCount)+"}";
47 | }
48 | }
49 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CodeTernary.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 | public class CodeTernary extends CodeObject
4 | {
5 | public var allow:CodeObject; //判断条件
6 | public var True:CodeObject; //成立返回
7 | public var False:CodeObject; //不成立返回
8 | }
9 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CodeThrow.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 |
4 |
5 | public class CodeThrow extends CodeObject
6 | {
7 | public var obj:CodeObject;
8 | override public function out(tabCount:int):String
9 | {
10 | obj.owner = owner;
11 | return "throw " + obj.out(0);
12 | }
13 | }
14 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CodeTry.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 |
4 | public class CodeTry extends CodeObject
5 | {
6 | public var tryExecutable:CodeExecutable;//try指令执行
7 | public var catchExecutable:CodeExecutable;//catch指令执行
8 | public var identifier:String;//异常对象
9 | override public function out(tabCount:int):String
10 | {
11 | tryExecutable.parent = owner;
12 | tryExecutable.owner = owner;
13 | tryExecutable.tempData = owner.tempData;
14 | var catchString:String = "";
15 | if(catchExecutable)
16 | {
17 | catchExecutable.parent = owner;
18 | catchExecutable.owner = owner;
19 | catchExecutable.tempData = owner.tempData;
20 | catchString = "\n"+getTab(tabCount)+"catch("+identifier+")"+getLeftBrace(tabCount)+catchExecutable.out(tabCount+1)+getTab(tabCount)+"}";
21 | }
22 | return getTab(tabCount)+"try" + getLeftBrace(tabCount) +
23 | tryExecutable.out(tabCount+1) + getTab(tabCount) + "}" + catchString;
24 | }
25 | }
26 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CodeVariable.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 | import how.as2js.codeDom.CodeObject;
4 |
5 | /**
6 | * 成员变量
7 | */
8 | public class CodeVariable
9 | {
10 | public var key:Object;//属性键
11 | public var value:CodeObject;//属性值
12 | public var modifierType:int;//修饰符 公共/私有等
13 | public var isStatic:Boolean = true;//是否静态
14 | public var isConst:Boolean = true;//是否常量
15 | public var type:CodeObject;//属性类型
16 | public var isOverride:Boolean = false;
17 | public function CodeVariable(key:Object,value:CodeObject,modifierType:int,isStatic:Boolean,isConst:Boolean,isOverride:Boolean,type:CodeObject)
18 | {
19 | this.key = key;
20 | this.value = value;
21 | this.modifierType = modifierType;
22 | this.isStatic = isStatic;
23 | this.isConst = isConst;
24 | this.isOverride = isOverride;
25 | this.type = type;
26 | }
27 | }
28 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/CodeWhile.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom
2 | {
3 | import how.as2js.codeDom.temp.TempCondition;
4 |
5 | public class CodeWhile extends CodeObject
6 | {
7 | public var While:TempCondition;
8 | public function CodeWhile()
9 | {
10 |
11 | }
12 | override public function out(tabCount:int):String
13 | {
14 | While.allow.owner = owner;
15 | While.executable.parent = owner;
16 | While.executable.owner = owner;
17 | While.executable.tempData = owner.tempData;
18 | var result:String = getTab(tabCount)+"while("+While.allow.out(tabCount)+")"+getLeftBrace(tabCount)+While.executable.out(tabCount+1)+"\n"+getTab(tabCount)+"}";
19 | return result;
20 | }
21 | }
22 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/temp/TempCase.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom.temp
2 | {
3 | import how.as2js.codeDom.CodeExecutable;
4 | import how.as2js.codeDom.CodeObject;
5 |
6 | public class TempCase
7 | {
8 | public var allow:Vector.; //判断条件
9 | public var executable:CodeExecutable; //指令列表
10 | public function TempCase(allow:Vector.,executable:CodeExecutable)
11 | {
12 | this.allow = allow;
13 | this.executable = executable;
14 | }
15 | }
16 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/temp/TempCondition.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom.temp
2 | {
3 | import how.as2js.codeDom.CodeObject;
4 | import how.as2js.codeDom.CodeExecutable;
5 |
6 | /**
7 | * if语句中一个 if语句
8 | */
9 | public class TempCondition
10 | {
11 | public var allow:CodeObject; //判断条件
12 | public var executable:CodeExecutable; //指令列表
13 | public function TempCondition(allow:CodeObject,executable:CodeExecutable)
14 | {
15 | this.allow = allow;
16 | this.executable = executable;
17 | }
18 | }
19 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/temp/TempData.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom.temp
2 | {
3 | import flash.utils.Dictionary;
4 |
5 | public class TempData
6 | {
7 | public var tempData:Dictionary;
8 | public var thisTempData:Dictionary;
9 | public var staticTempData:Dictionary;
10 | public var importTempData:Dictionary;
11 | public function TempData()
12 | {
13 | }
14 | }
15 | }
--------------------------------------------------------------------------------
/src/how/as2js/codeDom/temp/TempOperator.as:
--------------------------------------------------------------------------------
1 | package how.as2js.codeDom.temp
2 | {
3 | import flash.utils.Dictionary;
4 |
5 | import how.as2js.compiler.TokenType;
6 |
7 | public class TempOperator
8 | {
9 | //运算符优先级表,
10 | private static var _operators:Dictionary;
11 | private static function get Operators():Dictionary
12 | {
13 | if(!_operators)
14 | {
15 | _operators = new Dictionary();
16 | _operators[TokenType.InclusiveOr] = new TempOperator(TokenType.InclusiveOr, 1);
17 | _operators[TokenType.Combine] = new TempOperator(TokenType.Combine, 1);
18 | _operators[TokenType.XOR] = new TempOperator(TokenType.XOR, 1);
19 | _operators[TokenType.Shi] = new TempOperator(TokenType.Shi, 1);
20 | _operators[TokenType.Shr] = new TempOperator(TokenType.Shr, 1);
21 | _operators[TokenType.And] = new TempOperator(TokenType.And, 1);
22 | _operators[TokenType.Or] = new TempOperator(TokenType.Or, 1);
23 |
24 | _operators[TokenType.Equal] = new TempOperator(TokenType.Equal, 2);
25 | _operators[TokenType.NotEqual] = new TempOperator(TokenType.NotEqual, 2);
26 | _operators[TokenType.Greater] = new TempOperator(TokenType.Greater, 2);
27 | _operators[TokenType.GreaterOrEqual] = new TempOperator(TokenType.GreaterOrEqual, 2);
28 | _operators[TokenType.Less] = new TempOperator(TokenType.Less, 2);
29 | _operators[TokenType.LessOrEqual] = new TempOperator(TokenType.LessOrEqual, 2);
30 |
31 | _operators[TokenType.Plus] = new TempOperator(TokenType.Plus, 3);
32 | _operators[TokenType.Minus] = new TempOperator(TokenType.Minus, 3);
33 |
34 | _operators[TokenType.Multiply] = new TempOperator(TokenType.Multiply, 4);
35 | _operators[TokenType.Divide] = new TempOperator(TokenType.Divide, 4);
36 | _operators[TokenType.Modulo] = new TempOperator(TokenType.Modulo, 4);
37 | }
38 | return _operators;
39 | }
40 | public var operator:int; //符号类型
41 | public var level:int; //优先级
42 | public static function init():void
43 | {
44 | }
45 | public function TempOperator(oper:int,level:int)
46 | {
47 | this.operator = oper;
48 | this.level = level;
49 | }
50 | //获得运算符
51 | public static function getOper(oper:int):TempOperator
52 | {
53 | if (Operators.hasOwnProperty(oper))
54 | {
55 | return Operators[oper];
56 | }
57 | return null;
58 | }
59 | }
60 | }
--------------------------------------------------------------------------------
/src/how/as2js/compiler/LexState.as:
--------------------------------------------------------------------------------
1 | package how.as2js.compiler
2 | {
3 | public class LexState
4 | {
5 | //没有关键字
6 | public static const None:int = -1;
7 | //= 等于或者相等
8 | public static const AssignOrEqual:int = 1;
9 | /// 注释或者除号
10 | public static const CommentOrDivideOrAssignDivide:int = 2;
11 | //行注释
12 | public static const LineComment:int = 3;
13 | //区域注释开始
14 | public static const BlockCommentStart:int = 4;
15 | //区域注释结束
16 | public static const BlockCommentEnd:int = 5;
17 | //.或者多参符(...)
18 | public static const PeriodOrParams:int = 6;
19 | //多参符(...)
20 | public static const Params:int = 7;
21 | //+ 或者 ++ 或者 +=
22 | public static const PlusOrIncrementOrAssignPlus:int = 8;
23 | //- 或者 -=
24 | public static const MinusOrDecrementOrAssignMinus:int = 9;
25 | //* 或者 *=
26 | public static const MultiplyOrAssignMultiply:int = 10;
27 | //% 或者 %=
28 | public static const ModuloOrAssignModulo:int = 11;
29 | //& 或者 &= 或者 &&
30 | public static const AndOrCombine:int = 12;
31 | //| 或者 |= 或者 ||
32 | public static const OrOrInclusiveOr:int = 13;
33 | //^ 或者 ^=
34 | public static const XorOrAssignXor:int = 14;
35 | //<< 或者 <<=
36 | public static const ShiOrAssignShi:int = 15;
37 | //>> 或者 >>=
38 | public static const ShrOrAssignShr:int = 16;
39 | //! 非或者不等于
40 | public static const NotOrNotEqual:int = 17;
41 | //> 大于或者大于等于
42 | public static const GreaterOrGreaterEqual:int = 18;
43 | //< 小于或者小于等于
44 | public static const LessOrLessEqual:int = 19;
45 | //" 字符串
46 | public static const String:int = 20;
47 | //\ 格式符
48 | public static const StringEscape:int = 21;
49 | //' 字符串 单引号开始结束
50 | public static const SingleString:int = 22;
51 | //\ 格式符
52 | public static const SingleStringEscape:int = 23;
53 | //@ 开始字符串
54 | public static const SimpleStringStart:int = 24;
55 | //@" 不格式化的字符串 类似c# @符号
56 | public static const SimpleString:int = 25;
57 | //字符串内出现"是引号还是结束符
58 | public static const SimpleStringQuotationMarkOrOver:int = 26;
59 | //@" 不格式化的字符串 类似c# @符号
60 | public static const SingleSimpleString:int = 27;
61 | //字符串内出现"是引号还是结束符
62 | public static const SingleSimpleStringQuotationMarkOrOver:int = 28;
63 | //十进制数字或者十六进制数字
64 | public static const NumberOrHexNumber:int = 29;
65 | //十进制数字
66 | public static const Number:int = 30;
67 | //十六进制数字
68 | public static const HexNumber:int = 31;
69 | //描述符
70 | public static const Identifier:int = 32;
71 | }
72 | }
--------------------------------------------------------------------------------
/src/how/as2js/compiler/ScriptLexer.as:
--------------------------------------------------------------------------------
1 | package how.as2js.compiler
2 | {
3 | import how.as2js.Config;
4 | import how.as2js.Utils;
5 |
6 | /**
7 | * 脚本语法解析器
8 | */
9 | public class ScriptLexer
10 | {
11 | private var m_strToken:String = null; //字符串token
12 | private var m_listSourceLines:Vector.;//所有行
13 | private var m_listTokens:Vector.;//解析后所得Token
14 | private var _commentList:Vector.;
15 | public function get commentList():Vector.//解析后得到的注释内容
16 | {
17 | return _commentList;
18 | }
19 | private var commentStrToken:String = ""; //字符串token
20 | private var m_strBreviary:String;//字符串的摘要 取第一行字符串的前20个字符
21 | private const BREVIARY_CHAR:int = 20;//摘要的字符数
22 | private var m_iSourceLine:int;//当前解析行数
23 | private var m_iSourceChar:int;//当前解析字符
24 | private var m_lexState:int;
25 | private var ch:String;//当前的解析的字符
26 |
27 | public function get lexState():int
28 | {
29 | return m_lexState;
30 | }
31 |
32 | public function set lexState(value:int):void
33 | {
34 | m_lexState = value;
35 | if (m_lexState == LexState.None)
36 | {
37 | m_strToken = "";
38 | }
39 | }
40 | public function get EndOfLine():Boolean
41 | {
42 | return m_iSourceChar >= m_listSourceLines[m_iSourceLine].length;
43 | }
44 | public function get EndOfSource():Boolean
45 | {
46 | return m_iSourceLine >= m_listSourceLines.length;
47 | }
48 |
49 | public function ScriptLexer(buffer:String)
50 | {
51 | m_listSourceLines = new Vector.();
52 | m_listTokens = new Vector.();
53 | _commentList = new Vector.();
54 | var strSource:String = buffer.replace("\r\n", "\r");
55 | var strLines:Array = strSource.split('\r');
56 | m_strBreviary = strLines.length > 0 ? strLines[0] : "";
57 | if (m_strBreviary.length > BREVIARY_CHAR){ m_strBreviary = m_strBreviary.substring(0, BREVIARY_CHAR)};
58 | for (var i:int = 0; i < strLines.length; i++)
59 | {
60 | var strLine:String = strLines[i];
61 | m_listSourceLines.push(strLine + "\r\n");
62 | }
63 | m_iSourceLine = 0;
64 | m_iSourceChar = 0;
65 | lexState = LexState.None;
66 |
67 | }
68 | /**
69 | * 获得整段字符串的摘要
70 | */
71 | public function GetBreviary():String
72 | {
73 | return m_strBreviary;
74 | }
75 |
76 | protected function IgnoreLine():void
77 | {
78 | ++m_iSourceLine;
79 | m_iSourceChar = 0;
80 | }
81 | protected function ReadChar():String
82 | {
83 | if (EndOfSource){
84 | throw new Error("End of source reached.", m_iSourceLine);
85 | }
86 | var ch:String = m_listSourceLines[m_iSourceLine].charAt(m_iSourceChar++);
87 | if (m_iSourceChar >= m_listSourceLines[m_iSourceLine].length) {
88 | m_iSourceChar = 0;
89 | ++m_iSourceLine;
90 | }
91 | return ch;
92 | }
93 | protected function AddToken(type:int,lexeme:Object = null):void
94 | {
95 | lexeme = lexeme != null?lexeme:ch;
96 | m_listTokens.push(new Token(type, lexeme, m_iSourceLine, m_iSourceChar));
97 | lexState = LexState.None;
98 | }
99 | public function getValue(key:String):String
100 | {
101 | if(_commentList)
102 | {
103 | for (var i:int = 0; i < _commentList.length; i++)
104 | {
105 | if(_commentList[i] == "@"+key && i+1 < _commentList.length)
106 | {
107 | return _commentList[i+1];
108 | }
109 | }
110 | }
111 | return null;
112 | }
113 | protected function AddComment():void
114 | {
115 | if(Utils.IsLetterOrDigit(ch) || ch == '@')
116 | {
117 | commentStrToken += ch;
118 | }
119 | else
120 | {
121 | if(commentStrToken.length != 0)
122 | {
123 | _commentList.push(commentStrToken);
124 | }
125 | commentStrToken = "";
126 | }
127 | }
128 | private function ThrowInvalidCharacterException(ch:String):void
129 | {
130 | throw new Error("Unexpected character [" + ch + "] Line:" + (m_iSourceLine + 1) + " Column:" + m_iSourceChar + " [" + m_listSourceLines[m_iSourceLine] + "]");
131 | }
132 | private function UndoChar():void
133 | {
134 | if (m_iSourceLine == 0 && m_iSourceChar == 0){
135 | throw new Error("Cannot undo char beyond start of source.", m_iSourceLine);
136 | }
137 | --m_iSourceChar;
138 | if (m_iSourceChar < 0) {
139 | --m_iSourceLine;
140 | m_iSourceChar = m_listSourceLines[m_iSourceLine].length - 1;
141 | }
142 | }
143 | private function IsHexDigit(c:String):Boolean
144 | {
145 | if( Utils.IsDigit( c ) ){
146 | return true;
147 | }
148 | if( 'a' <= c && c <= 'f' ){
149 | return true;
150 | }
151 | if( 'A' <= c && c <= 'F' ){
152 | return true;
153 | }
154 | return false;
155 | }
156 | /**
157 | * 解析字符串
158 | */
159 | public function GetTokens():Vector.
160 | {
161 | m_iSourceLine = 0;
162 | m_iSourceChar = 0;
163 | lexState = LexState.None;
164 | m_listTokens.length = 0;
165 | while (!EndOfSource)
166 | {
167 | if (EndOfLine)
168 | {
169 | IgnoreLine();
170 | continue;
171 | }
172 | ch = ReadChar();
173 | var value:Number;
174 | switch (lexState)
175 | {
176 | case LexState.None:
177 | switch (ch)
178 | {
179 | case ' ':
180 | case '\t':
181 | case '\n':
182 | case '\r':
183 | break;
184 | case '(':
185 | AddToken(TokenType.LeftPar);
186 | break;
187 | case ')':
188 | AddToken(TokenType.RightPar);
189 | break;
190 | case '[':
191 | AddToken(TokenType.LeftBracket);
192 | break;
193 | case ']':
194 | AddToken(TokenType.RightBracket);
195 | break;
196 | case '{':
197 | AddToken(TokenType.LeftBrace);
198 | break;
199 | case '}':
200 | AddToken(TokenType.RightBrace);
201 | break;
202 | case ',':
203 | AddToken(TokenType.Comma);
204 | break;
205 | case ':':
206 | AddToken(TokenType.Colon);
207 | break;
208 | case ';':
209 | AddToken(TokenType.SemiColon);
210 | break;
211 | case '?':
212 | AddToken(TokenType.QuestionMark);
213 | break;
214 | case '.':
215 | lexState = LexState.PeriodOrParams;
216 | break;
217 | case '+':
218 | lexState = LexState.PlusOrIncrementOrAssignPlus;
219 | break;
220 | case '-':
221 | lexState = LexState.MinusOrDecrementOrAssignMinus;
222 | break;
223 | case '*':
224 | lexState = LexState.MultiplyOrAssignMultiply;
225 | break;
226 | case '/':
227 | lexState = LexState.CommentOrDivideOrAssignDivide;
228 | AddComment();
229 | break;
230 | case '%':
231 | lexState = LexState.ModuloOrAssignModulo;
232 | break;
233 | case '=':
234 | lexState = LexState.AssignOrEqual;
235 | break;
236 | case '&':
237 | lexState = LexState.AndOrCombine;
238 | break;
239 | case '|':
240 | lexState = LexState.OrOrInclusiveOr;
241 | break;
242 | case '!':
243 | lexState = LexState.NotOrNotEqual;
244 | break;
245 | case '>':
246 | lexState = LexState.GreaterOrGreaterEqual;
247 | break;
248 | case '<':
249 | lexState = LexState.LessOrLessEqual;
250 | break;
251 | case '^':
252 | lexState = LexState.XorOrAssignXor;
253 | break;
254 | case '@':
255 | lexState = LexState.SimpleStringStart;
256 | break;
257 | case "\"":
258 | lexState = LexState.String;
259 | break;
260 | case '\'':
261 | lexState = LexState.SingleString;
262 | break;
263 | default:
264 | if (ch == '_' || ch == '$' || Utils.IsLetter(ch))
265 | {
266 | lexState = LexState.Identifier;
267 | m_strToken = "" + ch;
268 | }
269 | else if (ch == '0')
270 | {
271 | lexState = LexState.NumberOrHexNumber;
272 | m_strToken = "";
273 | }
274 | else if (Utils.IsDigit(ch))
275 | {
276 | lexState = LexState.Number;
277 | m_strToken = "" + ch;
278 | }
279 | else
280 | {
281 | ThrowInvalidCharacterException(ch);
282 | }
283 | break;
284 | }
285 | break;
286 | case LexState.PeriodOrParams:
287 | if (ch == '.') {
288 | lexState = LexState.Params;
289 | } else {
290 | AddToken(TokenType.Period, ".");
291 | UndoChar();
292 | }
293 | break;
294 | case LexState.Params:
295 | if (ch == '.') {
296 | AddToken(TokenType.Params, "...");
297 | } else {
298 | ThrowInvalidCharacterException(ch);
299 | }
300 | break;
301 | case LexState.PlusOrIncrementOrAssignPlus:
302 | if (ch == '+') {
303 | AddToken(TokenType.Increment, "++");
304 | } else if (ch == '=') {
305 | AddToken(TokenType.AssignPlus, "+=");
306 | } else {
307 | AddToken(TokenType.Plus, "+");
308 | UndoChar();
309 | }
310 | break;
311 | case LexState.MinusOrDecrementOrAssignMinus:
312 | if (ch == '-') {
313 | AddToken(TokenType.Decrement, "--");
314 | } else if (ch == '=') {
315 | AddToken(TokenType.AssignMinus, "-=");
316 | } else {
317 | AddToken(TokenType.Minus, "-");
318 | UndoChar();
319 | }
320 | break;
321 | case LexState.MultiplyOrAssignMultiply:
322 | if (ch == '=') {
323 | AddToken(TokenType.AssignMultiply, "*=");
324 | } else {
325 | AddToken(TokenType.Multiply, "*");
326 | UndoChar();
327 | }
328 | break;
329 | case LexState.CommentOrDivideOrAssignDivide:
330 | switch (ch) {
331 | case '/':
332 | lexState = LexState.LineComment;
333 | AddComment();
334 | break;
335 | case '*':
336 | lexState = LexState.BlockCommentStart;
337 | AddComment();
338 | break;
339 | case '=':
340 | AddToken(TokenType.AssignDivide, "/=");
341 | break;
342 | default:
343 | AddToken(TokenType.Divide, "/");
344 | UndoChar();
345 | break;
346 | }
347 | break;
348 | case LexState.ModuloOrAssignModulo:
349 | if (ch == '=') {
350 | AddToken(TokenType.AssignModulo, "%=");
351 | } else {
352 | AddToken(TokenType.Modulo, "%");
353 | UndoChar();
354 | }
355 | break;
356 | case LexState.LineComment:
357 | if (ch == '\n'){
358 | lexState = LexState.None;
359 | }
360 | break;
361 | case LexState.BlockCommentStart:
362 | if (ch == '*'){
363 | lexState = LexState.BlockCommentEnd;
364 | }
365 | AddComment();
366 | break;
367 | case LexState.BlockCommentEnd:
368 | if (ch == '/'){
369 | lexState = LexState.None;
370 | }
371 | else{
372 | lexState = LexState.BlockCommentStart;
373 | }
374 | AddComment();
375 | break;
376 | case LexState.AssignOrEqual:
377 | if (ch == '=') {
378 | AddToken(TokenType.Equal, "==");
379 | } else {
380 | AddToken(TokenType.Assign, "=");
381 | UndoChar();
382 | }
383 | break;
384 | case LexState.AndOrCombine:
385 | if (ch == '&') {
386 | AddToken(TokenType.And, "&&");
387 | } else if (ch == '=') {
388 | AddToken(TokenType.AssignCombine, "&=");
389 | } else {
390 | AddToken(TokenType.Combine, "&");
391 | UndoChar();
392 | }
393 | break;
394 | case LexState.OrOrInclusiveOr:
395 | if (ch == '|') {
396 | AddToken(TokenType.Or, "||");
397 | } else if (ch == '=') {
398 | AddToken(TokenType.AssignInclusiveOr, "|=");
399 | } else {
400 | AddToken(TokenType.InclusiveOr, "|");
401 | UndoChar();
402 | }
403 | break;
404 | case LexState.XorOrAssignXor:
405 | if (ch == '=') {
406 | AddToken(TokenType.AssignXOR, "^=");
407 | } else {
408 | AddToken(TokenType.XOR, "^");
409 | UndoChar();
410 | }
411 | break;
412 | case LexState.GreaterOrGreaterEqual:
413 | if (ch == '=') {
414 | AddToken(TokenType.GreaterOrEqual, ">=");
415 | } else if (ch == '>') {
416 | lexState = LexState.ShrOrAssignShr;
417 | } else {
418 | AddToken(TokenType.Greater, ">");
419 | UndoChar();
420 | }
421 | break;
422 | case LexState.LessOrLessEqual:
423 | if (ch == '=') {
424 | AddToken(TokenType.LessOrEqual, "<=");
425 | } else if (ch == '<') {
426 | lexState = LexState.ShiOrAssignShi;
427 | } else {
428 | AddToken(TokenType.Less, "<");
429 | UndoChar();
430 | }
431 | break;
432 | case LexState.ShrOrAssignShr:
433 | if (ch == '=') {
434 | AddToken(TokenType.AssignShr, ">>=");
435 | } else {
436 | AddToken(TokenType.Shr, ">>");
437 | UndoChar();
438 | }
439 | break;
440 | case LexState.ShiOrAssignShi:
441 | if (ch == '=') {
442 | AddToken(TokenType.AssignShi, "<<=");
443 | } else {
444 | AddToken(TokenType.Shi, "<<");
445 | UndoChar();
446 | }
447 | break;
448 | case LexState.NotOrNotEqual:
449 | if (ch == '=') {
450 | AddToken(TokenType.NotEqual, "!=");
451 | } else {
452 | AddToken(TokenType.Not, "!");
453 | UndoChar();
454 | }
455 | break;
456 | case LexState.String:
457 | if (ch == "\"") {
458 | AddToken(TokenType.String, m_strToken);
459 | } else if (ch == '\\') {
460 | lexState = LexState.StringEscape;
461 | } else if (ch == '\r' || ch == '\n') {
462 | ThrowInvalidCharacterException(ch);
463 | } else {
464 | m_strToken += ch;
465 | }
466 | break;
467 | case LexState.StringEscape:
468 | if (ch == '\\' || ch == "\"") {
469 | m_strToken += ch;
470 | lexState = LexState.String;
471 | } else if (ch == 't') {
472 | m_strToken += '\t';
473 | lexState = LexState.String;
474 | } else if (ch == 'r') {
475 | m_strToken += '\r';
476 | lexState = LexState.String;
477 | } else if (ch == 'n') {
478 | m_strToken += '\n';
479 | lexState = LexState.String;
480 | } else {
481 | ThrowInvalidCharacterException(ch);
482 | }
483 | break;
484 | case LexState.SingleString:
485 | if (ch == '\'') {
486 | AddToken(TokenType.String, m_strToken);
487 | } else if (ch == '\\') {
488 | lexState = LexState.SingleStringEscape;
489 | } else if (ch == '\r' || ch == '\n') {
490 | ThrowInvalidCharacterException(ch);
491 | } else {
492 | m_strToken += ch;
493 | }
494 | break;
495 | case LexState.SingleStringEscape:
496 | if (ch == '\\' || ch == '\'') {
497 | m_strToken += ch;
498 | lexState = LexState.SingleString;
499 | } else if (ch == 't') {
500 | m_strToken += '\t';
501 | lexState = LexState.SingleString;
502 | } else if (ch == 'r') {
503 | m_strToken += '\r';
504 | lexState = LexState.SingleString;
505 | } else if (ch == 'n') {
506 | m_strToken += '\n';
507 | lexState = LexState.SingleString;
508 | } else {
509 | ThrowInvalidCharacterException(ch);
510 | }
511 | break;
512 | case LexState.SimpleStringStart:
513 | if (ch == "\"") {
514 | lexState = LexState.SimpleString;
515 | } else if (ch == '\'') {
516 | lexState = LexState.SingleSimpleString;
517 | } else {
518 | ThrowInvalidCharacterException(ch);
519 | }
520 | break;
521 | case LexState.SimpleString:
522 | if (ch == "\"") {
523 | lexState = LexState.SimpleStringQuotationMarkOrOver;
524 | } else {
525 | m_strToken += ch;
526 | }
527 | break;
528 | case LexState.SimpleStringQuotationMarkOrOver:
529 | if (ch == "\"") {
530 | m_strToken += "\"";
531 | lexState = LexState.SimpleString;
532 | } else {
533 | AddToken(TokenType.String, m_strToken);
534 | UndoChar();
535 | }
536 | break;
537 | case LexState.SingleSimpleString:
538 | if (ch == '\'') {
539 | lexState = LexState.SingleSimpleStringQuotationMarkOrOver;
540 | } else {
541 | m_strToken += ch;
542 | }
543 | break;
544 | case LexState.SingleSimpleStringQuotationMarkOrOver:
545 | if (ch == '\'') {
546 | m_strToken += '\'';
547 | lexState = LexState.SingleSimpleString;
548 | } else {
549 | AddToken(TokenType.String, m_strToken);
550 | UndoChar();
551 | }
552 | break;
553 | case LexState.NumberOrHexNumber:
554 | if (ch == 'x') {
555 | lexState = LexState.HexNumber;
556 | } else {
557 | m_strToken = "0";
558 | lexState = LexState.Number;
559 | // AddToken(TokenType.Number, 0);
560 | UndoChar();
561 | }
562 | break;
563 | case LexState.Number:
564 | if (Utils.IsDigit(ch) || ch == '.')
565 | {
566 | m_strToken += ch;
567 | }
568 | else
569 | {
570 | value = parseFloat(m_strToken);
571 | AddToken(TokenType.Number, value);
572 | UndoChar();
573 | }
574 | break;
575 | case LexState.HexNumber:
576 | if (IsHexDigit(ch))
577 | {
578 | m_strToken += ch;
579 | }
580 | else
581 | {
582 | if (Utils.IsNullOrEmpty(m_strToken)){
583 | ThrowInvalidCharacterException(ch);
584 | }
585 | value = parseInt(m_strToken);
586 | AddToken(TokenType.Number, value);
587 | UndoChar();
588 | }
589 | break;
590 | case LexState.Identifier:
591 | if (ch == '_' || ch == '$' || Utils.IsLetterOrDigit(ch)) {
592 | m_strToken += ch;
593 | } else {
594 | var tokenType:int;
595 | switch (m_strToken)
596 | {
597 | // case "modol":
598 | // break;
599 | case "package":
600 | tokenType = TokenType.Package;
601 | break;
602 | case "class":
603 | tokenType = TokenType.Class;
604 | break;
605 | case "interface":
606 | tokenType = TokenType.Interface;
607 | break;
608 | case "public":
609 | tokenType = TokenType.Public;
610 | break;
611 | case "protected":
612 | tokenType = TokenType.Protected;
613 | break;
614 | case "private":
615 | tokenType = TokenType.Private;
616 | break;
617 | case "internal":
618 | tokenType = TokenType.Internal;
619 | break;
620 | case "dynamic":
621 | tokenType = TokenType.Dynamic;
622 | break;
623 | case "final":
624 | tokenType = TokenType.Final;
625 | break;
626 | case "extends":
627 | tokenType = TokenType.Extends;
628 | break;
629 | case "override":
630 | tokenType = TokenType.Override;
631 | break;
632 | case "void":
633 | tokenType = TokenType.Void;
634 | break;
635 | case "import":
636 | tokenType = TokenType.Import;
637 | break;
638 | case "static":
639 | tokenType = TokenType.Static;
640 | break;
641 | case "get":
642 | tokenType = TokenType.Get;
643 | break;
644 | case "set":
645 | tokenType = TokenType.Set;
646 | break;
647 | case "super":
648 | tokenType = TokenType.Super;
649 | break;
650 | case "each":
651 | tokenType = TokenType.Each;
652 | break;
653 | case "new":
654 | tokenType = TokenType.New;
655 | break;
656 | case "const":
657 | tokenType = TokenType.Const;
658 | break;
659 | case "var":
660 | tokenType = TokenType.Var;
661 | break;
662 | case "function":
663 | tokenType = TokenType.Function;
664 | break;
665 | case "if":
666 | tokenType = TokenType.If;
667 | break;
668 | case "else":
669 | tokenType = TokenType.Else;
670 | break;
671 | case "while":
672 | tokenType = TokenType.While;
673 | break;
674 | case "for":
675 | tokenType = TokenType.For;
676 | break;
677 | case "in":
678 | tokenType = TokenType.In;
679 | break;
680 | case "switch":
681 | tokenType = TokenType.Switch;
682 | break;
683 | case "case":
684 | tokenType = TokenType.Case;
685 | break;
686 | case "default":
687 | tokenType = TokenType.Default;
688 | break;
689 | case "try":
690 | tokenType = TokenType.Try;
691 | break;
692 | case "catch":
693 | tokenType = TokenType.Catch;
694 | break;
695 | case "throw":
696 | tokenType = TokenType.Throw;
697 | break;
698 | case "continue":
699 | tokenType = TokenType.Continue;
700 | break;
701 | case "break":
702 | tokenType = TokenType.Break;
703 | break;
704 | case "return":
705 | tokenType = TokenType.Return;
706 | break;
707 | case "null":
708 | tokenType = TokenType.Null;
709 | break;
710 | case "true":
711 | case "false":
712 | tokenType = TokenType.Boolean;
713 | break;
714 | case "is":
715 | tokenType = TokenType.Is;
716 | break;
717 | case "as":
718 | tokenType = TokenType.As;
719 | break;
720 | case "delete":
721 | tokenType = TokenType.Delete;
722 | break;
723 | default:
724 | tokenType = TokenType.Identifier;
725 | break;
726 | }
727 | if (tokenType == TokenType.Boolean)
728 | {
729 | m_listTokens.push(new Token(tokenType, m_strToken == "true", m_iSourceLine, m_iSourceChar));
730 | }
731 | else if (tokenType == TokenType.Null)
732 | {
733 | m_listTokens.push(new Token(tokenType, null, m_iSourceLine, m_iSourceChar));
734 | }
735 | else
736 | {
737 | m_listTokens.push(new Token(tokenType, m_strToken, m_iSourceLine, m_iSourceChar));
738 | }
739 | UndoChar();
740 | lexState = LexState.None;
741 | }
742 | break;
743 | }
744 | }
745 | m_listTokens.push(new Token(TokenType.Finished, "", m_iSourceLine, m_iSourceChar));
746 | // Config.modol = parseInt(getValue("modol"));
747 | // Config.bind = getValue("bind") != null && getValue("bind") == "true";
748 | return m_listTokens;
749 | }
750 | }
751 | }
--------------------------------------------------------------------------------
/src/how/as2js/compiler/ScriptParser.as:
--------------------------------------------------------------------------------
1 | package how.as2js.compiler
2 | {
3 | import how.as2js.Config;
4 | import how.as2js.codeDom.CALC;
5 | import how.as2js.codeDom.CodeArray;
6 | import how.as2js.codeDom.CodeAssign;
7 | import how.as2js.codeDom.CodeCallFunction;
8 | import how.as2js.codeDom.CodeClass;
9 | import how.as2js.codeDom.CodeCocos;
10 | import how.as2js.codeDom.CodeDelete;
11 | import how.as2js.codeDom.CodeEgret;
12 | import how.as2js.codeDom.CodeExecutable;
13 | import how.as2js.codeDom.CodeFor;
14 | import how.as2js.codeDom.CodeForSimple;
15 | import how.as2js.codeDom.CodeForeach;
16 | import how.as2js.codeDom.CodeForin;
17 | import how.as2js.codeDom.CodeFunction;
18 | import how.as2js.codeDom.CodeIf;
19 | import how.as2js.codeDom.CodeInstruction;
20 | import how.as2js.codeDom.CodeIsAs;
21 | import how.as2js.codeDom.CodeMember;
22 | import how.as2js.codeDom.CodeNew;
23 | import how.as2js.codeDom.CodeObject;
24 | import how.as2js.codeDom.CodeOperator;
25 | import how.as2js.codeDom.CodeScriptObject;
26 | import how.as2js.codeDom.CodeSuper;
27 | import how.as2js.codeDom.CodeSwitch;
28 | import how.as2js.codeDom.CodeTernary;
29 | import how.as2js.codeDom.CodeThrow;
30 | import how.as2js.codeDom.CodeTry;
31 | import how.as2js.codeDom.CodeVariable;
32 | import how.as2js.codeDom.CodeWhile;
33 | import how.as2js.codeDom.temp.TempCase;
34 | import how.as2js.codeDom.temp.TempCondition;
35 | import how.as2js.codeDom.temp.TempOperator;
36 | import how.as2js.error.ParseError;
37 | import how.as2js.error.StackInfo;
38 | import how.as2js.runtime.Opcode;
39 |
40 | public class ScriptParser
41 | {
42 | private var m_strBreviary:String; //当前解析的脚本摘要
43 | private var m_iNextToken:int; //当前读到token
44 | private var m_listTokens:Vector.; //token列表
45 | private var codeClass:CodeClass;//解析结果
46 | public function ScriptParser(listTokens:Vector.,strBreviary:String)
47 | {
48 | m_strBreviary = strBreviary;
49 | m_iNextToken = 0;
50 | m_listTokens = listTokens.concat();
51 | }
52 | //解析脚本
53 | public function Parse():CodeClass
54 | {
55 | if(Config.modol == 0)
56 | {
57 | codeClass = new CodeClass();
58 | }
59 | else if(Config.modol == 1)
60 | {
61 | codeClass = new CodeEgret();
62 | }
63 | else if(Config.modol == 2)
64 | {
65 | codeClass = new CodeCocos();
66 | }
67 | ReadPackage();
68 | codeClass.packAge = GetPackageName();//包名
69 | ReadLeftBrace();
70 | codeClass.imports = GetImports();//导入列表
71 | codeClass.modifierType = GetModifierType();//修饰符
72 | if(PeekToken().type == TokenType.Function)//全局函数
73 | {
74 |
75 | }
76 | else
77 | {
78 | codeClass.isFinal = GetFinal();//终级类
79 | codeClass.isDynamic = GetDynamic();//动态类
80 | ReadClass();
81 | codeClass.name = ReadIdentifier();
82 | codeClass.parent = GetExtend();
83 | GetMembers(codeClass);
84 | }
85 | ReadRightBrace();
86 | return codeClass;
87 | }
88 | /// 读取导入列表
89 | private function GetImports():Vector.
90 | {
91 | var imports:Vector. = new Vector.();
92 | while(PeekToken().type == TokenType.Import)//说明存在导入
93 | {
94 | ReadToken();//读取import关键字
95 | var importItem:String = ReadIdentifier();
96 | while(PeekToken().type == TokenType.Period)
97 | {
98 | ReadToken();
99 | importItem += "."+ReadIdentifier();
100 | }
101 | imports.push(importItem);
102 | if(PeekToken().type == TokenType.SemiColon)//如果存在分号
103 | {
104 | ReadToken();
105 | }
106 | }
107 | return imports;
108 | }
109 | /// 读取包名
110 | private function GetPackageName():String
111 | {
112 | if(PeekToken().type == TokenType.Identifier)//说明存在包名定义
113 | {
114 | var packageName:String = ReadIdentifier();
115 | while(PeekToken().type == TokenType.Period)
116 | {
117 | ReadToken();
118 | packageName += "."+ReadIdentifier();
119 | }
120 | return packageName;
121 | }
122 | return "";
123 | }
124 | /// 读取修饰符
125 | private function GetModifierType():int
126 | {
127 | var token:Token = ReadToken();
128 | if(token.type == TokenType.Public
129 | ||token.type == TokenType.Protected
130 | ||token.type == TokenType.Internal
131 | ||token.type == TokenType.Private)
132 | {
133 | return token.type;
134 | }
135 | else
136 | {
137 | UndoToken();
138 | return TokenType.Internal;
139 | }
140 | }
141 |
142 | /// 读取final修饰符
143 | private function GetFinal():Boolean
144 | {
145 | if(PeekToken().type == TokenType.Final)
146 | {
147 | ReadToken();
148 | return true;
149 | }
150 | return false;
151 | }
152 |
153 | /// 读取dynamic修饰符
154 | private function GetDynamic():Boolean
155 | {
156 | if(PeekToken().type == TokenType.Dynamic)
157 | {
158 | ReadToken();
159 | return true;
160 | }
161 | return false;
162 | }
163 |
164 | /// 读取继承
165 | private function GetExtend():String
166 | {
167 | if(PeekToken().type == TokenType.Extends)
168 | {
169 | ReadToken();
170 | return ReadIdentifier();
171 | }
172 | return null;
173 | }
174 |
175 | /// 读取成员
176 | private function GetMembers(thisCodeClass:CodeClass=null):CodeClass
177 | {
178 | var codeClass:CodeClass = thisCodeClass==null?new CodeClass():thisCodeClass;
179 | ReadLeftBrace();
180 | while (PeekToken().type != TokenType.RightBrace)
181 | {
182 | var token:Token = ReadToken();
183 | var modifierType:int = TokenType.Private;//属性描述符
184 | var isStatic:Boolean = false;//是否静态属性
185 | var isConst:Boolean = false;//是否常量
186 | var isOverride:Boolean = false;
187 | var type:CodeObject = null;//属性类型
188 | if(token.type == TokenType.Static)
189 | {
190 | isStatic = true;
191 | token = ReadToken();
192 | }
193 | if(token.type == TokenType.Override)
194 | {
195 | isOverride = true;
196 | token = ReadToken();
197 | }
198 | if (token.type == TokenType.Public||token.type == TokenType.Private||token.type == TokenType.Protected||token.type == TokenType.Internal)
199 | {
200 | modifierType = token.type;
201 | token = ReadToken();
202 | }
203 | if(token.type == TokenType.Override)
204 | {
205 | isOverride = true;
206 | token = ReadToken();
207 | }
208 | if(token.type == TokenType.Static)
209 | {
210 | isStatic = true;
211 | token = ReadToken();
212 | }
213 | if(token.type == TokenType.Var)
214 | {
215 | token = ReadToken();
216 | }
217 | if(token.type == TokenType.Const)
218 | {
219 | isConst = true;
220 | token = ReadToken();
221 | }
222 | if(token.type == TokenType.Identifier)
223 | {
224 | var next:Token = ReadToken();
225 | if(next.type == TokenType.Colon)
226 | {
227 | type = GetOneObject();
228 | next = ReadToken();
229 | }
230 | if(next.type == TokenType.Assign)
231 | {
232 | if(next.type == TokenType.New)//实例化
233 | {
234 | codeClass.variables.push(new CodeVariable(token.lexeme,GetNew(),modifierType,isStatic,isConst,isOverride,type));
235 | }
236 | else if(token.lexeme is int)
237 | {
238 | codeClass.variables.push(new CodeVariable(parseInt(token.lexeme.toString()), GetObject(),modifierType,isStatic,isConst,isOverride,type));
239 | }
240 | else if(token.lexeme is Number)
241 | {
242 | codeClass.variables.push(new CodeVariable(parseFloat(token.lexeme.toString()), GetObject(),modifierType,isStatic,isConst,isOverride,type));
243 | }
244 | else
245 | {
246 | codeClass.variables.push(new CodeVariable(token.lexeme, GetObject(),modifierType,isStatic,isConst,isOverride,type));
247 | }
248 | var peek:Token = PeekToken();
249 | if(peek.type == TokenType.Comma || peek.type == TokenType.SemiColon)
250 | {
251 | ReadToken();
252 | }
253 | }
254 | else//默认不赋值就是空
255 | {
256 | codeClass.variables.push(new CodeVariable(token.lexeme,null,modifierType,isStatic,isConst,isOverride,type));
257 | peek = PeekToken();
258 | if(peek.type == TokenType.Comma || peek.type == TokenType.SemiColon)
259 | {
260 | ReadToken();
261 | }
262 | }
263 | }
264 | else if(token.type == TokenType.Function)
265 | {
266 | UndoToken();
267 | codeClass.functions.push(ParseFunctionDeclaration(isStatic));
268 | }
269 | else
270 | {
271 | throw new ParseError(token,"Table开始关键字必须为[变量名称]或者[function]关键字");
272 | }
273 | }
274 | ReadRightBrace();
275 | return codeClass;
276 | }
277 |
278 | //返回实例化
279 | private function GetNew(executable:Object = null):CodeNew
280 | {
281 | var ret:CodeNew = new CodeNew();
282 | ret.newObject = GetObject();
283 | // if(executable != null)
284 | // {
285 | // executable.AddInstruction(new Instruction(Opcode.NEW, ret));
286 | // }
287 | return ret;
288 | }
289 | //获得单一变量
290 | private function GetOneObject():CodeObject
291 | {
292 | var ret:CodeObject = null;
293 | var token:Token = ReadToken();
294 | var not:Boolean = false;
295 | var negative:Boolean = false;
296 | var calc:int = CALC.NONE;
297 | if (token.type == TokenType.Not) {
298 | not = true;
299 | token = ReadToken();
300 | } else if (token.type == TokenType.Minus) {
301 | negative = true;
302 | token = ReadToken();
303 | } else if (token.type == TokenType.Increment) {
304 | calc = CALC.PRE_INCREMENT;
305 | token = ReadToken();
306 | } else if (token.type == TokenType.Decrement) {
307 | calc = CALC.PRE_DECREMENT;
308 | token = ReadToken();
309 | }
310 | switch (token.type)
311 | {
312 | case TokenType.Super:
313 | ret = new CodeMember(null);
314 | (ret as CodeMember).type = CodeMember.TYPE_NULL;
315 | break;
316 | case TokenType.Identifier:
317 | if(token.lexeme == "Vector")
318 | {
319 | if(PeekToken().type == TokenType.Period)
320 | {
321 | ReadToken();//.
322 | ReadToken();//>
323 | ReadToken();//type
324 | ReadToken();//>
325 | }
326 | }
327 | ret = new CodeMember(token.lexeme.toString());
328 | break;
329 | case TokenType.Function:
330 | UndoToken();
331 | ret = ParseFunctionDeclaration(false);
332 | break;
333 | case TokenType.LeftPar:
334 | ret = GetObject();
335 | ReadRightParenthesis();
336 | break;
337 | case TokenType.LeftBracket:
338 | UndoToken();
339 | ret = GetArray();
340 | break;
341 | case TokenType.LeftBrace:
342 | UndoToken();
343 | ret = GetMembers();
344 | break;
345 | case TokenType.Null:
346 | case TokenType.Boolean:
347 | case TokenType.Number:
348 | case TokenType.String:
349 | ret = new CodeScriptObject(token.lexeme);
350 | break;
351 | case TokenType.New:
352 | ret = GetNew();
353 | break;
354 | default:
355 | throw new ParseError(token,"Object起始关键字错误 ");
356 | break;
357 | }
358 | ret.stackInfo = new StackInfo(m_strBreviary, token.sourceLine);
359 | ret = GetVariable(ret);
360 | ret.not = not;
361 | ret = GetTernary(ret);
362 | ret.negative = negative;
363 | if (ret is CodeMember) {
364 | if (calc != CALC.NONE) {
365 | (ret as CodeMember).calc = calc;
366 | } else {
367 | var peek:Token = ReadToken();
368 | if (peek.type == TokenType.Increment) {
369 | calc = CALC.POST_INCREMENT;
370 | } else if (peek.type == TokenType.Decrement) {
371 | calc = CALC.POST_DECREMENT;
372 | } else {
373 | UndoToken();
374 | }
375 | if (calc != CALC.NONE) {
376 | (ret as CodeMember).calc = calc;
377 | }
378 | }
379 | } else if (calc != CALC.NONE) {
380 | throw new ParseError(token,"++ 或者 -- 只支持变量的操作");
381 | }
382 | return ret;
383 | }
384 | //返回三元运算符
385 | private function GetTernary(parent:CodeObject):CodeObject
386 | {
387 | if (PeekToken().type == TokenType.QuestionMark)
388 | {
389 | var ret:CodeTernary = new CodeTernary();
390 | ret.allow = parent;
391 | ReadToken();
392 | ret.True = GetObject(false);
393 | // UndoToken();
394 | // UndoToken();
395 | ReadColon();
396 | ret.False = GetObject(false);
397 | return ret;
398 | }
399 | return parent;
400 | }
401 | //返回变量数据
402 | private function GetVariable(parent:CodeObject):CodeObject
403 | {
404 | var ret:CodeObject = parent;
405 | for ( ; ; ) {
406 | var m:Token = ReadToken();
407 | if (m.type == TokenType.Period) {
408 | var identifier:String = ReadIdentifier();
409 | ret = new CodeMember(identifier,null,0, ret);
410 | } else if (m.type == TokenType.LeftBracket) {
411 | var member:CodeObject = GetObject();
412 | ReadRightBracket();
413 | if (member is CodeScriptObject) {
414 | var obj:Object = (member as CodeScriptObject).object;
415 | if (obj is Number){
416 | ret = new CodeMember(null,null,parseFloat(obj.toString()), ret);
417 | }
418 | else if (obj is String){
419 | ret = new CodeMember(obj.toString(),null,0, ret);
420 | }
421 | else{
422 | throw new ParseError(m,"获取变量只能是 number或string");
423 | }
424 | } else {
425 | ret = new CodeMember(null,member,0, ret);
426 | }
427 | } else if (m.type == TokenType.LeftPar) {
428 | UndoToken();
429 | ret = GetFunction(ret);
430 | } else {
431 | UndoToken();
432 | break;
433 | }
434 | }
435 | return ret;
436 | }
437 | //返回一个调用函数 Object
438 | private function GetFunction(member:CodeObject):CodeCallFunction
439 | {
440 | var ret:CodeCallFunction = new CodeCallFunction();
441 | ReadLeftParenthesis();
442 | var pars:Vector. = new Vector.();
443 | var token:Token = PeekToken();
444 | while (token.type != TokenType.RightPar)
445 | {
446 | pars.push(GetObject());
447 | token = PeekToken();
448 | if (token.type == TokenType.Comma)
449 | {
450 | ReadComma();
451 | }
452 | else if (token.type == TokenType.RightPar)
453 | {
454 | break;
455 | }
456 | else
457 | {
458 | throw new ParseError(token,"Comma ',' or right parenthesis ')' expected in function declararion.");
459 | }
460 | }
461 | ReadRightParenthesis();
462 | ret.member = member;
463 | ret.parameters = pars;
464 | return ret;
465 | }
466 | //返回数组
467 | private function GetArray():CodeArray
468 | {
469 | ReadLeftBracket();
470 | var token:Token = PeekToken();
471 | var ret:CodeArray = new CodeArray();
472 | while (token.type != TokenType.RightBracket)
473 | {
474 | if (PeekToken().type == TokenType.RightBracket){
475 | break;
476 | }
477 | ret.elements.push(GetObject());
478 | token = PeekToken();
479 | if (token.type == TokenType.Comma) {
480 | ReadComma();
481 | } else if (token.type == TokenType.RightBracket) {
482 | break;
483 | }
484 | else
485 | {
486 | throw new ParseError(token,"Comma ',' or right parenthesis ']' expected in array object.");
487 | }
488 | }
489 | ReadRightBracket();
490 | return ret;
491 | }
492 | //获取一个Object
493 | private function GetObject(readColon:Boolean = true):CodeObject
494 | {
495 | var operateStack:Vector. = new Vector.();
496 | var objectStack:Vector. = new Vector.();
497 | while (true)
498 | {
499 | objectStack.push(GetOneObject());
500 | if (!P_Operator(operateStack, objectStack))
501 | {
502 | break;
503 | }
504 | }
505 | while (true)
506 | {
507 | if (operateStack.length <= 0)
508 | {
509 | break;
510 | }
511 | var oper:TempOperator = operateStack.pop();
512 | var binexp:CodeOperator = new CodeOperator(objectStack.pop(), objectStack.pop(), oper.operator);
513 | objectStack.push(binexp);
514 | }
515 | var ret:CodeObject = objectStack.pop();
516 | if (ret is CodeMember)
517 | {
518 | var member:CodeMember = ret as CodeMember;
519 | if (member.calc == CALC.NONE)
520 | {
521 | var token:Token = ReadToken();
522 | if(token.type == TokenType.Colon && readColon)//如果后面跟着个冒号
523 | {
524 | member.memType = GetOneObject();
525 | token = ReadToken();
526 | }
527 | switch (token.type)
528 | {
529 | case TokenType.Assign:
530 | case TokenType.AssignPlus:
531 | case TokenType.AssignMinus:
532 | case TokenType.AssignMultiply:
533 | case TokenType.AssignDivide:
534 | case TokenType.AssignModulo:
535 | case TokenType.AssignCombine:
536 | case TokenType.AssignInclusiveOr:
537 | case TokenType.AssignXOR:
538 | case TokenType.AssignShr:
539 | case TokenType.AssignShi:
540 | return new CodeAssign(member, GetObject(), token.type, m_strBreviary, token.sourceLine);
541 | break;
542 | default:
543 | UndoToken();
544 | break;
545 | }
546 | }
547 | }
548 | var nextToken:Token = ReadToken();
549 | if(nextToken.type == TokenType.Is || nextToken.type == TokenType.As)
550 | {
551 | ret = new CodeIsAs(ret,GetObject(),nextToken.type);
552 | }
553 | else
554 | {
555 | UndoToken();
556 | }
557 | return ret;
558 | }
559 | //解析操作符
560 | private function P_Operator(operateStack:Vector.,objectStack:Vector.):Boolean
561 | {
562 | var curr:TempOperator = TempOperator.getOper(PeekToken().type);
563 | if (curr == null) {return false;}
564 | ReadToken();
565 | while (operateStack.length > 0)
566 | {
567 | var oper:TempOperator = operateStack[operateStack.length-1];
568 | if (oper.level >= curr.level)
569 | {
570 | operateStack.pop();
571 | var binexp:CodeOperator = new CodeOperator(objectStack.pop(), objectStack.pop(), oper.operator);
572 | objectStack.push(binexp);
573 | }
574 | else
575 | {
576 | break;
577 | }
578 | }
579 | operateStack.push(curr);
580 | return true;
581 | }
582 | //解析成员函数(返回一个函数)
583 | private function ParseFunctionDeclaration(isStatic:Boolean):CodeFunction
584 | {
585 | var token:Token = ReadToken();
586 | if (token.type != TokenType.Function)
587 | {
588 | throw new ParseError(token,"Function declaration must start with the 'function' keyword.");
589 | }
590 | var scriptFunctionType:int = CodeFunction.TYPE_NORMAL;
591 | if(PeekToken().type == TokenType.Get)
592 | {
593 | token = ReadToken();
594 | scriptFunctionType = CodeFunction.TYPE_GET;
595 | }
596 | if(PeekToken().type == TokenType.Set)
597 | {
598 | token = ReadToken();
599 | scriptFunctionType = CodeFunction.TYPE_SET;
600 | }
601 | var strFunctionName:String;
602 | if (PeekToken().type != TokenType.LeftPar)//有可能是匿名函数
603 | {
604 | strFunctionName = ReadIdentifier();
605 | strFunctionName = scriptFunctionType==CodeFunction.TYPE_GET?".get"+strFunctionName:strFunctionName;
606 | strFunctionName = scriptFunctionType==CodeFunction.TYPE_SET?".set"+strFunctionName:strFunctionName;
607 | }
608 | ReadLeftParenthesis();
609 | var listParameters:Vector. = new Vector.();
610 | var listParameterTypes:Vector. = new Vector.();
611 | var listValues:Vector. = new Vector.();
612 | var bParams:Boolean = false;
613 | if (PeekToken().type != TokenType.RightPar)
614 | {
615 | while (true)
616 | {
617 | token = ReadToken();
618 | if (token.type == TokenType.Params)
619 | {
620 | token = ReadToken();
621 | bParams = true;
622 | }
623 | if (token.type != TokenType.Identifier)
624 | {
625 | throw new ParseError(token,"Unexpected token '" + token.lexeme + "' in function declaration.");
626 | }
627 | var strParameterName:String = token.lexeme.toString();
628 | token = PeekToken();
629 | if (token.type == TokenType.Colon)
630 | {
631 | ReadColon();
632 | var param:CodeObject = GetObject();
633 | if(param is CodeMember)
634 | {
635 | listParameterTypes.push(param);
636 | }
637 | else if(param is CodeAssign)
638 | {
639 | listValues.push((param as CodeAssign).value);
640 | listParameterTypes.push((param as CodeAssign).member);
641 | }
642 | }
643 | else
644 | {
645 | listParameterTypes.push(null);
646 | }
647 | listParameters.push(strParameterName);
648 | token = PeekToken();
649 | if (token.type == TokenType.Comma && !bParams)
650 | {
651 | ReadComma();
652 | }
653 | else if (token.type == TokenType.RightPar)
654 | {
655 | break;
656 | }
657 | else
658 | {
659 | throw new ParseError(token,"Comma ',' or right parenthesis ')' expected in function declararion.");
660 | }
661 | }
662 | }
663 | ReadRightParenthesis();
664 | token = ReadToken();
665 | if (token.type == TokenType.Colon)//如果后面跟着冒号
666 | {
667 | token = ReadToken();
668 | if(token.lexeme == "Vector")
669 | {
670 | if(PeekToken().type == TokenType.Period)
671 | {
672 | ReadToken();//.
673 | ReadToken();//>
674 | ReadToken();//type
675 | ReadToken();//>
676 | }
677 | }
678 | }
679 | else
680 | {
681 | UndoToken();
682 | }
683 | var executable:CodeExecutable = new CodeExecutable(CodeExecutable.Block_Function);
684 | ParseStatementBlock(executable);
685 | return new CodeFunction(strFunctionName,listParameters,listParameterTypes,listValues,executable,bParams,isStatic,scriptFunctionType);
686 | }
687 | //解析区域代码内容( {} 之间的内容)
688 | private function ParseStatementBlock(executable:CodeExecutable,readLeftBrace:Boolean = true,finished:int = 4):void
689 | {
690 |
691 | if (readLeftBrace)
692 | {
693 | ReadLeftBrace();
694 | }
695 | var tokenType:int;
696 | while (HasMoreTokens())
697 | {
698 | tokenType = ReadToken().type;
699 | if (tokenType == finished)
700 | {
701 | break;
702 | }
703 | UndoToken();
704 | ParseStatement(executable);
705 | }
706 | executable.endInstruction();
707 | }
708 | //解析区域代码内容 ({} 之间的内容)
709 | private function ParseStatement(executable:CodeExecutable):void
710 | {
711 | var token:Token = ReadToken();
712 | switch (token.type)
713 | {
714 | case TokenType.Public:
715 | throw new ParseError(token,"方法内的声明不支持public ");
716 | break;
717 | case TokenType.Protected:
718 | throw new ParseError(token,"方法内的声明不支持protected ");
719 | break;
720 | case TokenType.Private:
721 | throw new ParseError(token,"方法内的声明不支持private ");
722 | break;
723 | case TokenType.Internal:
724 | throw new ParseError(token,"方法内的声明不支持internal ");
725 | break;
726 | case TokenType.Var:
727 | ParseVar(executable);
728 | break;
729 | case TokenType.If:
730 | ParseIf(executable);
731 | break;
732 | case TokenType.For:
733 | ParseFor(executable);
734 | break;
735 | case TokenType.While:
736 | ParseWhile(executable);
737 | break;
738 | case TokenType.Switch:
739 | ParseSwtich(executable);
740 | break;
741 | case TokenType.Try:
742 | ParseTry(executable);
743 | break;
744 | case TokenType.Throw:
745 | ParseThrow(executable);
746 | break;
747 | case TokenType.Return:
748 | ParseReturn(executable);
749 | break;
750 | case TokenType.Identifier:
751 | case TokenType.Increment:
752 | case TokenType.Decrement:
753 | ParseExpression(executable);
754 | break;
755 | case TokenType.New:
756 | executable.addInstruction(new CodeInstruction(Opcode.NEW,GetNew(executable)));
757 | break;
758 | case TokenType.Super:
759 | executable.addInstruction(new CodeInstruction(Opcode.SUPER,GetSuper(executable)));
760 | break;
761 | case TokenType.Break:
762 | executable.addInstruction(new CodeInstruction(Opcode.BREAK, new CodeObject(m_strBreviary,token.sourceLine)));
763 | break;
764 | case TokenType.Continue:
765 | executable.addInstruction(new CodeInstruction(Opcode.CONTINUE, new CodeObject(m_strBreviary,token.sourceLine)));
766 | break;
767 | case TokenType.Function:
768 | ParseFunctionDeclaration(false);
769 | break;
770 | case TokenType.SemiColon:
771 | break;
772 | case TokenType.Delete:
773 | executable.addInstruction(new CodeInstruction(Opcode.DELETE, new CodeDelete(GetObject())));
774 | break;
775 | case TokenType.LeftPar:
776 | UndoToken();
777 | executable.addInstruction(new CodeInstruction(Opcode.RESOLVE,GetObject()));
778 | break;
779 | default:
780 | throw new ParseError(token,"不支持的语法 ");
781 | break;
782 | }
783 | }
784 |
785 | //解析Var关键字
786 | private function ParseVar(executable:CodeExecutable):void
787 | {
788 | for (; ; )
789 | {
790 | var tokenIndex:int = m_iNextToken;
791 | var identifier:String = ReadIdentifier();
792 | var typeMem:CodeObject;
793 | var peek:Token = PeekToken();
794 | if (peek.type == TokenType.Colon)
795 | {
796 | ReadToken();
797 | typeMem = GetOneObject();
798 | peek = PeekToken();
799 | }
800 | executable.addInstruction(new CodeInstruction(Opcode.VAR,typeMem,null,identifier));
801 | if (peek.type == TokenType.Assign)
802 | {
803 | m_iNextToken = tokenIndex;
804 | ParseStatement(executable);
805 | }
806 | peek = ReadToken();
807 | if (peek.type != TokenType.Comma)
808 | {
809 | UndoToken();
810 | break;
811 | }
812 | }
813 | }
814 | //解析if(判断语句)
815 | private function ParseIf(executable:CodeExecutable):void
816 | {
817 | var ret:CodeIf = new CodeIf();
818 | ret.If = ParseCondition(true,new CodeExecutable(CodeExecutable.Block_If,executable));
819 | for (; ; )
820 | {
821 | var token:Token = ReadToken();
822 | if (token.type == TokenType.Else)
823 | {
824 | if (PeekToken().type == TokenType.If)
825 | {
826 | ReadToken();
827 | ret.AddElseIf(ParseCondition(true,new CodeExecutable(CodeExecutable.Block_If,executable)));
828 | }
829 | else
830 | {
831 | UndoToken();
832 | break;
833 | }
834 | }
835 | else
836 | {
837 | UndoToken();
838 | break;
839 | }
840 | }
841 | if (PeekToken().type == TokenType.Else)
842 | {
843 | ReadToken();
844 | ret.Else = ParseCondition(false,new CodeExecutable(CodeExecutable.Block_If,executable));
845 | }
846 | executable.addInstruction(new CodeInstruction(Opcode.CALL_IF, ret));
847 | }
848 |
849 | //解析判断内容
850 | private function ParseCondition(condition:Boolean,executable:CodeExecutable):TempCondition
851 | {
852 | var con:CodeObject = null;
853 | if (condition)
854 | {
855 | ReadLeftParenthesis();
856 | con = GetObject();
857 | ReadRightParenthesis();
858 | }
859 | ParseStatementBlock(executable);
860 | return new TempCondition(con,executable);
861 | }
862 |
863 | //解析for语句
864 | private function ParseFor(executable:CodeExecutable):void
865 | {
866 | if(PeekToken().type == TokenType.Each)
867 | {
868 | ReadToken();
869 | ParseForeach(executable);
870 | }
871 | else
872 | {
873 | ReadLeftParenthesis();
874 | var partIndex:int = m_iNextToken;
875 | var token:Token = ReadToken();
876 | if (token.type == TokenType.Identifier)
877 | {
878 | var assign:Token = ReadToken();
879 | if (assign.type == TokenType.Assign)
880 | {
881 | var obj:CodeObject = GetObject();
882 | var comma:Token = ReadToken();
883 | if (comma.type == TokenType.Comma)
884 | {
885 | ParseFor_Simple(executable,token.lexeme.toString(), obj);
886 | return;
887 | }
888 | }
889 | }
890 | if(token.type == TokenType.Var)
891 | {
892 | if(ReadToken().type == TokenType.Identifier)
893 | {
894 | if(PeekToken().type == TokenType.Colon)
895 | {
896 | ReadColon();
897 | ReadIdentifier();
898 | }
899 | if(ReadToken().type == TokenType.In)
900 | {
901 | m_iNextToken = partIndex;
902 | ParseForin(executable);
903 | return;
904 | }
905 | }
906 | }
907 | m_iNextToken = partIndex;
908 | ParseFor_impl(executable);
909 | }
910 | }
911 |
912 | //解析正规for循环
913 | private function ParseFor_impl(executable:CodeExecutable):void
914 | {
915 | var ret:CodeFor = new CodeFor();
916 | var token:Token = ReadToken();
917 | if (token.type != TokenType.SemiColon)
918 | {
919 | UndoToken();
920 | var forBeginExecutable:CodeExecutable = new CodeExecutable(CodeExecutable.Block_ForBegin,executable);
921 | ParseStatementBlock(forBeginExecutable, false, TokenType.SemiColon);
922 | ret.beginExecutable = forBeginExecutable;
923 | }
924 | token = ReadToken();
925 | if (token.type != TokenType.SemiColon)
926 | {
927 | UndoToken();
928 | ret.condition = GetObject();
929 | ReadSemiColon();
930 | }
931 | token = ReadToken();
932 | if (token.type != TokenType.RightPar)
933 | {
934 | UndoToken();
935 | var forLoopExecutable:CodeExecutable = new CodeExecutable(CodeExecutable.Block_ForLoop,executable);
936 | ParseStatementBlock(forLoopExecutable, false, TokenType.RightPar);
937 | ret.loopExecutable = forLoopExecutable;
938 | }
939 | var forExecutable:CodeExecutable = new CodeExecutable(CodeExecutable.Block_For,executable);
940 | ParseStatementBlock(forExecutable);
941 | ret.SetContextExecutable(forExecutable);
942 | executable.addInstruction(new CodeInstruction(Opcode.CALL_FOR, ret));
943 | }
944 | //解析foreach语句
945 | private function ParseForeach(executable:CodeExecutable):void
946 | {
947 | var ret:CodeForeach = new CodeForeach();
948 | ReadLeftParenthesis();
949 | ReadVar();
950 | ret.identifier = ReadIdentifier();
951 | if(PeekToken().type == TokenType.Colon)
952 | {
953 | ReadColon();
954 | ReadIdentifier();
955 | }
956 | ReadIn();
957 | ret.loopObject = GetObject();
958 | ReadRightParenthesis();
959 | var forEachExecutable:CodeExecutable = new CodeExecutable(CodeExecutable.Block_Foreach,executable);
960 | ParseStatementBlock(forEachExecutable);
961 | ret.executable = forEachExecutable;
962 | executable.addInstruction(new CodeInstruction(Opcode.CALL_FOREACH, ret));
963 | }
964 | //解析forin语句
965 | private function ParseForin(executable:CodeExecutable):void
966 | {
967 | var ret:CodeForin = new CodeForin();
968 | ReadVar();
969 | ret.identifier = ReadIdentifier();
970 | if(PeekToken().type == TokenType.Colon)
971 | {
972 | ReadColon();
973 | ReadIdentifier();
974 | }
975 | ReadIn();
976 | ret.loopObject = GetObject();
977 | ReadRightParenthesis();
978 | var forEachExecutable:CodeExecutable = new CodeExecutable(CodeExecutable.Block_Foreach,executable);
979 | ParseStatementBlock(forEachExecutable);
980 | ret.executable = forEachExecutable;
981 | executable.addInstruction(new CodeInstruction(Opcode.CALL_FORIN, ret));
982 | }
983 | //解析单纯for循环
984 | private function ParseFor_Simple(executable:CodeExecutable,Identifier:String,obj:CodeObject):void
985 | {
986 | var ret:CodeForSimple = new CodeForSimple();
987 | ret.identifier = Identifier;
988 | ret.begin = obj;
989 | ret.finished = GetObject();
990 | if (PeekToken().type == TokenType.Comma)
991 | {
992 | ReadToken();
993 | ret.step = GetObject();
994 | }
995 | ReadRightParenthesis();
996 | var forExecutable:CodeExecutable = new CodeExecutable(CodeExecutable.Block_For,executable);
997 | ParseStatementBlock(forExecutable);
998 | ret.SetContextExecutable(forExecutable);
999 | executable.addInstruction(new CodeInstruction(Opcode.CALL_FORSIMPLE, ret));
1000 | }
1001 | //解析while(循环语句)
1002 | private function ParseWhile(executable:CodeExecutable):void
1003 | {
1004 | var ret:CodeWhile = new CodeWhile();
1005 | ret.While = ParseCondition(true,new CodeExecutable(CodeExecutable.Block_While,executable));
1006 | executable.addInstruction(new CodeInstruction(Opcode.CALL_WHILE, ret));
1007 | }
1008 |
1009 | //解析swtich语句
1010 | private function ParseSwtich(executable:CodeExecutable):void
1011 | {
1012 | var ret:CodeSwitch = new CodeSwitch();
1013 | ReadLeftParenthesis();
1014 | ret.condition = GetObject();
1015 | ReadRightParenthesis();
1016 | ReadLeftBrace();
1017 | var switchExecutable:CodeExecutable;
1018 | for (; ; )
1019 | {
1020 | var token:Token = ReadToken();
1021 | if (token.type == TokenType.Case) {
1022 |
1023 | var vals:Vector. = new Vector.();
1024 | ParseCase(vals);
1025 | switchExecutable = new CodeExecutable(CodeExecutable.Block_Switch,executable);
1026 | ParseStatementBlock(switchExecutable, false, TokenType.Break);
1027 | ret.AddCase(new TempCase(vals,switchExecutable));
1028 | }
1029 | else if (token.type == TokenType.Default)
1030 | {
1031 | ReadColon();
1032 | switchExecutable = new CodeExecutable(CodeExecutable.Block_Switch,executable);
1033 | ParseStatementBlock(switchExecutable, false, TokenType.Break);
1034 | ret.def = new TempCase(null,switchExecutable);
1035 | }
1036 | else if (token.type != TokenType.SemiColon)
1037 | {
1038 | UndoToken();
1039 | break;
1040 | }
1041 | }
1042 | ReadRightBrace();
1043 | executable.addInstruction(new CodeInstruction(Opcode.CALL_SWITCH, ret));
1044 | }
1045 | //解析case
1046 | private function ParseCase(vals:Vector.):void
1047 | {
1048 | // var val:Token = ReadToken();
1049 | // if (val.Type == TokenType.String || val.Type == TokenType.Number)
1050 | // {
1051 | // vals.push(val.Lexeme);
1052 | // }
1053 | // else
1054 | // {
1055 | // throw new ParseError(val,"case 语句 只支持 string和number类型");
1056 | // }
1057 | vals.push(GetObject(false));
1058 | ReadColon();
1059 | if (ReadToken().type == TokenType.Case)
1060 | {
1061 | ParseCase(vals);
1062 | }
1063 | else
1064 | {
1065 | UndoToken();
1066 | }
1067 | }
1068 |
1069 | //解析try catch
1070 | private function ParseTry(executable:CodeExecutable):void
1071 | {
1072 | var exec:CodeExecutable;
1073 | var ret:CodeTry = new CodeTry();
1074 | exec = new CodeExecutable(CodeExecutable.Block_Function,executable);
1075 | ParseStatementBlock(exec);
1076 | ret.tryExecutable = exec;
1077 | ReadCatch();
1078 | ReadLeftParenthesis();
1079 | ret.identifier = ReadIdentifier();
1080 | var peek:Token = PeekToken();
1081 | if (peek.type == TokenType.Colon)
1082 | {
1083 | ReadToken();
1084 | ReadToken();
1085 | peek = PeekToken();
1086 | }
1087 | ReadRightParenthesis();
1088 | exec = new CodeExecutable(CodeExecutable.Block_Function,executable);
1089 | ParseStatementBlock(exec);
1090 | ret.catchExecutable = exec;
1091 | executable.addInstruction(new CodeInstruction(Opcode.CALL_TRY, ret));
1092 | }
1093 | //解析throw
1094 | private function ParseThrow(executable:CodeExecutable):void
1095 | {
1096 | var ret:CodeThrow = new CodeThrow();
1097 | ret.obj = GetObject();
1098 | executable.addInstruction(new CodeInstruction(Opcode.THROW, ret));
1099 | }
1100 | //解析return
1101 | private function ParseReturn(executable:CodeExecutable):void
1102 | {
1103 | var peek:Token = PeekToken();
1104 | if (peek.type == TokenType.RightBrace ||
1105 | peek.type == TokenType.SemiColon ||
1106 | peek.type == TokenType.Finished)
1107 | {
1108 | executable.addInstruction(new CodeInstruction(Opcode.RET,null));
1109 | }
1110 | else
1111 | {
1112 | executable.addInstruction(new CodeInstruction(Opcode.RET, GetObject()));
1113 | }
1114 | }
1115 | //解析表达式
1116 | private function ParseExpression(executable:CodeExecutable):void
1117 | {
1118 | UndoToken();
1119 | var peek:Token = PeekToken();
1120 | var member:CodeObject = GetObject();
1121 | if (member is CodeCallFunction)
1122 | {
1123 | executable.addInstruction(new CodeInstruction(Opcode.CALL_FUNCTION, member));
1124 | }
1125 | else if (member is CodeMember)
1126 | {
1127 | if ((member as CodeMember).calc != CALC.NONE)
1128 | {
1129 | executable.addInstruction(new CodeInstruction(Opcode.RESOLVE, member));
1130 | }
1131 | else
1132 | {
1133 | throw new ParseError(peek,"变量后缀不支持此操作符 " + PeekToken().lexeme);
1134 | }
1135 | }
1136 | else if (member is CodeAssign)
1137 | {
1138 | executable.addInstruction(new CodeInstruction(Opcode.RESOLVE, member));
1139 | }
1140 | else
1141 | {
1142 | throw new ParseError(peek,"语法不支持起始符号为 " + member);
1143 | }
1144 | }
1145 | //返回super
1146 | private function GetSuper(executable:CodeExecutable):CodeSuper
1147 | {
1148 | var ret:CodeSuper = new CodeSuper();
1149 | if(PeekToken().type == TokenType.Period)
1150 | {
1151 | ReadToken();
1152 | ret.superObject = GetObject();
1153 | }
1154 | else//直接调用构造
1155 | {
1156 | UndoToken();
1157 | ret.superObject = GetObject();
1158 | }
1159 | return ret;
1160 | }
1161 | //解析内部函数
1162 | private function ParseFunction():Object
1163 | {
1164 | // if (m_scriptExecutable.Block == Executable_Block.Context
1165 | // || m_scriptExecutable.Block == Executable_Block.Class)
1166 | // {
1167 | // UndoToken();
1168 | // ScriptFunction func = ParseFunctionDeclaration(true,true);
1169 | // m_scriptExecutable.AddScriptInstruction(new ScriptInstruction(Opcode.MOV, new CodeMember(func.Name), new CodeFunction(func)));
1170 | // }
1171 | return null;
1172 | }
1173 |
1174 | /// 读取{
1175 | private function ReadLeftBrace():void
1176 | {
1177 | var token:Token = ReadToken();
1178 | if (token.type != TokenType.LeftBrace){
1179 | throw new ParseError(token,"Left brace '{' expected.");
1180 | }
1181 | }
1182 |
1183 | /// 读取}
1184 | private function ReadRightBrace():void
1185 | {
1186 | var token:Token = ReadToken();
1187 | if (token.type != TokenType.RightBrace){
1188 | throw new ParseError(token,"Right brace '}' expected.");
1189 | }
1190 | }
1191 | /// 回滚Token
1192 | private function UndoToken():void
1193 | {
1194 | if (m_iNextToken <= 0){
1195 | throw new ParseError(null,"No more tokens to undo.");
1196 | }
1197 | --m_iNextToken;
1198 | }
1199 |
1200 | /// 读取class
1201 | private function ReadClass():void
1202 | {
1203 | var token:Token = ReadToken();
1204 | if (token.type != TokenType.Class){
1205 | throw new ParseError(token,"Class 'class' expected.");
1206 | }
1207 | }
1208 | //读取 包关键字
1209 | private function ReadPackage():String
1210 | {
1211 | var token:Token = ReadToken();
1212 | if (token.type != TokenType.Package){
1213 | throw new ParseError(token,"Package 'package' expected.");
1214 | }
1215 | return token.lexeme.toString();
1216 | }
1217 | /// 获得第一个Token
1218 | private function ReadToken():Token
1219 | {
1220 | if (!HasMoreTokens()){
1221 | throw new ParseError(null,"Unexpected end of token stream.");
1222 | }
1223 | return m_listTokens[m_iNextToken++];
1224 | }
1225 | /// 是否还有更多需要解析的语法
1226 | private function HasMoreTokens():Boolean
1227 | {
1228 | return m_iNextToken < m_listTokens.length;
1229 | }
1230 | /// 返回第一个Token
1231 | public function PeekToken():Token
1232 | {
1233 | if (!HasMoreTokens()){
1234 | throw new ParseError(null,"Unexpected end of token stream.");
1235 | }
1236 | return m_listTokens[m_iNextToken];
1237 | }
1238 | /// 读取 未知字符
1239 | private function ReadIdentifier():String
1240 | {
1241 | var token:Token = ReadToken();
1242 | if (token.type != TokenType.Identifier){
1243 | throw new ParseError(token,"Identifier expected.");
1244 | }
1245 | return token.lexeme.toString();
1246 | }
1247 | /// 读取(
1248 | private function ReadLeftParenthesis():void
1249 | {
1250 | var token:Token = ReadToken();
1251 | if (token.type != TokenType.LeftPar){
1252 | throw new ParseError(token,"Left parenthesis '(' expected.");
1253 | }
1254 | }
1255 | /// 读取)
1256 | private function ReadRightParenthesis():void
1257 | {
1258 | var token:Token = ReadToken();
1259 | if (token.type != TokenType.RightPar){
1260 | throw new ParseError(token,"Right parenthesis ')' expected.");
1261 | }
1262 | }
1263 | /// 读取:
1264 | private function ReadColon():void
1265 | {
1266 | var token:Token = ReadToken();
1267 | if (token.type != TokenType.Colon){
1268 | throw new ParseError(token,"Colon ':' expected.");
1269 | }
1270 | }
1271 | /// 读取,
1272 | private function ReadComma():void
1273 | {
1274 | var token:Token = ReadToken();
1275 | if (token.type != TokenType.Comma){
1276 | throw new ParseError(token,"Comma ',' expected.");
1277 | }
1278 | }
1279 | /// 读取var
1280 | private function ReadVar():void
1281 | {
1282 | var token:Token = ReadToken();
1283 | if (token.type != TokenType.Var){
1284 | throw new ParseError(token,"Var 'var' expected.");
1285 | }
1286 | }
1287 | /// 读取in
1288 | private function ReadIn():void
1289 | {
1290 | var token:Token = ReadToken();
1291 | if (token.type != TokenType.In){
1292 | throw new ParseError(token,"In 'in' expected.");
1293 | }
1294 | }
1295 | /// 读取;
1296 | private function ReadSemiColon():void
1297 | {
1298 | var token:Token = ReadToken();
1299 | if (token.type != TokenType.SemiColon){
1300 | throw new ParseError(token,"SemiColon ';' expected.");
1301 | }
1302 | }
1303 | /// 读取catch
1304 | private function ReadCatch():void
1305 | {
1306 | var token:Token = ReadToken();
1307 | if (token.type != TokenType.Catch){
1308 | throw new ParseError(token,"Catch 'catch' expected.");
1309 | }
1310 | }
1311 | /// 读取[
1312 | private function ReadLeftBracket():void
1313 | {
1314 | var token:Token = ReadToken();
1315 | if (token.type != TokenType.LeftBracket){
1316 | throw new ParseError(token,"Left bracket '[' expected for array indexing expression.");
1317 | }
1318 | }
1319 | /// 读取]
1320 | private function ReadRightBracket():void
1321 | {
1322 | var token:Token = ReadToken();
1323 | if (token.type != TokenType.RightBracket){
1324 | throw new ParseError(token,"Right bracket ']' expected for array indexing expression.");
1325 | }
1326 | }
1327 | }
1328 | }
--------------------------------------------------------------------------------
/src/how/as2js/compiler/Token.as:
--------------------------------------------------------------------------------
1 | package how.as2js.compiler
2 | {
3 |
4 |
5 | public class Token
6 | {
7 | private var _type:int;
8 |
9 | /**
10 | * 标记类型
11 | */
12 | public function get type():int
13 | {
14 | return _type;
15 | }
16 |
17 | private var _lexeme:Object;
18 |
19 | /**
20 | * 标记值
21 | */
22 | public function get lexeme():Object
23 | {
24 | return _lexeme;
25 | }
26 |
27 | private var _sourceLine:int;
28 |
29 | /**
30 | * 所在行
31 | */
32 | public function get sourceLine():int
33 | {
34 | return _sourceLine;
35 | }
36 |
37 | private var _sourceChar:int;
38 |
39 | /**
40 | * 所在列
41 | */
42 | public function get sourceChar():int
43 | {
44 | return _sourceChar;
45 | }
46 |
47 | public function Token(tokenType:int,lexeme:Object, sourceLine:int, sourceChar:int)
48 | {
49 | this._type = tokenType;
50 | this._lexeme = lexeme;
51 | this._sourceLine = sourceLine;
52 | this._sourceChar = sourceChar;
53 | }
54 | public function toString():String
55 | {
56 | return TokenType.getTypeName(_type) + ":" + _lexeme.toString();
57 | }
58 | }
59 | }
--------------------------------------------------------------------------------
/src/how/as2js/compiler/TokenType.as:
--------------------------------------------------------------------------------
1 | package how.as2js.compiler
2 | {
3 | import flash.utils.describeType;
4 |
5 | public final class TokenType
6 | {
7 |
8 | public static function getTypeName(value:int):Object
9 | {
10 | var tokenXMLList:XMLList= describeType(TokenType).variable;
11 | for (var i:int = 0; i < tokenXMLList.length(); i++)
12 | {
13 | if(TokenType[tokenXMLList[i].@name.toString()] == value)
14 | {
15 | return tokenXMLList[i].@name;
16 | }
17 | }
18 | return null;
19 | }
20 | //空类型(没有实际用途)
21 | public static var None:int = 0;
22 | //var
23 | public static var Var:int = 1;
24 | //var
25 | public static var Const:int = 2;
26 | //{
27 | public static var LeftBrace:int = 3;
28 | //}
29 | public static var RightBrace:int = 4;
30 | //(
31 | public static var LeftPar:int = 5;
32 | //)
33 | public static var RightPar:int = 6;
34 | //[
35 | public static var LeftBracket:int = 7;
36 | //]
37 | public static var RightBracket:int = 8;
38 | //.
39 | public static var Period:int = 9;
40 | //:int = 0;
41 | public static var Comma:int = 10;
42 | //:
43 | public static var Colon:int = 11;
44 | //;
45 | public static var SemiColon:int = 12;
46 | //?
47 | public static var QuestionMark:int = 13;
48 | //+
49 | public static var Plus:int = 14;
50 | //++
51 | public static var Increment:int = 15;
52 | //+=
53 | public static var AssignPlus:int = 16;
54 | //-
55 | public static var Minus:int = 17;
56 | //--
57 | public static var Decrement:int = 18;
58 | //-=
59 | public static var AssignMinus:int = 19;
60 | //*
61 | public static var Multiply:int = 20;
62 | //*=
63 | public static var AssignMultiply:int = 21;
64 | ///
65 | public static var Divide:int = 22;
66 | ///=
67 | public static var AssignDivide:int = 23;
68 | //% 模运算
69 | public static var Modulo:int = 24;
70 | //%=
71 | public static var AssignModulo:int = 25;
72 | //| 或运算
73 | public static var InclusiveOr:int = 26;
74 | //|=
75 | public static var AssignInclusiveOr:int = 27;
76 | //||
77 | public static var Or:int = 28;
78 | //& 并运算
79 | public static var Combine:int = 29;
80 | //&=
81 | public static var AssignCombine:int = 30;
82 | //&&
83 | public static var And:int = 31;
84 | //^ 异或
85 | public static var XOR:int = 32;
86 | //^=
87 | public static var AssignXOR:int = 33;
88 | //<<左移
89 | public static var Shi:int = 34;
90 | //<<=
91 | public static var AssignShi:int = 35;
92 | //>> 右移
93 | public static var Shr:int = 36;
94 | //>>=
95 | public static var AssignShr:int = 37;
96 | //!
97 | public static var Not:int = 38;
98 | //=
99 | public static var Assign:int = 39;
100 | //==
101 | public static var Equal:int = 40;
102 | //!=
103 | public static var NotEqual:int = 41;
104 | //>
105 | public static var Greater:int = 42;
106 | //>=
107 | public static var GreaterOrEqual:int = 43;
108 | // <
109 | public static var Less:int = 44;
110 | //<=
111 | public static var LessOrEqual:int = 45;
112 | //...
113 | public static var Params:int = 46;
114 | //if
115 | public static var If:int = 47;
116 | //else
117 | public static var Else:int = 48;
118 | //for
119 | public static var For:int = 49;
120 | //final
121 | public static var Final:int = 50;
122 | //dynamic
123 | public static var Dynamic:int = 51;
124 | //each
125 | public static var Each:int = 52;
126 | //in
127 | public static var In:int = 53;
128 | //switch
129 | public static var Switch:int = 54;
130 | //case
131 | public static var Case:int = 55;
132 | //default
133 | public static var Default:int = 56;
134 | //break
135 | public static var Break:int = 57;
136 | //continue
137 | public static var Continue:int = 58;
138 | //return
139 | public static var Return:int = 59;
140 | //while
141 | public static var While:int = 60;
142 | //function
143 | public static var Function:int = 61;
144 | //try
145 | public static var Try:int = 62;
146 | //catch
147 | public static var Catch:int = 63;
148 | //throw
149 | public static var Throw:int = 64;
150 | //bool true false
151 | public static var Boolean:int = 65;
152 | //int float
153 | public static var Number:int = 66;
154 | //string
155 | public static var String:int = 67;
156 | //null
157 | public static var Null:int = 68;
158 | //包定义
159 | public static var Package:int = 69;
160 | //类定义
161 | public static var Class:int = 70;
162 | //接口定义
163 | public static var Interface:int = 71;
164 | //公共
165 | public static var Public:int = 72;
166 | //保护
167 | public static var Protected:int = 73;
168 | //私有
169 | public static var Private:int = 74;
170 | //包内
171 | public static var Internal:int = 75;
172 | //继承
173 | public static var Extends:int = 76;
174 | //静态
175 | public static var Static:int = 77;
176 | //重写
177 | public static var Override:int = 78;
178 | //实例
179 | public static var New:int = 79;
180 | //无返回值
181 | public static var Void:int = 80;
182 | //引入
183 | public static var Import:int = 81;
184 | //get
185 | public static var Get:int = 82;
186 | //set
187 | public static var Set:int = 83;
188 | //super
189 | public static var Super:int = 84;
190 | //说明符
191 | public static var Identifier:int = 85;
192 | //结束
193 | public static var Finished:int = 86;
194 | //is
195 | public static var Is:int = 87;
196 | //as
197 | public static var As:int = 88;
198 | //delete
199 | public static var Delete:int = 89;
200 | }
201 | }
--------------------------------------------------------------------------------
/src/how/as2js/error/ParseError.as:
--------------------------------------------------------------------------------
1 | package how.as2js.error
2 | {
3 | import how.as2js.compiler.Token;
4 | import how.as2js.compiler.TokenType;
5 |
6 | public class ParseError extends Error
7 | {
8 | public function ParseError(token:Token,message:String="")
9 | {
10 | var msg:String = " Line:" + (token.sourceLine+1) + " Column:" + token.sourceChar + " Type:" + TokenType.getTypeName(token.type) + " value[" + token.lexeme + "] " + message;
11 | super(!token?message:msg);
12 | }
13 | }
14 | }
--------------------------------------------------------------------------------
/src/how/as2js/error/StackInfo.as:
--------------------------------------------------------------------------------
1 | package how.as2js.error
2 | {
3 | public class StackInfo
4 | {
5 | public var Breviary:String = ""; // 文件摘要
6 | public var Line:int = 1; // 起始关键字所在行数
7 | public function StackInfo(breviary:String,line:int)
8 | {
9 | this.Breviary = breviary;
10 | this.Line = line;
11 | }
12 | }
13 | }
--------------------------------------------------------------------------------
/src/how/as2js/runtime/Opcode.as:
--------------------------------------------------------------------------------
1 | package how.as2js.runtime
2 | {
3 | public class Opcode
4 | {
5 | //定义一个类
6 | public static const Class:int = 0;
7 | //继承
8 | public static const Extends:int = 1;
9 | //赋值操作
10 | public static const MOV:int = 2;
11 | //申请一个局部变量
12 | public static const VAR:int = 3;
13 | //执行If语句
14 | public static const CALL_IF:int = 4;
15 | //执行For语句
16 | public static const CALL_FOR:int = 5;
17 | //执行For语句
18 | public static const CALL_FORSIMPLE:int = 6;
19 | //执行Foreach语句
20 | public static const CALL_FOREACH:int = 7;
21 | //执行Foreach语句
22 | public static const CALL_FORIN:int = 8;
23 | //执行While语句
24 | public static const CALL_WHILE:int = 9;
25 | //执行switch语句
26 | public static const CALL_SWITCH:int = 10;
27 | //执行try catch语句
28 | public static const CALL_TRY:int = 11;
29 | //调用一个函数
30 | public static const CALL_FUNCTION:int = 12;
31 | //throw
32 | public static const THROW:int = 13;
33 | //解析一个变量
34 | public static const RESOLVE:int = 14;
35 | //返回值
36 | public static const RET:int = 15;
37 | //break跳出 for foreach while
38 | public static const BREAK:int = 16;
39 | //continue跳出本次 for foreach while
40 | public static const CONTINUE:int = 17;
41 | //实例化
42 | public static const NEW:int = 18;
43 | //父类
44 | public static const SUPER:int = 19;
45 | //is as
46 | public static const ISAS:int = 20;
47 | //delete
48 | public static const DELETE:int = 21;
49 | }
50 | }
--------------------------------------------------------------------------------
/src/how/as2js/runtime/Runtime.as:
--------------------------------------------------------------------------------
1 | package how.as2js.runtime
2 | {
3 | import flash.utils.Dictionary;
4 |
5 | import how.as2js.Config;
6 | import how.as2js.codeDom.CodeClass;
7 |
8 | public class Runtime
9 | {
10 | private var _classes:Dictionary = new Dictionary();
11 | public function Runtime()
12 | {
13 | }
14 | public function getClasses(packAge:String):Vector.
15 | {
16 | var result:Vector. = new Vector.();
17 | if(packAge && _classes[packAge])
18 | {
19 | var classes:Dictionary = _classes[packAge];
20 | for (var key:String in classes)
21 | {
22 | result.push(classes[key]);
23 | }
24 | }
25 | return result;
26 | }
27 | public function getClass(packAge:String,className:String):CodeClass
28 | {
29 | if(packAge)
30 | {
31 | if(_classes[packAge])
32 | {
33 | return _classes[packAge][className];
34 | }
35 | else
36 | {
37 | return null;
38 | }
39 | }
40 | else
41 | {
42 | return _classes[className];
43 | }
44 | }
45 | public function registerClass(codeClass:CodeClass):void
46 | {
47 | if(codeClass.packAge.length)
48 | {
49 | _classes[codeClass.packAge] = _classes[codeClass.packAge] || new Dictionary();
50 | _classes[codeClass.packAge][codeClass.name] = codeClass;
51 | }
52 | else
53 | {
54 | _classes[codeClass.name] = codeClass;
55 | }
56 | }
57 | public function unRegisterClass(codeClass:CodeClass):void
58 | {
59 | if(codeClass.packAge)
60 | {
61 | delete _classes[codeClass.packAge][codeClass.name];
62 | }
63 | else
64 | {
65 | delete _classes[codeClass.name];
66 | }
67 | }
68 | public function outClass(modol:int = 1):String
69 | {
70 | var result:String = "";
71 | Config.modol = modol;
72 | for (var key:String in _classes)
73 | {
74 | var codeClass:CodeClass;
75 | if(_classes[key] is CodeClass)
76 | {
77 | codeClass = _classes[key];
78 | result += codeClass.outClass(this)+"\n";
79 | }
80 | for(var className:String in _classes[key])
81 | {
82 | codeClass = _classes[key][className];
83 | result += codeClass.outClass(this)+"\n";
84 | }
85 | }
86 | return result;
87 | }
88 | }
89 | }
--------------------------------------------------------------------------------
/src/how/as2js/runtime/ToJavaScript.as:
--------------------------------------------------------------------------------
1 | package how.as2js.runtime
2 | {
3 | import how.as2js.codeDom.CodeClass;
4 |
5 | public class ToJavaScript
6 | {
7 | public function ToJavaScript()
8 | {
9 | }
10 | public function to(codeClass:CodeClass):void
11 | {
12 | var imports:Vector. = codeClass.imports;
13 | }
14 | private function getVar(key:String):String
15 | {
16 | return "var " + key + ";";
17 | }
18 | }
19 | }
--------------------------------------------------------------------------------