Example #1
0
        public override bool CanConvertFrom(Type /*!*/ fromType, ParameterWrapper /*!*/ toParameter, NarrowingLevel level)
        {
            Type toType = toParameter.Type;

            if (base.CanConvertFrom(fromType, toParameter, level))
            {
                return(true);
            }

            // blocks:
            if (fromType == typeof(MissingBlockParam))
            {
                return(toType == typeof(BlockParam) && !toParameter.ProhibitNull);
            }

            if (fromType == typeof(BlockParam) && toType == typeof(MissingBlockParam))
            {
                return(true);
            }

            // protocol conversions:
            if (toParameter.ParameterInfo != null && toParameter.ParameterInfo.IsDefined(typeof(DefaultProtocolAttribute), false))
            {
                // any type is potentially convertible, except for nil if [NotNull] is used:
                return(fromType != typeof(Null) || !toParameter.ProhibitNull);
            }

            return(false);
        }
Example #2
0
        public static IReadOnlyCollection <SyntaxKind> GetModifiers(this ParameterWrapper parameter, bool isExtensionMethod)
        {
            var modifierList = new List <SyntaxKind>(6);

            if (isExtensionMethod)
            {
                modifierList.Add(SyntaxKind.ThisKeyword);
            }

            switch (parameter.ReferenceKind)
            {
            case ParameterReferenceKind.In:
                modifierList.Add(SyntaxKind.InKeyword);
                break;

            case ParameterReferenceKind.Out:
                modifierList.Add(SyntaxKind.OutKeyword);
                break;

            case ParameterReferenceKind.Ref:
                modifierList.Add(SyntaxKind.RefKeyword);
                break;
            }

            if (parameter.Attributes.HasKnownAttribute(KnownAttribute.ParamArray))
            {
                modifierList.Add(SyntaxKind.ParamsKeyword);
            }

            return(modifierList);
        }
        public override Candidate SelectBestConversionFor(DynamicMetaObject arg, ParameterWrapper candidateOne, ParameterWrapper candidateTwo, NarrowingLevel level)
        {
            Candidate basePreferred = base.SelectBestConversionFor(arg, candidateOne, candidateTwo, level);

            if (basePreferred == Candidate.One || basePreferred == Candidate.Two)
            {
                return(basePreferred);
            }

            bool isBytesLikeOne = IsBytesLikeParameter(candidateOne);
            bool isBytesLikeTwo = IsBytesLikeParameter(candidateTwo);

            if (isBytesLikeOne)
            {
                if (isBytesLikeTwo)
                {
                    return(basePreferred);
                }
                if (candidateTwo.Type.IsInterface)
                {
                    return(Candidate.One);
                }
            }
            else if (isBytesLikeTwo)
            {
                if (candidateOne.Type.IsInterface)
                {
                    return(Candidate.Two);
                }
            }

            return(basePreferred);
        }
        public override void save()
        {
            if (this._wrappedOperation == null)
            {
                this._wrappedOperation = this._factory._modelFactory.createNewElement <Operation>(this._owner._wrappedClass, this._name);
                this._wrappedOperation.setStereotype(getStereotype());
            }
            if (this._wrappedOperation != null)
            {
                this._wrappedOperation.save();
                this.isOverridden = this.isOverridden;
                //get the corresponding columns from this table
                this.involvedColumns = this.ownerTable.columns.Where(x => _involvedColumns.Any(y => y.name == x.name)).ToList();
                if (this._wrappedOperation != null)
                {
                    //first remove all existing parameters

                    this._wrappedOperation.ownedParameters = new HashSet <UML.Classes.Kernel.Parameter>();
                    foreach (var column in _involvedColumns)
                    {
                        {
                            ParameterWrapper parameter = this._wrappedOperation.model.factory.createNewElement <Parameter>(this._wrappedOperation, column.name) as ParameterWrapper;
                            parameter.type = ((Column)column)._wrappedattribute.type;
                            //TODO: this would be nicer if we could keep the parameters in memory and not save them directly
                            parameter.save();
                        }
                    }
                }
            }
        }
        protected override void AfterLoading()
        {
            //новый продукт
            var block = new ProductBlockWrapper(new ProductBlock());

            Item.Product = new ProductWrapper(new Product())
            {
                ProductBlock = block
            };

            //параметры продукта
            _parameter = new ParameterWrapper(new Parameter());
            var group = UnitOfWork.Repository <ParameterGroup>().GetById(GlobalAppProperties.Actual.NewProductParameterGroup.Id);

            _parameter.ParameterGroup = new ParameterGroupWrapper(group);

            var parameterBase = UnitOfWork.Repository <Parameter>().GetById(GlobalAppProperties.Actual.NewProductParameter.Id);
            var relation      = new ParameterRelation();

            relation.RequiredParameters.Add(parameterBase);
            _parameter.ParameterRelations.Add(new ParameterRelationWrapper(relation));

            var parameters = parameterBase.Paths().First().Parameters.Select(x => new ParameterWrapper(x)).ToList();

            parameters.Add(_parameter);
            parameters.ForEach(x => block.Parameters.Add(x));

            Item.PropertyChanged += ItemOnPropertyChanged;

            base.AfterLoading();
        }
 private bool HasExplicitProtocolConversion(ParameterWrapper /*!*/ parameter)
 {
     return
         (parameter.ParameterInfo != null &&
          parameter.ParameterInfo.IsDefined(typeof(DefaultProtocolAttribute), false) &&
          !parameter.IsParamsArray); // default protocol doesn't apply on param-array/dict itself, only on the expanded parameters
 }
        public void PopulateItems()
        {
            var e = GetInputElement();

            if (e != null)
            {
                var items = new List <ParameterWrapper>();

                // add instance parameters
                items.AddRange(GetParameters(e, "Instance"));

                // add type parameters
                if (e.CanHaveTypeAssigned())
                {
                    var et = DocumentManager.Instance.CurrentDBDocument.GetElement(e.GetTypeId());
                    if (et != null)
                    {
                        items.AddRange(GetParameters(et, "Type"));
                    }
                }
                ItemsCollection = new ObservableCollection <ParameterWrapper>(items.OrderBy(x => x.Name));
            }

            if (SelectedItem == null)
            {
                SelectedItem = ItemsCollection.FirstOrDefault();
            }
        }
