public void VerifyDefaultCtor()
 {
     NamespaceDeclaration nsdecl = new NamespaceDeclaration("My.NS");
     nsdecl.AddClass("MyClass").AddConstructor();
     CodeBuilder builder = new CodeBuilder();
     builder.GenerateCode(Console.Out, nsdecl);
 }
		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();
		}
		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);
		}
 public void can_create_enum()
 {
     var @enum = new EnumDeclaration("TransactionLineTypes");
     @enum.AddField("Pending", 1);
     var builder = new CodeBuilder();
     builder.GenerateCode(Console.Out, "Awish.Lars.Core.Enums", @enum);
 }
		public static void Parse(TheMethod pMethod, CodeBuilder pBuilder, FactoryExpressionCreator pCreator) {
			if (pMethod == null) return;
			bool isInterface = pMethod.MyClass.IsInterface;

			Dictionary<string,string> nonValidMethod = new Dictionary<string, string>(_notValidMethodMod);
			if (ClassParser.IsExtension) {
				nonValidMethod.Add("static",string.Empty);
			}

			pBuilder.AppendFormat("{0}function {1}({2}):{3}{4}",
				As3Helpers.ConvertModifiers(pMethod.Modifiers, nonValidMethod),
				pMethod.Name,
				As3Helpers.GetParameters(pMethod.Arguments),
				As3Helpers.Convert(pMethod.ReturnType),
				isInterface ? ";":" {"
			);

			pBuilder.AppendLine();

			if (isInterface)
				return;

			pBuilder.AppendLine();
			BlockParser.Parse(pMethod.CodeBlock, pBuilder, pCreator);
			pBuilder.AppendLine();
			pBuilder.AppendLine("}");
			pBuilder.AppendLine();
		}
		public void WriteCode(ITemplate tpl, FragmentCodePoint point, CodeBuilder cb) {
			if (!string.IsNullOrEmpty(code))
				cb.AppendLine(code);
			for (int i = 0; i < indentEffect; i++)
				cb.Indent();
			for (int i = 0; i < -indentEffect; i++)
				cb.Outdent();
		}
        public Code WriteCode(IRCodeBlock block)
        {
            var builder = new CodeBuilder();
            var visitor = new ByteCodeVisitor(builder);
            visitor.Visit(block);

            return builder.Build();
        }
        private static CodeBuilder.ICodeBlock GenerateSetToIgnorePausing(CodeBuilder.ICodeBlock codeBlock, SaveClasses.IElement element, bool hasBase)
        {

            string virtualOrOverride = "virtual";
            if (hasBase)
            {
                virtualOrOverride = "override";
            }

            codeBlock = codeBlock.Function("public " + virtualOrOverride + " void", "SetToIgnorePausing", "");

            if (hasBase)
            {
                codeBlock.Line("base.SetToIgnorePausing();");
            }
            else
            {
                codeBlock.Line("FlatRedBall.Instructions.InstructionManager.IgnorePausingFor(this);");

            }

            foreach (NamedObjectSave nos in element.AllNamedObjects)
            {
                if (nos.IsFullyDefined && !nos.IsDisabled && !nos.IsContainer)
                {
                    NamedObjectSaveCodeGenerator.AddIfConditionalSymbolIfNecesssary(codeBlock, nos);

                    bool shouldWrapInNullCheck = nos.SetByDerived || nos.SetByContainer || nos.Instantiate == false;

                    if (shouldWrapInNullCheck)
                    {
                        codeBlock = codeBlock.If(nos.InstanceName + " != null");
                    }



                    if (nos.GetAssetTypeInfo() != null && nos.GetAssetTypeInfo().CanIgnorePausing)
                    {
                        codeBlock.Line("FlatRedBall.Instructions.InstructionManager.IgnorePausingFor(" + nos.InstanceName + ");");
                    }
                    else if (nos.SourceType == SourceType.Entity)
                    {
                        codeBlock.Line(nos.InstanceName + ".SetToIgnorePausing();");
                    }

                    if (shouldWrapInNullCheck)
                    {
                        codeBlock = codeBlock.End();
                    }

                    NamedObjectSaveCodeGenerator.AddEndIfIfNecessary(codeBlock, nos);
                }
            }

            codeBlock = codeBlock.End();
            return codeBlock;
        }
        public void VerifySingleArg()
        {
            NamespaceDeclaration nsdecl = new NamespaceDeclaration("My.NS");
            nsdecl.AddClass("MyClass")
                .AddConstructor(typeof(int), "id", "_id");

            CodeBuilder builder = new CodeBuilder();
            builder.GenerateCode(Console.Out, nsdecl);
        }
		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");
				}
			}
		}
		private void WriteDefinition(ITemplate tpl, bool isServer, CodeBuilder cb) {
			cb.AppendLine("private string " + name + "(" + parameters + ") {").Indent()
			  .AppendLine("StringBuilder " + ParserUtils.RenderFunctionStringBuilderName + " = new StringBuilder();");

			foreach (IFragment f in ParserUtils.MergeFragments(fragments))
				f.WriteCode(tpl, isServer ? FragmentCodePoint.ServerRender : FragmentCodePoint.ClientRender, cb);
			
			cb.AppendLine("return " + ParserUtils.RenderFunctionStringBuilderName + ".ToString();")
			  .Outdent().AppendLine("}").AppendLine();
		}
        public override CodeBuilder.ICodeBlock GenerateInitialize(CodeBuilder.ICodeBlock codeBlock, SaveClasses.IElement element)
        {
            if(IsLoadingScreen(element))
            {
                codeBlock.Line("mSavedTargetElapedTime = FlatRedBallServices.Game.TargetElapsedTime.TotalSeconds;");
                codeBlock.Line("FlatRedBall.FlatRedBallServices.Game.TargetElapsedTime = TimeSpan.FromSeconds(.1);");

            }
            return codeBlock;
        }
