Пример #1
0
		public void Parse(CsNamespace pNameSpace, IEnumerable<CsUsingDirective> pUsing, string pOutputFolder) {
			if (pNameSpace == null) {
				return;
			}

			_outputFolder = pOutputFolder;
			string name = getNamespace(pNameSpace);
			string packDir = pOutputFolder + name.Replace('.', '\\');
			Directory.CreateDirectory(packDir);
			CodeBuilder builder = new CodeBuilder();

			foreach (CsNode cn in pNameSpace.member_declarations) {
				builder.Append("package ");

				builder.Append(name);
				builder.AppendLineAndIndent(" {");

				StringBuilder usings = new StringBuilder();

				parseUsing(pUsing, usings);
				parseUsing(pNameSpace.using_directives, usings);
				Using = usings.ToString();

				builder.Append(usings);

				builder.AppendLine(ClassParser.IMPORT_MARKER);
				ImportStatementList.Init();

				CsClass csClass = cn as CsClass;

				if (csClass != null) {
					ClassParser.Parse(csClass, builder, _creator);
					if (ClassParser.IsExtension) {
						File.WriteAllText(packDir + "\\" + ClassParser.ExtensionName + ".as", builder.ToString());

					} else {
						File.WriteAllText(packDir + "\\" + csClass.identifier.identifier + ".as", builder.ToString());
					}

					builder.Length = 0;
					continue;
				}

				CsInterface csInterface = cn as CsInterface;
				if (csInterface != null) {
					InterfaceParser.Parse(csInterface, builder, _creator);
					File.WriteAllText(packDir + "\\" + csInterface.identifier.identifier + ".as", builder.ToString());
					builder.Length = 0;
					continue;
				}

				if (csClass == null) {
					throw new Exception("Unknown type");
				}
			}
		}
Пример #2
0
		private static void parseUsingStatement(CsStatement pArg1, CodeBuilder pSb, FactoryExpressionCreator pCreator) {
			CsUsingStatement statement = (CsUsingStatement)pArg1;
			CsLocalVariableDeclaration declaration = statement.resource as CsLocalVariableDeclaration;

			string varname;

			if (declaration == null) {
				varname = "$$using$$";
				Expression e = pCreator.Parse(statement.resource);

				pSb.AppendFormat("var {0}:{1} = {2};", 
					varname,
					As3Helpers.Convert(Helpers.GetType(e.Type)),
					e.Value
				);

				pSb.AppendLine();

			} else {
				CsLocalVariableDeclarator declarator = declaration.declarators.First.Value;
				StringBuilder sb = new StringBuilder();

				sb.AppendFormat("var {0}:{1}",
					declarator.identifier.identifier,
					As3Helpers.Convert(Helpers.GetType(declaration.type))
				);

				varname = declarator.identifier.identifier;

				if (declarator.initializer == null) {
					sb.Append(";");

				} else {
					sb.AppendFormat(" = {0};", parseNode(declarator.initializer, pCreator));
				}

				pSb.Append(sb.ToString());
				pSb.AppendLine();

			}

			pSb.Append("try {");
			pSb.AppendLine();

			ParseNode(statement.statement, pSb, pCreator);

			pSb.Append("} finally {");
			pSb.AppendLine();
			pSb.AppendFormat("	if ({0} != null) {0}.Dispose();", varname);
			pSb.AppendLine();

			pSb.Append("}");
			pSb.AppendLine();
			pSb.AppendLine();
		}
		public void WriteCode(ITemplate tpl, FragmentCodePoint point, CodeBuilder cb) {
			if (CustomInstantiate)
				cb.AppendLine("if (" + Id + " == null) throw new InvalidOperationException(\"The control instance " + Id + " must be assigned before the control can be rendered.\");");
			
			if (NumInnerFragments > 0) {
				cb.Append("((IControlHost)" + Id + ").SetInnerFragments(new string[] { ");
				for (int i = 0; i < NumInnerFragments; i++) {
					if (i > 0)
						cb.Append(", ");
					cb.Append(Id + "_inner" + (i + 1).ToString(System.Globalization.CultureInfo.InvariantCulture) + "()");
				}
				cb.AppendLine(" });");
			}

			cb.AppendLine(ParserUtils.RenderFunctionStringBuilderName + ".Append(((IControl)" + Id + ").Html);");
		}
Пример #4
0
		public Expression Parse(CsExpression pStatement, FactoryExpressionCreator pCreator) {
			CsLambdaExpression ex = (CsLambdaExpression)pStatement;

			LambdaMethodExpression lambda = new LambdaMethodExpression((CsLambdaExpression)pStatement, pCreator);

			CodeBuilder b = new CodeBuilder();
			b.AppendFormat("function ({0}):{1} {{",
			               As3Helpers.GetParameters(lambda.Arguments),
			               (lambda.ReturnType == null) ? "void" : As3Helpers.Convert(lambda.ReturnType)
				);

			b.Indent();
			b.Indent();
			b.Indent();
			b.AppendLine();

			if (!(lambda.CodeBlock is CsBlock)) {
				b.Append("return ");
			}

			BlockParser.ParseNode(lambda.CodeBlock, b, pCreator);

			b.AppendLine("}");
			b.AppendLine();
			b.Unindent();
			b.Unindent();
			b.Unindent();
			return new Expression(b.ToString(), ex.entity_typeref);
		}
Пример #5
0
		public static void Parse(TheConstructor pConstructor, CodeBuilder pBuilder, FactoryExpressionCreator pCreator) {
			if (pConstructor.IsStaticConstructor) {
				pBuilder.Append("{");

			} else {
				pBuilder.AppendFormat("{4}{0}function {1}({2}){3} {{",
								ClassParser.IsMainClass ? "private " : As3Helpers.ConvertModifiers(pConstructor.Modifiers, _notValidConstructorMod),
								ClassParser.IsMainClass ? @"$ctor" : pConstructor.Name,
								As3Helpers.GetParameters(pConstructor.Arguments),
								ClassParser.IsMainClass ? ":void" : string.Empty,// pConstructor.MyClass.Name,
								pConstructor.OverridesBaseConstructor ? "override " : string.Empty
					);
			}

			pBuilder.AppendLine();

			if (pConstructor.HasBaseCall) {
				pBuilder.AppendFormat("\tsuper({0});", As3Helpers.GetCallingArguments(pConstructor.BaseArguments));
				pBuilder.AppendLine();
			}
		
			BlockParser.Parse(pConstructor.CodeBlock, pBuilder, pCreator);

			pBuilder.AppendLine("}");
			pBuilder.AppendLine();
		}
Пример #6
0
		private void WriteDefinition(CodeBuilder cb, string type, string backingFieldType, bool isServer) {
			cb.AppendLine(string.Format("private {0} {1};", isServer ? backingFieldServerType : backingFieldClientType, backingFieldName));
			if (isServer && clientInject)
				cb.AppendLine("[ClientInject]");
			cb.Append(AccessModifierHelper.WriteDeclarator(accessModifier, type, name)).AppendLine(" {").Indent();
			if (hasGetter)
				cb.AppendLine("get { return " + (type != backingFieldType ? "(" + type + ")" : "") + backingFieldName + "; }");
			if (hasSetter)
				cb.AppendLine("set { " + backingFieldName + " = " + (type != backingFieldType ? "(" + backingFieldType + ")" : "") + "value; " + (!string.IsNullOrEmpty(valueChangedHookName) ? valueChangedHookName + "(); " : "") + "}");
			cb.Outdent().AppendLine("}").AppendLine();
		}
Пример #7
0
		public static void Parse(TheConstant pConstant, CodeBuilder pBuilder) {
			string modifiers = As3Helpers.ConvertModifiers(pConstant.Modifiers);

			foreach (Constant declarator in pConstant.Constants) {
				StringBuilder sb = new StringBuilder();

				sb.AppendFormat(@"{0}const {1}:{2} = {3};",
					modifiers,
					declarator.Name,
					As3Helpers.Convert(declarator.ReturnType),
					declarator.Initializer.Value
				);

				pBuilder.Append(sb.ToString());
				pBuilder.AppendLine();
			}
		}
Пример #8
0
		public static void Parse(TheVariable pVariable, CodeBuilder pBuilder) {
			foreach (Variable declarator in pVariable.Variables) {
				StringBuilder sb = new StringBuilder();

				sb.AppendFormat("{0}var {1}:{2}",
					JsHelpers.ConvertModifiers(pVariable.Modifiers, _notValidVariableMod),
					declarator.Name,
					JsHelpers.Convert(declarator.ReturnType)
				);

				if (declarator.Initializer == null) {
					sb.Append(";");

				} else {
					sb.AppendFormat(" = {0};", declarator.Initializer.Value);
				}

				pBuilder.Append(sb.ToString());
				pBuilder.AppendLine();
			}
		}
Пример #9
0
        public override void VisitBinaryExpression(BinaryExpressionSyntax node)
        {
            var ci   = m_ClassInfoStack.Peek();
            var oper = m_Model.GetOperation(node) as IHasOperatorMethodExpression;

            if (null != oper && oper.UsesOperatorMethod)
            {
                IMethodSymbol msym     = oper.OperatorMethod;
                var           castOper = oper as IConversionExpression;
                if (null != castOper)
                {
                    InvocationInfo ii      = new InvocationInfo();
                    var            arglist = new List <ExpressionSyntax>()
                    {
                        node.Left
                    };
                    ii.Init(msym, arglist, m_Model);
                    OutputOperatorInvoke(ii, node);
                }
                else
                {
                    InvocationInfo ii      = new InvocationInfo();
                    var            arglist = new List <ExpressionSyntax>()
                    {
                        node.Left, node.Right
                    };
                    ii.Init(msym, arglist, m_Model);
                    OutputOperatorInvoke(ii, node);
                }
            }
            else
            {
                string op = node.OperatorToken.Text;
                ProcessBinaryOperator(node, ref op);
                string functor;
                if (s_BinaryFunctor.TryGetValue(op, out functor))
                {
                    CodeBuilder.AppendFormat("{0}(", functor);
                    VisitExpressionSyntax(node.Left);
                    CodeBuilder.Append(", ");
                    if (op == "as" || op == "is")
                    {
                        var typeInfo = m_Model.GetTypeInfo(node.Right);
                        var type     = typeInfo.Type;
                        OutputType(type, node, ci, op);
                    }
                    else if (op == "??")
                    {
                        var  rightOper    = m_Model.GetOperation(node.Right);
                        bool rightIsConst = null != rightOper && rightOper.ConstantValue.HasValue;
                        if (rightIsConst)
                        {
                            CodeBuilder.Append("true, ");
                            VisitExpressionSyntax(node.Right);
                        }
                        else
                        {
                            CodeBuilder.Append("false, (function() return ");
                            VisitExpressionSyntax(node.Right);
                            CodeBuilder.Append("; end)");
                        }
                    }
                    else
                    {
                        VisitExpressionSyntax(node.Right);
                    }
                    CodeBuilder.Append(")");
                }
                else if (op == "+")
                {
                    ProcessAddOrStringConcat(node.Left, node.Right);
                }
                else if (op == "==" || op == "~=")
                {
                    ProcessEqualOrNotEqual(op, node.Left, node.Right);
                }
                else
                {
                    CodeBuilder.Append("(");
                    VisitExpressionSyntax(node.Left);
                    CodeBuilder.AppendFormat(" {0} ", op);
                    VisitExpressionSyntax(node.Right);
                    CodeBuilder.Append(")");
                }
            }
        }
Пример #10
0
		public static void Parse(CsInterface pCsInterface, CodeBuilder pBuilder, FactoryExpressionCreator pCreator) {
			StringBuilder sb = new StringBuilder();
			TheClass myClass = TheClassFactory.Get(pCsInterface, pCreator);

			sb.AppendFormat("{1}interface {0}",
							myClass.Name,
							As3Helpers.ConvertModifiers(myClass.Modifiers, _notValidClassMod));

			if (myClass.Implements.Count != 0) {
				sb.Append(" extends ");
				foreach (string s in myClass.Implements) {
					sb.Append(As3Helpers.Convert(s));
					sb.Append(", ");
				}

				sb.Remove(sb.Length - 2, 2);
			}

			sb.Append(" {");
			sb.AppendLine();

			pBuilder.Append(sb.ToString());
			pBuilder.AppendLineAndIndent();

			if (pCsInterface.member_declarations != null) {
				foreach (CsNode memberDeclaration in pCsInterface.member_declarations) {
					//if (memberDeclaration is CsConstructor) {
					//    MethodParser.Parse(myClass.GetConstructor((CsConstructor)memberDeclaration), pBuilder);
					//} else 
				if (memberDeclaration is CsMethod) {
						MethodParser.Parse(myClass.GetMethod((CsMethod)memberDeclaration), pBuilder, pCreator);

					} else if (memberDeclaration is CsIndexer) {
						IndexerParser.Parse(myClass.GetIndexer((CsIndexer)memberDeclaration), pBuilder, pCreator);

					} else if (memberDeclaration is CsVariableDeclaration) {
						VariableParser.Parse(myClass.GetVariable((CsVariableDeclaration)memberDeclaration), pBuilder);
					} else 
					//if (memberDeclaration is CsConstantDeclaration) {
					//    ConstantParser.Parse(myClass.GetConstant((CsConstantDeclaration)memberDeclaration), pBuilder);
					//} else 
					//if (memberDeclaration is CsDelegate) {
					//    DelegateParser.Parse(myClass.GetDelegate((CsDelegate)memberDeclaration), pBuilder);
					//} else 
					//if (memberDeclaration is CsEvent) {
					//    EventParser.Parse(myClass.GetEvent(((CsEvent)memberDeclaration).declarators.First.Value.identifier.identifier),
					//                      pBuilder);
					//} else 
					if (memberDeclaration is CsProperty) {
						PropertyParser.Parse(myClass.GetProperty((CsProperty)memberDeclaration), pBuilder, pCreator);
					//} else if (memberDeclaration is CsInterface) {
					//    Parse((CsInterface)memberDeclaration, privateClasses);
					} else {
						throw new NotSupportedException();
					}
				}
			}

			pBuilder.AppendLineAndUnindent("}");
			pBuilder.AppendLineAndUnindent("}");
			pBuilder.AppendLine();
			string imports = ClassParser.getImports();
			pBuilder.Replace(ClassParser.IMPORT_MARKER, imports);
		}