Example #8
0
        public virtual bool CanConvertFrom(Type fromType, ParameterWrapper toParameter, NarrowingLevel level)
        {
            Assert.NotNull(fromType, toParameter);

            Type toType = toParameter.Type;

            if (fromType == Null.Type)
            {
                if (toParameter.ProhibitNull)
                {
                    return(false);
                }

                if (toType.IsGenericType && toType.GetGenericTypeDefinition() == typeof(Nullable <>))
                {
                    return(true);
                }

                if (!toType.IsValueType)
                {
                    return(true);
                }
            }

            if (fromType == toType)
            {
                return(true);
            }

            return(CanConvertFrom(fromType, toType, toParameter.ProhibitNull, level));
        }
 private void Connectors_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
 {
     if (e.Action == NotifyCollectionChangedAction.Remove)
     {
         ItemsCollection.Clear();
         SelectedItem = null;
         OnRequestChangeBuiltInParamSelector();
     }
     else
     {
         OnRequestChangeBuiltInParamSelector();
     }
 }
        private object GetFromHeaders(ParameterWrapper parameter)
        {
            if (!Request.Headers.Contains(parameter.Name))
            {
                return(null);
            }
            var vals = Request.Headers.GetValues(parameter.Name);

            if (vals.Count() <= 1)
            {
                return(vals.SingleOrDefault());
            }
            throw new InvalidCastException("Not currently able to deal with collections...");
        }
 private ParameterWrapper DeserializeValue(string val)
 {
     try
     {
         var name    = val.Split('+')[0];
         var bipName = val.Split('+')[1];
         return(SelectedItem = new ParameterWrapper {
             Name = name, BipName = bipName
         });
     }
     catch
     {
         return(SelectedItem = new ParameterWrapper {
             Name = "None", BipName = "None"
         });
     }
 }
Example #12
0
        public override Candidate SelectBestConversionFor(Type /*!*/ actualType, ParameterWrapper /*!*/ candidateOne, ParameterWrapper /*!*/ candidateTwo, NarrowingLevel level)
        {
            Type typeOne = candidateOne.Type;
            Type typeTwo = candidateTwo.Type;

            if (actualType == typeof(Null))
            {
                // if nil is passed as a block argument prefer BlockParam over missing block;
                if (typeOne == typeof(BlockParam) && typeTwo == typeof(MissingBlockParam))
                {
                    return(Candidate.One);
                }

                if (typeOne == typeof(MissingBlockParam) && typeTwo == typeof(BlockParam))
                {
                    return(Candidate.Two);
                }
            }
            else
            {
                if (actualType == typeOne && candidateOne.ProhibitNull)
                {
                    return(Candidate.One);
                }

                if (actualType == typeTwo && candidateTwo.ProhibitNull)
                {
                    return(Candidate.Two);
                }
            }

            if (actualType == typeOne)
            {
                return(Candidate.One);
            }

            if (actualType == typeTwo)
            {
                return(Candidate.Two);
            }


            return(Candidate.Equivalent);
        }
