Example #1
0
            public override FullNamedExpression Resolve(IResolveContext rc)
            {
                if (resolved != null || value == null)
                {
                    return(resolved);
                }

                resolved = value.GetTypeExpression().ResolveAsTypeStep(rc, false);
                if (resolved == null)
                {
                    value = null;
                    return(null);
                }

                TypeExpr te = resolved as TypeExpr;

                if (te != null)
                {
                    if (!te.CheckAccessLevel(rc.DeclContainer))
                    {
                        Report.SymbolRelatedToPreviousError(te.Type);
                        Expression.ErrorIsInaccesible(resolved.Location, resolved.GetSignatureForError());
                    }
                }

                return(resolved);
            }
Example #2
0
        /// <summary>
        /// Activate an instance in the provided context.
        /// </summary>
        /// <param name="context">Context in which to activate instances.</param>
        /// <param name="parameters">Parameters to the instance.</param>
        /// <returns>The activated instance.</returns>
        /// <remarks>
        /// The context parameter here should probably be ILifetimeScope in order to reveal Disposer,
        /// but will wait until implementing a concrete use case to make the decision.
        /// </remarks>
        private object ActivateInstance(IResolveContext context, IEnumerable <Parameter> parameters)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            CheckNotDisposed();

            var allBindings = GetAllBindings(_constructorBinders !, context, parameters);

            var selectedBinding = ConstructorSelector.SelectConstructorBinding(allBindings, parameters);

            if (!selectedBinding.CanInstantiate)
            {
                throw new InvalidOperationException(string.Format(
                                                        CultureInfo.CurrentCulture,
                                                        ReflectionActivatorResources.ConstructorSelectorCannotSelectAnInvalidBinding,
                                                        ConstructorSelector.GetType().Name));
            }

            var instance = selectedBinding.Instantiate();

            InjectProperties(instance, context);

            return(instance);
        }
Example #3
0
        private static IEnumerable <Localization> FilterLocalizations(IResolveContext context)
        {
            var result = new List <Localization>();
            var filter = CalculateCultureFilter(context);

            var localizations = context.Localizations.Concat(context.IntermediateRepresentation.Localizations).ToList();

            AddFilteredLocalizations(result, filter, localizations);

            // Filter localizations provided by extensions with data.
            var creator = context.ServiceProvider.GetService <ISymbolDefinitionCreator>();

            foreach (var data in context.ExtensionData)
            {
                var library = data.GetLibrary(creator);

                if (library?.Localizations != null && library.Localizations.Any())
                {
                    var extensionFilter = (!filter.Any() && data.DefaultCulture != null) ? new[] { data.DefaultCulture } : filter;

                    AddFilteredLocalizations(result, extensionFilter, library.Localizations);
                }
            }

            return(result);
        }
        /// <summary>
        /// Ensures the first draft of the SWID Tag exists on disk when being included
        /// in MSI packages.
        /// </summary>
        /// <param name="context">Resolve context.</param>
        public void PreResolve(IResolveContext context)
        {
            var section = context.IntermediateRepresentation.Sections.FirstOrDefault();

            // Only process MSI packages.
            if (SectionType.Product != section?.Type)
            {
                return;
            }

            this.backendHelper = context.ServiceProvider.GetService <IBackendHelper>();

            this.workingFolder = CalculateWorkingFolder(context.IntermediateFolder);

            // Ensure any tag files are generated to be imported by the MSI.
            var tagSymbols = this.CreateProductTagFiles(section);

            var tagSymbol = tagSymbols.FirstOrDefault();

            if (tagSymbol != null)
            {
                // If we created any tag files, add a WixVariable to map to the regid.
                section.AddSymbol(new WixVariableSymbol(tagSymbol.SourceLineNumbers, new Identifier(AccessModifier.Private, "WixTagRegid"))
                {
                    Value       = tagSymbol.Regid,
                    Overridable = false
                });
            }
        }
Example #5
0
        public IResolveResult Resolve(IResolveContext context)
        {
            foreach (var extension in context.Extensions)
            {
                extension.PreResolve(context);
            }

            ResolveResult resolveResult = null;

            try
            {
                var codepage = this.PopulateVariableResolver(context);

                this.LocalizeUI(context);

                resolveResult = this.DoResolve(context, codepage);
            }
            finally
            {
                foreach (var extension in context.Extensions)
                {
                    extension.PostResolve(resolveResult);
                }
            }

            return(resolveResult);
        }
Example #6
0
        public bool Resolve(IResolveContext ec)
        {
            if (types != null)
            {
                return(true);
            }

            types = new Type [Count];

            bool      ok = true;
            Parameter p;

            for (int i = 0; i < FixedParameters.Length; ++i)
            {
                p = this [i];
                Type t = p.Resolve(ec);
                if (t == null)
                {
                    ok = false;
                    continue;
                }

                types [i] = t;
            }

            return(ok);
        }
