Exemple #1
0
 /// <summary>
 /// This .ctor is handy for message inspectors.
 /// Creates a substitute message for the original one with new values.
 /// Binding-specific context is cloned and headers/correlation data are cloned conditionaly
 /// </summary>
 public RequestAnyMsg(RequestMsg inspectedOriginal,
     TypeSpec contract, MethodSpec method, bool oneWay, Guid? instance, object[] args,
     bool cloneHeaders = true, bool cloneCorrelation = true)
     : base(inspectedOriginal, contract, method, oneWay, instance, cloneHeaders, cloneCorrelation)
 {
     m_Arguments = args;
 }
Exemple #2
0
 /// <summary>
 /// Constructs request message from pre-computed  specs obtained by reflection. 
 /// This constructor is the fastest as it does not use reflection
 /// </summary>
 protected RequestMsg(TypeSpec contract, MethodSpec method, bool oneWay, Guid? instance) : base()
 {
     m_Contract = contract;
     m_Method = method;
     m_OneWay = oneWay;
     m_RemoteInstance = instance;
 }
Exemple #3
0
            /// <summary>
            /// Read ctor
            /// </summary>
            internal Type(TypeSpec parent, ResReader reader)
                : base(reader, ChunkTypes.RES_TABLE_TYPE_TYPE)
            {
                this.parent = parent;

                var id = reader.ReadByte();
                reader.Skip(3); // reserved
                if (id != parent.Id)
                {
                    throw new IOException("Type id (" + id + ") " + "doesn't match parent id (" + parent.Id + ").");
                }
                var entryCount = reader.ReadInt32();
                if (entryCount != parent.EntryCount)
                {
                    throw new IOException(string.Format("Type entry count ({0}) doesn't match parent entry count ({1})", entryCount, parent.EntryCount));
                }
                var entriesStart = reader.ReadInt32();
                configuration = new Configuration(reader);
                // Data
                var offsets = reader.ReadIntArray(entryCount);
                var dataSize = (Size - entriesStart);
                if ((dataSize % 4) != 0)
                {
                    throw new IOException("Type data size (" + dataSize + ") is not multiple of 4.");
                }
                for (var i = 0; i < entryCount; i++ )
                {
                    if (offsets[i] != NO_ENTRY)
                    {
                        var actualOffset = reader.Position;
                        var instance = EntryInstance.Read(this, reader);
                        parent.GetEntry(i).Add(instance);
                    } 
                }
            }
        protected BaseClassMapping(XmlElement node)
        {
            FCSType = new TypeSpec(node.GetAttribute("FCSType"), TypeSpec.TypeSpecCategories.FCSType);
            ForeignType = new TypeSpec(node.GetAttribute("ForeignType"), TypeSpec.TypeSpecCategories.ForeignType);

            ForeignType.HeaderFile = XmlUtils.GetOptionalAttribute(node, "HeaderFile");
        }
Exemple #5
0
 /// <summary>
 /// This .ctor is handy for message inspectors.
 /// Creates a substitute message for the original one with new values.
 /// Binding-specific context is cloned and headers/correlation data are cloned conditionaly
 /// </summary>
 protected RequestMsg(RequestMsg inspectedOriginal,
                   TypeSpec contract, MethodSpec method, bool oneWay, Guid? instance, 
                   bool cloneHeaders = true, bool cloneCorrelation = true) : this(contract, method, oneWay, instance)
 {
   m_ServerTransport = inspectedOriginal.m_ServerTransport;
   CloneState(inspectedOriginal, cloneHeaders, cloneCorrelation);
 }
        public EnumToBoolMapping(XmlElement element, TypeSpec fcsType)
        {
            enumValue = element.GetAttribute("FCSValue");
            boolMemberName = element.GetAttribute("ForeignMember");
            FCSType = fcsType;

        }
Exemple #7
0
        private static void InitializeTypes(SymbolTableStack symtabstack)
        {
            // int
            IntegerId = symtabstack.CreateInLocal("integer");
            IntegerType = TypeSpec.CreateType(TypeForm.Scalar);
            IntegerType.Identifier = IntegerId;
            IntegerId.Definition = Definition.TYPE;
            IntegerId.Type = IntegerType;

            // real
            RealId = symtabstack.CreateInLocal("real");
            RealType = TypeSpec.CreateType(TypeForm.Scalar);
            RealType.Identifier = RealId;
            RealId.Definition = Definition.TYPE;
            RealId.Type = RealType;

            // boolean
            BooleanId = symtabstack.CreateInLocal("boolean");
            BooleanType = TypeSpec.CreateType(TypeForm.Enumeration);
            BooleanType.Identifier = BooleanId;
            BooleanId.Definition = Definition.TYPE;
            BooleanId.Type = BooleanType;

            // char
            CharId = symtabstack.CreateInLocal("char");
            CharType = TypeSpec.CreateType(TypeForm.Scalar);
            CharType.Identifier = CharId;
            CharId.Definition = Definition.TYPE;
            CharId.Type = CharType;

            //
            UndefinedType = TypeSpec.CreateType(TypeForm.Scalar);
        }
Exemple #8
0
 protected virtual object CreateNestedDelta(object propValue, TypeSpec propValueType, Type propertyType)
 {
     if (propValueType.SerializationMode == TypeSerializationMode.Structured)
         return new ObjectDelta(propValue, propValueType, TypeMapper, this);
     if (propValueType.IsCollection)
         return new CollectionDelta(propValue, propValueType, TypeMapper, this);
     throw new NotImplementedException();
 }
