Inheritance: System.CodeDom.CodeExpression
コード例 #1
0
		public void Constructor0_Deny_Unrestricted ()
		{
			CodeDirectionExpression cde = new CodeDirectionExpression ();
			Assert.AreEqual (FieldDirection.In, cde.Direction, "Direction");
			cde.Direction = FieldDirection.Out;
			Assert.IsNull (cde.Expression, "Expression");
			cde.Expression = new CodeExpression ();
		}
コード例 #2
0
		public void Constructor1_Deny_Unrestricted ()
		{
			CodeExpression expression = new CodeExpression ();
			CodeDirectionExpression cde = new CodeDirectionExpression (FieldDirection.Out, expression);
			Assert.AreEqual (FieldDirection.Out, cde.Direction, "Direction");
			cde.Direction = FieldDirection.Ref;
			Assert.AreSame (expression, cde.Expression, "Expression");
			cde.Expression = new CodeExpression ();
		}
コード例 #3
0
 public static CodeDirectionExpression Clone(this CodeDirectionExpression expression)
 {
     if (expression == null) return null;
     CodeDirectionExpression e = new CodeDirectionExpression();
     e.Direction = expression.Direction;
     e.Expression = expression.Expression.Clone();
     e.UserData.AddRange(expression.UserData);
     return e;
 }
コード例 #4
0
 public TypescriptDirectionExpression(
     IExpressionFactory expressionFactory,
     CodeDirectionExpression codeExpression, 
     CodeGeneratorOptions options)
 {
     _expressionFactory = expressionFactory;
     _codeExpression = codeExpression;
     _options = options;
     System.Diagnostics.Debug.WriteLine("TypescriptDirectionExpression Created");
 }
コード例 #5
0
		public CodeExpression[] Generate(Table table, HardwireCodeGenerationContext generator, CodeTypeMemberCollection members)
		{
			bool isArray = table.Get("arraytype").IsNotNil();
			string memberName = table.Get("name").String;
			
			// Ignore arrays weird special members 
			if (isArray)
			{
				if ((memberName == "Get") || (memberName == "Set") || (memberName == "Address"))
					return null;
			}

			// Create the descriptor class
			string className = m_Prefix + "_" + Guid.NewGuid().ToString("N");

			CodeTypeDeclaration classCode = new CodeTypeDeclaration(className);
			classCode.TypeAttributes = System.Reflection.TypeAttributes.NestedPrivate | System.Reflection.TypeAttributes.Sealed;
			classCode.BaseTypes.Add(typeof(HardwiredMethodMemberDescriptor));

			// Create the class constructor
			CodeConstructor ctor = new CodeConstructor();
			ctor.Attributes = MemberAttributes.Assembly;
			classCode.Members.Add(ctor);

			// Create the parameters
			List<HardwireParameterDescriptor> paramDescs = HardwireParameterDescriptor.LoadDescriptorsFromTable(table.Get("params").Table);

			int paramNum = paramDescs.Count;
			int optionalNum = paramDescs.Where(p => p.HasDefaultValue).Count();

			// Add initialize call to ctor
			List<CodeExpression> initParams = new List<CodeExpression>();

			initParams.Add(new CodePrimitiveExpression(memberName));
			initParams.Add(new CodePrimitiveExpression(table.Get("static").Boolean || table.Get("ctor").Boolean));

			initParams.Add(new CodeArrayCreateExpression(typeof(ParameterDescriptor), 
				paramDescs.Select(e => e.Expression).ToArray())); 

			initParams.Add(new CodePrimitiveExpression(table.Get("extension").Boolean));

			ctor.Statements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "Initialize", initParams.ToArray()));


			// Create the Invoke method : protected override object Invoke(Script script, object obj, object[] pars, int argscount);

			CodeMemberMethod m = new CodeMemberMethod();
			m.Name = "Invoke";
			m.Attributes = MemberAttributes.Override | MemberAttributes.Family;
			m.ReturnType = new CodeTypeReference(typeof(object));
			m.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Script), "script"));
			m.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "obj"));
			m.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object[]), "pars"));
			m.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "argscount"));

			// get some meta about the method
			bool isVoid = table.Get("ret").String == "System.Void";
			bool isCtor = table.Get("ctor").Boolean;
			bool isStatic = table.Get("static").Boolean;
			bool isExtension = table.Get("extension").Boolean;
			bool specialName = table.Get("special").Boolean;

			string declType = table.Get("decltype").String;
			var paramArray = new CodeVariableReferenceExpression("pars");
			var paramThis = isStatic
				? (CodeExpression)(new CodeTypeReferenceExpression(declType))
				: (CodeExpression)(new CodeCastExpression(declType, new CodeVariableReferenceExpression("obj")));

			// Build a list of arguments to the call
			int refparCount = 0;
			List<CodeExpression> paramExps = new List<CodeExpression>();
			for (int i = 0; i < paramDescs.Count; i++)
			{
				var P = paramDescs[i];

				CodeExpression paramExp = new CodeCastExpression(paramDescs[i].ParamType, new CodeArrayIndexerExpression(paramArray, new CodePrimitiveExpression(i)));

				if (P.IsOut)
				{
					string varName = GenerateRefParamVariable(refparCount++);
					var vd = new CodeVariableDeclarationStatement(P.ParamType, varName);
					m.Statements.Add(vd);
					paramExp = new CodeDirectionExpression(FieldDirection.Out, new CodeVariableReferenceExpression(varName));
				}
				else if (P.IsRef)
				{
					string varName = GenerateRefParamVariable(refparCount++);
					var vd = new CodeVariableDeclarationStatement(P.ParamType, varName, paramExp);
					m.Statements.Add(vd);
					paramExp = new CodeDirectionExpression(FieldDirection.Ref, new CodeVariableReferenceExpression(varName));
				}

				paramExps.Add(paramExp);
			}



			// build a list of possible dispatching to default params
			List<CodeExpression[]> calls = new List<CodeExpression[]>();
			var paramArgsCount = new CodeVariableReferenceExpression("argscount");

			for(int callidx = paramNum - optionalNum; callidx <= paramNum; callidx++)
			{
				List<CodeExpression> pars = new List<CodeExpression>();

				// Build the array of parameters expressions
				for(int i = 0; i < callidx; i++)
				{
					pars.Add(paramExps[i]);
				}

				calls.Add(pars.ToArray());
			}


			// foreach "overload" of default pars, dispatch a call
			for (int i = 0; i < calls.Count - 1; i++)
			{
				int argcnt = calls[i].Length;

				CodeExpression condition = new CodeBinaryOperatorExpression(paramArgsCount,
						CodeBinaryOperatorType.LessThanOrEqual, new CodePrimitiveExpression(argcnt));

				var ifs = new CodeConditionStatement(condition, GenerateCall(table, generator, isVoid, isCtor, isStatic, isExtension, calls[i], paramThis, declType, specialName, refparCount).OfType<CodeStatement>().ToArray());

				m.Statements.Add(ifs);
			}

			m.Statements.AddRange(GenerateCall(table, generator, isVoid, isCtor, isStatic, isExtension, calls[calls.Count - 1], paramThis, declType, specialName, refparCount));


			// close
			classCode.Members.Add(m);
			members.Add(classCode);
			return new CodeExpression[] { new CodeObjectCreateExpression(className) };
		}
