Inheritance: System.CodeDom.CodeExpression
		public void Constructor0_Deny_Unrestricted ()
		{
			CodeArrayIndexerExpression caie = new CodeArrayIndexerExpression ();
			Assert.AreEqual (0, caie.Indices.Count, "Indices");
			Assert.IsNull (caie.TargetObject, "TargetObject");
			caie.TargetObject = new CodeExpression ();
		}
Beispiel #2
0
        void EmitArrayIndexer(CodeArrayIndexerExpression array)
        {
            if (array.TargetObject is CodePropertyReferenceExpression &&
                ((CodePropertyReferenceExpression)array.TargetObject).PropertyName == Parser.VarProperty &&
                array.Indices.Count == 1 && array.Indices[0] is CodePrimitiveExpression)
            {
                var name = ((CodePrimitiveExpression)array.Indices[0]).Value as string;

                if (name != null)
                {
                    var sep = name.IndexOf(Parser.ScopeVar);

                    if (sep != -1)
                        name = name.Substring(sep + 1);

                    writer.Write(name);
                    return;
                }
            }

            EmitExpression(array.TargetObject);

            foreach (CodeExpression index in array.Indices)
            {
                writer.Write(Parser.ArrayOpen);
                EmitExpression(index);
                writer.Write(Parser.ArrayClose);
            }
        }
		public void Constructor1_Deny_Unrestricted ()
		{
			CodeExpression target = new CodeExpression ();
			CodeExpression[] parameters = new CodeExpression[1] { target };
			CodeArrayIndexerExpression caie = new CodeArrayIndexerExpression (target, parameters);
			Assert.AreEqual (1, caie.Indices.Count, "Indices");
			Assert.AreSame (target, caie.TargetObject, "TargetObject");
			caie.TargetObject = new CodeExpression ();
		}
 public static CodeArrayIndexerExpression Clone(this CodeArrayIndexerExpression expression)
 {
     if (expression == null) return null;
     CodeArrayIndexerExpression e = new CodeArrayIndexerExpression();
     e.Indices.AddRange(expression.Indices.Clone());
     e.TargetObject = expression.TargetObject.Clone();
     e.UserData.AddRange(expression.UserData);
     return e;
 }
Beispiel #5
0
        private void EmitArrayIndexerExpression(CodeArrayIndexerExpression Indexer)
        {
            var index = (CodeArrayIndexerExpression) Indexer;

            Generator.Emit(OpCodes.Ldloc, VarsProperty);
            EmitExpression(index.Indices[0]);

            Generator.Emit(OpCodes.Callvirt, GetVariable);
        }
        /// <summary>
        /// Visits a <see cref="CodeArrayIndexerExpression"/>.
        /// </summary>
        /// <param name="codeArrayIndexerExpression">The <see cref="CodeArrayIndexerExpression"/> to visit.</param>
        protected virtual void VisitCodeArrayIndexerExpression(CodeArrayIndexerExpression codeArrayIndexerExpression)
        {
            if (codeArrayIndexerExpression == null)
            {
                return;
            }

            this.VisitCodeExpression(codeArrayIndexerExpression.TargetObject);
            this.VisitCodeExpressionCollection(codeArrayIndexerExpression.Indices);
        }
Beispiel #7
0
 private CodeExpression BuildArray(CodeStatementCollection statements, string name, object value)
 {
     Array array = (Array) value;
     Type type = value.GetType();
     string uniqueVariableName = GetUniqueVariableName(name, statements);
     CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(type.FullName, uniqueVariableName);
     statement.InitExpression = new CodeArrayCreateExpression(type.GetElementType(), array.Length);
     statements.Add(statement);
     CodeVariableReferenceExpression targetObject = new CodeVariableReferenceExpression(uniqueVariableName);
     string str2 = name + "_";
     for (int i = 0; i < array.Length; i++)
     {
         CodeArrayIndexerExpression left = new CodeArrayIndexerExpression(targetObject, new CodeExpression[0]);
         left.Indices.Add(new CodePrimitiveExpression(i));
         CodeExpression right = this.BuildObject(statements, str2 + i.ToString(), array.GetValue(i));
         statements.Add(new CodeAssignStatement(left, right));
     }
     return targetObject;
 }
Beispiel #8
0
        static CodeMemberProperty CreateProperty(PropertyNameType nameType, string constantsClassName, string defaultValuesClassName)
        {
            CodeMemberProperty publicProp = new CodeMemberProperty();
            publicProp.Name = nameType.propertyName;
            publicProp.Attributes = CodeDomHelperObjects.PublicFinal;
            publicProp.HasGet = true;
            publicProp.HasSet = true;
            publicProp.Type = new CodeTypeReference(nameType.propertyType);

            CodeAttributeDeclarationCollection attributes = new CodeAttributeDeclarationCollection();
            CodeAttributeArgument arg1 = new CodeAttributeArgument(
                                            new CodeFieldReferenceExpression(
                                                new CodeTypeReferenceExpression(constantsClassName),
                                                nameType.propertyName));
            CodeAttributeArgument arg2 = new CodeAttributeArgument(
                                            PropertyNameConstants.DefaultValueProperty,
                                            new CodeFieldReferenceExpression(
                                                new CodeTypeReferenceExpression(defaultValuesClassName),
                                                Constants.DefaultPrefix + nameType.propertyName));
            // Future TODO: Provide a library with attributes that custom channel writes 
            // can use to adorn their properties with default values and validators, we can
            // then add it here.
            attributes.Add(new CodeAttributeDeclaration(
                            new CodeTypeReference(TypeNameConstants.ConfigurationProperty),
                            arg1, arg2));
            publicProp.CustomAttributes = new CodeAttributeDeclarationCollection(attributes);
            string nameInConfig = constantsClassName + "." + nameType.propertyName;
            CodeArrayIndexerExpression baseIndexedProperty
                                        = new CodeArrayIndexerExpression(
                                            CodeDomHelperObjects.BaseRef,
                                            new CodeFieldReferenceExpression(
                                                new CodeTypeReferenceExpression(constantsClassName),
                                                nameType.propertyName));
            publicProp.GetStatements.Add(new CodeMethodReturnStatement(
                                                new CodeCastExpression(
                                                    nameType.propertyType,
                                                    baseIndexedProperty)));
            publicProp.SetStatements.Add(new CodeAssignStatement(
                                                baseIndexedProperty,
                                                new CodePropertySetValueReferenceExpression()));
            return publicProp;
        }
