private void BuildAddContentPlaceHolderNames(CodeMemberMethod method, string placeHolderID) {
            CodePropertyReferenceExpression propertyExpr = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "ContentPlaceHolders");
            CodeExpressionStatement stmt = new CodeExpressionStatement();
            stmt.Expression = new CodeMethodInvokeExpression(propertyExpr, "Add", new CodePrimitiveExpression(placeHolderID.ToLower(CultureInfo.InvariantCulture)));

            method.Statements.Add(stmt);
        }
        public static List<CodeStatement> GetCodeStatement(this RecordStep step,string dataClassParameter = null)
        {
            List<CodeStatement> codes = new List<CodeStatement>();
            CodeStatement actionCode = null;
            switch (step.Action)
            {
                case BindingFlags.SetProperty:
                    actionCode = getAssignDetailStatement(step, dataClassParameter);
                    break;
                case BindingFlags.InvokeMethod:
                    actionCode = getInvokeDetailStatement(step, dataClassParameter);
                    break;
                default:
                    break;
            }
            if (actionCode != null)
                codes.Add(actionCode);

            if(step.TakeScreenShot)
            {
                CodeExpressionStatement screenShotCode = new CodeExpressionStatement();
                screenShotCode.Expression = new CodeMethodInvokeExpression(
                    new CodeVariableReferenceExpression("SAPTestHelper.Current"),
                    "TakeScreenShot",
                    new CodePrimitiveExpression(step.StepId.ToString() + ".jpg"));
                codes.Add(screenShotCode);
            }
            return codes;
        }
        private static CodeExpressionStatement getInvokeDetailStatement(RecordStep step, string dataClass)
        {
            CodeExpressionStatement statement = new CodeExpressionStatement();
            CodeExpression[] paras;
            if (step.ActionParams != null)
            {
                paras = new CodeExpression[step.ActionParams.Count];
                ///判断是否参数化函数代码
                if(dataClass == null)
                {
                    for (int i = 0; i < step.ActionParams.Count; i++)
                    {
                        paras[i] = new CodePrimitiveExpression(step.ActionParams[i].Value);
                    }
                }
                else
                {
                    for (int i = 0; i < step.ActionParams.Count; i++)
                    {
                        paras[i] = step.ActionParams[i].GetVariableReference(dataClass);
                    }
                }

            }
            else
            {
                paras = new CodeExpression[0];
            }

            CodeMethodInvokeExpression method = new CodeMethodInvokeExpression(step.CompInfo.FindMethod, step.ActionName, paras);
            statement.Expression = method;
            return statement;
        }
        /// <summary>
        /// Generates code in the class area of the transformation class created by the T4 engine.
        /// </summary>
        /// <param name="arguments">The arguments for the directive.</param>
        protected override void Process(IDictionary<string, string> arguments)
        {
            // Don't generate the same code more then once if T4Toolbox.tt happens to be included multiple times
            if (this.directiveProcessed)
            {
                this.Warning("Multiple <#@ include file=\"T4Toolbox.tt\" #> directives were found in the template.");
                return;
            }

            this.References.Add(typeof(TransformationContext).Assembly.Location);

            // Add the following method call to the Initialize method of the generated text template.
            // T4Toolbox.TransformationContext.Initialize(this, this.GenerationEnvironment);
            var initialize = new CodeExpressionStatement(
                new CodeMethodInvokeExpression(
                    new CodeTypeReferenceExpression(typeof(TransformationContext).FullName),
                    "Initialize",
                    new CodeThisReferenceExpression(),
                    new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "GenerationEnvironment")));
            this.LanguageProvider.GenerateCodeFromStatement(initialize, this.PreInitializationCode, null);

            // Add the following method call to the Dispose(bool) method of the generated text template.
            // T4Toolbox.TransformationContext.Cleanup();
            var cleanup = new CodeExpressionStatement(
                new CodeMethodInvokeExpression(
                    new CodeTypeReferenceExpression(typeof(TransformationContext).FullName),
                    "Cleanup"));
            this.LanguageProvider.GenerateCodeFromStatement(cleanup, this.DisposeCode, null);

            this.directiveProcessed = true;
        }
 internal static void AddCallbackImplementation(CodeTypeDeclaration codeClass, string callbackName, string handlerName, string handlerArgs, bool methodHasOutParameters)
 {
     CodeFlags[] parameterFlags = new CodeFlags[1];
     CodeMemberMethod method = AddMethod(codeClass, callbackName, parameterFlags, new string[] { typeof(object).FullName }, new string[] { "arg" }, typeof(void).FullName, null, (CodeFlags) 0);
     CodeEventReferenceExpression left = new CodeEventReferenceExpression(new CodeThisReferenceExpression(), handlerName);
     CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(left, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null));
     CodeStatement[] trueStatements = new CodeStatement[2];
     trueStatements[0] = new CodeVariableDeclarationStatement(typeof(InvokeCompletedEventArgs), "invokeArgs", new CodeCastExpression(typeof(InvokeCompletedEventArgs), new CodeArgumentReferenceExpression("arg")));
     CodeVariableReferenceExpression targetObject = new CodeVariableReferenceExpression("invokeArgs");
     CodeObjectCreateExpression expression4 = new CodeObjectCreateExpression();
     if (methodHasOutParameters)
     {
         expression4.CreateType = new CodeTypeReference(handlerArgs);
         expression4.Parameters.Add(new CodePropertyReferenceExpression(targetObject, "Results"));
     }
     else
     {
         expression4.CreateType = new CodeTypeReference(typeof(AsyncCompletedEventArgs));
     }
     expression4.Parameters.Add(new CodePropertyReferenceExpression(targetObject, "Error"));
     expression4.Parameters.Add(new CodePropertyReferenceExpression(targetObject, "Cancelled"));
     expression4.Parameters.Add(new CodePropertyReferenceExpression(targetObject, "UserState"));
     trueStatements[1] = new CodeExpressionStatement(new CodeDelegateInvokeExpression(new CodeEventReferenceExpression(new CodeThisReferenceExpression(), handlerName), new CodeExpression[] { new CodeThisReferenceExpression(), expression4 }));
     method.Statements.Add(new CodeConditionStatement(condition, trueStatements, new CodeStatement[0]));
 }
		CodeMemberMethod CreateMethod()
		{
			CodeMemberMethod method = new CodeMemberMethod();
			
			// BeginInit method call.
			CodeExpressionStatement statement = new CodeExpressionStatement();
			CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression();
			statement.Expression = methodInvoke;
			
			CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression();
			methodRef.MethodName = "BeginInit";
			
			CodeCastExpression cast = new CodeCastExpression();
			cast.TargetType = new CodeTypeReference();
			cast.TargetType.BaseType = "System.ComponentModel.ISupportInitialize";
			
			CodeFieldReferenceExpression fieldRef = new CodeFieldReferenceExpression();
			fieldRef.FieldName = "pictureBox1";
			fieldRef.TargetObject = new CodeThisReferenceExpression();
			cast.Expression = fieldRef;

			methodRef.TargetObject = cast;
			methodInvoke.Method = methodRef;

			method.Statements.Add(statement);
			return method;
		}
