public IObjectContext CreateForSerialization(IMemberContext sourceMember, object source, IAdviceRequester adviceRequester)
 {
     return Factories
         .Select(f => f.CreateForSerialization(sourceMember, source, adviceRequester))
         .Where(d => d != null)
         .FirstOrDefault();
 }
 public Type GetActualType(XObject source, IMemberContext target, IAdviceRequester adviceRequester)
 {
     return Converters
             .Select(c => c.GetActualType(source, target, adviceRequester))
             .Where(t => t != null)
             .FirstOrDefault();
 }
        public bool Serialize(IMemberContext source, XObject target, IAdviceRequester adviceRequester)
        {
            if (source == null)
                throw new ArgumentNullException("source");
            if (target.NodeType != XmlNodeType.Element)
                throw new ArgumentException("Parameter must be an XML element.", "target");

            var elem = (XElement)target;

            IObjectContext sourceObject = source.GetValue();

            if (sourceObject == null || sourceObject.GetObject() == null)
            {
                if (_isNullableStrategy.IsNullable(source, elem, adviceRequester))
                {
                    elem.Add(Constants.XsiNilAttribute);
                    return true;
                }

                return false;
            }

            List<IMapping<IMemberContext, XObject>> mappings = _mapper.MapForSerialization(source, elem, adviceRequester)
                .ToList();
            if (mappings == null)
                throw new ArgumentException("Unable to map source '" + source + "' and target '" + target + "'.");

            SerializeRecursively(elem, mappings, adviceRequester);

            return true;
        }
 public IDeserializer Select(XObject source, IMemberContext target, IAdviceRequester adviceRequester)
 {
     return Selectors
             .Select(s => s.Select(source, target, adviceRequester))
             .Where(d => d != null)
             .FirstOrDefault();
 }
        public ISerializer Select(IMemberContext source, XObject target, IAdviceRequester adviceRequester)
        {
            if (target.NodeType != XmlNodeType.Element)
                return null;

            return _serializer;
        }