Пример #11
0
        public override void VisitIdentifierName(IdentifierNameSyntax node)
        {
            string name = node.Identifier.Text;

            if (m_ClassInfoStack.Count > 0)
            {
                ClassInfo  classInfo  = m_ClassInfoStack.Peek();
                SymbolInfo symbolInfo = m_Model.GetSymbolInfo(node);
                var        sym        = symbolInfo.Symbol;
                if (null != sym)
                {
                    if (sym.Kind == SymbolKind.NamedType || sym.Kind == SymbolKind.Namespace)
                    {
                        string fullName = ClassInfo.GetFullName(sym);
                        CodeBuilder.Append(fullName);

                        if (sym.Kind == SymbolKind.NamedType)
                        {
                            var namedType = sym as INamedTypeSymbol;
                            AddReferenceAndTryDeriveGenericTypeInstance(classInfo, namedType);
                        }
                        return;
                    }
                    else if (sym.Kind == SymbolKind.Field || sym.Kind == SymbolKind.Property || sym.Kind == SymbolKind.Event)
                    {
                        if (IsNewObjMember(name))
                        {
                            CodeBuilder.AppendFormat("getinstance(newobj, \"{0}\")", name);
                            return;
                        }
                        if (sym.ContainingType == classInfo.SemanticInfo || sym.ContainingType == classInfo.SemanticInfo.OriginalDefinition || classInfo.IsInherit(sym.ContainingType))
                        {
                            if (sym.IsStatic)
                            {
                                CodeBuilder.AppendFormat("getstatic({0}, \"{1}\")", classInfo.Key, sym.Name);
                            }
                            else
                            {
                                CodeBuilder.AppendFormat("getinstance(this, \"{0}\")", sym.Name);
                            }
                            return;
                        }
                    }
                    else if (sym.Kind == SymbolKind.Method && (sym.ContainingType == classInfo.SemanticInfo || sym.ContainingType == classInfo.SemanticInfo.OriginalDefinition || classInfo.IsInherit(sym.ContainingType)))
                    {
                        var    msym         = sym as IMethodSymbol;
                        string manglingName = NameMangling(msym);
                        var    mi           = new MethodInfo();
                        mi.Init(msym, node);
                        if (node.Parent is InvocationExpressionSyntax)
                        {
                            if (sym.IsStatic)
                            {
                                CodeBuilder.AppendFormat("getstatic({0}, \"{1}\")", classInfo.Key, manglingName);
                            }
                            else
                            {
                                CodeBuilder.AppendFormat("getinstance(this, \"{0}\")", manglingName);
                            }
                        }
                        else
                        {
                            string className     = ClassInfo.GetFullName(msym.ContainingType);
                            string delegationKey = string.Format("{0}:{1}", className, manglingName);
                            string varName       = string.Format("__delegation_{0}", GetSourcePosForVar(node));

                            CodeBuilder.Append("(function(){ ");

                            string paramsString = string.Join(", ", mi.ParamNames.ToArray());
                            if (msym.IsStatic)
                            {
                                CodeBuilder.AppendFormat("builddelegation(\"{0}\", {1}, \"{2}\", {3}, {4}, {5}, {6});", paramsString, varName, delegationKey, className, manglingName, msym.ReturnsVoid ? "false" : "true", msym.IsStatic ? "true" : "false");
                            }
                            else
                            {
                                CodeBuilder.AppendFormat("builddelegation(\"{0}\", {1}, \"{2}\", {3}, {4}, {5}, {6});", paramsString, varName, delegationKey, "this", manglingName, msym.ReturnsVoid ? "false" : "true", msym.IsStatic ? "true" : "false");
                            }

                            CodeBuilder.Append(" })()");
                        }
                        return;
                    }
                }
                else
                {
                    if (IsNewObjMember(name))
                    {
                        CodeBuilder.AppendFormat("getinstance(newobj, \"{0}\")", name);
                        return;
                    }
                    ReportIllegalSymbol(node, symbolInfo);
                }
            }
            CodeBuilder.Append(name);
        }
Пример #12
0
        public override void VisitPropertyDeclaration(PropertyDeclarationSyntax node)
        {
            var             ci      = m_ClassInfoStack.Peek();
            IPropertySymbol declSym = m_Model.GetDeclaredSymbol(node);

            if (null != declSym)
            {
                string require = ClassInfo.GetAttributeArgument <string>(declSym, "Cs2Lua.RequireAttribute", 0);
                if (!string.IsNullOrEmpty(require))
                {
                    m_SymbolTable.AddRequire(ci.Key, require);
                }
                if (ClassInfo.HasAttribute(declSym, "Cs2Lua.IgnoreAttribute"))
                {
                    return;
                }
                if (declSym.IsAbstract)
                {
                    return;
                }
            }

            bool noimpl = true;

            foreach (var accessor in node.AccessorList.Accessors)
            {
                var sym = m_Model.GetDeclaredSymbol(accessor);
                if (null != accessor.Body)
                {
                    noimpl = false;
                    break;
                }
            }

            if (noimpl)
            {
                //退化为field
                StringBuilder curBuilder = ci.CurrentCodeBuilder;

                if (declSym.IsStatic)
                {
                    ci.CurrentCodeBuilder = ci.StaticFieldCodeBuilder;
                }
                else
                {
                    ci.CurrentCodeBuilder = ci.InstanceFieldCodeBuilder;
                }
                CodeBuilder.AppendFormat("{0}{1} = ", GetIndentString(), SymbolTable.GetPropertyName(declSym));
                if (null != node.Initializer)
                {
                    VisitExpressionSyntax(node.Initializer.Value);
                    CodeBuilder.Append(",");
                }
                else
                {
                    CodeBuilder.Append("true,");
                }
                CodeBuilder.AppendLine();

                ci.CurrentCodeBuilder = curBuilder;
            }
            else
            {
                StringBuilder curBuilder = ci.CurrentCodeBuilder;
                if (declSym.IsStatic)
                {
                    ci.CurrentCodeBuilder = ci.StaticFunctionCodeBuilder;
                }
                else
                {
                    ci.CurrentCodeBuilder = ci.InstanceFunctionCodeBuilder;
                }
                foreach (var accessor in node.AccessorList.Accessors)
                {
                    var sym = m_Model.GetDeclaredSymbol(accessor);
                    if (null != sym)
                    {
                        var mi = new MethodInfo();
                        mi.Init(sym, accessor);
                        m_MethodInfoStack.Push(mi);

                        string manglingName = NameMangling(sym);
                        string keyword      = accessor.Keyword.Text;
                        string paramStr     = string.Join(", ", mi.ParamNames.ToArray());
                        if (!declSym.IsStatic)
                        {
                            if (string.IsNullOrEmpty(paramStr))
                            {
                                paramStr = "this";
                            }
                            else
                            {
                                paramStr = "this, " + paramStr;
                            }
                        }
                        CodeBuilder.AppendFormat("{0}{1} = {2}function({3})", GetIndentString(), manglingName, mi.ExistYield ? "wrapenumerable(" : string.Empty, paramStr);
                        CodeBuilder.AppendLine();
                        ++m_Indent;
                        if (null != accessor.Body)
                        {
                            if (mi.ValueParams.Count > 0)
                            {
                                OutputWrapValueParams(CodeBuilder, mi);
                            }
                            VisitBlock(accessor.Body);
                        }
                        --m_Indent;
                        CodeBuilder.AppendFormat("{0}end{1},", GetIndentString(), mi.ExistYield ? ")" : string.Empty);
                        CodeBuilder.AppendLine();

                        m_MethodInfoStack.Pop();
                    }
                }
                ci.CurrentCodeBuilder = curBuilder;

                CodeBuilder.AppendFormat("{0}{1} = {{", GetIndentString(), SymbolTable.GetPropertyName(declSym));
                CodeBuilder.AppendLine();
                ++m_Indent;
                foreach (var accessor in node.AccessorList.Accessors)
                {
                    var sym = m_Model.GetDeclaredSymbol(accessor);
                    if (null != sym)
                    {
                        string manglingName = NameMangling(sym);
                        string keyword      = accessor.Keyword.Text;
                        CodeBuilder.AppendFormat("{0}{1} = {2}.{3},", GetIndentString(), keyword, declSym.IsStatic ? "static_methods" : "instance_methods", manglingName);
                        CodeBuilder.AppendLine();
                    }
                }
                --m_Indent;
                CodeBuilder.AppendFormat("{0}", GetIndentString());
                CodeBuilder.AppendLine("},");
            }
        }
Пример #13
0
        public override void VisitIdentifierName(IdentifierNameSyntax node)
        {
            string name = node.Identifier.Text;

            if (m_ClassInfoStack.Count > 0)
            {
                ClassInfo  classInfo  = m_ClassInfoStack.Peek();
                SymbolInfo symbolInfo = m_Model.GetSymbolInfo(node);
                var        sym        = symbolInfo.Symbol;
                if (null != sym)
                {
                    if (sym.Kind == SymbolKind.NamedType || sym.Kind == SymbolKind.Namespace)
                    {
                        string fullName = ClassInfo.GetFullName(sym);
                        CodeBuilder.Append(fullName);

                        if (sym.Kind == SymbolKind.NamedType)
                        {
                            var namedType = sym as INamedTypeSymbol;
                            AddReferenceAndTryDeriveGenericTypeInstance(classInfo, namedType);
                        }
                        return;
                    }
                    else if (sym.Kind == SymbolKind.Field || sym.Kind == SymbolKind.Property || sym.Kind == SymbolKind.Event)
                    {
                        if (m_ObjectCreateStack.Count > 0)
                        {
                            ITypeSymbol symInfo = m_ObjectCreateStack.Peek();
                            if (null != symInfo)
                            {
                                var names = symInfo.GetMembers(name);
                                if (names.Length > 0)
                                {
                                    CodeBuilder.AppendFormat("newobj.{0}", name);
                                    return;
                                }
                            }
                        }
                        if (sym.ContainingType == classInfo.SemanticInfo || sym.ContainingType == classInfo.SemanticInfo.OriginalDefinition || classInfo.IsInherit(sym.ContainingType))
                        {
                            if (sym.IsStatic)
                            {
                                CodeBuilder.AppendFormat("{0}.{1}", classInfo.Key, sym.Name);
                            }
                            else
                            {
                                CodeBuilder.AppendFormat("this.{0}", sym.Name);
                            }
                            return;
                        }
                    }
                    else if (sym.Kind == SymbolKind.Method && sym.ContainingType == classInfo.SemanticInfo)
                    {
                        var    msym         = sym as IMethodSymbol;
                        string manglingName = NameMangling(msym);
                        var    mi           = new MethodInfo();
                        mi.Init(msym, node);
                        if (node.Parent is InvocationExpressionSyntax)
                        {
                            if (sym.IsStatic)
                            {
                                CodeBuilder.AppendFormat("{0}.{1}", classInfo.Key, manglingName);
                            }
                            else
                            {
                                CodeBuilder.AppendFormat("this:{0}", manglingName);
                            }
                        }
                        else
                        {
                            CodeBuilder.Append("(function(");
                            string paramsString = string.Join(", ", mi.ParamNames.ToArray());
                            CodeBuilder.Append(paramsString);
                            if (sym.IsStatic)
                            {
                                CodeBuilder.AppendFormat(") {0}{1}.{2}({3}); end)", msym.ReturnsVoid ? string.Empty : "return ", classInfo.Key, manglingName, paramsString);
                            }
                            else
                            {
                                CodeBuilder.AppendFormat(") {0}this:{1}({2}); end)", msym.ReturnsVoid ? string.Empty : "return ", manglingName, paramsString);
                            }
                        }
                        return;
                    }
                }
                else
                {
                    if (m_ObjectCreateStack.Count > 0)
                    {
                        ITypeSymbol symInfo = m_ObjectCreateStack.Peek();
                        if (null != symInfo)
                        {
                            var names = symInfo.GetMembers(name);
                            if (names.Length > 0)
                            {
                                CodeBuilder.AppendFormat("newobj.{0}", name);
                                return;
                            }
                        }
                    }
                    else
                    {
                        ReportIllegalSymbol(node, symbolInfo);
                    }
                }
            }
            CodeBuilder.Append(name);
        }
Пример #14
0
        public override void VisitSwitchStatement(SwitchStatementSyntax node)
        {
            MethodInfo mi = m_MethodInfoStack.Peek();

            mi.TryCatchUsingOrLoopSwitchStack.Push(false);

            string     varName = string.Format("__switch_{0}", GetSourcePosForVar(node));
            SwitchInfo si      = new SwitchInfo();

            si.SwitchVarName = varName;
            m_SwitchInfoStack.Push(si);

            CodeBuilder.AppendFormat("{0}local{{{1} = ", GetIndentString(), varName);
            IConversionExpression opd = null;
            var oper = m_Model.GetOperation(node) as ISwitchStatement;

            if (null != oper)
            {
                opd = oper.Value as IConversionExpression;
            }
            OutputExpressionSyntax(node.Expression, opd);
            CodeBuilder.AppendLine(";};");

            int ct = node.Sections.Count;
            SwitchSectionSyntax defaultSection = null;

            for (int i = 0; i < ct; ++i)
            {
                var section = node.Sections[i];
                int lct     = section.Labels.Count;
                for (int j = 0; j < lct; ++j)
                {
                    var label = section.Labels[j];
                    if (label is DefaultSwitchLabelSyntax)
                    {
                        defaultSection = section;
                        break;
                    }
                }
            }
            bool first = true;

            for (int i = 0; i < ct; ++i)
            {
                var section = node.Sections[i];
                if (section == defaultSection)
                {
                    continue;
                }
                ContinueInfo ci = new ContinueInfo();
                ci.Init(section);
                m_ContinueInfoStack.Push(ci);

                BreakAnalysis ba = new BreakAnalysis();
                ba.Visit(section);
                if (ba.BreakCount > 1)
                {
                    ci.IsIgnoreBreak = false;
                }
                else
                {
                    ci.IsIgnoreBreak = true;
                }

                CodeBuilder.AppendFormat("{0}{1} ", GetIndentString(), first ? "if(" : "}elseif(");
                int lct = section.Labels.Count;
                for (int j = 0; j < lct; ++j)
                {
                    var label = section.Labels[j] as CaseSwitchLabelSyntax;
                    if (null != label)
                    {
                        if (lct > 1)
                        {
                            CodeBuilder.Append("(");
                        }
                        CodeBuilder.AppendFormat("{0} == ", varName);
                        OutputExpressionSyntax(label.Value);
                        if (lct > 1)
                        {
                            CodeBuilder.Append(")");
                            if (j < lct - 1)
                            {
                                CodeBuilder.Append(" || ");
                            }
                        }
                    }
                }
                CodeBuilder.AppendLine(" ){");
                if (ba.BreakCount > 1)
                {
                    CodeBuilder.AppendFormat("{0}repeat{{", GetIndentString());
                    CodeBuilder.AppendLine();
                }
                ++m_Indent;

                int sct = section.Statements.Count;
                for (int j = 0; j < sct; ++j)
                {
                    var statement = section.Statements[j];
                    statement.Accept(this);
                }

                --m_Indent;
                if (ba.BreakCount > 1)
                {
                    CodeBuilder.AppendFormat("{0}}}until(0 != 0);", GetIndentString());
                    CodeBuilder.AppendLine();
                }

                m_ContinueInfoStack.Pop();
                first = false;
            }
            if (null != defaultSection)
            {
                ContinueInfo ci = new ContinueInfo();
                ci.Init(defaultSection);
                m_ContinueInfoStack.Push(ci);

                BreakAnalysis ba = new BreakAnalysis();
                ba.Visit(defaultSection);
                if (ba.BreakCount > 1)
                {
                    ci.IsIgnoreBreak = false;
                }
                else
                {
                    ci.IsIgnoreBreak = true;
                }
                if (ct > 1)
                {
                    CodeBuilder.AppendFormat("{0}}}else{{", GetIndentString());
                }
                else
                {
                    CodeBuilder.AppendFormat("{0}block{{", GetIndentString());
                }
                CodeBuilder.AppendLine();
                if (ba.BreakCount > 1)
                {
                    CodeBuilder.AppendFormat("{0}repeat{{", GetIndentString());
                    CodeBuilder.AppendLine();
                }
                ++m_Indent;

                int sct = defaultSection.Statements.Count;
                for (int j = 0; j < sct; ++j)
                {
                    var statement = defaultSection.Statements[j];
                    statement.Accept(this);
                }

                --m_Indent;
                if (ba.BreakCount > 1)
                {
                    CodeBuilder.AppendFormat("{0}}}until(0 != 0);", GetIndentString());
                    CodeBuilder.AppendLine();
                }
                CodeBuilder.AppendFormat("{0}}};", GetIndentString());
                CodeBuilder.AppendLine();

                m_ContinueInfoStack.Pop();
            }
            else if (ct > 0)
            {
                CodeBuilder.AppendFormat("{0}}};", GetIndentString());
                CodeBuilder.AppendLine();
            }

            m_SwitchInfoStack.Pop();
            mi.TryCatchUsingOrLoopSwitchStack.Pop();
        }