コード例 #6
0
ファイル: CodeGenerator.cs プロジェクト: carrie901/mono
			public void Visit (CodeDirectionExpression o)
			{
				g.GenerateDirectionExpression (o);
			}
コード例 #7
0
ファイル: DryadLinqCodeGen.cs プロジェクト: pszmyd/Dryad
        private CodeStmtPair MakeWriteFieldStatements(Type type,
                                                      CodeExpression objExpr,
                                                      FieldInfo finfo,
                                                      CodeVariableReferenceExpression[] indexExprs)
        {
            CodeExpression writerExpr = new CodeArgumentReferenceExpression("writer");
            CodeExpression fieldExpr;
            if (finfo == null)
            {
                fieldExpr = new CodeArrayIndexerExpression(objExpr, indexExprs);
            }
            else
            {
                string fieldName = TypeSystem.FieldName(finfo.Name);
                if (finfo.IsPublic ||
                    (TypeSystem.IsBackingField(finfo.Name) &&
                     finfo.DeclaringType.GetProperty(fieldName, FieldFlags).GetGetMethod() != null))
                {
                    fieldExpr = new CodeFieldReferenceExpression(objExpr, fieldName);
                }
                else
                {
                    CodeExpression getterExpr = new CodeVariableReferenceExpression(
                                                        ExtensionClassName + "." + this.GetterFieldName(finfo));
                    if (finfo.DeclaringType.IsValueType)
                    {
                        objExpr = new CodeDirectionExpression(FieldDirection.Out, objExpr);
                    }
                    fieldExpr = new CodeDelegateInvokeExpression(getterExpr, objExpr);
                }
            }

            CodeExpression writeCall;
            if (GetBuiltinReaderName(type) == null)
            {
                // for non-builtin types
                string serializerName = GetStaticSerializerName(type);
                CodeVariableReferenceExpression serializerExpr = new CodeVariableReferenceExpression(serializerName);
                writeCall = new CodeMethodInvokeExpression(serializerExpr, "Write", writerExpr, fieldExpr);
            }
            else
            {
                // for builtin types
                writeCall = new CodeMethodInvokeExpression(writerExpr, "Write", fieldExpr);
            }
            CodeStatement stmt1 = new CodeExpressionStatement(writeCall);
            
            if (type.IsValueType)
            {
                return new CodeStmtPair(null, new CodeStatement[] { stmt1 });
            }
            else if (finfo == null)
            {
                if (StaticConfig.AllowNullArrayElements)
                {
                    string bvIndexString = indexExprs[0].VariableName;
                    for (int i = 1; i < indexExprs.Length; i++)
                    {
                        bvIndexString += "*" + indexExprs[i].VariableName;
                    }
                    CodeExpression bvIndex = new CodeSnippetExpression(bvIndexString);
                    CodeExpression nullExpr = new CodeMethodInvokeExpression(
                                                      new CodeTypeReferenceExpression("Object"),
                                                      "ReferenceEquals",
                                                      fieldExpr,
                                                      NullExpr);
                    CodeExpression bvExpr = new CodeArgumentReferenceExpression("bv");
                    CodeStatement stmt0 = new CodeExpressionStatement(
                                                  new CodeMethodInvokeExpression(bvExpr, "Set", bvIndex));
                    stmt0 = new CodeConditionStatement(nullExpr, stmt0);

                    CodeExpression notNullExpr = new CodeBinaryOperatorExpression(
                                                         new CodeIndexerExpression(bvExpr, bvIndex),
                                                         CodeBinaryOperatorType.IdentityEquality,
                                                         new CodePrimitiveExpression(false));
                    stmt1 = new CodeConditionStatement(notNullExpr, stmt1);
                    return new CodeStmtPair(new CodeStatement[] { stmt0 }, new CodeStatement[] { stmt1 });      
                }
                else
                {
                    return new CodeStmtPair(null, new CodeStatement[] { stmt1 });
                }
            }
            else
            {
                CodeExpression nullExpr = new CodeMethodInvokeExpression(
                                                  new CodeTypeReferenceExpression("Object"),
                                                  "ReferenceEquals",
                                                  fieldExpr,
                                                  NullExpr);
                if (AttributeSystem.FieldCanBeNull(finfo))
                {
                    CodeExpression bvExpr = new CodeArgumentReferenceExpression("bv");
                    CodeStatement stmt0 = new CodeExpressionStatement(
                                                  new CodeMethodInvokeExpression(bvExpr, "Set", indexExprs[0]));
                    stmt0 = new CodeConditionStatement(nullExpr, stmt0);
                    
                    CodeExpression notNullExpr = new CodeBinaryOperatorExpression(
                                                         new CodeIndexerExpression(bvExpr, indexExprs[0]),
                                                         CodeBinaryOperatorType.IdentityEquality,
                                                         new CodePrimitiveExpression(false));
                    stmt1 = new CodeConditionStatement(notNullExpr, stmt1);
                    return new CodeStmtPair(new CodeStatement[] { stmt0 }, new CodeStatement[] { stmt1 });
                }
                else
                {
                    // YY: For now we always check null
                    string msg = "Field " + finfo.DeclaringType.Name + "." + finfo.Name + " is null.";
                    CodeExpression msgExpr = new CodePrimitiveExpression(msg);
                    CodeExpression throwExpr = new CodeObjectCreateExpression(typeof(ArgumentNullException), msgExpr);
                    CodeStatement stmt0 = new CodeConditionStatement(nullExpr, new CodeThrowExceptionStatement(throwExpr));
                    return new CodeStmtPair(null, new CodeStatement[] { stmt0, stmt1 });                    
                }
            }
        }
コード例 #8
0
 /// <devdoc>
 ///    <para>[To be supplied.]</para>
 /// </devdoc>
 private void GenerateDirectionExpression(CodeDirectionExpression e) {
     OutputDirection(e.Direction);
     GenerateExpression(e.Expression);
 }
コード例 #9
0
 public bool ValidateCodeDirectionExpression (CodeDirectionExpression exp) {
     PushError ("CodeDirectionExpression is not allowed.");
     return false;
 }
コード例 #10
0
 protected override void GenerateDirectionExpression(CodeDirectionExpression e) {
     // Visual Basic does not need to adorn the calling point with a direction, so just output the expression.
     GenerateExpression(e.Expression);
 }
コード例 #11
0
ファイル: Compiler.cs プロジェクト: hesam/SketchSharp
 private void Write(CodeDirectionExpression e){
   TextWriter w = this.writer;
   switch (e.Direction){
     case FieldDirection.Out: w.Write("out "); break;
     case FieldDirection.Ref: w.Write("ref "); break;
   }
   this.Write(e.Expression);
 }