Beispiel #9
0
		protected override void GenerateArrayIndexerExpression (CodeArrayIndexerExpression expression)
		{
			TextWriter output = Output;

			GenerateExpression (expression.TargetObject);
			output.Write ("(");
			OutputExpressionList (expression.Indices);
			output.Write (')');
		}
		private void CreateVertexInputMethods()
		{
			AsmListing asmVS = this.source.GetAsmTechnique(this.techniqueName, this.platform).VertexShader;

			//create the GetVertexInputCount() and GetVertexInput() methods

			CodeMemberMethod count = new CodeMemberMethod();
			count.Name = "GetVertexInputCountImpl";
			count.Attributes = MemberAttributes.Family | MemberAttributes.Override;
			count.ReturnType = new CodeTypeReference(typeof(int));

			Comment(count, "Returns the number of vertex inputs used by this shader");
			count.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(asmVS.InputCount)));
			classDom.Members.Add(count);

			//inputs are stored in a static array

			//create it...

			int[] arrayValues = new int[asmVS.InputCount * 2];
			for (int i = 0; i < asmVS.InputCount; i++)
			{
				arrayValues[i] = (int)asmVS.GetInput(i).Usage;
				arrayValues[i + asmVS.InputCount] = (int)asmVS.GetInput(i).Index;
			}

			this.vsInputField = new CodeMemberField(typeof(int[]), "vin");
			this.vsInputField.Attributes = MemberAttributes.Private | MemberAttributes.Static | MemberAttributes.Final;
			this.vsInputField.InitExpression = ShaderBytes.ToArray(arrayValues, this.directives);

			CodeFieldReferenceExpression vsInputRef = new CodeFieldReferenceExpression(ShaderClassEx, vsInputField.Name);

			//protected internal abstract void GetVertexInput(int index, out VertexElementUsage elementUsage, out int elementIndex);

			CodeMemberMethod getInput = new CodeMemberMethod();
			getInput.Name = "GetVertexInputImpl";
			getInput.Attributes = MemberAttributes.Family | MemberAttributes.Override;

			CodeParameterDeclarationExpression indexParam = new CodeParameterDeclarationExpression(typeof(int),"i");
			getInput.Parameters.Add(indexParam);

			CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(VertexElementUsage), "usage");
			param.Direction = FieldDirection.Out;
			getInput.Parameters.Add(param);

			param = new CodeParameterDeclarationExpression(typeof(int), "index");
			param.Direction = FieldDirection.Out;
			getInput.Parameters.Add(param);

			CodeArgumentReferenceExpression indexRef = new CodeArgumentReferenceExpression(indexParam.Name);

			//the element index is stored at 'i + asmVS.InputCount'
			CodeExpression indexArray = new CodeArrayIndexerExpression(vsInputRef,
				new CodeBinaryOperatorExpression(indexRef, CodeBinaryOperatorType.Add, new CodePrimitiveExpression(asmVS.InputCount)));

			//and the usage must be cast
			CodeExpression usageCast = new CodeCastExpression(typeof(VertexElementUsage), new CodeArrayIndexerExpression(vsInputRef,indexRef));

			getInput.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("usage"), usageCast));
			getInput.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("index"), indexArray));

			Comment(getInput, "Returns a vertex input used by this shader");

			classDom.Members.Add(getInput);
		}
        public bool ValidateCodeArrayIndexerExpression (CodeArrayIndexerExpression exp) {
            bool result = true;
            PushLocation (exp);

            if (exp.Indices != null && exp.Indices.Count > 0) {
                if (exp.Indices.Count > 1) {
                    PushError ("Can only have one index.");
                    result = false;
                } else {
                    if (!IsSimpleTarget (exp.Indices[0]))
                        result = false;
                }
            }

            if (!IsSimpleTarget (exp.TargetObject))
                result = false;

            PopLocation();
            return result;
        }
