Beispiel #1
0
        public ActionResult Edit(int recurringOrderId)
        {
            var customer = HttpContext.GetCustomer();

            var billingAddress = TypeConversions.ConvertToAddressViewModel(
                customer.PrimaryBillingAddress,
                customer);

            var countries = AddressSelectListBuilder.BuildCountrySelectList(billingAddress.Country);
            var states    = AddressSelectListBuilder.BuildStateSelectList(countries.SelectedValue.ToString(), billingAddress.State);

            var address = new AddressDetailViewModel(
                address: billingAddress,
                residenceTypeOptions: AddressSelectListBuilder.BuildResidenceTypeSelectList(billingAddress.ResidenceType.ToString()),
                stateOptions: states,
                countryOptions: countries,
                showCompanyField: AddressSettings.ShowCompanyField,
                showNickName: AddressSettings.ShowNickName,
                showSuite: AddressSettings.ShowSuite,
                showResidenceTypeField: true,
                showPostalCodeLookup: PostalCodeLookupProvider.IsEnabled(billingAddress.Country),
                returnUrl: string.Empty,
                header: AddressHeaderProvider.GetHeaderText(billingAddress.Id, AddressTypes.Billing));

            return(View(ControllerHelper.BuildRecurringOrderEditViewModel(
                            recurringOrderId: recurringOrderId,
                            address: address,
                            creditCard: new CreditCardViewModel(),
                            customer: customer)));
        }
        /// <summary>
        /// Return the extension method in reduced form if the extension method
        /// is applicable, and satisfies type parameter constraints, based on the
        /// "this" argument type. Otherwise, returns null.
        /// </summary>
        public static MethodSymbol Create(MethodSymbol method, TypeSymbol receiverType)
        {
            Debug.Assert(method.IsExtensionMethod && method.MethodKind != MethodKind.ReducedExtension);
            Debug.Assert(method.ParameterCount > 0);
            Debug.Assert((object)receiverType != null);

            HashSet <DiagnosticInfo> useSiteDiagnostics = null;

            method = InferExtensionMethodTypeArguments(method, receiverType, ref useSiteDiagnostics);
            if ((object)method == null)
            {
                return(null);
            }

            var conversions = new TypeConversions(method.ContainingAssembly.CorLibrary);
            var conversion  = conversions.ConvertExtensionMethodThisArg(method.Parameters[0].Type, receiverType, ref useSiteDiagnostics);

            if (!conversion.Exists)
            {
                return(null);
            }

            if (useSiteDiagnostics != null)
            {
                foreach (var diag in useSiteDiagnostics)
                {
                    if (diag.Severity == DiagnosticSeverity.Error)
                    {
                        return(null);
                    }
                }
            }

            return(Create(method));
        }
Beispiel #3
0
        protected override void CheckInterfaces(DiagnosticBag diagnostics)
        {
            // Check declared interfaces and all base interfaces. This is necessary
            // since references to all interfaces will be emitted to metadata
            // and it's possible to define derived interfaces with weaker
            // constraints than the base interfaces, at least in metadata.
            var interfaces = this.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics;

            if (interfaces.IsEmpty)
            {
                // nothing to verify
                return;
            }

            // Check constraints on the first declaration with explicit bases.
            var singleDeclaration = this.FirstDeclarationWithExplicitBases();

            if (singleDeclaration != null)
            {
                var corLibrary  = this.ContainingAssembly.CorLibrary;
                var conversions = new TypeConversions(corLibrary);
                var location    = singleDeclaration.NameLocation;

                foreach (var pair in interfaces)
                {
                    MultiDictionary <NamedTypeSymbol, NamedTypeSymbol> .ValueSet set = pair.Value;

                    foreach (var @interface in set)
                    {
                        @interface.CheckAllConstraints(DeclaringCompilation, conversions, location, diagnostics);
                    }

                    if (set.Count > 1)
                    {
                        NamedTypeSymbol other = pair.Key;
                        foreach (var @interface in set)
                        {
                            if ((object)other == @interface)
                            {
                                continue;
                            }

                            Debug.Assert(!other.Equals(@interface, TypeCompareKind.ConsiderEverything));

                            if (other.Equals(@interface, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes))
                            {
                                if (!other.Equals(@interface, TypeCompareKind.ObliviousNullableModifierMatchesAny))
                                {
                                    diagnostics.Add(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, location, @interface, this);
                                }
                            }
                            else if (other.Equals(@interface, TypeCompareKind.IgnoreTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes))
                            {
                                diagnostics.Add(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, location, @interface, other, this);
                            }
                        }
                    }
                }
            }
        }
Beispiel #4
0
        public static MethodSymbol Create(MethodSymbol method, TypeSymbol receiverType, CSharpCompilation compilation)
        {
            Debug.Assert(method.IsExtensionMethod && method.MethodKind != MethodKind.ReducedExtension);
            Debug.Assert(method.ParameterCount > 0);
            Debug.Assert((object)receiverType != null);

            var useSiteInfo = CompoundUseSiteInfo <AssemblySymbol> .DiscardedDependecies;

            method = InferExtensionMethodTypeArguments(method, receiverType, compilation, ref useSiteInfo);
            if ((object)method == null)
            {
                return(null);
            }

            var conversions = new TypeConversions(method.ContainingAssembly.CorLibrary);
            var conversion  = conversions.ConvertExtensionMethodThisArg(method.Parameters[0].Type, receiverType, ref useSiteInfo);

            if (!conversion.Exists)
            {
                return(null);
            }

            if (useSiteInfo.Diagnostics != null)
            {
                foreach (var diag in useSiteInfo.Diagnostics)
                {
                    if (diag.Severity == DiagnosticSeverity.Error)
                    {
                        return(null);
                    }
                }
            }

            return(Create(method));
        }
Beispiel #5
0
        public async Task <IQueryable <GooglePlaceModel.Result> > GetTopDestinations()
        {
            var singleTracksApi = _singleTracksApi;

            var request = (HttpWebRequest)WebRequest.Create(singleTracksApi.AllUsaPlaces.ToString());

            request.Accept = "application/json";
            request.Headers["X-Mashape-Key"] = singleTracksApi.X_Mashape_Key.ToString();

            WebResponse response = await request.GetResponseAsync();

            var raw = String.Empty;

            using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8, true, 1024, true))
            {
                raw = reader.ReadToEnd();
            }
            var allresults = JsonConvert.DeserializeObject <DestinationModel.RootObject>(raw);

            var googlePlaces = new List <GooglePlaceModel.Result>();

            googlePlaces = await TypeConversions.ToGooglePlaceFormat(allresults.places);

            return(googlePlaces.AsQueryable());
        }
Beispiel #6
0
        protected override void CheckInterfaces(DiagnosticBag diagnostics)
        {
            // Check declared interfaces and all base interfaces. This is necessary
            // since references to all interfaces will be emitted to metadata
            // and it's possible to define derived interfaces with weaker
            // constraints than the base interfaces, at least in metadata.
            var interfaces = this.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics;

            if (interfaces.IsEmpty)
            {
                // nothing to verify
                return;
            }

            // Check constraints on the first declaration with explicit bases.
            var singleDeclaration = this.FirstDeclarationWithExplicitBases();

            if (singleDeclaration != null)
            {
                var corLibrary  = this.ContainingAssembly.CorLibrary;
                var conversions = new TypeConversions(corLibrary);
                var location    = singleDeclaration.NameLocation;

                foreach (var @interface in interfaces)
                {
                    @interface.CheckAllConstraints(conversions, location, diagnostics);
                }
            }
        }
Beispiel #7
0
        protected override void CheckBase(DiagnosticBag diagnostics)
        {
            var localBase = this.BaseTypeNoUseSiteDiagnostics;

            if ((object)localBase == null)
            {
                // nothing to verify
                return;
            }

            // you need to know all bases before you can ask this question... (asking this causes a cycle)
            if (this.IsGenericType && !localBase.IsErrorType() && this.DeclaringCompilation.IsAttributeType(localBase))
            {
                var baseLocation = FindBaseRefSyntax(localBase);
                Debug.Assert(baseLocation != null);

                // A generic type cannot derive from '{0}' because it is an attribute class
                diagnostics.Add(ErrorCode.ERR_GenericDerivingFromAttribute, baseLocation, localBase);
            }

            // Check constraints on the first declaration with explicit bases.
            var singleDeclaration = this.FirstDeclarationWithExplicitBases();

            if (singleDeclaration != null)
            {
                var corLibrary  = this.ContainingAssembly.CorLibrary;
                var conversions = new TypeConversions(corLibrary);
                var location    = singleDeclaration.NameLocation;

                localBase.CheckAllConstraints(conversions, location, diagnostics);
            }
        }
        /// <summary>
        /// Return the extension method in reduced form if the extension method
        /// is applicable, and satisfies type parameter constraints, based on the
        /// "this" argument type. Otherwise, returns null.
        /// </summary>
        public static MethodSymbol Create(MethodSymbol method, TypeSymbol receiverType, Compilation compilation)
        {
            Debug.Assert(method.IsExtensionMethod && method.MethodKind != MethodKind.ReducedExtension);
            Debug.Assert(method.ParameterCount > 0);
            Debug.Assert((object)receiverType != null);

            HashSet<DiagnosticInfo> useSiteDiagnostics = null;

            method = method.InferExtensionMethodTypeArguments(receiverType, compilation, ref useSiteDiagnostics);
            if ((object)method == null)
            {
                return null;
            }

            var conversions = new TypeConversions(method.ContainingAssembly.CorLibrary);
            var conversion = conversions.ConvertExtensionMethodThisArg(method.Parameters[0].Type, receiverType, ref useSiteDiagnostics);
            if (!conversion.Exists)
            {
                return null;
            }

            if (useSiteDiagnostics != null)
            {
                foreach (var diag in useSiteDiagnostics)
                {
                    if (diag.Severity == DiagnosticSeverity.Error)
                    {
                        return null;
                    }
                }
            }

            return Create(method);
        }