Exemple #13
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();
		}
		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();
		}
		public void WriteCode(ITemplate tpl, MemberCodePoint point, CodeBuilder cb) {
			switch (point) {
				case MemberCodePoint.ServerDefinition:
					WriteDefinition(tpl, true, cb);
					break;
				case MemberCodePoint.ClientDefinition:
					if (tpl.EnableClientCreate)
						WriteDefinition(tpl, false, cb);
					break;
			}
		}
        public Code WriteCode(IRCodeBlock block)
        {
            var builder = new CodeBuilder();
            var visitor = new ActionReplayVisitor(builder);
            var optimizer = new ActionReplayOptimizer(builder);

            block = optimizer.Optimize(block);

            visitor.Visit(block);

            return builder.Build();
        }
		public void WriteCode(ITemplate tpl, MemberCodePoint point, CodeBuilder cb) {
			switch (point) {
				case MemberCodePoint.ClientDefinition:
					if (clientType != null)
						WriteDefinition(cb, clientType, backingFieldClientType, false);
					break;
				case MemberCodePoint.ServerDefinition:
					if (serverType != null)
						WriteDefinition(cb, serverType, backingFieldServerType, true);
					break;
			}
		}
 public void CreateInstance(Form main,string content)
 {
     if (main is Main)
     {
         Main form = (Main)main;
         CodeBuilder builder = new CodeBuilder(content);
         builder.Handle += new ExceptionHandle<ExceptionArgs>((ExceptionArgs e) =>
         {
             form.Dispatcher(DispatcherType.Error, e.Exception.Message.ToString());
         });
         builder.ShowDialog();
     }
 }
        public IExpression WithBody(VoidAction<ICodeBuilder> code)
        {
            method.Type = delegateType;
            method.CallingConvention = CallingConvention.HasThis;
            method.ReturnType = returnTypeReference;

            var codeBuilder = new CodeBuilder(host, method.Parameters);
            code(codeBuilder);

            var body = new BlockStatement();
            foreach (var statement in codeBuilder.Statements) body.Statements.Add(statement);
            method.Body = body;

            return method;
        }
        public override CodeBuilder.ICodeBlock GenerateFields(CodeBuilder.ICodeBlock codeBlock, SaveClasses.IElement element)
        {

            if (element is EntitySave)
            {
                EntitySave asEntity = element as EntitySave;

                if (asEntity.CreatedByOtherEntities && asEntity.GetAllBaseEntities().Count(item=>item.CreatedByOtherEntities) == 0)
                {
                    codeBlock.AutoProperty("public int", "Index");
                    codeBlock.AutoProperty("public bool", "Used");
                }
            }

            return codeBlock;
        }
		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);");
		}
		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();
			}
		}
		public static void Parse(TheIndexer pGetIndexer, CodeBuilder pBuilder, FactoryExpressionCreator pCreator) {
			bool isInterface = pGetIndexer.MyClass.IsInterface;

			if (pGetIndexer.Getter != null) {
				pBuilder.AppendFormat("{0}function {1}({2}):{3}{4}",
					JsHelpers.ConvertModifiers(pGetIndexer.Getter.Modifiers, _notValidMod),
					pGetIndexer.Getter.Name,
					JsHelpers.GetParameters(pGetIndexer.Getter.Arguments),
					JsHelpers.Convert(pGetIndexer.ReturnType),
					isInterface ? ";":" {"
				);
				pBuilder.AppendLine();

				if (!isInterface) {
					BlockParser.Parse(pGetIndexer.Getter.CodeBlock, pBuilder, pCreator);
					pBuilder.AppendLine();
					pBuilder.AppendLine("}");
					pBuilder.AppendLine();
				}
			}

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

			pBuilder.AppendFormat(
				"{0}function {1}({2}):void{3}",
				  JsHelpers.ConvertModifiers(pGetIndexer.Setter.Modifiers, _notValidMod),
				  pGetIndexer.Setter.Name,
				  JsHelpers.GetParameters(pGetIndexer.Setter.Arguments),
				  isInterface ? ";" : " {"
			);

			pBuilder.AppendLine();
			if (isInterface)
				return;
			//BlockParser.InsideSetter = true;
			BlockParser.Parse(pGetIndexer.Setter.CodeBlock, pBuilder, pCreator);
			//BlockParser.InsideSetter = false;
			pBuilder.AppendLine();
			pBuilder.AppendLine("}");
			pBuilder.AppendLine();
		}
Exemple #24
0
		public static void Parse(TheEvent pEvent, CodeBuilder pBuilder) {
			if (pEvent.IsFlashEvent) return;

			ImportStatementList.AddImport(@"System.EventHandler");

			bool isStatic = pEvent.Modifiers.Contains("static");

			pBuilder.AppendFormat(@"private {1} var _e{0}:EventHandler;
		{2}{1} function get {0}():EventHandler {{
			if (_e{0} == null) _e{0} = new EventHandler();
			return _e{0};
		}}", 
				pEvent.Name, 
				isStatic ? "static" : string.Empty,
				As3Helpers.ConvertModifiers(pEvent.Modifiers, _notValidClassMod)
				//,isStatic ? pEvent.MyClass.Name : "this"
			);

			pBuilder.AppendLine();
		}
		public void WriteCode(ITemplate tpl, MemberCodePoint point, CodeBuilder cb) {
			switch (point) {
				case MemberCodePoint.ServerDefinition:
					if (serverType != null)
						cb.AppendLine("private " + serverType + " " + Name + ";").AppendLine();
					break;
				case MemberCodePoint.ClientDefinition:
					if (clientType != null)
						cb.AppendLine("private " + ClientType + " " + Name + ";").AppendLine();
					break;
				case MemberCodePoint.TransferConstructor:
					if (serverType != null && clientType != null)
						cb.AppendLine("this." + name + " = (" + clientType + ")" + ParserUtils.ConfigObjectName + "[\"" + name + "\"];");
					break;
				case MemberCodePoint.ConfigObjectInit:
					if (serverType != null && clientType != null)
						cb.AppendLine(ParserUtils.ConfigObjectName + "[\"" + name + "\"] = this." + name + ";");
					break;
			}
		}
		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();
			}
		}
		public void WriteCode(ITemplate tpl, MemberCodePoint point, CodeBuilder cb) {
			switch (point) {
				case MemberCodePoint.ServerDefinition:
				case MemberCodePoint.ClientDefinition:
					WriteDefinition(cb);
					break;
				case MemberCodePoint.ServerConstructor:
				case MemberCodePoint.ClientConstructor:
					WriteNonTransferConstructorCode(cb);
					break;
				case MemberCodePoint.TransferConstructor:
					WriteTransferConstructorCode(cb);
					break;
				case MemberCodePoint.Attach:
					WriteAttachCode(cb);
					break;
				case MemberCodePoint.ConfigObjectInit:
					WriteConfigObjectInitCode(cb);
					break;
			}
		}
        public override CodeBuilder.ICodeBlock GenerateAdditionalMethods(CodeBuilder.ICodeBlock codeBlock, SaveClasses.IElement element)
        {
            if(element is EntitySave)
            {
                bool hasBase = element.InheritsFromElement();
                if (hasBase == false)
                {
                    codeBlock.Line("protected bool mIsPaused;");

                    var function = codeBlock.Function("public override void", "Pause", "FlatRedBall.Instructions.InstructionList instructions");

                    function.Line("base.Pause(instructions);");
                    function.Line("mIsPaused = true;");

                    foreach (var nos in element.AllNamedObjects)
                    {
                        GeneratePauseForNos(nos, function);
                    }
                }
                codeBlock = GenerateSetToIgnorePausing(codeBlock, element, hasBase);
            }

            return codeBlock;
        }
