internal ParameterDefinition Copy() { var p = new ParameterDefinition(Name, Type, IsOptional); p.ManagedName = ManagedName; p.MarshalDirection = MarshalDirection; return p; }
public void Read(ClrModuleReader reader) { this.ParameterDefinition = new ParameterDefinition(); this.ParameterDefinition.Attributes = (ParamAttributes)reader.Binary.ReadUInt16(); this.Sequence = reader.Binary.ReadUInt16(); this.ParameterDefinition.Name = reader.ReadString(); }
internal ParameterDefinition Copy() { var p = new ParameterDefinition(Name, Type.Copy(), IsOptional); p.IsOptional = IsOptional; p.MarshalDirection = MarshalDirection; return p; }
internal static ParameterDefinitionModel From(ParameterDefinition parameterDefinition) { return new ParameterDefinitionModel() { ParameterDefinitionId = parameterDefinition.Id, Name = parameterDefinition.Name, ParameterType = parameterDefinition.DefinitionType }; }
public MethodDefinition(string name, ClassDefinition parent, int numArgs) { Name = name; Parent = parent; Parameters = new ParameterDefinition[numArgs]; if (parent != null) { parent.Methods.Add(this); } }
public static IParameterDefinition AddParameter(this MethodDefinition method, ushort parameterIndex, string parameterName, ITypeReference parameterType, IMetadataHost host, bool isOut, bool isRef) { var fakeMethodParameter = new ParameterDefinition(); fakeMethodParameter.ContainingSignature = method; fakeMethodParameter.Index = parameterIndex; fakeMethodParameter.IsByReference = false; fakeMethodParameter.Type = parameterType; fakeMethodParameter.Name = host.NameTable.GetNameFor(parameterName); fakeMethodParameter.IsOut = isOut; fakeMethodParameter.IsByReference = isRef; method.Parameters.Add(fakeMethodParameter); return fakeMethodParameter; }
public void AddParameterIndex() { var object_ref = new TypeReference ("System", "Object", null, null, false); var method = new MethodDefinition ("foo", MethodAttributes.Static, object_ref); var x = new ParameterDefinition ("x", ParameterAttributes.None, object_ref); var y = new ParameterDefinition ("y", ParameterAttributes.None, object_ref); method.Parameters.Add (x); method.Parameters.Add (y); Assert.AreEqual (0, x.Index); Assert.AreEqual (1, y.Index); Assert.AreEqual (method, x.Method); Assert.AreEqual (method, y.Method); }
private static ParameterDefinition[] DateFunctionParamInfo() { var optionalParam = new ParameterDefinition() { HasDefaultValue = true, IsByValue = true }; return new ParameterDefinition[6] { new ParameterDefinition(){IsByValue = true}, optionalParam, optionalParam, optionalParam, optionalParam, optionalParam }; }
protected virtual bool WriteDataContextCtor(CodeWriter writer, Database schema, Type contextBaseType, ParameterDefinition[] parameters, string[] baseCallParameterNames, Type[] baseCallParameterTypes, GenerationContext context) { // if we have a contextBaseType, then check that we can do it if (contextBaseType != null) { var ctor = contextBaseType.GetConstructor(baseCallParameterTypes); if (ctor == null) return false; } using (writer.WriteCtor(SpecificationDefinition.Public, schema.Class, parameters, baseCallParameterNames)) { writer.WriteLine(writer.GetStatement(writer.GetMethodCallExpression("OnCreated"))); } writer.WriteLine(); return true; }
public AnonymousMethodBodyBuilder(IMetadataHost host, IUnitReflector reflector, ITypeReference delegateType, Type returnType, ParameterInfo[] parameters) { this.host = host; this.reflector = reflector; this.delegateType = delegateType; this.returnTypeReference = reflector.Get(returnType); foreach (var parameter in parameters) { var parameterDefinition = new ParameterDefinition(); parameterDefinition.Index = (ushort)parameter.Position; parameterDefinition.Type = reflector.Get(parameter.ParameterType); parameterDefinition.Name = host.NameTable.GetNameFor("altered" + parameter.Name); parameterDefinition.ContainingSignature = method; method.Parameters.Add(parameterDefinition); } }
public AnonymousMethodBodyBuilder(IMetadataHost host, IUnitReflector reflector, ITypeReference delegateType, ITypeReference returnType, KeyValuePair<string, ITypeReference>[] parameterTypes) { this.host = host; this.reflector = reflector; this.delegateType = delegateType; this.returnTypeReference = returnType; for (var pIndex = 0; pIndex < parameterTypes.Length; pIndex++) { var parameterType = parameterTypes[pIndex]; var parameterDefinition = new ParameterDefinition(); parameterDefinition.Index = (ushort) pIndex; parameterDefinition.Type = parameterType.Value; parameterDefinition.Name = host.NameTable.GetNameFor("altered" + parameterType.Key); parameterDefinition.ContainingSignature = method; method.Parameters.Add(parameterDefinition); } }
/// <summary> /// Initializes a new instance of the <see cref="ConstructorBasedImportDefinition"/> class. /// </summary> /// <param name="contractName">The contract name that is used to identify the current import.</param> /// <param name="requiredTypeIdentity">The type identity of the export type expected.</param> /// <param name="cardinality"> /// One of the enumeration values that indicates the cardinality of the export object required by the import definition. /// </param> /// <param name="creationPolicy"> /// A value that indicates that the importer requires a specific creation policy for the exports used to satisfy this import. /// </param> /// <param name="declaringType">The type that declares the constructor on which the import is placed.</param> /// <param name="constructor">The constructor that declares the import.</param> /// <param name="parameter">The parameter on which the import is defined.</param> private ConstructorBasedImportDefinition( string contractName, TypeIdentity requiredTypeIdentity, ImportCardinality cardinality, CreationPolicy creationPolicy, TypeIdentity declaringType, ConstructorDefinition constructor, ParameterDefinition parameter) : base(contractName, requiredTypeIdentity, cardinality, false, true, creationPolicy, declaringType) { { Lokad.Enforce.Argument(() => parameter); } m_Constructor = constructor; m_Parameter = parameter; }
private void CreateTextWidgetDefinition() { var widgetDefinition = WidgetDefinitionRepository.FindByName("Text"); ParameterDefinition textParameterDefinition = new ParameterDefinition("Text"); ParameterDefinition fontSizeParameterDefinition = new ParameterDefinition("FontSize"); ParameterDefinition textColourParameterDefinition = new ParameterDefinition("TextColour"); if (widgetDefinition == null) { widgetDefinition = new WidgetDefinition("Text"); widgetDefinition.AddParameterDefinition(textParameterDefinition); widgetDefinition.AddParameterDefinition(fontSizeParameterDefinition); widgetDefinition.AddParameterDefinition(textColourParameterDefinition); WidgetDefinitionRepository.Add(widgetDefinition); } else { if (!widgetDefinition.ParameterDefinitions.Any(x => x.Name == "Text")) { widgetDefinition.AddParameterDefinition(textParameterDefinition); WidgetDefinitionRepository.Update(widgetDefinition); } if (!widgetDefinition.ParameterDefinitions.Any(x => x.Name == "FontSize")) { widgetDefinition.AddParameterDefinition(fontSizeParameterDefinition); WidgetDefinitionRepository.Update(widgetDefinition); } if (!widgetDefinition.ParameterDefinitions.Any(x => x.Name == "TextColour")) { widgetDefinition.AddParameterDefinition(textColourParameterDefinition); WidgetDefinitionRepository.Update(widgetDefinition); } } }
private void EmitPrivateFieldSetMethodCall(ModuleDefinition destModule, ILProcessor ilProcessor, FieldDefinition structField, FieldWrapper fieldWrapper, ParameterDefinition valueParameter, ParameterDefinition indexParameter) { string str = this.MakeName(structField, fieldWrapper); StructType type = base.MetadataContainer.AddStruct(structField.FieldType); MethodReference method = base.OperationContext.Import(destModule, type.PrivateSetters[str]); ilProcessor.EmitLdarg(valueParameter); if (indexParameter != null) { ilProcessor.EmitLdarg(indexParameter); } ilProcessor.Emit(OpCodes.Call, method); if (indexParameter != null) { ilProcessor.Emit(OpCodes.Ret); } }
private void EmitSimpleFieldSetCode(ModuleDefinition destModule, ILProcessor ilProcessor, FieldDefinition fieldWrapper, ParameterDefinition valueParameter) { ilProcessor.EmitLdarg(valueParameter); ilProcessor.Emit(OpCodes.Stfld, base.OperationContext.Import(destModule, fieldWrapper)); }
/// <summary> /// Returns a method whose body is empty, but which can be replaced with the real body when it is /// available. /// </summary> /// <remarks> /// Public because it needs to get called when an anonymous delegate is encountered /// while translating a method body. Just mapping the anonymous delegate doesn't /// provide the information needed. The parameters of a method reference are not /// IParameterDefinitions. /// </remarks> public MethodDefinition TranslateMetadata(R.IMethodSymbol methodSymbol) { Contract.Requires(methodSymbol != null); Contract.Ensures(Contract.Result<MethodDefinition>() != null); var containingType = (ITypeDefinition)this.typeSymbolCache[methodSymbol.ContainingType]; var isConstructor = methodSymbol.MethodKind == R.CommonMethodKind.Constructor; List<IParameterDefinition> parameters = new List<IParameterDefinition>(); var m = new MethodDefinition() { CallingConvention = methodSymbol.IsStatic ? CallingConvention.Default : CallingConvention.HasThis, ContainingTypeDefinition = containingType, InternFactory = this.host.InternFactory, IsHiddenBySignature = true, // REVIEW IsNewSlot = containingType.IsInterface, // REVIEW IsRuntimeSpecial = isConstructor, IsSpecialName = isConstructor, IsStatic = methodSymbol.IsStatic, IsVirtual = containingType.IsInterface, // REVIEW: Why doesn't using methodSymbol.Virtual work for interface methods? Locations = Helper.WrapLocations(methodSymbol.Locations), Name = this.nameTable.GetNameFor(methodSymbol.Name), Parameters = parameters, Type = this.Map(methodSymbol.ReturnType), Visibility = this.Map(methodSymbol.DeclaredAccessibility), }; // IMPORTANT: Have to add it to the cache before doing anything else because it may // get looked up if it is generic and a parameter's type involves the generic // method parameter. this.methodSymbolCache.Add(methodSymbol, m); #region Define the generic parameters if (methodSymbol.IsGenericMethod) { var genericParameters = new List<IGenericMethodParameter>(); foreach (var gp in methodSymbol.TypeParameters) { var gp2 = this.CreateTypeDefinition(gp); genericParameters.Add((IGenericMethodParameter) gp2); } m.GenericParameters = genericParameters; } #endregion #region Define the parameters ushort i = 0; foreach (var p in methodSymbol.Parameters) { var p_prime = new ParameterDefinition() { ContainingSignature = m, IsByReference = p.RefKind == RefKind.Ref, IsIn = p.RefKind == RefKind.None, IsOut = p.RefKind == RefKind.Out, Name = nameTable.GetNameFor(p.Name), Type = this.Map(p.Type), Index = i++, }; parameters.Add(p_prime); } #endregion Define the parameters #region Define default ctor, if needed if (/*methodSymbol.IsSynthesized &&*/ isConstructor) { // BUGBUG!! m.IsHiddenBySignature = true; m.IsRuntimeSpecial = true; m.IsSpecialName = true; var statements = new List<IStatement>(); var body = new SourceMethodBody(this.host, null, null) { LocalsAreZeroed = true, Block = new BlockStatement() { Statements = statements }, }; var thisRef = new ThisReference() { Type = containingType, }; // base(); foreach (var baseClass in containingType.BaseClasses) { var baseCtor = new Microsoft.Cci.MutableCodeModel.MethodReference() { CallingConvention = CallingConvention.HasThis, ContainingType = baseClass, GenericParameterCount = 0, InternFactory = this.host.InternFactory, Name = nameTable.Ctor, Type = this.host.PlatformType.SystemVoid, }; statements.Add( new ExpressionStatement() { Expression = new MethodCall() { MethodToCall = baseCtor, IsStaticCall = false, // REVIEW: Is this needed in addition to setting the ThisArgument? ThisArgument = thisRef, Type = this.host.PlatformType.SystemVoid, // REVIEW: Is this the right way to do this? Arguments = new List<IExpression>(), } } ); break; } // return; statements.Add(new ReturnStatement()); body.MethodDefinition = m; m.Body = body; } #endregion return m; }
private StringBuilder AppendParameter(StringBuilder buf, IList <GenericParameter> genArgs, ParameterDefinition parameter) { AddTypeCount = false; buf.Append(GetTypeName(parameter.ParameterType)); AddTypeCount = true; return(buf); }
/// <summary> /// Build a ParameterDefinition instance based on a property name and provide value and schema. /// </summary> /// <param name="name"></param> /// <param name="value"></param> /// <param name="containerSchema"></param> /// <returns></returns> internal static ParameterDefinition ParseProperty(string name, JToken value, JsonSchema containerSchema) { ParameterDefinition param = new ParameterDefinition(); param.Name = name; param.OriginalValue = value.ToString(); switch (value.Type) { case JTokenType.Boolean: param.Type = ParameterDataType.Boolean; break; case JTokenType.Float: param.Type = ParameterDataType.Double; break; case JTokenType.Integer: param.Type = ParameterDataType.Int64; break; case JTokenType.String: var propValue = value.Value <string>(); SimpleDataType customType = Validation.ExtensionMethods.ParseSimpleTypeString(propValue.ToLowerInvariant()); ParameterDataType paramType = (customType != SimpleDataType.None) ? new ParameterDataType(customType) : ParameterDataType.String; param.Type = paramType; break; case JTokenType.Date: param.Type = ParameterDataType.DateTimeOffset; break; case JTokenType.Object: { var objectSchema = GeneratePropertyCollection((JObject)value); if (objectSchema.ContainsKey("@odata.type")) { param.Type = objectSchema["@odata.type"].OriginalValue.ParseParameterDataType(); } else if (objectSchema.ContainsKey("@type")) { param.Type = objectSchema["@type"].OriginalValue.ParseParameterDataType(); } else { // See if we can infer type from the parent scehma var propertyCollection = GeneratePropertyCollection((JObject)value); ParameterDefinition[] customMembers = null; if (propertyCollection != null) { customMembers = propertyCollection.Values.ToArray(); } ParameterDefinition schemaProperty; if (null != containerSchema && containerSchema.ExpectedProperties.TryGetValue(name, out schemaProperty)) { param.Type = new ParameterDataType(schemaProperty.Type, customMembers); } else { param.Type = new ParameterDataType(customMembers); } } break; } case JTokenType.Array: { ParameterDataType propertyType = ParameterDataType.GenericCollection; // Try to infer type from the items in the array var firstChild = value.First; if (null != firstChild) { var objectType = ParseProperty("array[0]", firstChild, null); if (null != objectType) { //Assume is a collection of Json propertyType = ParameterDataType.CollectionOfType(objectType.Type); if (propertyType.CollectionResourceType == SimpleDataType.Collection) { //If inner type is collection, assume its a Json collection propertyType = ParameterDataType.JsonCollection; } } } // See if we can do better than GenericCollection if that's the situation we're in. if (propertyType == ParameterDataType.GenericCollection) { ParameterDefinition schemaProperty; if (null != containerSchema && containerSchema.ExpectedProperties.TryGetValue(name, out schemaProperty)) { // Use the parent schema's type indication //propertyType = ParameterDataType.CollectionOfType(schemaProperty.Type); propertyType = schemaProperty.Type; } } Dictionary <string, ParameterDefinition> members = null; if ((propertyType.IsObject || (propertyType.IsCollection && propertyType.CollectionResourceType == SimpleDataType.Object)) && string.IsNullOrEmpty(propertyType.CustomTypeName)) { // If we don't know what kind of object is here, let's record what we see as custom members var firstValue = value.First as JObject; members = firstValue != null?GeneratePropertyCollection(firstValue) : new Dictionary <string, ParameterDefinition>(); } ParameterDefinition[] customMembers = null; if (members != null) { customMembers = members.Values.ToArray(); } param.Type = new ParameterDataType(propertyType, customMembers); break; } case JTokenType.Null: param.Type = ParameterDataType.GenericObject; param.OriginalValue = null; break; default: Console.WriteLine("Unsupported: Property {0} is of type {1} which is not currently supported.", name, value.Type); throw new NotSupportedException(string.Format("Unsupported: Property {0} is of type {1} which is not currently supported.", name, value.Type)); } return(param); }
private PropertyValidationOutcome ValidateSimpleArrayProperty(ParameterDefinition actualProperty, ParameterDefinition expectedProperty, IssueLogger issues) { if (!actualProperty.Type.IsCollection || !expectedProperty.Type.IsCollection) { throw new SchemaBuildException("Cannot use simple array valiation without array types", null); } if (actualProperty.Type == expectedProperty.Type) { return(PropertyValidationOutcome.Ok); } else if (expectedProperty.Type.IsCollection && actualProperty.Type.IsCollection && actualProperty.OriginalValue == "[]") // Check for the empty array case { return(PropertyValidationOutcome.Ok); } else if (expectedProperty.Type.IsLessSpecificThan(actualProperty.Type)) { return(PropertyValidationOutcome.Ok); } else { issues.Error(ValidationErrorCode.ArrayTypeMismatch, $"Array expected members to be of type {expectedProperty.Type} but found: {actualProperty.Type}"); return(PropertyValidationOutcome.InvalidType); } }
static void AddNormalCheck(TypeDefinition type, Collection <Instruction> c, PropertyDefinition property, ParameterDefinition left, ParameterDefinition right) { var genericInstance = new Lazy <TypeReference>(() => ReferenceFinder.ImportCustom(property.PropertyType.GetGenericInstanceType(type))); var getMethodImported = ReferenceFinder.ImportCustom(property.GetGetMethod(type)); c.Add(Instruction.Create(type.GetLdArgForType(), left)); c.Add(Instruction.Create(getMethodImported.GetCallForMethod(), getMethodImported)); if (property.PropertyType.IsValueType || property.PropertyType.IsGenericParameter) { c.Add(Instruction.Create(OpCodes.Box, genericInstance.Value)); } c.Add(Instruction.Create(type.GetLdArgForType(), right)); c.Add(Instruction.Create(getMethodImported.GetCallForMethod(), getMethodImported)); if (property.PropertyType.IsValueType || property.PropertyType.IsGenericParameter) { c.Add(Instruction.Create(OpCodes.Box, genericInstance.Value)); } c.Add(Instruction.Create(OpCodes.Call, ReferenceFinder.Object.StaticEquals)); }
protected abstract void BuildInstructions(ModuleDefinition module, TypeDefinition type, MethodDefinition method, ParameterDefinition parameter, CustomAttribute attribute, List <Instruction> instructions);
private void InjectAssemblyName(IAssemblyResolver assemblyResolver, string assemblyPath, string outputPath) { var assemblyName = Path.GetFileNameWithoutExtension(assemblyPath); using (var assembly = AssemblyDefinition.ReadAssembly(assemblyPath)) { var module = assembly.MainModule; var attributeType = ResolveSystemAttribute(module); var baseCtor = attributeType.Methods.FirstOrDefault(m => m.Name == ".ctor"); var iana = new TypeDefinition(InjectedAttributeNamespace, InjectedAttributeTypeName, TypeAttributes.Class); iana.BaseType = module.ImportReference(attributeType); var field = new FieldDefinition("assemblyName", FieldAttributes.Private | FieldAttributes.InitOnly, module.TypeSystem.String); var getterAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName; var getter = new MethodDefinition("get_AssemblyName", getterAttributes, module.TypeSystem.String); getter.DeclaringType = iana; getter.HasThis = true; getter.IsGetter = true; getter.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); getter.Body.Instructions.Add(Instruction.Create(OpCodes.Ldfld, field)); getter.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); var property = new PropertyDefinition("AssemblyName", PropertyAttributes.None, module.TypeSystem.String); property.HasThis = true; property.GetMethod = getter; var methodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName; var ctor = new MethodDefinition(".ctor", methodAttributes, module.TypeSystem.Void); var param = new ParameterDefinition("assemblyName", ParameterAttributes.None, module.TypeSystem.String); ctor.Parameters.Add(param); ctor.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); ctor.Body.Instructions.Add(Instruction.Create(OpCodes.Call, module.ImportReference(baseCtor))); ctor.Body.Instructions.Add(Instruction.Create(OpCodes.Nop)); ctor.Body.Instructions.Add(Instruction.Create(OpCodes.Nop)); ctor.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); ctor.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_1)); ctor.Body.Instructions.Add(Instruction.Create(OpCodes.Stfld, field)); ctor.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); iana.Fields.Add(field); iana.Properties.Add(property); iana.Methods.Add(ctor); iana.Methods.Add(getter); module.Types.Add(iana); foreach (var type in module.Types) { type.CustomAttributes.Add(new CustomAttribute(ctor) { ConstructorArguments = { new CustomAttributeArgument(module.TypeSystem.String, assemblyName) } }); } assembly.Write(outputPath); } TypeDefinition ResolveSystemAttribute(ModuleDefinition module) { foreach (var reference in module.AssemblyReferences) { var resolved = assemblyResolver.Resolve(reference); var attributeType = resolved.MainModule.GetType("System.Attribute"); if (attributeType != null) { return(attributeType); } } throw new Exception("Unable to locate System.Attribute in any of the assemblies."); } }
private static bool IsSmartContractState(ParameterDefinition firstArg) { return(firstArg.ParameterType.FullName == typeof(ISmartContractState).FullName); }
public CecilSignalDescriptor(CecilWidgetLibrary lib, XmlElement elem, Stetic.ItemGroup group, Stetic.ClassDescriptor klass, EventDefinition sinfo) : base(elem, group, klass) { if (sinfo != null) { string handler = sinfo.EventType.FullName; handlerTypeName = handler.Replace('/', '+'); Type t = Registry.GetType(handler, false); if (t != null) { MethodInfo mi = t.GetMethod("Invoke"); handlerReturnTypeName = mi.ReturnType.FullName; ParameterInfo[] pars = mi.GetParameters(); handlerParameters = new ParameterDescriptor [pars.Length]; for (int n = 0; n < pars.Length; n++) { handlerParameters [n] = new ParameterDescriptor(pars[n].Name, pars[n].ParameterType.FullName); } } else { // If the type is generic, the type arguments must be ignored when looking for the type string tn = handler; int i = handler.IndexOf('<'); if (i != -1) { tn = handler.Substring(0, i); // Convert the type name to a type reference handler = handler.Replace('<', '['); handler = handler.Replace('>', ']'); } TypeDefinition td = lib.FindTypeDefinition(tn); if (td != null) { MethodDefinition mi = null; foreach (MethodDefinition md in td.Methods) { if (md.Name == "Invoke") { mi = md; break; } } if (mi != null) { handlerReturnTypeName = CecilWidgetLibrary.GetInstanceType(td, sinfo.EventType, mi.ReturnType.ReturnType); handlerParameters = new ParameterDescriptor [mi.Parameters.Count]; for (int n = 0; n < handlerParameters.Length; n++) { ParameterDefinition par = mi.Parameters [n]; handlerParameters [n] = new ParameterDescriptor(par.Name, CecilWidgetLibrary.GetInstanceType(td, sinfo.EventType, par.ParameterType)); } } } else { handlerParameters = new ParameterDescriptor [0]; } } SaveCecilXml(elem); } else { handlerTypeName = elem.GetAttribute("handlerTypeName"); handlerReturnTypeName = elem.GetAttribute("handlerReturnTypeName"); ArrayList list = new ArrayList(); foreach (XmlNode npar in elem.ChildNodes) { XmlElement epar = npar as XmlElement; if (epar == null) { continue; } list.Add(new ParameterDescriptor(epar.GetAttribute("name"), epar.GetAttribute("type"))); } handlerParameters = (ParameterDescriptor[])list.ToArray(typeof(ParameterDescriptor)); } Load(elem); }
static void AddSimpleValueCheck(Collection <Instruction> c, PropertyDefinition property, TypeDefinition type, ParameterDefinition left, ParameterDefinition right) { var getMethod = property.GetGetMethod(type); var getMethodImported = ReferenceFinder.ImportCustom(getMethod); c.Add(Instruction.Create(type.GetLdArgForType(), left)); c.Add(Instruction.Create(getMethodImported.GetCallForMethod(), getMethodImported)); c.Add(Instruction.Create(type.GetLdArgForType(), right)); c.Add(Instruction.Create(getMethodImported.GetCallForMethod(), getMethodImported)); c.Add(Instruction.Create(OpCodes.Ceq)); }
static void AddCollectionEquals(TypeDefinition type, MethodDefinition collectionEquals, PropertyDefinition property, TypeDefinition propType, Collection <Instruction> e, ParameterDefinition left, ParameterDefinition right) { e.If( cf => { cf.Add(Instruction.Create(type.GetLdArgForType(), right)); cf.Add(Instruction.Create(OpCodes.Ldnull)); cf.Add(Instruction.Create(OpCodes.Ceq)); }, t => t.Add(Instruction.Create(OpCodes.Ldc_I4_0)), es => { var getMethod = property.GetGetMethod(type); var getMethodImported = ReferenceFinder.ImportCustom(getMethod); es.Add(Instruction.Create(type.GetLdArgForType(), left)); es.Add(Instruction.Create(getMethodImported.GetCallForMethod(), getMethodImported)); if (propType.IsValueType && !property.PropertyType.IsArray) { var imported = ReferenceFinder.ImportCustom(property.PropertyType); es.Add(Instruction.Create(OpCodes.Box, imported)); } es.Add(Instruction.Create(type.GetLdArgForType(), right)); es.Add(Instruction.Create(getMethodImported.GetCallForMethod(), getMethodImported)); if (propType.IsValueType && !property.PropertyType.IsArray) { var imported = ReferenceFinder.ImportCustom(property.PropertyType); es.Add(Instruction.Create(OpCodes.Box, imported)); } es.Add(Instruction.Create(OpCodes.Call, collectionEquals)); }); }
static void AddCollectionCheck(TypeDefinition type, MethodDefinition collectionEquals, Collection <Instruction> c, PropertyDefinition property, TypeDefinition propType, ParameterDefinition left, ParameterDefinition right) { c.If( AddCollectionFirstArgumentCheck, AddCollectionSecondArgumentCheck, e => AddCollectionEquals(type, collectionEquals, property, propType, e, left, right)); }
private void EmitKnownStructFieldSetReturn(ModuleDefinition destModule, ILProcessor ilProcessor, MethodBody body, FieldDefinition field, ParameterDefinition indexParameter, ParameterDefinition valueParameter) { int num; ilProcessor.Emit(OpCodes.Ldflda, base.OperationContext.Import(destModule, field)); ilProcessor.EmitLdarg(valueParameter); ilProcessor.EmitLdarg(indexParameter); string[] members = GetKnownStructMembers(field); Instruction[] targets = new Instruction[members.Length]; ilProcessor.Emit(OpCodes.Switch, targets); ilProcessor.Emit(OpCodes.Ldstr, indexParameter.Name); ilProcessor.Emit(OpCodes.Newobj, destModule.ImportReference(base.ModuleContext.GetCorLibMethod("System.ArgumentOutOfRangeException", <> c.< > 9__29_0 ?? (< > c.< > 9__29_0 = new Func <MethodDefinition, bool>(< > c.< > 9. < EmitKnownStructFieldSetReturn > b__29_0))))); ilProcessor.Emit(OpCodes.Throw); Collection <FieldDefinition> fields = field.FieldType.Resolve().Fields; for (int i = 0; i < members.Length; i = num) { ilProcessor.Emit(OpCodes.Stfld, destModule.ImportReference(base.ModuleContext.Import(fields.Single <FieldDefinition>(f => f.Name == members[i])))); targets[i] = body.Instructions.Last <Instruction>(); ilProcessor.Emit(OpCodes.Ret); num = i + 1; } }
public override void BuildMethod() { AddStatement.DeclareInterceptedType(field.ContainingType.ResolvedType); Context.Log.WriteTrace(" Adding: var interceptedField = interceptedType.GetField('{0}');", field.Name.Value); Context.Block.Statements.Add( Declare.Variable<FieldInfo>("interceptedField").As( Call.VirtualMethod("GetField", typeof (string)).ThatReturns<FieldInfo>().WithArguments( Constant.Of(field.Name.Value)).On("interceptedType")) ); AddStatement.DeclareArgumentsList(); AddStatement.AddArgumentToList(Params["assignedValue"]); var actionT = SharpMockTypes.Actions[1]; var actionActualT = new GenericTypeInstanceReference(); actionActualT.GenericType = actionT; actionActualT.GenericArguments.Add(field.Type); var assignment = new AnonymousDelegate(); assignment.Type = actionActualT; assignment.ReturnType = Context.Host.PlatformType.SystemVoid; assignment.CallingConvention = CallingConvention.HasThis; var parameterDefinition = new ParameterDefinition(); parameterDefinition.Index = 0; parameterDefinition.Type = field.Type; parameterDefinition.Name = Context.Host.NameTable.GetNameFor("alteredValue"); parameterDefinition.ContainingSignature = assignment; assignment.Parameters.Add(parameterDefinition); var assignmentBody = new BlockStatement(); var assignActualField = new ExpressionStatement(); var actualField = new TargetExpression(); actualField.Type = field.Type; actualField.Definition = field; var value = new BoundExpression(); value.Type = field.Type; value.Definition = parameterDefinition; var assignValueToField = new Assignment(); assignValueToField.Source = value; assignValueToField.Target = actualField; assignValueToField.Type = field.Type; assignActualField.Expression = assignValueToField; actualField.Type = field.Type; actualField.Definition = field; assignmentBody.Statements.Add(assignActualField); assignmentBody.Statements.Add(new ReturnStatement()); assignment.Body = assignmentBody; Context.Block.Statements.Add( Declare.Variable("local_0", actionActualT).As(assignment) ); AddStatement.DeclareRegistryInterceptor(); AddStatement.DeclareInvocation(); AddStatement.SetArgumentsOnInvocation(); AddStatement.SetOriginalCallOnInvocation(); AddStatement.SetTargetOnInvocationToNull(); Context.Block.Statements.Add( Do(Call.PropertySetter<MemberInfo>("OriginalCallInfo").WithArguments("interceptedField").On("invocation")) ); AddStatement.CallShouldInterceptOnInterceptor(); AddStatement.CallInterceptOnInterceptor(); Context.Block.Statements.Add(Return.Void()); }
private static Instruction GetInstructionForParameter <TParam, TThis, TInput, TLocal, TUseOutput, TMethodOutputBind>(CecilContext stardewContext, ILProcessor ilProcessor, ParameterDefinition parameter) { if (!parameter.HasCustomAttributes) { return(null); } var attribute = parameter.CustomAttributes.FirstOrDefault(n => n.AttributeType.IsDefinition && n.AttributeType.Resolve().BaseType?.FullName == typeof(TParam).FullName); if (attribute == null) { return(null); } Instruction instruction = null; if (typeof(TThis).FullName == attribute.AttributeType.FullName) { instruction = ilProcessor.Create(OpCodes.Ldarg, ilProcessor.Body.ThisParameter); } else if (typeof(TInput).FullName == attribute.AttributeType.FullName) { var type = attribute.ConstructorArguments[0].Value as TypeReference; var name = attribute.ConstructorArguments[1].Value as string; var inputParam = ilProcessor.Body.Method.Parameters.FirstOrDefault( p => p.Name == name && p.ParameterType.FullName == type?.FullName); if (inputParam != null) { if (((bool)attribute.ConstructorArguments[2].Value)) { instruction = ilProcessor.Create(OpCodes.Ldarga, inputParam); } else { instruction = ilProcessor.Create(OpCodes.Ldarg, inputParam); } } } else if (typeof(TLocal).FullName == attribute.AttributeType.FullName) { var type = attribute.ConstructorArguments[0].Value as TypeReference; var index = attribute.ConstructorArguments[1].Value as int?; var inputParam = ilProcessor.Body.Variables.FirstOrDefault( p => p.Index == index && p.VariableType.FullName == type?.FullName); if (inputParam != null) { instruction = ilProcessor.Create(OpCodes.Ldloc, inputParam); } } else if (typeof(TUseOutput).FullName == attribute.AttributeType.FullName) { var outputVar = ilProcessor.Body.Variables.First(n => n.Name == "UseReturnVal"); instruction = ilProcessor.Create(OpCodes.Ldloca, outputVar); } else if (typeof(TMethodOutputBind).FullName == attribute.AttributeType.FullName) { var outputVar = ilProcessor.Body.Variables.First(n => n.Name == "OldReturnContainer"); instruction = ilProcessor.Create(OpCodes.Ldloc, outputVar); } else { throw new Exception("Unhandled parameter bind type"); } return(instruction); }
private static PropertyValidationOutcome ValidateStringFormat(ParameterDefinition schemaProperty, ParameterDefinition inputProperty, IssueLogger issues) { switch (schemaProperty.StringFormat()) { case ExpectedStringFormat.Iso8601Date: { DateTimeOffset?output = inputProperty.OriginalValue.TryParseIso8601Date(); if (!output.HasValue) { issues.Error(ValidationErrorCode.InvalidDateTimeString, $"Invalid ISO 8601 date-time string in property: {schemaProperty.Name}: {inputProperty.OriginalValue}"); return(PropertyValidationOutcome.BadStringValue); } return(PropertyValidationOutcome.Ok); } case ExpectedStringFormat.AbsoluteUrl: { try { new Uri(inputProperty.OriginalValue, UriKind.Absolute); return(PropertyValidationOutcome.Ok); } catch (FormatException) { issues.Error(ValidationErrorCode.InvalidUrlString, $"Invalid absolute URL value in property {schemaProperty.Name}: {inputProperty.OriginalValue}"); return(PropertyValidationOutcome.BadStringValue); } } case ExpectedStringFormat.EnumeratedValue: { if (!schemaProperty.IsValidEnumValue(inputProperty.OriginalValue)) { issues.Error(ValidationErrorCode.InvalidEnumeratedValueString, $"Invalid enumerated value in property {schemaProperty.Name}: {inputProperty.OriginalValue}"); return(PropertyValidationOutcome.BadStringValue); } return(PropertyValidationOutcome.Ok); } case ExpectedStringFormat.Generic: return(PropertyValidationOutcome.Ok); default: throw new NotImplementedException(); } }
/// <summary> /// Replace generic parameters with actual arguments /// </summary> private MonoTypeContext ResolveGenericParameter() { switch (Type.etype) { case ElementType.Var: case ElementType.MVar: { GenericParameter parameter = (GenericParameter)Type; TypeReference resolvedType = Arguments[parameter]; return(new MonoTypeContext(resolvedType)); } case ElementType.Array: { ArrayType array = (ArrayType)Type; MonoTypeContext arrayContext = new MonoTypeContext(array.ElementType, Arguments); MonoTypeContext resolvedContext = arrayContext.ResolveGenericParameter(); ArrayType newArray = new ArrayType(resolvedContext.Type, array.Rank); if (array.Rank > 1) { for (int i = 0; i < array.Rank; i++) { newArray.Dimensions[i] = array.Dimensions[i]; } } return(new MonoTypeContext(newArray, Arguments)); } case ElementType.GenericInst: { GenericInstanceType genericInstance = (GenericInstanceType)Type; GenericInstanceType newInstance = new GenericInstanceType(genericInstance.ElementType); foreach (TypeReference argument in genericInstance.GenericArguments) { MonoTypeContext argumentContext = new MonoTypeContext(argument, Arguments); MonoTypeContext resolvedArgument = argumentContext.Resolve(); newInstance.GenericArguments.Add(resolvedArgument.Type); } return(new MonoTypeContext(newInstance, Arguments)); } case ElementType.ByRef: { ByReferenceType reference = (ByReferenceType)Type; MonoTypeContext refContext = new MonoTypeContext(reference.ElementType, Arguments); MonoTypeContext resolvedContext = refContext.ResolveGenericParameter(); ByReferenceType newReference = new ByReferenceType(resolvedContext.Type); return(new MonoTypeContext(newReference, Arguments)); } case ElementType.Ptr: { PointerType pointer = (PointerType)Type; MonoTypeContext ptrContext = new MonoTypeContext(pointer.ElementType, Arguments); MonoTypeContext resolvedContext = ptrContext.ResolveGenericParameter(); PointerType newPointer = new PointerType(resolvedContext.Type); return(new MonoTypeContext(newPointer, Arguments)); } case ElementType.Pinned: { PinnedType pinned = (PinnedType)Type; MonoTypeContext pinContext = new MonoTypeContext(pinned.ElementType, Arguments); MonoTypeContext resolvedContext = pinContext.ResolveGenericParameter(); PinnedType newPinned = new PinnedType(resolvedContext.Type); return(new MonoTypeContext(newPinned, Arguments)); } case ElementType.FnPtr: { FunctionPointerType funcPtr = (FunctionPointerType)Type; FunctionPointerType newFuncPtr = new FunctionPointerType(); newFuncPtr.HasThis = funcPtr.HasThis; newFuncPtr.ExplicitThis = funcPtr.ExplicitThis; newFuncPtr.CallingConvention = funcPtr.CallingConvention; MonoTypeContext returnContext = new MonoTypeContext(funcPtr.ReturnType, Arguments); MonoTypeContext resolvedReturn = returnContext.Resolve(); newFuncPtr.ReturnType = resolvedReturn.Type; foreach (ParameterDefinition param in funcPtr.Parameters) { MonoTypeContext paramContext = new MonoTypeContext(param.ParameterType, Arguments); MonoTypeContext resolvedParam = paramContext.Resolve(); ParameterDefinition newParameter = new ParameterDefinition(param.Name, param.Attributes, resolvedParam.Type); newFuncPtr.Parameters.Add(newParameter); } return(new MonoTypeContext(newFuncPtr, Arguments)); } default: throw new Exception($"Unknown generic parameter container {Type}"); } }
private static void AddParameterDataToProperty(IEnumerable <ParameterDefinition> parameters, ParameterDefinition schemaPropertyDef) { if (null != schemaPropertyDef && null != parameters) { // See if we can look up more data for this new property var findParameterQuery = from p in parameters where p.Name == schemaPropertyDef.Name select p; var parameterData = findParameterQuery.FirstOrDefault(); if (null != parameterData) { schemaPropertyDef.Description = parameterData.Description; } } }
void emulate_Starg(ParameterDefinition arg) { setArg(index(arg), valueStack.pop()); }
/// <summary> /// Returns the first <see cref="CustomAttribute"/>s that matches <typeparamref name="TAttr"/>, /// or <code>null</code>. /// </summary> public static CustomAttribute GetAttribute <TAttr>(this ParameterDefinition def) where TAttr : Attribute => GetAttributes <TAttr>(def).FirstOrDefault();
public SsaVariable(SsaVariable original, string newName) { this.Name = newName; this.IsStackLocation = original.IsStackLocation; this.OriginalVariableIndex = original.OriginalVariableIndex; this.Parameter = original.Parameter; this.Variable = original.Variable; }
/// <summary> /// Get mutable copy of a parameter definition of an anonymous delegate. The parameters of anonymous delegate /// are not visited until the code of a souce method body is visited. /// </summary> /// <param name="parameterDefinition"></param> /// <returns></returns> private ParameterDefinition GetMutableCopyParamAnonymDeleg(IParameterDefinition parameterDefinition) { ParameterDefinition/*?*/ result; object/*?*/ cachedValue = null; this.cache.TryGetValue(parameterDefinition, out cachedValue); result = cachedValue as ParameterDefinition; if (result != null) return result; result = new ParameterDefinition(); this.cache.Add(parameterDefinition, result); this.cache.Add(result, result); result.Copy(parameterDefinition, this.host.InternFactory); return result; }
public void Emit(OpCode opcode, ParameterDefinition parameter) { Append (Create (opcode, parameter)); }
public ManagedParameter(ParameterDefinition nativeParam) { Native = nativeParam; Name = nativeParam.Name; }
public virtual void ReadConstant (ParameterDefinition param) { }
static void ReadMethodDefinition(XmlReader reader, ClassDefinition @class) { string name = reader.GetAttribute("Name"); string isExcluded = reader.GetAttribute("IsExcluded"); var parameters = new List<ParameterDefinition>(); while (reader.Read()) { if (reader.NodeType == XmlNodeType.EndElement) { break; } if (reader.NodeType != XmlNodeType.Element) { continue; } switch (reader.Name) { case "Parameter": { string parameterName = reader.GetAttribute("Name"); var parameter = new ParameterDefinition(parameterName, null); string marshalDirectionString = reader.GetAttribute("MarshalDirection"); if (marshalDirectionString != null) { MarshalDirection marshalDirection; if (Enum.TryParse(marshalDirectionString, out marshalDirection)) { parameter.MarshalDirection = marshalDirection; } } parameters.Add(parameter); } continue; } } var method = new MethodDefinition(name, @class, parameters.Count); for (int i = 0; i < parameters.Count; i++) { method.Parameters[i] = parameters[i]; } if ("true".Equals(isExcluded)) { method.IsExcluded = true; } }
public static Instruction Create (OpCode opcode, ParameterDefinition parameter) { if (parameter == null) throw new ArgumentNullException ("parameter"); if (opcode.OperandType != OperandType.ShortInlineArg && opcode.OperandType != OperandType.InlineArg) throw new ArgumentException ("opcode"); return new Instruction (opcode, parameter); }
/// <summary> /// Writes attach/detach method /// </summary> /// <param name="writer"></param> /// <param name="table"></param> /// <param name="schema"></param> /// <param name="context"></param> protected virtual void WriteClassChildrenAttachment(CodeWriter writer, Table table, Database schema, GenerationContext context) { var children = GetClassChildren(table).ToList(); if (children.Count > 0) { using (writer.WriteRegion("Attachement handlers")) { foreach (var child in children) { // the reverse child is the association seen from the child // we're going to use it... var reverseChild = schema.GetReverseAssociation(child); // ... to get the parent name var memberName = reverseChild.Member; var entityParameter = new ParameterDefinition { Name = "entity", LiteralType = child.Type }; // the Attach event handler sets the child entity parent to "this" using (writer.WriteMethod(SpecificationDefinition.Private, GetChildAttachMethodName(child), null, entityParameter)) { writer.WriteLine( writer.GetStatement( writer.GetAssignmentExpression( writer.GetMemberExpression(entityParameter.Name, memberName), writer.GetThisExpression()))); } writer.WriteLine(); // the Detach event handler sets the child entity parent to null using (writer.WriteMethod(SpecificationDefinition.Private, GetChildDetachMethodName(child), null, entityParameter)) { writer.WriteLine( writer.GetStatement( writer.GetAssignmentExpression( writer.GetMemberExpression(entityParameter.Name, memberName), writer.GetNullExpression()))); } writer.WriteLine(); } } } }
int GetParameterIndex (ParameterDefinition parameter) { if (body.method.HasThis) { if (parameter == body.this_parameter) return 0; return parameter.Index + 1; } return parameter.Index; }
public static CodeProviderCallArgument CreateGenericParameterArgument([NotNull] string name, [NotNull] ParameterDefinition parameterDefinition) { return(new CodeProviderCallArgument(name, CodeProviderCallArgumentType.ParameterDefinition, null) { parameterDefinition = parameterDefinition }); }
/// <summary> /// Returns all <see cref="CustomAttribute"/>s that match <typeparamref name="TAttr"/>. /// </summary> public static IEnumerable <CustomAttribute> GetAttributes <TAttr>(this ParameterDefinition def) where TAttr : Attribute => def.CustomAttributes.Where(x => x.AttributeType.Is <TAttr>(true));
void emulate_Ldarga(ParameterDefinition arg) { valueStack.pushUnknown(); makeArgUnknown(arg); }
static void AddPropertyCode(TypeDefinition type, MethodDefinition collectionEquals, PropertyDefinition property, Collection <Instruction> ins, ParameterDefinition left, ParameterDefinition right) { ins.IfNot( c => { if (!property.PropertyType.IsGenericParameter) { var propType = property.PropertyType.Resolve(); var isCollection = propType.IsCollection() || property.PropertyType.IsArray; if ((simpleTypes.Contains(propType.FullName) || propType.IsEnum) && !property.PropertyType.IsArray) { AddSimpleValueCheck(c, property, type, left, right); } else if (!isCollection || propType.FullName == typeof(string).FullName) { AddNormalCheck(type, c, property, left, right); } else { AddCollectionCheck(type, collectionEquals, c, property, propType, left, right); } } else { var genericType = property.PropertyType.GetGenericInstanceType(type); AddNormalCheck(type, c, property, left, right); } }, AddReturnFalse); }
public SsaVariable(ParameterDefinition p) { this.Name = string.IsNullOrEmpty(p.Name) ? "param" + p.Index : p.Name; this.Parameter = p; }
int index(ParameterDefinition arg) { return(arg.Sequence); }
public Instruction Create(OpCode opcode, ParameterDefinition parameter) { return Instruction.Create (opcode, parameter); }
public Value getArg(ParameterDefinition arg) { return(getArg(index(arg))); }
public virtual void ReadMarshalSpec (ParameterDefinition param) { }
public void setArg(ParameterDefinition arg, Value value) { setArg(index(arg), value); }
public override IDisposable WriteCtor(SpecificationDefinition specificationDefinition, string name, ParameterDefinition[] parameters, IList<string> baseCallParameters) { return WriteGeneralMethod(specificationDefinition, name, false, null, parameters, baseCallParameters); }
public void makeArgUnknown(ParameterDefinition arg) { setArg(arg, getUnknownArg(index(arg))); }
internal ParameterDefinition Copy() { ParameterDefinition p = new ParameterDefinition(Name, Type, IsOptional); p.ManagedName = ManagedName; return p; }
private static PropertyValidationOutcome ValidateSameDataType(ParameterDefinition expected, ParameterDefinition actual, IssueLogger issues, bool relaxStringValidation) { if (expected.Type == actual.Type && actual.Type != ParameterDataType.String) { return(PropertyValidationOutcome.Ok); } else if (expected.Type == actual.Type && actual.Type == ParameterDataType.String) { // Perform extra validation to see if the string is the right format (iso date, enum value, url, or just a string) if (relaxStringValidation) { return(PropertyValidationOutcome.Ok); } return(ValidateStringFormat(expected, actual, issues)); } else if (expected.Type == ParameterDataType.String && expected.Type.IsLessSpecificThan(actual.Type)) { return(PropertyValidationOutcome.Ok); } else if (actual.Type.IsLessSpecificThan(expected.Type)) { if (relaxStringValidation) { issues.Message( $"Expected type {expected.Type} but actual was {actual.Type}, which is less specific than the expected type. Property: {actual.Name}, actual value: '{actual.OriginalValue}'"); return(PropertyValidationOutcome.Ok); } issues.Error( ValidationErrorCode.ExpectedTypeDifferent, $"Expected type {expected.Type} but actual was {actual.Type}, which is less specific than the expected type. Property: {actual.Name}, actual value: '{actual.OriginalValue}'"); return(PropertyValidationOutcome.BadStringValue); } else { // Type of the inputProperty is mismatched from the expected value. issues.Error( ValidationErrorCode.ExpectedTypeDifferent, $"Expected type {expected.Type} but actual was {actual.Type}. Property: {actual.Name}, actual value: '{actual.OriginalValue}'"); return(PropertyValidationOutcome.InvalidType); } }
internal static ParameterDefinition Clone(ParameterDefinition param, ImportContext context) { ParameterDefinition np = new ParameterDefinition ( param.Name, param.Sequence, param.Attributes, context.Import (param.ParameterType)); if (param.HasConstant) np.Constant = param.Constant; if (param.MarshalSpec != null) np.MarshalSpec = param.MarshalSpec; foreach (CustomAttribute ca in param.CustomAttributes) np.CustomAttributes.Add (CustomAttribute.Clone (ca, context)); return np; }
/// <summary> /// Verify that a property from the json-to-validate matches something in our schema /// </summary> private PropertyValidationOutcome ValidateProperty(ParameterDefinition inputProperty, Dictionary <string, JsonSchema> schemas, IssueLogger issues, ValidationOptions options) { if (this.ExpectedProperties.ContainsKey(inputProperty.Name)) { // The property was expected to be found in this schema! Yay. var schemaPropertyDef = this.ExpectedProperties[inputProperty.Name]; // Check for simple value types first if (this.SimpleValueTypes(schemaPropertyDef.Type, inputProperty.Type) && this.AllFalse(schemaPropertyDef.Type.IsCollection, inputProperty.Type.IsCollection)) { return(ValidateSameDataType(schemaPropertyDef, inputProperty, issues, (null != options) ? options.RelaxedStringValidation : false)); } else if (null == inputProperty.OriginalValue) { if (null != this.NullableProperties && !this.NullableProperties.Contains(schemaPropertyDef.Name)) { issues.Warning(ValidationErrorCode.NullPropertyValue, $"Non-nullable property {schemaPropertyDef.Name} had a null value in the response. Expected {schemaPropertyDef.Type}."); } return(PropertyValidationOutcome.Ok); } else if (schemaPropertyDef.Type.IsCollection || inputProperty.Type.IsCollection) { // Check for an array if (schemaPropertyDef.Type.IsCollection && !inputProperty.Type.IsCollection) { // Expected an array, but didn't get one issues.Error(ValidationErrorCode.ExpectedArrayValue, $"Expected an array but property was not an array: {inputProperty.Name}"); return(PropertyValidationOutcome.InvalidType); } else if (!schemaPropertyDef.Type.IsCollection && inputProperty.Type.IsCollection) { issues.Error(ValidationErrorCode.ExpectedNonArrayValue, $"Expected a value of type {schemaPropertyDef.Type} but property was an array: {inputProperty.Name}"); return(PropertyValidationOutcome.InvalidType); } return(this.ValidateArrayProperty(inputProperty, schemas, issues, options)); } else if (schemaPropertyDef.Type.IsObject && inputProperty.Type.IsObject) { // Compare the ODataType schema to the custom schema if (null == schemaPropertyDef.Type.CustomTypeName || !schemas.ContainsKey(schemaPropertyDef.Type.CustomTypeName)) { issues.Error(ValidationErrorCode.ResourceTypeNotFound, $"Missing resource: resource {schemaPropertyDef.Type.CustomTypeName} was not found (property name '{inputProperty.Name}')."); return(PropertyValidationOutcome.MissingResourceType); } else if (inputProperty.Type.IsObject) { var odataSchema = schemas[schemaPropertyDef.Type.CustomTypeName]; if (null != inputProperty.Type.CustomMembers && !odataSchema.ValidateCustomObject(inputProperty.Type.CustomMembers.ToArray(), issues, schemas, options)) { if (issues.Errors.Any()) { issues.Error(ValidationErrorCode.ConsolidatedError, $"Schema validation failed on property '{inputProperty.Name}' ['{odataSchema.ResourceName}']"); } else { issues.Warning(ValidationErrorCode.ConsolidatedError, $"Schema validation failed on property '{inputProperty.Name}' ['{odataSchema.ResourceName}']"); } return(PropertyValidationOutcome.InvalidType); } else if (null == inputProperty.Type.CustomMembers) { //Temporarily disabled: Issue Tracked at https://github.com/OneDrive/apidoctor/issues/13 //issues.Error(ValidationErrorCode.NoCustomMembersFound, $"Property '{inputProperty.Name}' is of type Custom but has no custom members."); } return(PropertyValidationOutcome.Ok); } else { var odataSchema = schemas[schemaPropertyDef.Type.CustomTypeName]; if (inputProperty.Type.CustomMembers == null) { issues.Error(ValidationErrorCode.MissingCustomMembers, $"Property {inputProperty.Name} is missing custom members and cannot be validated."); return(PropertyValidationOutcome.InvalidType); } else { odataSchema.ValidateObjectProperties(inputProperty.Type.CustomMembers, options, schemas, issues); return(PropertyValidationOutcome.Ok); } } } else if (schemaPropertyDef.Type.IsObject) { issues.Warning(ValidationErrorCode.CustomValidationNotSupported, $"Schemas type was 'Custom' which is not supported. Add a resource type to the definition of property: {inputProperty.Name}"); return(PropertyValidationOutcome.MissingResourceType); } else { issues.Error(ValidationErrorCode.ExpectedTypeDifferent, $"Type mismatch: property '{inputProperty.Name}' [{inputProperty.Type}] doesn't match expected type [{schemaPropertyDef.Type}]."); return(PropertyValidationOutcome.InvalidType); } } else { // Check to see if this property is on the ignorable list string[] ignorableUndocumentedProperties = this.OriginalResource?.SourceFile.Parent.Requirements?.IgnorableProperties; string propertyName = inputProperty.Name; string annotationName = null; var indexOfAtSign = propertyName.IndexOf('@'); if (indexOfAtSign > 0) { // [email protected] is an example of what we're looking for here annotationName = propertyName.Substring(indexOfAtSign); propertyName = propertyName.Substring(0, indexOfAtSign); } if (null != annotationName) { // Check to see if propertyName is known or not. If it isn't known, fail. if (this.Properties.Any(x => x.Name.Equals(propertyName))) { // If the cleaned up propertyName is known, then check to see if the annotation is ignorable if (null != ignorableUndocumentedProperties && ignorableUndocumentedProperties.Contains(annotationName)) { // If we know of both the property and the annotation, we're good. return(PropertyValidationOutcome.Ok); } } } if (null != ignorableUndocumentedProperties && ignorableUndocumentedProperties.Contains(propertyName)) { return(PropertyValidationOutcome.Ok); } if (this.OriginalResource?.OriginalMetadata?.IsOpenType == true) { return(PropertyValidationOutcome.Ok); } // This property isn't documented issues.Warning(new UndocumentedPropertyWarning(null, inputProperty.Name, inputProperty.Type, ResourceName)); return(PropertyValidationOutcome.MissingFromSchema); } }