Example #7
0
        private void InjectProperties(object instance, IResolveContext context)
        {
            if (_configuredProperties.Length == 0)
            {
                return;
            }

            var actualProperties = instance
                                   .GetType()
                                   .GetRuntimeProperties()
                                   .Where(pi => pi.CanWrite)
                                   .ToList();

            foreach (var configuredProperty in _configuredProperties)
            {
                foreach (var actualProperty in actualProperties)
                {
                    var setter = actualProperty.SetMethod;

                    if (setter != null &&
                        configuredProperty.CanSupplyValue(setter.GetParameters()[0], context, out var vp))
                    {
                        actualProperties.Remove(actualProperty);
                        actualProperty.SetValue(instance, vp(), null);
                        break;
                    }
                }
            }
        }
Example #8
0
        Object IResolveBuilder.Initialize(IResolveContext context)
        {
            var typedContext = ValidateContext(context);

            return(Elements
                   .Select(e => e.ElementInitialize(typedContext))
                   .ToArray());
        }
        public MasterSlaveTest(ITestOutputHelper output, TestStartupFixture fixture)
        {
            Output   = output;
            Services = fixture.Services;
            Context  = Services.GetRequiredService <IResolveContext>();

            DapperMaster = Context.ResolveDapper("master_slave");
            DapperSlave  = Context.ResolveDapper("master_slave", true);
        }
Example #10
0
 public FieldInitializer(FieldBuilder field, Expression expression, IResolveContext rc)
     : base(new FieldExpr(field, expression.Location), expression, expression.Location)
 {
     this.rc = rc;
     if (!field.IsStatic)
     {
         ((FieldExpr)target).InstanceExpression = CompilerGeneratedThis.Instance;
     }
 }
Example #11
0
        void IResolveBuilder.InitializeContext(IResolveContext context)
        {
            var typedContext = ValidateContext(context);

            foreach (var element in Elements)
            {
                element.ElementInitializeContext(typedContext);
            }
        }
        public override object ResolveInstance(IResolveContext resolveContext)
        {
            if (_threadLocal.IsValueCreated == false)
            {
                _threadLocal.Value = resolveContext.CreateInstance();
            }

            return(_threadLocal.Value);
        }
        public override object ResolveInstance(IResolveContext resolveContext)
        {
            if (resolveContext.Container.Scope.TryGetScopedInstance(resolveContext.Registration.TypeKey, out var instance))
            {
                return(instance);
            }

            throw new ResolveException($"There is no external instance available in the current scope for {resolveContext.Registration.TypeKey}.");
        }
        protected override IEnumerable ToEnumerable(Object state, IResolveContext context)
        {
            if (context == null)
            {
                throw Logger.Fatal.ArgumentNull(nameof(context));
            }

            return(context.ProvisionerContext.GetState <TResult>());
        }
Example #15
0
        /// <summary>
        /// Returns true if the parameter is able to provide a value to a particular site.
        /// </summary>
        /// <param name="pi">Constructor, method, or property-mutator parameter.</param>
        /// <param name="context">The component context in which the value is being provided.</param>
        /// <param name="valueProvider">If the result is true, the <paramref name="valueProvider" /> parameter will
        /// be set to a function that will lazily retrieve the parameter value. If the result is <see langword="false" />,
        /// will be set to <see langword="null" />.</param>
        /// <returns><see langword="true" /> if a value can be supplied; otherwise, <see langword="false" />.</returns>
        /// <exception cref="ArgumentNullException">
        /// Thrown if <paramref name="pi" /> is <see langword="null" />.
        /// </exception>
        public override bool CanSupplyValue(ParameterInfo pi, IResolveContext context, [NotNullWhen(returnValue: true)] out Func <object?>?valueProvider)
        {
            if (pi == null)
            {
                throw new ArgumentNullException(nameof(pi));
            }

            bool hasDefaultValue;
            var  tryToGetDefaultValue = true;

            try
            {
                // Workaround for https://github.com/dotnet/corefx/issues/17943
                if (pi.Member.DeclaringType?.Assembly.IsDynamic ?? true)
                {
                    hasDefaultValue = pi.DefaultValue != null && pi.HasDefaultValue;
                }
                else
                {
                    hasDefaultValue = pi.HasDefaultValue;
                }
            }
            catch (FormatException) when(pi.ParameterType == typeof(DateTime))
            {
                // Workaround for https://github.com/dotnet/corefx/issues/12338
                // If HasDefaultValue throws FormatException for DateTime
                // we expect it to have default value
                hasDefaultValue      = true;
                tryToGetDefaultValue = false;
            }

            if (hasDefaultValue)
            {
                valueProvider = () =>
                {
                    if (!tryToGetDefaultValue)
                    {
                        return(default(DateTime));
                    }

                    var defaultValue = pi.DefaultValue;

                    // Workaround for https://github.com/dotnet/corefx/issues/11797
                    if (defaultValue == null && pi.ParameterType.IsValueType)
                    {
                        defaultValue = Activator.CreateInstance(pi.ParameterType);
                    }

                    return(defaultValue);
                };

                return(true);
            }

            valueProvider = null;
            return(false);
        }