Example #13
0
        /// <summary>
        /// Allocate a register for the given type.
        /// </summary>
        protected override RegisterSpec Allocate(TypeReference type, bool forceObject, RCategory category, object parameter)
        {
            var isWide = !forceObject && type.IsWide();

            if (isWide)
            {
                var pair = body.AllocateWideRegister(category);
                switch (category)
                {
                case RCategory.Temp:
                    return(new RegisterSpec(pair.Item1, pair.Item2, type));

                case RCategory.Variable:
                case RCategory.VariablePreventOptimization:
                case RCategory.TempVariable:
                    return(new VariableRegisterSpec(pair.Item1, pair.Item2, type, (AstVariable)parameter));

                case RCategory.Argument:
                    return(new ArgumentRegisterSpec(pair.Item1, pair.Item2, type, ParameterWrapper.Wrap(parameter)));

                default:
                    throw new ArgumentException("Unknown category " + category);
                }
            }
            var isPrimitive = !forceObject && (type is PrimitiveType);
            var register    = body.AllocateRegister(category, isPrimitive ? RType.Value : RType.Object);

            switch (category)
            {
            case RCategory.Temp:
                return(new RegisterSpec(register, null, type));

            case RCategory.Variable:
            case RCategory.VariablePreventOptimization:
            case RCategory.TempVariable:
                return(new VariableRegisterSpec(register, null, type, (AstVariable)parameter));

            case RCategory.Argument:
                return(new ArgumentRegisterSpec(register, null, type, ParameterWrapper.Wrap(parameter)));

            default:
                throw new ArgumentException("Unknown category " + category);
            }
        }
Example #14
0
        public static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("No arguments were passed.");
                Console.WriteLine("Please pass the path to the file or a directory");
                return;
            }
            String path = args[0];

            String htmlCode = "<!DOCTYPE html>\r\n<html>\r\n\r\n<head>\r\n\r\n    <!-- BOOTSTRAP 3 -->\r\n    <link rel=\"stylesheet\" media=\"screen\" href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.min.css\">\r\n\r\n    <!-- OUR CSS -->\r\n    <link rel=\"stylesheet\" href=\"css/styles.css\">\r\n    <link rel=\"stylesheet\" href=\"css/responsive.css\">\r\n    <link rel=\"stylesheet\" href=\"css/custom.css\">\r\n\r\n    <title>Class Details</title>\r\n</head>\r\n\r\n<body>\r\n\r\n    <!--**************************************************************************************************\r\n                                                   HEADER\r\n        **************************************************************************************************-->\r\n    <nav class=\"navbar navbar-default\" role=\"navigation\">\r\n        <div class=\"navbar-header\">\r\n            <button type=\"button\" class=\"navbar-toggle\" data-toggle=\"collapse\" data-target=\".navbar-ex1-collapse\">\r\n\t\t\t<span class=\"sr-only\">Toggle navigation</span>\r\n\t\t\t<span class=\"icon-bar\"></span>\r\n\t\t\t<span class=\"icon-bar\"></span>\r\n\t\t\t<span class=\"icon-bar\"></span>\r\n\t\t</button>\r\n        </div>\r\n\r\n        <div class=\"collapse navbar-collapse navbar-ex1-collapse\">\r\n            <ul class=\"nav navbar-nav\">\r\n                <li><a href=\"#\">Overview</a></li>\r\n                <li><a href=\"#\">Structures</a></li>\r\n                <li><a href=\"#\">Classes</a></li>\r\n                <li><a href=\"#\">Files</a></li>\r\n                <li><a href=\"#\">Tree</a></li>\r\n            </ul>\r\n        </div>\r\n        <!-- /.navbar-collapse -->\r\n    </nav>\r\n    \r\n    <!-- MAIN CONTAINER -->\r\n    <div class=\"container main-container\">";

            htmlCode += ClassWebPage.generateClassName("LinkedList");

            ClassWrapper[] classWrappers = new ClassWrapper[5];
            for (var i = 0; i < 5; i++)
            {
                classWrappers[i] = new ClassWrapper("LinkedList", "", null, null);
            }
            htmlCode += ClassWebPage.generateImplementedClasses(classWrappers);

            ParameterWrapper[] parameters = new ParameterWrapper[2];
            for (var i = 0; i < parameters.Length; i++)
            {
                parameters[i] = new ParameterWrapper("start", "struct Node*");
            }
            htmlCode += ClassWebPage.generateFields(parameters);

            ConstructorWrapper[] constructors = new ConstructorWrapper[2];
            constructors[0] = new ConstructorWrapper("LinkedList", "", "", new ParameterWrapper[0]);
            constructors[1] = new ConstructorWrapper("LinkedList", "", "", parameters);
            htmlCode       += ClassWebPage.generateConstructors(constructors);

            MethodWrapper[] methods = new MethodWrapper[10];
            for (var i = 0; i < methods.Length; i++)
            {
                methods[i] = new MethodWrapper("traverse", "Traverses the given LinkedList", "", parameters, "void");
            }
            htmlCode += ClassWebPage.generateMethods(methods);

            htmlCode += "</div><!--.main-container-->\r\n\r\n\r\n\r\n    <!-- JQUERY SCRIPT -->\r\n    <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js\"></script>\r\n    <!-- BOOTSTRAP SCRIPT -->\r\n    <script src=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/js/bootstrap.min.js\"></script>\r\n    <!-- OUR SCRIPT -->\r\n    <script src=\"js/script.js\"></script>\r\n</body>\r\n\r\n</html>\r\n";

            File.WriteAllText("/Users/gauravpunjabi/Desktop/index.html", htmlCode);
        }