Example #7
0
 private CodeStatement GenerateCallStatementC2J(GMethod method, CodeExpression invokeExpression)
 {
     CodeStatement call;
     if (method.IsConstructor || method.IsVoid)
     {
         call = new CodeExpressionStatement(invokeExpression);
     }
     else
     {
         if (method.ReturnType.IsPrimitive)
         {
             if (method.ReturnType.JVMSubst != null)
             {
                 invokeExpression = new CodeCastExpression(method.ReturnType.CLRReference, invokeExpression);
             }
             call = new CodeMethodReturnStatement(invokeExpression);
         }
         else
         {
             CodeMethodInvokeExpression conversionExpression = CreateConversionExpressionJ2CParam(method.ReturnType,
                                                                                             invokeExpression);
             call = new CodeMethodReturnStatement(conversionExpression);
         }
     }
     return call;
 }
		public override object Serialize (IDesignerSerializationManager manager, object value)
		{
			if (value == null)
				throw new ArgumentNullException ("value");
			if (manager == null)
				throw new ArgumentNullException ("manager");

			if (!(value is Control))
				throw new InvalidOperationException ("value is not a Control");

			object serialized = base.Serialize (manager, value);
			CodeStatementCollection statements = serialized as CodeStatementCollection;
			if (statements != null) { // the root control is serialized to CodeExpression
				ICollection childControls = TypeDescriptor.GetProperties (value)["Controls"].GetValue (value) as ICollection;
				if (childControls.Count > 0) {
					CodeExpression componentRef = base.GetExpression (manager, value);

					CodeStatement statement = new CodeExpressionStatement (
						new CodeMethodInvokeExpression (componentRef, "SuspendLayout"));
					statement.UserData["statement-order"] = "begin";
					statements.Add (statement);
					statement = new CodeExpressionStatement (
						new CodeMethodInvokeExpression (componentRef, "ResumeLayout", 
										new CodeExpression[] { 
											new CodePrimitiveExpression (false) }));
					statement.UserData["statement-order"] = "end";
					statements.Add (statement);
					serialized = statements;
				}
			}
			return serialized;
		}
 private void BuildAddContentPlaceHolderNames(CodeMemberMethod method, string placeHolderID)
 {
     CodePropertyReferenceExpression targetObject = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "ContentPlaceHolders");
     CodeExpressionStatement statement = new CodeExpressionStatement {
         Expression = new CodeMethodInvokeExpression(targetObject, "Add", new CodeExpression[] { new CodePrimitiveExpression(placeHolderID.ToLower(CultureInfo.InvariantCulture)) })
     };
     method.Statements.Add(statement);
 }