Exemple #29
0
        static Block WhereFilter(Block sourceBlock)
        {
            var builder = new CodeBuilder();
            var stage   = WhereStageType.Left;

            foreach (var verb in sourceBlock.AsAdded)
            {
                switch (stage)
                {
                case WhereStageType.Left:
                    switch (verb)
                    {
                    case Push push:
                        var value = push.Value;
                        switch (value)
                        {
                        case Variable variable:
                            builder.Define(variable.Name);
                            stage = WhereStageType.Assign;
                            break;

                        case Parameters _:
                            builder.Verb(verb);
                            stage = WhereStageType.Assign;
                            break;
                        }

                        break;

                    case Define _:
                        builder.Verb(verb);
                        stage = WhereStageType.Assign;

                        break;
                    }

                    return(null);

                case WhereStageType.Assign:
                    if (verb is Assign)
                    {
                        builder.Verb(verb);
                        builder.Push();
                        stage = WhereStageType.Right;
                    }
                    else
                    {
                        return(null);
                    }

                    break;

                case WhereStageType.Right:
                    if (verb is AppendToArray)
                    {
                        builder.PopAndInline();
                        builder.End();
                        stage = WhereStageType.Left;
                    }
                    else
                    {
                        builder.Verb(verb);
                    }
                    break;
                }
            }

            switch (stage)
            {
            case WhereStageType.Right:
                builder.PopAndInline();
                return(builder.Block);
            }

            return(null);
        }
Exemple #30
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(", ");
                    }
                }
            }
        }
 InternalLocal DeclareTempLocal(IType localType)
 {
     return(CodeBuilder.DeclareTempLocal(_currentMethod, localType));
 }
Exemple #32
0
 public GeneratorVisitor(CodeBuilder cb)
 {
     this.cb = cb ?? throw new ArgumentNullException(nameof(cb));
 }
Exemple #33
0
 public override void EmitPostPublicCallStatements(CodeBuilder b, string var)
 {
     b.AppendLine("{0}_pinned.Free();", var);
 }
Exemple #34
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))
                {
                    SymbolTable.Instance.AddRequire(ci.Key, require);
                }
                if (ClassInfo.HasAttribute(declSym, "Cs2Lua.IgnoreAttribute"))
                {
                    return;
                }
                if (declSym.IsAbstract)
                {
                    return;
                }
            }

            bool noimpl = true;

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

            if (null != node.ExpressionBody)
            {
                StringBuilder curBuilder = ci.CurrentCodeBuilder;
                if (declSym.IsStatic)
                {
                    ci.CurrentCodeBuilder = ci.StaticFunctionCodeBuilder;
                }
                else
                {
                    ci.CurrentCodeBuilder = ci.InstanceFunctionCodeBuilder;
                }

                var mi = new MethodInfo();
                mi.Init(declSym.GetMethod, node.ExpressionBody);
                m_MethodInfoStack.Push(mi);

                string manglingName = NameMangling(declSym.GetMethod);
                CodeBuilder.AppendFormat("{0}{1} = function({2})", GetIndentString(), manglingName, declSym.IsStatic ? string.Empty : "this");
                CodeBuilder.AppendLine();
                ++m_Indent;
                CodeBuilder.AppendFormat("{0}return ", GetIndentString());
                IConversionExpression opd = null;
                var oper = m_Model.GetOperation(node.ExpressionBody) as IBlockStatement;
                if (null != oper && oper.Statements.Length == 1)
                {
                    var iret = oper.Statements[0] as IReturnStatement;
                    if (null != iret)
                    {
                        opd = iret.ReturnedValue as IConversionExpression;
                    }
                }
                OutputExpressionSyntax(node.ExpressionBody.Expression, opd);
                CodeBuilder.AppendLine(";");
                --m_Indent;
                CodeBuilder.AppendFormat("{0}end,", GetIndentString());
                CodeBuilder.AppendLine();

                m_MethodInfoStack.Pop();

                ci.CurrentCodeBuilder = curBuilder;

                CodeBuilder.AppendFormat("{0}{1} = {{", GetIndentString(), SymbolTable.GetPropertyName(declSym));
                CodeBuilder.AppendLine();
                ++m_Indent;
                CodeBuilder.AppendFormat("{0}get = {1}.{2},", GetIndentString(), declSym.IsStatic ? "static_methods" : "instance_methods", manglingName);
                CodeBuilder.AppendLine();
                --m_Indent;
                CodeBuilder.AppendFormat("{0}", GetIndentString());
                CodeBuilder.AppendLine("},");
            }
            else if (noimpl)
            {
                //退化为field
                StringBuilder curBuilder = ci.CurrentCodeBuilder;

                if (declSym.IsStatic)
                {
                    ci.CurrentCodeBuilder = ci.StaticFieldCodeBuilder;
                }
                else
                {
                    ci.CurrentCodeBuilder = ci.InstanceFieldCodeBuilder;
                }

                ++m_Indent;
                CodeBuilder.AppendFormat("{0}{1} = ", GetIndentString(), SymbolTable.GetPropertyName(declSym));
                if (null != node.Initializer)
                {
                    IConversionExpression opd = null;
                    var oper = m_Model.GetOperation(node.Initializer) as ISymbolInitializer;
                    if (null != oper)
                    {
                        opd = oper.Value as IConversionExpression;
                    }
                    CodeBuilder.AppendFormat("{0}", declSym.Type.TypeKind == TypeKind.Delegate ? "delegationwrap(" : string.Empty);
                    OutputExpressionSyntax(node.Initializer.Value, opd);
                    CodeBuilder.AppendFormat("{0}", declSym.Type.TypeKind == TypeKind.Delegate ? ")" : string.Empty);
                    CodeBuilder.Append(",");
                }
                else if (declSym.Type.TypeKind == TypeKind.Delegate)
                {
                    CodeBuilder.Append("wrapdelegation{},");
                }
                else
                {
                    OutputFieldDefaultValue(declSym.Type);
                    CodeBuilder.Append(",");
                }
                CodeBuilder.AppendLine();
                --m_Indent;

                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;
                        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))
                            {
                                SymbolTable.Instance.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{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("},");
            }
        }