Example #15
0
        public override void save()
        {
            if (this._wrappedOperation == null)
            {
                this._wrappedOperation = this._factory._modelFactory.createNewElement <Operation>(this._owner._wrappedClass, this._name);
                this._wrappedOperation.setStereotype(getStereotype());
            }
            if (this._wrappedOperation != null)
            {
                this._wrappedOperation.save();
                this.isOverridden = this.isOverridden;
                this.isRenamed    = this.isRenamed;
                //get the corresponding columns from this table
                this.involvedColumns = getCorrespondingColumns();
                if (this._wrappedOperation != null)
                {
                    //first remove all existing parameters

                    this._wrappedOperation.ownedParameters = new HashSet <UML.Classes.Kernel.Parameter>();
                    uint parameterPosition = 0;
                    foreach (var column in _involvedColumns)
                    {
                        {
                            ParameterWrapper parameter = this._wrappedOperation.model.factory.createNewElement <Parameter>(this._wrappedOperation, column.name) as ParameterWrapper;
                            parameter.type     = ((Column)column)._wrappedattribute.type;
                            parameter.position = parameterPosition;
                            //TODO: this would be nicer if we could keep the parameters in memory and not save them directly
                            parameter.save();
                            parameterPosition++;
                        }
                    }
                }
            }
            //set all attributes to static
            foreach (Column involvedColumn in this.involvedColumns)
            {
                if (involvedColumn._wrappedattribute != null &&
                    !involvedColumn._wrappedattribute.isStatic)
                {
                    involvedColumn._wrappedattribute.isStatic = true;
                    involvedColumn._wrappedattribute.save();
                }
            }
        }
        protected override void DeserializeCore(XmlElement nodeElement, SaveContext context)
        {
            base.DeserializeCore(nodeElement, context);

            var colorNode = nodeElement.ChildNodes.Cast <XmlNode>().FirstOrDefault(x => x.Name == "paramWrapper");

            if (colorNode == null)
            {
                return;
            }

            var deserialized = DeserializeValue(colorNode.InnerText);

            if (deserialized.Name == "None" && deserialized.BipName == "None")
            {
                return;
            }
            SelectedItem = deserialized;
        }
        public ComplectTypeWindow(ParameterGroup parameterGroup)
        {
            ParameterComplectType = new ParameterWrapper(new Parameter {
                ParameterGroup = parameterGroup
            });

            OkCommand = new DelegateCommand(
                () =>
            {
                IsOk = true;
                this.Close();
            },
                () => ParameterComplectType.IsValid);

            ParameterComplectType.PropertyChanged += (sender, args) => ((DelegateCommand)OkCommand).RaiseCanExecuteChanged();

            InitializeComponent();
            this.DataContext = this;
        }
Example #18
0
        public override Candidate SelectBestConversionFor(DynamicMetaObject arg, ParameterWrapper candidateOne, ParameterWrapper candidateTwo, NarrowingLevel level)
        {
            Candidate basePreferred = base.SelectBestConversionFor(arg, candidateOne, candidateTwo, level);

            if (basePreferred == Candidate.One || basePreferred == Candidate.Two)
            {
                return(basePreferred);
            }

            if (Converter.IsNumeric(arg.LimitType))
            {
                if (Converter.IsFloatingPoint(arg.LimitType))
                {
                    if (Converter.IsFloatingPoint(candidateOne.Type))
                    {
                        if (!Converter.IsFloatingPoint(candidateTwo.Type))
                        {
                            return(Candidate.One);
                        }
                    }
                    else if (Converter.IsFloatingPoint(candidateTwo.Type))
                    {
                        return(Candidate.Two);
                    }
                }
                else     // arg is integer
                {
                    if (Converter.IsInteger(candidateOne.Type))
                    {
                        if (!Converter.IsInteger(candidateTwo.Type))
                        {
                            return(Candidate.One);
                        }
                    }
                    else if (Converter.IsInteger(candidateTwo.Type))
                    {
                        return(Candidate.Two);
                    }
                }
            }

            return(basePreferred);
        }