Beispiel #9
0
        protected override void CheckBase(DiagnosticBag diagnostics)
        {
            var localBase = this.BaseTypeNoUseSiteDiagnostics;

            if ((object)localBase == null)
            {
                // nothing to verify
                return;
            }

            Location baseLocation           = null;
            bool     baseContainsErrorTypes = localBase.ContainsErrorType();

            if (!baseContainsErrorTypes)
            {
                baseLocation = FindBaseRefSyntax(localBase);
                Debug.Assert(!this.IsClassType() || localBase.IsObjectType() || baseLocation != null);
            }

            // you need to know all bases before you can ask this question... (asking this causes a cycle)
            if (this.IsGenericType && !baseContainsErrorTypes && this.DeclaringCompilation.IsAttributeType(localBase))
            {
                // A generic type cannot derive from '{0}' because it is an attribute class
                diagnostics.Add(ErrorCode.ERR_GenericDerivingFromAttribute, baseLocation, localBase);
            }

            // Check constraints on the first declaration with explicit bases.
            var singleDeclaration = this.FirstDeclarationWithExplicitBases();

            if (singleDeclaration != null)
            {
                var corLibrary  = this.ContainingAssembly.CorLibrary;
                var conversions = new TypeConversions(corLibrary);
                var location    = singleDeclaration.NameLocation;

                localBase.CheckAllConstraints(DeclaringCompilation, conversions, location, diagnostics);
            }

            // Records can only inherit from other records or object
            if (this.IsClassType() && !localBase.IsObjectType() && !baseContainsErrorTypes)
            {
                HashSet <DiagnosticInfo> useSiteDiagnostics = null;

                if (declaration.Kind == DeclarationKind.Record)
                {
                    if (SynthesizedRecordClone.FindValidCloneMethod(localBase, ref useSiteDiagnostics) is null ||
                        SynthesizedRecordPrintMembers.FindValidPrintMembersMethod(localBase, DeclaringCompilation) is null)
                    {
                        diagnostics.Add(ErrorCode.ERR_BadRecordBase, baseLocation);
                    }
                }
                else if (SynthesizedRecordClone.FindValidCloneMethod(localBase, ref useSiteDiagnostics) is object)
                {
                    diagnostics.Add(ErrorCode.ERR_BadInheritanceFromRecord, baseLocation);
                }

                diagnostics.Add(baseLocation, useSiteDiagnostics);
            }
        }
Beispiel #10
0
        private void ProcessLd0(XILSInstr i)
        {
            var targetConst = TypeConversions.ConvertValue(0, i.ResultTypes[0]);

            Emit(new XILSInstr(DefaultInstructionSet.Instance.LdConst(targetConst),
                               RemapPreds(i.Preds),
                               i.OperandTypes, i.ResultTypes));
        }
Beispiel #11
0
        public static object DefaultEval(ArrayRef arrayRef, IEvaluator eval)
        {
            Array array = (Array)arrayRef.ArrayExpr.Eval(eval);

            long[] indices = arrayRef.Indices.Select(i =>
                                                     TypeConversions.ToLong(i.Eval(eval))).ToArray();
            return(array.GetValue(indices));
        }
 private static bool IsMOne(Expression e)
 {
     return(e.IsConst() &&
            object.Equals(
                TypeConversions.ConvertValue(
                    e.Eval(DefaultEvaluator.DefaultConstEvaluator),
                    typeof(double)), -1.0));
 }
        protected override void CheckBase(BindingDiagnosticBag diagnostics)
        {
            var localBase = this.BaseTypeNoUseSiteDiagnostics;

            if ((object)localBase == null)
            {
                // nothing to verify
                return;
            }

            Location baseLocation           = null;
            bool     baseContainsErrorTypes = localBase.ContainsErrorType();

            if (!baseContainsErrorTypes)
            {
                baseLocation = FindBaseRefSyntax(localBase);
                Debug.Assert(!this.IsClassType() || localBase.IsObjectType() || baseLocation != null);
            }

            // you need to know all bases before you can ask this question... (asking this causes a cycle)
            if (this.IsGenericType && !baseContainsErrorTypes && this.DeclaringCompilation.IsAttributeType(localBase))
            {
                MessageID.IDS_FeatureGenericAttributes.CheckFeatureAvailability(diagnostics, this.DeclaringCompilation, baseLocation);
            }

            // Check constraints on the first declaration with explicit bases.
            var singleDeclaration = this.FirstDeclarationWithExplicitBases();

            if (singleDeclaration != null)
            {
                var corLibrary  = this.ContainingAssembly.CorLibrary;
                var conversions = new TypeConversions(corLibrary);
                var location    = singleDeclaration.NameLocation;

                localBase.CheckAllConstraints(DeclaringCompilation, conversions, location, diagnostics);
            }

            // Records can only inherit from other records or object
            if (this.IsClassType() && !localBase.IsObjectType() && !baseContainsErrorTypes)
            {
                var useSiteInfo = new CompoundUseSiteInfo <AssemblySymbol>(diagnostics, ContainingAssembly);

                if (declaration.Kind == DeclarationKind.Record)
                {
                    if (SynthesizedRecordClone.FindValidCloneMethod(localBase, ref useSiteInfo) is null)
                    {
                        diagnostics.Add(ErrorCode.ERR_BadRecordBase, baseLocation);
                    }
                }
                else if (SynthesizedRecordClone.FindValidCloneMethod(localBase, ref useSiteInfo) is object)
                {
                    diagnostics.Add(ErrorCode.ERR_BadInheritanceFromRecord, baseLocation);
                }

                diagnostics.Add(baseLocation, useSiteInfo);
            }
        }
Beispiel #14
0
        public static CachedACDItem GetTrinityItem(ACDItem item)
        {
            try
            {
                if (!item.IsValid)
                {
                    return(default(CachedACDItem));
                }

                CachedACDItem cItem = new CachedACDItem(item.Stats)
                {
                    AcdItem           = item,
                    InternalName      = item.InternalName,
                    RealName          = item.Name,
                    Level             = item.Level,
                    Quality           = item.GetItemQuality(),
                    GoldAmount        = item.Gold,
                    BalanceId         = item.GameBalanceId,
                    DynamicId         = item.AnnId,
                    ActorSnoId        = item.ActorSnoId,
                    OneHanded         = item.IsOneHand,
                    TwoHanded         = item.IsTwoHand,
                    DyeType           = item.DyeType,
                    ItemType          = item.GetItemType(),
                    BaseType          = item.ItemBaseType,
                    FollowerType      = item.FollowerSpecialType,
                    IsUnidentified    = item.IsUnidentified,
                    ItemStackQuantity = item.ItemStackQuantity,
                    InventoryRow      = item.InventoryRow,
                    InventoryColumn   = item.InventoryColumn,
                    ItemLink          = item.ItemLink,
                    GameBalanceId     = item.GameBalanceId,
                    TrinityItemType   = TypeConversions.DetermineItemType(item.InternalName, item.GetItemType(), item.FollowerSpecialType),
                    IsAncient         = item.GetAttribute <int>(ActorAttributeType.AncientRank) > 0,
                    InventorySlot     = item.InventorySlot,
                };

                TrinityItemBaseType trinityItemBaseType = TypeConversions
                                                          .GetTrinityItemBaseType(
                    TypeConversions.DetermineItemType(
                        item.InternalName,
                        item.GetItemType(),
                        item.FollowerSpecialType));

                cItem.TrinityItemBaseType = trinityItemBaseType;
                cItem.IsEquipment         = GetIsEquipment(trinityItemBaseType);
                cItem.IsSalvageable       = GetIsSalvageable(cItem);
                cItem.IsClassItem         = GetIsClassItem(cItem);
                cItem.IsOffHand           = GetIsOffhand(cItem);
                return(cItem);
            }
            catch (Exception ex)
            {
                Core.Logger.Error("Error getting TrinityItem {0}", ex.Message);
                return(default(CachedACDItem));
            }
        }
Beispiel #15
0
        public IEnumerable <AddressViewModel> GetCustomerAddresses(Customer customer)
        {
            var addressCollection = new Addresses();

            addressCollection.LoadCustomer(customer.CustomerID);

            return(addressCollection
                   .Cast <Address>()
                   .Select(address => TypeConversions.ConvertToAddressViewModel(address, customer)));
        }