コード例 #12
0
ファイル: In.cs プロジェクト: rneilturner/win-tools
 internal CodeExpression BuildWriteExpression(CodeArgumentReferenceExpression codeArgumentReferenceExpression, CodeDirectionExpression codeDirectionExpression)
 {
     //throw new System.NotImplementedException();
     CodeExpression expr = base.BuildWriteExpression(codeArgumentReferenceExpression, codeDirectionExpression);
     return expr;
 }
コード例 #13
0
        protected virtual CodeDirectionExpression Rewrite(CodeDirectionExpression source, ref bool didRewrite)
        {
            if (source == null)
            {
                return source;
            }

            bool didChildRewrite = false;
            CodeDirectionExpression result = new CodeDirectionExpression();
            result.Expression = this.Rewrite(source.Expression, ref didChildRewrite);
            result.Direction = this.Rewrite(source.Direction, ref didChildRewrite);
            this.Rewrite(result.UserData, source.UserData, ref didChildRewrite);
            if (didChildRewrite)
            {
                didRewrite = true;
                return result;
            }
            else
            {
                return source;
            }
        }
コード例 #14
0
 private Expression Translate(CodeDirectionExpression expr){
   if (expr == null) return null;
   if (expr.Direction == FieldDirection.In)
     return this.Translate(expr.Expression);
   else
     return new UnaryExpression(this.Translate(expr.Expression), NodeType.AddressOf);
 }
コード例 #15
0
 private void BuildParameters(CodeStatementCollection statements, MethodInfo method, object[] paramValues,
                              CodeExpressionCollection parameters)
 {
     ParameterInfo[] infoArray1 = method.GetParameters();
     for (int num1 = 0; num1 < infoArray1.Length; num1++)
     {
         ParameterInfo info1 = infoArray1[num1];
         Type type1 = infoArray1[num1].ParameterType;
         FieldDirection direction1 = FieldDirection.In;
         if (type1.IsByRef)
         {
             direction1 = FieldDirection.Ref;
             type1 = type1.GetElementType();
         }
         CodeExpression expression1 = null;
         if (!info1.IsOut)
         {
             expression1 = BuildObject(statements, info1.Name, paramValues[num1]);
         }
         else
         {
             direction1 = FieldDirection.Out;
         }
         if (direction1 != FieldDirection.In)
         {
             if ((expression1 == null) || !(expression1 is CodeVariableReferenceExpression))
             {
                 CodeVariableDeclarationStatement statement1 =
                     new CodeVariableDeclarationStatement(type1.FullName, info1.Name);
                 if (expression1 != null)
                 {
                     statement1.InitExpression = expression1;
                 }
                 statements.Add(statement1);
                 expression1 = new CodeVariableReferenceExpression(statement1.Name);
             }
             expression1 = new CodeDirectionExpression(direction1, expression1);
         }
         parameters.Add(expression1);
     }
 }
コード例 #16
0
 internal override CodeExpression Clone(CodeExpression expression)
 {
     CodeDirectionExpression directionExpr = (CodeDirectionExpression)expression;
     CodeDirectionExpression newDirection = new CodeDirectionExpression();
     newDirection.Direction = directionExpr.Direction;
     newDirection.Expression = RuleExpressionWalker.Clone(directionExpr.Expression);
     return newDirection;
 }
コード例 #17
0
ファイル: MethodEmitter.cs プロジェクト: maleficus1234/Pie
 // Emit a codedom directioned variable expression (ref int foo or out int foo)
 public static CodeExpression Emit(DirectionedArgument p)
 {
     var dir = FieldDirection.Out;
     if (p.Direction == ParameterDirection.Ref)
         dir = FieldDirection.Ref;
     var codeDirection = new CodeDirectionExpression(dir,
         new CodeVariableReferenceExpression(p.Name));
     return codeDirection;
 }
コード例 #18
0
 public void Generate(CodeDirectionExpression expression)
 {
     throw new NotSupportedException();
 }
コード例 #19
0
ファイル: Parser.cs プロジェクト: iskiselev/JSIL.NetFramework
        // Parse:
        //              argument --> direction logical-expression
        //                       --> logical-expression
        //              
        //              direction --> IN
        //                        --> OUT 
        //                        --> REF 
        private CodeExpression ParseArgument(ParserContext parserContext, bool assignIsEquality)
        {
            CodeExpression argResult = null;

            Token token = parserContext.CurrentToken;
            int directionPosition = token.StartPosition;
            FieldDirection? direction = null;
            ValueCheck check = ValueCheck.Read;
            switch (token.TokenID)
            {
                case TokenID.In:
                    direction = FieldDirection.In;
                    parserContext.NextToken(); // eat the direction token
                    break;
                case TokenID.Out:
                    direction = FieldDirection.Out;
                    parserContext.NextToken();
                    check = ValueCheck.Write;
                    break;
                case TokenID.Ref:
                    direction = FieldDirection.Ref;
                    parserContext.NextToken();
                    check = ValueCheck.Read | ValueCheck.Write;
                    break;
            }

            argResult = ParseBinaryExpression(parserContext, 0, true, check);
            if (direction != null)
            {
                argResult = new CodeDirectionExpression(direction.Value, argResult);
                parserContext.exprPositions[argResult] = directionPosition;
                ValidateExpression(parserContext, argResult, assignIsEquality, ValueCheck.Read);
            }

            return argResult;
        }
コード例 #20
0
ファイル: Script.cs プロジェクト: hdougie/webservicestudio2
 private void BuildParameters(CodeStatementCollection statements, MethodInfo method, object[] paramValues, CodeExpressionCollection parameters)
 {
     ParameterInfo[] infoArray = method.GetParameters();
     for (int i = 0; i < infoArray.Length; i++)
     {
         ParameterInfo info = infoArray[i];
         Type parameterType = infoArray[i].ParameterType;
         FieldDirection @in = FieldDirection.In;
         if (parameterType.IsByRef)
         {
             @in = FieldDirection.Ref;
             parameterType = parameterType.GetElementType();
         }
         CodeExpression expression = null;
         if (!info.IsOut)
         {
             expression = this.BuildObject(statements, info.Name, paramValues[i]);
         }
         else
         {
             @in = FieldDirection.Out;
         }
         if (@in != FieldDirection.In)
         {
             if ((expression == null) || !(expression is CodeVariableReferenceExpression))
             {
                 CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(parameterType.FullName, info.Name);
                 if (expression != null)
                 {
                     statement.InitExpression = expression;
                 }
                 statements.Add(statement);
                 expression = new CodeVariableReferenceExpression(statement.Name);
             }
             expression = new CodeDirectionExpression(@in, expression);
         }
         parameters.Add(expression);
     }
 }
コード例 #21
0
ファイル: CodeValidator.cs プロジェクト: uQr/referencesource
 private void ValidateDirectionExpression(CodeDirectionExpression e) {
    ValidateExpression(e.Expression);
 }