Пример #15
0
		private static void parseContinueStatement(CsStatement pStatement, CodeBuilder pSb, FactoryExpressionCreator pCreator) {
			//CsContinueStatement continueStatement = (CsContinueStatement)pStatement;

			pSb.Append("continue");
			pSb.AppendLine();
			pSb.AppendLine();
		}
Пример #16
0
 private static void parseBreakStatement(CsStatement pStatement, CodeBuilder pSb, FactoryExpressionCreator pCreator)
 {
     pSb.Append("break;");
     pSb.AppendLine();
     pSb.AppendLine();
 }
Пример #17
0
        public override void VisitInitializerExpression(InitializerExpressionSyntax node)
        {
            var oper = m_Model.GetOperation(node);

            if (null != oper)
            {
                bool isCollection        = node.IsKind(SyntaxKind.CollectionInitializerExpression);
                bool isObjectInitializer = node.IsKind(SyntaxKind.ObjectInitializerExpression);
                bool isArray             = node.IsKind(SyntaxKind.ArrayInitializerExpression);
                bool isComplex           = node.IsKind(SyntaxKind.ComplexElementInitializerExpression);
                if (isCollection)
                {
                    if (null != oper.Type)
                    {
                        bool isDictionary = IsImplementationOfSys(oper.Type, "IDictionary");
                        bool isList       = IsImplementationOfSys(oper.Type, "IList");
                        if (isDictionary)
                        {
                            CodeBuilder.Append("{");
                            var args = node.Expressions;
                            int ct   = args.Count;
                            for (int i = 0; i < ct; ++i)
                            {
                                var exp = args[i] as InitializerExpressionSyntax;
                                if (null != exp)
                                {
                                    CodeBuilder.Append("[tostring(");
                                    VisitToplevelExpression(exp.Expressions[0], string.Empty);
                                    CodeBuilder.Append(")] = ");
                                    VisitToplevelExpression(exp.Expressions[1], string.Empty);
                                }
                                else
                                {
                                    Log(args[i], "Dictionary init error !");
                                }
                                if (i < ct - 1)
                                {
                                    CodeBuilder.Append(", ");
                                }
                            }
                            CodeBuilder.Append("}");
                        }
                        else if (isList)
                        {
                            CodeBuilder.Append("{");
                            var args = node.Expressions;
                            int ct   = args.Count;
                            for (int i = 0; i < ct; ++i)
                            {
                                VisitExpressionSyntax(args[i]);
                                if (i < ct - 1)
                                {
                                    CodeBuilder.Append(", ");
                                }
                            }
                            CodeBuilder.Append("}");
                        }
                        else
                        {
                            CodeBuilder.Append("{");
                            var args = node.Expressions;
                            int ct   = args.Count;
                            for (int i = 0; i < ct; ++i)
                            {
                                VisitExpressionSyntax(args[i]);
                                if (i < ct - 1)
                                {
                                    CodeBuilder.Append(", ");
                                }
                            }
                            CodeBuilder.Append("}");
                        }
                    }
                    else
                    {
                        Log(node, "Can't find operation type ! operation info: {0}", oper.ToString());
                    }
                }
                else if (isComplex)
                {
                    CodeBuilder.Append("{");
                    var args = node.Expressions;
                    int ct   = args.Count;
                    for (int i = 0; i < ct; ++i)
                    {
                        VisitExpressionSyntax(args[i]);
                        if (i < ct - 1)
                        {
                            CodeBuilder.Append(", ");
                        }
                    }
                    CodeBuilder.Append("}");
                }
                else
                {
                    if (isArray)
                    {
                        CodeBuilder.Append("wraparray{");
                    }
                    var args = node.Expressions;
                    int ct   = args.Count;
                    for (int i = 0; i < ct; ++i)
                    {
                        var exp = args[i];
                        VisitToplevelExpression(exp, string.Empty);
                        if (i < ct - 1)
                        {
                            CodeBuilder.Append(", ");
                        }
                    }
                    if (isArray)
                    {
                        CodeBuilder.Append("}");
                    }
                }
            }
            else
            {
                Log(node, "Can't find operation info !");
            }
        }
        private void GeneratePropertyMapping(Property property)
        {
            bool isString    = property.SystemType == typeof(string);
            bool isByteArray = property.SystemType == typeof(byte[]);

            CodeBuilder.Append($"builder.Property(t => t.{property.PropertyName})");

            CodeBuilder.IncrementIndent();
            if (property.IsRequired)
            {
                CodeBuilder.AppendLine();
                CodeBuilder.Append(".IsRequired()");
            }

            if (property.IsRowVersion == true)
            {
                CodeBuilder.AppendLine();
                CodeBuilder.Append(".IsRowVersion()");
            }

            CodeBuilder.AppendLine();
            CodeBuilder.Append($".HasColumnName({property.ColumnName.ToLiteral()})");

            if (!string.IsNullOrEmpty(property.StoreType))
            {
                CodeBuilder.AppendLine();
                CodeBuilder.Append($".HasColumnType({property.StoreType.ToLiteral()})");
            }

            if ((isString || isByteArray) && property.Size > 0)
            {
                CodeBuilder.AppendLine();
                CodeBuilder.Append($".HasMaxLength({property.Size.Value.ToString(CultureInfo.InvariantCulture)})");
            }

            if (!string.IsNullOrEmpty(property.Default))
            {
                CodeBuilder.AppendLine();
                CodeBuilder.Append($".HasDefaultValueSql({property.Default.ToLiteral()})");
            }

            switch (property.ValueGenerated)
            {
            case ValueGenerated.OnAdd:
                CodeBuilder.AppendLine();
                CodeBuilder.Append(".ValueGeneratedOnAdd()");
                break;

            case ValueGenerated.OnAddOrUpdate:
                CodeBuilder.AppendLine();
                CodeBuilder.Append(".ValueGeneratedOnAddOrUpdate()");
                break;

            case ValueGenerated.OnUpdate:
                CodeBuilder.AppendLine();
                CodeBuilder.Append(".ValueGeneratedOnUpdate()");
                break;
            }
            CodeBuilder.DecrementIndent();

            CodeBuilder.AppendLine(";");
        }
        private void GenerateRelationshipMapping(Relationship relationship)
        {
            CodeBuilder.Append("builder.HasOne(t => t.");
            CodeBuilder.Append(relationship.PropertyName);
            CodeBuilder.Append(")");
            CodeBuilder.AppendLine();

            CodeBuilder.IncrementIndent();

            CodeBuilder.Append(relationship.PrimaryCardinality == Cardinality.Many
                ? ".WithMany(t => t."
                : ".WithOne(t => t.");

            CodeBuilder.Append(relationship.PrimaryPropertyName);
            CodeBuilder.Append(")");

            CodeBuilder.AppendLine();
            CodeBuilder.Append(".HasForeignKey");
            if (relationship.IsOneToOne)
            {
                CodeBuilder.Append("<");
                CodeBuilder.Append(_entity.EntityNamespace);
                CodeBuilder.Append(".");
                CodeBuilder.Append(_entity.EntityClass.ToSafeName());
                CodeBuilder.Append(">");
            }
            CodeBuilder.Append("(d => ");

            var  keys      = relationship.Properties;
            bool wroteLine = false;

            if (keys.Count == 1)
            {
                var propertyName = keys.First().PropertyName.ToSafeName();
                CodeBuilder.Append($"d.{propertyName}");
            }
            else
            {
                CodeBuilder.Append("new { ");
                foreach (var p in keys)
                {
                    if (wroteLine)
                    {
                        CodeBuilder.Append(", ");
                    }

                    CodeBuilder.Append($"d.{p.PropertyName}");
                    wroteLine = true;
                }
                CodeBuilder.Append("}");
            }
            CodeBuilder.Append(")");

            if (!string.IsNullOrEmpty(relationship.RelationshipName))
            {
                CodeBuilder.AppendLine();
                CodeBuilder.Append(".HasConstraintName(\"");
                CodeBuilder.Append(relationship.RelationshipName);
                CodeBuilder.Append("\")");
            }

            CodeBuilder.DecrementIndent();

            CodeBuilder.AppendLine(";");
        }
Пример #20
0
 private void OutputOperatorInvoke(InvocationInfo ii, SyntaxNode node)
 {
     if (SymbolTable.Instance.IsCs2LuaSymbol(ii.MethodSymbol))
     {
         CodeBuilder.AppendFormat("{0}.", ii.ClassKey);
         string manglingName = NameMangling(ii.MethodSymbol);
         CodeBuilder.Append(manglingName);
         CodeBuilder.Append("(");
         OutputArgumentList(ii.Args, ii.DefaultValueArgs, ii.GenericTypeArgs, ii.ArrayToParams, false, node, ii.ArgConversions.ToArray());
         CodeBuilder.Append(")");
     }
     else
     {
         string method = ii.MethodSymbol.Name;
         string luaOp  = string.Empty;
         if (SymbolTable.ForSlua)
         {
             //slua导出时把重载操作符导出成lua实例方法了,然后利用lua实例上支持的操作符元方法在运行时绑定到重载实现
             //这里把lua支持的操作符方法转成lua操作(可能比invokeexternoperator要快一些)
             if (method == "op_Addition")
             {
                 luaOp = "+";
             }
             else if (method == "op_Subtraction")
             {
                 luaOp = "-";
             }
             else if (method == "op_Multiply")
             {
                 luaOp = "*";
             }
             else if (method == "op_Division")
             {
                 luaOp = "/";
             }
             else if (method == "op_UnaryNegation")
             {
                 luaOp = "-";
             }
             else if (method == "op_UnaryPlus")
             {
                 luaOp = "+";
             }
             else if (method == "op_LessThan")
             {
                 luaOp = "<";
             }
             else if (method == "op_GreaterThan")
             {
                 luaOp = ">";
             }
             else if (method == "op_LessThanOrEqual")
             {
                 luaOp = "<=";
             }
             else if (method == "op_GreaterThanOrEqual")
             {
                 luaOp = ">= ";
             }
         }
         if (string.IsNullOrEmpty(luaOp))
         {
             CodeBuilder.AppendFormat("invokeexternoperator({0}, ", ii.GenericClassKey);
             CodeBuilder.AppendFormat("\"{0}\"", method);
             CodeBuilder.Append(", ");
             OutputArgumentList(ii.Args, ii.DefaultValueArgs, ii.GenericTypeArgs, ii.ArrayToParams, false, node, ii.ArgConversions.ToArray());
             CodeBuilder.Append(")");
         }
         else
         {
             if (ii.Args.Count == 1)
             {
                 if (luaOp == "-")
                 {
                     CodeBuilder.Append("(");
                     CodeBuilder.Append(luaOp);
                     CodeBuilder.Append(" ");
                     OutputExpressionSyntax(ii.Args[0], ii.ArgConversions[0]);
                     CodeBuilder.Append(")");
                 }
             }
             else if (ii.Args.Count == 2)
             {
                 CodeBuilder.Append("(");
                 OutputExpressionSyntax(ii.Args[0], ii.ArgConversions[0]);
                 CodeBuilder.Append(" ");
                 CodeBuilder.Append(luaOp);
                 CodeBuilder.Append(" ");
                 OutputExpressionSyntax(ii.Args[1], ii.ArgConversions[1]);
                 CodeBuilder.Append(")");
             }
         }
     }
 }
Пример #21
0
        private void OutputType(ITypeSymbol type, SyntaxNode node, ClassInfo ci, string errorTag)
        {
            if (null != type && type.TypeKind != TypeKind.Error)
            {
                if (type.TypeKind == TypeKind.TypeParameter)
                {
                    var typeParam = type as ITypeParameterSymbol;
                    if (typeParam.TypeParameterKind == TypeParameterKind.Type && !m_SkipGenericTypeDefine && null != m_GenericTypeInstance)
                    {
                        IMethodSymbol sym = FindClassMethodDeclaredSymbol(node);
                        if (null != sym)
                        {
                            var t = SymbolTable.Instance.FindTypeArgument(type);
                            if (t.TypeKind != TypeKind.TypeParameter)
                            {
                                CodeBuilder.Append(ClassInfo.GetFullName(t));
                                AddReferenceAndTryDeriveGenericTypeInstance(ci, t);
                            }
                            else
                            {
                                CodeBuilder.Append(t.Name);
                            }
                        }
                        else
                        {
                            ISymbol varSym = FindVariableDeclaredSymbol(node);
                            if (null != varSym)
                            {
                                var t = SymbolTable.Instance.FindTypeArgument(type);
                                if (t.TypeKind != TypeKind.TypeParameter)
                                {
                                    CodeBuilder.Append(ClassInfo.GetFullName(t));
                                    AddReferenceAndTryDeriveGenericTypeInstance(ci, t);
                                }
                                else
                                {
                                    CodeBuilder.Append(t.Name);
                                }
                            }
                            else
                            {
                                Log(node, "Can't find declaration for type param !", type.Name);
                            }
                        }
                    }
                    else
                    {
                        CodeBuilder.Append(type.Name);
                    }
                }
                else if (type.TypeKind == TypeKind.Array)
                {
                    var arrType = type as IArrayTypeSymbol;
                    CodeBuilder.Append(SymbolTable.PrefixExternClassName("System.Array"));
                }
                else
                {
                    var fullName = ClassInfo.GetFullName(type);
                    CodeBuilder.Append(fullName);

                    var namedType = type as INamedTypeSymbol;
                    if (null != namedType)
                    {
                        AddReferenceAndTryDeriveGenericTypeInstance(ci, namedType);
                    }
                }
            }
            else if (null != type)
            {
                CodeBuilder.Append("nil");
                ReportIllegalType(node, type);
            }
            else
            {
                CodeBuilder.Append("nil");
                Log(node, "Unknown {0} Type !", errorTag);
            }
        }