Example #16
0
        private ResolveResult DoResolve(IResolveContext context, int?codepage)
        {
            var buildingPatch = context.IntermediateRepresentation.Sections.Any(s => s.Type == SectionType.Patch);

            var filesWithEmbeddedFiles = new ExtractEmbeddedFiles();

            IEnumerable <DelayedField> delayedFields;

            {
                var command = new ResolveFieldsCommand();
                command.Messaging                = this.Messaging;
                command.BuildingPatch            = buildingPatch;
                command.VariableResolver         = this.VariableResolver;
                command.BindPaths                = context.BindPaths;
                command.Extensions               = context.Extensions;
                command.FilesWithEmbeddedFiles   = filesWithEmbeddedFiles;
                command.IntermediateFolder       = context.IntermediateFolder;
                command.Intermediate             = context.IntermediateRepresentation;
                command.SupportDelayedResolution = true;
                command.AllowUnresolvedVariables = context.AllowUnresolvedVariables;
                command.Execute();

                delayedFields = command.DelayedFields;
            }

#if TODO_PATCHING
            if (context.IntermediateRepresentation.SubStorages != null)
            {
                foreach (SubStorage transform in context.IntermediateRepresentation.SubStorages)
                {
                    var command = new ResolveFieldsCommand();
                    command.BuildingPatch            = buildingPatch;
                    command.BindVariableResolver     = context.WixVariableResolver;
                    command.BindPaths                = context.BindPaths;
                    command.Extensions               = context.Extensions;
                    command.FilesWithEmbeddedFiles   = filesWithEmbeddedFiles;
                    command.IntermediateFolder       = context.IntermediateFolder;
                    command.Intermediate             = context.IntermediateRepresentation;
                    command.SupportDelayedResolution = false;
                    command.Execute();
                }
            }
#endif

            var expectedEmbeddedFiles = filesWithEmbeddedFiles.GetExpectedEmbeddedFiles();

            context.IntermediateRepresentation.UpdateLevel(IntermediateLevels.Resolved);

            return(new ResolveResult
            {
                Codepage = codepage.HasValue ? codepage.Value : -1,
                ExpectedEmbeddedFiles = expectedEmbeddedFiles,
                DelayedFields = delayedFields,
                IntermediateRepresentation = context.IntermediateRepresentation
            });
        }
Example #17
0
        public override Type Resolve(IResolveContext ec)
        {
            if (parameter_type == null)
            {
                throw new InternalErrorException("A type of implicit lambda parameter `{0}' is not set",
                                                 Name);
            }

            return(parameter_type);
        }
        /// <summary>
        /// Inject properties onto an instance, filtered by a property selector.
        /// </summary>
        /// <param name="context">The component context to resolve dependencies from.</param>
        /// <param name="instance">The instance to inject onto.</param>
        /// <param name="propertySelector">The property selector.</param>
        /// <param name="parameters">The set of parameters for the resolve that can be used to satisfy injectable properties.</param>
        public static void InjectProperties(IResolveContext context, object instance, IPropertySelector propertySelector, IEnumerable <Parameter> parameters)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }

            if (propertySelector == null)
            {
                throw new ArgumentNullException(nameof(propertySelector));
            }

            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            var resolveParameters = parameters as Parameter[] ?? parameters.ToArray();

            var instanceType         = instance.GetType();
            var injectableProperties = InjectableProperties.GetOrAdd(instanceType, type => GetInjectableProperties(type).ToArray());

            for (var index = 0; index < injectableProperties.Length; index++)
            {
                var property = injectableProperties[index];

                if (!propertySelector.InjectProperty(property, instance))
                {
                    continue;
                }

                var setParameter  = property.SetMethod.GetParameters()[0];
                var valueProvider = (Func <object?>?)null;
                var parameter     = resolveParameters.FirstOrDefault(p => p.CanSupplyValue(setParameter, context, out valueProvider));
                if (parameter != null)
                {
                    var setter = PropertySetters.GetOrAdd(property, MakeFastPropertySetter);
                    setter(instance, valueProvider !());
                    continue;
                }

                var propertyService       = new TypedService(property.PropertyType);
                var instanceTypeParameter = new NamedParameter(InstanceTypeNamedParameter, instanceType);
                if (context.TryResolveService(propertyService, new Parameter[] { instanceTypeParameter }, out var propertyValue))
                {
                    var setter = PropertySetters.GetOrAdd(property, MakeFastPropertySetter);
                    setter(instance, propertyValue);
                }
            }
        }
        private static Boolean ValidateResolveContext(IResolveContext resolveContext)
        {
            if (resolveContext == null)
            {
                throw Logger.Fatal.InvalidOperation(
                          SR.ResolveRegistrar_ContextFactoryReturnedNull
                          );
            }

            return(true);
        }
        /// <summary>
        /// 构建信息
        /// </summary>
        /// <param name="rules">服务类型规则</param>
        /// <param name="scope"></param>
        /// <param name="context">构建行为在执行过程的上下文</param>
        /// <returns></returns>
        public object[] ResolveAll(RegisterRule[] rules, ILifetimeScope scope, IResolveContext context)
        {
            var list = new List <object>(rules.Length);

            foreach (var rule in rules)
            {
                list.Add(RegisterRuleBuilder.Build(rule, this, this).Invoke(rule, this, scope, context));
            }

            return(list.ToArray());
        }