Beispiel #12
0
		protected abstract void GenerateArrayIndexerExpression (CodeArrayIndexerExpression e);
		public override void AddBind(IShaderDom shader, Action<CodeStatement, string> add)
		{
			bool requiresUnused = false;

			//bind the semantics bound attributes
			foreach (SemanticMapping mapping in semanticMapping)
			{
				//eg:
				//state.SetWorldMatrix(this.vreg.Matrix4Transpose(8), ref this.v_8);

				string method = string.Format("Set{0}{1}", mapping.Type.Mapping, mapping.Type.Type.Name);

				if (mapping.Type.IsArray)
					method += "Array";

				//for each register set, see if it uses this mapping

				int changeRefIndex = 0;
				foreach (KeyValuePair<AsmListing, CodeExpression> listing in listingRegisters)
				{
					Register sreg;
					RegisterSet registers = listing.Key.RegisterSet;
					CodeExpression registersRef = listing.Value;

					if (registers.TryGetRegister(mapping.Register.Name, out sreg))
					{
						//it does.. so the constants need setting..
						//changed |= state.SetWorldMatrix(ref this.vreg[8], ref this.vreg[9], ref this.vreg[9], ref unused, ref this.v_8);

						CodeExpression changeRef = Ref(mapping.ChangeRefs[changeRefIndex]);

						CodeExpression getRegisterX =	//this.vreg[8]
							new CodeArrayIndexerExpression(registersRef, new CodePrimitiveExpression(sreg.Index));

						//invoke
						CodeExpression invokeSet = null;

						if (mapping.Type.IsArray)
						{
							invokeSet = new CodeMethodInvokeExpression(shader.ShaderSystemRef, method, registersRef, new CodePrimitiveExpression(sreg.Index), new CodePrimitiveExpression(sreg.Size), changeRef);
						}
						else
						{
							if (mapping.Type.Type == typeof(Matrix))
							{
								int rank = (int)mapping.Register.Rank;
								if (rank != 4 && requiresUnused == false) // an 'unused' variable is required
								{
									//add a temporary. A matrix being set may not use all 4 rows. Need a temp write target
									add(new CodeVariableDeclarationStatement(typeof(Vector4), "unused", new CodeObjectCreateExpression(typeof(Vector4))), null);
									requiresUnused = true;
								}

								//setter takes in X,Y,Z,W registers
								CodeExpression unused = new CodeVariableReferenceExpression("unused");
								CodeExpression Y = rank >= 2 ? new CodeArrayIndexerExpression(registersRef, new CodePrimitiveExpression(sreg.Index + 1)) : unused;
								CodeExpression Z = rank >= 3 ? new CodeArrayIndexerExpression(registersRef, new CodePrimitiveExpression(sreg.Index + 2)) : unused;
								CodeExpression W = rank >= 4 ? new CodeArrayIndexerExpression(registersRef, new CodePrimitiveExpression(sreg.Index + 3)) : unused;

								invokeSet = new CodeMethodInvokeExpression(shader.ShaderSystemRef, method, Ref(getRegisterX), Ref(Y), Ref(Z), Ref(W), changeRef);
							}
							else
								invokeSet = new CodeMethodInvokeExpression(shader.ShaderSystemRef, method, Ref(getRegisterX), changeRef);
						}

						//update the change value appropriately
						CodeExpression changeValue = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), (registersRef as CodeFieldReferenceExpression).FieldName + "_change");

						//change |= ...;
						CodeStatement assign = new CodeAssignStatement(changeValue, 
							new CodeBinaryOperatorExpression(changeValue, CodeBinaryOperatorType.BitwiseOr,
								invokeSet));

						if (ExtractAssignmentForExtenionBlock(assign, shader, listing.Key))
							continue;

						add(assign, changeRefIndex != 0 ? null : string.Format("Set the value for attribute '{0}'", mapping.Register.Name));

						changeRefIndex++;
					}
				}
			}

			//bind the shader globals

			foreach (GlobalAttribute global in globals)
			{
				string registerTypeName = global.Type.Name;
				if (global.Type == typeof(Matrix))
				{
					registerTypeName += (int)global.Register.Rank;
				}
				
				int changeRefIndex = 0;
				foreach (KeyValuePair<AsmListing, CodeExpression> listing in listingRegisters)
				{
					Register sreg;
					RegisterSet registers = listing.Key.RegisterSet;
					CodeExpression registersRef = listing.Value;

					bool isMatrix = global.Type == typeof(Matrix);

					if (registers.TryGetRegister(global.Register.Name, out sreg))
					{
						//special case the booleans, as they have different logic to set globally.
						if (sreg.Category == RegisterCategory.Boolean)
						{
							if (global.Register.ArraySize != -1)
								throw new CompileException("'GLOBAL' Boolean Arrays are not supported");


							//this is a bit of a hack :-/
							//need to figure out if this is a vertex or pixel boolean constant.
							if (listing.Key == asm.VertexShader)
							{
								CodeExpression setValue = new CodeMethodInvokeExpression(shader.ShaderSystemRef, "SetGlobalBool", shader.VertexShaderBooleanRegistersRef, new CodePrimitiveExpression(sreg.Index), global.GlobalIdRef);

								//update the change flag
								CodeExpression invoke = new CodeBinaryOperatorExpression(
									shader.VertexShaderBooleanRegistersChangedRef, CodeBinaryOperatorType.BitwiseOr,
									setValue);

								add(shader.ETS(invoke),
									string.Format("Set the value for global 'bool {0}'", global.Register.Name));
							}
							if (listing.Key == asm.PixelShader)
							{
								CodeExpression setValue = new CodeMethodInvokeExpression(shader.ShaderSystemRef, "SetGlobalBool", shader.PixelShaderBooleanRegistersRef, new CodePrimitiveExpression(sreg.Index), global.GlobalIdRef);
								
								//update the change flag
								CodeExpression invoke = new CodeBinaryOperatorExpression(
									shader.PixelShaderBooleanRegistersChangedRef, CodeBinaryOperatorType.BitwiseOr,
									setValue);

								add(shader.ETS(invoke),
									string.Format("Set the value for global 'bool {0}'", global.Register.Name));
							}
						}
						else
						{
							//eg:
							//changed |= state.SetGlobalMatrix3(ref this.vreg[8], ref this.vreg[9], ref this.vreg[10], ShadowShaderBlend.g_id0, ref this.g_0);

							CodeExpression getRegisterX =	//this.vreg[8]
								new CodeArrayIndexerExpression(registersRef, new CodePrimitiveExpression(sreg.Index));

							string methodName = "SetGlobal" + global.Type.Name;
							int rank = (int)global.Register.Rank;

							if (isMatrix)
								methodName += rank;

							//eg, SetGlobalMatrix3

							CodeExpression changeRef = Ref(global.ChangeRefs[changeRefIndex]);
							CodeExpression invokeSet;

							//logic changes for arrays

							if (global.Register.ArraySize != -1)
							{
								//SetGlobalMatrix3 for Arrays takes in the array itself as the first arg.
								invokeSet =
									new CodeMethodInvokeExpression(shader.ShaderSystemRef, methodName, registersRef, new CodePrimitiveExpression(global.Register.Index), new CodePrimitiveExpression(global.Register.Size + global.Register.Index), global.GlobalIdRef, changeRef);
								//state.SetGlobal(this.ga0, ShadowShaderBlend.g_id0, ref this.g_0);
							}
							else
							{
								//SetGlobalMatrix3 for non-arays takes a variable number of arguements
								if (isMatrix)
								{
									List<CodeExpression> args = new List<CodeExpression>();
									//add X
									args.Add(Ref(getRegisterX));
									if (rank >= 2) args.Add(Ref(new CodeArrayIndexerExpression(registersRef, new CodePrimitiveExpression(sreg.Index + 1))));
									if (rank >= 3) args.Add(Ref(new CodeArrayIndexerExpression(registersRef, new CodePrimitiveExpression(sreg.Index + 2))));
									if (rank >= 4) args.Add(Ref(new CodeArrayIndexerExpression(registersRef, new CodePrimitiveExpression(sreg.Index + 3))));

									args.Add(global.GlobalIdRef);
									args.Add(changeRef);
									
									invokeSet =
										new CodeMethodInvokeExpression(shader.ShaderSystemRef, methodName, args.ToArray());
								}
								else
									invokeSet =
										new CodeMethodInvokeExpression(shader.ShaderSystemRef, methodName, Ref(getRegisterX), global.GlobalIdRef, changeRef);
							}

								
							//update the change value appropriately
							CodeExpression changeValue = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), (registersRef as CodeFieldReferenceExpression).FieldName + "_change");

							//change |= ...;
							CodeStatement assign = new CodeAssignStatement(changeValue, 
								new CodeBinaryOperatorExpression(changeValue, CodeBinaryOperatorType.BitwiseOr,
									invokeSet));

							if (ExtractAssignmentForExtenionBlock(assign, shader, listing.Key))
								continue;

							add(assign, changeRefIndex != 0 ? null : string.Format("Set the value for global '{0}'", global.Register.Name));

							changeRefIndex++;
						}
					}
				}
			}
		}
		protected override void GenerateArrayIndexerExpression(CodeArrayIndexerExpression e)
		{
			Output.Write("[CodeArrayIndexerExpression: {0}]", e.ToString());
		}
		private void CreateConstantSetters(IShaderDom shader, Action<CodeTypeMember, string> add, string name, CodeExpression assignmentField, CodeExpression assignmentArrayField)
		{
			/*
			 * Something like:

			public void SetInvTargetSize(ref Microsoft.Xna.Framework.Vector2 value)
			{
				this.vreg.SetVector2(130, ref value);
			}

			public Microsoft.Xna.Framework.Vector2 InvTargetSize
			{
				set
				{
					this.SetInvTargetSize(ref value);
				}
			}*/

			Register reg;
			Type dataType;
			bool hasSetMethod;
			int stride;

			if (!ExtractRegType(name, out reg, out dataType, out hasSetMethod, out stride))
				return;

			Type arrayOrSingleType = dataType;

			//right...

			//create the method of the given type.


			//public void SetInvTargetSize(ref Microsoft.Xna.Framework.Vector2 value)
			CodeStatementCollection methodStatements = new CodeStatementCollection();

			CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(dataType, "value");
			List<CodeParameterDeclarationExpression> additionalParams = new List<CodeParameterDeclarationExpression>();

			if (reg.ArraySize == -1)
				param.Direction = FieldDirection.Ref;
			else
			{
				arrayOrSingleType = dataType.MakeArrayType();
				param.Type = new CodeTypeReference(arrayOrSingleType);

				//add array params, readIndex, writeIndex, count
				additionalParams.Add(new CodeParameterDeclarationExpression(typeof(uint), "readIndex"));
				additionalParams.Add(new CodeParameterDeclarationExpression(typeof(uint), "writeIndex"));
				additionalParams.Add(new CodeParameterDeclarationExpression(typeof(uint), "count"));
			}

			CodeExpression valueRef = new CodeArgumentReferenceExpression(param.Name);

			//when there isn't a set method, there is just a set property
			if (!hasSetMethod)
				valueRef = new CodePropertySetValueReferenceExpression();

			//create the guts
			//depends on what constants use it...

			//eg:
			//this.vreg.SetVector2(130, ref value);

			Register sreg;

			if (dataType == typeof(bool))
			{
				//special case for booleans, assign the array directly.
				//looks like:
				// 
				// if (preg_bool[index] != value)
				// {
				//  preg_bool[index] = value;
				//  preg_bool_changed = true;
				// }

				foreach (KeyValuePair<AsmListing, CodeExpression> listing in listingRegisters)
				{
					RegisterSet registers = listing.Key.RegisterSet;
					CodeExpression registersRef = listing.Value;

					if (registers.TryGetRegister(name, out sreg))
					{
						if (listing.Key == asm.PixelShader)
						{
							CodeExpression arrayIndex = new CodeArrayIndexerExpression(shader.PixelShaderBooleanRegistersRef, new CodePrimitiveExpression(sreg.Index));

							CodeStatement assign = new CodeAssignStatement(arrayIndex, new CodePropertySetValueReferenceExpression());
							CodeStatement change = new CodeAssignStatement(shader.PixelShaderBooleanRegistersChangedRef, new CodePrimitiveExpression(true));

							CodeStatement condition = new CodeConditionStatement(
								new CodeBinaryOperatorExpression(arrayIndex, CodeBinaryOperatorType.IdentityInequality, new CodePropertySetValueReferenceExpression()),
								new CodeStatement[]{assign, change});

							methodStatements.Add(condition);
						}
						if (listing.Key == asm.VertexShader)
						{
							CodeExpression arrayIndex = new CodeArrayIndexerExpression(shader.VertexShaderBooleanRegistersRef, new CodePrimitiveExpression(sreg.Index));

							CodeStatement assign = new CodeAssignStatement(arrayIndex, new CodePropertySetValueReferenceExpression());
							CodeStatement change = new CodeAssignStatement(shader.VertexShaderBooleanRegistersChangedRef, new CodePrimitiveExpression(true));

							CodeStatement condition = new CodeConditionStatement(
								new CodeBinaryOperatorExpression(arrayIndex, CodeBinaryOperatorType.IdentityInequality, new CodePropertySetValueReferenceExpression()),
								new CodeStatement[] { assign, change });

							methodStatements.Add(condition);
						}
					}
				}
			}
			else
			{
				//some array set methods require temporary values, but should only be created once.
				bool tempValuesCreated = false;

				foreach (KeyValuePair<AsmListing, CodeExpression> listing in listingRegisters)
				{
					RegisterSet registers = listing.Key.RegisterSet;
					CodeExpression registersRef = listing.Value;

					if (registers.TryGetRegister(name, out sreg))
					{
						//Assign the register array data
						AssignRegister(dataType, sreg, reg, listing.Value, valueRef, methodStatements, ref tempValuesCreated);

						//set changed
						CodeExpression changeValue = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), (registersRef as CodeFieldReferenceExpression).FieldName + "_change");

						methodStatements.Add(new CodeAssignStatement(changeValue, new CodePrimitiveExpression(true)));
					}
				}
			}

			string upperName = Common.ToUpper(name);

			//there is always a setable property
			CodeMemberProperty property = new CodeMemberProperty();
			property.Name = upperName;
			property.Type = param.Type;
			property.Attributes = MemberAttributes.Final | MemberAttributes.Public;
			property.HasSet = true;
			property.HasGet = false;

			//there isn't always a set method
			CodeMemberMethod method = null;

			CodeStatement assignAttribute = null;

			if (hasSetMethod || reg.ArraySize != -1)
			{
				//create the method to set the value
				string methodName = "Set" + upperName;

				method = new CodeMemberMethod();
				method.Name = methodName;
				method.Attributes = MemberAttributes.Final | MemberAttributes.Public;

				method.Parameters.Add(param);
				method.Parameters.AddRange(additionalParams.ToArray());
				method.Statements.AddRange(methodStatements);


				//create a property that calls the Set method

				//is not an array
				CodeMethodInvokeExpression invokeSetter =
					new CodeMethodInvokeExpression(
						shader.Instance, method.Name,
						new CodeDirectionExpression(reg.ArraySize == -1 ? FieldDirection.Ref : FieldDirection.In, new CodePropertySetValueReferenceExpression()));

				if (reg.ArraySize != -1)
				{
					//add method ops (readIndex, writeIndex, count)
					invokeSetter.Parameters.Add(new CodePrimitiveExpression(0));
					invokeSetter.Parameters.Add(new CodePrimitiveExpression(0));
					invokeSetter.Parameters.Add(new CodeCastExpression(typeof(uint), new CodePropertyReferenceExpression(valueRef, "Length")));
				}

				property.SetStatements.Add(invokeSetter);



				//call the method as well for attribute assign
				CodeMethodInvokeExpression assignSetter = 
					new CodeMethodInvokeExpression(
						shader.Instance, method.Name,
						new CodeDirectionExpression(param.Direction, shader.AttributeAssignValue));

				if (reg.ArraySize != -1)
				{
					//add method ops (readIndex, writeIndex, count)
					assignSetter.Parameters.Add(new CodePrimitiveExpression(0));
					assignSetter.Parameters.Add(new CodePrimitiveExpression(0));
					assignSetter.Parameters.Add(new CodeCastExpression(typeof(uint), new CodePropertyReferenceExpression(valueRef, "Length")));
				}

				assignAttribute = shader.ETS(assignSetter);
			}
			else
			{
				//create a property to directly set the value

				property.SetStatements.AddRange(methodStatements);

				//attribute assign sets the property
				assignAttribute = new CodeAssignStatement(
					new CodePropertyReferenceExpression(shader.Instance, property.Name),
						shader.AttributeAssignValue);
			}
			

			if (reg.ArraySize > 0)
			{
				if (method != null)
					add(method, string.Format("Set the shader array value '{0} {1}[{2}]'", reg.Type, reg.Name, reg.ArraySize));
				add(property, string.Format("Set and copy the array data for the shader value '{0} {1}[{2}]'", reg.Type, reg.Name, reg.ArraySize));
			}
			else
			{
				if (method != null)
					add(method, string.Format("Set the shader value '{0} {1}'", reg.Type, reg.Name));
				add(property, string.Format("Assign the shader value '{0} {1}'", reg.Type, reg.Name));
			}

			//create the attribute assignment value statement.

			List<CodeStatement> assignList;
			if (!attributeAssignment.TryGetValue(arrayOrSingleType, out assignList))
			{
				assignList = new List<CodeStatement>();
				attributeAssignment.Add(arrayOrSingleType, assignList);
			}

			//create the statement...
			
			CodeExpression assignIdsMatch =
				new CodeBinaryOperatorExpression(shader.AttributeAssignId,  CodeBinaryOperatorType.IdentityEquality, assignmentField);

			CodeConditionStatement performAssign =
				new CodeConditionStatement(assignIdsMatch,
					assignAttribute, //call the assignment code
					new CodeMethodReturnStatement(new CodePrimitiveExpression(true))); //return true, set correctly.

			assignList.Add(performAssign);
		}