Esempio n. 6
0
		// TODO: Replace IMemberContext with MemberCore
		public EmitContext (IMemberContext rc, ILGenerator ig, TypeSpec return_type)
		{
			this.MemberContext = rc;
			this.ig = ig;

			this.return_type = return_type;
		}
        public void Deserialize(XObject source, IMemberContext target, IAdviceRequester adviceRequester)
        {
            if (source == null)
                return;

            if (source.NodeType != XmlNodeType.Element)
                throw new ArgumentException("Parameter must be an XML element.", "source");

            if (_log.IsDebugEnabled)
                _log.Debug("Deserializing " + source.ToFriendlyName() + " into " + target + ".");

            var elem = (XElement)source;

            Type targetType = _typeConverter.GetActualType(source, target, adviceRequester);
            if (targetType == null)
                throw new ArgumentException("Unable to get target type for target '" + target + "'.");

            IObjectContext targetObject = _objectContextFactory.CreateForDeserialization(target, targetType, adviceRequester);
            if (targetObject == null)
                throw new ArgumentException("Unable to create target object for target '" + target + "'.");

            target.SetValue(targetObject);

            List<IMapping<XObject, IMemberContext>> mappings = _mapper.MapForDeserialization(elem, target, adviceRequester)
                .ToList();
            if (mappings == null)
                throw new ArgumentException("Unable to map source '" + source + "' and target '" + target + "'.");

            DeserializeRecursively(mappings, adviceRequester);

            target.CommitChanges();
        }
 public IObjectContext CreateForDeserialization(IMemberContext targetMember, Type targetType, IAdviceRequester adviceRequester)
 {
     return Factories
         .Select(f => f.CreateForDeserialization(targetMember, targetType, adviceRequester))
         .Where(d => d != null)
         .FirstOrDefault();
 }
        private static IMapping<IMemberContext, XObject> CreateMappingForSerialization(IMemberContext member, XElement target)
        {
            var targetTypeAndName = GetTargetTypeAndName(member);

            XObject xobj;
            bool addTargetToParent = true;
            switch (targetTypeAndName.Key)
            {
                case XmlNodeType.Element:
                    if (!member.ContractType.IsSubTypeOf<IXmlSerializable>() && member.ContractType.IsCollectionType() && HasXmlElementAttribute(member) || HasXmlTextAttribute(member))
                    {
                        xobj = target;
                        addTargetToParent = false;
                    }
                    else
                        xobj = new XElement(targetTypeAndName.Value);
                    break;
                case XmlNodeType.Attribute:
                    xobj = new XAttribute(targetTypeAndName.Value, string.Empty);
                    break;
                default:
                    throw new ArgumentOutOfRangeException("Mapped to an unknown node type: " + targetTypeAndName.Key + ".");
            }

            return new Mapping<IMemberContext, XObject>(member, xobj, addTargetToParent);
        }
        public IEnumerable<IMapping<XObject, IMemberContext>> MapForDeserialization(XElement source, IMemberContext target, IAdviceRequester adviceRequester)
        {
            if (source == null)
                throw new ArgumentNullException("source");
            if (target == null)
                throw new ArgumentNullException("target");

            var targetObject = target.GetValue();
            foreach (var member in targetObject.Members.Where(m => !m.Attributes.OfType<XmlIgnoreAttribute>().Any()))
            {
                var sourceType = GetSourceTypeAndPotentialNames(member);

                switch (sourceType.Key)
                {
                    case XmlNodeType.Element:
                        foreach (var mapping in GetMappingsFromElement(sourceType.Value, source, targetObject, member, adviceRequester))
                            yield return mapping;
                        break;
                    case XmlNodeType.Attribute:
                        yield return GetMappingFromAttribute(sourceType.Value, source, member);
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }
            }
        }
        protected virtual IDeserializer Select(XObject source, IMemberContext target, Type type, IAdviceRequester adviceRequester)
        {
            var typeCode = Type.GetTypeCode(type);

            switch (typeCode)
            {
                case TypeCode.Empty:
                case TypeCode.DBNull:
                    return null;
                case TypeCode.Object:
                    if (target.ContractType == typeof(TimeSpan))
                        break;
                    if (target.ContractType == typeof(string))
                        break;
                    if (target.ContractType.IsNullable())
                        break;

                    return null;
            }

            if (source == null)
                return GetDeserializer(type);

            if (source.NodeType == XmlNodeType.Element && !((XElement)source).HasElements)
                return GetDeserializer(type);

            if (source.NodeType == XmlNodeType.Attribute)
                return GetDeserializer(type);

            return null;
        }
        public override IDeserializer Select(XObject source, IMemberContext target, IAdviceRequester adviceRequester)
        {
            var contractTypeFromAttr = GetContractTypeFromAttributes(source, target);
            if (contractTypeFromAttr == null)
                return null;

            return Select(source, target, contractTypeFromAttr, adviceRequester);
        }
        private static Type GetActualTypeFromXmlElementAttribute(XElement source, IMemberContext target)
        {
            if (source == null)
                return null;

            return GetTypeFromXmlElementAttributeWithMatchingName(source, target)
                   ?? GetTypeFromXmlElementAttributeWithoutName(target);
        }
        public IObjectContext CreateForSerialization(IMemberContext sourceMember, object source, IAdviceRequester adviceRequester)
        {
            if (source == null)
                return null;

            ObjectContextInfo contextInfo = GetContextInfo(source.GetType(), adviceRequester);

            return contextInfo.CreateFor(source);
        }
Esempio n. 15
0
		public bool ResolveType(IMemberContext mc, TypeSpec defaultType)
		{
			if (TypeExpression != null)
				this.Type = TypeExpression.ResolveAsType (mc);
			else
				this.Type = defaultType;

			return this.Type != null;
		}
 public MultipleMatchesAdviceRequestedEventArgs(XElement source, IObjectContext targetOwner, IMemberContext target, IEnumerable<XObject> matches, XObject selectedMatch)
     : base(CommonAdviceTypes.MultipleMatches)
 {
     Source = source;
     TargetOwner = targetOwner;
     Target = target;
     Matches = (matches ?? Enumerable.Empty<XObject>()).ToList();
     SelectedMatch = selectedMatch;
 }
Esempio n. 17
0
		public override TypeExpr ResolveAsType (IMemberContext ec)
		{
			var type = ec.Module.PredefinedTypes.Nullable.Resolve ();
			if (type == null)
				return null;

			TypeArguments args = new TypeArguments (underlying);
			GenericTypeExpr ctype = new GenericTypeExpr (type, args, loc);
			return ctype.ResolveAsType (ec);
		}
