public TypescriptBaseReferenceExpression(
     CodeBaseReferenceExpression codeExpression, 
     CodeGeneratorOptions options)
 {
     _codeExpression = codeExpression;
     _options = options;
     System.Diagnostics.Debug.WriteLine("TypescriptBaseReferenceExpression Created");
 }
Example #2
0
 private void ValidateBaseReferenceExpression(CodeBaseReferenceExpression e) { // Nothing to validate
 }
		public void FixupAsync ()
		{
			var type = ml_context.ChannelType;
			var od = context.Operation;

			var baseExpr = new CodeBaseReferenceExpression ();
			var asyncResultType = new CodeTypeReference (typeof (IAsyncResult));

			// BeginXxx() implementation
			var cm = new CodeMemberMethod {
				Name = "Begin" + od.Name,
				// Analysis disable BitwiseOperatorOnEnumWithoutFlags
				Attributes = MemberAttributes.Public | MemberAttributes.Final,
				// Analysis restore BitwiseOperatorOnEnumWithoutFlags
				ReturnType = asyncResultType
				};
			type.Members.Add (cm);

			var inArgs = new List<CodeParameterDeclarationExpression > ();
			foreach (CodeParameterDeclarationExpression p in context.BeginMethod.Parameters) {
				inArgs.Add (p);
				cm.Parameters.Add (p);
			}
			inArgs.RemoveAt (inArgs.Count - 1);
			inArgs.RemoveAt (inArgs.Count - 1);

			var call = new CodeMethodInvokeExpression (
				baseExpr,
				"BeginInvoke",
				new CodePrimitiveExpression (od.Name),
				new CodeArrayCreateExpression (typeof (object), inArgs.ConvertAll<CodeExpression> (decl => new CodeArgumentReferenceExpression (decl.Name)).ToArray ()),
				new CodeArgumentReferenceExpression ("asyncCallback"),
				new CodeArgumentReferenceExpression ("userState"));
			cm.Statements.Add (new CodeMethodReturnStatement (call));

			// EndXxx() implementation

			cm = new CodeMemberMethod {
				Name = "End" + od.Name,
				// Analysis disable BitwiseOperatorOnEnumWithoutFlags
				Attributes = MemberAttributes.Public | MemberAttributes.Final,
				// Analysis restore BitwiseOperatorOnEnumWithoutFlags
				ReturnType = context.EndMethod.ReturnType };
			type.Members.Add (cm);

			AddMethodParam (cm, typeof (IAsyncResult), "result");

			var outArgs = new List<CodeParameterDeclarationExpression > ();

			string resultArgName = "result";
			var argsDecl = new CodeVariableDeclarationStatement (
				typeof (object []),
				"args",
				new CodeArrayCreateExpression (typeof (object), new CodePrimitiveExpression (outArgs.Count)));
			cm.Statements.Add (argsDecl);

			var ret = new CodeMethodInvokeExpression (
				baseExpr,
				"EndInvoke",
				new CodePrimitiveExpression (od.Name),
				new CodeVariableReferenceExpression ("args"),
				new CodeArgumentReferenceExpression (resultArgName));
			if (cm.ReturnType.BaseType == "System.Void")
				cm.Statements.Add (new CodeExpressionStatement (ret));
			else
				cm.Statements.Add (new CodeMethodReturnStatement (new CodeCastExpression (context.EndMethod.ReturnType, ret)));
		}
Example #4
0
		protected override void GenerateBaseReferenceExpression (CodeBaseReferenceExpression e)
		{
		}