Beispiel #16
0
 private CodeBinaryOperatorExpression VarAssign(CodeArrayIndexerExpression name, CodeExpression value)
 {
     return new CodeBinaryOperatorExpression(name, CodeBinaryOperatorType.Assign, value);
 }
Beispiel #17
0
        protected override void GenerateArrayIndexerExpression(CodeArrayIndexerExpression e) {
            GenerateExpression(e.TargetObject);
            Output.Write("[");
            bool first = true;
            foreach(CodeExpression exp in e.Indices) {            
                if (first) {
                    first = false;
                }
                else {
                    Output.Write(", ");
                }
                GenerateExpression(exp);
            }
            Output.Write("]");

        }
Beispiel #18
0
        public override CodeExpression ToCodeExpression()
        {
            CodeArrayIndexerExpression access = new CodeArrayIndexerExpression();
            access.TargetObject = array.ToCodeExpression();

            for (Node n = args; n != null; n = n.nd_next)
                access.Indices.Add(n.ToCodeExpression());

            return access;
        }
Beispiel #19
0
 private void ValidateArrayIndexerExpression(CodeArrayIndexerExpression e) {
     ValidateExpression(e.TargetObject);
     foreach(CodeExpression exp in e.Indices) {            
         ValidateExpression(exp);
     }
 }