Beispiel #16
0
        internal void CheckConstraints(DiagnosticBag diagnostics)
        {
            var target = this.Target as TypeSymbol;

            if ((object)target != null && _locations.Length > 0)
            {
                var corLibrary  = this.ContainingAssembly.CorLibrary;
                var conversions = new TypeConversions(corLibrary);
                target.CheckAllConstraints(DeclaringCompilation, conversions, _locations[0], diagnostics);
            }
        }
 public static IVRange ToRange(object obj)
 {
     if (obj is IVRange)
     {
         return((IVRange)obj);
     }
     else
     {
         long v = TypeConversions.ToLong(obj);
         return(new IVRange(v, v));
     }
 }
Beispiel #18
0
        public AddressViewModel GetCustomerAddress(int?addressId, Customer customer)
        {
            var address = new Address();

            if (addressId.HasValue)
            {
                address.LoadFromDB(addressId.Value);
                if (address.CustomerID != customer.CustomerID)
                {
                    throw new HttpException(403, "Forbidden");
                }
            }

            return(TypeConversions.ConvertToAddressViewModel(address, customer));
        }
Beispiel #19
0
        private void ProcessLoadConstant(XILSInstr i)
        {
            var rTypes = i.ResultTypes;

            var constant       = i.StaticOperand;
            var targetConstant = TypeConversions.ConvertValue(constant, rTypes[0]);

            var inew = new XILSInstr(
                DefaultInstructionSet.Instance.LdConst(targetConstant),
                RemapPreds(i.Preds),
                new TypeDescriptor[0],
                rTypes);

            Emit(inew);
        }
Beispiel #20
0
        public ActionResult Edit(RecurringOrderPostViewModel model)
        {
            var customer = HttpContext.GetCustomer();

            if (!ModelState.IsValid)
            {
                return(View(ActionNames.Edit, ControllerHelper.BuildRecurringOrderEditViewModel(
                                recurringOrderId: model.RecurringOrderId,
                                address: new AddressDetailViewModel(
                                    address: model.Address,
                                    residenceTypeOptions: AddressSelectListBuilder.BuildResidenceTypeSelectList(model.Address.ResidenceType.ToString()),
                                    stateOptions: AddressSelectListBuilder.BuildStateSelectList(model.Address.Country, model.Address.State),
                                    countryOptions: AddressSelectListBuilder.BuildCountrySelectList(model.Address.Country),
                                    showCompanyField: AddressSettings.ShowCompanyField,
                                    showNickName: AddressSettings.ShowNickName,
                                    showSuite: AddressSettings.ShowSuite,
                                    showResidenceTypeField: true,
                                    showPostalCodeLookup: PostalCodeLookupProvider.IsEnabled(model.Address.Country),
                                    returnUrl: string.Empty,
                                    header: AddressHeaderProvider.GetHeaderText(model.Address.Id, AddressTypes.Billing)),
                                creditCard: model.CreditCard,
                                customer: customer)));
            }

            if (!customer.Owns.RecurringOrder(model.RecurringOrderId))
            {
                throw new HttpException(403, "Forbidden");
            }

            var result = ControllerHelper.UpdateRecurringOrder(
                recurringOrderId: model.RecurringOrderId,
                address: TypeConversions.ConvertToAddress(model.Address, customer),
                creditCard: model.CreditCard,
                customer: customer);

            switch (result.Status)
            {
            case RecurringOrderActionStatus.Failure:
                NoticeProvider.PushNotice(result.Message, NoticeType.Failure);
                break;

            default:
            case RecurringOrderActionStatus.Success:
                break;
            }

            return(RedirectToAction(ActionNames.Index));
        }
        protected override void CheckInterfaces(DiagnosticBag diagnostics)
        {
            // Check declared interfaces and all base interfaces. This is necessary
            // since references to all interfaces will be emitted to metadata
            // and it's possible to define derived interfaces with weaker
            // constraints than the base interfaces, at least in metadata.
            var interfaces = this.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics;

            if (interfaces.IsEmpty)
            {
                // nothing to verify
                return;
            }

            // Check constraints on the first declaration with explicit bases.
            var singleDeclaration = this.FirstDeclarationWithExplicitBases();

            if (singleDeclaration != null)
            {
                var corLibrary  = this.ContainingAssembly.CorLibrary;
                var conversions = new TypeConversions(corLibrary);
                var location    = singleDeclaration.NameLocation;

                foreach (var @interface in interfaces)
                {
                    @interface.CheckAllConstraints(conversions, location, diagnostics);
                }

                if (interfaces.Count > 1)
                {
                    var seenInterfaces = new Dictionary <NamedTypeSymbol, NamedTypeSymbol>(EqualsIgnoringComparer.InstanceIgnoringTupleNames);
                    foreach (var @interface in interfaces)
                    {
                        NamedTypeSymbol other;
                        if (seenInterfaces.TryGetValue(@interface, out other))
                        {
                            diagnostics.Add(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, location, @interface, other, this);
                        }
                        else
                        {
                            seenInterfaces.Add(@interface, @interface);
                        }
                    }
                }
            }
        }
        public async Task <ActionResult> CsvDestination()
        {
            var content = await _placeService.GetCsvFormat();

            string csv = TypeConversions.jsonToCSV(content, ",");

            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);

            result.Content = new StringContent(csv);
            result.Content.Headers.ContentType        = new MediaTypeHeaderValue("text/csv");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "destinations.csv"
            };

            return(View(result));
        }
Beispiel #23
0
        /// <summary>
        /// Check constraints of generic types referenced in constraint types. For instance,
        /// with "interface I&lt;T&gt; where T : I&lt;T&gt; {}", check T satisfies constraints
        /// on I&lt;T&gt;. Those constraints are not checked when binding ConstraintTypes
        /// since ConstraintTypes has not been set on I&lt;T&gt; at that point.
        /// </summary>
        private void CheckConstraintTypeConstraints(DiagnosticBag diagnostics)
        {
            var constraintTypes = this.ConstraintTypesNoUseSiteDiagnostics;

            if (constraintTypes.Length == 0)
            {
                return;
            }

            var corLibrary  = this.ContainingAssembly.CorLibrary;
            var conversions = new TypeConversions(corLibrary);
            var location    = _locations[0];

            // @t-mawind
            //   A concept parameter with no constraint types is pointless, so
            //   don't allow it.
            if (WasDeclaredImplicit() && constraintTypes.IsEmpty)
            {
                diagnostics.Add(ErrorCode.ERR_NoConstraintsOnImplicitParam, location, Name);
            }

            foreach (var constraintType in constraintTypes)
            {
                // @t-mawind
                //   Concept constraints can be used if and only if this
                //   parameter has 'implicit' set.
                if (constraintType.IsConceptType() && !WasDeclaredImplicit())
                {
                    diagnostics.Add(ErrorCode.ERR_ConceptConstraintOnNonImplicitParam, location, Name, constraintType.Name);
                }
                if (!constraintType.IsConceptType() && WasDeclaredImplicit())
                {
                    diagnostics.Add(ErrorCode.ERR_NonConceptConstraintOnImplicitParam, location, Name, constraintType.Name);
                }

                HashSet <DiagnosticInfo> useSiteDiagnostics = null;
                constraintType.AddUseSiteDiagnostics(ref useSiteDiagnostics);

                if (!diagnostics.Add(location, useSiteDiagnostics))
                {
                    constraintType.CheckAllConstraints(conversions, location, diagnostics);
                }
            }
        }
Beispiel #24
0
        protected override void ProcessInstruction(XILSInstr i)
        {
            var       otypes = i.OperandTypes.Select(t => t.Equals(GenuineType) ? ReplacementType : t).ToArray();
            var       rtypes = i.ResultTypes.Select(t => t.Equals(GenuineType) ? ReplacementType : t).ToArray();
            XILSInstr inew;

            if (i.Name == InstructionCodes.LdConst &&
                i.StaticOperand != null &&
                i.StaticOperand.GetType().Equals(GenuineType.CILType))
            {
                var cnew = DefaultInstructionSet.Instance.LdConst(TypeConversions.ConvertValue(i.StaticOperand, ReplacementType.CILType));
                inew = cnew.CreateStk(i.Preds, otypes, rtypes);
            }
            else
            {
                inew = i.Command.CreateStk(i.Preds, otypes, rtypes);
            }
            base.ProcessInstruction(inew);
        }
Beispiel #25
0
        public int UpdateAddress(AddressViewModel address, Customer customer)
        {
            var adnsfAddress = TypeConversions.ConvertToAddress(address, customer);

            if (address.Id.HasValue)
            {
                if (!Customer.OwnsThisAddress(customer.CustomerID, (int)address.Id))
                {
                    throw new HttpException(403, "Forbidden");
                }

                adnsfAddress.UpdateDB();
            }
            else
            {
                adnsfAddress.InsertDB();
            }

            return(adnsfAddress.AddressID);
        }