Exemple #35
0
        /// <summary>
        /// Test creation of models
        /// </summary>
        public void CanCreate()
        {
            ModelContainer models = new ModelContainer()
            {
                Settings = new ModelBuilderSettings()
                {
                    ModelCodeLocation          = @"C:\dev\MyApp\src\Lib\CommonLibrary.WebModules\Src\Generated",
                    ModelCodeLocationTemplate  = @"C:\dev\MyApp\src\Lib\GenericCode\CodeGen\Templates\Default",
                    ModelInstallLocation       = @"C:\dev\MyApp\install\",
                    ModelCodeLocationUI        = @"C:\dev\MyApp\models\ui\",
                    ModelDbStoredProcTemplates = @"C:\dev\MyApp\src\Lib\GenericCode\CodeGen\Templates\DefaultSql",
                    ModelOrmLocation           = @"C:\dev\MyApp\src\Lib\CommonLibrary.WebModules\Config\hbm.xml",
                    DbAction_Create            = DbCreateType.DropCreate,
                    Connection       = new ConnectionInfo("Server=server1;Database=db1;User=user1;Password=password;", "System.Data.SqlClient"),
                    AssemblyName     = "CommonLibrary.WebModules",
                    OrmGenerationDef = new OrmGeneration(true, "<!-- ORM_GEN_START -->", "<!-- ORM_GEN_END -->"),
                },

                ExtendedSettings = new Dictionary <string, object>()
                {
                },

                // Model definition.
                AllModels = new List <Model>()
                {
                    new Model("ModelBase")
                    {
                        NameSpace           = "CommonLibrary.WebModules",
                        GenerateCode        = false,
                        GenerateTable       = false,
                        GenerateOrMap       = false,
                        PropertiesSortOrder = 1,
                        Properties          = new List <PropertyInfo>()
                        {
                            new PropertyInfo("Id", typeof(int))
                            {
                                IsRequired = true, ColumnName = "Id", IsKey = true
                            },
                            new PropertyInfo("CreateDate", typeof(DateTime))
                            {
                                IsRequired = true
                            },
                            new PropertyInfo("UpdateDate", typeof(DateTime))
                            {
                                IsRequired = true
                            },
                            new PropertyInfo("CreateUser", typeof(string))
                            {
                                IsRequired = true, MaxLength = "20"
                            },
                            new PropertyInfo("UpdateUser", typeof(string))
                            {
                                IsRequired = true, MaxLength = "20"
                            },
                            new PropertyInfo("UpdateComment", typeof(string))
                            {
                                IsRequired = false, MaxLength = "150"
                            },
                            new PropertyInfo("Version", typeof(int))
                            {
                                IsRequired = true, DefaultValue = 1
                            },
                            new PropertyInfo("IsActive", typeof(bool))
                            {
                                IsRequired = true, DefaultValue = 0
                            }
                        }
                    },
                    new Model("RatingPostBase")
                    {
                        NameSpace           = "CommonLibrary.WebModules",
                        Inherits            = "ModelBase",
                        GenerateCode        = false,
                        GenerateTable       = false,
                        GenerateOrMap       = false,
                        PropertiesSortOrder = 100,
                        Properties          = new List <PropertyInfo>()
                        {
                            new PropertyInfo("AverageRating", typeof(double)),
                            new PropertyInfo("TotalLiked", typeof(int)),
                            new PropertyInfo("TotalDisLiked", typeof(int)),
                            new PropertyInfo("TotalBookMarked", typeof(int)),
                            new PropertyInfo("TotalAbuseReports", typeof(int))
                        }
                    },
                    new Model("Address")
                    {
                        Properties = new List <PropertyInfo>()
                        {
                            new PropertyInfo("Street", typeof(string))
                            {
                                MaxLength = "40"
                            },
                            new PropertyInfo("City", typeof(string))
                            {
                                MaxLength = "40"
                            },
                            new PropertyInfo("State", typeof(string))
                            {
                                MaxLength = "20"
                            },
                            new PropertyInfo("Country", typeof(string))
                            {
                                MaxLength = "20", DefaultValue = "U.S."
                            },
                            new PropertyInfo("Zip", typeof(string))
                            {
                                MaxLength = "10"
                            },
                            new PropertyInfo("CityId", typeof(int)),
                            new PropertyInfo("StateId", typeof(int)),
                            new PropertyInfo("CountryId", typeof(int))
                        }
                    },
                    new Model("BlogPost")
                    {
                        TableName           = "BlogPosts",
                        NameSpace           = "CommonLibrary.WebModules.BlogPosts",
                        GenerateTable       = true, GenerateCode = true, GenerateTests = true,
                        GenerateUI          = true, GenerateRestApi = true, GenerateFeeds = true, GenerateOrMap = true,
                        IsWebUI             = true,
                        PropertiesSortOrder = 50,
                        Properties          = new List <PropertyInfo>()
                        {
                            new PropertyInfo("Title", typeof(string))
                            {
                                ColumnName = "Title", MinLength = "10", MaxLength = "150", IsRequired = true
                            },
                            new PropertyInfo("Summary", typeof(string))
                            {
                                MaxLength = "200", IsRequired = true
                            },
                            new PropertyInfo("Description", typeof(StringClob))
                            {
                                MinLength = "10", MaxLength = "-1", IsRequired = true
                            },
                            new PropertyInfo("Url", typeof(string))
                            {
                                MaxLength = "150", RegEx = ""
                            },
                            new PropertyInfo("AllowComments", typeof(bool))
                            {
                                DefaultValue = true
                            }
                        },
                        Inherits = "ModelBase",
                        Includes = new List <Include>()
                        {
                            new Include("RatingPostBase")
                        },
                        HasMany = new List <Relation>()
                        {
                            new Relation("Comment")
                        },
                        ExcludeFiles = "Feeds.cs,ImportExport.cs,Serializer.cs"
                    },
                    new Model("Event")
                    {
                        TableName           = "Events",
                        NameSpace           = "CommonLibrary.WebModules.Events",
                        GenerateTable       = true, GenerateCode = true, GenerateTests = true,
                        GenerateUI          = true, GenerateRestApi = true, GenerateFeeds = true, GenerateOrMap = true,
                        IsWebUI             = true,
                        PropertiesSortOrder = 50,
                        Properties          = new List <PropertyInfo>()
                        {
                            new PropertyInfo("Title", typeof(string))
                            {
                                ColumnName = "Title", MinLength = "10", MaxLength = "150", IsRequired = true
                            },
                            new PropertyInfo("Summary", typeof(string))
                            {
                                MaxLength = "200", IsRequired = true
                            },
                            new PropertyInfo("Description", typeof(StringClob))
                            {
                                MinLength = "10", MaxLength = "-1", IsRequired = true
                            },
                            new PropertyInfo("StartDate", typeof(DateTime))
                            {
                                IsRequired = true
                            },
                            new PropertyInfo("EndDate", typeof(DateTime))
                            {
                                IsRequired = true
                            },
                            new PropertyInfo("StartTime", typeof(DateTime)),
                            new PropertyInfo("EndTime", typeof(DateTime)),
                            new PropertyInfo("IsOnline", typeof(bool))
                            {
                                DefaultValue = false
                            },
                            new PropertyInfo("Email", typeof(string))
                            {
                                IsRequired = false, MaxLength = "30", RegEx = "RegexPatterns.Email", IsRegExConst = true
                            },
                            new PropertyInfo("Phone", typeof(string))
                            {
                                IsRequired = false, MaxLength = "20", RegEx = "RegexPatterns.PhoneUS", IsRegExConst = true
                            },
                            new PropertyInfo("Url", typeof(string))
                            {
                                IsRequired = false, MaxLength = "150", RegEx = "RegexPatterns.Url", IsRegExConst = true
                            },
                            new PropertyInfo("Keywords", typeof(string))
                            {
                                MaxLength = "100"
                            }
                        },
                        Inherits = "ModelBase",
                        Includes = new List <Include>()
                        {
                            new Include("RatingPostBase")
                        },
                        ComposedOf = new List <Composition>()
                        {
                            new Composition("Address")
                        },
                        Validations = new List <ValidationItem>()
                        {
                            new ValidationItem("Address", typeof(LocationRule))
                            {
                                IsStatic = false
                            }
                        },
                        DataMassages = new List <DataMassageItem>()
                        {
                            new DataMassageItem("Address", typeof(LocationDataMassager), Massage.AfterValidation)
                            {
                                IsStatic = true
                            }
                        },
                        ExcludeFiles = "Feeds.cs,ImportExport.cs,Serializer.cs"
                    },
                    new Model("Job")
                    {
                        TableName           = "Jobs",
                        NameSpace           = "CommonLibrary.WebModules.Jobs",
                        GenerateTable       = true, GenerateCode = true, GenerateTests = true,
                        GenerateUI          = true, GenerateRestApi = true, GenerateFeeds = true, GenerateOrMap = true,
                        IsWebUI             = true,
                        PropertiesSortOrder = 50,
                        Properties          = new List <PropertyInfo>()
                        {
                            new PropertyInfo("Title", typeof(string))
                            {
                                ColumnName = "Title", MinLength = "10", MaxLength = "150", IsRequired = true
                            },
                            new PropertyInfo("Summary", typeof(string))
                            {
                                MaxLength = "200", IsRequired = true
                            },
                            new PropertyInfo("Description", typeof(StringClob))
                            {
                                MinLength = "10", MaxLength = "-1", IsRequired = true
                            },
                            new PropertyInfo("StartDate", typeof(DateTime))
                            {
                                IsRequired = true
                            },
                            new PropertyInfo("EndDate", typeof(DateTime))
                            {
                                IsRequired = true
                            },
                            new PropertyInfo("StartTime", typeof(DateTime)),
                            new PropertyInfo("EndTime", typeof(DateTime)),
                            new PropertyInfo("IsOnline", typeof(bool))
                            {
                                DefaultValue = false
                            },
                            new PropertyInfo("Email", typeof(string))
                            {
                                IsRequired = false, MaxLength = "30", RegEx = "RegexPatterns.Email", IsRegExConst = true
                            },
                            new PropertyInfo("Phone", typeof(string))
                            {
                                IsRequired = false, MaxLength = "20", RegEx = "RegexPatterns.PhoneUS", IsRegExConst = true
                            },
                            new PropertyInfo("Url", typeof(string))
                            {
                                IsRequired = false, MaxLength = "150", RegEx = "RegexPatterns.Url", IsRegExConst = true
                            },
                            new PropertyInfo("Keywords", typeof(string))
                            {
                                MaxLength = "100"
                            }
                        },
                        Inherits = "ModelBase",
                        Includes = new List <Include>()
                        {
                            new Include("RatingPostBase")
                        },
                        ComposedOf = new List <Composition>()
                        {
                            new Composition("Address")
                        },
                        Validations = new List <ValidationItem>()
                        {
                            new ValidationItem("Address", typeof(LocationRule))
                            {
                                IsStatic = false
                            }
                        },
                        DataMassages = new List <DataMassageItem>()
                        {
                            new DataMassageItem("Address", typeof(LocationDataMassager), Massage.AfterValidation)
                            {
                                IsStatic = true
                            }
                        },
                        ExcludeFiles = "Feeds.cs,ImportExport.cs,Serializer.cs"
                    }
                }
            };

            ModelContext ctx = new ModelContext()
            {
                AllModels = models
            };
            IList <ICodeBuilder> builders = new List <ICodeBuilder>()
            {
                new CodeBuilderWebUI(),
                new CodeBuilderDb(ctx.AllModels.Settings.Connection),
                new CodeBuilderORMHibernate(),
                new CodeBuilderDomain()
            };
            BoolMessage message = CodeBuilder.Process(ctx, builders);
        }