Example #19
0
        public override bool CanConvertFrom(Type/*!*/ fromType, ParameterWrapper/*!*/ toParameter, NarrowingLevel level) {
            Type toType = toParameter.Type;

            if (base.CanConvertFrom(fromType, toParameter, level)) {
                return true;
            }

            // blocks:
            if (fromType == typeof(MissingBlockParam)) {
                return toType == typeof(BlockParam) && !toParameter.ProhibitNull;
            }

            if (fromType == typeof(BlockParam) && toType == typeof(MissingBlockParam)) {
                return true;
            }

            // protocol conversions:
            if (toParameter.ParameterInfo != null && toParameter.ParameterInfo.IsDefined(typeof(DefaultProtocolAttribute), false)) {
                // any type is potentially convertible, except for nil if [NotNull] is used:
                return fromType != typeof(DynamicNull) || !toParameter.ProhibitNull;
            }

            return false;
        }
        public override Candidate SelectBestConversionFor(DynamicMetaObject /*!*/ arg, ParameterWrapper /*!*/ candidateOne,
                                                          ParameterWrapper /*!*/ candidateTwo, NarrowingLevel level)
        {
            Type typeOne    = candidateOne.Type;
            Type typeTwo    = candidateTwo.Type;
            Type actualType = arg.GetLimitType();

            if (actualType == typeof(DynamicNull))
            {
                // if nil is passed as a block argument prefers BlockParam over a missing block:
                if (typeOne == typeof(BlockParam) && typeTwo == typeof(MissingBlockParam))
                {
                    Debug.Assert(!candidateOne.ProhibitNull);
                    return(Candidate.One);
                }

                if (typeOne == typeof(MissingBlockParam) && typeTwo == typeof(BlockParam))
                {
                    Debug.Assert(!candidateTwo.ProhibitNull);
                    return(Candidate.Two);
                }
            }
            else
            {
                if (typeOne == actualType)
                {
                    if (typeTwo == actualType)
                    {
                        // prefer non-nullable reference type over nullable:
                        if (!actualType.IsValueType)
                        {
                            if (candidateOne.ProhibitNull)
                            {
                                return(Candidate.One);
                            }
                            else if (candidateTwo.ProhibitNull)
                            {
                                return(Candidate.Two);
                            }
                        }
                    }
                    else
                    {
                        return(Candidate.One);
                    }
                }
                else if (typeTwo == actualType)
                {
                    return(Candidate.Two);
                }
            }

            // prefer integer type over enum:
            if (typeOne.IsEnum && Enum.GetUnderlyingType(typeOne) == typeTwo)
            {
                return(Candidate.Two);
            }

            if (typeTwo.IsEnum && Enum.GetUnderlyingType(typeTwo) == typeOne)
            {
                return(Candidate.One);
            }

            return(base.SelectBestConversionFor(arg, candidateOne, candidateTwo, level));
        }
        public HttpParamers GetHttpParamers()
        {
            HttpParamers paramers = ParameterWrapper.WrapContract(this.quickContract);

            return(paramers);
        }
 public override bool CanConvertFrom(ParameterWrapper /*!*/ fromParameter, ParameterWrapper /*!*/ toParameter)
 {
     return(Converter.CanConvertFrom(null, fromParameter.Type, toParameter.Type, toParameter.ProhibitNull, NarrowingLevel.None, false, false).IsConvertible);
 }
        /// <summary>
        /// Returns true if fromArg of type fromType can be assigned to toParameter with a conversion on given narrowing level.
        /// </summary>
        public override bool CanConvertFrom(Type /*!*/ fromType, DynamicMetaObject fromArg, ParameterWrapper /*!*/ toParameter, NarrowingLevel level)
        {
            var result = Converter.CanConvertFrom(fromArg, fromType, toParameter.Type, toParameter.ProhibitNull, level,
                                                  HasExplicitProtocolConversion(toParameter), _implicitProtocolConversions
                                                  );

            if (result.Assumption != null)
            {
                if (_argumentAssumptions == null)
                {
                    _argumentAssumptions = new List <Key <int, NarrowingLevel, Ast> >();
                }

                if (_argumentAssumptions.FindIndex((k) => k.First == toParameter.ParameterInfo.Position && k.Second == level) < 0)
                {
                    _argumentAssumptions.Add(Key.Create(toParameter.ParameterInfo.Position, level, result.Assumption));
                }
            }

            return(result.IsConvertible);
        }