Esempio n. 18
0
		protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
		{
			var type = ec.Module.PredefinedTypes.Nullable.Resolve (loc);
			if (type == null)
				return null;

			TypeArguments args = new TypeArguments (underlying);
			GenericTypeExpr ctype = new GenericTypeExpr (type, args, loc);
			return ctype.ResolveAsTypeTerminal (ec, false);
		}
 private static Type GetTypeFromXmlAttributeAttributeWithoutName(IMemberContext target)
 {
     return target.Attributes
             .OfType<XmlAttributeAttribute>()
             .Where(a => string.IsNullOrWhiteSpace(a.AttributeName))
             .Where(a => a.Type != null)
             .Where(a => target.ContractType.IsAssignableFrom(a.Type))
             .Select(a => a.Type)
             .FirstOrDefault();
 }
        public IObjectContext CreateForDeserialization(IMemberContext targetMember, Type targetType, IAdviceRequester adviceRequester)
        {
            ObjectContextInfo contextInfo = GetContextInfo(targetType, adviceRequester);

            object target = _instantiator.Create(targetType, adviceRequester);
            if (target == null)
                throw new ArgumentException("Unable to create instance of '" + targetType + "' for member '" + targetMember + "'.");

            return contextInfo.CreateFor(target);
        }
 private static Type GetTypeFromXmlArrayItemAttributeWithMatchingName(XElement source, IMemberContext target)
 {
     return target.Attributes
             .OfType<XmlArrayItemAttribute>()
             .Where(a => !string.IsNullOrWhiteSpace(a.ElementName))
             .Where(a => a.ElementName == source.Name)
             .Where(a => a.Type != null)
             .Where(a => target.ContractType.IsAssignableFrom(a.Type))
             .Select(a => a.Type)
             .FirstOrDefault();
 }
        public bool Serialize(IMemberContext source, XObject target, IAdviceRequester adviceRequester)
        {
            if (source == null)
                throw new ArgumentNullException("source");

            var sourceObject = source.GetValue().GetObject();

            if (target.NodeType != XmlNodeType.Element)
                throw new ArgumentException("Parameter must be an XML element.", "source");

            var elem = (XElement)target;

            var xmlSerializable = (IXmlSerializable)sourceObject;

            var memoryStream = new MemoryStream();

            var xmlWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

            xmlWriter.WriteStartElement(elem.Name.LocalName);
            xmlWriter.WriteAttributeString("xmlns", "xsi", null, Constants.XmlSchemaInstanceNamespaceAttribute.Value);
            xmlWriter.WriteAttributeString("xmlns", "xsd", null, Constants.XmlSchemaNamespaceAttribute.Value);
            xmlSerializable.WriteXml(xmlWriter);
            xmlWriter.WriteEndElement();
            xmlWriter.Flush();
            memoryStream.Position = 0;

            var tempTarget = XElement.Load(memoryStream);

            if (tempTarget.HasElements)
                foreach (var element in tempTarget.Elements())
                    elem.Add(element);
            else
                elem.SetValue(tempTarget.Value);

            foreach (var attribute in tempTarget.Attributes())
            {
                if (attribute.Name == Constants.XmlSchemaNamespaceAttribute.Name || attribute.Name == Constants.XmlSchemaInstanceNamespaceAttribute.Name)
                    continue;
                elem.Add(attribute);
            }

            foreach (var childElem in elem.Elements())
            {
                var xmlnsXsiAttr = childElem.Attribute(Constants.XmlSchemaInstanceNamespaceAttribute.Name);
                if (xmlnsXsiAttr != null)
                    xmlnsXsiAttr.Remove();

                var xmlnsXsdAttr = childElem.Attribute(Constants.XmlSchemaNamespaceAttribute.Name);
                if (xmlnsXsdAttr != null)
                    xmlnsXsdAttr.Remove();
            }

            return true;
        }
        private static Type GetContractTypeFromXmlElementAttributes(XObject source, IMemberContext target)
        {
            var elem = source as XElement;
            if (elem == null)
                return null;

            return (from attr in target.Attributes.OfType<XmlElementAttribute>()
                    where attr.Type != null
                    where attr.ElementName == elem.Name
                    select attr.Type).FirstOrDefault();
        }
Esempio n. 24
0
		protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
		{
			if (TypeManager.generic_nullable_type == null) {
				TypeManager.generic_nullable_type = TypeManager.CoreLookupType (ec.Compiler,
					"System", "Nullable", 1, MemberKind.Struct, true);
			}

			TypeArguments args = new TypeArguments (underlying);
			GenericTypeExpr ctype = new GenericTypeExpr (TypeManager.generic_nullable_type, args, loc);
			return ctype.ResolveAsTypeTerminal (ec, false);
		}