Exemple #9
0
 public PomonaResponse(PomonaQuery query, object entity, HttpStatusCode statusCode)
 {
     if (query == null) throw new ArgumentNullException("query");
     this.entity = entity;
     this.statusCode = statusCode;
     expandedPaths = query.ExpandedPaths;
     resultType = query.ResultType;
 }
Exemple #10
0
 //static .ctor
 static TestContractAClient()
 {
     var t = typeof(NFX.NUnit.Glue.ITestContractA);
      s_ts_CONTRACT = new TypeSpec(t);
      @s_ms_Method1_0 = new MethodSpec(t.GetMethod("Method1", new Type[]{ typeof(@System.@Int32) }));
      @s_ms_Method2_1 = new MethodSpec(t.GetMethod("Method2", new Type[]{ typeof(@System.@Int32) }));
      @s_ms_Sleeper_2 = new MethodSpec(t.GetMethod("Sleeper", new Type[]{ typeof(@System.@Int32) }));
 }
Exemple #11
0
 /// <summary>
 /// Constructs request message from method information and arguments for call invocation. 
 /// This constructor is slower as it uses reflection
 /// </summary>
 protected RequestMsg(MethodInfo method, Guid? instance) : base()
 {
     m_Contract = new TypeSpec(method.DeclaringType);
     m_Method = new MethodSpec(method);
     m_OneWay = Attribute.IsDefined(method, typeof(OneWayAttribute));
     
     m_RemoteInstance = instance;
 }
        public PomonaJsonSerializerTypeEntry(TypeSpec type)
        {
            if (type == null)
                throw new ArgumentNullException(nameof(type));
            this.type = type;

            BuildAcceleratedPropertyWritingAction();
        }
Exemple #13
0
 //static .ctor
 static AuthServiceClient()
 {
     var t = typeof(IAuthService);
     s_ts_CONTRACT = new TypeSpec(t);
     s_ms_CloseSession = new MethodSpec(t.GetMethod("CloseSession", new Type[] { typeof(Guid) }));
     s_ms_CreateSession = new MethodSpec(t.GetMethod("CreateSession", new Type[] { typeof(long) }));
     s_ms_GetSessionUser = new MethodSpec(t.GetMethod("GetSessionUser", new Type[] { typeof(Guid) }));
 }
Exemple #14
0
 protected Delta(object original, TypeSpec type, ITypeMapper typeMapper, Delta parent = null)
 {
     if (original == null) throw new ArgumentNullException("original");
     if (type == null) throw new ArgumentNullException("type");
     if (typeMapper == null) throw new ArgumentNullException("typeMapper");
     Original = original;
     Type = type;
     TypeMapper = typeMapper;
     this.parent = parent;
 }
 public static void Error_InvalidConstantType(TypeSpec t, Location loc, Report Report)
 {
     if (t.IsGenericParameter) {
         Report.Error (1959, loc,
             "Type parameter `{0}' cannot be declared const", TypeManager.CSharpName (t));
     } else {
         Report.Error (283, loc,
             "The type `{0}' cannot be declared const", TypeManager.CSharpName (t));
     }
 }
 public ItemValueDeserializerNode(TypeSpec expectedBaseType,
                                  IDeserializationContext context,
                                  string expandPath = "",
                                  IDeserializerNode parent = null)
 {
     Parent = parent;
     ExpectedBaseType = expectedBaseType;
     Context = context;
     ExpandPath = expandPath;
     this.valueType = expectedBaseType;
 }
Exemple #17
0
        public MemberSpec(string specText, TypeSpec.TypeSpecCategories typeCategory)
        {
            int index = specText.LastIndexOf(' ');
            string[] bits = new string[2];
            bits[0] = specText.Substring(0, index);
            bits[1] = specText.Substring(index + 1);

            Type = new TypeSpec(bits[0], typeCategory);
            Name = bits[1];

        }
Exemple #18
0
 public RouteAction Match(HttpMethod method, PathNodeType nodeType, TypeSpec resourceType)
 {
     switch (nodeType)
     {
         case PathNodeType.Collection:
             return MatchCollectionNodeRequest(method, (ResourceType)resourceType);
         case PathNodeType.Resource:
             if (!MethodInfo.Name.StartsWith(method.ToString()))
                 return null;
             return MatchResourceNodeRequest(method, (ResourceType)resourceType);
     }
     return null;
 }
Exemple #19
0
		/// <summary>
		/// Resolve an IField from its name and a declaring TypeSpec.
		/// </summary>
		/// <param name="declaringType">Declaring TypeSpec</param>
		/// <param name="fieldName">Field name</param>
		/// <returns>IField, or null if none found</returns>
		public IField ResolveField(TypeSpec declaringType, String fieldName)
		{
			TypeDef typeDef = declaringType.ResolveTypeDef();
			if (typeDef == null)
				return null;

			FieldDef fieldDef = typeDef.FindField(fieldName);
			if (fieldDef == null)
				return null;

			MemberRef memberRef = new MemberRefUser(_module, fieldDef.Name, fieldDef.FieldSig, declaringType);
			return this.Importer.Import(memberRef);
		}
Exemple #20
0
        public PomonaResponse(object entity, HttpStatusCode statusCode = HttpStatusCode.OK,
                              string expandedPaths = "",
                              TypeSpec resultType = null,
                              IEnumerable<KeyValuePair<string, string>> responseHeaders = null)
        {
            this.entity = entity;
            this.statusCode = statusCode;
            this.expandedPaths = expandedPaths;
            this.resultType = resultType;

            if (responseHeaders != null)
                this.responseHeaders = responseHeaders.ToList();
        }