Example #24
0
 /// <summary>
 /// Returns true if fromArg of type fromType can be assigned to toParameter with a conversion on given narrowing level.
 /// </summary>
 public override bool CanConvertFrom(Type /*!*/ fromType, DynamicMetaObject fromArg, ParameterWrapper /*!*/ toParameter, NarrowingLevel level)
 {
     return(Converter.CanConvertFrom(fromArg, fromType, toParameter.Type, toParameter.ProhibitNull, level,
                                     HasExplicitProtocolConversion(toParameter), _implicitProtocolConversions
                                     ));
 }
Example #25
0
        public override Candidate SelectBestConversionFor(DynamicMetaObject arg, ParameterWrapper candidateOne, ParameterWrapper candidateTwo, NarrowingLevel level)
        {
            Candidate basePreferred = base.SelectBestConversionFor(arg, candidateOne, candidateTwo, level);

            if (basePreferred == Candidate.One || basePreferred == Candidate.Two)
            {
                return(basePreferred);
            }

            // Work around the choice made in Converter.PreferConvert
            // This cannot be done using NarrowingLevel rules because it would confuse rules for selecting custom operators
            if (level >= PythonNarrowing.IndexOperator && Converter.IsPythonBigInt(arg.LimitType))
            {
                TypeCode c1tc = candidateOne.Type.GetTypeCode();
                TypeCode c2tc = candidateTwo.Type.GetTypeCode();
                if (c1tc is TypeCode.UInt32 && c2tc is TypeCode.Int32)
                {
                    return(Candidate.Two);
                }
                if (c1tc is TypeCode.Int32 && c2tc is TypeCode.UInt32)
                {
                    return(Candidate.One);
                }
                if (c1tc is TypeCode.UInt64 && c2tc is TypeCode.Int64)
                {
                    return(Candidate.Two);
                }
                if (c1tc is TypeCode.Int64 && c2tc is TypeCode.UInt64)
                {
                    return(Candidate.One);
                }
            }

            // This block codifies the following set of rules for Python numerics (i.e. numeric types and any derived types):
            // 1. Prefer the parameter that is of the matching kind to the argument type (i.e. floating-point to floating-point, or integer to integer).
            // 2. If both parameters are of the matching kind, break the tie by prefering the one that is wider, if any (so the chance of overflow is lower).
            //    "Wider" here means being able to represent all values of the narrower type; e.g. in this sense UInt64 is not wider than SByte.
            // There are the following exceptions to these rules:
            // * Rule 1 is not applied to user-defined subtypes (i.e. subclasses of Extensible<T>). This is to allow such types to bind to parameters
            //   of type object or an interface on Extensible<T> (rule from the DLR). It is because a user-defined type may have user-defined operators
            //   that may need to be inspected by the overload and provide additional functionality above a simple numeric value.
            // * Rule 2 is not applied on narrowing level None, so in a case of a widening cast or a perfect type match, the most efficient (narrowest)
            //   type is selected (rule from the DLR).
            // * If one of the parameters is Boolean and the other is numeric, the Boolean parameter is treated as a 1-bit-wide numeric (thus becomes a case for Rule 2).
            //   This makes the preference for numeric types over Boolean consistent with the one encoded using narrowing levels and conversion sequence.
            // TODO: Increase test coverage for cases involving Complex, Decimal, Half
            if (Converter.IsPythonNumeric(arg.LimitType))
            {
                if (Converter.IsPythonFloatingPoint(arg.LimitType))
                {
                    if (Converter.IsFloatingPoint(candidateOne.Type))
                    {
                        if (!Converter.IsFloatingPoint(candidateTwo.Type))
                        {
                            if (!Converter.IsExtensibleNumeric(arg.LimitType))
                            {
                                return(Candidate.One);
                            }
                        }
                        else if (level > PythonNarrowing.None)     // both params are floating point
                        {
                            Candidate preferred = SelectWiderNumericType(candidateOne.Type, candidateTwo.Type);
                            if (preferred != Candidate.Ambiguous)
                            {
                                return(preferred);
                            }
                        }
                    }
                    else if (Converter.IsFloatingPoint(candidateTwo.Type))
                    {
                        if (!Converter.IsExtensibleNumeric(arg.LimitType))
                        {
                            return(Candidate.Two);
                        }
                    }
                }
                else     // arg is integer
                {
                    if (Converter.IsInteger(candidateOne.Type))
                    {
                        if (!Converter.IsInteger(candidateTwo.Type))
                        {
                            if (!Converter.IsExtensibleNumeric(arg.LimitType) || (Converter.IsBoolean(candidateTwo.Type) && level > PythonNarrowing.None))
                            {
                                return(Candidate.One);
                            }
                        }
                        else if (level > PythonNarrowing.None)     // both params are integer
                        {
                            Candidate preferred = SelectWiderNumericType(candidateOne.Type, candidateTwo.Type);
                            if (preferred != Candidate.Ambiguous)
                            {
                                return(preferred);
                            }
                        }
                    }
                    else if (Converter.IsInteger(candidateTwo.Type))
                    {
                        if (!Converter.IsExtensibleNumeric(arg.LimitType) || (Converter.IsBoolean(candidateOne.Type) && level > PythonNarrowing.None))
                        {
                            return(Candidate.Two);
                        }
                    }
                }
            }

            return(basePreferred);
        }