コード例 #22
0
ファイル: CompileUplevel.cs プロジェクト: nobled/mono
		CodeMemberMethod GenerateMethod (CodeTypeDeclaration mainClass)
		{
			CodeMemberMethod method;

			if (GroupZero)
				method = GetMainMethod ();
			else
				method = GetGroupMethod ();

			mainClass.Members.Add (method);
			CodeConditionStatement matches, subMatches;
			ArrayList reverseMatches;
			CodeMemberMethod childMethod;
			CodeExpression hasJSRef = GroupZero ?
				(CodeExpression) new CodeVariableReferenceExpression ("hasJavaScript") :
				(CodeExpression) new CodeArgumentReferenceExpression ("hasJavaScript");

			reverseMatches = GenerateExceptions (mainClass, !GroupZero);
			if (reverseMatches != null && reverseMatches.Count > 0)
				foreach (CodeConditionStatement ccs in reverseMatches)
					method.Statements.Add (ccs);
      
			if (childGroups.Count > 0) {
				CodeDirectionExpression hasJavaScript = new CodeDirectionExpression (FieldDirection.Out, hasJSRef);
				CodeExpression ualengthRef = GroupZero ?
					(CodeExpression) new CodeVariableReferenceExpression ("ualength") :
					(CodeExpression) new CodeArgumentReferenceExpression ("ualength");

				int groupId = 0;
	
				CodeMethodReturnStatement returnHasJS = new CodeMethodReturnStatement (
					new CodeVariableReferenceExpression ("hasJavaScript"));
				
				foreach (GroupDefinition gd in childGroups) {
					matches = gd.GenerateConditionStatement (mainClass);

					if (gd.ChildGroups.Count > 0) {
						childMethod = gd.GenerateMethod (mainClass);

						subMatches = new CodeConditionStatement ();
						subMatches.Condition = new CodeMethodInvokeExpression (
							new CodeMethodReferenceExpression (
								new CodeTypeReferenceExpression ("UplevelHelper"), childMethod.Name),
							new CodeExpression[] {new CodeArgumentReferenceExpression ("ua"),
									      hasJavaScript, ualengthRef}
						);
						subMatches.TrueStatements.Add (returnHasJS);
						subMatches.FalseStatements.Add (new CodeMethodReturnStatement (
											new CodePrimitiveExpression (false))
						);
						
						matches.TrueStatements.Add (subMatches);
					} else {
						reverseMatches = gd.GenerateExceptions (mainClass, !GroupZero);
						if (reverseMatches != null && reverseMatches.Count > 0)
							foreach (CodeConditionStatement ccs in reverseMatches)
								matches.TrueStatements.Add (ccs);
	    
						if (!GroupZero && gd.Positional)
							matches.TrueStatements.Add (
								new CodeAssignStatement (
									new CodeVariableReferenceExpression ("hasJavaScript"),
									new CodePrimitiveExpression (true))
							);
						matches.TrueStatements.Add (returnTrue);
					}
					method.Statements.Add (matches);
					groupId++;
				}

				// return false;
				method.Statements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (false)));
			} else 
				// return <valueOf_DefaultJS>
				method.Statements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (DefaultJS)));
      
			return method;
		}
コード例 #23
0
ファイル: DryadLinqCodeGen.cs プロジェクト: pszmyd/Dryad
            MakeReadFieldStatements(Type type,
                                    CodeExpression objExpr,
                                    FieldInfo finfo,
                                    CodeVariableReferenceExpression[] indexExprs)
        {
            CodeStatement[] stmts;
            CodeExpression readerExpr = new CodeArgumentReferenceExpression("reader");
            string readerName = GetBuiltinReaderName(type);
            if (readerName == null)
            {
                // For non-builtin types
                string serializerName = GetStaticSerializerName(type);
                CodeVariableReferenceExpression serializerExpr = new CodeVariableReferenceExpression(serializerName);                
                CodeVariableDeclarationStatement tempDecl = null;
                CodeExpression setterExpr = null;

                CodeExpression fieldExpr;
                if (finfo == null)
                {
                    fieldExpr = new CodeArrayIndexerExpression(objExpr, indexExprs);
                }
                else if (finfo.IsPublic && !finfo.IsInitOnly)
                {
                    fieldExpr = new CodeFieldReferenceExpression(objExpr, finfo.Name);
                }
                else
                {
                    string fieldName = TypeSystem.FieldName(finfo.Name);
                    if (!TypeSystem.IsBackingField(finfo.Name) ||
                        finfo.DeclaringType.GetProperty(fieldName, FieldFlags).GetSetMethod() == null)
                    {
                        setterExpr = new CodeVariableReferenceExpression(ExtensionClassName + "." + this.SetterFieldName(finfo));
                        fieldName = this.m_fieldToStaticName[finfo];
                    }
                    tempDecl = new CodeVariableDeclarationStatement(type, fieldName);
                    fieldExpr = new CodeVariableReferenceExpression(tempDecl.Name);
                }

                CodeExpression fieldValExpr = new CodeMethodInvokeExpression(serializerExpr, "Read", readerExpr);
                CodeStatement readCall = new CodeAssignStatement(fieldExpr, fieldValExpr);
                if (tempDecl == null)
                {
                    stmts = new CodeStatement[] { readCall };
                }
                else
                {
                    CodeStatement setCall;
                    if (setterExpr == null)
                    {
                        CodeExpression propExpr = new CodePropertyReferenceExpression(objExpr, tempDecl.Name);
                        setCall = new CodeAssignStatement(propExpr, fieldExpr);
                    }
                    else
                    {
                        if (finfo.DeclaringType.IsValueType)
                        {
                            objExpr = new CodeDirectionExpression(FieldDirection.Out, objExpr);
                        }
                        CodeExpression setExpr = new CodeDelegateInvokeExpression(setterExpr, objExpr, fieldExpr);
                        setCall = new CodeExpressionStatement(setExpr);
                    }
                    stmts = new CodeStatement[] { tempDecl, readCall, setCall };
                }
            }
            else
            {
                // for builtin types
                CodeExpression readCall = new CodeMethodInvokeExpression(readerExpr, readerName);
                if (finfo == null)
                {
                    CodeExpression fieldExpr = new CodeArrayIndexerExpression(objExpr, indexExprs);
                    stmts = new CodeStatement[] { new CodeAssignStatement(fieldExpr, readCall) };
                }
                else
                {
                    string fieldName = TypeSystem.FieldName(finfo.Name);
                    if ((finfo.IsPublic && !finfo.IsInitOnly) ||
                        (TypeSystem.IsBackingField(finfo.Name) &&
                         finfo.DeclaringType.GetProperty(fieldName, FieldFlags).GetSetMethod() != null))
                    {
                        CodeExpression fieldExpr = new CodeFieldReferenceExpression(objExpr, fieldName);
                        stmts = new CodeStatement[] { new CodeAssignStatement(fieldExpr, readCall) };
                    }
                    else
                    {
                        CodeExpression setterExpr = new CodeVariableReferenceExpression(
                                                            ExtensionClassName + "." + this.SetterFieldName(finfo));
                        if (finfo.DeclaringType.IsValueType)
                        {
                            objExpr = new CodeDirectionExpression(FieldDirection.Out, objExpr);
                        }
                        CodeExpression setExpr = new CodeDelegateInvokeExpression(setterExpr, objExpr, readCall);
                        stmts = new CodeStatement[] { new CodeExpressionStatement(setExpr) };
                    }
                }
            }

            if (!type.IsValueType &&
                (finfo != null || StaticConfig.AllowNullArrayElements) &&
                (finfo == null || AttributeSystem.FieldCanBeNull(finfo)))
            {
                CodeExpression bvIndex = indexExprs[0];
                if (finfo == null)
                {
                    string bvIndexString = indexExprs[0].VariableName;
                    for (int i = 1; i < indexExprs.Length; i++)
                    {
                        bvIndexString += "*" + indexExprs[i].VariableName;
                    }
                    bvIndex = new CodeSnippetExpression(bvIndexString);
                }
                CodeExpression bvExpr = new CodeArgumentReferenceExpression("bv");
                CodeExpression ifExpr = new CodeBinaryOperatorExpression(
                                                new CodeIndexerExpression(bvExpr, bvIndex),
                                                CodeBinaryOperatorType.IdentityEquality,
                                                new CodePrimitiveExpression(false));
                CodeStatement stmt = new CodeConditionStatement(ifExpr, stmts);
                stmts = new CodeStatement[] { stmt };
            }
            return stmts;
        }