Example #5
0
 protected override void GenerateBaseReferenceExpression(CodeBaseReferenceExpression e)
 {
     base.Output.Write("MyBase");
 }
		public override void BuildCodeDomTree (CodeCompileUnit compileUnit)
		{
         
			CodeThisReferenceExpression @this = new CodeThisReferenceExpression ();
			CodeBaseReferenceExpression @base = new CodeBaseReferenceExpression ();
			CodeTypeReferenceExpression thisType = new CodeTypeReferenceExpression (new CodeTypeReference (GeneratedTypeName));
			CodeTypeReference uriType = new CodeTypeReference (typeof(Uri));

			CodeMemberField executableField = new CodeMemberField {
            Name = "_Executable",
            Type = new CodeTypeReference(typeof(XsltExecutable)),
            Attributes = MemberAttributes.Private | MemberAttributes.Static
         };

			// methods

			// cctor
			CodeTypeConstructor cctor = new CodeTypeConstructor {
            CustomAttributes = { 
               new CodeAttributeDeclaration(DebuggerNonUserCodeTypeReference)
            }
         };

			CodeVariableDeclarationStatement procVar = new CodeVariableDeclarationStatement {
            Name = "proc",
            Type = new CodeTypeReference(typeof(IXsltProcessor)),
            InitExpression = new CodeIndexerExpression {
               TargetObject = new CodePropertyReferenceExpression {
                  PropertyName = "Xslt",
                  TargetObject = new CodeTypeReferenceExpression(typeof(Processors))
               },
               Indices = { 
                  new CodePrimitiveExpression(parser.ProcessorName)
               }
            } 
         };

			CodeVariableDeclarationStatement sourceVar = new CodeVariableDeclarationStatement {
            Name = "source",
            Type = new CodeTypeReference(typeof(Stream)),
            InitExpression = new CodePrimitiveExpression(null)
         };

			CodeVariableDeclarationStatement sourceUriVar = new CodeVariableDeclarationStatement {
            Name = "sourceUri",
            Type = uriType,
            InitExpression = new CodeObjectCreateExpression {
               CreateType = uriType,
               Parameters = {
                  new CodePrimitiveExpression(ValidatorUri.AbsoluteUri)
               }
            }
         };

			CodeVariableDeclarationStatement resolverVar = new CodeVariableDeclarationStatement {
            Name = "resolver",
            Type = new CodeTypeReference(typeof(XmlResolver)),
            InitExpression = new CodeObjectCreateExpression(typeof(XmlEmbeddedResourceResolver))
         };

			CodeTryCatchFinallyStatement trySt = new CodeTryCatchFinallyStatement { 
            TryStatements = {
               new CodeAssignStatement {
                  Left = new CodeVariableReferenceExpression(sourceVar.Name),
                  Right = new CodeCastExpression {
                     TargetType = new CodeTypeReference(typeof(Stream)),
                     Expression = new CodeMethodInvokeExpression {
                        Method = new CodeMethodReferenceExpression {
                           MethodName = "GetEntity",
                           TargetObject = new CodeVariableReferenceExpression(resolverVar.Name)
                        },
                        Parameters = {
                           new CodeVariableReferenceExpression(sourceUriVar.Name),
                           new CodePrimitiveExpression(null),
                           new CodeTypeOfExpression(typeof(Stream))
                        }
                     }
                  }
               }
            }
         };

			CodeVariableDeclarationStatement optionsVar = new CodeVariableDeclarationStatement {
            Name = "options",
            Type = new CodeTypeReference(typeof(XsltCompileOptions)),
         };
			optionsVar.InitExpression = new CodeObjectCreateExpression (optionsVar.Type);

			trySt.TryStatements.Add (optionsVar);
			trySt.TryStatements.Add (new CodeAssignStatement {
            Left = new CodePropertyReferenceExpression {
               PropertyName = "BaseUri",
               TargetObject = new CodeVariableReferenceExpression(optionsVar.Name)
            },
            Right = new CodeVariableReferenceExpression(sourceUriVar.Name)
         });
			trySt.TryStatements.Add (new CodeAssignStatement {
            Left = new CodeFieldReferenceExpression {
               FieldName = executableField.Name,
               TargetObject = thisType
            },
            Right = new CodeMethodInvokeExpression(
               new CodeMethodReferenceExpression {
                  MethodName = "Compile",
                  TargetObject = new CodeVariableReferenceExpression(procVar.Name)
               },
               new CodeVariableReferenceExpression(sourceVar.Name),
               new CodeVariableReferenceExpression(optionsVar.Name)
            )
         });

			CodeConditionStatement disposeIf = new CodeConditionStatement {
            Condition = new CodeBinaryOperatorExpression {
               Left = new CodeVariableReferenceExpression(sourceVar.Name),
               Operator = CodeBinaryOperatorType.IdentityInequality,
               Right = new CodePrimitiveExpression(null)
            },
            TrueStatements = {
               new CodeMethodInvokeExpression {
                  Method = new CodeMethodReferenceExpression {
                     MethodName = "Dispose",
                     TargetObject = new CodeVariableReferenceExpression(sourceVar.Name)
                  }
               }
            }
         };

			trySt.FinallyStatements.Add (disposeIf);

			cctor.Statements.AddRange (new CodeStatement[] {
                procVar,
                sourceVar,
                sourceUriVar,
                resolverVar,
                trySt
            });

			// ctor
			CodeConstructor ctor = new CodeConstructor {
            Attributes = MemberAttributes.Public,
            CustomAttributes = { 
               new CodeAttributeDeclaration(DebuggerNonUserCodeTypeReference)
            },
            BaseConstructorArgs = { 
               new CodeFieldReferenceExpression {
                  FieldName = executableField.Name,
                  TargetObject = thisType
               }
            }
         };

			// class
			CodeTypeDeclaration codeType = new CodeTypeDeclaration {
            Name = GeneratedTypeName,
            IsClass = true,
            BaseTypes = { typeof(SchematronXsltValidator) },
            Members = { cctor, ctor, executableField }
         };

			CodeNamespace codeNamespace = new CodeNamespace {
            Name = GeneratedTypeNamespace,
            Types = { codeType }
         };

			compileUnit.Namespaces.Add (codeNamespace);
		}