Esempio n. 25
0
		public BlockContext (IMemberContext mc, ExplicitBlock block, TypeSpec returnType)
			: base (mc)
		{
			if (returnType == null)
				throw new ArgumentNullException ("returnType");

			this.return_type = returnType;

			// TODO: check for null value
			CurrentBlock = block;
		}
        public IDeserializer Select(XObject source, IMemberContext target, IAdviceRequester adviceRequester)
        {
            Type actualType = _typeConverter.GetActualType(source, target, adviceRequester);
            if (actualType == null)
                return null;

            if (_log.IsDebugEnabled)
                _log.Debug("Selected collection deserialization for source '" + source.ToFriendlyName() + "' and target '" + target + "'.");

            return _deserializer;
        }
Esempio n. 27
0
		public void AddAttributes (Attributes attrs, IMemberContext context)
		{
			if (attrs == null)
				return;

			if (attributes == null)
				attributes = attrs;
			else
				throw new NotImplementedException ();

			attributes.AttachTo (this, context);
		}
Esempio n. 28
0
		public EmitContext (IMemberContext rc, ILGenerator ig, TypeSpec return_type)
		{
			this.member_context = rc;
			this.ig = ig;
			this.return_type = return_type;

			if (rc.Module.Compiler.Settings.Checked)
				flags |= Options.CheckedScope;

#if STATIC
			ig.__CleverExceptionBlockAssistance ();
#endif
		}
        private static IEnumerable<XName> GetElementNamesFromXmlArrayItemAttributes(IMemberContext target)
        {
            var arrayItemNames = target.Attributes
                    .OfType<XmlArrayItemAttribute>()
                    .Select(a => (XName)a.ElementName)
                    .Where(n => n != null)
                    .ToList();

            if (!arrayItemNames.Any())
                return null;

            return arrayItemNames;
        }
        public IEnumerable<IMapping<XObject, IMemberContext>> MapForDeserialization(XElement source, IMemberContext target, IAdviceRequester adviceRequester)
        {
            var targetObject = target.GetValue();
            if (targetObject == null)
                throw new ArgumentException("Target should have had it value set to a collection at this point.", "target");

            var elementNames = GetElementNames(target);

            return source.Elements()
                    .Where(e => elementNames.Contains(e.Name, CaseInsensitiveXNameComparer.Instance))
                    .Select(elem => new Mapping<XObject, IMemberContext>(elem, targetObject.Members.Single()))
                    .ToList();
        }
Esempio n. 31
0
        // <summary>
        //   Resolve is used in method definitions
        // </summary>
        public virtual TypeSpec Resolve(IMemberContext rc, int index)
        {
            if (parameter_type != null)
            {
                return(parameter_type);
            }

            if (attributes != null)
            {
                attributes.AttachTo(this, rc);
            }

            parameter_type = texpr.ResolveAsType(rc);
            if (parameter_type == null)
            {
                return(null);
            }

            this.idx = index;

            if ((modFlags & Parameter.Modifier.RefOutMask) != 0 && parameter_type.IsSpecialRuntimeType)
            {
                rc.Module.Compiler.Report.Error(1601, Location, "Method or delegate parameter cannot be of type `{0}'",
                                                GetSignatureForError());
                return(null);
            }

            TypeManager.CheckTypeVariance(parameter_type,
                                          (modFlags & Parameter.Modifier.RefOutMask) != 0 ? Variance.None : Variance.Contravariant,
                                          rc);

            if (parameter_type.IsStatic)
            {
                rc.Module.Compiler.Report.Error(721, Location, "`{0}': static types cannot be used as parameters",
                                                texpr.GetSignatureForError());
                return(parameter_type);
            }

            if ((modFlags & Modifier.This) != 0 && (parameter_type.IsPointer || parameter_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic))
            {
                rc.Module.Compiler.Report.Error(1103, Location, "The extension method cannot be of type `{0}'",
                                                TypeManager.CSharpName(parameter_type));
            }

            return(parameter_type);
        }
Esempio n. 32
0
        public override TypeSpec Resolve(IMemberContext ec, int index)
        {
            if (base.Resolve(ec, index) == null)
            {
                return(null);
            }

            var ac = parameter_type as ArrayContainer;

            if (ac == null || ac.Rank != 1)
            {
                ec.Module.Compiler.Report.Error(225, Location, "The params parameter must be a single dimensional array");
                return(null);
            }

            return(parameter_type);
        }
Esempio n. 33
0
        public override TypeSpec ResolveAsType(IMemberContext ec)
        {
            eclass = ExprClass.Type;

            var otype = ec.Module.PredefinedTypes.Nullable.Resolve();

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

            TypeArguments   args  = new TypeArguments(new TypeExpression(underlying, loc));
            GenericTypeExpr ctype = new GenericTypeExpr(otype, args, loc);

            type = ctype.ResolveAsType(ec);
            return(type);
        }