Exemple #21
0
 //static .ctor
 static JokeContractClient()
 {
     var t = typeof(@BusinessLogic.@IJokeContract);
      s_ts_CONTRACT = new TypeSpec(t);
      @s_ms_Echo_0 = new MethodSpec(t.GetMethod("Echo", new Type[]{ typeof(@System.@String) }));
      @s_ms_UnsecureEcho_1 = new MethodSpec(t.GetMethod("UnsecureEcho", new Type[]{ typeof(@System.@String) }));
      @s_ms_UnsecEchoMar_2 = new MethodSpec(t.GetMethod("UnsecEchoMar", new Type[]{ typeof(@System.@String) }));
      @s_ms_SimpleWorkAny_3 = new MethodSpec(t.GetMethod("SimpleWorkAny", new Type[]{ typeof(@System.@String), typeof(@System.@Int32), typeof(@System.@Int32), typeof(@System.@Boolean), typeof(@System.@Double) }));
      @s_ms_SimpleWorkMar_4 = new MethodSpec(t.GetMethod("SimpleWorkMar", new Type[]{ typeof(@System.@String), typeof(@System.@Int32), typeof(@System.@Int32), typeof(@System.@Boolean), typeof(@System.@Double) }));
      @s_ms_DBWork_5 = new MethodSpec(t.GetMethod("DBWork", new Type[]{ typeof(@System.@String), typeof(@System.@Int32), typeof(@System.@Int32) }));
      @s_ms_Notify_6 = new MethodSpec(t.GetMethod("Notify", new Type[]{ typeof(@System.@String) }));
      @s_ms_ObjectWork_7 = new MethodSpec(t.GetMethod("ObjectWork", new Type[]{ typeof(@System.@Object) }));
 }
Exemple #22
0
 protected Delta(object original, TypeSpec type, ITypeResolver typeMapper, Delta parent = null)
 {
     if (original == null)
         throw new ArgumentNullException(nameof(original));
     if (type == null)
         throw new ArgumentNullException(nameof(type));
     if (typeMapper == null)
         throw new ArgumentNullException(nameof(typeMapper));
     Original = original;
     Type = type;
     TypeMapper = typeMapper;
     Parent = parent;
 }
Exemple #23
0
        //
        private TypeSpec(string value)
        {
            form = TypeForm.Array;

            TypeSpec indexType = new TypeSpec(TypeForm.Subrange);
            // FIXME: Predefined
            // indexType.SetAttribute(TypeKey.SubrangeBaseType, Predefined.IntegerType);
            indexType.SetAttribute(TypeKey.SubrangeMinValue, 1);
            indexType.SetAttribute(TypeKey.SubrangeMaxValue, value.Length);
            SetAttribute(TypeKey.ArrayIndexType, indexType);
            // FIXME: Predefined
            // SetAttribute(TypeKey.ArrayElementType, Predefined.CharType);
            SetAttribute(TypeKey.ArrayElementCount, value.Length);
        }
        private static bool TryGetJsonWriterMethodForWritingType(TypeSpec type, out MethodInfo method)
        {
            method = null;
            if (type.SerializationMode != TypeSerializationMode.Value)
                return false;

            method = typeof(JsonWriter)
                .GetMethods(BindingFlags.Instance | BindingFlags.Public)
                .Where(x => x.Name == "WriteValue")
                .FirstOrDefault(
                    x => x.GetParameters().Length == 1 && x.GetParameters()[0].ParameterType == type.Type);

            return method != null;
        }
        public EnumToMultiMemberMapping(XmlElement element, TypeSpec parentFCSType, TypeSpec parentForeignType) 
        {
            if (element.GetAttribute("FCSMember").Length > 0)
                FCSSpec = new MemberSpec(element.GetAttribute("FCSMember"), TypeSpec.TypeSpecCategories.FCSType);
            else
                FCSSpec = new MemberSpec(parentFCSType, "");


            foreach (XmlNode subNode in element.SelectNodes(".//x:ValueToForeignBoolMember", GenerationContext.NamespaceManager))
            {
                mappings.Add(new EnumToBoolMapping(subNode as XmlElement, FCSSpec.Type));
            }


        }
Exemple #26
0
 protected PropertySpec(ITypeResolver typeResolver,
                        PropertyInfo propertyInfo,
                        TypeSpec reflectedType)
     : base(typeResolver, propertyInfo)
 {
     if (reflectedType == null)
         throw new ArgumentNullException(nameof(reflectedType));
     ReflectedType = reflectedType;
     this.declaringType = CreateLazy(() => typeResolver.LoadDeclaringType(this));
     this.propertyType = CreateLazy(() => typeResolver.LoadPropertyType(this));
     Flags = typeResolver.LoadPropertyFlags(this);
     this.baseDefinition = CreateLazy(() => typeResolver.LoadBaseDefinition(this));
     this.getter = CreateLazy(() => typeResolver.LoadGetter(this));
     this.setter = CreateLazy(() => typeResolver.LoadSetter(this));
     this.isRequiredForConstructor = CreateLazy(() => ReflectedType.RequiredProperties.Contains(this));
 }
		public override void Error_ValueCannotBeConverted (ResolveContext ec, TypeSpec t, bool expl)
		{
			if (t.IsGenericParameter) {
				ec.Report.Error(403, loc,
					"Cannot convert null to the type parameter `{0}' because it could be a value " +
					"type. Consider using `default ({0})' instead", t.Name);
				return;
			}

			if (TypeSpec.IsValueType (t)) {
				ec.Report.Error(37, loc, "Cannot convert null to `{0}' because it is a value type",
					t.GetSignatureForError ());
				return;
			}

			base.Error_ValueCannotBeConverted (ec, t, expl);
		}