Example #7
0
			public void Visit (CodeBaseReferenceExpression o)
			{
				g.GenerateBaseReferenceExpression (o);
			}
Example #8
0
 protected override void GenerateBaseReferenceExpression(CodeBaseReferenceExpression e)
 {
     Write("super(type(self), self)");
 }
Example #9
0
 private void Write(CodeBaseReferenceExpression e){
   this.writer.Write("base");
 }
        CodeExpression ParseExpression(CodeSegment tokenSegment, out CodeSegment nextToParse, CodeTypeDeclarationEx enclosingType) {
            CodeExpression expression = null;
            nextToParse = tokenSegment.Next;


            if(tokenSegment.Token == Token.Identifier && tokenSegment.Next != null
                    && tokenSegment.Next.Token == Token.LiteralBracketOpen) {

                bool ismethodDeclaration = false;
                var closingliteral = tokenSegment.Next.FindClosingBracked(true);
                if(closingliteral != null) {
                    //ensure that it is not a defect method declaration
                    var bra = closingliteral.NextOmit(whitespacetokenNewLines);
                    if(bra != null && bra.Token == Token.BlockOpen) {
                        // it is a method indeed
                        ismethodDeclaration = true;
                    }
                } else {
                    RegisterError(_document, tokenSegment.Next, "Missing: )");
                }

                #region Parse for Method Invokes

                if(!ismethodDeclaration) {

                    CodeTypeDeclarationEx methodContext = null;

                    if(tokenSegment.Previous != null && tokenSegment.Previous.Previous != null
                        && tokenSegment.Previous.Token == Token.MemberInvoke) {

                        var invoker = tokenSegment.Previous.Previous;

                        #region adjust Method Context

                        if(_document.CodeLanguage.SELFREF_CAN_BE_OMITTED)
                            methodContext = enclosingType;

                        if(invoker.CodeDOMObject is CodeBaseReferenceExpression) {
                            foreach(CodeTypeReferenceEx bt in enclosingType.BaseTypes) {
                                var typedeclaration = bt.ResolveTypeDeclarationCache();
                                if(typedeclaration != null && typedeclaration.IsClass) {
                                    methodContext = typedeclaration;
                                    break;
                                }
                            }
                        } else if(invoker.CodeDOMObject is CodeThisReferenceExpression) {
                            methodContext = enclosingType;
                        } else if(invoker.Token == Token.Identifier) {
                            invoker.CodeDOMObject = CodeTypeDeclarationDynamic.Default;
                            methodContext = CodeTypeDeclarationDynamic.Default;
                        }

                        #endregion
                    }

                    var invokeExpression = new CodeMethodInvokeExpression();
                    var methodRef = new CodeMethodReferenceExpressionExAHK(_document, null, tokenSegment.TokenString, methodContext);

                    invokeExpression.Method = methodRef;
                    tokenSegment.CodeDOMObject = methodRef;
                    expression = invokeExpression;
                }

                nextToParse = tokenSegment.Next.Next;
                
                #endregion

            } else if(tokenSegment.Token == Token.KeyWord) {

                #region Parse Keywords

                if(tokenSegment.TokenString.Equals("new", _document.CodeLanguage.NameComparisation)) {

                    #region NEW parse for new Object Expressions

                    var newObjectInvoke = tokenSegment.NextOmit(whitespacetokenNewLines);
                    if(newObjectInvoke != null && newObjectInvoke.Token == Token.Identifier) {

                        var objectinstangicing = new CodeObjectCreateExpression();
                        objectinstangicing.CreateType = new CodeTypeReferenceEx(_document, newObjectInvoke.TokenString, enclosingType);
                        tokenSegment.CodeDOMObject = objectinstangicing;
                        newObjectInvoke.CodeDOMObject = objectinstangicing.CreateType;

                        expression = objectinstangicing;
                        nextToParse = newObjectInvoke.Next;
                    }

                    #endregion

                } else if(tokenSegment.TokenString.Equals("this", _document.CodeLanguage.NameComparisation)) {
                    var thisrefExpression = new CodeThisReferenceExpression();
                    tokenSegment.CodeDOMObject = thisrefExpression;
                    expression = thisrefExpression;
                } else if(tokenSegment.TokenString.Equals("base", _document.CodeLanguage.NameComparisation)) {
                    var baserefExpression = new CodeBaseReferenceExpression();
                    tokenSegment.CodeDOMObject = baserefExpression;
                    expression = baserefExpression;
                }

                #endregion

            } else if(tokenSegment.Token == Token.Identifier  && tokenSegment.Previous != null
                    && tokenSegment.Previous.Token == Token.MemberInvoke) {

                #region Parse MemberInvoke (Dot) Class.Member

                var context = tokenSegment.Previous.Previous;
                if(context == null) {
                    //unexpected!
                    var err = "Unexpected Member Invoke!";
                    RegisterError(_document, tokenSegment, err);
                    RegisterError(_document, tokenSegment.Previous, err);
                    nextToParse = tokenSegment.Next;
                } else if(context.Token == Token.KeyWord && context.TokenString.Equals("this", _document.CodeLanguage.NameComparisation)) {

                    var propRef = new CodePropertyReferenceExpressionEx(_document, null, tokenSegment.TokenString, enclosingType);
                    tokenSegment.CodeDOMObject = propRef;

                } else if(context.Token == Token.KeyWord && context.TokenString.Equals("base", _document.CodeLanguage.NameComparisation)) {

                    CodeTypeDeclarationEx typedeclaration = null;
                    foreach(CodeTypeReferenceEx bt in enclosingType.BaseTypes) {
                        typedeclaration = bt.ResolveTypeDeclarationCache();
                        if(typedeclaration != null && typedeclaration.IsClass) {
                            break;
                        }
                    }
                    var propRef = new CodePropertyReferenceExpressionEx(_document, null, tokenSegment.TokenString, typedeclaration);
                    tokenSegment.CodeDOMObject = propRef;

                } else if(context.Token == Token.Identifier) {
                    // we currently not supprt real expression parsing, so leave here...

                    context.CodeDOMObject = CodeTypeDeclarationDynamic.Default;
                    var propRef = new CodePropertyReferenceExpressionEx(_document, null, tokenSegment.TokenString, CodeTypeDeclarationDynamic.Default);
                    tokenSegment.CodeDOMObject = propRef;

                }

                #region Parse for one hirarchy this/base Property/Field Invokes



                #endregion

                #endregion

            } else if(tokenSegment.Token == Token.TraditionalCommandInvoke) {

                #region Parse Traditional Command Invoke

                var members = from m in _languageRoot.Members.Cast<CodeTypeMember>()
                              let methd = m as CodeMemberMethodExAHK
                              where methd != null && methd.IsTraditionalCommand && methd.Name.Equals(tokenSegment.TokenString, StringComparison.InvariantCultureIgnoreCase)
                              select methd;
                if(members.Any()) {

                    var invokeExpression = new CodeMethodInvokeExpression();
                    var methodRef = new CodeMethodReferenceExpressionExAHK(_document, members.First());

                    tokenSegment.CodeDOMObject = methodRef;
                    expression = invokeExpression;
                } else {
                    RegisterError(_document, tokenSegment, string.Format("Unknown traditional Command '{0}'", tokenSegment.TokenString));
                }

                #endregion
            } else if(tokenSegment.Token == Token.LiteralString) {

                if(tokenSegment.TokenString[tokenSegment.TokenString.Length - 1] != '"') {
                    RegisterError(_document, tokenSegment, "Missing string end Quote");
                }
            }

            if(!(nextToParse != null && nextToParse.LineNumber == tokenSegment.LineNumber)) {
                nextToParse = null;
            }
            return expression;
        }
        public CodeExpression Visit(Expression exp)
        {
            //Expression c = new QueryVisitor((e) => e.NodeType == ExpressionType.Constant && e.Type.Name.StartsWith("<>c__DisplayClass")).Visit(exp);
            //if (c != null)
            //{
            //    object v = CodeDom.Eval(exp);
            //    return GetFromPrimitive(v);
            //}
            //else
            //{
            CodeExpression res = _Visit(exp);
            if (res is CodeDom.CodeThisExpression)
                res = new CodeThisReferenceExpression();
            else if (res is CodeDom.CodeBaseExpression)
                res = new CodeBaseReferenceExpression();

            return res;
            //}
        }
        protected virtual CodeBaseReferenceExpression Rewrite(CodeBaseReferenceExpression source, ref bool didRewrite)
        {
            if (source == null)
            {
                return source;
            }

            bool didChildRewrite = false;
            CodeBaseReferenceExpression result = new CodeBaseReferenceExpression();
            this.Rewrite(result.UserData, source.UserData, ref didChildRewrite);
            if (didChildRewrite)
            {
                didRewrite = true;
                return result;
            }
            else
            {
                return source;
            }
        }
 private Expression Translate(CodeBaseReferenceExpression expr){
   if (expr == null) return null;
   return new Base();
 }
 /// <summary>
 /// Visits a <see cref="CodeBaseReferenceExpression"/>.
 /// </summary>
 /// <param name="codeBaseReferenceExpression">The <see cref="CodeBaseReferenceExpression"/> to visit.</param>
 protected virtual void VisitCodeBaseReferenceExpression(CodeBaseReferenceExpression codeBaseReferenceExpression)
 {
 }
 /// <devdoc>
 ///    <para>
 ///       Generates
 ///       code for the specified CodeDom based base reference expression
 ///       representation.
 ///    </para>
 /// </devdoc>
 private  void GenerateBaseReferenceExpression(CodeBaseReferenceExpression e) {
     Output.Write("base");
 }