Exemple #36
0
 protected override void EmitPostPublicEventHandlerReturnValueStatements(CodeBuilder b)
 {
     b.AppendLine("retval = CfxV8Value.Unwrap(e.m_returnValue);");
     b.AppendLine("__retval = e.m_returnValue != null || e.m_exception_wrapped != null ? 1 : 0;");
 }
Exemple #37
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("{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}) end)", classInfo.Key, manglingName, paramsString);
                            }
                            else
                            {
                                CodeBuilder.AppendFormat(") this:{0}({1}) end)", 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("{0}", name);
                                return;
                            }
                        }
                    }
                    else
                    {
                        ReportIllegalSymbol(node, symbolInfo);
                    }
                }
            }
            CodeBuilder.Append(name);
        }
Exemple #38
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);
            }
        }
 public override CodeBuilder DecorateCodeBuilder(CodeBuilder incomingBuilder, CodeBuilderContext context)
 {
     return(new AttributeCodeGeneratorReplacingCodeBuilder(context));
 }
Exemple #40
0
 public override void EmitNativeCall(CodeBuilder b, string functionName)
 {
     b.AppendLine("{0}(self, &{1}, {2});",
                  functionName, Arguments[1].VarName, Arguments[2].VarName);
 }
Exemple #41
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)
                {
                    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)
                    {
                        if (IsNewObjMember(name))
                        {
                            CodeBuilder.AppendFormat("{0}(SymbolKind.{1}, newobj, \"{2}\")", isExtern ? "getexterninstance" : "getinstance", sym.Kind.ToString(), name);
                            return;
                        }
                        if (sym.ContainingType == classInfo.SemanticInfo || sym.ContainingType == classInfo.SemanticInfo.OriginalDefinition || classInfo.IsInherit(sym.ContainingType))
                        {
                            if (sym.IsStatic)
                            {
                                CodeBuilder.AppendFormat("{0}(SymbolKind.{1}, {2}, \"{3}\")", isExtern ? "getexternstatic" : "getstatic", sym.Kind.ToString(), classInfo.Key, sym.Name);
                            }
                            else
                            {
                                CodeBuilder.AppendFormat("{0}(SymbolKind.{1}, this, \"{2}\")", isExtern ? "getexterninstance" : "getinstance", sym.Kind.ToString(), 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("{0}(SymbolKind.{1}, {2}, \"{3}\")", isExtern ? "getexternstatic" : "getstatic", sym.Kind.ToString(), classInfo.Key, manglingName);
                            }
                            else
                            {
                                CodeBuilder.AppendFormat("{0}(SymbolKind.{1}, this, \"{2}\")", isExtern ? "getexterninstance" : "getinstance", sym.Kind.ToString(), 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
                {
                    SymbolKind kind;
                    if (IsNewObjMember(name, out kind))
                    {
                        CodeBuilder.AppendFormat("getinstance(SymbolKind.{0}, newobj, \"{1}\")", kind.ToString(), name);
                        return;
                    }
                    ReportIllegalSymbol(node, symbolInfo);
                }
            }
            CodeBuilder.Append(name);
        }
Exemple #42
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))
                {
                    SymbolTable.Instance.AddRequire(ci.Key, require);
                }
                if (ClassInfo.HasAttribute(declSym, "Cs2Lua.IgnoreAttribute"))
                {
                    return;
                }
                if (declSym.IsAbstract)
                {
                    return;
                }
            }

            if (null != node.ExpressionBody)
            {
                StringBuilder curBuilder = ci.CurrentCodeBuilder;
                if (declSym.IsStatic)
                {
                    ci.CurrentCodeBuilder = ci.StaticFunctionCodeBuilder;
                }
                else
                {
                    ci.CurrentCodeBuilder = ci.InstanceFunctionCodeBuilder;
                }

                var mi = new MethodInfo();
                mi.Init(declSym.GetMethod, node.ExpressionBody);
                m_MethodInfoStack.Push(mi);

                string manglingName = NameMangling(declSym.GetMethod);
                CodeBuilder.AppendFormat("{0}{1} = function(this, {2})", GetIndentString(), manglingName, string.Join(",", mi.ParamNames.ToArray()));
                CodeBuilder.AppendLine();
                ++m_Indent;
                CodeBuilder.AppendFormat("{0}return ", GetIndentString());
                IConversionExpression opd = null;
                var oper = m_Model.GetOperation(node.ExpressionBody) as IBlockStatement;
                if (null != oper && oper.Statements.Length == 1)
                {
                    var iret = oper.Statements[0] as IReturnStatement;
                    if (null != iret)
                    {
                        opd = iret.ReturnedValue as IConversionExpression;
                    }
                }
                OutputExpressionSyntax(node.ExpressionBody.Expression, opd);
                CodeBuilder.AppendLine(";");
                --m_Indent;
                CodeBuilder.AppendFormat("{0}end,", GetIndentString());
                CodeBuilder.AppendLine();

                m_MethodInfoStack.Pop();

                ci.CurrentCodeBuilder = curBuilder;
            }
            else
            {
                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))
                            {
                                SymbolTable.Instance.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;
            }
        }
 public abstract void Decompile(CodeBuilder builder);