Beispiel #20
0
        private static string BuildCodeExtractingModelType(CodeDomProvider provider)
        {
            var getType = new CodeMethodInvokeExpression
                (
                    new CodeThisReferenceExpression(),
                    "GetType"
                );

            var baseType = new CodeFieldReferenceExpression
                (
                    getType,
                    "BaseType"
                );

            var getFirstGenericArgument = new CodeArrayIndexerExpression
                (
                    new CodeMethodInvokeExpression
                        (
                        baseType,
                        "GetGenericArguments"
                        ),
                    new CodePrimitiveExpression(0)
                );

            var fullName = new CodeFieldReferenceExpression
                (
                    getFirstGenericArgument,
                    "FullName"
                );

            string modelTypeCode;
            using (var writer = new StringWriter())
            {
                provider.GenerateCodeFromExpression(fullName, writer, new CodeGeneratorOptions());
                modelTypeCode = writer.ToString();
            }
            return modelTypeCode;
        }
Beispiel #21
0
        private CodeStatement BuildReadStringStatement(MemberType memberType, string classRefName, CodeMemberField memberField)
        {
            string tempListName = memberField.Name + "_List";

            // If called by the Native contract serializer method classRefName
            // will be null indicating this is a local field type
            CodeTypeReferenceExpression classRefType = null;
            if (classRefName != null || classRefName == "")
                classRefType = new CodeTypeReferenceExpression(classRefName);

            // Build left code assignment value
            CodeFieldReferenceExpression leftStatement = new CodeFieldReferenceExpression(
                classRefType,
                memberField.Name + (memberField.Type.ArrayElementType == null ? "" : "[i]"));

            // Build right code assignment value
            CodeExpression readExpression;
            if (memberField.Type.ArrayElementType != null)
            {
                readExpression = new CodeArrayIndexerExpression(
                    new CodeVariableReferenceExpression(tempListName),
                    new CodeVariableReferenceExpression("i"));
            }
            else if (memberType == MemberType.Field)
                readExpression = new CodeMethodInvokeExpression(
                    new CodeTypeReferenceExpression("reader"),
                    "ReadString");
            else
                readExpression = new CodeFieldReferenceExpression(
                    new CodeTypeReferenceExpression("reader"),
                    "Value");

            CodeStatement assignStatement;

            // if the field is a string type just read it
            if (memberField.Type.BaseType == "System.String")
            {
                assignStatement = new CodeAssignStatement(leftStatement, readExpression);
            }
            // Else build convert statement
            else
            {
                CodeExpression convertExpression = new CodeMethodInvokeExpression(
                    new CodeTypeReferenceExpression("XmlConvert"),
                    CodeGenUtils.GetConvertMethod(memberField.Type.BaseType),
                    new CodeExpression[] { readExpression });

                assignStatement = new CodeAssignStatement(leftStatement, convertExpression);
            }
            return assignStatement;
        }