Example #16
0
 protected override void GenerateBaseReferenceExpression(System.CodeDom.CodeBaseReferenceExpression e)
 {
     throw new Exception("The method or operation is not implemented.");
 }
        private CodeExpression BuildExpression(XSharpParser.PrimaryExpressionContext expression)
        {
            CodeExpression expr = null;
            XSharpParser.PrimaryContext ctx = expression.Expr;
            //
            if (ctx is XSharpParser.SelfExpressionContext) // Self
            {
                expr = new CodeThisReferenceExpression();
            }
            else if (ctx is XSharpParser.SuperExpressionContext) // Super
            {
                expr = new CodeBaseReferenceExpression();
            }
            else if (ctx is XSharpParser.LiteralExpressionContext)
            {
                XSharpParser.LiteralExpressionContext lit = (XSharpParser.LiteralExpressionContext)ctx;
                expr = BuildLiteralValue(lit.Literal);
            }
            else if (ctx is XSharpParser.LiteralArrayExpressionContext) // { expr [, expr] }
            {
                XSharpParser.LiteralArrayContext arr = ((XSharpParser.LiteralArrayExpressionContext)ctx).LiteralArray;
                // Typed Array ?
                if (arr.Type != null)
                {
                    List<CodeExpression> exprlist = new List<CodeExpression>();
                    foreach (var Element in arr._Elements)
                    {
                        exprlist.Add(BuildExpression(Element.Expr,true));
                    }
                    expr = new CodeArrayCreateExpression(BuildDataType(arr.Type), exprlist.ToArray());
                }
                else
                {
                    expr = new CodeSnippetExpression(arr.GetText());
                }
            }
            else if (ctx is XSharpParser.DelegateCtorCallContext)
            {
                XSharpParser.DelegateCtorCallContext delg = (XSharpParser.DelegateCtorCallContext)ctx;
                //
                CodeTypeReference ctr = BuildDataType(delg.Type);
                CodeExpression ce = BuildExpression(delg.Obj,false);
                //
                expr = new CodeDelegateCreateExpression(BuildDataType(delg.Type), BuildExpression(delg.Obj,false), delg.Func.GetText());

            }
            else if (ctx is XSharpParser.CtorCallContext)
            {
                XSharpParser.CtorCallContext ctor = (XSharpParser.CtorCallContext)ctx;
                CodeTypeReference ctr = BuildDataType(ctor.Type);
                List<CodeExpression> exprlist = new List<CodeExpression>();
                if (ctor.ArgList != null)
                {
                    foreach (var arg in ctor.ArgList._Args)
                    {
                        // We should handle arg.Name if arg.ASSIGN_OP is not null...
                        exprlist.Add(BuildExpression(arg.Expr,false));
                    }
                }
                expr = new CodeObjectCreateExpression(ctr.BaseType, exprlist.ToArray());
            }
            else if (ctx is XSharpParser.TypeOfExpressionContext)
            {
                CodeTypeReference ctr = BuildDataType(((XSharpParser.TypeOfExpressionContext)ctx).Type);
                expr = new CodeTypeOfExpression(ctr);
            }
            else if (ctx is XSharpParser.NameExpressionContext)
            {
                String name = ((XSharpParser.NameExpressionContext)ctx).Name.Id.GetText();
                // Sometimes, we will need to do it that way....
                if (name.ToLower() == "self")
                {
                    expr = new CodeThisReferenceExpression();
                }
                else if (name.ToLower() == "super")
                {
                    expr = new CodeBaseReferenceExpression();
                }
                else
                {
                    CodeTypeReference ctr = BuildSimpleName(((XSharpParser.NameExpressionContext)ctx).Name);
                    expr = new CodeVariableReferenceExpression(name);
                }
            }
            else
            {
                expr = new CodeSnippetExpression(ctx.GetText());
            }
            return expr;
        }
 public void Generate(CodeBaseReferenceExpression expression)
 {
     Write("super");
 }