コード例 #24
0
ファイル: TypeBuilder.cs プロジェクト: pusp/o2platform
        internal static CodeTypeDeclaration CreateTypeManager(XmlQualifiedName rootElementName,
                                                              bool enableServiceReference,  
                                                              CodeStatementCollection typeDictionaryStatements, 
                                                              CodeStatementCollection elementDictionaryStatements,
                                                              CodeStatementCollection wrapperDictionaryStatements) {
            //Create the services type class and add members
            string servicesClassName = NameGenerator.GetServicesClassName();
            CodeTypeDeclaration servicesTypeDecl = new CodeTypeDeclaration(servicesClassName);
            servicesTypeDecl.Attributes = MemberAttributes.Public;

            //Create singleton
            CodeMemberField singletonField = CodeDomHelper.CreateMemberField(Constants.TypeManagerSingletonField, servicesClassName, MemberAttributes.Static, true);
            CodeMemberProperty singletonProperty = CodeDomHelper.CreateProperty(Constants.TypeManagerInstance, null, singletonField, MemberAttributes.Public | MemberAttributes.Static, false);

            MemberAttributes privateStatic = MemberAttributes.Private | MemberAttributes.Static;
            //Create static constructor
            CodeTypeConstructor staticServicesConstructor = new CodeTypeConstructor();

            CodeTypeReference returnType = CodeDomHelper.CreateDictionaryType("XName", "System.Type");
            CodeTypeReference wrapperReturnType = CodeDomHelper.CreateDictionaryType("System.Type", "System.Type");
            
            //Create a dictionary of TypeName vs System.Type and the method to create it
            CodeMemberProperty typeDictProperty = null;
            if (typeDictionaryStatements.Count > 0) {
                
                typeDictProperty = CodeDomHelper.CreateInterfaceImplProperty(Constants.GlobalTypeDictionary, Constants.ILinqToXsdTypeManager, returnType, Constants.TypeDictionaryField);
                
                CodeMemberField staticTypeDictionary = CodeDomHelper.CreateDictionaryField(Constants.TypeDictionaryField, "XName", "System.Type");
                CodeMemberMethod buildTypeDictionary = CodeDomHelper.CreateMethod(Constants.BuildTypeDictionary, privateStatic, null);
                buildTypeDictionary.Statements.AddRange(typeDictionaryStatements);

                staticServicesConstructor.Statements.Add(CodeDomHelper.CreateMethodCall(null, Constants.BuildTypeDictionary));
                servicesTypeDecl.Members.Add(staticTypeDictionary);
                servicesTypeDecl.Members.Add(buildTypeDictionary);
            }                
            else {
                typeDictProperty = CodeDomHelper.CreateInterfaceImplProperty(Constants.GlobalTypeDictionary, Constants.ILinqToXsdTypeManager, returnType);
                typeDictProperty.GetStatements.Add(
                    new CodeMethodReturnStatement(
                        new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(Constants.XTypedServices), Constants.EmptyDictionaryField)));
            }

            //Create a dictionary of ElementName Vs System.Type - For Auto typing and substitutionGroups
            CodeMemberProperty elementDictProperty = null;
            if (elementDictionaryStatements.Count > 0) {
                elementDictProperty = CodeDomHelper.CreateInterfaceImplProperty(Constants.GlobalElementDictionary, Constants.ILinqToXsdTypeManager, returnType, Constants.ElementDictionaryField);
                
                CodeMemberField staticElementDictionary = CodeDomHelper.CreateDictionaryField(Constants.ElementDictionaryField, "XName", "System.Type");
                CodeMemberMethod buildElementDictionary = CodeDomHelper.CreateMethod(Constants.BuildElementDictionary, privateStatic, null);
                buildElementDictionary.Statements.AddRange(elementDictionaryStatements);

                staticServicesConstructor.Statements.Add(CodeDomHelper.CreateMethodCall(null, Constants.BuildElementDictionary));
                servicesTypeDecl.Members.Add(staticElementDictionary);
                servicesTypeDecl.Members.Add(buildElementDictionary);
            }  
            else {
                elementDictProperty = CodeDomHelper.CreateInterfaceImplProperty(Constants.GlobalElementDictionary, Constants.ILinqToXsdTypeManager, returnType);
                elementDictProperty.GetStatements.Add(
                    new CodeMethodReturnStatement(
                        new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(Constants.XTypedServices), Constants.EmptyDictionaryField)));
            }              

            //Create a dictionary of Wrapper Element Type Vs Wrapper Type - For Auto typing when casting from XElement to Type
            CodeMemberProperty wrapperDictProperty = null;
            if (wrapperDictionaryStatements.Count > 0) {
                wrapperDictProperty = CodeDomHelper.CreateInterfaceImplProperty(Constants.RootContentTypeMapping, Constants.ILinqToXsdTypeManager, wrapperReturnType, Constants.WrapperDictionaryField);
                
                CodeMemberField staticWrapperDictionary = CodeDomHelper.CreateDictionaryField(Constants.WrapperDictionaryField, "System.Type", "System.Type");
                CodeMemberMethod buildWrapperDictionary = CodeDomHelper.CreateMethod(Constants.BuildWrapperDictionary, privateStatic, null);
                buildWrapperDictionary.Statements.AddRange(wrapperDictionaryStatements);
                
                staticServicesConstructor.Statements.Add(CodeDomHelper.CreateMethodCall(null, Constants.BuildWrapperDictionary));
                servicesTypeDecl.Members.Add(staticWrapperDictionary);
                servicesTypeDecl.Members.Add(buildWrapperDictionary);
            }        
            else {
                wrapperDictProperty = CodeDomHelper.CreateInterfaceImplProperty(Constants.RootContentTypeMapping, Constants.ILinqToXsdTypeManager, wrapperReturnType);
                wrapperDictProperty.GetStatements.Add(
                    new CodeMethodReturnStatement(
                        new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(Constants.XTypedServices), Constants.EmptyTypeMappingDictionary)));
            }

            //Implement IXmlSerializable AddSchemas method for the XmlSchemaProvider method and Schemas get set property for runtime access to schemas
            //if (enableServiceReference) { //Since property is on the interface, it has to be implemented;
                string schemaSetFieldName = "schemaSet";
                CodeTypeReference schemaSetType = new CodeTypeReference("XmlSchemaSet");

                CodeMemberField schemaSetField = new CodeMemberField(schemaSetType, schemaSetFieldName);
                schemaSetField.Attributes = MemberAttributes.Private | MemberAttributes.Static;

                    //AddSchemas method
                CodeMemberMethod addSchemasMethod = CodeDomHelper.CreateMethod("AddSchemas", MemberAttributes.FamilyOrAssembly | MemberAttributes.Static, null);
                addSchemasMethod.Parameters.Add(new CodeParameterDeclarationExpression("XmlSchemaSet", "schemas"));
                //schemas.Add(schemaSet);
                addSchemasMethod.Statements.Add(CodeDomHelper.CreateMethodCall(new CodeVariableReferenceExpression("schemas"), "Add", new CodeFieldReferenceExpression(null, schemaSetFieldName)));

                
                CodeTypeReferenceExpression interLockedType = new CodeTypeReferenceExpression("System.Threading.Interlocked");

                CodeMemberProperty schemaSetProperty = CodeDomHelper.CreateInterfaceImplProperty("Schemas", Constants.ILinqToXsdTypeManager, schemaSetType);
                CodeFieldReferenceExpression schemaSetFieldRef = new CodeFieldReferenceExpression(null, schemaSetFieldName);
                
                CodeDirectionExpression schemaSetParam = new CodeDirectionExpression(FieldDirection.Ref, schemaSetFieldRef);

                schemaSetProperty.GetStatements.Add(
                    new CodeConditionStatement(
                        new CodeBinaryOperatorExpression(schemaSetFieldRef, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null)),
                        new CodeVariableDeclarationStatement(schemaSetType, "tempSet", new CodeObjectCreateExpression(schemaSetType)),
                        new CodeExpressionStatement(
                            CodeDomHelper.CreateMethodCall(interLockedType, "CompareExchange",
                                                        schemaSetParam, 
                                                        new CodeVariableReferenceExpression("tempSet"), 
                                                        new CodePrimitiveExpression(null)))));
                
                schemaSetProperty.GetStatements.Add(
                    new CodeMethodReturnStatement(
                        new CodeVariableReferenceExpression(schemaSetFieldName)));

                //Setter
                schemaSetProperty.SetStatements.Add(new CodeAssignStatement(schemaSetFieldRef, new CodePropertySetValueReferenceExpression()));

                servicesTypeDecl.Members.Add(schemaSetField);
                servicesTypeDecl.Members.Add(schemaSetProperty);
                servicesTypeDecl.Members.Add(addSchemasMethod);
            //}
            //Implement ILinqToXsdTypeManager
            servicesTypeDecl.Members.Add(typeDictProperty);
            servicesTypeDecl.Members.Add(elementDictProperty);
            servicesTypeDecl.Members.Add(wrapperDictProperty);
            servicesTypeDecl.BaseTypes.Add(Constants.ILinqToXsdTypeManager);
            
            


            //Add a getter that will get the root type name
            CodeMemberMethod getRootType = new CodeMemberMethod(); 
            getRootType.Attributes = MemberAttributes.Static | MemberAttributes.Public;
            getRootType.Name = Constants.GetRootType;
            getRootType.ReturnType = new CodeTypeReference("System.Type");
            if (rootElementName.IsEmpty) {
                getRootType.Statements.Add(
                    new CodeMethodReturnStatement(
                        CodeDomHelper.Typeof("Xml.Schema.Linq.XTypedElement")));
            }
            else {
                getRootType.Statements.Add(
                    new CodeMethodReturnStatement(
                        new CodeIndexerExpression(
                            CodeDomHelper.CreateFieldReference(null, Constants.ElementDictionaryField),
                            CodeDomHelper.XNameGetExpression(rootElementName.Name, rootElementName.Namespace))));
            }

            servicesTypeDecl.Members.Add(staticServicesConstructor);
            servicesTypeDecl.Members.Add(getRootType);
            servicesTypeDecl.Members.Add(singletonField);
            servicesTypeDecl.Members.Add(singletonProperty);
            return servicesTypeDecl;
        }