Exemple #28
0
		protected override ParametersCompiled ResolveParameters (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegateType)
		{
			if (!delegateType.IsDelegate)
				return null;

			AParametersCollection d_params = Delegate.GetParameters (delegateType);

			if (HasExplicitParameters) {
				if (!VerifyExplicitParameters (ec, tic, delegateType, d_params))
					return null;

				return Parameters;
			}

			//
			// If L has an implicitly typed parameter list we make implicit parameters explicit
			// Set each parameter of L is given the type of the corresponding parameter in D
			//
			if (!VerifyParameterCompatibility (ec, tic, delegateType, d_params, ec.IsInProbingMode))
				return null;

			TypeSpec [] ptypes = new TypeSpec [Parameters.Count];
			for (int i = 0; i < d_params.Count; i++) {
				// D has no ref or out parameters
				if ((d_params.FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask) != 0)
					return null;

				TypeSpec d_param = d_params.Types [i];

				//
				// When type inference context exists try to apply inferred type arguments
				//
				if (tic != null) {
					d_param = tic.InflateGenericArgument (ec, d_param);
				}

				ptypes [i] = d_param;
				ImplicitLambdaParameter ilp = (ImplicitLambdaParameter) Parameters.FixedParameters [i];
				ilp.SetParameterType (d_param);
				ilp.Resolve (null, i);
			}

			Parameters.Types = ptypes;
			return Parameters;
		}
Exemple #29
0
        public override TypeSpec LoadBaseType(TypeSpec typeSpec)
        {
            if (typeSpec is StructuredType)
            {
                if (Filter.IsIndependentTypeRoot(typeSpec))
                    return null;

                var exposedBaseType = typeSpec.Type.BaseType;

                while (exposedBaseType != null && !Filter.TypeIsMapped(exposedBaseType))
                    exposedBaseType = exposedBaseType.BaseType;

                if (exposedBaseType != null)
                    return FromType(exposedBaseType);
                return null;
            }
            return base.LoadBaseType(typeSpec);
        }
Exemple #30
0
        public object Bind(TypeSpec type = null, object patchedObject = null)
        {
            if (this.deserializedBody == null)
            {
                if (Request.Body == null)
                    throw new InvalidOperationException("No http body to deserialize.");

                if (Method == HttpMethod.Patch)
                {
                    patchedObject = patchedObject
                                    ?? Node.Session.Dispatch(new PomonaContext(Node, executeQueryable : true))
                                           .Entity;
                    if (patchedObject != null)
                        type = TypeMapper.FromType(patchedObject.GetType());
                }

                this.deserializedBody = Deserialize(type as StructuredType, patchedObject);
            }
            return this.deserializedBody;
        }
Exemple #31
0
        protected override Expression ResolveOperatorPredefined(ResolveContext ec, Binary.PredefinedOperator [] operators, bool primitives_only, TypeSpec enum_type)
        {
            Expression e = base.ResolveOperatorPredefined(ec, operators, primitives_only, enum_type);

            if (e == this || enum_type != null)
            {
                return(LiftResult(ec, e));
            }

            //
            // 7.9.9 Equality operators and null
            //
            // The == and != operators permit one operand to be a value of a nullable type and
            // the other to be the null literal, even if no predefined or user-defined operator
            // (in unlifted or lifted form) exists for the operation.
            //
            if (e == null && (Oper & Operator.EqualityMask) != 0)
            {
                if ((IsLeftNullLifted && right_unwrap != null) || (IsRightNullLifted && left_unwrap != null))
                {
                    return(LiftResult(ec, this));
                }
            }

            return(e);
        }
Exemple #32
0
 public NullableType(TypeSpec type, Location loc)
 {
     this.underlying = type;
     this.loc        = loc;
 }
Exemple #33
0
        Expression ConvertExpression(ResolveContext ec)
        {
            // TODO: ImplicitConversionExists should take care of this
            if (left.eclass == ExprClass.MethodGroup)
            {
                return(null);
            }

            TypeSpec ltype = left.Type;

            //
            // If left is a nullable type and an implicit conversion exists from right to underlying type of left,
            // the result is underlying type of left
            //
            if (ltype.IsNullableType)
            {
                unwrap = Unwrap.Create(left, false);
                if (unwrap == null)
                {
                    return(null);
                }

                //
                // Reduce (left ?? null) to left
                //
                if (right.IsNull)
                {
                    return(ReducedExpression.Create(left, this));
                }

                if (Convert.ImplicitConversionExists(ec, right, unwrap.Type))
                {
                    left  = unwrap;
                    ltype = left.Type;

                    //
                    // If right is a dynamic expression, the result type is dynamic
                    //
                    if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
                    {
                        type = right.Type;

                        // Need to box underlying value type
                        left = Convert.ImplicitBoxingConversion(left, ltype, type);
                        return(this);
                    }

                    right = Convert.ImplicitConversion(ec, right, ltype, loc);
                    type  = ltype;
                    return(this);
                }
            }
            else if (TypeSpec.IsReferenceType(ltype))
            {
                if (Convert.ImplicitConversionExists(ec, right, ltype))
                {
                    //
                    // If right is a dynamic expression, the result type is dynamic
                    //
                    if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
                    {
                        type = right.Type;
                        return(this);
                    }

                    //
                    // Reduce ("foo" ?? expr) to expression
                    //
                    Constant lc = left as Constant;
                    if (lc != null && !lc.IsDefaultValue)
                    {
                        return(ReducedExpression.Create(lc, this));
                    }

                    //
                    // Reduce (left ?? null) to left OR (null-constant ?? right) to right
                    //
                    if (right.IsNull || lc != null)
                    {
                        return(ReducedExpression.Create(lc != null ? right : left, this));
                    }

                    right = Convert.ImplicitConversion(ec, right, ltype, loc);
                    type  = ltype;
                    return(this);
                }

                //
                // Special case null ?? null
                //
                if (ltype == right.Type)
                {
                    type = ltype;
                    return(this);
                }
            }
            else
            {
                return(null);
            }

            TypeSpec rtype = right.Type;

            if (!Convert.ImplicitConversionExists(ec, unwrap != null ? unwrap : left, rtype) || right.eclass == ExprClass.MethodGroup)
            {
                return(null);
            }

            //
            // Reduce (null ?? right) to right
            //
            if (left.IsNull)
            {
                return(ReducedExpression.Create(right, this).Resolve(ec));
            }

            left = Convert.ImplicitConversion(ec, unwrap != null ? unwrap : left, rtype, loc);
            type = rtype;
            return(this);
        }