Example #21
0
		protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
		{
			if (TypeManager.generic_nullable_type == null) {
				TypeManager.generic_nullable_type = TypeManager.CoreLookupType (
					"System", "Nullable`1", Kind.Struct, true);
			}

			TypeArguments args = new TypeArguments (underlying);
			GenericTypeExpr ctype = new GenericTypeExpr (TypeManager.generic_nullable_type, args, loc);
			return ctype.ResolveAsTypeTerminal (ec, false);
		}
Example #22
0
        public async ValueTask <IResolveResult> ResolveStatusAsync(IResolveContext context)
        {
            var ping = new Ping();

            var pingResult = await ping.SendPingAsync(context.Host);

            return(new ResolveResult
            {
                IsOnline = pingResult.Status == IPStatus.Success,
                Latency = (int)pingResult.RoundtripTime
            });
        }
        public ValuesController(IResolveContext context, [DependencyDapper("master_slave")] IDapper writer, [DependencyDapper("master_slave", true)] IDapper reader, [DependencyDapper("sqlite1-conn")] IDapper rep1, [DependencyDapper("sqlite2-conn")] IDapper rep2, [DependencyDapper("msql-conn")] IDapper sql)
        {
            MasterReader = reader;
            MasterWriter = writer;
            SQLiteRepo1  = context.ResolveDapper("sqlite1-conn");
            SQLiteRepo2  = context.ResolveDapper("sqlite2-conn");

            Repo1 = rep1;
            Repo2 = rep2;

            SQLRepo = sql;
        }
        public async ValueTask <IResolveResult> ResolveStatusAsync(IResolveContext context)
        {
            var mcClient = new McApiClient(_http, context.Logger);

            var isOnline = await mcClient.CheckServerStatusAsync(context.ServiceConfig["host"],
                                                                 context.ServiceConfig["port"] ?? "25565");

            return(new ResolveResult
            {
                IsOnline = isOnline
            });
        }
Example #25
0
        protected override TypeExpr DoResolveAsTypeStep(IResolveContext ec)
        {
            if (TypeManager.generic_nullable_type == null)
            {
                TypeManager.generic_nullable_type = TypeManager.CoreLookupType(
                    "System", "Nullable`1", Kind.Struct, true);
            }

            TypeArguments   args  = new TypeArguments(underlying);
            GenericTypeExpr ctype = new GenericTypeExpr(TypeManager.generic_nullable_type, args, loc);

            return(ctype.ResolveAsTypeTerminal(ec, false));
        }
Example #26
0
            public virtual FullNamedExpression Resolve(IResolveContext rc)
            {
                FullNamedExpression fne = RootNamespace.GetRootNamespace(Alias);

                if (fne == null)
                {
                    Report.Error(430, Location,
                                 "The extern alias `{0}' was not specified in -reference option",
                                 Alias);
                }

                return(fne);
            }