コード例 #25
0
ファイル: DryadLinqCodeGen.cs プロジェクト: pszmyd/Dryad
        // Add the serializer class
        internal string AddSerializerClass(Type type)
        {
            // Check if the serializer class is built-in
            string serializerName = GetBuiltInDryadLinqSerializer(type);
            if (serializerName != null)
            {
                return serializerName;
            }

            // Check if the serializer class is already generated
            if (this.m_typeToSerializerName.TryGetValue(type, out serializerName))
            {
                return serializerName;
            }

            // Check for custom serialization
            Type customSerializerType = FindCustomSerializerType(type);
            if (customSerializerType != null)
            {
                serializerName = TypeSystem.TypeName(customSerializerType, this.AnonymousTypeToName);
                if (type.IsGenericType)
                {
                    Type[] argTypes = type.GetGenericArguments();
                    int len = argTypes.Length;
                    for (int i = 0; i < len; i++)
                    {
                        this.AddAnonymousClass(argTypes[i]);
                    }
                    if (customSerializerType.IsGenericTypeDefinition)
                    {
                        if (customSerializerType.GetGenericArguments().Length != len * 2)
                        {
                            throw new DryadLinqException("The custom serializer " + customSerializerType +
                                                         " must have " + (len*2) + " generic type parameters.");
                        }

                        int cnt = 1;
                        int matchIdx = serializerName.Length - 2;
                        while (matchIdx >= 0)
                        {
                            if (serializerName[matchIdx] == '>') cnt++;
                            if (serializerName[matchIdx] == '<') cnt--;
                            if (cnt == 0) break;
                            matchIdx--;
                        }
                        serializerName = serializerName.Substring(0, matchIdx);
                        serializerName += "<";
                        for (int i = 0; i < len; i++)
                        {
                            serializerName += this.MakeTypeNameAlias(
                                                      TypeSystem.TypeName(argTypes[i], this.m_anonymousTypeToName));
                            serializerName += ",";
                        }
                        for (int i = 0; i < len; i++)
                        {
                            serializerName += this.MakeTypeNameAlias(this.AddSerializerClass(argTypes[i]));
                            if (i < (len-1)) serializerName += ",";
                        }
                        serializerName += ">";
                    }
                }
                return serializerName;
            }

            if (!TypeSystem.IsAnonymousType(type))
            {
                if (!type.IsPublic && !type.IsNestedPublic)
                {
                    throw new DryadLinqException(DryadLinqErrorCode.TypeRequiredToBePublic,
                                                 String.Format(SR.TypeRequiredToBePublic, type));
                }
                if (IsObject(type))
                {
                    throw new DryadLinqException(DryadLinqErrorCode.CannotHandleObjectFields,
                                                 String.Format(SR.CannotHandleObjectFields, type.FullName));
                }

                // The serializer has troubles if a data type has no data-members, so we outlaw these.
                // Abstract classes don't admit such an easy test. 
                if (!type.IsAbstract && TypeSystem.GetSize(type) == 0)
                {
                    throw new DryadLinqException(DryadLinqErrorCode.TypeMustHaveDataMembers,
                                                 String.Format(SR.TypeMustHaveDataMembers, type));
                }
            }

            bool isReal = TypeSystem.IsRealType(type);
            this.AddAnonymousClass(type);
            bool isTypeSerializable = TypeSystem.IsTypeSerializable(type);

            // Check for builtin serialization
            CodeExpression serializationTypeExpr = null;
            if (type.IsGenericType)
            {
                string serializationClassName = GetGenericSerializationClassName(type);
                if (serializationClassName != null)
                {
                    // Add anonymous classes for type arguments
                    Type[] argTypes = type.GetGenericArguments();
                    int len = argTypes.Length;
                    for (int i = 0; i < len; i++)
                    {
                        this.AddAnonymousClass(argTypes[i]);
                    }
                    CodeTypeReference[] argRefs = new CodeTypeReference[len * 2];
                    for (int i = 0; i < len; i++)
                    {
                        argRefs[i] = new CodeTypeReference(this.MakeTypeNameAlias(TypeSystem.TypeName(argTypes[i], this.m_anonymousTypeToName)));
                        argRefs[len + i] = new CodeTypeReference(this.MakeTypeNameAlias(this.AddSerializerClass(argTypes[i])));
                    }
                    CodeTypeReference typeRef = new CodeTypeReference(serializationClassName, argRefs);
                    serializationTypeExpr = new CodeTypeReferenceExpression(typeRef);
                }
            }

            // We now add the serializer class
            serializerName = "DryadLinqSerializer" + MakeName(type);
            this.m_typeToSerializerName[type] = serializerName;
            string typeName = TypeSystem.TypeName(type, this.m_anonymousTypeToName);
            string baseClassName = "DryadLinqSerializer<" + typeName + ">";
            CodeTypeDeclaration serializerClass = new CodeTypeDeclaration(serializerName + " : " + baseClassName);
            this.m_dryadCodeSpace.Types.Add(serializerClass);
            serializerClass.IsClass = true;
            serializerClass.TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed;

            // Add the Read method
            CodeMemberMethod readMethod = new CodeMemberMethod();
            serializerClass.Members.Add(readMethod);
            readMethod.Attributes = MemberAttributes.Public | MemberAttributes.Override;
            readMethod.Name = "Read";
            readMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(DryadLinqBinaryReader), "reader"));
            typeName = this.MakeTypeNameAlias(typeName);
            readMethod.ReturnType = new CodeTypeReference(typeName);

            CodeExpression objExpr = new CodeArgumentReferenceExpression("obj");
            CodeExpression readerExpr = new CodeArgumentReferenceExpression("reader");
            if (type.IsEnum)
            {
                string readerName = GetBuiltinReaderName(type.GetFields()[0].FieldType);
                CodeExpression valExpr = new CodeMethodInvokeExpression(readerExpr, readerName);
                valExpr = new CodeCastExpression(type, valExpr);
                readMethod.Statements.Add(new CodeMethodReturnStatement(valExpr));                
            }
            else if (serializationTypeExpr != null)
            {
                CodeExpression outObjExpr = new CodeDirectionExpression(FieldDirection.Out, objExpr);
                CodeExpression readCallExpr = new CodeMethodInvokeExpression(
                                                      serializationTypeExpr, "Read", readerExpr, outObjExpr);
                readMethod.Statements.Add(new CodeVariableDeclarationStatement(typeName, "obj"));
                readMethod.Statements.Add(new CodeExpressionStatement(readCallExpr));
                readMethod.Statements.Add(new CodeMethodReturnStatement(objExpr));
            }
            else if (TypeSystem.IsAnonymousType(type))
            {
                string className = this.m_anonymousTypeToName[type];
                CodeExpression newObjectCall = new CodeMethodInvokeExpression(
                                                       new CodeTypeReferenceExpression("FormatterServices"),
                                                       "GetUninitializedObject",
                                                       new CodeTypeOfExpression(className));
                newObjectCall = new CodeCastExpression(className, newObjectCall);
                readMethod.Statements.Add(new CodeVariableDeclarationStatement(className, "obj", newObjectCall));

                PropertyInfo[] props = type.GetProperties();
                System.Array.Sort(props, (x, y) => x.MetadataToken.CompareTo(y.MetadataToken));
                for (int i = 0; i < props.Length; i++)
                {
                    string fieldName = "_" + props[i].Name;
                    CodeExpression fieldExpr = new CodeFieldReferenceExpression(objExpr, fieldName);
                    string readerName = GetBuiltinReaderName(props[i].PropertyType);
                    CodeStatement stmt;
                    if (readerName == null)
                    {
                        string fieldSerializerName = GetStaticSerializerName(props[i].PropertyType);
                        CodeVariableReferenceExpression
                            serializerExpr = new CodeVariableReferenceExpression(fieldSerializerName);
                        CodeExpression
                            readCallExpr = new CodeMethodInvokeExpression(serializerExpr, "Read", readerExpr);
                        stmt = new CodeAssignStatement(fieldExpr, readCallExpr);
                    }
                    else
                    {
                        CodeExpression readCallExpr = new CodeMethodInvokeExpression(readerExpr, readerName);
                        stmt = new CodeAssignStatement(fieldExpr, readCallExpr);
                    }
                    if (!props[i].PropertyType.IsValueType)
                    {
                        CodeExpression ifExpr = new CodeMethodInvokeExpression(readerExpr, "ReadBool");
                        stmt = new CodeConditionStatement(ifExpr, stmt);
                    }
                    readMethod.Statements.Add(stmt);
                }
                readMethod.Statements.Add(new CodeMethodReturnStatement(objExpr));
            }
            else if (!isReal)
            {
                throw new DryadLinqException(DryadLinqErrorCode.UDTMustBeConcreteType,
                                             String.Format(SR.UDTMustBeConcreteType, type.FullName));
            }
            else if (TypeSystem.HasFieldOfNonPublicType(type))
            {
                throw new DryadLinqException(DryadLinqErrorCode.UDTHasFieldOfNonPublicType,
                                             String.Format(SR.UDTHasFieldOfNonPublicType, type.FullName));
            }
            else if (typeof(System.Delegate).IsAssignableFrom(type))
            {
                throw new DryadLinqException(DryadLinqErrorCode.UDTIsDelegateType,
                                             String.Format(SR.UDTIsDelegateType, type.FullName));
            }
            else if (!type.IsSealed && TypeSystem.HasSubtypes(type))
            {
                throw new DryadLinqException(DryadLinqErrorCode.CannotHandleSubtypes,
                                             String.Format(SR.CannotHandleSubtypes, type.FullName));
            }
            else if (isTypeSerializable)   // The only choice we have left is to add the auto generated Read method body. 
            {
                // make sure we aren't trying to auto-serialize a circular type
                if (TypeSystem.IsCircularType(type))
                {
                    throw new DryadLinqException(DryadLinqErrorCode.CannotHandleCircularTypes,
                                                 String.Format(SR.CannotHandleCircularTypes, type.FullName));
                }
                readMethod.Statements.AddRange(this.MakeReadMethodBody(type));
            }
            else
            {
                // tell the user we could do this automatically for them, but they just need to ask explicitly
                throw new DryadLinqException(DryadLinqErrorCode.TypeNotSerializable,
                                             String.Format(SR.TypeNotSerializable, type.FullName));
            }
            
            // Add the Write method
            CodeMemberMethod writeMethod = new CodeMemberMethod();
            serializerClass.Members.Add(writeMethod);
            writeMethod.Attributes = MemberAttributes.Public | MemberAttributes.Override;
            writeMethod.Name = "Write";
            writeMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(DryadLinqBinaryWriter), "writer"));
            writeMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeName, "obj"));
            writeMethod.ReturnType = new CodeTypeReference(typeof(void));

            CodeExpression writerExpr = new CodeArgumentReferenceExpression("writer");
            if (type.IsEnum)
            {
                Type intType = type.GetFields()[0].FieldType;
                CodeExpression valExpr = new CodeCastExpression(intType, objExpr);
                CodeExpression writeCallExpr = new CodeMethodInvokeExpression(writerExpr, "Write", valExpr);
                writeMethod.Statements.Add(new CodeExpressionStatement(writeCallExpr));
            }
            else if (serializationTypeExpr != null)
            {
                CodeExpression writeCallExpr = new CodeMethodInvokeExpression(
                                                       serializationTypeExpr, "Write", writerExpr, objExpr);
                writeMethod.Statements.Add(new CodeExpressionStatement(writeCallExpr));
            }
            else if (TypeSystem.IsAnonymousType(type))
            {
                PropertyInfo[] props = type.GetProperties();
                System.Array.Sort(props, (x, y) => x.MetadataToken.CompareTo(y.MetadataToken));
                for (int i = 0; i < props.Length; i++)
                {
                    Type fieldType = props[i].PropertyType;
                    string fieldName = "_" + props[i].Name;
                    CodeExpression fieldExpr = new CodeFieldReferenceExpression(objExpr, fieldName);
                    CodeExpression writeCall;
                    if (GetBuiltinReaderName(type) == null)
                    {
                        string fieldSerializerName = GetStaticSerializerName(fieldType);
                        CodeVariableReferenceExpression
                            serializerExpr = new CodeVariableReferenceExpression(fieldSerializerName);
                        writeCall = new CodeMethodInvokeExpression(serializerExpr, "Write", writerExpr, fieldExpr);
                    }
                    else
                    {
                        writeCall = new CodeMethodInvokeExpression(writerExpr, "Write", fieldExpr);
                    }
                    CodeStatement stmt = new CodeExpressionStatement(writeCall);
                    if (!fieldType.IsValueType)
                    {
                        CodeExpression nullExpr = new CodeMethodInvokeExpression(
                                                          new CodeTypeReferenceExpression("Object"),
                                                          "ReferenceEquals",
                                                          fieldExpr,
                                                          NullExpr);
                        CodeExpression notNullExpr = new CodeBinaryOperatorExpression(
                                                             nullExpr,
                                                             CodeBinaryOperatorType.IdentityEquality,
                                                             new CodePrimitiveExpression(false));
                        writeCall = new CodeMethodInvokeExpression(writerExpr, "Write", notNullExpr);
                        writeMethod.Statements.Add(new CodeExpressionStatement(writeCall));
                        stmt = new CodeConditionStatement(notNullExpr, stmt);
                    }
                    writeMethod.Statements.Add(stmt);
                }
            }
            else
            {
                writeMethod.Statements.AddRange(this.MakeWriteMethodBody(type));
            }

            return serializerName;
        }