Example #10
0
        public static void AddDisposalOfMember(CodeMemberMethod disposeMethod, string memberName)
        {
            CodeBinaryOperatorExpression isnull = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression(memberName), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null));
            CodeExpressionStatement callDispose = new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(memberName), "Dispose"));

            //add dispose code
            disposeMethod.Statements.Add(new CodeConditionStatement(isnull, callDispose));
        }
 public TypescriptExpressionStatement(
     IStatementFactory statementFactory,
     IExpressionFactory expressionFactory,
     CodeExpressionStatement statement,
     CodeGeneratorOptions options)
 {
     _statementFactory = statementFactory;
     _expressionFactory = expressionFactory;
     _statement = statement;
     _options = options;
 }
 public static CodeExpressionStatement Clone(this CodeExpressionStatement statement)
 {
     if (statement == null) return null;
     CodeExpressionStatement s = new CodeExpressionStatement();
     s.EndDirectives.AddRange(statement.EndDirectives);
     s.Expression = statement.Expression.Clone();
     s.LinePragma = statement.LinePragma;
     s.StartDirectives.AddRange(statement.StartDirectives);
     s.UserData.AddRange(statement.UserData);
     return s;
 }
Example #13
0
        Type EmitExpressionStatement(CodeExpressionStatement Expression, bool ForceTypes)
        {
            Depth++;
            Debug("Emitting expression statement");
            Type Generated = EmitExpression(Expression.Expression, ForceTypes);

            if (Generated != typeof(void))
                Generator.Emit(OpCodes.Pop);

            Depth--;

            return Generated;
        }
Example #14
0
		public void GetKeywordFromCodeDom()
		{
			CodeStatement st = new CodeExpressionStatement(new CodeArgumentReferenceExpression("foo"));
			CodeExpression exp = new CodeArgumentReferenceExpression("foo");
			CodeIterationStatement it = new CodeIterationStatement(st, exp, st);

			CodeConditionStatement cond = new CodeConditionStatement(exp);

			new Microsoft.CSharp.CSharpCodeProvider().GenerateCodeFromStatement(
				it, Console.Out, new System.CodeDom.Compiler.CodeGeneratorOptions());
			new Microsoft.CSharp.CSharpCodeProvider().GenerateCodeFromStatement(
				cond, Console.Out, new System.CodeDom.Compiler.CodeGeneratorOptions());

			new Microsoft.VisualBasic.VBCodeProvider().GenerateCodeFromStatement(
				it, Console.Out, new System.CodeDom.Compiler.CodeGeneratorOptions());
			new Microsoft.VisualBasic.VBCodeProvider().GenerateCodeFromStatement(
				cond, Console.Out, new System.CodeDom.Compiler.CodeGeneratorOptions());
		}
 internal static void CreatePropertySetStatements(CodeStatementCollection methodStatements, CodeStatementCollection statements, CodeExpression target, string targetPropertyName, Type destinationType, CodeExpression value, CodeLinePragma linePragma)
 {
     bool flag = false;
     if (destinationType == null)
     {
         flag = true;
     }
     if (flag)
     {
         CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression();
         CodeExpressionStatement statement = new CodeExpressionStatement(expression) {
             LinePragma = linePragma
         };
         expression.Method.TargetObject = new CodeCastExpression(typeof(IAttributeAccessor), target);
         expression.Method.MethodName = "SetAttribute";
         expression.Parameters.Add(new CodePrimitiveExpression(targetPropertyName));
         expression.Parameters.Add(GenerateConvertToString(value));
         statements.Add(statement);
     }
     else if (destinationType.IsValueType)
     {
         CodeAssignStatement statement2 = new CodeAssignStatement(BuildPropertyReferenceExpression(target, targetPropertyName), new CodeCastExpression(destinationType, value)) {
             LinePragma = linePragma
         };
         statements.Add(statement2);
     }
     else
     {
         CodeExpression expression2;
         if (destinationType == typeof(string))
         {
             expression2 = GenerateConvertToString(value);
         }
         else
         {
             expression2 = new CodeCastExpression(destinationType, value);
         }
         CodeAssignStatement statement3 = new CodeAssignStatement(BuildPropertyReferenceExpression(target, targetPropertyName), expression2) {
             LinePragma = linePragma
         };
         statements.Add(statement3);
     }
 }
        private CodeStatement GetOutputWriteStatement(CodeExpression expr, bool encode) {

            // Call HttpUtility.HtmlEncode on the expression if needed
            if (encode) {
                expr = new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(
                        new CodeTypeReferenceExpression(typeof(HttpUtility)),
                       "HtmlEncode"),
                    expr);
            }

            CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression();
            CodeExpressionStatement call = new CodeExpressionStatement(methodInvoke);
            methodInvoke.Method.TargetObject = new CodeArgumentReferenceExpression(renderMethodParameterName);
            methodInvoke.Method.MethodName = "Write";

            methodInvoke.Parameters.Add(expr);

            return call;
        }
        //Create main method
        private void CreateEntryPoint(List<string> statements)
        {
            //Create an object and assign the name as "Main"
            CodeEntryPointMethod mymain = new CodeEntryPointMethod();
            mymain.Name = "Main";
            //Mark the access modifier for the main method as Public and //static
            mymain.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            //Change string to statements
            if(statements != null){

                foreach (string item in statements) {
                    if (item != null) {
                        CodeSnippetExpression exp1 = new CodeSnippetExpression(@item);
                        CodeExpressionStatement ces1 = new CodeExpressionStatement(exp1);
                        mymain.Statements.Add(ces1);
                    }
                }
            }
            myclass.Members.Add(mymain);
        }
 private void AddOutputWriteStringStatement(CodeStatementCollection methodStatements, string s)
 {
     if (!this.UseResourceLiteralString(s))
     {
         this.AddOutputWriteStatement(methodStatements, new CodePrimitiveExpression(s), null);
     }
     else
     {
         int num;
         int num2;
         bool flag;
         base._stringResourceBuilder.AddString(s, out num, out num2, out flag);
         CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression();
         CodeExpressionStatement statement = new CodeExpressionStatement(expression);
         expression.Method.TargetObject = new CodeThisReferenceExpression();
         expression.Method.MethodName = "WriteUTF8ResourceString";
         expression.Parameters.Add(new CodeArgumentReferenceExpression("__w"));
         expression.Parameters.Add(new CodePrimitiveExpression(num));
         expression.Parameters.Add(new CodePrimitiveExpression(num2));
         expression.Parameters.Add(new CodePrimitiveExpression(flag));
         methodStatements.Add(statement);
     }
 }