Example #19
0
		void CallBaseFrameworkInitialize (CodeMemberMethod method)
		{
			CodeBaseReferenceExpression baseRef = new CodeBaseReferenceExpression ();
			CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (baseRef, "FrameworkInitialize");
			method.Statements.Add (invoke);
		}
Example #20
0
 /// <summary>
 /// Generates code for the specified base reference expression.
 /// </summary>
 /// <remarks><c>parent</c></remarks>
 protected override void GenerateBaseReferenceExpression(CodeBaseReferenceExpression e)
 {
     Output.Write(SpecialWords.Parent);
 }
Example #21
0
		protected abstract void GenerateBaseReferenceExpression (CodeBaseReferenceExpression e);
 public bool ValidateCodeBaseReferenceExpression (CodeBaseReferenceExpression exp) {
     // could include code that looks up the location stack to see if there's a type member
     // that has a MemberAttribute of Override
     return true;
 }
		void GenerateEventBasedAsyncSupport (CodeTypeDeclaration type, OperationDescription od, CodeNamespace cns)
		{
			var method = FindByName (type, od.Name) ?? FindByName (type, "Begin" + od.Name);
			var endMethod = method.Name == od.Name ? null : FindByName (type, "End" + od.Name);
			bool methodAsync = method.Name.StartsWith ("Begin", StringComparison.Ordinal);
			var resultType = endMethod != null ? endMethod.ReturnType : method.ReturnType;

			var thisExpr = new CodeThisReferenceExpression ();
			var baseExpr = new CodeBaseReferenceExpression ();
			var nullExpr = new CodePrimitiveExpression (null);
			var asyncResultType = new CodeTypeReference (typeof (IAsyncResult));

			// OnBeginXxx() implementation
			var cm = new CodeMemberMethod () {
				Name = "OnBegin" + od.Name,
				Attributes = MemberAttributes.Private | MemberAttributes.Final,
				ReturnType = asyncResultType
				};
			type.Members.Add (cm);

			AddMethodParam (cm, typeof (object []), "args");
			AddMethodParam (cm, typeof (AsyncCallback), "asyncCallback");
			AddMethodParam (cm, typeof (object), "userState");

			var call = new CodeMethodInvokeExpression (
				thisExpr,
				"Begin" + od.Name);
			for (int idx = 0; idx < method.Parameters.Count - (methodAsync ? 2 : 0); idx++) {
				var p = method.Parameters [idx];
				cm.Statements.Add (new CodeVariableDeclarationStatement (p.Type, p.Name, new CodeCastExpression (p.Type, new CodeArrayIndexerExpression (new CodeArgumentReferenceExpression ("args"), new CodePrimitiveExpression (idx)))));
				call.Parameters.Add (new CodeVariableReferenceExpression (p.Name));
			}
			call.Parameters.Add (new CodeArgumentReferenceExpression ("asyncCallback"));
			call.Parameters.Add (new CodeArgumentReferenceExpression ("userState"));
			cm.Statements.Add (new CodeMethodReturnStatement (call));

			// OnEndXxx() implementation
			cm = new CodeMemberMethod () {
				Name = "OnEnd" + od.Name,
				Attributes = MemberAttributes.Private | MemberAttributes.Final,
				ReturnType = new CodeTypeReference (typeof (object [])) };
			type.Members.Add (cm);

			AddMethodParam (cm, typeof (IAsyncResult), "result");

			var outArgRefs = new List<CodeVariableReferenceExpression> ();

			for (int idx = 0; idx < method.Parameters.Count; idx++) {
				var p = method.Parameters [idx];
				if (p.Direction != FieldDirection.In) {
					cm.Statements.Add (new CodeVariableDeclarationStatement (p.Type, p.Name));
					outArgRefs.Add (new CodeVariableReferenceExpression (p.Name)); // FIXME: should this work? They need "out" or "ref" modifiers.
				}
			}

			call = new CodeMethodInvokeExpression (
				thisExpr,
				"End" + od.Name,
				new CodeArgumentReferenceExpression ("result"));
			call.Parameters.AddRange (outArgRefs.Cast<CodeExpression> ().ToArray ()); // questionable

			var retCreate = new CodeArrayCreateExpression (typeof (object));
			if (resultType.BaseType == "System.Void")
				cm.Statements.Add (call);
			else {
				cm.Statements.Add (new CodeVariableDeclarationStatement (typeof (object), "__ret", call));
				retCreate.Initializers.Add (new CodeVariableReferenceExpression ("__ret"));
			}
			foreach (var outArgRef in outArgRefs)
				retCreate.Initializers.Add (new CodeVariableReferenceExpression (outArgRef.VariableName));

			cm.Statements.Add (new CodeMethodReturnStatement (retCreate));

			// OnXxxCompleted() implementation
			cm = new CodeMemberMethod () {
				Name = "On" + od.Name + "Completed",
				Attributes = MemberAttributes.Private | MemberAttributes.Final };
			type.Members.Add (cm);

			AddMethodParam (cm, typeof (object), "state");

			string argsname = identifiers.AddUnique (od.Name + "CompletedEventArgs", null);
			var iaargs = new CodeTypeReference ("InvokeAsyncCompletedEventArgs"); // avoid messy System.Type instance for generic nested type :|
			var iaref = new CodeVariableReferenceExpression ("args");
			var methodEventArgs = new CodeObjectCreateExpression (new CodeTypeReference (argsname),
				new CodePropertyReferenceExpression (iaref, "Results"),
				new CodePropertyReferenceExpression (iaref, "Error"),
				new CodePropertyReferenceExpression (iaref, "Cancelled"),
				new CodePropertyReferenceExpression (iaref, "UserState"));
			cm.Statements.Add (new CodeConditionStatement (
				new CodeBinaryOperatorExpression (
					new CodeEventReferenceExpression (thisExpr, od.Name + "Completed"), CodeBinaryOperatorType.IdentityInequality, nullExpr),
				new CodeVariableDeclarationStatement (iaargs, "args", new CodeCastExpression (iaargs, new CodeArgumentReferenceExpression ("state"))),
				new CodeExpressionStatement (new CodeMethodInvokeExpression (thisExpr, od.Name + "Completed", thisExpr, methodEventArgs))));

			// delegate fields
			type.Members.Add (new CodeMemberField (new CodeTypeReference ("BeginOperationDelegate"), "onBegin" + od.Name + "Delegate"));
			type.Members.Add (new CodeMemberField (new CodeTypeReference ("EndOperationDelegate"), "onEnd" + od.Name + "Delegate"));
			type.Members.Add (new CodeMemberField (new CodeTypeReference (typeof (SendOrPostCallback)), "on" + od.Name + "CompletedDelegate"));

			// XxxCompletedEventArgs class
			var argsType = new CodeTypeDeclaration (argsname);
			argsType.BaseTypes.Add (new CodeTypeReference (typeof (AsyncCompletedEventArgs)));
			cns.Types.Add (argsType);

			var argsCtor = new CodeConstructor () {
				Attributes = MemberAttributes.Public | MemberAttributes.Final };
			argsCtor.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object []), "results"));
			argsCtor.Parameters.Add (new CodeParameterDeclarationExpression (typeof (Exception), "error"));
			argsCtor.Parameters.Add (new CodeParameterDeclarationExpression (typeof (bool), "cancelled"));
			argsCtor.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object), "userState"));
			argsCtor.BaseConstructorArgs.Add (new CodeArgumentReferenceExpression ("error"));
			argsCtor.BaseConstructorArgs.Add (new CodeArgumentReferenceExpression ("cancelled"));
			argsCtor.BaseConstructorArgs.Add (new CodeArgumentReferenceExpression ("userState"));
			var resultsField = new CodeFieldReferenceExpression (thisExpr, "results");
			argsCtor.Statements.Add (new CodeAssignStatement (resultsField, new CodeArgumentReferenceExpression ("results")));
			argsType.Members.Add (argsCtor);

			argsType.Members.Add (new CodeMemberField (typeof (object []), "results"));

			if (resultType.BaseType != "System.Void") {
				var resultProp = new CodeMemberProperty {
					Name = "Result",
					Type = resultType,
					Attributes = MemberAttributes.Public | MemberAttributes.Final };
				resultProp.GetStatements.Add (new CodeMethodReturnStatement (new CodeCastExpression (resultProp.Type, new CodeArrayIndexerExpression (resultsField, new CodePrimitiveExpression (0)))));
				argsType.Members.Add (resultProp);
			}

			// event field
			var handlerType = new CodeTypeReference (typeof (EventHandler<>));
			handlerType.TypeArguments.Add (new CodeTypeReference (argsType.Name));
			type.Members.Add (new CodeMemberEvent () {
				Name = od.Name + "Completed",
				Type = handlerType,
				Attributes = MemberAttributes.Public | MemberAttributes.Final });

			// XxxAsync() implementations
			bool hasAsync = false;
			foreach (int __x in Enumerable.Range (0, 2)) {
				cm = new CodeMemberMethod ();
				type.Members.Add (cm);
				cm.Name = od.Name + "Async";
				cm.Attributes = MemberAttributes.Public 
						| MemberAttributes.Final;

				var inArgs = new List<CodeParameterDeclarationExpression > ();

				for (int idx = 0; idx < method.Parameters.Count - (methodAsync ? 2 : 0); idx++) {
					var pd = method.Parameters [idx];
					inArgs.Add (pd);
					cm.Parameters.Add (pd);
				}

				// First one is overload without asyncState arg.
				if (!hasAsync) {
					call = new CodeMethodInvokeExpression (thisExpr, cm.Name, inArgs.ConvertAll<CodeExpression> (decl => new CodeArgumentReferenceExpression (decl.Name)).ToArray ());
					call.Parameters.Add (nullExpr);
					cm.Statements.Add (new CodeExpressionStatement (call));
					hasAsync = true;
					continue;
				}

				// Second one is the primary one.

				cm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object), "userState"));

				// if (onBeginBarOperDelegate == null) onBeginBarOperDelegate = new BeginOperationDelegate (OnBeginBarOper);
				// if (onEndBarOperDelegate == null) onEndBarOperDelegate = new EndOperationDelegate (OnEndBarOper);
				// if (onBarOperCompletedDelegate == null) onBarOperCompletedDelegate = new BeginOperationDelegate (OnBarOperCompleted);
				var beginOperDelegateRef = new CodeFieldReferenceExpression (thisExpr, "onBegin" + od.Name + "Delegate");
				var endOperDelegateRef = new CodeFieldReferenceExpression (thisExpr, "onEnd" + od.Name + "Delegate");
				var operCompletedDelegateRef = new CodeFieldReferenceExpression (thisExpr, "on" + od.Name + "CompletedDelegate");

				var ifstmt = new CodeConditionStatement (
					new CodeBinaryOperatorExpression (beginOperDelegateRef, CodeBinaryOperatorType.IdentityEquality, nullExpr),
					new CodeAssignStatement (beginOperDelegateRef, new CodeDelegateCreateExpression (new CodeTypeReference ("BeginOperationDelegate"), thisExpr, "OnBegin" + od.Name)));
				cm.Statements.Add (ifstmt);
				ifstmt = new CodeConditionStatement (
					new CodeBinaryOperatorExpression (endOperDelegateRef, CodeBinaryOperatorType.IdentityEquality, nullExpr),
					new CodeAssignStatement (endOperDelegateRef, new CodeDelegateCreateExpression (new CodeTypeReference ("EndOperationDelegate"), thisExpr, "OnEnd" + od.Name)));
				cm.Statements.Add (ifstmt);
				ifstmt = new CodeConditionStatement (
					new CodeBinaryOperatorExpression (operCompletedDelegateRef, CodeBinaryOperatorType.IdentityEquality, nullExpr),
					new CodeAssignStatement (operCompletedDelegateRef, new CodeDelegateCreateExpression (new CodeTypeReference (typeof (SendOrPostCallback)), thisExpr, "On" + od.Name + "Completed")));
				cm.Statements.Add (ifstmt);

				// InvokeAsync (onBeginBarOperDelegate, inValues, onEndBarOperDelegate, onBarOperCompletedDelegate, userState);

				inArgs.Add (new CodeParameterDeclarationExpression (typeof (object), "userState"));

				var args = new List<CodeExpression> ();
				args.Add (beginOperDelegateRef);
				args.Add (new CodeArrayCreateExpression (typeof (object), inArgs.ConvertAll<CodeExpression> (decl => new CodeArgumentReferenceExpression (decl.Name)).ToArray ()));
				args.Add (endOperDelegateRef);
				args.Add (new CodeFieldReferenceExpression (thisExpr, "on" + od.Name + "CompletedDelegate"));
				args.Add (new CodeArgumentReferenceExpression ("userState"));
				call = new CodeMethodInvokeExpression (baseExpr, "InvokeAsync", args.ToArray ());
				cm.Statements.Add (new CodeExpressionStatement (call));
			}
		}