コード例 #26
0
ファイル: PhpGenerator.CLR.cs プロジェクト: jdluzen/Phalanger
 /// <summary>
 /// Generates code for the specified direction expression.
 /// </summary>
 /// <remarks><c>EXPRESSION</c></remarks>
 protected override void GenerateDirectionExpression(CodeDirectionExpression e)
 {
     GenerateExpression(e);
 }
コード例 #27
0
ファイル: CodeGenerator.cs プロジェクト: carrie901/mono
		protected virtual void GenerateDirectionExpression (CodeDirectionExpression e)
		{
			OutputDirection (e.Direction);
			output.Write (' ');
			GenerateExpression (e.Expression);
		}
コード例 #28
0
 public virtual CodeExpression DoMethodInvokeCore(CodeMemberMethod method, string methodName, System.Type returnType, CodeExpression targetObject, List<CodeExpression> parameters)
 {
     CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression(targetObject, methodName, new CodeExpression[0]);
     foreach (CodeExpression expression2 in parameters)
     {
         AxParameterData data = (AxParameterData) expression2.UserData[typeof(AxParameterData)];
         CodeExpression expression3 = expression2;
         if (data != null)
         {
             expression3 = new CodeDirectionExpression(data.Direction, expression2);
         }
         expression.Parameters.Add(expression3);
     }
     if (returnType == typeof(void))
     {
         method.Statements.Add(new CodeExpressionStatement(expression));
         return null;
     }
     CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(returnType, ReturnValueVariableName, new CodeCastExpression(returnType, expression));
     method.Statements.Add(statement);
     return new CodeVariableReferenceExpression(ReturnValueVariableName);
 }