Пример #22
0
        private void OutputExpressionList(IList <ExpressionSyntax> args, IList <ArgDefaultValueInfo> defValArgs, bool arrayToParams, params IConversionExpression[] opds)
        {
            int ct = args.Count;

            for (int i = 0; i < ct; ++i)
            {
                var exp = args[i];
                var opd = opds.Length > i ? opds[i] : null;
                if (i > 0)
                {
                    if (null == exp && SymbolTable.ForXlua)
                    {
                    }
                    else
                    {
                        CodeBuilder.Append(", ");
                    }
                }
                //表达式对象为空表明这个是一个out实参,替换为__cs2lua_out
                if (null == exp)
                {
                    if (SymbolTable.ForXlua)
                    {
                        //xlua直接忽略out参数,仅作返回值
                    }
                    else
                    {
                        CodeBuilder.Append("__cs2lua_out");
                    }
                }
                else if (i < ct - 1)
                {
                    OutputExpressionSyntax(exp, opd);
                }
                else
                {
                    if (arrayToParams)
                    {
                        CodeBuilder.Append("unpack(");
                        OutputExpressionSyntax(exp, opd);
                        CodeBuilder.Append(")");
                    }
                    else
                    {
                        OutputExpressionSyntax(exp, opd);
                    }
                }
            }
            if (null != defValArgs)
            {
                int dvCt = defValArgs.Count;
                if (ct > 0 && dvCt > 0)
                {
                    CodeBuilder.Append(", ");
                }
                for (int i = 0; i < dvCt; ++i)
                {
                    var info = defValArgs[i];
                    OutputConstValue(info.Value, info.OperOrSym);
                    if (i < dvCt - 1)
                    {
                        CodeBuilder.Append(", ");
                    }
                }
            }
        }
Пример #23
0
		private static void parseBreakStatement(CsStatement pStatement, CodeBuilder pSb, FactoryExpressionCreator pCreator) {
			pSb.Append("break;");
			pSb.AppendLine();
			pSb.AppendLine();
		}
Пример #24
0
        public override void VisitVariableDeclarator(VariableDeclaratorSyntax node)
        {
            var ci       = m_ClassInfoStack.Peek();
            var localSym = m_Model.GetDeclaredSymbol(node) as ILocalSymbol;

            if (null != localSym && localSym.HasConstantValue)
            {
                if (null != node.Initializer)
                {
                    CodeBuilder.AppendFormat("{0}local({1}); {2}", GetIndentString(), node.Identifier.Text, node.Identifier.Text);
                }
                else
                {
                    CodeBuilder.AppendFormat("{0}local({1})", GetIndentString(), node.Identifier.Text);
                }
                CodeBuilder.Append(" = ");
                OutputConstValue(localSym.ConstantValue, localSym);
                CodeBuilder.AppendLine(";");
                return;
            }
            bool        dslToObject = false;
            ITypeSymbol type        = null;

            if (null != node.Initializer)
            {
                type = m_Model.GetTypeInfoEx(node.Initializer.Value).Type;
                if (null != localSym && null != localSym.Type && null != type)
                {
                    dslToObject = InvocationInfo.IsDslToObject(localSym.Type, type);
                }
            }
            VisitLocalVariableDeclarator(ci, node, dslToObject);
            if (null != node.Initializer)
            {
                var valSyntax = node.Initializer.Value;
                var rightType = m_Model.GetTypeInfoEx(valSyntax).Type;
                var rightOper = m_Model.GetOperationEx(valSyntax);
                if (null == rightType && null != rightOper)
                {
                    rightType = rightOper.Type;
                }
                ;
                bool needWrapStruct = NeedWrapStruct(valSyntax, rightType, rightOper, dslToObject);
                if (needWrapStruct)
                {
                    MarkNeedFuncInfo();
                    if (SymbolTable.Instance.IsCs2DslSymbol(type))
                    {
                        CodeBuilder.AppendFormat("{0}{1} = wrapstruct({2}, {3});", GetIndentString(), node.Identifier.Text, node.Identifier.Text, ClassInfo.GetFullName(type));
                        CodeBuilder.AppendLine();
                    }
                    else
                    {
                        string ns = ClassInfo.GetNamespaces(type);
                        if (ns != "System")
                        {
                            CodeBuilder.AppendFormat("{0}{1} = wrapexternstruct({2}, {3});", GetIndentString(), node.Identifier.Text, node.Identifier.Text, ClassInfo.GetFullName(type));
                            CodeBuilder.AppendLine();
                        }
                    }
                }
            }
        }
Пример #25
0
 public override void VisitLiteralExpression(LiteralExpressionSyntax node)
 {
     CodeBuilder.Append(node.Token.Text);
 }
Пример #26
0
        public override void VisitIdentifierName(IdentifierNameSyntax node)
        {
            string name = node.Identifier.Text;

            if (m_ClassInfoStack.Count > 0)
            {
                ClassInfo  classInfo  = m_ClassInfoStack.Peek();
                SymbolInfo symbolInfo = m_Model.GetSymbolInfoEx(node);
                var        sym        = symbolInfo.Symbol;
                if (null != sym)
                {
                    bool isExtern = !SymbolTable.Instance.IsCs2DslSymbol(sym);
                    if (sym.Kind == SymbolKind.NamedType || sym.Kind == SymbolKind.Namespace)
                    {
                        string fullName = ClassInfo.GetFullName(sym);
                        CodeBuilder.Append(fullName);

                        if (sym.Kind == SymbolKind.NamedType)
                        {
                            var namedType = sym as INamedTypeSymbol;
                            AddReferenceAndTryDeriveGenericTypeInstance(classInfo, namedType);
                        }
                        return;
                    }
                    else if (sym.Kind == SymbolKind.Field || sym.Kind == SymbolKind.Property || sym.Kind == SymbolKind.Event)
                    {
                        var    fsym     = sym as IFieldSymbol;
                        var    psym     = sym as IPropertySymbol;
                        string fullName = ClassInfo.GetFullName(sym.ContainingType);
                        if (sym.IsStatic)
                        {
                            if (isExtern && null != fsym && fsym.Type.IsValueType && !SymbolTable.IsBasicType(fsym.Type))
                            {
                                MarkNeedFuncInfo();
                                CodeBuilder.AppendFormat("getexternstaticstructmember(SymbolKind.{0}, {1}, \"{2}\")", SymbolTable.Instance.GetSymbolKind(sym), fullName, sym.Name);
                            }
                            else if (isExtern && null != psym && psym.Type.IsValueType && !SymbolTable.IsBasicType(psym.Type))
                            {
                                MarkNeedFuncInfo();
                                CodeBuilder.AppendFormat("getexternstaticstructmember(SymbolKind.{0}, {1}, \"{2}\")", SymbolTable.Instance.GetSymbolKind(sym), fullName, sym.Name);
                            }
                            else
                            {
                                string luaLibFunc;
                                if (null != fsym && SymbolTable.Instance.IsInvokeToLuaLibField(fsym, out luaLibFunc))
                                {
                                    OutputInvokeToLuaLib(true, luaLibFunc, fsym.Type, "SymbolKind.");
                                    CodeBuilder.AppendFormat("{0}, {1}, \"{2}\")", SymbolTable.Instance.GetSymbolKind(sym), fullName, sym.Name);
                                }
                                else if (null != psym && SymbolTable.Instance.IsInvokeToLuaLibProperty(psym, out luaLibFunc))
                                {
                                    OutputInvokeToLuaLib(true, luaLibFunc, psym.Type, "SymbolKind.");
                                    CodeBuilder.AppendFormat("{0}, {1}, \"{2}\")", SymbolTable.Instance.GetSymbolKind(sym), fullName, sym.Name);
                                }
                                else
                                {
                                    CodeBuilder.AppendFormat("{0}(SymbolKind.{1}, {2}, \"{3}\")", isExtern ? "getexternstatic" : "getstatic", SymbolTable.Instance.GetSymbolKind(sym), fullName, sym.Name);
                                }
                            }
                            return;
                        }
                        else if (IsNewObjMember(name))
                        {
                            if (isExtern && null != fsym && fsym.Type.IsValueType && !SymbolTable.IsBasicType(fsym.Type))
                            {
                                MarkNeedFuncInfo();
                                CodeBuilder.AppendFormat("getexterninstancestructmember(SymbolKind.{0}, newobj, {1}, \"{2}\")", SymbolTable.Instance.GetSymbolKind(sym), fullName, name);
                            }
                            else if (isExtern && null != psym && psym.Type.IsValueType && !SymbolTable.IsBasicType(psym.Type))
                            {
                                MarkNeedFuncInfo();
                                CodeBuilder.AppendFormat("getexterninstancestructmember(SymbolKind.{0}, newobj, {1}, \"{2}\")", SymbolTable.Instance.GetSymbolKind(sym), fullName, name);
                            }
                            else
                            {
                                string luaLibFunc;
                                if (null != fsym && SymbolTable.Instance.IsInvokeToLuaLibField(fsym, out luaLibFunc))
                                {
                                    OutputInvokeToLuaLib(true, luaLibFunc, fsym.Type, "SymbolKind.");
                                    CodeBuilder.AppendFormat("{0}, {1}, newobj, \"{2}\")", SymbolTable.Instance.GetSymbolKind(sym), fullName, sym.Name);
                                }
                                else if (null != psym && SymbolTable.Instance.IsInvokeToLuaLibProperty(psym, out luaLibFunc))
                                {
                                    OutputInvokeToLuaLib(true, luaLibFunc, psym.Type, "SymbolKind.");
                                    CodeBuilder.AppendFormat("{0}, {1}, newobj, \"{2}\")", SymbolTable.Instance.GetSymbolKind(sym), fullName, sym.Name);
                                }
                                else
                                {
                                    CodeBuilder.AppendFormat("{0}(SymbolKind.{1}, newobj, {2}, \"{3}\")", isExtern ? "getexterninstance" : "getinstance", SymbolTable.Instance.GetSymbolKind(sym), fullName, name);
                                }
                            }
                            return;
                        }
                        else if (sym.ContainingType == classInfo.SemanticInfo || sym.ContainingType == classInfo.SemanticInfo.OriginalDefinition || classInfo.IsInherit(sym.ContainingType))
                        {
                            if (isExtern && null != fsym && fsym.Type.IsValueType && !SymbolTable.IsBasicType(fsym.Type))
                            {
                                MarkNeedFuncInfo();
                                CodeBuilder.AppendFormat("getexterninstancestructmember(SymbolKind.{0}, this, {1}, \"{2}\")", SymbolTable.Instance.GetSymbolKind(sym), fullName, sym.Name);
                            }
                            else if (isExtern && null != psym && psym.Type.IsValueType && !SymbolTable.IsBasicType(psym.Type))
                            {
                                MarkNeedFuncInfo();
                                CodeBuilder.AppendFormat("getexterninstancestructmember(SymbolKind.{0}, this, {1}, \"{2}\")", SymbolTable.Instance.GetSymbolKind(sym), fullName, sym.Name);
                            }
                            else
                            {
                                string luaLibFunc;
                                if (null != fsym && SymbolTable.Instance.IsInvokeToLuaLibField(fsym, out luaLibFunc))
                                {
                                    OutputInvokeToLuaLib(true, luaLibFunc, fsym.Type, "SymbolKind.");
                                    CodeBuilder.AppendFormat("{0}, this, {1}, \"{2}\")", SymbolTable.Instance.GetSymbolKind(sym), fullName, sym.Name);
                                }
                                else if (null != psym && SymbolTable.Instance.IsInvokeToLuaLibProperty(psym, out luaLibFunc))
                                {
                                    OutputInvokeToLuaLib(true, luaLibFunc, psym.Type, "SymbolKind.");
                                    CodeBuilder.AppendFormat("{0}, this, {1}, \"{2}\")", SymbolTable.Instance.GetSymbolKind(sym), fullName, sym.Name);
                                }
                                else
                                {
                                    CodeBuilder.AppendFormat("{0}(SymbolKind.{1}, this, {2}, \"{3}\")", isExtern ? "getexterninstance" : "getinstance", SymbolTable.Instance.GetSymbolKind(sym), fullName, sym.Name);
                                }
                            }
                            return;
                        }
                    }
                    else if (sym.Kind == SymbolKind.Method)
                    {
                        var    msym         = sym as IMethodSymbol;
                        string manglingName = NameMangling(msym);
                        var    mi           = new MethodInfo();
                        mi.Init(msym, node);
                        string fullName = ClassInfo.GetFullName(sym.ContainingType);
                        if (sym.IsStatic && node.Parent is InvocationExpressionSyntax)
                        {
                            CodeBuilder.AppendFormat("{0}(SymbolKind.{1}, {2}, \"{3}\")", isExtern ? "getexternstatic" : "getstatic", SymbolTable.Instance.GetSymbolKind(sym), fullName, manglingName);
                            return;
                        }
                        else if (sym.ContainingType == classInfo.SemanticInfo || sym.ContainingType == classInfo.SemanticInfo.OriginalDefinition || classInfo.IsInherit(sym.ContainingType))
                        {
                            if (node.Parent is InvocationExpressionSyntax)
                            {
                                CodeBuilder.AppendFormat("{0}(SymbolKind.{1}, this, {2}, \"{3}\")", isExtern ? "getexterninstance" : "getinstance", SymbolTable.Instance.GetSymbolKind(sym), fullName, manglingName);
                            }
                            else
                            {
                                string srcPos        = GetSourcePosForVar(node);
                                string delegationKey = string.Format("{0}:{1}", fullName, manglingName);
                                if (msym.IsStatic)
                                {
                                    CodeBuilder.AppendFormat("builddelegation(\"{0}\", \"{1}\", {2}, {3}, {4})", srcPos, delegationKey, fullName, manglingName, "true");
                                }
                                else
                                {
                                    CodeBuilder.AppendFormat("builddelegation(\"{0}\", \"{1}\", this, {2}, {3})", srcPos, delegationKey, manglingName, "false");
                                }
                            }
                            return;
                        }
                    }
                }
                else
                {
                    string     fn;
                    SymbolKind kind;
                    if (IsNewObjMember(name, out fn, out kind))
                    {
                        CodeBuilder.AppendFormat("getinstance(SymbolKind.{0}, newobj, {1}, \"{2}\")", kind.ToString(), fn, name);
                        return;
                    }
                    ReportIllegalSymbol(node, symbolInfo);
                }
            }
            CodeBuilder.Append(name);
        }
Пример #27
0
        public override void VisitYieldStatement(YieldStatementSyntax node)
        {
            MethodInfo mi = m_MethodInfoStack.Peek();

            mi.ExistYield = true;

            if (node.ReturnOrBreakKeyword.Text == "return")
            {
                CodeBuilder.AppendFormat("{0}wrapyield(", GetIndentString());
                if (null != node.Expression)
                {
                    var oper = m_Model.GetOperation(node.Expression);
                    var type = oper.Type;
                    OutputExpressionSyntax(node.Expression);
                    if (null != type && (IsImplementationOfSys(type, "IEnumerable") || IsImplementationOfSys(type, "IEnumerator")))
                    {
                        CodeBuilder.Append(", true");
                    }
                    else
                    {
                        CodeBuilder.Append(", false");
                    }
                    if (null != type && IsSubclassOf(type, "UnityEngine.YieldInstruction"))
                    {
                        CodeBuilder.Append(", true");
                    }
                    else
                    {
                        CodeBuilder.Append(", false");
                    }
                }
                else
                {
                    CodeBuilder.Append("null, false, false");
                }
                CodeBuilder.Append(");");
                CodeBuilder.AppendLine();
            }
            else
            {
                bool isLastNode = IsLastNodeOfParent(node);
                if (!isLastNode)
                {
                    CodeBuilder.AppendFormat("{0}block{{", GetIndentString());
                    CodeBuilder.AppendLine();
                }

                CodeBuilder.AppendFormat("{0}return(null);", GetIndentString());
                CodeBuilder.AppendLine();

                if (IsLastNodeOfMethod(node))
                {
                    mi.ExistTopLevelReturn = true;
                }

                if (!isLastNode)
                {
                    CodeBuilder.AppendFormat("{0}}};", GetIndentString());
                    CodeBuilder.AppendLine();
                }
            }
        }