Example #26
0
        public override bool CanConvertFrom(Type fromType, DynamicMetaObject fromArg, ParameterWrapper toParameter, NarrowingLevel level)
        {
            if ((fromType == typeof(List) || fromType.IsSubclassOf(typeof(List))))
            {
                if (toParameter.Type.IsGenericType() &&
                    toParameter.Type.GetGenericTypeDefinition() == typeof(IList <>) &&
                    (toParameter.ParameterInfo.IsDefined(typeof(BytesConversionAttribute), false) ||
                     toParameter.ParameterInfo.IsDefined(typeof(BytesConversionNoStringAttribute), false)))
                {
                    return(false);
                }
            }
            else if (fromType == typeof(string))
            {
                if (toParameter.Type == typeof(IList <byte>) &&
                    !Binder.Context.PythonOptions.Python30 &&
                    toParameter.ParameterInfo.IsDefined(typeof(BytesConversionAttribute), false))
                {
                    // string -> byte array, we allow this in Python 2.6
                    return(true);
                }
            }
            else if (fromType == typeof(Bytes))
            {
                if (toParameter.Type == typeof(string) &&
                    !Binder.Context.PythonOptions.Python30 &&
                    toParameter.ParameterInfo.IsDefined(typeof(BytesConversionAttribute), false))
                {
                    return(true);
                }
            }

            return(base.CanConvertFrom(fromType, fromArg, toParameter, level));
        }
        public override bool CanConvertFrom(Type fromType, DynamicMetaObject fromArg, ParameterWrapper toParameter, NarrowingLevel level)
        {
            if ((fromType == typeof(PythonList) || fromType.IsSubclassOf(typeof(PythonList))))
            {
                if (toParameter.Type.IsGenericType() &&
                    toParameter.Type.GetGenericTypeDefinition() == typeof(IList <>) &&
                    toParameter.ParameterInfo.IsDefined(typeof(BytesConversionAttribute), false))
                {
                    return(false);
                }
            }

            return(base.CanConvertFrom(fromType, fromArg, toParameter, level));
        }
Example #28
0
 private bool IsBytesLikeParameter(ParameterWrapper parameter)
 {
     return(parameter.ParameterInfo?.IsDefined(typeof(BytesLikeAttribute), inherit: false) ?? false);
 }
Example #29
0
        public override bool CanConvertFrom(Type fromType, DynamicMetaObject fromArg, ParameterWrapper toParameter, NarrowingLevel level)
        {
            Type toType = toParameter.Type;

            if (IsBytesLikeParameter(toParameter))
            {
                if ((fromType == typeof(PythonList) || fromType.IsSubclassOf(typeof(PythonList))))
                {
                    if (toType.IsGenericType &&
                        toType.GetGenericTypeDefinition() == typeof(IList <>))
                    {
                        return(false);
                    }
                }

                if (typeof(IBufferProtocol).IsAssignableFrom(fromType))
                {
                    if (toParameter.Type == typeof(IList <byte>) || toParameter.Type == typeof(IReadOnlyList <byte>))
                    {
                        return(true);
                    }
                }
            }

            if (fromType.IsGenericType &&
                fromType.GetGenericTypeDefinition() == typeof(Memory <>) &&
                toType.IsGenericType &&
                toType.GetGenericTypeDefinition() == typeof(ReadOnlyMemory <>) &&
                fromType.GetGenericArguments()[0] == toType.GetGenericArguments()[0])
            {
                return(true);
            }

            if (toType == typeof(IBufferProtocol))
            {
                if (fromType == typeof(Memory <byte>) ||
                    fromType == typeof(ReadOnlyMemory <byte>) ||
                    fromType == typeof(byte[]) ||
                    fromType == typeof(ArraySegment <byte>))
                {
                    return(true);
                }
            }

            if (fromType == typeof(int) && toType.IsAssignableFrom(typeof(BigInteger)))
            {
                return(true); // PEP 237: int/long unification (GH #52)
            }

            return(base.CanConvertFrom(fromType, fromArg, toParameter, level));
        }