Example #19
0
        public void CreateEntryPoint(ref CodeTypeDeclaration customClass)
        {
            //Create an object and assign the name as “Main”
            CodeEntryPointMethod main = new CodeEntryPointMethod();
            main.Name = "Main";

            //Mark the access modifier for the main method as Public and //static
            main.Attributes = MemberAttributes.Public | MemberAttributes.Static;

            //Provide defenition to the main method.
            //Create an object of the “Cmyclass” and invoke the method
            //by passing the required parameters.
            CodeSnippetExpression exp = new CodeSnippetExpression(CallingMethod(customClass));

            //Create expression statements for the snippets
            CodeExpressionStatement ces = new CodeExpressionStatement(exp);

            //Add the expression statements to the main method.
            main.Statements.Add(ces);

            //Add the main method to the class
            customClass.Members.Add(main);
        }
Example #20
0
        CodeExpressionStatement[] ParseMultiExpression(string code)
        {
            var tokens = SplitTokens(code);

            #region Date/time

            int n = tokens.Count - 2;
            if (tokens.Count > 1 && ((string)tokens[n]).Length > 0 && ((string)tokens[n])[0] == Multicast)
            {
                string arg = ((string)tokens[n + 1]).ToUpperInvariant().Trim();
                arg = arg.Length == 1 ? arg : arg.TrimEnd('S');

                switch (arg)
                {
                    case "S":
                    case "SECOND":
                    case "M":
                    case "MINUTE":
                    case "H":
                    case "HOUR":
                    case "D":
                    case "DAY":
                        return new[] { new CodeExpressionStatement(ParseDateExpression(code)) };
                }
            }

            #endregion

            var result = ParseMultiExpression(tokens.ToArray());
            var statements = new CodeExpressionStatement[result.Length];

            for (int i = 0; i < result.Length; i++)
                statements[i] = new CodeExpressionStatement(result[i]);

            return statements;
        }
		protected override void GenerateExpressionStatement(CodeExpressionStatement e)
		{
			Output.Write("[CodeExpressionStatement:");
			base.GenerateExpression(e.Expression);
			Output.WriteLine("]");
		}