Пример #28
0
        public override void VisitSwitchStatement(SwitchStatementSyntax node)
        {
            string     varName = string.Format("__compiler_switch_{0}", node.GetLocation().GetLineSpan().StartLinePosition.Line);
            SwitchInfo si      = new SwitchInfo();

            si.SwitchVarName = varName;
            m_SwitchInfoStack.Push(si);

            CodeBuilder.AppendFormat("{0}local {1} = ", GetIndentString(), varName);
            IConversionExpression opd = null;
            var oper = m_Model.GetOperation(node) as ISwitchStatement;

            if (null != oper)
            {
                opd = oper.Value as IConversionExpression;
            }
            OutputExpressionSyntax(node.Expression, opd);
            CodeBuilder.AppendLine(";");

            int ct = node.Sections.Count;
            SwitchSectionSyntax defaultSection = null;

            for (int i = 0; i < ct; ++i)
            {
                var section = node.Sections[i];
                int lct     = section.Labels.Count;
                for (int j = 0; j < lct; ++j)
                {
                    var label = section.Labels[j];
                    if (label is DefaultSwitchLabelSyntax)
                    {
                        defaultSection = section;
                        break;
                    }
                }
            }
            for (int i = 0; i < ct; ++i)
            {
                var section = node.Sections[i];
                if (section == defaultSection)
                {
                    continue;
                }
                ContinueInfo ci = new ContinueInfo();
                ci.Init(section);
                m_ContinueInfoStack.Push(ci);

                BreakAnalysis ba = new BreakAnalysis();
                ba.Visit(section);
                if (ba.BreakCount > 1)
                {
                    ci.IsIgnoreBreak = false;
                }
                else
                {
                    ci.IsIgnoreBreak = true;
                }

                CodeBuilder.AppendFormat("{0}{1} ", GetIndentString(), i == 0 ? "if" : "elseif");
                int lct = section.Labels.Count;
                for (int j = 0; j < lct; ++j)
                {
                    var label = section.Labels[j] as CaseSwitchLabelSyntax;
                    if (null != label)
                    {
                        if (lct > 1)
                        {
                            CodeBuilder.Append("(");
                        }
                        CodeBuilder.AppendFormat("{0} == ", varName);
                        OutputExpressionSyntax(label.Value);
                        if (lct > 1)
                        {
                            CodeBuilder.Append(")");
                            if (j < lct - 1)
                            {
                                CodeBuilder.Append(" or ");
                            }
                        }
                    }
                }
                CodeBuilder.AppendLine(" then");
                if (ba.BreakCount > 1)
                {
                    CodeBuilder.AppendFormat("{0}repeat", GetIndentString());
                    CodeBuilder.AppendLine();
                }
                ++m_Indent;

                int sct = section.Statements.Count;
                for (int j = 0; j < sct; ++j)
                {
                    var statement = section.Statements[j];
                    statement.Accept(this);
                }

                --m_Indent;
                if (ba.BreakCount > 1)
                {
                    CodeBuilder.AppendFormat("{0}until 0 ~= 0;", GetIndentString());
                    CodeBuilder.AppendLine();
                }

                m_ContinueInfoStack.Pop();
            }
            if (null != defaultSection)
            {
                ContinueInfo ci = new ContinueInfo();
                ci.Init(defaultSection);
                m_ContinueInfoStack.Push(ci);

                BreakAnalysis ba = new BreakAnalysis();
                ba.Visit(defaultSection);
                if (ba.BreakCount > 1)
                {
                    ci.IsIgnoreBreak = false;
                }
                else
                {
                    ci.IsIgnoreBreak = true;
                }
                if (ct > 1)
                {
                    CodeBuilder.AppendFormat("{0}else", GetIndentString());
                }
                else
                {
                    CodeBuilder.AppendFormat("{0}do", GetIndentString());
                }
                CodeBuilder.AppendLine();
                if (ba.BreakCount > 1)
                {
                    CodeBuilder.AppendFormat("{0}repeat", GetIndentString());
                    CodeBuilder.AppendLine();
                }
                ++m_Indent;

                int sct = defaultSection.Statements.Count;
                for (int j = 0; j < sct; ++j)
                {
                    var statement = defaultSection.Statements[j];
                    statement.Accept(this);
                }

                --m_Indent;
                if (ba.BreakCount > 1)
                {
                    CodeBuilder.AppendFormat("{0}until 0 ~= 0;", GetIndentString());
                    CodeBuilder.AppendLine();
                }
                CodeBuilder.AppendFormat("{0}end;", GetIndentString());
                CodeBuilder.AppendLine();

                m_ContinueInfoStack.Pop();
            }
            else if (ct > 0)
            {
                CodeBuilder.AppendFormat("{0}end;", GetIndentString());
                CodeBuilder.AppendLine();
            }

            m_SwitchInfoStack.Pop();
        }
Пример #29
0
        public override void VisitConstructorDeclaration(ConstructorDeclarationSyntax node)
        {
            bool          isExportConstructor = false;
            var           ci      = m_ClassInfoStack.Peek();
            IMethodSymbol declSym = m_Model.GetDeclaredSymbol(node);

            if (null != declSym)
            {
                string require = ClassInfo.GetAttributeArgument <string>(declSym, "Cs2Lua.RequireAttribute", 0);
                if (!string.IsNullOrEmpty(require))
                {
                    m_SymbolTable.AddRequire(ci.Key, require);
                }
                if (ClassInfo.HasAttribute(declSym, "Cs2Lua.IgnoreAttribute"))
                {
                    return;
                }
                if (declSym.IsAbstract)
                {
                    return;
                }
                isExportConstructor = ClassInfo.HasAttribute(declSym, "Cs2Lua.ExportAttribute");
            }

            bool            generateBasicCtor  = false;
            bool            generateBasicCctor = false;
            ClassSymbolInfo csi;

            if (m_SymbolTable.ClassSymbols.TryGetValue(ci.Key, out csi))
            {
                generateBasicCtor  = csi.GenerateBasicCtor;
                generateBasicCctor = csi.GenerateBasicCctor;
            }

            bool isStatic = declSym.IsStatic;
            var  mi       = new MethodInfo();

            mi.Init(declSym, node);
            m_MethodInfoStack.Push(mi);

            string manglingName = NameMangling(declSym);

            if (isStatic)
            {
                ci.ExistStaticConstructor = true;
            }
            else
            {
                ci.ExistConstructor = true;

                if (isExportConstructor)
                {
                    ci.ExportConstructor     = manglingName;
                    ci.ExportConstructorInfo = mi;
                }
                else if (string.IsNullOrEmpty(ci.ExportConstructor))
                {
                    //有构造但还没有明确指定的导出构造,则使用第一次遇到的构造
                    ci.ExportConstructor     = manglingName;
                    ci.ExportConstructorInfo = mi;
                }
            }

            bool myselfDefinedBaseClass = ci.SemanticInfo.BaseType.ContainingAssembly == m_SymbolTable.AssemblySymbol;

            CodeBuilder.AppendFormat("{0}{1} = function({2}", GetIndentString(), manglingName, isStatic ? string.Empty : "this");
            if (mi.ParamNames.Count > 0)
            {
                if (!isStatic)
                {
                    CodeBuilder.Append(", ");
                }
                CodeBuilder.Append(string.Join(", ", mi.ParamNames.ToArray()));
            }
            CodeBuilder.Append(")");
            CodeBuilder.AppendLine();
            ++m_Indent;
            if (mi.ValueParams.Count > 0)
            {
                OutputWrapValueParams(CodeBuilder, mi);
            }
            if (!string.IsNullOrEmpty(mi.OriginalParamsName))
            {
                if (mi.ParamsIsValueType)
                {
                    CodeBuilder.AppendFormat("{0}local {1} = wrapvaluetypearray{{...}};", GetIndentString(), mi.OriginalParamsName);
                }
                else if (mi.ParamsIsExternValueType)
                {
                    CodeBuilder.AppendFormat("{0}local {1} = wrapexternvaluetypearray{{...}};", GetIndentString(), mi.OriginalParamsName);
                }
                else
                {
                    CodeBuilder.AppendFormat("{0}local {1} = wraparray{{...}};", GetIndentString(), mi.OriginalParamsName);
                }
                CodeBuilder.AppendLine();
            }
            foreach (string name in mi.OutParamNames)
            {
                CodeBuilder.AppendFormat("{0}local {1} = nil;", GetIndentString(), name);
                CodeBuilder.AppendLine();
            }
            //首先执行初始化列表
            var init = node.Initializer;

            if (null != init)
            {
                var    oper          = m_Model.GetOperation(init) as IInvocationExpression;
                string manglingName2 = NameMangling(oper.TargetMethod);
                if (init.ThisOrBaseKeyword.Text == "this")
                {
                    CodeBuilder.AppendFormat("{0}this:{1}(", GetIndentString(), manglingName2);
                }
                else if (init.ThisOrBaseKeyword.Text == "base")
                {
                    CodeBuilder.AppendFormat("{0}this.base.{1}(this", GetIndentString(), manglingName2);
                    if (init.ArgumentList.Arguments.Count > 0)
                    {
                        CodeBuilder.Append(", ");
                    }
                }
                VisitArgumentList(init.ArgumentList);
                CodeBuilder.AppendLine(");");
            }
            //再执行构造函数内容(字段初始化部分)
            if (isStatic)
            {
                if (!string.IsNullOrEmpty(ci.BaseKey) && myselfDefinedBaseClass)
                {
                    CodeBuilder.AppendFormat("{0}{1}.cctor();", GetIndentString(), ci.BaseKey);
                    CodeBuilder.AppendLine();
                }
                if (generateBasicCctor)
                {
                    CodeBuilder.AppendFormat("{0}{1}.__cctor();", GetIndentString(), ci.Key);
                    CodeBuilder.AppendLine();
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(ci.BaseKey) && !ClassInfo.IsBaseInitializerCalled(node, m_Model) && myselfDefinedBaseClass)
                {
                    //如果当前构造没有调父类构造并且委托的其它构造也没有调父类构造,则调用默认构造。
                    CodeBuilder.AppendFormat("{0}this.base.ctor(this);", GetIndentString());
                    CodeBuilder.AppendLine();
                }
                if (generateBasicCtor)
                {
                    CodeBuilder.AppendFormat("{0}this:__ctor({1});", GetIndentString(), string.Join(", ", mi.GenericTypeTypeParamNames.ToArray()));
                    CodeBuilder.AppendLine();
                }
            }
            //再执行构造函数内容(构造函数部分)
            if (null != node.Body)
            {
                VisitBlock(node.Body);
            }
            if (!mi.ExistTopLevelReturn)
            {
                if (mi.ReturnParamNames.Count > 0)
                {
                    CodeBuilder.AppendFormat("{0}return this, {1};", GetIndentString(), string.Join(", ", mi.ReturnParamNames));
                    CodeBuilder.AppendLine();
                }
                else if (!isStatic)
                {
                    CodeBuilder.AppendFormat("{0}return this;", GetIndentString());
                    CodeBuilder.AppendLine();
                }
            }
            --m_Indent;
            CodeBuilder.AppendFormat("{0}end,", GetIndentString());
            CodeBuilder.AppendLine();
            m_MethodInfoStack.Pop();
        }
Пример #30
0
        public override void VisitEventDeclaration(EventDeclarationSyntax node)
        {
            var          ci      = m_ClassInfoStack.Peek();
            IEventSymbol declSym = m_Model.GetDeclaredSymbol(node);

            if (null != declSym)
            {
                string require = ClassInfo.GetAttributeArgument <string>(declSym, "Cs2Lua.RequireAttribute", 0);
                if (!string.IsNullOrEmpty(require))
                {
                    m_SymbolTable.AddRequire(ci.Key, require);
                }
                if (ClassInfo.HasAttribute(declSym, "Cs2Lua.IgnoreAttribute"))
                {
                    return;
                }
                if (declSym.IsAbstract)
                {
                    return;
                }
            }

            StringBuilder curBuilder = ci.CurrentCodeBuilder;

            if (declSym.IsStatic)
            {
                ci.CurrentCodeBuilder = ci.StaticFunctionCodeBuilder;
            }
            else
            {
                ci.CurrentCodeBuilder = ci.InstanceFunctionCodeBuilder;
            }
            foreach (var accessor in node.AccessorList.Accessors)
            {
                var sym = m_Model.GetDeclaredSymbol(accessor);
                if (null != sym)
                {
                    var mi = new MethodInfo();
                    mi.Init(sym, accessor);
                    m_MethodInfoStack.Push(mi);

                    string manglingName = NameMangling(sym);
                    string keyword      = accessor.Keyword.Text;
                    string paramStr     = string.Join(", ", mi.ParamNames.ToArray());
                    if (!declSym.IsStatic)
                    {
                        if (string.IsNullOrEmpty(paramStr))
                        {
                            paramStr = "this";
                        }
                        else
                        {
                            paramStr = "this, " + paramStr;
                        }
                    }
                    CodeBuilder.AppendFormat("{0}{1} = function({2})", GetIndentString(), manglingName, paramStr);
                    CodeBuilder.AppendLine();
                    ++m_Indent;
                    bool   isStatic    = declSym.IsStatic;
                    string luaModule   = ClassInfo.GetAttributeArgument <string>(sym, "Cs2Lua.TranslateToAttribute", 0);
                    string luaFuncName = ClassInfo.GetAttributeArgument <string>(sym, "Cs2Lua.TranslateToAttribute", 1);
                    if (!string.IsNullOrEmpty(luaModule) || !string.IsNullOrEmpty(luaFuncName))
                    {
                        if (!string.IsNullOrEmpty(luaModule))
                        {
                            m_SymbolTable.AddRequire(ci.Key, luaModule);
                        }
                        if (sym.ReturnsVoid && mi.ReturnParamNames.Count <= 0)
                        {
                            CodeBuilder.AppendFormat("{0}{1}({2}", GetIndentString(), luaFuncName, isStatic ? string.Empty : "this");
                        }
                        else
                        {
                            CodeBuilder.AppendFormat("{0}return {1}({2}", GetIndentString(), luaFuncName, isStatic ? string.Empty : "this");
                        }
                        if (mi.ParamNames.Count > 0)
                        {
                            if (!isStatic)
                            {
                                CodeBuilder.Append(", ");
                            }
                            CodeBuilder.Append(string.Join(", ", mi.ParamNames.ToArray()));
                        }
                        CodeBuilder.AppendLine(");");
                    }
                    else if (null != accessor.Body)
                    {
                        if (mi.ValueParams.Count > 0)
                        {
                            OutputWrapValueParams(CodeBuilder, mi);
                        }
                        VisitBlock(accessor.Body);
                    }
                    --m_Indent;
                    CodeBuilder.AppendFormat("{0}end,", GetIndentString());
                    CodeBuilder.AppendLine();

                    m_MethodInfoStack.Pop();
                }
            }
            ci.CurrentCodeBuilder = curBuilder;

            CodeBuilder.AppendFormat("{0}{1} = {{", GetIndentString(), SymbolTable.GetEventName(declSym));
            CodeBuilder.AppendLine();
            ++m_Indent;
            foreach (var accessor in node.AccessorList.Accessors)
            {
                var sym = m_Model.GetDeclaredSymbol(accessor);
                if (null != sym)
                {
                    string manglingName = NameMangling(sym);
                    string keyword      = accessor.Keyword.Text;
                    CodeBuilder.AppendFormat("{0}{1} = {2}.{3},", GetIndentString(), keyword, declSym.IsStatic ? "static_methods" : "instance_methods", manglingName);
                    CodeBuilder.AppendLine();
                }
            }
            --m_Indent;
            CodeBuilder.AppendFormat("{0}", GetIndentString());
            CodeBuilder.AppendLine("},");
        }