Beispiel #26
0
        public object Div(object v1, object v2, TypeDescriptor resultType)
        {
            object oresult;

            if (TryCallIntrinsicOp("op_Division", out oresult, v1, v2))
            {
                return(oresult);
            }

            TypeDescriptor  t1   = TypeDescriptor.GetTypeOf(v1);
            TypeDescriptor  t2   = TypeDescriptor.GetTypeOf(v2);
            EResultCategory rcat = GetResultCategory(t1);

            switch (rcat)
            {
            case EResultCategory.SignedIntegral:
            {
                long l1 = TypeConversions.ToLong(v1);
                long l2 = TypeConversions.ToLong(v2);
                return(l1 / l2);
            }

            case EResultCategory.UnsignedIntegral:
            {
                ulong u1 = TypeConversions.ToULong(v1);
                ulong u2 = TypeConversions.ToULong(v2);
                return(u1 / u2);
            }

            case EResultCategory.FloatingPoint:
            {
                double d1 = TypeConversions.ToDouble(v1);
                double d2 = TypeConversions.ToDouble(v2);
                return(d1 / d2);
            }

            default:
                throw new NotImplementedException();
            }
        }
Beispiel #27
0
        internal static void DumpItemSNOReference()
        {
            string[] names  = Enum.GetNames(typeof(SNOActor));
            int[]    values = (int[])Enum.GetValues(typeof(SNOActor));
            var      toLog  = new List <string>();

            for (int i = 0; i < names.Length; i++)
            {
                var sno  = values[i];
                var name = names[i];
                var type = TypeConversions.DetermineItemType(name, ItemType.Unknown);
                if (type != TrinityItemType.Unknown || GameData.GoldSNO.Contains(sno) ||
                    GameData.ForceToItemOverrideIds.Contains(sno) || GameData.HealthGlobeSNO.Contains(sno) || Legendary.ItemIds.Contains(sno))
                {
                    toLog.Add($"{{ {sno}, TrinityItemType.{type} }}, // {name}");
                }
            }

            var path = WriteLinesToLog("ItemSNOReference.log", toLog, true);

            Core.Logger.Log("Finished Dumping Item SNO Reference to {0}", path);
        }
Beispiel #28
0
        /// <summary>
        /// Check constraints of generic types referenced in constraint types. For instance,
        /// with "interface I&lt;T&gt; where T : I&lt;T&gt; {}", check T satisfies constraints
        /// on I&lt;T&gt;. Those constraints are not checked when binding ConstraintTypes
        /// since ConstraintTypes has not been set on I&lt;T&gt; at that point.
        /// </summary>
        private void CheckConstraintTypeConstraints(DiagnosticBag diagnostics)
        {
            var constraintTypes = this.ConstraintTypesNoUseSiteDiagnostics;

            if (constraintTypes.Length == 0)
            {
                return;
            }

            var corLibrary  = this.ContainingAssembly.CorLibrary;
            var conversions = new TypeConversions(corLibrary);
            var location    = _locations[0];

            foreach (var constraintType in constraintTypes)
            {
                HashSet <DiagnosticInfo> useSiteDiagnostics = null;
                constraintType.Type.AddUseSiteDiagnostics(ref useSiteDiagnostics);

                if (!diagnostics.Add(location, useSiteDiagnostics))
                {
                    constraintType.Type.CheckAllConstraints(DeclaringCompilation, conversions, location, diagnostics);
                }
            }
        }
Beispiel #29
0
        public ActionResult Index()
        {
            var customer = HttpContext.GetCustomer();

            var shippingAddress = TypeConversions.ConvertToAddressViewModel(
                customer.PrimaryShippingAddress,
                customer);

            var countries = AddressSelectListBuilder.BuildCountrySelectList(shippingAddress.Country);
            var states    = AddressSelectListBuilder.BuildStateSelectList(countries.SelectedValue.ToString(), shippingAddress.State);

            return(View(new AddressDetailViewModel(
                            address: shippingAddress,
                            residenceTypeOptions: AddressSelectListBuilder.BuildResidenceTypeSelectList(shippingAddress.ResidenceType.ToString()),
                            stateOptions: states,
                            countryOptions: countries,
                            showCompanyField: AddressSettings.ShowCompanyField,
                            showNickName: AddressSettings.ShowNickName,
                            showSuite: AddressSettings.ShowSuite,
                            showResidenceTypeField: true,
                            showPostalCodeLookup: PostalCodeLookupProvider.IsEnabled(shippingAddress.Country),
                            returnUrl: string.Empty,
                            header: AddressHeaderProvider.GetHeaderText(shippingAddress.Id, AddressTypes.Shipping))));
        }
Beispiel #30
0
        public object LShift(object v1, object v2, TypeDescriptor resultType)
        {
            object oresult;

            if (TryCallIntrinsicOp("op_LeftShift", out oresult, v1, v2))
            {
                return(oresult);
            }

            TypeDescriptor  t1   = TypeDescriptor.GetTypeOf(v1);
            TypeDescriptor  t2   = TypeDescriptor.GetTypeOf(v2);
            EResultCategory rcat = GetResultCategory(t1);

            switch (rcat)
            {
            case EResultCategory.SignedIntegral:
            {
                long v = TypeConversions.ToLong(v1);
                int  s = (int)TypeConversions.ToLong(v2);
                return(v << s);
            }

            case EResultCategory.UnsignedIntegral:
            {
                ulong v = TypeConversions.ToULong(v1);
                int   s = (int)TypeConversions.ToLong(v2);
                return(v << s);
            }

            case EResultCategory.FloatingPoint:
                throw new ArgumentException();

            default:
                throw new NotImplementedException();
            }
        }
        protected override void CheckBase(DiagnosticBag diagnostics)
        {
            var localBase = this.BaseTypeNoUseSiteDiagnostics;

            if ((object)localBase == null)
            {
                // nothing to verify
                return;
            }

            // you need to know all bases before you can ask this question... (asking this causes a cycle)
            if (this.IsGenericType && !localBase.IsErrorType() && this.DeclaringCompilation.IsAttributeType(localBase))
            {
                var baseLocation = FindBaseRefSyntax(localBase);
                Debug.Assert(baseLocation != null);

                // A generic type cannot derive from '{0}' because it is an attribute class
                diagnostics.Add(ErrorCode.ERR_GenericDerivingFromAttribute, baseLocation, localBase);
            }

            // Check constraints on the first declaration with explicit bases.
            var singleDeclaration = this.FirstDeclarationWithExplicitBases();
            if (singleDeclaration != null)
            {
                var corLibrary = this.ContainingAssembly.CorLibrary;
                var conversions = new TypeConversions(corLibrary);
                var location = singleDeclaration.NameLocation;

                localBase.CheckAllConstraints(conversions, location, diagnostics);
            }
        }
        internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken)
        {
            while (true)
            {
                cancellationToken.ThrowIfCancellationRequested();
                var incompletePart = _state.NextIncompletePart;
                switch (incompletePart)
                {
                    case CompletionPart.Attributes:
                        GetAttributes();
                        break;

                    case CompletionPart.Type:
                        {
                            var diagnostics = DiagnosticBag.GetInstance();
                            var conversions = new TypeConversions(this.ContainingAssembly.CorLibrary);
                            this.Type.CheckAllConstraints(conversions, _location, diagnostics);

                            if (this.Type.IsRestrictedType())
                            {
                                diagnostics.Add(ErrorCode.ERR_FieldCantBeRefAny, this.CSharpSyntaxNode.Type.Location, this.Type);
                            }

                            if (_state.NotePartComplete(CompletionPart.Type))
                            {
                                this.AddDeclarationDiagnostics(diagnostics);
                            }

                            diagnostics.Free();
                        }
                        break;

                    case CompletionPart.Parameters:
                        {
                            var parameters = this.Parameters;
                            if (parameters.Length > 0)
                            {
                                var diagnostics = DiagnosticBag.GetInstance();
                                var conversions = new TypeConversions(this.ContainingAssembly.CorLibrary);
                                foreach (var parameter in this.Parameters)
                                {
                                    parameter.ForceComplete(locationOpt, cancellationToken);
                                    parameter.Type.CheckAllConstraints(conversions, parameter.Locations[0], diagnostics);
                                }

                                if (_state.NotePartComplete(CompletionPart.Parameters))
                                {
                                    this.AddDeclarationDiagnostics(diagnostics);
                                    DeclaringCompilation.SymbolDeclaredEvent(this);
                                }

                                diagnostics.Free();
                            }
                            else
                            {
                                if (_state.NotePartComplete(CompletionPart.Parameters))
                                {
                                    DeclaringCompilation.SymbolDeclaredEvent(this);
                                }
                            }
                        }
                        break;

                    case CompletionPart.None:
                        return;

                    default:
                        // any other values are completion parts intended for other kinds of symbols
                        _state.NotePartComplete(CompletionPart.All & ~CompletionPart.PropertySymbolAll);
                        break;
                }

                _state.SpinWaitComplete(incompletePart, cancellationToken);
            }
        }