Beispiel #22
0
		protected override void GenerateArrayIndexerExpression (CodeArrayIndexerExpression e)
		{
		}
Beispiel #23
0
        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 });                    
                }
            }
        }
		protected override void CreateConstructor (CodeStatementCollection localVars,
							   CodeStatementCollection trueStmt)
		{
#if NET_2_0
			if (!String.IsNullOrEmpty (pageParser.MasterPageFile))
				// This is here just to trigger master page build, so that its type
				// is available when compiling the page itself.
				BuildManager.GetCompiledType (pageParser.MasterPageFile);
#endif
			if (pageParser.ClientTarget != null) {
				CodeExpression prop;
				prop = new CodePropertyReferenceExpression (thisRef, "ClientTarget");
				CodeExpression ct = new CodePrimitiveExpression (pageParser.ClientTarget);
				if (localVars == null)
					localVars = new CodeStatementCollection ();
				localVars.Add (new CodeAssignStatement (prop, ct));
			}

			ArrayList deps = pageParser.Dependencies;
			int depsCount = deps != null ? deps.Count : 0;
			
			if (depsCount > 0) {
				if (localVars == null)
					localVars = new CodeStatementCollection ();
				if (trueStmt == null)
					trueStmt = new CodeStatementCollection ();

				CodeAssignStatement assign;
#if NET_2_0
				localVars.Add (
					new CodeVariableDeclarationStatement (
						typeof (string[]),
						"dependencies")
				);

				CodeVariableReferenceExpression dependencies = new CodeVariableReferenceExpression ("dependencies");
				trueStmt.Add (
					new CodeAssignStatement (dependencies, new CodeArrayCreateExpression (typeof (string), depsCount))
				);
				
				CodeArrayIndexerExpression arrayIndex;
				object o;
				
				for (int i = 0; i < depsCount; i++) {
					o = deps [i];
					arrayIndex = new CodeArrayIndexerExpression (dependencies, new CodeExpression[] {new CodePrimitiveExpression (i)});
					assign = new CodeAssignStatement (arrayIndex, new CodePrimitiveExpression (o));
					trueStmt.Add (assign);
				}
				
				CodeMethodInvokeExpression getDepsCall = new CodeMethodInvokeExpression (
					thisRef,
					"GetWrappedFileDependencies",
					new CodeExpression[] {dependencies}
				);
				assign = new CodeAssignStatement (GetMainClassFieldReferenceExpression ("__fileDependencies"), getDepsCall);
#else
				localVars.Add (new CodeVariableDeclarationStatement (
						typeof (ArrayList),
						"dependencies")
				);

				CodeVariableReferenceExpression dependencies = new CodeVariableReferenceExpression ("dependencies");
				trueStmt.Add (
					new CodeAssignStatement (dependencies, new CodeObjectCreateExpression (typeof (ArrayList), new CodeExpression[] {new CodePrimitiveExpression (depsCount)}))
				);

				CodeMethodInvokeExpression invoke;
				for (int i = 0; i < depsCount; i++) {
					invoke = new CodeMethodInvokeExpression (dependencies, "Add", new CodeExpression[] {new CodePrimitiveExpression (deps [i])});
					trueStmt.Add (invoke);
				}
				assign = new CodeAssignStatement (GetMainClassFieldReferenceExpression ("__fileDependencies"), dependencies);
#endif

				trueStmt.Add (assign);
			}

			base.CreateConstructor (localVars, trueStmt);
		}