Пример #31
0
		public static void Parse(CsClass pCsClass, CodeBuilder pBuilder, FactoryExpressionCreator pCreator) {
			ExtensionName = null;

			StringBuilder sb = new StringBuilder();
			CodeBuilder privateClasses = new CodeBuilder();

			TheClass myClass = TheClassFactory.Get(pCsClass, pCreator);

			IsMainClass = Helpers.HasAttribute(pCsClass.attributes, "JsMainClassAttribute");
			bool isResource = Helpers.HasAttribute(pCsClass.attributes, "JsEmbedAttribute");
			IsExtension = Helpers.HasAttribute(pCsClass.attributes, "JsExtensionAttribute");

			if (IsMainClass) {
				JsNamespaceParser.MainClassName = myClass.FullName;
				AttributeItem vals = Helpers.GetAttributeValue(pCsClass.attributes, "JsMainClassAttribute", pCreator)[0];
				sb.AppendFormat(@"[SWF(width=""{0}"", height=""{1}"", frameRate=""{2}"", backgroundColor=""{3}"")]",
				                vals.Parameters[0],
								vals.Parameters[1],
								vals.Parameters[2],
								vals.Parameters[3]
					);
				sb.AppendLine();
				sb.Append("\t");
			}

			if (isResource) {
				AttributeItem vals = Helpers.GetAttributeValue(pCsClass.attributes, "JsEmbedAttribute", pCreator)[0];

				string path = vals.Parameters[0] as String;
				if (!string.IsNullOrEmpty(path)) {
					path = Path.Combine(Project.Root, path);
					string ex = Path.GetExtension(path).Substring(1);
					string mimeType;

					if (vals.NamedArguments.ContainsKey("mimeType")) {
						mimeType = vals.NamedArguments["mimeType"].Value;

					} else {
						switch (ex) {
							case @"gif":
							case @"png":
							case @"jpg":
							case @"jpeg":
							case @"svg":
								mimeType = "image/" + ex;
								break;

							case @"mp3":
								mimeType = @"audio/mpeg";
								break;

							case @"swf":
								mimeType = @"application/x-shockwave-flash";
								break;

							case @"ttf":
							case @"otf":
								mimeType = @"application/x-font";
								break;

							default:
								mimeType = @"application/octet-stream";
								break;
						}
					}

					StringBuilder addParams = new StringBuilder();
					foreach (var item in vals.NamedArguments.Where(pItem => !pItem.Key.Equals("mimeType"))) {
						addParams.AppendFormat(@", {0}=""{1}""", item.Key, item.Value.Value);
					}

					sb.AppendFormat(@"[Embed(source=""{0}"", mimeType=""{1}""{2})]",
									path.Replace("\\", "\\\\"),
									mimeType,
									addParams
					);

					sb.AppendLine();
					sb.Append("\t");

				}
			}

			if (!IsExtension) {
				sb.AppendFormat("{1}class {0}",
							myClass.Name,
							JsHelpers.ConvertModifiers(myClass.Modifiers, _notValidClassMod));

				if (myClass.Extends.Count != 0) {
					sb.AppendFormat(" extends {0}", JsHelpers.Convert(myClass.Extends[0]));
				}

				if (myClass.Implements.Count != 0) {
					sb.Append(" implements ");
					foreach (string s in myClass.Implements) {
						sb.Append(JsHelpers.Convert(s));
						sb.Append(", ");
					}

					sb.Remove(sb.Length - 2, 2);
				}

				sb.Append(" {");
				sb.AppendLine();

				pBuilder.Append(sb.ToString());
				pBuilder.AppendLineAndIndent();
			}

			if (IsMainClass) {
				ImportStatementList.List.Add("flash.events.Event");
				pBuilder.AppendFormat(
									  @"public function {0}() {{
			if (stage) $ctor();
			else addEventListener(Event.ADDED_TO_STAGE, __loaded);
		}}

		private function __loaded(e:Event = null):void {{
			removeEventListener(Event.ADDED_TO_STAGE, __loaded);
			$ctor();
		}}
",
				                      myClass.Name);
				pBuilder.AppendLine();
			}

			if (pCsClass.member_declarations != null) {
				if (!myClass.IsPrivate)
					ImportStatementList.List.Add(myClass.NameSpace+".*");

				foreach (CsNode memberDeclaration in pCsClass.member_declarations) {
					if (memberDeclaration is CsConstructor) {
						MethodParser.Parse(myClass.GetConstructor((CsConstructor)memberDeclaration), pBuilder, pCreator);

					} else if (memberDeclaration is CsMethod) {
						MethodParser.Parse(myClass.GetMethod((CsMethod)memberDeclaration), pBuilder, pCreator);
						if (IsExtension && string.IsNullOrEmpty(ExtensionName)) {
							ExtensionName = ((CsMethod)memberDeclaration).identifier.identifier;
						}

					} else if (memberDeclaration is CsIndexer) {
						IndexerParser.Parse(myClass.GetIndexer((CsIndexer)memberDeclaration), pBuilder, pCreator);

					} else if (memberDeclaration is CsVariableDeclaration) {
						VariableParser.Parse(myClass.GetVariable((CsVariableDeclaration)memberDeclaration), pBuilder);

					} else if (memberDeclaration is CsConstantDeclaration) {
						ConstantParser.Parse(myClass.GetConstant((CsConstantDeclaration)memberDeclaration), pBuilder);

					} else if (memberDeclaration is CsDelegate) {
						DelegateParser.Parse(myClass.GetDelegate((CsDelegate)memberDeclaration), pBuilder);

					} else if (memberDeclaration is CsEvent) {
						EventParser.Parse(myClass.GetEvent(((CsEvent)memberDeclaration).declarators.First.Value.identifier.identifier), pBuilder);

					} else if (memberDeclaration is CsProperty) {
						PropertyParser.Parse(myClass.GetProperty((CsProperty)memberDeclaration), pBuilder, pCreator);

					} else if (memberDeclaration is CsClass) {
						Parse((CsClass)memberDeclaration, privateClasses, pCreator);

					} else {
						throw new NotSupportedException();
					}
				}
			}

			string imports = getImports();
			pBuilder.Replace(IMPORT_MARKER, imports);

			pBuilder.AppendLineAndUnindent("}");

			if (IsExtension) {
				return;
			}

			if (!myClass.IsPrivate) {
				pBuilder.AppendLineAndUnindent("}");
			}

			if (privateClasses.Length == 0) {
				return;
			}

			pBuilder.AppendLine();
			pBuilder.Append(JsNamespaceParser.Using);
			pBuilder.AppendLine(imports);
			pBuilder.Append(privateClasses);
		}
Пример #32
0
        public override void VisitConditionalAccessExpression(ConditionalAccessExpressionSyntax node)
        {
            CodeBuilder.Append("condaccess(");
            VisitExpressionSyntax(node.Expression);
            CodeBuilder.Append(", ");
            var elementBinding = node.WhenNotNull as ElementBindingExpressionSyntax;

            if (null != elementBinding)
            {
                var oper    = m_Model.GetOperation(node.WhenNotNull);
                var symInfo = m_Model.GetSymbolInfo(node.WhenNotNull);
                var sym     = symInfo.Symbol;
                var psym    = sym as IPropertySymbol;
                if (null != sym && sym.IsStatic)
                {
                    var ci = m_ClassInfoStack.Peek();
                    AddReferenceAndTryDeriveGenericTypeInstance(ci, sym);
                }
                if (null != psym && psym.IsIndexer)
                {
                    CodeBuilder.Append("(function() return ");
                    CodeBuilder.AppendFormat("get{0}{1}indexer(", psym.ContainingAssembly == m_SymbolTable.AssemblySymbol ? string.Empty : "extern", psym.IsStatic ? "static" : "instance");
                    if (psym.IsStatic)
                    {
                        string fullName = ClassInfo.GetFullName(psym.ContainingType);
                        CodeBuilder.Append(fullName);
                    }
                    else
                    {
                        VisitExpressionSyntax(node.Expression);
                    }
                    CodeBuilder.Append(", ");
                    if (!psym.IsStatic)
                    {
                        string fnOfIntf = "nil";
                        CheckExplicitInterfaceAccess(psym.GetMethod, ref fnOfIntf);
                        CodeBuilder.AppendFormat("{0}, ", fnOfIntf);
                    }
                    string manglingName = NameMangling(psym.GetMethod);
                    CodeBuilder.AppendFormat("\"{0}\", ", manglingName);
                    InvocationInfo          ii   = new InvocationInfo();
                    List <ExpressionSyntax> args = new List <ExpressionSyntax> {
                        node.WhenNotNull
                    };
                    ii.Init(psym.GetMethod, args, m_Model);
                    OutputArgumentList(ii.Args, ii.DefaultValueArgs, ii.GenericTypeArgs, ii.ArrayToParams, false, elementBinding);
                    CodeBuilder.Append(")");
                    CodeBuilder.Append("; end)");
                }
                else if (oper.Kind == OperationKind.ArrayElementReferenceExpression)
                {
                    CodeBuilder.Append("(function() return ");
                    VisitExpressionSyntax(node.Expression);
                    CodeBuilder.Append("[");
                    VisitExpressionSyntax(node.WhenNotNull);
                    CodeBuilder.Append(" + 1]");
                    CodeBuilder.Append("; end)");
                }
                else if (null != sym)
                {
                    CodeBuilder.Append("(function() return ");
                    CodeBuilder.AppendFormat("get{0}{1}element(", sym.ContainingAssembly == m_SymbolTable.AssemblySymbol ? string.Empty : "extern", sym.IsStatic ? "static" : "instance");
                    if (sym.IsStatic)
                    {
                        string fullName = ClassInfo.GetFullName(sym.ContainingType);
                        CodeBuilder.Append(fullName);
                    }
                    else
                    {
                        VisitExpressionSyntax(node.Expression);
                    }
                    CodeBuilder.Append(", ");
                    CodeBuilder.AppendFormat("\"{0}\", ", sym.Name);
                    VisitExpressionSyntax(node.WhenNotNull);
                    CodeBuilder.Append(")");
                    CodeBuilder.Append("; end)");
                }
                else
                {
                    ReportIllegalSymbol(node, symInfo);
                }
            }
            else
            {
                CodeBuilder.Append("(function() return ");
                VisitExpressionSyntax(node.Expression);
                VisitExpressionSyntax(node.WhenNotNull);
                CodeBuilder.Append("; end)");
            }
            CodeBuilder.Append(")");
        }
Пример #33
0
		public static void ParseNode(CsNode pNode, CodeBuilder pSb, FactoryExpressionCreator pCreator) {
			CsBlock block = pNode as CsBlock;
			if (block != null) {
				Parse(block, pSb, pCreator);
				return;
			}

			CsStatement statement = pNode as CsStatement;
			if (statement != null) {
				pSb.Indent();
				parseStatement(statement, pSb, pCreator);
				pSb.Unindent();
				return;
			}

			CsExpression expression = pNode as CsExpression;
			if (expression != null) {
				Expression ex = pCreator.Parse(pNode as CsExpression);
				pSb.Append(ex.Value + ";");
				pSb.AppendLine();
				return;
			}

			throw new Exception();
		}
Пример #34
0
		private static void parseLocalVariable(CsStatement pStatement, CodeBuilder pSb, FactoryExpressionCreator pCreator) {
			CsDeclarationStatement declarationStatement = (CsDeclarationStatement)pStatement;

			CsLocalVariableDeclaration localVariableDeclaration = declarationStatement.declaration as CsLocalVariableDeclaration;
			if (localVariableDeclaration == null) {
				parseLocalConstantDeclaration(pStatement, pSb, pCreator);
				return;
			}

			foreach (var declarator in localVariableDeclaration.declarators) {
				StringBuilder sb = new StringBuilder();

				sb.AppendFormat("var {0}:{1}",
					declarator.identifier.identifier,
					As3Helpers.Convert(Helpers.GetType(localVariableDeclaration.type))
				);

				if (declarator.initializer == null) {
					sb.Append(";");

				} else {
					sb.AppendFormat(" = {0};", parseNode(declarator.initializer, pCreator));
				}

				pSb.Append(sb.ToString());
				pSb.AppendLine();
			}
		}
Пример #35
0
 public override void VisitDefaultExpression(DefaultExpressionSyntax node)
 {
     CodeBuilder.Append("nil");
 }
Пример #36
0
        public override void VisitMemberAccessExpression(MemberAccessExpressionSyntax node)
        {
            SymbolInfo symInfo = m_Model.GetSymbolInfo(node);
            var        sym     = symInfo.Symbol;

            string className = string.Empty;

            if (null != sym && sym.IsStatic && null != sym.ContainingType)
            {
                className = ClassInfo.GetFullName(sym.ContainingType);
            }

            if (null != sym)
            {
                if (sym.IsStatic)
                {
                    var ci = m_ClassInfoStack.Peek();
                    AddReferenceAndTryDeriveGenericTypeInstance(ci, sym);
                }
            }
            else
            {
                ReportIllegalSymbol(node, symInfo);
            }
            if (node.Parent is InvocationExpressionSyntax)
            {
                var    msym         = sym as IMethodSymbol;
                string manglingName = NameMangling(msym);
                if (string.IsNullOrEmpty(className))
                {
                    VisitExpressionSyntax(node.Expression);
                    CodeBuilder.Append(":");
                }
                else
                {
                    CodeBuilder.Append(className);
                    CodeBuilder.Append(".");
                }
                CodeBuilder.Append(manglingName);
            }
            else
            {
                var msym = sym as IMethodSymbol;
                if (null != msym)
                {
                    string manglingName = NameMangling(msym);
                    var    mi           = new MethodInfo();
                    mi.Init(msym, node);

                    CodeBuilder.Append("(function(");
                    string paramsString = string.Join(", ", mi.ParamNames.ToArray());
                    CodeBuilder.Append(paramsString);
                    CodeBuilder.Append(") ");
                    if (!msym.ReturnsVoid)
                    {
                        CodeBuilder.Append("return ");
                    }
                    if (string.IsNullOrEmpty(className))
                    {
                        VisitExpressionSyntax(node.Expression);
                        CodeBuilder.Append(":");
                    }
                    else
                    {
                        CodeBuilder.Append(className);
                        CodeBuilder.Append(".");
                    }
                    CodeBuilder.Append(manglingName);
                    CodeBuilder.AppendFormat("({0}) end)", paramsString);
                }
                else
                {
                    var    psym     = sym as IPropertySymbol;
                    string fnOfIntf = string.Empty;
                    string mname    = string.Empty;
                    bool   propExplicitImplementInterface = false;
                    bool   propForBasicValueType          = false;
                    if (null != psym)
                    {
                        if (!psym.IsStatic)
                        {
                            propExplicitImplementInterface = CheckExplicitInterfaceAccess(psym, ref fnOfIntf, ref mname);
                            propForBasicValueType          = SymbolTable.IsBasicValueProperty(psym);
                        }
                    }
                    if (propExplicitImplementInterface)
                    {
                        CodeBuilder.AppendFormat("getwithinterface(");
                        VisitExpressionSyntax(node.Expression);
                        CodeBuilder.AppendFormat(", \"{0}\", \"{1}\")", fnOfIntf, mname);
                    }
                    else if (propForBasicValueType)
                    {
                        string pname = psym.Name;
                        CodeBuilder.AppendFormat("getforbasicvalue(");
                        VisitExpressionSyntax(node.Expression);
                        CodeBuilder.AppendFormat(", \"{0}\", \"{1}\")", className, pname);
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(className))
                        {
                            VisitExpressionSyntax(node.Expression);
                        }
                        else
                        {
                            CodeBuilder.Append(className);
                        }
                        CodeBuilder.Append(node.OperatorToken.Text);
                        CodeBuilder.Append(node.Name.Identifier.Text);
                    }
                }
            }
        }