Example #24
0
		protected override void GenerateBaseReferenceExpression (CodeBaseReferenceExpression expression)
		{
			Output.Write ("base");
		}
		protected override void GenerateBaseReferenceExpression(CodeBaseReferenceExpression e)
		{
			Output.Write("[CodeBaseReferenceExpression: {0}]", e.ToString());
		}
        private CodeMemberMethod GetInitCleanupMethod(Type methodAttributeType, MultiDirectionTestClass testClass)
        {
            bool isStatic = false;
            string generatedMetholdName = string.Empty;
            string methodToInvokeName = string.Empty;
            CodeParameterDeclarationExpression parameterDec = null;

            if (methodAttributeType == typeof(ClassInitializeAttribute))
            {
                isStatic = true;
                generatedMetholdName = GodeGeneratorConst.ClassInitMethodName;
                methodToInvokeName = testClass.ClassInit.Name;
                parameterDec = new CodeParameterDeclarationExpression(typeof(TestContext), "testContext");
            }
            else if (methodAttributeType == typeof(ClassCleanupAttribute))
            {
                isStatic = true;
                generatedMetholdName = GodeGeneratorConst.ClassCleanupMethodName;
                methodToInvokeName = testClass.ClassCleanup.Name;
            }
            else
            {
                throw new ArgumentException("methodAttributeType");
            }

            CodeMemberMethod result = new CodeMemberMethod();
            result.Name = generatedMetholdName;

            // Add parameter list if needed
            if (parameterDec != null)
            {
                result.Parameters.Add(parameterDec);
            }

            CodeExpression callBase = null;
            if (isStatic)
            {
                result.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                callBase = new CodeTypeReferenceExpression(testClass.ClassType.FullName);
            }
            else
            {
                result.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                callBase = new CodeBaseReferenceExpression();
            }

            // Add methold attribute
            CodeAttributeDeclaration methodAttribute = new CodeAttributeDeclaration(
                new CodeTypeReference(methodAttributeType));
            result.CustomAttributes.Add(methodAttribute);

            // Add invoke statement
            CodeMethodInvokeExpression invokeExp = null;
            if (parameterDec != null)
            {
                CodeVariableReferenceExpression sourceParameter = new CodeVariableReferenceExpression(parameterDec.Name);
                invokeExp = new CodeMethodInvokeExpression(callBase, methodToInvokeName, sourceParameter);
            }
            else
            {
                invokeExp = new CodeMethodInvokeExpression(callBase, methodToInvokeName);
            }

            result.Statements.Add(invokeExp);

            return result;
        }