Beispiel #25
0
        public CodeExpression ParseBaseExpression()
        {
            if (TokenType == CDILToken.Integer)
            {
                CodePrimitiveExpression expr = new CodePrimitiveExpression(TokenValue);
                GetNextToken();
                return expr;
            }
            if (TokenType == CDILToken.String)
            {
                CodePrimitiveExpression expr = new CodePrimitiveExpression(TokenValue);
                GetNextToken();
                return expr;
            }
            if (IsKeyword("base"))
            {
                GetNextToken();
                return new CodeBaseReferenceExpression();
            }

            if (IsKeyword("null"))
            {
                GetNextToken();
                return new CodePrimitiveExpression(null);
            }

            if (IsKeyword("false"))
            {
                GetNextToken();
                return new CodePrimitiveExpression(false);
            }

            if (IsKeyword("true"))
            {
                GetNextToken();
                return new CodePrimitiveExpression(true);
            }

            if (IsKeyword("this"))
            {
                GetNextToken();
                return new CodeThisReferenceExpression();
            }

            if (IsKeyword("setvalue"))
            {
                GetNextToken();
                return new CodePropertySetValueReferenceExpression();
            }

            if (IsKeyword("arg"))
            {
                GetNextToken();
                Expect(CDILToken.LeftParen);
                string name = EatKeyword();
                Expect(CDILToken.RightParen);
                return new CodeArgumentReferenceExpression(name);
            }

            if (IsKeyword("delegatecall"))
            {
                CodeDelegateInvokeExpression retval = new CodeDelegateInvokeExpression();
                GetNextToken();
                Expect(CDILToken.LeftParen);
                retval.TargetObject = ParseExpression();
                Expect(CDILToken.RightParen);
                Expect(CDILToken.LeftParen);
                while (TokenType != CDILToken.RightParen && TokenType != CDILToken.EOF)
                {
                    CodeExpression expr = ParseExpression();
                    retval.Parameters.Add(expr);
                    if (TokenType == CDILToken.Comma)
                    {
                        GetNextToken();
                    }
                }
                Expect(CDILToken.RightParen);
                return retval;
            }

            if (IsKeyword("typeref"))
            {
                GetNextToken();
                Expect(CDILToken.LeftParen);
                CodeTypeReference typeRef = ParseType();
                Expect(CDILToken.RightParen);
                return new CodeTypeReferenceExpression(typeRef);
            }

            if (IsKeyword("typeof"))
            {
                GetNextToken();
                Expect(CDILToken.LeftParen);
                CodeTypeReference typeRef = ParseType();
                Expect(CDILToken.RightParen);
                return new CodeTypeOfExpression(typeRef);
            }

            if (IsKeyword("add"))
            {
                CodeBinaryOperatorExpression cboe = new CodeBinaryOperatorExpression();
                cboe.Operator = CodeBinaryOperatorType.Add;
                GetNextToken();
                Expect(CDILToken.LeftParen);
                cboe.Left = ParseExpression();
                Expect(CDILToken.Comma);
                cboe.Right = ParseExpression();
                Expect(CDILToken.RightParen);
                return cboe;
            }

            if (IsKeyword("equal"))
            {
                CodeBinaryOperatorExpression cboe = new CodeBinaryOperatorExpression();
                cboe.Operator = CodeBinaryOperatorType.ValueEquality;
                GetNextToken();
                Expect(CDILToken.LeftParen);
                cboe.Left = ParseExpression();
                Expect(CDILToken.Comma);
                cboe.Right = ParseExpression();
                Expect(CDILToken.RightParen);
                return cboe;
            }

            if (IsKeyword("refequal"))
            {
                CodeBinaryOperatorExpression cboe = new CodeBinaryOperatorExpression();
                cboe.Operator = CodeBinaryOperatorType.IdentityEquality;
                GetNextToken();
                Expect(CDILToken.LeftParen);
                cboe.Left = ParseExpression();
                Expect(CDILToken.Comma);
                cboe.Right = ParseExpression();
                Expect(CDILToken.RightParen);
                return cboe;
            }

            if (IsKeyword("refnotequal"))
            {
                CodeBinaryOperatorExpression cboe = new CodeBinaryOperatorExpression();
                cboe.Operator = CodeBinaryOperatorType.IdentityInequality;
                GetNextToken();
                Expect(CDILToken.LeftParen);
                cboe.Left = ParseExpression();
                Expect(CDILToken.Comma);
                cboe.Right = ParseExpression();
                Expect(CDILToken.RightParen);
                return cboe;
            }

            if (IsKeyword("arrayitem"))
            {
                GetNextToken();
                Expect(CDILToken.LeftParen);
                CodeArrayIndexerExpression caie = new CodeArrayIndexerExpression();
                caie.TargetObject = ParseExpression();
                while (TokenType == CDILToken.Comma)
                {
                    Expect(CDILToken.Comma);
                    caie.Indices.Add(ParseExpression());
                }
                Expect(CDILToken.RightParen);
                return caie;
            }

            if (IsKeyword("index"))
            {
                GetNextToken();
                Expect(CDILToken.LeftParen);
                CodeIndexerExpression cie = new CodeIndexerExpression();
                cie.TargetObject = ParseExpression();
                while (TokenType == CDILToken.Comma)
                {
                    Expect(CDILToken.Comma);
                    cie.Indices.Add(ParseExpression());
                }
                Expect(CDILToken.RightParen);
                return cie;
            }

            if (IsKeyword("var"))
            {
                GetNextToken();
                Expect(CDILToken.LeftParen);
                string name = EatKeyword();
                Expect(CDILToken.RightParen);
                return new CodeVariableReferenceExpression(name);
            }

            if (IsKeyword("defaultscope"))
            {
                GetNextToken();
                return null;
            }

            if (IsKeyword("ref"))
            {
                GetNextToken();
                Expect(CDILToken.LeftParen);
                CodeExpression expr = ParseExpression();
                Expect(CDILToken.RightParen);
                return new CodeDirectionExpression(FieldDirection.Ref, expr);
            }

            if (IsKeyword("out"))
            {
                GetNextToken();
                Expect(CDILToken.LeftParen);
                CodeExpression expr = ParseExpression();
                Expect(CDILToken.RightParen);
                return new CodeDirectionExpression(FieldDirection.Out, expr);
            }

            if (IsKeyword("cast"))
            {
                GetNextToken();
                Expect(CDILToken.LeftParen);
                CodeTypeReference type = ParseType();
                Expect(CDILToken.Comma);
                CodeExpression expr = ParseExpression();
                Expect(CDILToken.RightParen);
                return new CodeCastExpression(type, expr);
            }
            if (IsKeyword("new"))
            {
                GetNextToken();
                CodeTypeReference type = ParseType();
                CodeObjectCreateExpression retval = new CodeObjectCreateExpression(type);
                Expect(CDILToken.LeftParen);
                while (TokenType != CDILToken.RightParen && TokenType != CDILToken.EOF)
                {
                    CodeExpression expr = ParseExpression();
                    retval.Parameters.Add(expr);
                    if (TokenType == CDILToken.Comma)
                    {
                        GetNextToken();
                    }
                }
                Expect(CDILToken.RightParen);
                return retval;
            }

            if (IsKeyword("newarray"))
            {
                GetNextToken();
                Expect(CDILToken.LeftParen);
                CodeArrayCreateExpression retval = new CodeArrayCreateExpression();
                retval.CreateType = ParseType();
                Expect(CDILToken.Comma);
                retval.SizeExpression = ParseExpression();
                Expect(CDILToken.RightParen);
                return retval;
            }

            throw BuildException("Unexpected token '" + TokenType + "'");
        }