Exemple #34
0
 public static TypeSpec MakeType(ModuleContainer module, TypeSpec underlyingType)
 {
     return(module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType(module,
                                                                     new[] { underlyingType }));
 }
 public RequestMsg_IZoneHostReplicator_PostDynamicHostInfo(TypeSpec contract, MethodSpec method, bool oneWay, Guid?instance)
     : base(contract, method, oneWay, instance)
 {
 }
Exemple #36
0
 SLParameter ToParameterToCSharpTypes(SLImportModules modules, ParameterItem p, int index)
 {
     return(new SLParameter(p.PublicName, p.PrivateName, MapTypeSimplified(modules, p.TypeSpec),
                            p.IsInOut && TypeSpec.IsBuiltInValueType(p.TypeSpec) ? SLParameterKind.InOut : SLParameterKind.None));
 }
Exemple #37
0
 public int CreateMethodSignature(TypeSpec rettype, TypeSpec[] ps, bool has_this = false, TypeSpec[] gmparams = null)
 {
     return(CreateMethodSignature(b, rettype, ps, has_this, gmparams));
 }
Exemple #38
0
 public static MethodSpec GetValue(TypeSpec nullableType)
 {
     return((MethodSpec)MemberCache.FindMember(nullableType,
                                               MemberFilter.Method("get_Value", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None));
 }
Exemple #39
0
 public static MethodSpec GetConstructor(TypeSpec nullableType)
 {
     return((MethodSpec)MemberCache.FindMember(nullableType,
                                               MemberFilter.Constructor(ParametersCompiled.CreateFullyResolved(GetUnderlyingType(nullableType))), BindingRestriction.DeclaredOnly));
 }
 public void BeginCatchBlock(TypeSpec type)
 {
     ig.BeginCatchBlock(type.GetMetaInfo());
 }
Exemple #41
0
 public static TypeSpec GetUnderlyingType(TypeSpec nullableType)
 {
     return(((InflatedTypeSpec)nullableType).TypeArguments[0]);
 }
        //
        // The stack contains the pointer and the value of type `type'
        //
        public void EmitStoreFromPtr(TypeSpec type)
        {
            if (type.IsEnum)
            {
                type = EnumSpec.GetUnderlyingType(type);
            }

            switch (type.BuiltinType)
            {
            case BuiltinTypeSpec.Type.Int:
            case BuiltinTypeSpec.Type.UInt:
                ig.Emit(OpCodes.Stind_I4);
                return;

            case BuiltinTypeSpec.Type.Long:
            case BuiltinTypeSpec.Type.ULong:
                ig.Emit(OpCodes.Stind_I8);
                return;

            case BuiltinTypeSpec.Type.Char:
            case BuiltinTypeSpec.Type.Short:
            case BuiltinTypeSpec.Type.UShort:
                ig.Emit(OpCodes.Stind_I2);
                return;

            case BuiltinTypeSpec.Type.Float:
                ig.Emit(OpCodes.Stind_R4);
                return;

            case BuiltinTypeSpec.Type.Double:
                ig.Emit(OpCodes.Stind_R8);
                return;

            case BuiltinTypeSpec.Type.Byte:
            case BuiltinTypeSpec.Type.SByte:
            case BuiltinTypeSpec.Type.Bool:
                ig.Emit(OpCodes.Stind_I1);
                return;

            case BuiltinTypeSpec.Type.IntPtr:
                ig.Emit(OpCodes.Stind_I);
                return;
            }

            switch (type.Kind)
            {
            case MemberKind.Struct:
            case MemberKind.TypeParameter:
                if (IsAnonymousStoreyMutateRequired)
                {
                    type = CurrentAnonymousMethod.Storey.Mutator.Mutate(type);
                }

                ig.Emit(OpCodes.Stobj, type.GetMetaInfo());
                break;

            default:
                ig.Emit(OpCodes.Stind_Ref);
                break;
            }
        }
        public override Type?GetType(string className, bool throwOnError, bool ignoreCase)
        {
            if (className == null)
            {
                throw new ArgumentNullException(nameof(className));
            }
            if (className.Length == 0)
            {
                throw new ArgumentException(SR.Argument_EmptyName, nameof(className));
            }

            TypeBuilder?result = null;

            if (types == null && throwOnError)
            {
                throw new TypeLoadException(className);
            }

            TypeSpec ts = TypeSpec.Parse(className);

            if (!ignoreCase)
            {
                ITypeName displayNestedName = ts.TypeNameWithoutModifiers();
                name_cache.TryGetValue(displayNestedName, out result);
            }
            else
            {
                if (types != null)
                {
                    result = search_in_array(types, num_types, ts.Name !);
                }
                if (!ts.IsNested && result != null)
                {
                    result = GetMaybeNested(result, ts.Nested);
                }
            }
            if ((result == null) && throwOnError)
            {
                throw new TypeLoadException(className);
            }
            if (result != null && (ts.HasModifiers || ts.IsByRef))
            {
                Type mt = result;
                if (result is TypeBuilder)
                {
                    var tb = result as TypeBuilder;
                    if (tb.is_created)
                    {
                        mt = tb.CreateType() !;
                    }
                }
                foreach (IModifierSpec mod in ts.Modifiers)
                {
                    if (mod is PointerSpec)
                    {
                        mt = mt.MakePointerType() !;
                    }
                    else if (mod is IArraySpec)
                    {
                        var spec = (mod as IArraySpec) !;
                        if (spec.IsBound)
                        {
                            return(null);
                        }
                        if (spec.Rank == 1)
                        {
                            mt = mt.MakeArrayType();
                        }
                        else
                        {
                            mt = mt.MakeArrayType(spec.Rank);
                        }
                    }
                }
                if (ts.IsByRef)
                {
                    mt = mt.MakeByRefType();
                }
                result = mt as TypeBuilder;
                if (result == null)
                {
                    return(mt);
                }
            }
            if (result != null && result.is_created)
            {
                return(result.CreateType());
            }
            else
            {
                return(result);
            }
        }
Exemple #44
0
 protected override void Error_TypeDoesNotContainDefinition(ResolveContext ec, TypeSpec type, string name)
 {
     ec.Report.Error(1935, loc, "An implementation of `{0}' query expression pattern could not be found. " +
                     "Are you missing `System.Linq' using directive or `System.Core.dll' assembly reference?",
                     name);
 }
Exemple #45
0
        void GatherGenerics(TypeMapper typeMapper, FunctionDeclaration func, SLImportModules modules, TypeSpec type,
                            SLGenericTypeDeclarationCollection genericDecl, Dictionary <string, List <BaseConstraint> > redundantConstraints)
        {
            if (!func.IsTypeSpecGeneric(type))
            {
                return;
            }

            if (type.ContainsGenericParameters)
            {
                var entity = typeMapper.GetEntityForTypeSpec(type);
                if (entity != null)
                {
                    for (int i = 0; i < entity.Type.Generics.Count; i++)
                    {
                        var genDecl             = entity.Type.Generics [i];
                        var originalGenTypeSpec = type.GenericParameters [i];
                        if (originalGenTypeSpec is NamedTypeSpec named)
                        {
                            var depthIndex = func.GetGenericDepthAndIndex(originalGenTypeSpec);
                            if (depthIndex.Item1 < 0 || depthIndex.Item2 < 0)
                            {
                                continue;
                            }
                            var genRef     = new SLGenericReferenceType(depthIndex.Item1, depthIndex.Item2);
                            var genRefName = genRef.Name;
                            List <BaseConstraint> constList = null;
                            if (!redundantConstraints.TryGetValue(genRefName, out constList))
                            {
                                constList = new List <BaseConstraint> ();
                                redundantConstraints.Add(genRefName, constList);
                            }
                            constList.AddRange(genDecl.Constraints);
                        }
                        else if (originalGenTypeSpec is ClosureTypeSpec closure)
                        {
                            GatherGenerics(typeMapper, func, modules, closure.Arguments, genericDecl, redundantConstraints);
                            GatherGenerics(typeMapper, func, modules, closure.ReturnType, genericDecl, redundantConstraints);
                        }
                        else if (originalGenTypeSpec is TupleTypeSpec tuple)
                        {
                            foreach (var tupleSpec in tuple.Elements)
                            {
                                GatherGenerics(typeMapper, func, modules, tupleSpec, genericDecl, redundantConstraints);
                            }
                        }
                    }
                }
                foreach (var subType in type.GenericParameters)
                {
                    GatherGenerics(typeMapper, func, modules, subType, genericDecl, redundantConstraints);
                }
            }
            else
            {
                if (type is NamedTypeSpec named)
                {
                    var depthIndex = func.GetGenericDepthAndIndex(type);
                    var gd         = func.GetGeneric(depthIndex.Item1, depthIndex.Item2);
                    var genRef     = new SLGenericReferenceType(depthIndex.Item1, depthIndex.Item2);
                    var sldecl     = new SLGenericTypeDeclaration(new SLIdentifier(genRef.Name));
#if SWIFT4
                    if (depthIndex.Item1 >= func.GetMaxDepth())
                    {
                        sldecl.Constraints.AddRange(gd.Constraints.Select(baseConstraint =>
                                                                          MethodWrapping.ToSLGenericConstraint(func, baseConstraint, genRef.ToString())
                                                                          ));
                    }
#else
                    sldecl.Constraints.AddRange(gd.Constraints.Select(bc => {
                        InheritanceConstraint inh = bc as InheritanceConstraint;
                        if (inh == null)
                        {
                            throw new CompilerException("Equality constraints not supported (yet)");
                        }
                        return(new SLGenericConstraint(true, new SLSimpleType(genRef.Name), parent.TypeSpecMapper.MapType(func, modules, inh.InheritsTypeSpec)));
                    }));
#endif
                    genericDecl.Add(sldecl);
                }
                else if (type is ClosureTypeSpec closure)
                {
                    GatherGenerics(typeMapper, func, modules, closure.Arguments, genericDecl, redundantConstraints);
                    GatherGenerics(typeMapper, func, modules, closure.ReturnType, genericDecl, redundantConstraints);
                }
                else if (type is TupleTypeSpec tuple)
                {
                    foreach (var tupleSpec in tuple.Elements)
                    {
                        GatherGenerics(typeMapper, func, modules, tupleSpec, genericDecl, redundantConstraints);
                    }
                }
            }
        }
Exemple #46
0
 public Lifted(Expression expr, Expression unwrap, TypeSpec type)
     : this(expr, unwrap as Unwrap, type)
 {
 }
Exemple #47
0
        void GatherGenerics(TypeMapper typeMapper, FunctionDeclaration func, SLImportModules modules, TypeSpec type,
                            SLGenericTypeDeclarationCollection genericDeclations)
        {
            var redundantConstraints = new Dictionary <string, List <BaseConstraint> > ();

            GatherGenerics(typeMapper, func, modules, type, genericDeclations, redundantConstraints);

            // In the process of gathering generics, there may be generic types with
            // constraints that are redundant. In the process of gathering the generics, I
            // collect all the generic reference types that have constraints that would be
            // considered redundant.
            // After gathering, all constraints are looked up and if they're redundant, they get removed.

            foreach (var generic in genericDeclations)
            {
                var genericName = generic.Name.Name;
                List <BaseConstraint> forbiddenList = null;
                if (!redundantConstraints.TryGetValue(genericName, out forbiddenList))
                {
                    continue;
                }
                for (int i = generic.Constraints.Count - 1; i >= 0; i--)
                {
                    var candidateConstraint = generic.Constraints [i];
                    foreach (var forbidden in forbiddenList)
                    {
                        var forbiddenInherit = forbidden as InheritanceConstraint;
                        if (candidateConstraint.IsInheritance && forbidden != null)
                        {
                            var candidateString        = candidateConstraint.SecondType.ToString();
                            var forbiddenNamedTypeSpec = forbiddenInherit.InheritsTypeSpec as NamedTypeSpec;
                            if (forbiddenNamedTypeSpec == null)
                            {
                                continue;
                            }
                            var verbottenString = forbiddenNamedTypeSpec.NameWithoutModule;
                            if (candidateString == verbottenString)
                            {
                                generic.Constraints.RemoveAt(i);
                                break;
                            }
                        }
                    }
                }
            }
        }
Exemple #48
0
 public static Constant Create(TypeSpec nullable, Location loc)
 {
     return(new LiftedNull(nullable, loc));
 }
Exemple #49
0
        private void CreateTypeSignature(List <byte> tmp, TypeSpec ts)
        {
            if (ts == null)
            {
                tmp.Add(0x01);
                return;
            }

            switch (ts.stype)
            {
            case TypeSpec.SpecialType.None:
                int stype = -1;
                if (ts.m.simple_type_idx != null)
                {
                    stype = ts.m.simple_type_idx[ts.tdrow];
                }
                if (stype == -1)
                {
                    if (ts.gtparams != null)
                    {
                        tmp.Add(0x15);
                    }

                    int val = 0;
                    if (ts.IsValueType)
                    {
                        val = 0x11;
                    }
                    else
                    {
                        val = 0x12;
                    }

                    val |= 0x80;
                    tmp.Add((byte)val);


                    CompressInt(tmp, ts.m.AssemblyName.Length);
                    foreach (var ch in ts.m.AssemblyName)
                    {
                        tmp.Add((byte)ch);
                    }

                    // create typedef pointer
                    var tok = corlib.MakeCodedIndexEntry(
                        tid_TypeDef,
                        ts.tdrow,
                        TypeDefOrRef);
                    CompressInt(tmp, tok);

                    if (ts.gtparams != null)
                    {
                        CompressInt(tmp, ts.gtparams.Length);
                        foreach (var gtp in ts.gtparams)
                        {
                            CreateTypeSignature(tmp, gtp);
                        }
                    }
                }
                else
                {
                    tmp.Add((byte)stype);
                }
                break;

            case TypeSpec.SpecialType.Ptr:
                tmp.Add(0x0f);
                CreateTypeSignature(tmp, ts.other);
                break;

            case TypeSpec.SpecialType.MPtr:
                tmp.Add(0x10);
                CreateTypeSignature(tmp, ts.other);
                break;

            case TypeSpec.SpecialType.SzArray:
                tmp.Add(0x1d);
                CreateTypeSignature(tmp, ts.other);
                break;

            default:
                throw new NotImplementedException();
            }
        }
Exemple #50
0
 private LiftedNull(TypeSpec nullable_type, Location loc)
     : base(nullable_type, loc)
 {
     eclass = ExprClass.Value;
 }
Exemple #51
0
        protected override Expression DoResolve(ResolveContext rc)
        {
            var sn = expr as SimpleName;
            const ResolveFlags flags = ResolveFlags.VariableOrValue | ResolveFlags.Type;

            if (sn != null)
            {
                expr = sn.LookupNameExpression(rc, MemberLookupRestrictions.ReadAccess | MemberLookupRestrictions.ExactArity);

                //
                // Resolve expression which does have type set as we need expression type
                // with disable flow analysis as we don't know whether left side expression
                // is used as variable or type
                //
                if (expr is VariableReference || expr is ConstantExpr || expr is Linq.TransparentMemberAccess)
                {
                    expr = expr.Resolve(rc);
                }
                else if (expr is TypeParameterExpr)
                {
                    expr.Error_UnexpectedKind(rc, flags, sn.Location);
                    expr = null;
                }
            }
            else
            {
                expr = expr.Resolve(rc, flags);
            }

            if (expr == null)
            {
                return(null);
            }

            TypeSpec expr_type = expr.Type;

            if (expr_type.IsPointer || expr_type.Kind == MemberKind.Void || expr_type == InternalType.NullLiteral || expr_type == InternalType.AnonymousMethod)
            {
                expr.Error_OperatorCannotBeApplied(rc, loc, ".", expr_type);
                return(null);
            }

            if (targs != null)
            {
                if (!targs.Resolve(rc, true))
                {
                    return(null);
                }
            }

            var results = new List <string> ();
            var nexpr   = expr as NamespaceExpression;

            if (nexpr != null)
            {
                string namespaced_partial;

                if (partial_name == null)
                {
                    namespaced_partial = nexpr.Namespace.Name;
                }
                else
                {
                    namespaced_partial = nexpr.Namespace.Name + "." + partial_name;
                }

                rc.CurrentMemberDefinition.GetCompletionStartingWith(namespaced_partial, results);
                if (partial_name != null)
                {
                    results = results.Select(l => l.Substring(partial_name.Length)).ToList();
                }
            }
            else
            {
                var r = MemberCache.GetCompletitionMembers(rc, expr_type, partial_name).Select(l => l.Name);
                AppendResults(results, partial_name, r);
            }

            throw new CompletionResult(partial_name == null ? "" : partial_name, results.Distinct().ToArray());
        }
Exemple #52
0
 private Wrap(Expression expr, TypeSpec type)
     : base(expr, type)
 {
     eclass = ExprClass.Value;
 }
Exemple #53
0
        Expression ConvertExpression(ResolveContext ec)
        {
            // TODO: ImplicitConversionExists should take care of this
            if (left.eclass == ExprClass.MethodGroup)
            {
                return(null);
            }

            TypeSpec ltype = left.Type;

            //
            // If left is a nullable type and an implicit conversion exists from right to underlying type of left,
            // the result is underlying type of left
            //
            if (ltype.IsNullableType)
            {
                unwrap = Unwrap.Create(left, false);
                if (unwrap == null)
                {
                    return(null);
                }

                //
                // Reduce (left ?? null) to left
                //
                if (right.IsNull)
                {
                    return(ReducedExpression.Create(left, this));
                }

                Expression conv;
                if (right.Type.IsNullableType)
                {
                    conv = right.Type == ltype ? right : Convert.ImplicitNulableConversion(ec, right, ltype);
                    if (conv != null)
                    {
                        right = conv;
                        type  = ltype;
                        return(this);
                    }
                }
                else
                {
                    conv = Convert.ImplicitConversion(ec, right, unwrap.Type, loc);
                    if (conv != null)
                    {
                        left  = unwrap;
                        ltype = left.Type;

                        //
                        // If right is a dynamic expression, the result type is dynamic
                        //
                        if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
                        {
                            type = right.Type;

                            // Need to box underlying value type
                            left = Convert.ImplicitBoxingConversion(left, ltype, type);
                            return(this);
                        }

                        right = conv;
                        type  = ltype;
                        return(this);
                    }
                }
            }
            else if (TypeSpec.IsReferenceType(ltype))
            {
                if (Convert.ImplicitConversionExists(ec, right, ltype))
                {
                    //
                    // If right is a dynamic expression, the result type is dynamic
                    //
                    if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
                    {
                        type = right.Type;
                        return(this);
                    }

                    //
                    // Reduce ("foo" ?? expr) to expression
                    //
                    Constant lc = left as Constant;
                    if (lc != null && !lc.IsDefaultValue)
                    {
                        return(ReducedExpression.Create(lc, this, false));
                    }

                    //
                    // Reduce (left ?? null) to left OR (null-constant ?? right) to right
                    //
                    if (right.IsNull || lc != null)
                    {
                        //
                        // Special case null ?? null
                        //
                        if (right is NullLiteral && ltype == right.Type)
                        {
                            return(null);
                        }

                        return(ReducedExpression.Create(lc != null ? right : left, this, false));
                    }

                    right = Convert.ImplicitConversion(ec, right, ltype, loc);
                    type  = ltype;
                    return(this);
                }
            }
            else if (ltype == InternalType.ThrowExpr)
            {
                //
                // LAMESPEC: I am not really sure what's point of allowing throw on left side
                //
                return(ReducedExpression.Create(right, this, false).Resolve(ec));
            }
            else
            {
                return(null);
            }

            TypeSpec rtype = right.Type;

            if (!Convert.ImplicitConversionExists(ec, unwrap ?? left, rtype) || right.eclass == ExprClass.MethodGroup)
            {
                return(null);
            }

            //
            // Reduce (null ?? right) to right
            //
            if (left.IsNull)
            {
                return(ReducedExpression.Create(right, this, false).Resolve(ec));
            }

            left = Convert.ImplicitConversion(ec, unwrap ?? left, rtype, loc);
            user_conversion_left = left is UserCast;
            type = rtype;
            return(this);
        }
Exemple #54
0
 public static TypeSpec GetEnumUnderlyingType(ModuleContainer module, TypeSpec nullableEnum)
 {
     return(MakeType(module, EnumSpec.GetUnderlyingType(GetUnderlyingType(nullableEnum))));
 }