Example #27
0
        /// <summary>
        /// Binds the set of parameters to the constructor. <see cref="BoundConstructor.CanInstantiate"/> indicates success.
        /// </summary>
        /// <param name="availableParameters">The set of all parameters.</param>
        /// <param name="context">The current component context.</param>
        /// <returns>The bind result.</returns>
        public BoundConstructor Bind(IEnumerable <Parameter> availableParameters, IResolveContext context)
        {
            if (availableParameters is null)
            {
                throw new ArgumentNullException(nameof(availableParameters));
            }

            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var constructorArgs      = _constructorArgs;
            var constructorArgLength = constructorArgs.Length;

            if (constructorArgLength == 0)
            {
                // No args, auto-bind with an empty value-retriever array to avoid the allocation.
                return(BoundConstructor.ForBindSuccess(this, _factory !, Array.Empty <Func <object?> >()));
            }

            if (_illegalParameter is object)
            {
                return(BoundConstructor.ForBindFailure(this, _illegalParameter));
            }

            var valueRetrievers = new Func <object?> [constructorArgLength];

            for (var idx = 0; idx < constructorArgLength; idx++)
            {
                var pi         = constructorArgs[idx];
                var foundValue = false;

                foreach (var param in availableParameters)
                {
                    if (param.CanSupplyValue(pi, context, out var valueRetriever))
                    {
                        valueRetrievers[idx] = valueRetriever;
                        foundValue           = true;
                        break;
                    }
                }

                if (!foundValue)
                {
                    return(BoundConstructor.ForBindFailure(this, pi));
                }
            }

            return(BoundConstructor.ForBindSuccess(this, _factory !, valueRetrievers));
        }
        internal static T Activate <T>(this IResolveContext <T> self)
        {
            if (self.IsNull())
            {
                throw new NoNullAllowedException("The type to create was not set.");
            }
            if (self.TypeContext == null)
            {
                return(default(T));
            }
            var context = ((IScopeContextInternal)self.TypeContext);

            return(context.Activate(context.GetActivationScope(), self.Initializer));
        }
Example #29
0
        private static IEnumerable <string> CalculateCultureFilter(IResolveContext context)
        {
            var filter = context.FilterCultures ?? Array.Empty <string>();

            // If no filter was specified, look for a language neutral localization file specified
            // from the command-line (not embedded in the intermediate). If found, filter on language
            // neutral.
            if (!filter.Any() && context.Localizations.Any(l => String.IsNullOrEmpty(l.Culture)))
            {
                filter = new[] { String.Empty };
            }

            return(filter);
        }