Esempio n. 34
0
        public static void Create(IMemberContext context, ParametersBlock block, ParametersCompiled parameters, TypeContainer host, TypeSpec returnType, Location loc)
        {
            if (returnType != null && returnType.Kind != MemberKind.Void &&
                returnType != host.Module.PredefinedTypes.Task.TypeSpec &&
                !returnType.IsGenericTask)
            {
                host.Compiler.Report.Error(1983, loc, "The return type of an async method must be void, Task, or Task<T>");
            }

            for (int i = 0; i < parameters.Count; i++)
            {
                Parameter          p   = parameters[i];
                Parameter.Modifier mod = p.ModFlags;
                if ((mod & Parameter.Modifier.ISBYREF) != 0)
                {
                    host.Compiler.Report.Error(1988, p.Location,
                                               "Async methods cannot have ref or out parameters");
                    return;
                }

                // TODO:
                if (p is ArglistParameter)
                {
                    host.Compiler.Report.Error(1636, p.Location,
                                               "__arglist is not allowed in parameter list of iterators");
                    return;
                }

                // TODO:
                if (parameters.Types[i].IsPointer)
                {
                    host.Compiler.Report.Error(1637, p.Location,
                                               "Iterators cannot have unsafe parameters or yield types");
                    return;
                }
            }

            if (!block.IsAsync)
            {
                host.Compiler.Report.Warning(1998, 1, loc,
                                             "Async block lacks `await' operator and will run synchronously");
            }

            block.WrapIntoAsyncTask(context, host, returnType);
        }
Esempio n. 35
0
		public ResolveContext (IMemberContext mc)
		{
			if (mc == null)
				throw new ArgumentNullException ();

			MemberContext = mc;

			//
			// The default setting comes from the command line option
			//
			if (mc.Module.Compiler.Settings.Checked)
				flags |= Options.CheckedScope;

			//
			// The constant check state is always set to true
			//
			flags |= Options.ConstantCheckState;
		}
Esempio n. 36
0
        public ResolveContext(IMemberContext mc)
        {
            if (mc == null)
            {
                throw new ArgumentNullException();
            }

            MemberContext = mc;

            //
            // The default setting comes from the command line option
            //
            if (mc.Module.Compiler.Settings.Checked)
            {
                flags |= Options.CheckedScope;
            }

            //
            // The constant check state is always set to true
            //
            flags |= Options.ConstantCheckState;

            //
            // File type set from member context module sourcefile.
            //
            var memberCore = mc as MemberCore;

            if (memberCore != null && memberCore.Location.SourceFile != null)
            {
                fileType = memberCore.Location.SourceFile.FileType;
            }
            else if (mc.Module != null && mc.Module.Location.SourceFile != null)
            {
                fileType = mc.Module.Location.SourceFile.FileType;
                if (mc.Module.Location.SourceFile.PsExtended)
                {
                    flags |= Options.PsExtended;
                }
            }
            else
            {
                fileType = SourceFileType.CSharp;
            }
        }
Esempio n. 37
0
        public static TypeInfo GetTypeInfo(TypeSpec type, IMemberContext context)
        {
            if (!type.IsStruct)
            {
                return(simple_type);
            }

            TypeInfo info;
            Dictionary <TypeSpec, TypeInfo> type_hash;

            if (type.BuiltinType > 0)
            {
                // Don't cache built-in types, they are null in most cases except for
                // corlib compilation when we need to distinguish between declaration
                // and referencing
                type_hash = null;
            }
            else
            {
                type_hash = context.Module.TypeInfoCache;
                if (type_hash.TryGetValue(type, out info))
                {
                    return(info);
                }
            }

            var struct_info = StructInfo.GetStructInfo(type, context);

            if (struct_info != null)
            {
                info = new TypeInfo(struct_info, 0);
            }
            else
            {
                info = simple_type;
            }

            if (type_hash != null)
            {
                type_hash.Add(type, info);
            }

            return(info);
        }
Esempio n. 38
0
        //
        // Extension methods look up for dotted namespace names
        //
        public IList <MethodSpec> LookupExtensionMethod(IMemberContext invocationContext, TypeSpec extensionType, string name, int arity, out Namespace scope)
        {
            //
            // Inspect parent namespaces in namespace expression
            //
            scope = this;
            do
            {
                var candidates = scope.LookupExtensionMethod(invocationContext, extensionType, name, arity);
                if (candidates != null)
                {
                    return(candidates);
                }

                scope = scope.Parent;
            } while (scope != null);

            return(null);
        }