Example #22
0
 /// <summary>
 /// Execute one expression as statement.
 /// </summary>
 public CodeExpressionStatement Add(CodeExpression expr)
 {
     CodeExpressionStatement st = new CodeExpressionStatement(expr);
     csc.Add(st);
     return st;
 }
        /// <summary>
        /// 构造一个命名空间
        /// </summary>
        /// <returns>code</returns>
        static CodeNamespace CreateMimsyNamespace()
        {
            // 定义命名空间
            CodeNamespace mimsyNamespace = new CodeNamespace("Mimsy");
            // 添加引用
            mimsyNamespace.Imports.AddRange(new[]
            {
               new CodeNamespaceImport("System"),
               new CodeNamespaceImport("System.Text"),
               new CodeNamespaceImport("System.Collections")
            });

            // 定义类
            CodeTypeDeclaration jubjubClass = new CodeTypeDeclaration("Jubjub")
            {
                TypeAttributes = TypeAttributes.Public  // NotPublic = internal, the internal type isn't visible to the dynamic binder
            };

            // 定义成员字段
            CodeMemberField wabeCountFld = new CodeMemberField(typeof(int), "_wabeCount")
            {
                Attributes = MemberAttributes.Private
            };

            jubjubClass.Members.Add(wabeCountFld);  // 附加字段到类
            mimsyNamespace.Types.Add(jubjubClass);  // 附加类到命名空间

            // 定义实例构造函数
            CodeConstructor jubjubCtor = new CodeConstructor
            {
                Attributes = MemberAttributes.Public
            };

            // 定义参数
            var para = new CodeParameterDeclarationExpression(typeof(int), "wabeCount");
            jubjubCtor.Parameters.Add(para);  // 附加参数到构造函数

            // 添加 ArrayList 字段
            var typerefArrayList = new CodeTypeReference("ArrayList");
            CodeMemberField updatesFld = new CodeMemberField(typerefArrayList, "_updates");
            jubjubClass.Members.Add(updatesFld);

            // 引用 _updates 字段
            var refUpdatesFld = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_updates");
            // 实例化 ArrayList
            var newArrayList = new CodeObjectCreateExpression(typerefArrayList);
            // 赋值
            var assignUpdates = new CodeAssignStatement(refUpdatesFld, newArrayList);
            jubjubCtor.Statements.Add(assignUpdates); // 附加赋值语句到构造函数

            // 引用 _wabeCount 字段
            var refWabeCountFld = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_wabeCount");
            // 定义引用属性(用于赋值时进行判断)
            var refWabeCountProp = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "WabeCount");
            // 定义引用参数
            var refWabeCountArg = new CodeArgumentReferenceExpression("wabeCount");
            // 定义赋值语句
            var assignWabeCount = new CodeAssignStatement(refWabeCountProp, refWabeCountArg);

            jubjubCtor.Statements.Add(assignWabeCount);  // 附加赋值语句到构造函数

            jubjubClass.Members.Add(jubjubCtor);    // 附加构造函数到类

            // 定义成员属性
            CodeMemberProperty wabeCountProp = new CodeMemberProperty()
            {
                Attributes = MemberAttributes.Public | MemberAttributes.Final, // Final == Nonvirtual
                Type = new CodeTypeReference(typeof(int)),
                Name = "WabeCount"
            };
            // 为属性添加 get 语句
            wabeCountProp.GetStatements.Add(new CodeMethodReturnStatement(refWabeCountFld));

            // 为属性添加 set 语句
            var suppliedPropertyValue = new CodePropertySetValueReferenceExpression();  // value
            var zero = new CodePrimitiveExpression(0);
            var suppliedPropValIsLessThanZero = new CodeBinaryOperatorExpression(suppliedPropertyValue, CodeBinaryOperatorType.LessThan, zero);

            // if/else 语句进行赋值判断, CodeDOM 不支持三元运算表达式 (value < 0) ? 0 : value;
            var testSuppliedPropValAndAssign = new CodeConditionStatement(suppliedPropValIsLessThanZero,
                new CodeStatement[]
                {
                    new CodeAssignStatement(refWabeCountFld,zero)
                },
                new CodeStatement[]
                {
                    new CodeAssignStatement(refWabeCountFld,suppliedPropertyValue)
                });
            wabeCountProp.SetStatements.Add(testSuppliedPropValAndAssign);
            wabeCountProp.SetStatements.Add(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(refUpdatesFld, "Add"), refWabeCountFld));

            jubjubClass.Members.Add(wabeCountProp);  // 附加属性到类

            // 定义一个方法
            CodeMemberMethod methGetWabeCountHistory = new CodeMemberMethod
            {
                Attributes = MemberAttributes.Public | MemberAttributes.Final,
                Name = "GetWabeCountHistory",
                ReturnType = new CodeTypeReference(typeof(string))
            };

            jubjubClass.Members.Add(methGetWabeCountHistory);  // 附加方法到类

            // 定义本地变量并实例化
            methGetWabeCountHistory.Statements.Add(new CodeVariableDeclarationStatement("StringBuilder", "result"));
            var refResultVar = new CodeVariableReferenceExpression("result");
            methGetWabeCountHistory.Statements.Add(new CodeAssignStatement(refResultVar, new CodeObjectCreateExpression("StringBuilder")));

            // 定义本地变量 ndx
            methGetWabeCountHistory.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "ndx"));
            // 引用本地变量 ndx
            var refNdxVar = new CodeVariableReferenceExpression("ndx");

            #region  创建 for 语句

            // 赋值语句 ndx = 0
            var initNdxVar = new CodeAssignStatement(refNdxVar, new CodePrimitiveExpression(0));
            // 条件语句  ndx < this._updates.Count
            var testNdxWithUpdatesCount = new CodeBinaryOperatorExpression(refNdxVar, CodeBinaryOperatorType.LessThan,
                new CodePropertyReferenceExpression(refUpdatesFld, "Count"));
            // 自增语句
            var incrementNdxVar = new CodeAssignStatement(refNdxVar,
                new CodeBinaryOperatorExpression(refNdxVar, CodeBinaryOperatorType.Add,
                    new CodePrimitiveExpression(1)));
            // 比较 if(ndx == 0)
            var compareNdxWithZero = new CodeBinaryOperatorExpression(refNdxVar, CodeBinaryOperatorType.ValueEquality,
                new CodePrimitiveExpression(0));
            // 方法调用 result.AppendFormat("{0}", this._updates[ndx])
            var methAppendFormatInvoke = new CodeExpressionStatement(
                new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(refResultVar, "AppendFormat"),
                    new CodePrimitiveExpression("{0}"),
                    new CodeArrayIndexerExpression(refUpdatesFld, refNdxVar)
                    )
                  );
            // 方法调用 result.AppendFormat(", {0}", this._updates[ndx])
            var methAppendFormtInvokeWithCommas = new CodeExpressionStatement(
            new CodeMethodInvokeExpression(
                new CodeMethodReferenceExpression(refResultVar, "AppendFormat"),
                new CodePrimitiveExpression(", {0}"),
                new CodeArrayIndexerExpression(refUpdatesFld, refNdxVar)
                )
              );

            methGetWabeCountHistory.Statements.Add(
                new CodeIterationStatement(initNdxVar, testNdxWithUpdatesCount, incrementNdxVar,
                    new CodeConditionStatement(compareNdxWithZero,
                        new CodeStatement[] { methAppendFormatInvoke },
                        new CodeStatement[] { methAppendFormtInvokeWithCommas })));

            #endregion

            // 定义返回值
            methGetWabeCountHistory.Statements.Add(
                new CodeMethodReturnStatement(
                    new CodeMethodInvokeExpression(
                        new CodeMethodReferenceExpression(refResultVar, "ToString"))));

            return mimsyNamespace;
        }
        private void GenerateAppEntryPoint()
        {
            if (ApplicationFile.Length > 0)
            {

                // [STAThread]
                // public static void Main () {
                //
                CodeMemberMethod cmmMain = GenerateEntryPointMethod();

                if (cmmMain != null)
                {
                    CodeVariableReferenceExpression cvreSplashScreen = null;
                    if (!string.IsNullOrEmpty(_splashImage) && !HostInBrowser)
                    {
                        cvreSplashScreen = GenerateSplashScreenInstance(cmmMain);
                    }

                    //   MyApplication app = new MyApplication();
                    //
                    CodeVariableReferenceExpression cvreApp = GenerateAppInstance(cmmMain);

                    if (_ccRoot.InitializeComponentFn != null)
                    {
                        //   app.InitializeComponent();
                        //
                        CodeMethodInvokeExpression cmieIT = new CodeMethodInvokeExpression();
                        cmieIT.Method = new CodeMethodReferenceExpression(cvreApp, INITIALIZE_COMPONENT);
                        cmmMain.Statements.Add(new CodeExpressionStatement(cmieIT));
                    }

                    if (!HostInBrowser)
                    {
                        //   app.Run();
                        //
                        CodeMethodReferenceExpression cmreRun = new CodeMethodReferenceExpression(cvreApp, "Run");
                        CodeMethodInvokeExpression cmieRun = new CodeMethodInvokeExpression();
                        cmieRun.Method = cmreRun;

                        CodeStatement csRun = new CodeExpressionStatement(cmieRun);
                        cmmMain.Statements.Add(csRun);
                    }

                    _ccRoot.CodeClass.Members.Add(cmmMain);
                }
            }
        }
        private void GenerateInitializeComponent(bool isApp)
        {
            // public void InitializeComponent()
            // {
            //
            CodeMemberMethod cmmLC = _ccRoot.InitializeComponentFn;

            if (cmmLC == null)
            {
                cmmLC = _ccRoot.EnsureInitializeComponentFn;
                if (!isApp)
                {
                    cmmLC.ImplementationTypes.Add(new CodeTypeReference(KnownTypes.Types[(int)KnownElements.IComponentConnector]));
                }
            }

            //     if (_contentLoaded)
            //     {
            //         return;
            //     }
            //
            CodeConditionStatement ccsCL = new CodeConditionStatement();
            ccsCL.Condition = new CodeFieldReferenceExpression(null, CONTENT_LOADED);
            ccsCL.TrueStatements.Add(new CodeMethodReturnStatement());
            if (!isApp)
            {
                cmmLC.Statements.Add(ccsCL);
            }
            else
            {
                cmmLC.Statements.Insert(0, ccsCL);
            }

            //     _contentLoaded = true;
            //
            CodeAssignStatement casCL = new CodeAssignStatement(new CodeFieldReferenceExpression(null, CONTENT_LOADED),
                                                                new CodePrimitiveExpression(true));
            if (!isApp)
            {
                cmmLC.Statements.Add(casCL);
            }
            else
            {
                cmmLC.Statements.Insert(1, casCL);
            }

            // Generate canonicalized string as resource id.
            bool requestExtensionChange = false;
            string resourceID = ResourcesGenerator.GetResourceIdForResourceFile(
                    SourceFileInfo.RelativeSourceFilePath + XAML, 
                    SourceFileInfo.OriginalFileLinkAlias, 
                    SourceFileInfo.OriginalFileLogicalName,
                    TargetPath,
                    Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar,
                    requestExtensionChange);
            
            string uriPart = string.Empty;

            string version = String.IsNullOrEmpty(AssemblyVersion) ? String.Empty : COMPONENT_DELIMITER + VER + AssemblyVersion;
            string token = String.IsNullOrEmpty(AssemblyPublicKeyToken) ? String.Empty : COMPONENT_DELIMITER + AssemblyPublicKeyToken;
            uriPart = FORWARDSLASH + AssemblyName + version + token + COMPONENT_DELIMITER + COMPONENT + FORWARDSLASH + resourceID;

            //
            //  Uri resourceLocator = new Uri(uriPart, UriKind.Relative);
            //
            string resVarname = RESOURCE_LOCATER;

            CodeFieldReferenceExpression cfreRelUri = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(System.UriKind)), "Relative");

            CodeExpression[] uriParams = { new CodePrimitiveExpression(uriPart), cfreRelUri };
            CodeObjectCreateExpression coceResourceLocator = new CodeObjectCreateExpression(typeof(System.Uri), uriParams);
            CodeVariableDeclarationStatement cvdsresLocator = new CodeVariableDeclarationStatement(typeof(System.Uri), resVarname, coceResourceLocator);

            cmmLC.Statements.Add(cvdsresLocator);

            //
            //  System.Windows.Application.LoadComponent(this, resourceLocator);
            //
            CodeMethodReferenceExpression cmreLoadContent = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(KnownTypes.Types[(int)KnownElements.Application]), LOADCOMPONENT);
            CodeMethodInvokeExpression cmieLoadContent = new CodeMethodInvokeExpression();

            cmieLoadContent.Method = cmreLoadContent;

            CodeVariableReferenceExpression cvreMemStm = new CodeVariableReferenceExpression(resVarname);

            cmieLoadContent.Parameters.Add(new CodeThisReferenceExpression());
            cmieLoadContent.Parameters.Add(cvreMemStm);

            CodeExpressionStatement cesLC = new CodeExpressionStatement(cmieLoadContent);
            AddLinePragma(cesLC, 1);
            cmmLC.Statements.Add(cesLC);

            // private bool _contentLoaded;
            //
            CodeMemberField cmfCL = new CodeMemberField();
            cmfCL.Name = CONTENT_LOADED;
            cmfCL.Attributes = MemberAttributes.Private;
            cmfCL.Type = new CodeTypeReference(typeof(bool));
            _ccRoot.CodeClass.Members.Add(cmfCL);

            if (!isApp)
            {
                // Make sure that ICC.Connect is generated to avoid compilation errors
                EnsureHookupFn();
            }
        }
        private CodeStatement AddCLREvent(Type eventTarget, CodeContext cc, CodeExpression ce, MarkupEventInfo mei)
        {

            bool subClassed = _ccRoot.SubClass.Length > 0;
            CodeStatement csEvent = null;
            // param2: <FooEventHandler>
            CodeExpression cDelExp = GetEventDelegate(cc, mei.mi, mei.eventName, mei.eventHandler);

            if (mei.mi.DeclaringType.IsAssignableFrom(eventTarget))
            {
                // _element.FooEvent += new FooEventHandlerDelegate(OnFoo);
                csEvent = new CodeAttachEventStatement(ce, mei.eventName, cDelExp);
            }
            else if (eventTarget == null || // for known attached events on unknown local tags
                     KnownTypes.Types[(int)KnownElements.UIElement].IsAssignableFrom(eventTarget) ||
                     KnownTypes.Types[(int)KnownElements.ContentElement].IsAssignableFrom(eventTarget))
            {
                // _element.AddHandler(FooEvent, new FooEventHandlerDelegate(OnFoo));
                CodeFieldReferenceExpression cfreEvent = GetEvent(mei.mi, mei.eventName, mei.eventHandler);
                CodeMethodInvokeExpression cmieAddHandler = new CodeMethodInvokeExpression(ce, ADDHANDLER, cfreEvent, cDelExp);
                csEvent = new CodeExpressionStatement(cmieAddHandler);
            }
            else
            {
                string eventTargetName = eventTarget != null ? eventTarget.FullName : cc.LocalElementFullName;
                ThrowCompilerException(SRID.UnknownEventAttribute, mei.eventName, mei.eventHandler, eventTargetName);
            }

            // When x:SubClass is used, event handlers can be specified in a code-behind file, under this sub class.
            // But these handler methods need to be accessible from the intermediary generated sub class. So an empty
            // internal virtual method with the same signature as the handler method is generated in this intermediary
            // sub class (in the generated file):
            //
            //      internal virtual void OnFooEvent(object sender, FooEventArgs ea)
            //      {
            //      }
            //
            // Since a delegate cannot take the address of a virtual function, a non-virtual helper function
            // with the same signature as the above function & which calls the above function is also generated:
            //
            //      private void OnFooEventHelper(object sender, FooEventArgs ea)
            //      {
            //          OnFooEvent(sender, ea);
            //      }
            //
            // All this is done only if x:Subclass is specified, since this means that this sub class would need to be
            // defined in a code-behind file. This also means that inline events (in <x:Code>) will not be supported.

            if (subClassed)
            {
                GenerateProtectedEventHandlerMethod(mei);
            }

            AddLinePragma(csEvent, mei.lineNumber);
            return csEvent;
        }