Exemple #44
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;
                }
                CodeBuilder.AppendFormat("{0}else", 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
            {
                CodeBuilder.AppendFormat("{0}end;", GetIndentString());
                CodeBuilder.AppendLine();
            }

            m_SwitchInfoStack.Pop();
        }
Exemple #45
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))
                {
                    SymbolTable.Instance.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))
                        {
                            SymbolTable.Instance.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("},");
        }
Exemple #46
0
 public override void EmitPreProxyCallStatements(CodeBuilder b, string var)
 {
     b.AppendLine("PinnedObject {0}_pinned = new PinnedObject({0});", var);
     b.AppendLine("var {0}_length = {0} == null ? UIntPtr.Zero : (UIntPtr){0}.LongLength;", var);
 }
Exemple #47
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))
                {
                    SymbolTable.Instance.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 (SymbolTable.Instance.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 = SymbolTable.Instance.IsCs2LuaSymbol(ci.SemanticInfo.BaseType);

            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();
            }
            if (SymbolTable.ForXlua && mi.OutParamNames.Count > 0)
            {
                CodeBuilder.AppendFormat("{0}local {1};", GetIndentString(), string.Join(", ", mi.OutParamNames.ToArray()));
                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();
        }
Exemple #48
0
 public override void EmitPublicEventArgFields(CodeBuilder b, string var)
 {
     b.AppendLine("internal IntPtr[] m_{0};", var);
     b.AppendLine("internal {0}[] m_{1}_managed;", Struct.ClassName, var);
 }
Exemple #49
0
 public override void Decompile(CodeBuilder builder)
 {
     throw new NotImplementedException();
 }
Exemple #50
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(")");
             }
         }
     }
 }