Beispiel #26
0
 protected override void GenerateArrayIndexerExpression(CodeArrayIndexerExpression e)
 {
     base.GenerateExpression(e.TargetObject);
     base.Output.Write("(");
     bool flag = true;
     foreach (CodeExpression expression in e.Indices)
     {
         if (flag)
         {
             flag = false;
         }
         else
         {
             base.Output.Write(", ");
         }
         base.GenerateExpression(expression);
     }
     base.Output.Write(")");
 }
 private void GenerateArrayIndexerExpression(CodeArrayIndexerExpression e)
 {
     this.GenerateExpression(e.TargetObject);
     this.Output.Write("[");
     bool flag1 = true;
     foreach (CodeExpression expression1 in e.Indices)
     {
         if (flag1)
         {
             flag1 = false;
         }
         else
         {
             this.Output.Write(", ");
         }
         this.GenerateExpression(expression1);
     }
     this.Output.Write("]");
 }
Beispiel #28
0
 protected override void GenerateArrayIndexerExpression(System.CodeDom.CodeArrayIndexerExpression e)
 {
     throw new Exception("The method or operation is not implemented.");
 }
Beispiel #29
0
			public void Visit (CodeArrayIndexerExpression o)
			{
				g.GenerateArrayIndexerExpression (o);
			}
Beispiel #30
0
            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;
        }
Beispiel #31
0
 /// <summary>
 /// Generates code for the specified array indexer expression.
 /// </summary>
 /// <remarks><c>TARGET[INDEX1][INDEX2]...</c></remarks>
 protected override void GenerateArrayIndexerExpression(CodeArrayIndexerExpression e)
 {
     OutputArrayIndexerExpression(e.TargetObject, e.Indices);
 }