Example #30
0
 internal ParameterViewModel(ParameterWrapper wrapper)
 {
     Wrapper = wrapper;
 }
Example #31
0
        private static void AddLinkedValueRowToDataGrid(DataGridView dgObj, GridColumnTemplate gct,
                                                        ParameterWrapper vdo)
        {
            var  newRow      = new DataGridViewRow();
            Enum unitToUse   = null;
            var  varUnitDict =
                (Dictionary <string, Enum>)QraStateContainer.Instance.Parameters["VarUnitDict"];

            varUnitDict.TryGetValue(vdo.Key, out unitToUse);
            unitToUse = unitToUse ?? vdo.Unit;
            string unitDisplayName = null;

            if (unitToUse is UnitlessUnit)
            {
                var uu = (UnitlessUnit)unitToUse;
                if (uu == UnitlessUnit.Unitless)
                {
                    unitDisplayName = "...";
                }
            }

            var valueObj = QraStateContainer.Instance.GetStateDefinedValueObject(vdo.Key);

            var values = valueObj.GetValue(unitToUse);

            if (gct == null && values.Length == 1)
            {
                if (unitToUse is UnitlessUnit || unitDisplayName != null)
                {
                    newRow.CreateCells(dgObj, vdo.VariableDisplayName, Parsing.DoubleToString(values[0]),
                                       unitDisplayName);
                    newRow.Cells[0].ReadOnly = true;
                    newRow.Cells[0].Tag      = vdo.Key;
                    newRow.Cells[2].ReadOnly = true;
                }
                else
                {
                    var unitType       = unitToUse.GetType();
                    var possibleValues = unitType.GetEnumValues();
                    var cbCell         = new DataGridViewComboBoxCell();
                    cbCell.DataSource = possibleValues;
                    cbCell.ValueType  = unitType;

                    newRow.Cells.Add(new DataGridViewTextBoxCell());
                    newRow.Cells.Add(new DataGridViewTextBoxCell());
                    newRow.Cells.Add(cbCell);
                    newRow.Cells[0].Value    = vdo.VariableDisplayName;
                    newRow.Cells[0].Tag      = vdo.Key;
                    newRow.Cells[1].Value    = Parsing.DoubleToString(values[0]);
                    newRow.Cells[2].Value    = unitToUse;
                    newRow.Cells[0].ReadOnly = true;
                }
            }
            else
            {
                if (gct == null && values.Length > 1)
                {
                    throw new Exception("GridColumnTemplate is required when multiple values are specified.");
                }

                var cellValues       = new string[gct.Headers.Length];
                var indexIncrementor = 0;

                if (gct.FirstColumnValues != null)
                {
                    indexIncrementor += 1;

                    cellValues = new string[cellValues.Length + 1];
                    var optionalFirstColumnValueRowIndex = dgObj.Rows.Count - 1;
                    cellValues[0] = gct.FirstColumnValues[optionalFirstColumnValueRowIndex];
                }

                for (var cellIndex = 0; cellIndex < gct.Headers.Length; cellIndex++)
                {
                    if (values.Length > cellIndex)
                    {
                        var svalue = values[cellIndex].ToString("F2", new CultureInfo("en-US"));
                        cellValues[cellIndex + indexIncrementor] = svalue;
                    }
                }


                newRow.CreateCells(dgObj, cellValues);
            }

            vdo.OriginalValues = values;

            vdo.Unit   = unitToUse;
            newRow.Tag = vdo;

            dgObj.Rows.Add(newRow);
        }
Example #32
0
        public override Candidate SelectBestConversionFor(Type/*!*/ actualType, ParameterWrapper/*!*/ candidateOne, ParameterWrapper/*!*/ candidateTwo, NarrowingLevel level) {
            Type typeOne = candidateOne.Type;
            Type typeTwo = candidateTwo.Type;

            if (actualType == typeof(DynamicNull)) {
                // if nil is passed as a block argument prefer BlockParam over missing block;
                if (typeOne == typeof(BlockParam) && typeTwo == typeof(MissingBlockParam)) {
                    return Candidate.One;
                }

                if (typeOne == typeof(MissingBlockParam) && typeTwo == typeof(BlockParam)) {
                    return Candidate.Two;
                }
            } else {
                if (actualType == typeOne && candidateOne.ProhibitNull) {
                    return Candidate.One;
                }

                if (actualType == typeTwo && candidateTwo.ProhibitNull) {
                    return Candidate.Two;
                }
            }

            if (actualType == typeOne) {
                return Candidate.One;
            }

            if (actualType == typeTwo) {
                return Candidate.Two;
            }


            return Candidate.Equivalent;
        }