Example #30
0
        // <summary>
        //   Resolve is used in method definitions
        // </summary>
        public virtual Type Resolve(IResolveContext ec)
        {
            // HACK: to resolve attributes correctly
            this.resolve_context = ec;

            if (parameter_type != null)
            {
                return(parameter_type);
            }

            TypeExpr texpr = TypeName.ResolveAsTypeTerminal(ec, false);

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

            parameter_type = texpr.Type;

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

#if GMCS_SOURCE
            TypeParameterExpr tparam = texpr as TypeParameterExpr;
            if (tparam != null)
            {
                return(parameter_type);
            }
#endif

            if ((parameter_type.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute)
            {
                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)
            {
                Report.Error(1103, Location, "The type of extension method cannot be `{0}'",
                             TypeManager.CSharpName(parameter_type));
            }

            return(parameter_type);
        }
Example #31
0
        public override Type Resolve(IResolveContext ec)
        {
            if (base.Resolve(ec) == null)
            {
                return(null);
            }

            if (!parameter_type.IsArray || parameter_type.GetArrayRank() != 1)
            {
                Report.Error(225, Location, "The params parameter must be a single dimensional array");
                return(null);
            }

            return(parameter_type);
        }
Example #32
0
		protected override void Error_TypeOrNamespaceNotFound (IResolveContext ec)
		{
			Report.Error (825, loc, "The contextual keyword `var' may only appear within a local variable declaration");
		}
Example #33
0
		//
		// This is used if the expression should be resolved as a type or namespace name.
		// the default implementation fails.   
		//
		public virtual FullNamedExpression ResolveAsTypeStep (IResolveContext rc,  bool silent)
		{
			if (!silent) {
				Expression e = this;
				EmitContext ec = rc as EmitContext;
				if (ec != null)
					e = e.Resolve (ec);
				if (e != null)
					e.Error_UnexpectedKind (ResolveFlags.Type, loc);
			}
			return null;
		}
Example #34
0
		public override TypeExpr ResolveAsTypeTerminal (IResolveContext ec, bool silent)
		{
			return ResolveAsBaseTerminal (ec, silent);
		}		
Example #35
0
		public override Type Resolve (IResolveContext ec)
		{
			return typeof (ArglistParameter);
		}
Example #36
0
		public override Type Resolve (IResolveContext ec)
		{
			if (parameter_type == null)
				throw new InternalErrorException ("A type of implicit lambda parameter `{0}' is not set",
					Name);

			return parameter_type;
		}
        private static IEnumerable CreateResultSource(String propertyName, IResolveBuilder resolveBuilder, IResolveContext resolveContext)
        {
            Logger.Debug(
                "Property {PropertyName} resolver {$Resolver} initializing.",
                propertyName,
                resolveBuilder
            );

            var resultSource = resolveBuilder.ToEnumerable(
                resolveContext
,
                resolveBuilder.Initialize(resolveContext));

            Logger.Debug(
                "Property {PropertyName} resolver {$Resolver} resolved into {$Value}.",
                propertyName,
                resolveBuilder,
                resultSource
            );

            return resultSource;
        }
Example #38
0
		public override FullNamedExpression ResolveAsTypeStep (IResolveContext ec, bool silent)
		{
			return this;
		}
Example #39
0
		public override FullNamedExpression ResolveAsTypeStep (IResolveContext ec, bool silent)
		{
			TypeExpr t = DoResolveAsTypeStep (ec);
			if (t == null)
				return null;

			eclass = ExprClass.Type;
			return t;
		}
Example #40
0
		//
		// This is used to resolve the expression as a type, a null
		// value will be returned if the expression is not a type
		// reference
		//
		public virtual TypeExpr ResolveAsTypeTerminal (IResolveContext ec, bool silent)
		{
			TypeExpr te = ResolveAsBaseTerminal (ec, silent);
			if (te == null)
				return null;

			if (!silent) { // && !(te is TypeParameterExpr)) {
				ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (te.Type);
				if (obsolete_attr != null && !ec.IsInObsoleteScope) {
					AttributeTester.Report_ObsoleteMessage (obsolete_attr, te.GetSignatureForError (), Location);
				}
			}

			GenericTypeExpr ct = te as GenericTypeExpr;
			if (ct != null) {
				// Skip constrains check for overrides and explicit implementations
				// TODO: they should use different overload
				GenericMethod gm = ec.GenericDeclContainer as GenericMethod;
				if (gm != null && ((gm.ModFlags & Modifiers.OVERRIDE) != 0 || gm.MemberName.Left != null)) {
					te.loc = loc;
					return te;
				}

				// TODO: silent flag is ignored
				ct.CheckConstraints (ec);
			}

			return te;
		}
Example #41
0
		//
		// C# 3.0 introduced contextual keywords (var) which behaves like a type if type with
		// same name exists or as a keyword when no type was found
		// 
		public virtual TypeExpr ResolveAsContextualType (IResolveContext rc, bool silent)
		{
			return ResolveAsTypeTerminal (rc, silent);
		}		
Example #42
0
		protected virtual void Error_TypeOrNamespaceNotFound (IResolveContext ec)
		{
			MemberCore mc = ec.DeclContainer.GetDefinition (Name);
			if (mc != null) {
				Error_UnexpectedKind (ec.DeclContainer, "type", GetMemberType (mc), loc);
				return;
			}

			string ns = ec.DeclContainer.NamespaceEntry.NS.Name;
			string fullname = (ns.Length > 0) ? ns + "." + Name : Name;
			foreach (Assembly a in RootNamespace.Global.Assemblies) {
				Type type = a.GetType (fullname);
				if (type != null) {
					Report.SymbolRelatedToPreviousError (type);
					Expression.ErrorIsInaccesible (loc, TypeManager.CSharpName (type));
					return;
				}
			}

			Type t = ec.DeclContainer.LookupAnyGeneric (Name);
			if (t != null) {
				Namespace.Error_InvalidNumberOfTypeArguments (t, loc);
				return;
			}

			if (targs != null) {
				FullNamedExpression retval = ec.DeclContainer.LookupNamespaceOrType (SimpleName.RemoveGenericArity (Name), loc, true);
				if (retval != null) {
					Namespace.Error_TypeArgumentsCannotBeUsed (retval, loc);
					return;
				}
			}
						
			NamespaceEntry.Error_NamespaceNotFound (loc, Name);
		}
Example #43
0
		public override TypeExpr ResolveAsContextualType (IResolveContext rc, bool silent)
		{
			TypeExpr te = base.ResolveAsContextualType (rc, true);
			if (te != null)
				return te;

			if (initializer == null)
				return null;
			
	  		if (initializer.Count > 1) {
	  			Location loc = ((Mono.CSharp.CSharpParser.VariableDeclaration)initializer [1]).Location;
	  			Report.Error (819, loc, "An implicitly typed local variable declaration cannot include multiple declarators");
				initializer = null;
				return null;
	  		}
			  	
			Expression variable_initializer = ((Mono.CSharp.CSharpParser.VariableDeclaration)initializer [0]).expression_or_array_initializer;
			if (variable_initializer == null) {
				Report.Error (818, loc, "An implicitly typed local variable declarator must include an initializer");
				return null;
			}
			
			return null;
		}
        private static Boolean ValidateResolveContext(IResolveContext resolveContext)
        {
            if (resolveContext == null)
            {
                throw Logger.Fatal.InvalidOperation(
                    SR.ResolveRegistrar_ContextFactoryReturnedNull
                );
            }

            return true;
        }
 public ReturnTypeCollector(IResolveContext resolveContext)
 {
     this.resolveContext = resolveContext;
 }
Example #46
0
		public override TypeExpr ResolveAsTypeTerminal (IResolveContext ec, bool silent)
		{
			return this;
		}
Example #47
0
		public bool Resolve (IResolveContext ec)
		{
			if (types != null)
				return true;

			types = new Type [Count];
			
			bool ok = true;
			Parameter p;
			for (int i = 0; i < FixedParameters.Length; ++i) {
				p = this [i];
				Type t = p.Resolve (ec);
				if (t == null) {
					ok = false;
					continue;
				}

				types [i] = t;
			}

			return ok;
		}
Example #48
0
		public override TypeExpr ResolveAsTypeTerminal (IResolveContext ec, bool silent)
		{
			// It's null for corlib compilation only
			if (type == null)
				return DoResolveAsTypeStep (ec);

			return this;
		}
Example #49
0
		public override Type Resolve (IResolveContext ec)
		{
			if (base.Resolve (ec) == null)
				return null;

			if (!parameter_type.IsArray || parameter_type.GetArrayRank () != 1) {
				Report.Error (225, Location, "The params parameter must be a single dimensional array");
				return null;
			}

			return parameter_type;
		}
Example #50
0
		// This performes recursive type lookup, providing support for generic types.
		// For example, given the type:
		//
		// System.Collections.Generic.KeyValuePair`2[[System.Int32],[System.String]]
		//
		// The types will be checked in the following order:
		//                                                                             _
		// System                                                                       |
		// System.Collections                                                           |
		// System.Collections.Generic                                                   |
		//                        _                                                     |
		//     System              | recursive call 1                                   |
		//     System.Int32       _|                                                    | main method call
		//                        _                                                     |
		//     System              | recursive call 2                                   |
		//     System.String      _|                                                    |
		//                                                                              |
		// System.Collections.Generic.KeyValuePair`2[[System.Int32],[System.String]]   _|
		//
		private Type TypeLookup (IResolveContext ec, string name)
		{
			int index = 0;
			int dot = 0;
			bool done = false;
			FullNamedExpression resolved = null;
			Type type = null;
			Type recursive_type = null;
			while (index < name.Length) {
				if (name[index] == '[') {
					int open = index;
					int braces = 1;
					do {
						index++;
						if (name[index] == '[')
							braces++;
						else if (name[index] == ']')
							braces--;
					} while (braces > 0);
					recursive_type = TypeLookup (ec, name.Substring (open + 1, index - open - 1));
					if (recursive_type == null || (recursive_type == typeof(UnexpectedType)))
						return recursive_type;
				}
				else {
					if (name[index] == ',')
						done = true;
					else if ((name[index] == '.' && !done) || (index == name.Length && name[0] != '[')) {
						string substring = name.Substring(dot, index - dot);

						if (resolved == null)
							resolved = RootNamespace.Global.Lookup (ec.DeclContainer, substring, Location.Null);
						else if (resolved is Namespace)
						    resolved = (resolved as Namespace).Lookup (ec.DeclContainer, substring, Location.Null);
						else if (type != null)
							type = TypeManager.GetNestedType (type, substring);
						else
							return null;

						if (resolved == null)
							return null;
						else if (type == null && resolved is TypeExpr)
							type = resolved.Type;

						dot = index + 1;
					}
				}
				index++;
			}
			if (name[0] != '[') {
				string substring = name.Substring(dot, index - dot);

				if (type != null)
					return TypeManager.GetNestedType (type, substring);
				
				if (resolved != null) {
					resolved = (resolved as Namespace).Lookup (ec.DeclContainer, substring, Location.Null);
					if (resolved is TypeExpr)
						return resolved.Type;
					
					if (resolved == null)
						return null;
					
					resolved.Error_UnexpectedKind (ec.DeclContainer, "type", loc);
					return typeof (UnexpectedType);
				}
				else
					return null;
			}
			else
				return recursive_type;
			}
Example #51
0
		// <summary>
		//   Resolve is used in method definitions
		// </summary>
		public virtual Type Resolve (IResolveContext ec)
		{
			// HACK: to resolve attributes correctly
			this.resolve_context = ec;

			if (parameter_type != null)
				return parameter_type;

			TypeExpr texpr = TypeName.ResolveAsTypeTerminal (ec, false);
			if (texpr == null)
				return null;

			parameter_type = texpr.Type;

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

#if GMCS_SOURCE
			TypeParameterExpr tparam = texpr as TypeParameterExpr;
			if (tparam != null) {
				return parameter_type;
			}
#endif

			if ((parameter_type.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
				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) {
				Report.Error (1103, Location, "The type of extension method cannot be `{0}'",
					TypeManager.CSharpName (parameter_type));
			}

			return parameter_type;
		}
Example #52
0
		public TypeExpr ResolveAsBaseTerminal (IResolveContext ec, bool silent)
		{
			int errors = Report.Errors;

			FullNamedExpression fne = ResolveAsTypeStep (ec, silent);

			if (fne == null)
				return null;
				
			TypeExpr te = fne as TypeExpr;				
			if (te == null) {
				if (!silent && errors == Report.Errors)
					fne.Error_UnexpectedKind (null, "type", loc);
				return null;
			}

			if (!te.CheckAccessLevel (ec.GenericDeclContainer)) {
				Report.SymbolRelatedToPreviousError (te.Type);
				ErrorIsInaccesible (loc, TypeManager.CSharpName (te.Type));
				return null;
			}

			te.loc = loc;
			return te;
		}
Example #53
0
		protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
		{
			TypeExpr lexpr = left.ResolveAsTypeTerminal (ec, false);
			if (lexpr == null)
				return null;

			Type ltype = lexpr.Type;
#if GMCS_SOURCE
			if ((dim.Length > 0) && (dim [0] == '?')) {
				TypeExpr nullable = new Nullable.NullableType (lexpr, loc);
				if (dim.Length > 1)
					nullable = new ComposedCast (nullable, dim.Substring (1), loc);
				return nullable.ResolveAsTypeTerminal (ec, false);
			}
#endif

			if (dim == "*" && !TypeManager.VerifyUnManaged (ltype, loc))
				return null;

			if (dim.Length != 0 && dim [0] == '[') {
				if (TypeManager.IsSpecialType (ltype)) {
					Report.Error (611, loc, "Array elements cannot be of type `{0}'", TypeManager.CSharpName (ltype));
					return null;
				}

				if ((ltype.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
					Report.SymbolRelatedToPreviousError (ltype);
					Report.Error (719, loc, "Array elements cannot be of static type `{0}'", 
						TypeManager.CSharpName (ltype));
				}
			}

			if (dim != "")
				type = TypeManager.GetConstructedType (ltype, dim);
			else
				type = ltype;

			if (type == null)
				throw new InternalErrorException ("Couldn't create computed type " + ltype + dim);

			if (type.IsPointer && !ec.IsInUnsafeScope){
				UnsafeError (loc);
			}

			eclass = ExprClass.Type;
			return this;
		}
Example #54
0
		protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
		{
			Type t = TypeLookup (ec, name);
			if (t == null) {
				NamespaceEntry.Error_NamespaceNotFound (loc, name);
				return null;
			}
			if (t == typeof(UnexpectedType))
				return null;
			type = t;
			return this;
		}
Example #55
0
		protected abstract TypeExpr DoResolveAsTypeStep (IResolveContext ec);
Example #56
0
		protected override TypeExpr ResolveAsTypeTerminal (Expression expr, IResolveContext ec, bool silent)
		{
			try {
				Enter ();
				return base.ResolveAsTypeTerminal (expr, ec, silent);
			}
			finally {
				Leave ();
			}
		}
Example #57
0
		FullNamedExpression ResolveNested (IResolveContext ec, Type t)
		{
			if (!TypeManager.IsGenericTypeDefinition (t) && !TypeManager.IsGenericType (t))
				return null;

			DeclSpace ds = ec.DeclContainer;
			while (ds != null && !IsNestedChild (t, ds.TypeBuilder))
				ds = ds.Parent;

			if (ds == null)
				return null;

			Type[] gen_params = TypeManager.GetTypeArguments (t);

			int arg_count = targs != null ? targs.Count : 0;

			for (; (ds != null) && ds.IsGeneric; ds = ds.Parent) {
				if (arg_count + ds.CountTypeParameters == gen_params.Length) {
					TypeArguments new_args = new TypeArguments ();
					foreach (TypeParameter param in ds.TypeParameters)
						new_args.Add (new TypeParameterExpr (param, loc));

					if (targs != null)
						new_args.Add (targs);

					return new GenericTypeExpr (t, new_args, loc);
				}
			}

			return null;
		}
Example #58
0
		protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
		{
			return this;
		}
Example #59
0
		protected virtual TypeExpr ResolveAsTypeTerminal (Expression expr, IResolveContext ec, bool silent)
		{
			return expr.ResolveAsTypeTerminal (ec, silent);
		}
Example #60
0
		public override FullNamedExpression ResolveAsTypeStep (IResolveContext ec, bool silent)
		{
			FullNamedExpression fne = ec.GenericDeclContainer.LookupGeneric (Name, loc);
			if (fne != null)
				return fne.ResolveAsTypeStep (ec, silent);

			int errors = Report.Errors;
			fne = ec.DeclContainer.LookupNamespaceOrType (Name, loc, /*ignore_cs0104=*/ false);

			if (fne != null) {
				if (fne.Type == null)
					return fne;

				FullNamedExpression nested = ResolveNested (ec, fne.Type);
				if (nested != null)
					return nested.ResolveAsTypeStep (ec, false);

				if (targs != null) {
					GenericTypeExpr ct = new GenericTypeExpr (fne.Type, targs, loc);
					return ct.ResolveAsTypeStep (ec, false);
				}

				return fne;
			}

			if (silent || errors != Report.Errors)
				return null;

			Error_TypeOrNamespaceNotFound (ec);
			return null;
		}