Esempio n. 39
0
        //
        // System.Linq.Expressions.ParameterExpression type
        //
        public static TypeExpr ResolveParameterExpressionType(IMemberContext ec, Location location)
        {
            if (parameter_expr_tree_type != null)
            {
                return(parameter_expr_tree_type);
            }

            Type p_type = TypeManager.parameter_expression_type;

            if (p_type == null)
            {
                p_type = TypeManager.CoreLookupType(ec.Compiler, "System.Linq.Expressions", "ParameterExpression", Kind.Class, true);
                TypeManager.parameter_expression_type = p_type;
            }

            parameter_expr_tree_type = new TypeExpression(p_type, location).
                                       ResolveAsTypeTerminal(ec, false);

            return(parameter_expr_tree_type);
        }
Esempio n. 40
0
        public override FullNamedExpression Resolve(IMemberContext rc, bool local)
        {
            if (resolved != null || value == null)
            {
                return(resolved);
            }

            if (local)
            {
                return(null);
            }

            resolved = value.GetTypeExpression().ResolveAsTypeOrNamespace(rc);
            if (resolved == null)
            {
                value = null;
                return(null);
            }

            return(resolved);
        }
Esempio n. 41
0
        public void Error_NamespaceDoesNotExist(IMemberContext ctx, string name, int arity, Location loc)
        {
            var retval = LookupType(ctx, name, arity, LookupMode.IgnoreAccessibility, loc);

            if (retval != null)
            {
                ctx.Module.Compiler.Report.SymbolRelatedToPreviousError(retval.Type);
                ErrorIsInaccesible(ctx, retval.GetSignatureForError(), loc);
                return;
            }

            retval = LookupType(ctx, name, -System.Math.Max(1, arity), LookupMode.Probing, loc);
            if (retval != null)
            {
                Error_TypeArgumentsCannotBeUsed(ctx, retval.Type, arity, loc);
                return;
            }

            Namespace ns;

            if (arity > 0 && namespaces.TryGetValue(name, out ns))
            {
                ns.Error_TypeArgumentsCannotBeUsed(ctx, null, arity, loc);
                return;
            }

            if (this is GlobalRootNamespace)
            {
                ctx.Module.Compiler.Report.Error(400, loc,
                                                 "The type or namespace name `{0}' could not be found in the global namespace (are you missing an assembly reference?)",
                                                 name);
            }
            else
            {
                ctx.Module.Compiler.Report.Error(234, loc,
                                                 "The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing an assembly reference?",
                                                 name, GetSignatureForError());
            }
        }
Esempio n. 42
0
        ///
        /// Looks for extension method in this namespace
        ///
        public List <MethodSpec> LookupExtensionMethod(IMemberContext invocationContext, TypeSpec extensionType, string name, int arity)
        {
            if (types == null)
            {
                return(null);
            }

            List <MethodSpec> found = null;

            // TODO: Add per namespace flag when at least 1 type has extension

            foreach (var tgroup in types.Values)
            {
                foreach (var ts in tgroup)
                {
                    if ((ts.Modifiers & Modifiers.METHOD_EXTENSION) == 0)
                    {
                        continue;
                    }

                    var res = ts.MemberCache.FindExtensionMethods(invocationContext, extensionType, name, arity);
                    if (res == null)
                    {
                        continue;
                    }

                    if (found == null)
                    {
                        found = res;
                    }
                    else
                    {
                        found.AddRange(res);
                    }
                }
            }

            return(found);
        }