Пример #37
0
        public override void VisitIndexerDeclaration(IndexerDeclarationSyntax node)
        {
            var ci      = m_ClassInfoStack.Peek();
            var declSym = m_Model.GetDeclaredSymbol(node);

            if (null != declSym)
            {
                string require = ClassInfo.GetAttributeArgument <string>(declSym, "Cs2Lua.RequireAttribute", 0);
                if (!string.IsNullOrEmpty(require))
                {
                    m_SymbolTable.AddRequire(ci.Key, require);
                }
                if (ClassInfo.HasAttribute(declSym, "Cs2Lua.IgnoreAttribute"))
                {
                    return;
                }
                if (declSym.IsAbstract)
                {
                    return;
                }
            }

            StringBuilder currentBuilder = ci.CurrentCodeBuilder;

            if (declSym.IsStatic)
            {
                ci.CurrentCodeBuilder = ci.StaticFunctionCodeBuilder;
            }
            else
            {
                ci.CurrentCodeBuilder = ci.InstanceFunctionCodeBuilder;
            }

            foreach (var accessor in node.AccessorList.Accessors)
            {
                var sym = m_Model.GetDeclaredSymbol(accessor);
                if (null != sym)
                {
                    var mi = new MethodInfo();
                    mi.Init(sym, accessor);
                    m_MethodInfoStack.Push(mi);

                    string manglingName = NameMangling(sym);
                    string keyword      = accessor.Keyword.Text;
                    CodeBuilder.AppendFormat("{0}{1} = function(this, {2})", GetIndentString(), manglingName, string.Join(", ", mi.ParamNames.ToArray()));
                    CodeBuilder.AppendLine();
                    ++m_Indent;
                    bool   isStatic    = declSym.IsStatic;
                    string luaModule   = ClassInfo.GetAttributeArgument <string>(sym, "Cs2Lua.TranslateToAttribute", 0);
                    string luaFuncName = ClassInfo.GetAttributeArgument <string>(sym, "Cs2Lua.TranslateToAttribute", 1);
                    if (!string.IsNullOrEmpty(luaModule) || !string.IsNullOrEmpty(luaFuncName))
                    {
                        if (!string.IsNullOrEmpty(luaModule))
                        {
                            m_SymbolTable.AddRequire(ci.Key, luaModule);
                        }
                        if (sym.ReturnsVoid && mi.ReturnParamNames.Count <= 0)
                        {
                            CodeBuilder.AppendFormat("{0}{1}({2}", GetIndentString(), luaFuncName, isStatic ? string.Empty : "this");
                        }
                        else
                        {
                            CodeBuilder.AppendFormat("{0}return {1}({2}", GetIndentString(), luaFuncName, isStatic ? string.Empty : "this");
                        }
                        if (mi.ParamNames.Count > 0)
                        {
                            if (!isStatic)
                            {
                                CodeBuilder.Append(", ");
                            }
                            CodeBuilder.Append(string.Join(", ", mi.ParamNames.ToArray()));
                        }
                        CodeBuilder.AppendLine(");");
                    }
                    else if (null != accessor.Body)
                    {
                        if (mi.ValueParams.Count > 0)
                        {
                            OutputWrapValueParams(CodeBuilder, mi);
                        }
                        if (!string.IsNullOrEmpty(mi.OriginalParamsName))
                        {
                            if (keyword == "get")
                            {
                                if (mi.ParamsIsValueType)
                                {
                                    CodeBuilder.AppendFormat("{0}local {1} = wrapvaluetypearray{{...}};", GetIndentString(), mi.OriginalParamsName);
                                }
                                else if (mi.ParamsIsExternValueType)
                                {
                                    CodeBuilder.AppendFormat("{0}local {1} = wrapexternvaluetypearray{{...}};", GetIndentString(), mi.OriginalParamsName);
                                }
                                else
                                {
                                    CodeBuilder.AppendFormat("{0}local {1} = wraparray{{...}};", GetIndentString(), mi.OriginalParamsName);
                                }
                                CodeBuilder.AppendLine();
                            }
                            else
                            {
                                CodeBuilder.AppendFormat("{0}local {1} = {{...}};", GetIndentString(), mi.OriginalParamsName);
                                CodeBuilder.AppendLine();
                                CodeBuilder.AppendFormat("{0}local value = table.remove({1});", GetIndentString(), mi.OriginalParamsName);
                                CodeBuilder.AppendLine();
                                if (mi.ParamsIsValueType)
                                {
                                    CodeBuilder.AppendFormat("{0}{1} = wrapvaluetypearray({2});", GetIndentString(), mi.OriginalParamsName, mi.OriginalParamsName);
                                }
                                else if (mi.ParamsIsExternValueType)
                                {
                                    CodeBuilder.AppendFormat("{0}{1} = wrapexternvaluetypearray({2});", GetIndentString(), mi.OriginalParamsName, mi.OriginalParamsName);
                                }
                                else
                                {
                                    CodeBuilder.AppendFormat("{0}{1} = wraparray({2});", GetIndentString(), mi.OriginalParamsName, mi.OriginalParamsName);
                                }
                                CodeBuilder.AppendLine();
                            }
                        }
                        VisitBlock(accessor.Body);
                    }
                    --m_Indent;
                    CodeBuilder.AppendFormat("{0}end,", GetIndentString());
                    CodeBuilder.AppendLine();

                    m_MethodInfoStack.Pop();
                }
            }

            ci.CurrentCodeBuilder = currentBuilder;
        }
Пример #38
0
        public override void VisitObjectCreationExpression(ObjectCreationExpressionSyntax node)
        {
            var ci           = m_ClassInfoStack.Peek();
            var oper         = m_Model.GetOperation(node);
            var objectCreate = oper as IObjectCreationExpression;

            if (null != objectCreate)
            {
                var typeSymInfo = objectCreate.Type;
                var sym         = objectCreate.Constructor;

                m_ObjectCreateStack.Push(typeSymInfo);

                string fullTypeName = ClassInfo.GetFullName(typeSymInfo);

                //处理ref/out参数
                InvocationInfo ii = new InvocationInfo();
                ii.Init(sym, node.ArgumentList, m_Model);
                AddReferenceAndTryDeriveGenericTypeInstance(ci, sym);

                bool isCollection = IsImplementationOfSys(typeSymInfo, "ICollection");
                bool isExternal   = typeSymInfo.ContainingAssembly != m_SymbolTable.AssemblySymbol;

                string ctor      = NameMangling(sym);
                string localName = string.Format("__compiler_newobject_{0}", node.GetLocation().GetLineSpan().StartLinePosition.Line);
                if (ii.ReturnArgs.Count > 0)
                {
                    CodeBuilder.Append("(function() ");
                    CodeBuilder.AppendFormat("local {0}; {1}", localName, localName);
                    CodeBuilder.Append(", ");
                    OutputExpressionList(ii.ReturnArgs);
                    CodeBuilder.Append(" = ");
                }
                if (isCollection)
                {
                    bool isDictionary = IsImplementationOfSys(typeSymInfo, "IDictionary");
                    bool isList       = IsImplementationOfSys(typeSymInfo, "IList");
                    if (isDictionary)
                    {
                        //字典对象的处理
                        CodeBuilder.AppendFormat("new{0}dictionary({1}, ", isExternal ? "extern" : string.Empty, fullTypeName);
                        if (isExternal)
                        {
                            CodeBuilder.AppendFormat("\"{0}\", ", fullTypeName);
                        }
                    }
                    else if (isList)
                    {
                        //列表对象的处理
                        CodeBuilder.AppendFormat("new{0}list({1}, ", isExternal ? "extern" : string.Empty, fullTypeName);
                        if (isExternal)
                        {
                            CodeBuilder.AppendFormat("\"{0}\", ", fullTypeName);
                        }
                    }
                    else
                    {
                        //集合对象的处理
                        CodeBuilder.AppendFormat("new{0}collection({1}, ", isExternal ? "extern" : string.Empty, fullTypeName);
                        if (isExternal)
                        {
                            CodeBuilder.AppendFormat("\"{0}\", ", fullTypeName);
                        }
                    }
                }
                else
                {
                    CodeBuilder.AppendFormat("new{0}object({1}, ", isExternal ? "extern" : string.Empty, fullTypeName);
                    if (isExternal)
                    {
                        CodeBuilder.AppendFormat("\"{0}\", ", fullTypeName);
                    }
                }
                if (string.IsNullOrEmpty(ctor))
                {
                    CodeBuilder.Append("nil");
                }
                else
                {
                    CodeBuilder.AppendFormat("\"{0}\"", ctor);
                }
                if (isExternal)
                {
                    ClassSymbolInfo csi;
                    if (m_SymbolTable.ClassSymbols.TryGetValue(fullTypeName, out csi))
                    {
                        if (csi.ExtensionClasses.Count > 0)
                        {
                            CodeBuilder.Append(", (function(obj)");
                            foreach (var pair in csi.ExtensionClasses)
                            {
                                string refname = pair.Key;
                                CodeBuilder.AppendFormat(" {0}.__install_{1}(obj);", fullTypeName, refname.Replace(".", "_"));
                            }
                            CodeBuilder.Append(" end)");
                        }
                        else
                        {
                            CodeBuilder.Append(", nil");
                        }
                    }
                    else
                    {
                        CodeBuilder.Append(", nil");
                    }
                }
                if (null != node.Initializer)
                {
                    CodeBuilder.Append(", ");
                    if (!isCollection)
                    {
                        CodeBuilder.Append("{");
                    }
                    VisitInitializerExpression(node.Initializer);
                    if (!isCollection)
                    {
                        CodeBuilder.Append("}");
                    }
                }
                else
                {
                    CodeBuilder.Append(", {}");
                }
                if (ii.Args.Count + ii.DefaultValueArgs.Count + ii.GenericTypeArgs.Count > 0)
                {
                    CodeBuilder.Append(", ");
                }
                OutputArgumentList(ii.Args, ii.DefaultValueArgs, ii.GenericTypeArgs, ii.ArrayToParams, false, node);
                CodeBuilder.Append(")");
                if (ii.ReturnArgs.Count > 0)
                {
                    CodeBuilder.Append("; ");
                    CodeBuilder.AppendFormat("return {0}; end)()", localName);
                }

                m_ObjectCreateStack.Pop();
            }
            else
            {
                var methodBinding = oper as IMethodBindingExpression;
                if (null != methodBinding)
                {
                    var typeSymInfo = methodBinding.Type;
                    var msym        = methodBinding.Method;
                    if (null != msym)
                    {
                        string manglingName = NameMangling(msym);
                        var    mi           = new MethodInfo();
                        mi.Init(msym, node);

                        CodeBuilder.Append("(function(");
                        string paramsString = string.Join(", ", mi.ParamNames.ToArray());
                        CodeBuilder.Append(paramsString);
                        CodeBuilder.Append(") ");
                        if (!msym.ReturnsVoid)
                        {
                            CodeBuilder.Append("return ");
                        }
                        if (msym.IsStatic)
                        {
                            AddReferenceAndTryDeriveGenericTypeInstance(ci, msym);

                            string className = ClassInfo.GetFullName(msym.ContainingType);
                            CodeBuilder.Append(className);
                            CodeBuilder.Append(".");
                        }
                        else
                        {
                            CodeBuilder.Append("this:");
                        }
                        CodeBuilder.Append(manglingName);
                        CodeBuilder.AppendFormat("({0}) end)", paramsString);
                    }
                    else
                    {
                        VisitArgumentList(node.ArgumentList);
                    }
                }
                else
                {
                    var typeParamObjCreate = oper as ITypeParameterObjectCreationExpression;
                    if (null != typeParamObjCreate)
                    {
                        CodeBuilder.Append("newtypeparamobject(");
                        OutputType(typeParamObjCreate.Type, node, ci, "new");
                        CodeBuilder.Append(")");
                    }
                    else
                    {
                        Log(node, "Unknown ObjectCreationExpressionSyntax !");
                    }
                }
            }
        }
Пример #39
0
		public static void Parse(TheProperty pProperty, CodeBuilder pBuilder, FactoryExpressionCreator pCreator) {
			if (pProperty == null) return;
			bool isInterface = pProperty.MyClass.IsInterface;
			string type = JsHelpers.Convert(pProperty.ReturnType);

			if (pProperty.IsEmpty && !isInterface) {
				pBuilder.AppendFormat("private var _{0}:{1};", pProperty.Name, type);
				pBuilder.AppendLine();
			}

			TheClass parent = pProperty.MyClass;
			bool isStandardGetSet = false;
			while (parent.Base != null) {
				isStandardGetSet |= parent.FullName.StartsWith("flash.");
				parent = parent.Base;
			}

			if (pProperty.Getter != null) {//Getter
				if (isStandardGetSet) {//base is flash, use standard setter/getter
					pBuilder.AppendFormat("{0}function get {1}():{2}{3}",
						JsHelpers.ConvertModifiers(pProperty.Getter.Modifiers, _notValidPropertyMod),
						pProperty.Name,
						type,
						isInterface ? ";" : " {"
					);

				} else {
					bool isEnum = false;

					foreach (string s in pProperty.MyClass.Implements) {
						if (!s.StartsWith("IEnumerator", StringComparison.Ordinal)) {
							continue;
						}

						isEnum = true;
						break;
					}

					isEnum &= pProperty.Getter.Name.Equals("get_Current");

					//bool isEnum =
					//    pProperty.Getter.Name.Equals("get_Current") &&
					//    pProperty.MyClass.Implements.Contains()

					pBuilder.AppendFormat("{0}function {1}():{2}{3}",
						JsHelpers.ConvertModifiers(pProperty.Getter.Modifiers, _notValidPropertyMod),
						pProperty.Getter.Name,
						isEnum ? "*" : type,
						isInterface ? ";" : " {"
					);
				}

				pBuilder.AppendLine();

				if (!isInterface) {
					if (pProperty.IsEmpty) {
						pBuilder.Indent();
						pBuilder.AppendFormat("return _{0};", pProperty.Name);
						pBuilder.Unindent();

					} else {
						BlockParser.Parse(pProperty.Getter.CodeBlock, pBuilder, pCreator);
					}

					pBuilder.AppendLine();
					pBuilder.AppendLine("}");
					pBuilder.AppendLine();
				}
			}

			if (pProperty.Setter == null) {
				return;
			}

			if (isStandardGetSet) {//Setter
//base is flash, use standard setter/getter
				pBuilder.AppendFormat("{0}function set {1}(value:{2}):void{3}",
				                      JsHelpers.ConvertModifiers(pProperty.Setter.Modifiers, _notValidPropertyMod),
				                      pProperty.Name,
				                      type,
									  isInterface ? ";" : " {"
					);
			} else {
				pBuilder.AppendFormat("{0}function {1}(value:{2}):{2}{3}",
				                      JsHelpers.ConvertModifiers(pProperty.Setter.Modifiers, _notValidPropertyMod),
				                      pProperty.Setter.Name,
				                      type,
									  isInterface ? ";" : " {"
					);
			}

			pBuilder.AppendLine();

			if (!isInterface) {
				if (pProperty.IsEmpty) {
					pBuilder.Indent();
					pBuilder.AppendFormat("_{0} = value;", pProperty.Name);
					pBuilder.AppendLine();
					pBuilder.Append("return value;");
					pBuilder.Unindent();

				} else {
					BlockParser.InsideSetter = !isStandardGetSet;
					BlockParser.Parse(pProperty.Setter.CodeBlock, pBuilder, pCreator);
					BlockParser.InsideSetter = false;
					if (!isStandardGetSet)
						pBuilder.AppendLine("	return value;");
				}

				pBuilder.AppendLine();
				pBuilder.AppendLine("}");
			}

			pBuilder.AppendLine();
		}