Exemple #51
0
 public void WriteCode(ITemplate tpl, FragmentCodePoint point, CodeBuilder cb)
 {
     cb.AppendLine(ParserUtils.RenderFunctionStringBuilderName + ".Append(" + Expression + ");");
 }
 public void GenerateToJson(CodeBuilder codeBuilder, int indentLevel, StringBuilder appendBuilder, JsonType type, string valueGetter, bool canBeNull, JsonFormat format)
 {
     codeBuilder.MakeAppend(indentLevel, appendBuilder, format);
     codeBuilder.AppendLine(indentLevel, $"builder.AppendDate({valueGetter});");
 }
Exemple #53
0
 public override void EmitRemoteEventArgFields(CodeBuilder b, string var)
 {
     b.AppendLine("internal {0}[] m_{1}_managed;", Struct.RemoteClassName, var);
 }
 public string OnNewObject(CodeBuilder codeBuilder, int indentLevel, Func <string, string> valueSetter)
 {
     codeBuilder.AppendLine(indentLevel, valueSetter("default(DateTime)"));
     return(null);
 }
 public void OnObjectFinished(CodeBuilder codeBuilder, int indentLevel, Func <string, string> valueSetter, string wasSetVariable)
 {
 }
        public override void VisitTryStatement(TryStatementSyntax node)
        {
            if (null != node.Block)
            {
                ClassInfo  ci = m_ClassInfoStack.Peek();
                MethodInfo mi = m_MethodInfoStack.Peek();

                string srcPos         = GetSourcePosForVar(node);
                string retVar         = string.Format("__try_ret_{0}", srcPos);
                string retValVar      = string.Format("__try_retval_{0}", srcPos);
                string handledVar     = string.Format("__catch_handled_{0}", srcPos);
                string catchRetValVar = string.Format("__catch_retval_{0}", srcPos);

                mi.TryCatchUsingOrLoopSwitchStack.Push(true);

                ReturnContinueBreakAnalysis returnAnalysis0 = new ReturnContinueBreakAnalysis();
                returnAnalysis0.RetValVar = retValVar;
                returnAnalysis0.Visit(node.Block);
                mi.TempReturnAnalysisStack.Push(returnAnalysis0);

                if (mi.IsAnonymousOrLambdaMethod)
                {
                    //嵌入函数里的try块不能拆分成方法
                    CodeBuilder.AppendFormat("{0}local({1}, {2}); multiassign({1}, {2}) = dsltry({3}, {1}){{", GetIndentString(), retVar, retValVar, returnAnalysis0.ExistReturnInLoopOrSwitch ? "true" : "false");
                    CodeBuilder.AppendLine();
                    ++m_Indent;
                    ++mi.TryUsingLayer;
                    VisitBlock(node.Block);
                    --mi.TryUsingLayer;
                    --m_Indent;
                    CodeBuilder.AppendFormat("{0}}};", GetIndentString());
                    CodeBuilder.AppendLine();
                }
                else
                {
                    //普通函数里的try块拆分成方法
                    var           dataFlow = m_Model.AnalyzeDataFlow(node.Block);
                    var           ctrlFlow = m_Model.AnalyzeControlFlow(node.Block);
                    List <string> inputs, outputs;
                    string        paramsStr;
                    string        outParamsStr = mi.CalcTryUsingFuncInfo(dataFlow, ctrlFlow, out inputs, out outputs, out paramsStr);

                    returnAnalysis0.OutParamsStr = outParamsStr;

                    string prestr   = ", ";
                    string tryFunc  = string.Format("__try_func_{0}", srcPos);
                    bool   isStatic = mi.SemanticInfo.IsStatic;

                    CodeBuilder.AppendFormat("{0}local({1}, {2}); multiassign({1}, {2}", GetIndentString(), retVar, retValVar);
                    if (!string.IsNullOrEmpty(outParamsStr))
                    {
                        CodeBuilder.Append(prestr);
                        CodeBuilder.Append(outParamsStr);
                    }
                    CodeBuilder.AppendFormat(") = dsltryfunc({0}, {1}, {2}, {3}", retValVar, tryFunc, isStatic ? ci.Key : "this", dataFlow.DataFlowsOut.Length + (string.IsNullOrEmpty(mi.ReturnVarName) ? 1 : 2));
                    if (!string.IsNullOrEmpty(paramsStr))
                    {
                        CodeBuilder.Append(prestr);
                        CodeBuilder.Append(paramsStr);
                    }
                    CodeBuilder.AppendLine("){");
                    ++m_Indent;
                    ++mi.TryUsingLayer;
                    VisitBlock(node.Block);
                    if (outputs.Count > 0 && ctrlFlow.ReturnStatements.Length <= 0)
                    {
                        //return(0)代表非try块里的返回语句
                        CodeBuilder.AppendFormat("{0}return(0", GetIndentString());
                        if (!string.IsNullOrEmpty(outParamsStr))
                        {
                            CodeBuilder.Append(prestr);
                            CodeBuilder.Append(outParamsStr);
                        }
                        CodeBuilder.AppendLine(");");
                    }
                    --mi.TryUsingLayer;
                    --m_Indent;
                    CodeBuilder.AppendFormat("{0}}}options[{1}];", GetIndentString(), mi.CalcTryUsingFuncOptions(dataFlow, ctrlFlow, inputs, outputs));
                    CodeBuilder.AppendLine();
                }

                mi.TempReturnAnalysisStack.Pop();
                mi.TryCatchUsingOrLoopSwitchStack.Pop();

                if (returnAnalysis0.Exist)
                {
                    CodeBuilder.AppendFormat("{0}if({1}){{", GetIndentString(), retVar);
                    CodeBuilder.AppendLine();
                    ++m_Indent;
                    if (null != node.Finally)
                    {
                        VisitFinallyClause(node.Finally);
                    }
                    OutputTryCatchUsingReturn(returnAnalysis0, mi, retValVar);
                    --m_Indent;
                    CodeBuilder.AppendFormat("{0}}};", GetIndentString());
                    CodeBuilder.AppendLine();
                }

                if (node.Catches.Count > 0)
                {
                    CodeBuilder.AppendFormat("{0}local({1}, {2}); {1} = false;", GetIndentString(), handledVar, catchRetValVar);
                    CodeBuilder.AppendLine();
                    foreach (var clause in node.Catches)
                    {
                        ReturnContinueBreakAnalysis returnAnalysis1 = new ReturnContinueBreakAnalysis();
                        returnAnalysis1.RetValVar = null;//catch块代码部分总是包装成一个函数对象
                        returnAnalysis1.Visit(clause.Block);
                        mi.TempReturnAnalysisStack.Push(returnAnalysis1);

                        CodeBuilder.AppendFormat("{0}{1} = dslcatch({2}, {3}, {4},", GetIndentString(), catchRetValVar, handledVar, retValVar, retVar);
                        CodeBuilder.AppendLine();
                        ++m_Indent;
                        ++mi.TryUsingLayer;
                        VisitCatchClause(clause, handledVar);
                        --mi.TryUsingLayer;
                        --m_Indent;
                        CodeBuilder.AppendFormat("{0});", GetIndentString());
                        CodeBuilder.AppendLine();

                        mi.TempReturnAnalysisStack.Pop();

                        if (returnAnalysis1.Exist)
                        {
                            if (null != node.Finally)
                            {
                                VisitFinallyClause(node.Finally);
                            }
                            OutputTryCatchUsingReturn(returnAnalysis1, mi, catchRetValVar);
                        }
                    }
                    if (node.Catches.Count > 1)
                    {
                        if (SymbolTable.EnableTranslationCheck)
                        {
                            Logger.Instance.Log("Translation Warning", "try have multiple catch ! location: {0}", GetSourcePosForLog(node));
                        }
                    }
                }
                if (null != node.Finally)
                {
                    if (returnAnalysis0.Exist)
                    {
                        CodeBuilder.AppendFormat("{0}if(! {1}){{", GetIndentString(), retVar);
                        CodeBuilder.AppendLine();
                        ++m_Indent;
                        VisitFinallyClause(node.Finally);
                        --m_Indent;
                        CodeBuilder.AppendFormat("{0}}};", GetIndentString());
                        CodeBuilder.AppendLine();
                    }
                    else
                    {
                        VisitFinallyClause(node.Finally);
                    }
                }
            }
        }
		public void WriteCode(ITemplate tpl, FragmentCodePoint point, CodeBuilder cb) {
			cb.AppendLine(ParserUtils.RenderFunctionStringBuilderName + ".Append(PositionHelper.CreateStyle(Position, -1, -1));");
		}