コード例 #29
0
 protected override void GenerateDirectionExpression(CodeDirectionExpression e)
 {
     base.GenerateExpression(e.Expression);
 }
コード例 #30
0
        public static List<CodeExpression> SetMethodParams(
            this CodeMemberMethod method,
            IMethodSymbol methodSymbol,
            IList<string> namespaces,
            string argumentNameToReplaceWithThis = null)
        {
            List<CodeExpression> passedParameters = new List<CodeExpression>();

            foreach (IParameterSymbol argSymbol in methodSymbol.Parameters)
            {
                CodeParameterDeclarationExpression argParam = new CodeParameterDeclarationExpression
                {
                    Type = argSymbol.Type.GetTypeReference(namespaces)
                };

                string argName = argSymbol.Name;

                CodeExpression passedParameter = null;

                if ((argumentNameToReplaceWithThis != null) && (argumentNameToReplaceWithThis.Equals(argName)))
                {
                    passedParameter = new CodeThisReferenceExpression();
                }
                else
                {
                    passedParameter = new CodeVariableReferenceExpression(argName);
                }

                argParam.Name = argName;

                FieldDirection direction = argSymbol.RefKind.GetDirection();

                if (direction != FieldDirection.In)
                {
                    passedParameter = new CodeDirectionExpression(direction, passedParameter);
                }

                passedParameters.Add(passedParameter);

                argParam.Direction = direction;

                if (argSymbol.HasExplicitDefaultValue)
                {
                    argParam.Name += "=" + argSymbol.ExplicitDefaultValue.ObjToStr();
                }

                method.Parameters.Add(argParam);
            }

            return passedParameters;
        }