Пример #40
0
        public override void VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node)
        {
            SymbolInfo symInfo = m_Model.GetSymbolInfo(node);
            var        sym     = symInfo.Symbol as IMethodSymbol;

            if (null != sym)
            {
                var mi = new MethodInfo();
                mi.Init(sym, node);
                m_MethodInfoStack.Push(mi);

                CodeBuilder.Append("(function(");
                CodeBuilder.Append(string.Join(", ", mi.ParamNames.ToArray()));
                if (node.Body is BlockSyntax)
                {
                    CodeBuilder.AppendLine(")");
                    ++m_Indent;
                    if (mi.ValueParams.Count > 0)
                    {
                        OutputWrapValueParams(CodeBuilder, mi);
                    }
                    if (!string.IsNullOrEmpty(mi.OriginalParamsName))
                    {
                        if (mi.ParamsIsValueType)
                        {
                            CodeBuilder.AppendFormat("{0}local {1} = wrapvaluetypearray{{...}};", GetIndentString(), mi.OriginalParamsName);
                        }
                        else if (mi.ParamsIsExternValueType)
                        {
                            CodeBuilder.AppendFormat("{0}local {1} = wrapexternvaluetypearray{{...}};", GetIndentString(), mi.OriginalParamsName);
                        }
                        else
                        {
                            CodeBuilder.AppendFormat("{0}local {1} = wraparray{{...}};", GetIndentString(), mi.OriginalParamsName);
                        }
                        CodeBuilder.AppendLine();
                    }
                    node.Body.Accept(this);
                    if (!mi.ExistTopLevelReturn && mi.ReturnParamNames.Count > 0)
                    {
                        CodeBuilder.AppendFormat("{0}return {1};", GetIndentString(), string.Join(", ", mi.ReturnParamNames));
                        CodeBuilder.AppendLine();
                    }
                    --m_Indent;
                    CodeBuilder.AppendFormat("{0}end)", GetIndentString());
                }
                else
                {
                    string varName = string.Format("__compiler_lambda_{0}", node.GetLocation().GetLineSpan().StartLinePosition.Line);
                    CodeBuilder.AppendFormat(") ");
                    if (mi.ReturnParamNames.Count > 0)
                    {
                        CodeBuilder.AppendFormat("local {0} = ", varName);
                    }
                    else
                    {
                        CodeBuilder.Append("return ");
                    }
                    IConversionExpression opd = null;
                    var oper = m_Model.GetOperation(node) as ILambdaExpression;
                    if (null != oper && oper.Body.Statements.Length == 1)
                    {
                        var iret = oper.Body.Statements[0] as IReturnStatement;
                        if (null != iret)
                        {
                            opd = iret.ReturnedValue as IConversionExpression;
                        }
                    }
                    var exp = node.Body as ExpressionSyntax;
                    OutputExpressionSyntax(exp, opd);
                    if (mi.ReturnParamNames.Count > 0)
                    {
                        CodeBuilder.AppendFormat("; return {0}, {1}", varName, string.Join(", ", mi.ReturnParamNames));
                    }
                    CodeBuilder.Append("; end)");
                }
                m_MethodInfoStack.Pop();
            }
            else
            {
                ReportIllegalSymbol(node, symInfo);
            }
        }
Пример #41
0
		private static void parseLocalConstantDeclaration(CsStatement pStatement, CodeBuilder pSb, FactoryExpressionCreator pCreator) {
			CsDeclarationStatement declarationStatement = (CsDeclarationStatement)pStatement;

			CsLocalConstantDeclaration lcd = (CsLocalConstantDeclaration)declarationStatement.declaration;

			foreach (CsLocalConstantDeclarator declarator in lcd.declarators) {
				StringBuilder sb = new StringBuilder();

				sb.AppendFormat(@"const {0}:{1} = {2};",
					declarator.identifier.identifier,
					As3Helpers.Convert(Helpers.GetType(lcd.type)),
					pCreator.Parse(declarator.expression).Value
				);

				pSb.Append(sb.ToString());
				pSb.AppendLine();
			}
		}
Пример #42
0
 public static CodeBuilder operator +(CodeBuilder codeBuilder, string s)
 {
     codeBuilder.Append(s);
     return(codeBuilder);
 }
Пример #43
0
		private static void parseIfStatement(CsStatement pStatement, CodeBuilder pSb, FactoryExpressionCreator pCreator) {
			CsIfStatement ifStatement = (CsIfStatement)pStatement;

			pSb.AppendFormat("if ({0}){{", pCreator.Parse(ifStatement.condition));
			pSb.AppendLine();

			ParseNode(ifStatement.if_statement, pSb, pCreator);

			if (ifStatement.else_statement != null) {
				pSb.AppendLine();
				pSb.Append("} else {");
				pSb.AppendLine();
				pSb.AppendLine();
				ParseNode(ifStatement.else_statement, pSb, pCreator);
			}

			pSb.Append("}");
			pSb.AppendLine();
			pSb.AppendLine();
		}
Пример #44
0
    public void EmitEnum(CodeBuilder b)
    {
        var enumName = CSharp.ApplyStyle(CfxName);

        b.AppendSummaryAndRemarks(comments);

        if (Name.Contains("_flags") || additionalFlags.Contains(enumName))
        {
            b.AppendLine("[Flags()]");
        }

        var prefixBuilder = new StringBuilder();
        var allEqual      = true;

        if (members.Length > 1)
        {
            do
            {
                char c = members[0].Name[prefixBuilder.Length];
                for (var i = 1; i <= members.Length - 1; i++)
                {
                    if (c != members[i].Name[prefixBuilder.Length])
                    {
                        allEqual = false;
                        break;
                    }
                }
                if (allEqual)
                {
                    prefixBuilder.Append(c);
                }
            } while(allEqual);

            while (prefixBuilder.Length > 0 && prefixBuilder[prefixBuilder.Length - 1] != '_')
            {
                --prefixBuilder.Length;
            }
        }

        b.BeginBlock("public enum {0}", enumName);
        foreach (var m in members)
        {
            m.PublicName = CSharp.ApplyStyle(m.Name.Substring(prefixBuilder.Length));

            if (char.IsDigit(m.PublicName[0]))
            {
                switch (enumName)
                {
                case "CfxScaleFactor":
                    m.PublicName = "ScaleFactor" + m.PublicName;
                    break;

                case "CfxChannelLayout":
                    // version numbers like CEF_CHANNEL_LAYOUT_4_0, CEF_CHANNEL_LAYOUT_5_0_BACK
                    m.PublicName = "V" + m.PublicName;
                    break;

                default:
                    Debug.Assert(false);
                    break;
                }
            }

            b.AppendSummary(m.Comments);
            b.Append(m.PublicName);
            if (m.Value != null)
            {
                b.Append(" = {0}", GetEnumMemberValue(m.Value));
            }
            b.AppendLine(",");
        }
        b.TrimRight();
        b.CutRight(1);
        b.AppendLine();
        b.EndBlock();
    }
Пример #45
0
		private static void parseSwitchStatement(CsStatement pStatement, CodeBuilder pSb, FactoryExpressionCreator pCreator) {
			CsSwitchStatement switchStatement = (CsSwitchStatement)pStatement;

			pSb.AppendFormat("switch ({0}){{", pCreator.Parse(switchStatement.expression).Value);
			pSb.AppendLine();
			pSb.Indent();

			foreach (CsSwitchSection caseNode in switchStatement.sections) {
				LinkedList<CsSwitchLabel> labels = caseNode.labels;
				foreach (CsSwitchLabel label in labels){
					if (label.default_label) {
						pSb.Append("default:");
						pSb.AppendLine();

					} else {
						Expression txt = pCreator.Parse(label.expression);
						pSb.AppendFormat("case {0}:", txt.Value);
						pSb.AppendLine();
					}
				}

				foreach (CsStatement statementNode in caseNode.statements) {
					pSb.Indent();
					parseStatement(statementNode, pSb, pCreator);
					pSb.Unindent();
				}
			}

			pSb.Unindent();
			pSb.Append("}");
			pSb.AppendLine();
		}
Пример #46
0
        public override void VisitReturnStatement(ReturnStatementSyntax node)
        {
            MethodInfo mi = m_MethodInfoStack.Peek();

            mi.ExistTopLevelReturn = IsLastNodeOfMethod(node);

            bool isLastNode = IsLastNodeOfParent(node);

            if (!isLastNode || mi.TryCatchUsingLayer > 0)
            {
                CodeBuilder.AppendFormat("{0}block{{", GetIndentString());
                CodeBuilder.AppendLine();
            }

            if (mi.TryCatchUsingLayer > 0)
            {
                if (null != node.Expression)
                {
                    IConversionExpression opd = null;
                    var iret = m_Model.GetOperation(node) as IReturnStatement;
                    if (null != iret)
                    {
                        opd = iret.ReturnedValue as IConversionExpression;
                    }
                    CodeBuilder.AppendFormat("{0}{1} = ", GetIndentString(), mi.ReturnVarName);
                    OutputExpressionSyntax(node.Expression, opd);
                    CodeBuilder.AppendLine(";");
                }
                CodeBuilder.AppendFormat("{0}return(1);", GetIndentString());
                CodeBuilder.AppendLine();
            }
            else
            {
                string prestr;
                if (mi.SemanticInfo.MethodKind == MethodKind.Constructor)
                {
                    CodeBuilder.AppendFormat("{0}return(this", GetIndentString());
                    prestr = ", ";
                }
                else
                {
                    CodeBuilder.AppendFormat("{0}return(", GetIndentString());
                    prestr = string.Empty;
                }
                if (null != node.Expression)
                {
                    CodeBuilder.Append(prestr);
                    IConversionExpression opd = null;
                    var iret = m_Model.GetOperation(node) as IReturnStatement;
                    if (null != iret)
                    {
                        opd = iret.ReturnedValue as IConversionExpression;
                    }
                    OutputExpressionSyntax(node.Expression, opd);
                    prestr = ", ";
                }
                var names = mi.ReturnParamNames;
                if (names.Count > 0)
                {
                    for (int i = 0; i < names.Count; ++i)
                    {
                        CodeBuilder.Append(prestr);
                        CodeBuilder.Append(names[i]);
                        prestr = ", ";
                    }
                }
                CodeBuilder.AppendLine(");");
            }

            if (!isLastNode || mi.TryCatchUsingLayer > 0)
            {
                CodeBuilder.AppendFormat("{0}}};", GetIndentString());
                CodeBuilder.AppendLine();
            }
        }
Пример #47
0
		private static void parseExpressionStatement(CsStatement pStatement, CodeBuilder pSb, FactoryExpressionCreator pCreator) {
			Expression ex = pCreator.Parse(((CsExpressionStatement)pStatement).expression);
			pSb.Append(ex.Value+";");
			pSb.AppendLine();
		}
Пример #48
0
        public override void VisitForStatement(ForStatementSyntax node)
        {
            MethodInfo mi = m_MethodInfoStack.Peek();

            mi.TryCatchUsingOrLoopSwitchStack.Push(false);

            ContinueInfo ci = new ContinueInfo();

            ci.Init(node.Statement);
            m_ContinueInfoStack.Push(ci);

            if (null != node.Declaration)
            {
                VisitVariableDeclaration(node.Declaration);
            }
            if (null != node.Initializers && node.Initializers.Count > 0)
            {
                foreach (var exp in node.Initializers)
                {
                    CodeBuilder.AppendFormat("{0}", GetIndentString());
                    VisitToplevelExpression(exp, ";");
                }
            }
            CodeBuilder.AppendFormat("{0}while( ", GetIndentString());
            if (null != node.Condition)
            {
                var oper = m_Model.GetOperation(node) as IForLoopStatement;
                IConversionExpression opd = null;
                if (null != oper)
                {
                    opd = oper.Condition as IConversionExpression;
                }
                OutputExpressionSyntax(node.Condition, opd);
            }
            else
            {
                CodeBuilder.Append("true");
            }
            CodeBuilder.AppendLine(" ){");
            if (ci.HaveContinue)
            {
                if (ci.HaveBreak)
                {
                    CodeBuilder.AppendFormat("{0}local{{{1} = false;}};", GetIndentString(), ci.BreakFlagVarName);
                    CodeBuilder.AppendLine();
                }
                CodeBuilder.AppendFormat("{0}do{{", GetIndentString());
                CodeBuilder.AppendLine();
            }
            ++m_Indent;
            node.Statement.Accept(this);
            --m_Indent;
            if (ci.HaveContinue)
            {
                CodeBuilder.AppendFormat("{0}}}while(false);", GetIndentString());
                CodeBuilder.AppendLine();
                if (ci.HaveBreak)
                {
                    CodeBuilder.AppendFormat("{0}if({1}){{break;}};", GetIndentString(), ci.BreakFlagVarName);
                    CodeBuilder.AppendLine();
                }
            }
            foreach (var exp in node.Incrementors)
            {
                CodeBuilder.AppendFormat("{0}", GetIndentString());
                VisitToplevelExpression(exp, ";");
            }
            CodeBuilder.AppendFormat("{0}}};", GetIndentString());
            CodeBuilder.AppendLine();

            m_ContinueInfoStack.Pop();
            mi.TryCatchUsingOrLoopSwitchStack.Pop();
        }
Пример #49
0
		private static void parseWhileStatement(CsStatement pStatement, CodeBuilder pSb, FactoryExpressionCreator pCreator) {
			CsWhileStatement whileStatement = (CsWhileStatement)pStatement;

			pSb.AppendFormat("while ({0}){{", pCreator.Parse(whileStatement.condition));
			pSb.AppendLine();
			ParseNode(whileStatement.statement, pSb, pCreator);
			pSb.Append("}");
			pSb.AppendLine();
			pSb.AppendLine();
		}
Пример #50
0
 public override void VisitParenthesizedExpression(ParenthesizedExpressionSyntax node)
 {
     CodeBuilder.Append("( ");
     VisitExpressionSyntax(node.Expression);
     CodeBuilder.Append(" )");
 }