Example #27
0
		protected override void GenerateExpressionStatement (CodeExpressionStatement e)
		{
		}
 internal override CodeStatement Clone()
 {
     CodeExpressionStatement newStatement = new CodeExpressionStatement();
     newStatement.Expression = RuleExpressionWalker.Clone(exprStatement.Expression);
     return newStatement;
 }
 private ExpressionStatement(CodeExpressionStatement exprStatement)
 {
     this.exprStatement = exprStatement;
 }
Example #30
0
        void Statements(List<CodeLine> lines)
        {
            for (int i = 0; i < lines.Count; i++)
            {
                #region Line

                string code = lines[i].Code;

                if (string.IsNullOrEmpty(code))
                    continue;

                line = lines[i].LineNumber;
                fileName = lines[i].FileName;

                #endregion

                #region Blocks

                var parent = blocks.Count > 0 ? blocks.Peek().Statements : main.Statements;
                string codeTrim = code.TrimStart(Spaces);
                int blocksCount = -1;

                if (codeTrim.Length > 0)
                {
                    CodeBlock block;
                    char sym = codeTrim[0];
                    bool skip = false;

                    switch (sym)
                    {
                        case BlockOpen:
                            if (blocks.Count == 0)
                            {
                                block = new CodeBlock(lines[i], Scope, new CodeStatementCollection(), CodeBlock.BlockKind.Dummy, blocks.Count == 0 ? null : blocks.Peek());
                                CloseTopSingleBlock();
                                blocks.Push(block);
                            }
                            block = blocks.Peek();
                            if (block.Type == CodeBlock.BlockType.Expect)
                                block.Type = CodeBlock.BlockType.Within;
                            skip = true;
                            break;

                        case BlockClose:
                            if (blocks.Count == 0)
                                throw new ParseException(ExUnexpected, lines[i]);
                            CloseBlock();
                            skip = true;
                            break;

                        default:
                            if (blocks.Count > 0 && blocks.Peek().Type == CodeBlock.BlockType.Expect)
                            {
                                blocksCount = blocks.Count;
                                block = blocks.Peek();
                                block.Type = CodeBlock.BlockType.Within;
                                block.Level = blocksCount;
                            }
                            break;
                    }

                    if (skip)
                    {
                        code = codeTrim.Substring(1);
                        if (code.Length == 0)
                            continue;
                        lines[i].Code = code;
                    }
                }

                codeTrim = null;

                #endregion

                #region Tokens

                var token = GetToken(code);

                try
                {
                    switch (token)
                    {
                        case Token.Assign:
                            var assign = ParseAssign(code);
                            assign.LinePragma = lines[i];
                            parent.Add(assign);
                            break;

                        case Token.Command:
                            var command = new CodeExpressionStatement(OptimiseExpression(ParseCommand(code)));

                            if (command.Expression == null)
                                continue;

                            command.LinePragma = lines[i];
                            parent.Add(command);
                            break;

                        case Token.Label:
                            var label = new CodeExpressionStatement(ParseLabel(lines[i]));
                            label.LinePragma = lines[i];
                            parent.Add(label);
                            break;

                        case Token.Hotkey:
                            var hotkey = ParseHotkey(lines, i);
                            hotkey.LinePragma = lines[i];
                            parent.Add(hotkey);
                            break;

                        case Token.Flow:
                            {
                                var result = ParseFlow(lines, i);
                                if (result != null)
                                {
                                    for (int n = 0; n < result.Length; n++)
                                        result[n].LinePragma = lines[i];
                                    parent.AddRange(result);
                                }
                            }
                            break;

                        case Token.Expression:
                            {
                                int n = i + 1;
                                if (IsFunction(code, n < lines.Count ? lines[n].Code : string.Empty))
                                    ParseFunction(lines[i]);
                                else
                                {
                                    var statements = ParseMultiExpression(code);

                                    for (n = 0; n < statements.Length; n++)
                                    {
                                        var expr = OptimiseLoneExpression(statements[n].Expression);

                                        if (expr == null)
                                            continue;
                                        else
                                            statements[n] = new CodeExpressionStatement(expr);

                                        statements[n].LinePragma = lines[n];
                                        parent.Add(statements[n]);
                                    }
                                }
                            }
                            break;

                        case Token.Directive:
                            ParseDirective(code);
                            break;

                        case Token.Unknown:
                        default:
                            throw new ParseException(ExUnexpected, lines[i]);
                    }
                }
#if !DEBUG
                catch (ParseException e)
                {
                    throw new ParseException(e.Message, lines[i]);
                }
#endif
                finally { }

                #endregion

                #region Blocks

                if (blocks.Count == blocksCount && blocks.Peek().IsSingle)
                    CloseBlock(blocksCount, blocks.Count > blocksCount && blocksCount != -1);

                #endregion
            }

            #region Blocks

            CloseTopSingleBlocks();
            CloseTopLabelBlock();
            CloseTopSingleBlocks();
            CloseSingleLoopBlocks();

            if (blocks.Count > 0)
                throw new ParseException(ExUnclosedBlock, blocks.Peek().Line);

            #endregion
        }
Example #31
0
 protected override void GenerateExpressionStatement(System.CodeDom.CodeExpressionStatement e)
 {
     GenerateExpression(e.Expression);
     Output.WriteLine(";");
 }