Beispiel #33
0
        // Based on SymbolLoader::ResolveBounds.
        public static TypeParameterBounds ResolveBounds(
            this TypeParameterSymbol typeParameter,
            AssemblySymbol corLibrary,
            ConsList<TypeParameterSymbol> inProgress,
            ImmutableArray<TypeSymbol> constraintTypes,
            bool inherited,
            CSharpCompilation currentCompilation,
            ArrayBuilder<TypeParameterDiagnosticInfo> diagnosticsBuilder,
            ref ArrayBuilder<TypeParameterDiagnosticInfo> useSiteDiagnosticsBuilder)
        {
            Debug.Assert(currentCompilation == null || typeParameter.IsFromCompilation(currentCompilation));

            ImmutableArray<NamedTypeSymbol> interfaces;

            NamedTypeSymbol effectiveBaseClass = corLibrary.GetSpecialType(typeParameter.HasValueTypeConstraint ? SpecialType.System_ValueType : SpecialType.System_Object);
            TypeSymbol deducedBaseType = effectiveBaseClass;
            DynamicTypeEraser dynamicEraser = null;

            if (constraintTypes.Length == 0)
            {
                interfaces = ImmutableArray<NamedTypeSymbol>.Empty;
            }
            else
            {
                var constraintTypesBuilder = ArrayBuilder<TypeSymbol>.GetInstance();
                var interfacesBuilder = ArrayBuilder<NamedTypeSymbol>.GetInstance();
                var conversions = new TypeConversions(corLibrary);
                HashSet<DiagnosticInfo> useSiteDiagnostics = null;

                // Resolve base types, determine the effective base class and
                // interfaces, and filter out any constraint types that cause cycles.
                foreach (var constraintType in constraintTypes)
                {
                    NamedTypeSymbol constraintEffectiveBase;
                    TypeSymbol constraintDeducedBase;

                    switch (constraintType.TypeKind)
                    {
                        case TypeKind.Dynamic:
                            Debug.Assert(inherited || currentCompilation == null);
                            continue;

                        case TypeKind.TypeParameter:
                            {
                                var containingSymbol = typeParameter.ContainingSymbol;
                                var constraintTypeParameter = (TypeParameterSymbol)constraintType;
                                ConsList<TypeParameterSymbol> constraintsInProgress;

                                if (constraintTypeParameter.ContainingSymbol == containingSymbol)
                                {
                                    // The constraint type parameter is from the same containing type or method.
                                    if (inProgress.ContainsReference(constraintTypeParameter))
                                    {
                                        // "Circular constraint dependency involving '{0}' and '{1}'"
                                        diagnosticsBuilder.Add(new TypeParameterDiagnosticInfo(constraintTypeParameter, new CSDiagnosticInfo(ErrorCode.ERR_CircularConstraint, constraintTypeParameter, typeParameter)));
                                        continue;
                                    }

                                    constraintsInProgress = inProgress;
                                }
                                else
                                {
                                    // The constraint type parameter is from a different containing symbol so no cycle.
                                    constraintsInProgress = ConsList<TypeParameterSymbol>.Empty;
                                }

                                // Use the calculated bounds from the constraint type parameter.
                                constraintEffectiveBase = constraintTypeParameter.GetEffectiveBaseClass(constraintsInProgress);
                                constraintDeducedBase = constraintTypeParameter.GetDeducedBaseType(constraintsInProgress);
                                AddInterfaces(interfacesBuilder, constraintTypeParameter.GetInterfaces(constraintsInProgress));

                                if (constraintTypeParameter.HasValueTypeConstraint && !inherited && currentCompilation != null && constraintTypeParameter.IsFromCompilation(currentCompilation))
                                {
                                    // "Type parameter '{1}' has the 'struct' constraint so '{1}' cannot be used as a constraint for '{0}'"
                                    diagnosticsBuilder.Add(new TypeParameterDiagnosticInfo(typeParameter, new CSDiagnosticInfo(ErrorCode.ERR_ConWithValCon, typeParameter, constraintTypeParameter)));
                                    continue;
                                }
                            }
                            break;

                        case TypeKind.Interface:
                        case TypeKind.Class:
                        case TypeKind.Delegate:
                            NamedTypeSymbol erasedConstraintType;

                            if (inherited || currentCompilation == null)
                            {
                                // only inherited constraints may contain dynamic
                                if (dynamicEraser == null)
                                {
                                    dynamicEraser = new DynamicTypeEraser(corLibrary.GetSpecialType(SpecialType.System_Object));
                                }

                                erasedConstraintType = (NamedTypeSymbol)dynamicEraser.EraseDynamic(constraintType);
                            }
                            else
                            {
                                Debug.Assert(!constraintType.ContainsDynamic());
                                Debug.Assert(constraintType.TypeKind != TypeKind.Delegate);

                                erasedConstraintType = (NamedTypeSymbol)constraintType;
                            }

                            if (constraintType.IsInterfaceType())
                            {
                                AddInterface(interfacesBuilder, erasedConstraintType);
                                constraintTypesBuilder.Add(constraintType);
                                continue;
                            }
                            else
                            {
                                constraintEffectiveBase = erasedConstraintType;
                                constraintDeducedBase = constraintType;
                                break;
                            }

                        case TypeKind.Struct:
                            Debug.Assert(inherited || currentCompilation == null);
                            constraintEffectiveBase = corLibrary.GetSpecialType(SpecialType.System_ValueType);
                            constraintDeducedBase = constraintType;
                            break;

                        case TypeKind.Enum:
                            Debug.Assert(inherited || currentCompilation == null);
                            constraintEffectiveBase = corLibrary.GetSpecialType(SpecialType.System_Enum);
                            constraintDeducedBase = constraintType;
                            break;

                        case TypeKind.Array:
                            Debug.Assert(inherited || currentCompilation == null);
                            constraintEffectiveBase = corLibrary.GetSpecialType(SpecialType.System_Array);
                            constraintDeducedBase = constraintType;
                            break;

                        case TypeKind.Error:
                            constraintEffectiveBase = (NamedTypeSymbol)constraintType;
                            constraintDeducedBase = constraintType;
                            break;

                        case TypeKind.Submission:
                        default:
                            throw ExceptionUtilities.UnexpectedValue(constraintType.TypeKind);
                    }

                    CheckEffectiveAndDeducedBaseTypes(conversions, constraintEffectiveBase, constraintDeducedBase);

                    constraintTypesBuilder.Add(constraintType);

                    // Determine the more encompassed of the current effective base
                    // class and the previously computed effective base class.
                    if (!deducedBaseType.IsErrorType() && !constraintDeducedBase.IsErrorType())
                    {
                        if (!IsEncompassedBy(conversions, deducedBaseType, constraintDeducedBase, ref useSiteDiagnostics))
                        {
                            if (!IsEncompassedBy(conversions, constraintDeducedBase, deducedBaseType, ref useSiteDiagnostics))
                            {
                                // "Type parameter '{0}' inherits conflicting constraints '{1}' and '{2}'"
                                diagnosticsBuilder.Add(new TypeParameterDiagnosticInfo(typeParameter, new CSDiagnosticInfo(ErrorCode.ERR_BaseConstraintConflict, typeParameter, constraintDeducedBase, deducedBaseType)));
                            }
                            else
                            {
                                deducedBaseType = constraintDeducedBase;
                                effectiveBaseClass = constraintEffectiveBase;
                            }
                        }
                    }
                }

                AppendUseSiteDiagnostics(useSiteDiagnostics, typeParameter, ref useSiteDiagnosticsBuilder);

                CheckEffectiveAndDeducedBaseTypes(conversions, effectiveBaseClass, deducedBaseType);

                constraintTypes = constraintTypesBuilder.ToImmutableAndFree();
                interfaces = interfacesBuilder.ToImmutableAndFree();
            }

            Debug.Assert((effectiveBaseClass.SpecialType == SpecialType.System_Object) || (deducedBaseType.SpecialType != SpecialType.System_Object));

            // Only create a TypeParameterBounds instance for this type
            // parameter if the bounds are not the default values.
            if ((constraintTypes.Length == 0) && (deducedBaseType.SpecialType == SpecialType.System_Object))
            {
                Debug.Assert(effectiveBaseClass.SpecialType == SpecialType.System_Object);
                Debug.Assert(interfaces.Length == 0);
                return null;
            }

            var bounds = new TypeParameterBounds(constraintTypes, interfaces, effectiveBaseClass, deducedBaseType);

            // Additional constraint checks for overrides.
            if (inherited)
            {
                CheckOverrideConstraints(typeParameter, bounds, diagnosticsBuilder);
            }

            return bounds;
        }
        private static MethodSymbol InferExtensionMethodTypeArguments(MethodSymbol method, TypeSymbol thisType, CSharpCompilation compilation, ref HashSet <DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert(method.IsExtensionMethod);
            Debug.Assert((object)thisType != null);

            if (!method.IsGenericMethod || method != method.ConstructedFrom)
            {
                return(method);
            }

            // We never resolve extension methods on a dynamic receiver.
            if (thisType.IsDynamic())
            {
                return(null);
            }

            var containingAssembly = method.ContainingAssembly;
            var errorNamespace     = containingAssembly.GlobalNamespace;
            var conversions        = new TypeConversions(containingAssembly.CorLibrary);

            // There is absolutely no plausible syntax/tree that we could use for these
            // synthesized literals.  We could be speculatively binding a call to a PE method.
            var syntaxTree = CSharpSyntaxTree.Dummy;
            var syntax     = (CSharpSyntaxNode)syntaxTree.GetRoot();

            // Create an argument value for the "this" argument of specific type,
            // and pass the same bad argument value for all other arguments.
            var thisArgumentValue = new BoundLiteral(syntax, ConstantValue.Bad, thisType)
            {
                WasCompilerGenerated = true
            };
            var otherArgumentType  = new ExtendedErrorTypeSymbol(errorNamespace, name: string.Empty, arity: 0, errorInfo: null, unreported: false);
            var otherArgumentValue = new BoundLiteral(syntax, ConstantValue.Bad, otherArgumentType)
            {
                WasCompilerGenerated = true
            };

            var paramCount = method.ParameterCount;
            var arguments  = new BoundExpression[paramCount];

            for (int i = 0; i < paramCount; i++)
            {
                var argument = (i == 0) ? thisArgumentValue : otherArgumentValue;
                arguments[i] = argument;
            }

            var typeArgs = MethodTypeInferrer.InferTypeArgumentsFromFirstArgument(
                conversions,
                method,
                arguments.AsImmutable(),
                useSiteDiagnostics: ref useSiteDiagnostics);

            if (typeArgs.IsDefault)
            {
                return(null);
            }

            // For the purpose of constraint checks we use error type symbol in place of type arguments that we couldn't infer from the first argument.
            // This prevents constraint checking from failing for corresponding type parameters.
            int firstNullInTypeArgs       = -1;
            var notInferredTypeParameters = PooledHashSet <TypeParameterSymbol> .GetInstance();

            var typeParams = method.TypeParameters;
            var typeArgsForConstraintsCheck = typeArgs;

            for (int i = 0; i < typeArgsForConstraintsCheck.Length; i++)
            {
                if (!typeArgsForConstraintsCheck[i].HasType)
                {
                    firstNullInTypeArgs = i;
                    var builder = ArrayBuilder <TypeWithAnnotations> .GetInstance();

                    builder.AddRange(typeArgsForConstraintsCheck, firstNullInTypeArgs);

                    for (; i < typeArgsForConstraintsCheck.Length; i++)
                    {
                        var typeArg = typeArgsForConstraintsCheck[i];
                        if (!typeArg.HasType)
                        {
                            notInferredTypeParameters.Add(typeParams[i]);
                            builder.Add(TypeWithAnnotations.Create(ErrorTypeSymbol.UnknownResultType));
                        }
                        else
                        {
                            builder.Add(typeArg);
                        }
                    }

                    typeArgsForConstraintsCheck = builder.ToImmutableAndFree();
                    break;
                }
            }

            // Check constraints.
            var diagnosticsBuilder = ArrayBuilder <TypeParameterDiagnosticInfo> .GetInstance();

            var substitution = new TypeMap(typeParams, typeArgsForConstraintsCheck);
            ArrayBuilder <TypeParameterDiagnosticInfo> useSiteDiagnosticsBuilder = null;
            var success = method.CheckConstraints(conversions, substitution, typeParams, typeArgsForConstraintsCheck, compilation, diagnosticsBuilder, nullabilityDiagnosticsBuilderOpt: null, ref useSiteDiagnosticsBuilder,
                                                  ignoreTypeConstraintsDependentOnTypeParametersOpt: notInferredTypeParameters.Count > 0 ? notInferredTypeParameters : null);

            diagnosticsBuilder.Free();
            notInferredTypeParameters.Free();

            if (useSiteDiagnosticsBuilder != null && useSiteDiagnosticsBuilder.Count > 0)
            {
                if (useSiteDiagnostics == null)
                {
                    useSiteDiagnostics = new HashSet <DiagnosticInfo>();
                }

                foreach (var diag in useSiteDiagnosticsBuilder)
                {
                    useSiteDiagnostics.Add(diag.DiagnosticInfo);
                }
            }

            if (!success)
            {
                return(null);
            }

            // For the purpose of construction we use original type parameters in place of type arguments that we couldn't infer from the first argument.
            ImmutableArray <TypeWithAnnotations> typeArgsForConstruct = typeArgs;

            if (typeArgs.Any(t => !t.HasType))
            {
                typeArgsForConstruct = typeArgs.ZipAsArray(
                    method.TypeParameters,
                    (t, tp) => t.HasType ? t : TypeWithAnnotations.Create(tp));
            }

            return(method.Construct(typeArgsForConstruct));
        }
        /// <summary>
        /// If the extension method is applicable based on the "this" argument type, return
        /// the method constructed with the inferred type arguments. If the method is not an
        /// unconstructed generic method, type inference is skipped. If the method is not
        /// applicable, or if constraints when inferring type parameters from the "this" type
        /// are not satisfied, the return value is null.
        /// </summary>
        public static MethodSymbol InferExtensionMethodTypeArguments(this MethodSymbol method, TypeSymbol thisType, Compilation compilation, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert(method.IsExtensionMethod);
            Debug.Assert((object)thisType != null);

            if (!method.IsGenericMethod || method != method.ConstructedFrom)
            {
                return method;
            }

            // We never resolve extension methods on a dynamic receiver.
            if (thisType.IsDynamic())
            {
                return null;
            }

            var containingAssembly = method.ContainingAssembly;
            var errorNamespace = containingAssembly.GlobalNamespace;
            var conversions = new TypeConversions(containingAssembly.CorLibrary);

            // There is absolutely no plausible syntax/tree that we could use for these
            // synthesized literals.  We could be speculatively binding a call to a PE method.
            var syntaxTree = CSharpSyntaxTree.Dummy;
            var syntax = (CSharpSyntaxNode)syntaxTree.GetRoot();

            // Create an argument value for the "this" argument of specific type,
            // and pass the same bad argument value for all other arguments.
            var thisArgumentValue = new BoundLiteral(syntax, ConstantValue.Bad, thisType) { WasCompilerGenerated = true };
            var otherArgumentType = new ExtendedErrorTypeSymbol(errorNamespace, name: string.Empty, arity: 0, errorInfo: null, unreported: false);
            var otherArgumentValue = new BoundLiteral(syntax, ConstantValue.Bad, otherArgumentType) { WasCompilerGenerated = true };

            var paramCount = method.ParameterCount;
            var arguments = new BoundExpression[paramCount];
            var argumentTypes = new TypeSymbol[paramCount];
            for (int i = 0; i < paramCount; i++)
            {
                var argument = (i == 0) ? thisArgumentValue : otherArgumentValue;
                arguments[i] = argument;
                argumentTypes[i] = argument.Type;
            }

            var typeArgs = MethodTypeInferrer.InferTypeArgumentsFromFirstArgument(
                conversions,
                method,
                argumentTypes.AsImmutableOrNull(),
                arguments.AsImmutableOrNull(),
                ref useSiteDiagnostics);

            if (typeArgs.IsDefault)
            {
                return null;
            }

            int firstNullInTypeArgs = -1;

            // For the purpose of constraint checks we use error type symbol in place of type arguments that we couldn't infer from the first argument.
            // This prevents constraint checking from failing for corresponding type parameters. 
            var typeArgsForConstraintsCheck = typeArgs;
            for (int i = 0; i < typeArgsForConstraintsCheck.Length; i++)
            {
                if ((object)typeArgsForConstraintsCheck[i] == null)
                {
                    firstNullInTypeArgs = i;
                    var builder = ArrayBuilder<TypeSymbol>.GetInstance();
                    builder.AddRange(typeArgs, firstNullInTypeArgs);

                    for (; i < typeArgsForConstraintsCheck.Length; i++)
                    {
                        builder.Add(typeArgsForConstraintsCheck[i] ?? ErrorTypeSymbol.UnknownResultType);
                    }

                    typeArgsForConstraintsCheck = builder.ToImmutableAndFree();
                    break;
                }
            }

            // Check constraints.
            var diagnosticsBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance();
            var typeParams = method.TypeParameters;
            var substitution = new TypeMap(typeParams, typeArgsForConstraintsCheck.SelectAsArray(TypeMap.TypeSymbolAsTypeWithModifiers));
            ArrayBuilder<TypeParameterDiagnosticInfo> useSiteDiagnosticsBuilder = null;
            var success = method.CheckConstraints(conversions, substitution, typeParams, typeArgsForConstraintsCheck, compilation, diagnosticsBuilder, ref useSiteDiagnosticsBuilder);
            diagnosticsBuilder.Free();

            if (useSiteDiagnosticsBuilder != null && useSiteDiagnosticsBuilder.Count > 0)
            {
                if (useSiteDiagnostics == null)
                {
                    useSiteDiagnostics = new HashSet<DiagnosticInfo>();
                }

                foreach (var diag in useSiteDiagnosticsBuilder)
                {
                    useSiteDiagnostics.Add(diag.DiagnosticInfo);
                }
            }

            if (!success)
            {
                return null;
            }

            // For the purpose of construction we use original type parameters in place of type arguments that we couldn't infer from the first argument.
            var typeArgsForConstruct = typeArgs;
            if (firstNullInTypeArgs != -1)
            {
                var builder = ArrayBuilder<TypeSymbol>.GetInstance();
                builder.AddRange(typeArgs, firstNullInTypeArgs);

                for (int i = firstNullInTypeArgs; i < typeArgsForConstruct.Length; i++)
                {
                    builder.Add(typeArgsForConstruct[i] ?? typeParams[i]);
                }

                typeArgsForConstruct = builder.ToImmutableAndFree();
            }

            return method.Construct(typeArgsForConstruct);
        }
        /// <summary>
        /// Check constraints of generic types referenced in constraint types. For instance,
        /// with "interface I&lt;T&gt; where T : I&lt;T&gt; {}", check T satisfies constraints
        /// on I&lt;T&gt;. Those constraints are not checked when binding ConstraintTypes
        /// since ConstraintTypes has not been set on I&lt;T&gt; at that point.
        /// </summary>
        private void CheckConstraintTypeConstraints(DiagnosticBag diagnostics)
        {
            var constraintTypes = this.ConstraintTypesNoUseSiteDiagnostics;
            if (constraintTypes.Length == 0)
            {
                return;
            }

            var corLibrary = this.ContainingAssembly.CorLibrary;
            var conversions = new TypeConversions(corLibrary);
            var location = _locations[0];

            foreach (var constraintType in constraintTypes)
            {
                HashSet<DiagnosticInfo> useSiteDiagnostics = null;
                constraintType.AddUseSiteDiagnostics(ref useSiteDiagnostics);

                if (!diagnostics.Add(location, useSiteDiagnostics))
                {
                    constraintType.CheckAllConstraints(conversions, location, diagnostics);
                }
            }
        }
        /// <summary>
        /// If the extension method is applicable based on the "this" argument type, return
        /// the method constructed with the inferred type arguments. If the method is not an
        /// unconstructed generic method, type inference is skipped. If the method is not
        /// applicable, or if constraints when inferring type parameters from the "this" type
        /// are not satisfied, the return value is null.
        /// </summary>
        public static MethodSymbol InferExtensionMethodTypeArguments(this MethodSymbol method, TypeSymbol thisType, Compilation compilation, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert(method.IsExtensionMethod);
            Debug.Assert((object)thisType != null);

            if (!method.IsGenericMethod || method != method.ConstructedFrom)
            {
                return method;
            }

            // We never resolve extension methods on a dynamic receiver.
            if (thisType.IsDynamic())
            {
                return null;
            }

            var containingAssembly = method.ContainingAssembly;
            var errorNamespace = containingAssembly.GlobalNamespace;
            var conversions = new TypeConversions(containingAssembly.CorLibrary);

            // There is absolutely no plausible syntax/tree that we could use for these
            // synthesized literals.  We could be speculatively binding a call to a PE method.
            var syntaxTree = CSharpSyntaxTree.Dummy;
            var syntax = (CSharpSyntaxNode)syntaxTree.GetRoot();

            // Create an argument value for the "this" argument of specific type,
            // and pass the same bad argument value for all other arguments.
            var thisArgumentValue = new BoundLiteral(syntax, ConstantValue.Bad, thisType) { WasCompilerGenerated = true };
            var otherArgumentType = new ExtendedErrorTypeSymbol(errorNamespace, name: string.Empty, arity: 0, errorInfo: null, unreported: false);
            var otherArgumentValue = new BoundLiteral(syntax, ConstantValue.Bad, otherArgumentType) { WasCompilerGenerated = true };

            var paramCount = method.ParameterCount;
            var arguments = new BoundExpression[paramCount];
            var argumentTypes = new TypeSymbol[paramCount];
            for (int i = 0; i < paramCount; i++)
            {
                var argument = (i == 0) ? thisArgumentValue : otherArgumentValue;
                arguments[i] = argument;
                argumentTypes[i] = argument.Type;
            }

            var typeArgs = MethodTypeInferrer.InferTypeArgumentsFromFirstArgument(
                conversions,
                method,
                argumentTypes.AsImmutableOrNull(),
                arguments.AsImmutableOrNull(),
                ref useSiteDiagnostics);

            if (typeArgs.IsDefault)
            {
                return null;
            }

            // Check constraints.
            var diagnosticsBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance();
            var typeParams = method.TypeParameters;
            var substitution = new TypeMap(typeParams, typeArgs);
            ArrayBuilder<TypeParameterDiagnosticInfo> useSiteDiagnosticsBuilder = null;
            var success = method.CheckConstraints(conversions, substitution, method.TypeParameters, typeArgs, compilation, diagnosticsBuilder, ref useSiteDiagnosticsBuilder);
            diagnosticsBuilder.Free();

            if (useSiteDiagnosticsBuilder != null && useSiteDiagnosticsBuilder.Count > 0)
            {
                if (useSiteDiagnostics == null)
                {
                    useSiteDiagnostics = new HashSet<DiagnosticInfo>();
                }

                foreach (var diag in useSiteDiagnosticsBuilder)
                {
                    useSiteDiagnostics.Add(diag.DiagnosticInfo);
                }
            }

            if (!success)
            {
                return null;
            }

            return method.Construct(typeArgs);
        }
        protected override void CheckInterfaces(DiagnosticBag diagnostics)
        {
            // Check declared interfaces and all base interfaces. This is necessary
            // since references to all interfaces will be emitted to metadata
            // and it's possible to define derived interfaces with weaker
            // constraints than the base interfaces, at least in metadata.
            var interfaces = this.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics;

            if (interfaces.IsEmpty)
            {
                // nothing to verify
                return;
            }

            // Check constraints on the first declaration with explicit bases.
            var singleDeclaration = this.FirstDeclarationWithExplicitBases();
            if (singleDeclaration != null)
            {
                var corLibrary = this.ContainingAssembly.CorLibrary;
                var conversions = new TypeConversions(corLibrary);
                var location = singleDeclaration.NameLocation;

                foreach (var @interface in interfaces)
                {
                    @interface.CheckAllConstraints(conversions, location, diagnostics);
                }

                if (interfaces.Count > 1)
                {
                    var seenInterfaces = new Dictionary<NamedTypeSymbol, NamedTypeSymbol>(EqualsIgnoringComparer.InstanceIgnoringTupleNames);
                    foreach (var @interface in interfaces)
                    {
                        NamedTypeSymbol other;
                        if (seenInterfaces.TryGetValue(@interface, out other))
                        {
                            diagnostics.Add(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, location, @interface, other, this);
                        }
                        else
                        {
                            seenInterfaces.Add(@interface, @interface);
                        }
                    }
                }
            }
        }
        protected override void CheckInterfaces(DiagnosticBag diagnostics)
        {
            // Check declared interfaces and all base interfaces. This is necessary
            // since references to all interfaces will be emitted to metadata
            // and it's possible to define derived interfaces with weaker
            // constraints than the base interfaces, at least in metadata.
            var interfaces = this.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics;

            if (interfaces.IsEmpty)
            {
                // nothing to verify
                return;
            }

            // Check constraints on the first declaration with explicit bases.
            var singleDeclaration = this.FirstDeclarationWithExplicitBases();
            if (singleDeclaration != null)
            {
                var corLibrary = this.ContainingAssembly.CorLibrary;
                var conversions = new TypeConversions(corLibrary);
                var location = singleDeclaration.NameLocation;

                foreach (var @interface in interfaces)
                {
                    @interface.CheckAllConstraints(conversions, location, diagnostics);
                }
            }
        }
        /// <summary>
        /// Lower a foreach loop that will enumerate a collection using an enumerator.
        /// 
        /// E e = ((C)(x)).GetEnumerator()
        /// try {
        ///     while (e.MoveNext()) {
        ///         V v = (V)(T)e.Current;
        ///         // body
        ///     }
        /// }
        /// finally {
        ///     // clean up e
        /// }
        /// </summary>
        private BoundStatement RewriteEnumeratorForEachStatement(BoundForEachStatement node)
        {
            ForEachStatementSyntax forEachSyntax = (ForEachStatementSyntax)node.Syntax;

            ForEachEnumeratorInfo enumeratorInfo = node.EnumeratorInfoOpt;
            Debug.Assert(enumeratorInfo != null);

            BoundExpression collectionExpression = GetUnconvertedCollectionExpression(node);
            BoundExpression rewrittenExpression = (BoundExpression)Visit(collectionExpression);
            BoundStatement rewrittenBody = (BoundStatement)Visit(node.Body);

            TypeSymbol enumeratorType = enumeratorInfo.GetEnumeratorMethod.ReturnType;
            TypeSymbol elementType = enumeratorInfo.ElementType;

            // E e
            LocalSymbol enumeratorVar = new TempLocalSymbol(enumeratorType, RefKind.None, this.containingMethod);

            // Reference to e.
            BoundLocal boundEnumeratorVar = MakeBoundLocal(forEachSyntax, enumeratorVar, enumeratorType);

            // ((C)(x)).GetEnumerator() or (x).GetEnumerator();
            BoundExpression enumeratorVarInitValue = SynthesizeCall(forEachSyntax, rewrittenExpression, enumeratorInfo.GetEnumeratorMethod, enumeratorInfo.CollectionConversion, enumeratorInfo.CollectionType);

            // E e = ((C)(x)).GetEnumerator();
            BoundStatement enumeratorVarDecl = MakeLocalDeclaration(forEachSyntax, enumeratorVar, enumeratorVarInitValue);

            AddForEachExpressionSequencePoint(forEachSyntax, ref enumeratorVarDecl);

            // V v
            LocalSymbol iterationVar = node.IterationVariable;

            //(V)(T)e.Current
            BoundExpression iterationVarAssignValue = SynthesizeConversion(
                syntax: forEachSyntax,
                operand: SynthesizeConversion(
                    syntax: forEachSyntax,
                    operand: BoundCall.Synthesized(
                        syntax: forEachSyntax,
                        receiverOpt: boundEnumeratorVar,
                        method: enumeratorInfo.CurrentPropertyGetter),
                    conversion: enumeratorInfo.CurrentConversion,
                    type: elementType),
                conversion: node.ElementConversion,
                type: iterationVar.Type);

            // V v = (V)(T)e.Current;
            BoundStatement iterationVarDecl = MakeLocalDeclaration(forEachSyntax, iterationVar, iterationVarAssignValue);

            AddForEachIterationVariableSequencePoint(forEachSyntax, ref iterationVarDecl);

            // while (e.MoveNext()) {
            //     V v = (V)(T)e.Current;
            //     /* node.Body */
            // }
            BoundStatement whileLoop = RewriteWhileStatement(
                syntax: forEachSyntax,
                rewrittenCondition: BoundCall.Synthesized(
                    syntax: forEachSyntax,
                    receiverOpt: boundEnumeratorVar,
                    method: enumeratorInfo.MoveNextMethod),
                conditionSequencePointSpan: forEachSyntax.InKeyword.Span,
                rewrittenBody: new BoundBlock(rewrittenBody.Syntax,
                    statements: ReadOnlyArray<BoundStatement>.CreateFrom(iterationVarDecl, rewrittenBody),
                    localsOpt: ReadOnlyArray<LocalSymbol>.CreateFrom(iterationVar)),
                breakLabel: node.BreakLabel,
                continueLabel: node.ContinueLabel,
                hasErrors: false);

            BoundStatement result;

            if (enumeratorInfo.DisposeMethodOpt != null)
            {
                BoundBlock finallyBlockOpt;
                var idisposableTypeSymbol = enumeratorInfo.DisposeMethodOpt.ContainingType;
                var conversions = new TypeConversions(this.containingMethod.ContainingAssembly.CorLibrary);

                if (conversions.ClassifyImplicitConversion(enumeratorType, idisposableTypeSymbol).IsImplicit)
                {
                    Debug.Assert(enumeratorInfo.DisposeMethodOpt != null);

                    Conversion receiverConversion = enumeratorType.IsStructType() ?
                        Conversion.Boxing :
                        Conversion.ImplicitReference;

                    // ((IDisposable)e).Dispose(); or e.Dispose();
                    BoundStatement disposeCall = new BoundExpressionStatement(forEachSyntax,
                        expression: SynthesizeCall(forEachSyntax, boundEnumeratorVar, enumeratorInfo.DisposeMethodOpt, receiverConversion, idisposableTypeSymbol));

                    BoundStatement disposeStmt;
                    if (enumeratorType.IsValueType)
                    {
                        // No way for the struct to be nullable and disposable.
                        Debug.Assert(((TypeSymbol)enumeratorType.OriginalDefinition).SpecialType != SpecialType.System_Nullable_T);

                        // For non-nullable structs, no null check is required.
                        disposeStmt = disposeCall;
                    }
                    else
                    {
                        // NB: cast to object missing from spec.  Needed to ignore user-defined operators and box type parameters.
                        // if ((object)e != null) ((IDisposable)e).Dispose(); 
                        disposeStmt = RewriteIfStatement(
                            syntax: forEachSyntax,
                            rewrittenCondition: new BoundBinaryOperator(forEachSyntax,
                                operatorKind: BinaryOperatorKind.NotEqual,
                                left: SynthesizeConversion(
                                    syntax: forEachSyntax,
                                    operand: boundEnumeratorVar,
                                    conversion: enumeratorInfo.EnumeratorConversion,
                                    type: this.compilation.GetSpecialType(SpecialType.System_Object)),
                                right: new BoundLiteral(forEachSyntax,
                                    constantValueOpt: ConstantValue.Null,
                                    type: null),
                                constantValueOpt: null,
                                methodOpt: null,
                                resultKind: LookupResultKind.Viable,
                                type: this.compilation.GetSpecialType(SpecialType.System_Boolean)),
                            rewrittenConsequence: disposeCall,
                            rewrittenAlternativeOpt: null,
                            hasErrors: false);
                    }

                    finallyBlockOpt = new BoundBlock(forEachSyntax,
                        localsOpt: ReadOnlyArray<LocalSymbol>.Null,
                        statements: ReadOnlyArray<BoundStatement>.CreateFrom(disposeStmt));
                }
                else
                {
                    Debug.Assert(!enumeratorType.IsSealed);

                    // IDisposable d
                    LocalSymbol disposableVar = new TempLocalSymbol(idisposableTypeSymbol, RefKind.None, this.containingMethod);

                    // Reference to d.
                    BoundLocal boundDisposableVar = MakeBoundLocal(forEachSyntax, disposableVar, idisposableTypeSymbol);

                    BoundTypeExpression boundIDisposableTypeExpr = new BoundTypeExpression(forEachSyntax,
                        type: idisposableTypeSymbol);

                    // e as IDisposable
                    BoundExpression disposableVarInitValue = new BoundAsOperator(forEachSyntax,
                        operand: boundEnumeratorVar,
                        targetType: boundIDisposableTypeExpr,
                        conversion: Conversion.ExplicitReference, // Explicit so the emitter won't optimize it away.
                        type: idisposableTypeSymbol);

                    // IDisposable d = e as IDisposable;
                    BoundStatement disposableVarDecl = MakeLocalDeclaration(forEachSyntax, disposableVar, disposableVarInitValue);

                    // if (d != null) d.Dispose();
                    BoundStatement ifStmt = RewriteIfStatement(
                        syntax: forEachSyntax,
                        rewrittenCondition: new BoundBinaryOperator(forEachSyntax,
                            operatorKind: BinaryOperatorKind.NotEqual, // reference equality
                            left: boundDisposableVar,
                            right: new BoundLiteral(forEachSyntax,
                                constantValueOpt: ConstantValue.Null,
                                type: null),
                            constantValueOpt: null,
                            methodOpt: null,
                            resultKind: LookupResultKind.Viable,
                            type: this.compilation.GetSpecialType(SpecialType.System_Boolean)),
                        rewrittenConsequence: new BoundExpressionStatement(forEachSyntax,
                            expression: BoundCall.Synthesized(
                                syntax: forEachSyntax,
                                receiverOpt: boundDisposableVar,
                                method: enumeratorInfo.DisposeMethodOpt)),
                        rewrittenAlternativeOpt: null,
                        hasErrors: false);

                    // IDisposable d = e as IDisposable;
                    // if (d != null) d.Dispose();
                    finallyBlockOpt = new BoundBlock(forEachSyntax,
                        localsOpt: ReadOnlyArray<LocalSymbol>.CreateFrom(disposableVar),
                        statements: ReadOnlyArray<BoundStatement>.CreateFrom(disposableVarDecl, ifStmt));
                }

                // try {
                //     while (e.MoveNext()) {
                //         V v = (V)(T)e.Current;
                //         /* loop body */
                //     }
                // }
                // finally {
                //     /* dispose of e */
                // }
                BoundStatement tryFinally = new BoundTryStatement(forEachSyntax,
                    tryBlock: new BoundBlock(forEachSyntax,
                        localsOpt: ReadOnlyArray<LocalSymbol>.Empty,
                        statements: ReadOnlyArray<BoundStatement>.CreateFrom(whileLoop)),
                    catchBlocks: ReadOnlyArray<BoundCatchBlock>.Empty,
                    finallyBlockOpt: finallyBlockOpt);

                // E e = ((C)(x)).GetEnumerator();
                // try {
                //     /* as above */
                result = new BoundBlock(
                    syntax: forEachSyntax,
                    localsOpt: ReadOnlyArray<LocalSymbol>.CreateFrom(enumeratorVar),
                    statements: ReadOnlyArray<BoundStatement>.CreateFrom(enumeratorVarDecl, tryFinally));
            }
            else
            {
                // E e = ((C)(x)).GetEnumerator();
                // while (e.MoveNext()) {
                //     V v = (V)(T)e.Current;
                //     /* loop body */
                // }
                result = new BoundBlock(
                    syntax: forEachSyntax,
                    localsOpt: ReadOnlyArray<LocalSymbol>.CreateFrom(enumeratorVar),
                    statements: ReadOnlyArray<BoundStatement>.CreateFrom(enumeratorVarDecl, whileLoop));
            }

            AddForEachKeywordSequencePoint(forEachSyntax, ref result);

            return result;
        }