Esempio n. 43
0
        public MemberSpec FindElement(IMemberContext mc, string name, Location loc)
        {
            // TODO: cache it
            for (int i = 0; i < elements.Count; ++i)
            {
                var ename = elements [i];
                if (ename == null || ename != name)
                {
                    continue;
                }

                var member_name = GetElementPropertyName(i);
                var ms          = MemberCache.FindMember(tuple, MemberFilter.Field(member_name, null), BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
                if (ms == null)
                {
                    mc.Module.Compiler.Report.Error(8128, loc, "Member `{0}' was not found on type '{1}'", member_name, tuple.GetSignatureForError());
                    return(null);
                }

                return(ms);
            }

            return(null);
        }
Esempio n. 44
0
        public Namespace Resolve(IMemberContext rc)
        {
            if (resolved != null)
            {
                return(resolved);
            }

            FullNamedExpression fne = name.GetTypeExpression().ResolveAsTypeOrNamespace(rc);

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

            resolved = fne as Namespace;
            if (resolved == null)
            {
                rc.Module.Compiler.Report.SymbolRelatedToPreviousError(fne.Type);
                rc.Module.Compiler.Report.Error(138, Location,
                                                "`{0}' is a type not a namespace. A using namespace directive can only be applied to namespaces",
                                                GetSignatureForError());
            }
            return(resolved);
        }
Esempio n. 45
0
        public static void Create(IMemberContext context, ParametersBlock block, ParametersCompiled parameters, TypeContainer host, TypeSpec returnType, Location loc)
        {
            for (int i = 0; i < parameters.Count; i++)
            {
                Parameter          p   = parameters[i];
                Parameter.Modifier mod = p.ModFlags;
                if ((mod & Parameter.Modifier.ISBYREF) != 0)
                {
                    host.Compiler.Report.Error(1988, p.Location,
                                               "Async methods cannot have ref or out parameters");
                    return;
                }

                if (p is ArglistParameter)
                {
                    host.Compiler.Report.Error(4006, p.Location,
                                               "__arglist is not allowed in parameter list of async methods");
                    return;
                }

                if (parameters.Types[i].IsPointer)
                {
                    host.Compiler.Report.Error(4005, p.Location,
                                               "Async methods cannot have unsafe parameters");
                    return;
                }
            }

            if (!block.IsAsync)
            {
                host.Compiler.Report.Warning(1998, 1, loc,
                                             "Async block lacks `await' operator and will run synchronously");
            }

            block.WrapIntoAsyncTask(context, host, returnType);
        }
Esempio n. 46
0
        public bool IsConditionallyExcluded(IMemberContext ctx)
        {
            if ((Kind & (MemberKind.Class | MemberKind.Method)) == 0)
            {
                return(false);
            }

            var conditions = MemberDefinition.ConditionalConditions();

            if (conditions == null)
            {
                return(false);
            }

            var m = ctx.CurrentMemberDefinition;
            CompilationSourceFile unit = null;

            while (m != null && unit == null)
            {
                unit = m as CompilationSourceFile;
                m    = m.Parent;
            }

            if (unit != null)
            {
                foreach (var condition in conditions)
                {
                    if (unit.IsConditionalDefined(condition))
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Esempio n. 47
0
 public AsyncTaskStorey(ParametersBlock block, IMemberContext context, AsyncInitializer initializer, TypeSpec type)
     : base(block, initializer.Host, context.CurrentMemberDefinition as MemberBase, context.CurrentTypeParameters, "async", MemberKind.Struct)
 {
     return_type    = type;
     awaiter_fields = new Dictionary <TypeSpec, List <Field> > ();
 }
Esempio n. 48
0
 public ResolveContext(IMemberContext mc, Options options)
     : this(mc)
 {
     flags |= options;
 }
Esempio n. 49
0
 public override TypeSpec ResolveAsType(IMemberContext ec)
 {
     eclass = ExprClass.Type;
     type   = ec.Module.Compiler.BuiltinTypes.Dynamic;
     return(type);
 }
Esempio n. 50
0
 public override void EncodeAttributeValue(IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
 {
     throw new NotSupportedException();
 }
Esempio n. 51
0
        //
        // Is this member accessible from invocation context
        //
        public bool IsAccessible(IMemberContext ctx)
        {
            var ma = Modifiers & Modifiers.AccessibilityMask;

            if (ma == Modifiers.PUBLIC)
            {
                return(true);
            }

            var parentType = /* this as TypeSpec ?? */ DeclaringType;
            var ctype      = ctx.CurrentType;

            if (ma == Modifiers.PRIVATE)
            {
                if (ctype == null || parentType == null)
                {
                    return(false);
                }
                //
                // It's only accessible to the current class or children
                //
                if (parentType.MemberDefinition == ctype.MemberDefinition)
                {
                    return(true);
                }

                return(TypeManager.IsNestedChildOf(ctype, parentType.MemberDefinition));
            }

            if ((ma & Modifiers.INTERNAL) != 0)
            {
                bool b;
                var  assembly = ctype == null ? ctx.Module.DeclaringAssembly : ctype.MemberDefinition.DeclaringAssembly;

                if (parentType == null)
                {
                    b = ((ITypeDefinition)MemberDefinition).IsInternalAsPublic(assembly);
                }
                else
                {
                    b = DeclaringType.MemberDefinition.IsInternalAsPublic(assembly);
                }

                if (b || ma == Modifiers.INTERNAL)
                {
                    return(b);
                }
            }

            //
            // Checks whether `ctype' is a subclass or nested child of `parentType'.
            //
            while (ctype != null)
            {
                if (TypeManager.IsFamilyAccessible(ctype, parentType))
                {
                    return(true);
                }

                // Handle nested types.
                ctype = ctype.DeclaringType;                    // TODO: Untested ???
            }

            return(false);
        }
Esempio n. 52
0
 public override TypeSpec ResolveAsType(IMemberContext ec, bool allowUnboundTypeArguments)
 {
     eclass = ExprClass.Type;
     type   = ec.Module.Compiler.BuiltinTypes.Dynamic;
     return(type);
 }
Esempio n. 53
0
 public override TypeSpec ResolveAsType(IMemberContext ec)
 {
     type   = ec.CurrentType;
     eclass = ExprClass.Type;
     return(type);
 }
 public override TypeSpec Resolve(IMemberContext ec, int index)
 {
     return(parameter_type);
 }
        //
        // System.Linq.Expressions.ParameterExpression type
        //
        public static TypeExpr ResolveParameterExpressionType(IMemberContext ec, Location location)
        {
            TypeSpec p_type = ec.Module.PredefinedTypes.ParameterExpression.Resolve();

            return(new TypeExpression(p_type, location));
        }
Esempio n. 56
0
 public void Resolve(IMemberContext context)
 {
     type = Type.ResolveAsType(context);
 }
Esempio n. 57
0
 public FieldInitializerContext(IMemberContext mc, ResolveContext constructorContext)
     : base(mc, Options.FieldInitializerScope | Options.ConstructorScope)
 {
     this.ctor_block = constructorContext.CurrentBlock.Explicit;
 }
 public AddMeetingNotAttendeeCommandHandler(IMemberContext memberContext, IMeetingRepository meetingRepository)
 {
     _memberContext     = memberContext;
     _meetingRepository = meetingRepository;
 }
Esempio n. 59
0
 public override FullNamedExpression ResolveAsTypeOrNamespace(IMemberContext mc)
 {
     return(this);
 }
Esempio n. 60
0
        public TypeExpr LookupType(IMemberContext ctx, string name, int arity, LookupMode mode, Location loc)
        {
            if (types == null)
            {
                return(null);
            }

            TypeExpr te;

            if (arity == 0 && cached_types.TryGetValue(name, out te))
            {
                return(te);
            }

            IList <TypeSpec> found;

            if (!types.TryGetValue(name, out found))
            {
                return(null);
            }

            TypeSpec best = null;

            foreach (var ts in found)
            {
                if (ts.Arity == arity)
                {
                    if (best == null)
                    {
                        if ((ts.Modifiers & Modifiers.INTERNAL) != 0 && !ts.MemberDefinition.IsInternalAsPublic(ctx.Module.DeclaringAssembly) && mode != LookupMode.IgnoreAccessibility)
                        {
                            continue;
                        }

                        best = ts;
                        continue;
                    }

                    if (best.MemberDefinition.IsImported && ts.MemberDefinition.IsImported)
                    {
                        if (mode == LookupMode.Normal)
                        {
                            ctx.Module.Compiler.Report.SymbolRelatedToPreviousError(best);
                            ctx.Module.Compiler.Report.SymbolRelatedToPreviousError(ts);
                            ctx.Module.Compiler.Report.Error(433, loc, "The imported type `{0}' is defined multiple times", ts.GetSignatureForError());
                        }
                        break;
                    }

                    if (best.MemberDefinition.IsImported)
                    {
                        best = ts;
                    }

                    if ((best.Modifiers & Modifiers.INTERNAL) != 0 && !best.MemberDefinition.IsInternalAsPublic(ctx.Module.DeclaringAssembly))
                    {
                        continue;
                    }

                    if (mode != LookupMode.Normal)
                    {
                        continue;
                    }

                    if (ts.MemberDefinition.IsImported)
                    {
                        ctx.Module.Compiler.Report.SymbolRelatedToPreviousError(ts);
                    }

                    ctx.Module.Compiler.Report.Warning(436, 2, loc,
                                                       "The type `{0}' conflicts with the imported type of same name'. Ignoring the imported type definition",
                                                       best.GetSignatureForError());
                }

                //
                // Lookup for the best candidate with the closest arity match
                //
                if (arity < 0)
                {
                    if (best == null)
                    {
                        best = ts;
                    }
                    else if (System.Math.Abs(ts.Arity + arity) < System.Math.Abs(best.Arity + arity))
                    {
                        best = ts;
                    }
                }
            }

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

            te = new TypeExpression(best, Location.Null);

            // TODO MemberCache: Cache more
            if (arity == 0 && mode == LookupMode.Normal)
            {
                cached_types.Add(name, te);
            }

            return(te);
        }