Exemple #58
0
        private void GenerateRelationshipProperties()
        {
            CodeBuilder.AppendLine("#region Generated Relationships");
            foreach (var relationship in _entity.Relationships.OrderBy(r => r.PropertyName))
            {
                var propertyName     = relationship.PropertyName.ToSafeName();
                var primaryNamespace = relationship.PrimaryEntity.EntityNamespace;
                var primaryName      = relationship.PrimaryEntity.EntityClass.ToSafeName();
                var primaryFullName  = _entity.EntityNamespace != primaryNamespace
                    ? $"{primaryNamespace}.{primaryName}"
                    : primaryName;

                if (relationship.Cardinality == Cardinality.Many)
                {
                    if (Options.Data.Entity.Document)
                    {
                        CodeBuilder.AppendLine("/// <summary>");
                        CodeBuilder.AppendLine($"/// Gets or sets the navigation collection for entity <see cref=\"{primaryFullName}\" />.");
                        CodeBuilder.AppendLine("/// </summary>");
                        CodeBuilder.AppendLine("/// <value>");
                        CodeBuilder.AppendLine($"/// The the navigation collection for entity <see cref=\"{primaryFullName}\" />.");
                        CodeBuilder.AppendLine("/// </value>");
                    }

                    if (Options.Data.Entity.AddIgnoreMapAttributeOnChildren)
                    {
                        CodeBuilder.AppendLine("[IgnoreMap]");
                    }

                    CodeBuilder.AppendLine($"public virtual ICollection<{primaryFullName}> {propertyName} {{ get; set; }}");
                    CodeBuilder.AppendLine();
                }
                else
                {
                    if (Options.Data.Entity.Document)
                    {
                        CodeBuilder.AppendLine("/// <summary>");
                        CodeBuilder.AppendLine($"/// Gets or sets the navigation property for entity <see cref=\"{primaryFullName}\" />.");
                        CodeBuilder.AppendLine("/// </summary>");
                        CodeBuilder.AppendLine("/// <value>");
                        CodeBuilder.AppendLine($"/// The the navigation property for entity <see cref=\"{primaryFullName}\" />.");
                        CodeBuilder.AppendLine("/// </value>");

                        foreach (var property in relationship.Properties)
                        {
                            CodeBuilder.AppendLine($"/// <seealso cref=\"{property.PropertyName}\" />");
                        }
                    }

                    if (Options.Data.Entity.AddIgnoreMapAttributeOnChildren)
                    {
                        CodeBuilder.AppendLine("[IgnoreMap]");
                    }

                    CodeBuilder.AppendLine($"public virtual {primaryFullName} {propertyName} {{ get; set; }}");
                    CodeBuilder.AppendLine();
                }
            }
            CodeBuilder.AppendLine("#endregion");
            CodeBuilder.AppendLine();
        }
 public ByteCodeVisitor(CodeBuilder builder)
 {
     Builder = builder;
 }
Exemple #60
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();
                    }
                    if (SymbolTable.ForXlua && mi.OutParamNames.Count > 0)
                    {
                        CodeBuilder.AppendFormat("{0}local {1};", GetIndentString(), string.Join(", ", mi.OutParamNames.ToArray()));
                        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}", GetSourcePosForVar(node));
                    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;
                    if (null != exp)
                    {
                        OutputExpressionSyntax(exp, opd);
                    }
                    else
                    {
                        ReportIllegalSymbol(node, symInfo);
                    }
                    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);
            }
        }