예제 #1
0
 internal static T[] AsArrayInternal <T>(this IEnumerable <T>?source)
 {
     if (source == null)
     {
         return(ArrayEx.Empty <T>());
     }
     if (source is T[] array)
     {
         return(array);
     }
     if (source is ReadOnlyCollectionEx <T> readOnlyCollectionEx)
     {
         return(readOnlyCollectionEx.Wrapped is T[] wrappedArray ? wrappedArray : readOnlyCollectionEx.ToArray());
     }
     if (source is ICollection <T> collection1 && collection1.Count == 0)
     {
         return(ArrayEx.Empty <T>());
     }
     if (source is ICollection <T> collection2)
     {
         var result = new T[collection2.Count];
         collection2.CopyTo(result, 0);
         return(result);
     }
     return(new List <T>(source).ToArray());
 }
예제 #2
0
            protected internal override Expression VisitLambda <T>(Expression <T> node)
            {
                IEnumerable <ParameterExpression> parameters = ArrayEx.Empty <ParameterExpression>();

                var count = node.ParameterCount;

                if (count > 0)
                {
                    var parameterList = new List <ParameterExpression>(count);

                    for (var i = 0; i < count; i++)
                    {
                        parameterList.Add(node.GetParameter(i));
                    }

                    parameters = parameterList;
                }

                PushParameters(parameters);

                base.VisitLambda(node);

                PopParameters(parameters);

                return(node);
            }
예제 #3
0
 // Constructs a new sorted list. The sorted list is initially empty and has
 // a capacity of zero. Upon adding the first element to the sorted list the
 // capacity is increased to 16, and then increased in multiples of two as
 // required. The elements of the sorted list are ordered according to the
 // IComparable interface, which must be implemented by the keys of
 // all entries added to the sorted list.
 public SortedList()
 {
     _keys     = ArrayEx.Empty <object>();
     _values   = ArrayEx.Empty <object>();
     _size     = 0;
     _comparer = new Comparer(CultureInfo.CurrentCulture);
 }
 public ConditionalExtendedList(IEnumerable <T> target, IEnumerable <T> append, Func <bool>?enumerateTarget, Func <bool>?enumerateAppend)
 {
     _target          = target?.WrapAsIList() ?? ArrayEx.Empty <T>();
     _append          = append?.WrapAsIList() ?? ArrayEx.Empty <T>();
     _enumerateTarget = enumerateTarget ?? (target == null ? FuncHelper.GetFallacyFunc() : FuncHelper.GetTautologyFunc());
     _enumerateAppend = enumerateAppend ?? (append == null ? FuncHelper.GetFallacyFunc() : FuncHelper.GetTautologyFunc());
 }
예제 #5
0
        internal PathInfo(
            PathType pathType,
            string path,
            bool isValidHelperLiteral,
            int contextChangeCount,
            IReadOnlyList <PathSegment> segments)
        {
            IsValidHelperLiteral = isValidHelperLiteral;
            HasValue             = pathType != PathType.Empty;
            _path = path;

            _hashCode = (_path.GetHashCode() * 397) ^ HasValue.GetHashCode();

            if (!HasValue)
            {
                return;
            }

            IsVariable    = pathType == PathType.Variable;
            IsInversion   = pathType == PathType.Inversion;
            IsBlockHelper = pathType == PathType.BlockHelper;
            IsBlockClose  = pathType == PathType.BlockClose;

            ContextChangeDepth = contextChangeCount;
            HasContextChange   = ContextChangeDepth > 0;

            var plainSegments = segments.Where(o => !o.IsContextChange && o.IsNotEmpty).ToArray();

            IsThis     = string.Equals(path, "this", StringComparison.OrdinalIgnoreCase) || path == "." || plainSegments.Any(o => o.IsThis);
            IsPureThis = string.Equals(path, "this", StringComparison.OrdinalIgnoreCase) || path == ".";

            var segment = plainSegments.SingleOrDefault(o => !o.IsThis);

            if (!segment.IsNotEmpty)
            {
                IsPureThis  = true;
                TrimmedPath = ".";
                PathChain   = ArrayEx.Empty <ChainSegment>();
                return;
            }

            PathChain = segment.PathChain;
            var lastIndex = segment.PathChain.Length - 1;

            using (var container = StringBuilderPool.Shared.Use())
            {
                for (int index = 0; index < PathChain.Length; index++)
                {
                    container.Value.Append(PathChain[index].TrimmedValue);
                    if (index != lastIndex)
                    {
                        container.Value.Append('.');
                    }
                }

                TrimmedPath = container.Value.ToString();
            }

            _trimmedHashCode = TrimmedPath.GetHashCode();
        }
예제 #6
0
        protected override Expression VisitIteratorExpression(IteratorExpression iex)
        {
            var context = Arg <BindingContext>(CompilationContext.BindingContext);

            var template = FunctionBuilder.CompileCore(new[] { iex.Template }, CompilationContext.Configuration);
            var ifEmpty  = FunctionBuilder.CompileCore(new[] { iex.IfEmpty }, CompilationContext.Configuration);

            if (iex.Sequence is PathExpression pathExpression)
            {
                pathExpression.Context = PathExpression.ResolutionContext.Parameter;
            }

            var compiledSequence  = Arg <object>(FunctionBuilder.Reduce(iex.Sequence, CompilationContext));
            var blockParamsValues = CreateBlockParams();

            return(Call(() =>
                        Iterator.Iterate(context, blockParamsValues, compiledSequence, template, ifEmpty)
                        ));

            ExpressionContainer <ChainSegment[]> CreateBlockParams()
            {
                var parameters = iex.BlockParams?.BlockParam?.Parameters;

                if (parameters == null)
                {
                    parameters = ArrayEx.Empty <ChainSegment>();
                }

                return(Arg(parameters));
            }
        }
예제 #7
0
        internal static T[] AsArrayInternal <T>(this IEnumerable <T> source)
        {
            switch (source)
            {
            case null:
                return(ArrayEx.Empty <T>());

            case T[] array:
                return(array);

            case ReadOnlyCollectionEx <T> readOnlyCollectionEx when readOnlyCollectionEx.Wrapped is T[] array:
                return(array);

            case ICollection <T> collection when collection.Count == 0:
                return(ArrayEx.Empty <T>());

            case ICollection <T> collection:
                var result = new T[collection.Count];
                collection.CopyTo(result, 0);
                return(result);

            default:
                return(new List <T>(source).ToArray());
            }
        }
예제 #8
0
        public static TResult[] Select <T, TResult>(this T[] array, Func <T, TResult> selector)
        {
            if (array == null)
            {
                throw new ArgumentNullException("array");
            }

            if (array.Length == 0)
            {
                return(ArrayEx.Empty <TResult>());
            }

            if (selector == null)
            {
                throw new ArgumentNullException("selector");
            }

            var result = new TResult[array.Length];

            for (int i = 0; i < array.Length; i++)
            {
                result[i] = selector(array[i]);
            }

            return(result);
        }
예제 #9
0
 public InventoryItem()
 {
     Id      = EmptyID;
     Color01 = DefaultColor;
     Color02 = DefaultColor;
     Sockets = ArrayEx.Empty <int>();
 }
예제 #10
0
        /// <summary>
        ///     Creates an <see cref="IndexExpression" /> to access an array.
        /// </summary>
        /// <param name="array">An expression representing the array to index.</param>
        /// <param name="indexes">An <see cref="IEnumerable{T}" /> containing expressions used to index the array.</param>
        /// <remarks>
        ///     The expression representing the array can be obtained by using the <see cref="MakeMemberAccess" /> method,
        ///     or through <see cref="NewArrayBounds(System.Type,System.Linq.Expressions.Expression[])" /> or
        ///     <see cref="NewArrayInit(System.Type,System.Linq.Expressions.Expression[])" />.
        /// </remarks>
        /// <returns>The created <see cref="IndexExpression" />.</returns>
        public static IndexExpression ArrayAccess(Expression array, IEnumerable <Expression>?indexes)
        {
            if (array == null)
            {
                throw new ArgumentNullException(nameof(array));
            }

            ExpressionUtils.RequiresCanRead(array, nameof(array));

            var arrayType = array.Type;

            if (!arrayType.IsArray)
            {
                throw new ArgumentException("Argument must be array", nameof(array));
            }

            if (indexes != null)
            {
                return(ArrayAccessExtracted(array, indexes, arrayType));
            }

            if (arrayType.GetArrayRank() != 0)
            {
                throw new ArgumentException("Incorrect number of indexes");
            }

            return(new IndexExpression(array, null, ArrayEx.Empty <Expression>()));
        }
예제 #11
0
        public static object Get(Type type, IEnumerable <Type> preferredTypes)
        {
            if (!_dataGenerators.TryGetValue(type, out var dictionary))
            {
                return(type.GetTypeInfo().IsValueType ? Activator.CreateInstance(type) : null);
            }

            Delegate @delegate = null;

            foreach (var preferredType in preferredTypes)
            {
                if (!dictionary.TryGetValue(preferredType, out var found))
                {
                    continue;
                }

                @delegate = found;
                break;
            }

            if (@delegate == null)
            {
                @delegate = dictionary.First().Value;
            }

            return(@delegate.DynamicInvoke(ArrayEx.Empty <object>()));
        }
예제 #12
0
        public static PathInfo Parse(string path)
        {
            if (path == "null")
            {
                return(new PathInfo(PathType.Empty, path, false, 0, null));
            }

            var originalPath  = path;
            var pathSubstring = new Substring(path);

            var isValidHelperLiteral = true;
            var pathType             = GetPathType(pathSubstring);
            var isVariable           = pathType == PathType.Variable;
            var isInversion          = pathType == PathType.Inversion;
            var isBlockHelper        = pathType == PathType.BlockHelper;

            if (isVariable || isBlockHelper || isInversion)
            {
                isValidHelperLiteral = isBlockHelper || isInversion;
                pathSubstring        = new Substring(pathSubstring, 1);
            }

            var contextChangeCount = 0;
            var segments           = new List <PathSegment>();
            var pathParts          = Substring.Split(pathSubstring, '/');

            if (pathParts.Count > 1)
            {
                isValidHelperLiteral = false;
            }
            for (var index = 0; index < pathParts.Count; index++)
            {
                var segment = pathParts[index];
                if (segment.Length == 2 && segment[0] == '.' && segment[1] == '.')
                {
                    contextChangeCount++;
                    isValidHelperLiteral = false;
                    segments.Add(new PathSegment(segment, ArrayEx.Empty <ChainSegment>()));
                    continue;
                }

                if (segment.Length == 1 && segment[0] == '.')
                {
                    isValidHelperLiteral = false;
                    segments.Add(new PathSegment(segment, ArrayEx.Empty <ChainSegment>()));
                    continue;
                }

                var chainSegments = GetPathChain(segment).ToArray();
                if (chainSegments.Length > 1)
                {
                    isValidHelperLiteral = false;
                }

                segments.Add(new PathSegment(segment, chainSegments));
            }

            return(new PathInfo(pathType, originalPath, isValidHelperLiteral, contextChangeCount, segments));
        }
예제 #13
0
        public static PathInfo Parse(string path)
        {
            if (path == "null")
            {
                return(Empty);
            }

            var originalPath  = path;
            var pathType      = GetPathType(path);
            var pathSubstring = new Substring(path);

            var isValidHelperLiteral = true;
            var isVariable           = pathType == PathType.Variable;
            var isInversion          = pathType == PathType.Inversion;
            var isBlockHelper        = pathType == PathType.BlockHelper;

            if (isVariable || isBlockHelper || isInversion)
            {
                isValidHelperLiteral = isBlockHelper || isInversion;
                pathSubstring        = new Substring(pathSubstring, 1);
            }

            var segments           = new List <PathSegment>();
            var pathParts          = Substring.Split(pathSubstring, '/');
            var extendedEnumerator = ExtendedEnumerator <Substring> .Create(pathParts);

            while (extendedEnumerator.MoveNext())
            {
                var segment = extendedEnumerator.Current.Value;
                if (segment.Length == 2 && segment[0] == '.' && segment[1] == '.')
                {
                    isValidHelperLiteral = false;
                    segments.Add(new PathSegment(segment, ArrayEx.Empty <ChainSegment>()));
                    continue;
                }

                if (segment.Length == 1 && segment[0] == '.')
                {
                    isValidHelperLiteral = false;
                    segments.Add(new PathSegment(segment, ArrayEx.Empty <ChainSegment>()));
                    continue;
                }

                var chainSegments = GetPathChain(segment);
                if (chainSegments.Length > 1)
                {
                    isValidHelperLiteral = false;
                }

                segments.Add(new PathSegment(segment, chainSegments));
            }

            if (isValidHelperLiteral && segments.Count > 1)
            {
                isValidHelperLiteral = false;
            }

            return(new PathInfo(pathType, originalPath, isValidHelperLiteral, segments.ToArray()));
        }
예제 #14
0
 /// <summary>
 ///     Creates an <see cref="InvocationExpression" /> that
 ///     applies a delegate or lambda expression to a list of argument expressions.
 /// </summary>
 /// <returns>
 ///     An <see cref="InvocationExpression" /> that
 ///     applies the specified delegate or lambda expression to the provided arguments.
 /// </returns>
 /// <param name="expression">
 ///     An <see cref="Expression" /> that represents the delegate
 ///     or lambda expression to be applied.
 /// </param>
 /// <param name="arguments">
 ///     An <see cref="IEnumerable{TDelegate}" /> of <see cref="Expression" /> objects
 ///     that represent the arguments that the delegate or lambda expression is applied to.
 /// </param>
 /// <exception cref="ArgumentNullException">
 ///     <paramref name="expression" /> is null.
 /// </exception>
 /// <exception cref="ArgumentException">
 ///     <paramref name="expression" />.Type does not represent a delegate type or an <see cref="Expression{TDelegate}" />
 ///     .-or-The <see cref="Type" /> property of an element of <paramref name="arguments" /> is not assignable to the type
 ///     of the corresponding parameter of the delegate represented by <paramref name="expression" />.
 /// </exception>
 /// <exception cref="InvalidOperationException">
 ///     <paramref name="arguments" /> does not contain the same number of elements as the list of parameters for the
 ///     delegate represented by <paramref name="expression" />.
 /// </exception>
 public static InvocationExpression Invoke(Expression expression, IEnumerable <Expression>?arguments)
 {
     if (expression == null)
     {
         throw new ArgumentNullException(nameof(expression));
     }
     return(InvokeExtracted(expression, arguments ?? ArrayEx.Empty <Expression>()));
 }
예제 #15
0
        public void ResizeWithLengthLessThanZeroThrows()
        {
            var array = ArrayEx.Empty <int>();

            Assert.That(() =>
                        array.Resize(-1),
                        Throws.InstanceOf <ArgumentOutOfRangeException>());
        }
예제 #16
0
        public void SelectWithEmptyArrayAndNullLambdaDoesNotThrow()
        {
            var array = ArrayEx.Empty <int>();

            Assert.That(new TestDelegate(() =>
                                         array.Select <int, byte>(null)),
                        Throws.Nothing);
        }
        /// <inheritdoc />
        public Assembly[] GetAssemblies()
        {
#if SSHARP
            return(ArrayEx.Empty <Assembly>());
#else
            return(Array.Empty <Assembly>());
#endif
        }
예제 #18
0
 public QuadTreeNode(Vector3 center, float size, int maxDepth)
 {
     Size     = size;
     MaxDepth = maxDepth;
     m_items  = ArrayEx.Empty <T>();
     Bound    = CreateBBox(center, size);
     m_childs = ArrayEx.Empty <QuadTreeNode <T> >();
     Center   = new Vector3(center.X, 0f, center.Z);
 }
예제 #19
0
 /// <summary>
 ///     Creates a <see cref="TryExpression" /> representing a try block with the specified elements.
 /// </summary>
 /// <param name="type">The result type of the try expression. If null, body and all handlers must have identical type.</param>
 /// <param name="body">The body of the try block.</param>
 /// <param name="finally">
 ///     The body of the finally block. Pass null if the try block has no finally block associated with
 ///     it.
 /// </param>
 /// <param name="fault">The body of the t block. Pass null if the try block has no fault block associated with it.</param>
 /// <param name="handlers">
 ///     A collection of <see cref="CatchBlock" />s representing the catch statements to be associated
 ///     with the try block.
 /// </param>
 /// <returns>The created <see cref="TryExpression" />.</returns>
 public static TryExpression MakeTry(Type?type, Expression body, Expression? @finally, Expression?fault, IEnumerable <CatchBlock>?handlers)
 {
     ContractUtils.RequiresNotNull(body, nameof(body));
     ExpressionUtils.RequiresCanRead(body, nameof(body));
     if (handlers == null)
     {
         return(MakeTryExtracted(type, body, @finally, fault, ArrayEx.Empty <CatchBlock>()));
     }
     return(MakeTryExtracted(type, body, @finally, fault, handlers));
 }
예제 #20
0
 public WorldObject(uint guid, ObjectsMgr manager)
 {
     _manager    = manager;
     _lock       = new object();
     _server     = manager.Server;
     _guid       = guid | (uint)(TypeID << 16);
     _updatable  = ArrayEx.Empty <IUpdatable>();
     _components = ArrayEx.Empty <ObjectComponent>();
     _manager.Add(this);
 }
예제 #21
0
        public static PathInfo GetPathInfo(string path)
        {
            if (path == "null")
            {
                return(new PathInfo(false, path, false, null));
            }

            var originalPath = path;

            var isValidHelperLiteral = true;
            var isVariable           = path.StartsWith("@");
            var isInversion          = path.StartsWith("^");
            var isBlockHelper        = path.StartsWith("#");

            if (isVariable || isBlockHelper || isInversion)
            {
                isValidHelperLiteral = isBlockHelper || isInversion;
                path = path.Substring(1);
            }

            var segments  = new List <PathSegment>();
            var pathParts = path.Split('/');

            if (pathParts.Length > 1)
            {
                isValidHelperLiteral = false;
            }
            foreach (var segment in pathParts)
            {
                if (segment == "..")
                {
                    isValidHelperLiteral = false;
                    segments.Add(new PathSegment(segment, ArrayEx.Empty <ChainSegment>()));
                    continue;
                }

                if (segment == ".")
                {
                    isValidHelperLiteral = false;
                    segments.Add(new PathSegment(segment, ArrayEx.Empty <ChainSegment>()));
                    continue;
                }

                var segmentString = isVariable ? "@" + segment : segment;
                var chainSegments = GetPathChain(segmentString).ToArray();
                if (chainSegments.Length > 1)
                {
                    isValidHelperLiteral = false;
                }

                segments.Add(new PathSegment(segmentString, chainSegments));
            }

            return(new PathInfo(true, originalPath, isValidHelperLiteral, segments.ToArray()));
        }
예제 #22
0
 private QuadTreeNode(QuadTreeNode <T> parent, Vector3 center, float size)
 {
     Size     = size;
     Center   = center;
     Parent   = parent;
     Depth    = parent.Depth + 1;
     MaxDepth = parent.MaxDepth;
     m_items  = ArrayEx.Empty <T>();
     Bound    = CreateBBox(center, size);
     m_childs = ArrayEx.Empty <QuadTreeNode <T> >();
 }
        public bool TryGetDescriptor(Type type, out ObjectDescriptor value)
        {
            if (!Type.IsAssignableFrom(type))
            {
                value = ObjectDescriptor.Empty;
                return(false);
            }

            value = (ObjectDescriptor)Factory.MakeGenericMethod(type).Invoke(null, ArrayEx.Empty <object>());
            return(true);
        }
예제 #24
0
 public IEnumerable <TElement> this[TKey key]
 {
     get
     {
         if (_groupings.TryGetValue(key, out var grouping))
         {
             return(grouping);
         }
         return(ArrayEx.Empty <TElement>());
     }
 }
예제 #25
0
        public void HoistedParameter()
        {
            var i = Expression.Parameter(typeof(int), "i");

            var l = Expression.Lambda <Func <int, string> >(
                Expression.Invoke(
                    Expression.Lambda <Func <string> >(
                        Expression.Call(i, typeof(int).GetMethod("ToString", ArrayEx.Empty <Type>())))), i).Compile();

            Assert.AreEqual("42", l(42));
        }
예제 #26
0
 public static ICollection <T> AsICollection <T>(this IEnumerable <T>?source)
 {
     if (source == null)
     {
         return(ArrayEx.Empty <T>());
     }
     if (source is ICollection <T> collection)
     {
         return(collection);
     }
     return(EnumerationList <T> .Create(source));
 }
예제 #27
0
        public void CompileSimpleInstanceCall()
        {
            var p = Expression.Parameter(typeof(string), "p");
            var lambda = Expression.Lambda<Func<string, string>>(
                Expression.Call(
                    p, typeof(string).GetMethod("ToString", ArrayEx.Empty<Type>())),
                p);

            var ts = lambda.Compile();

            Assert.AreEqual("foo", ts("foo"));
            Assert.AreEqual("bar", ts("bar"));
        }
예제 #28
0
        internal PathInfo(
            bool hasValue,
            string path,
            bool isValidHelperLiteral,
            PathSegment[] segments
            )
        {
            IsValidHelperLiteral = isValidHelperLiteral;
            HasValue             = hasValue;
            _path = path;

            unchecked
            {
                _hashCode = (_path.GetHashCode() * 397) ^ HasValue.GetHashCode();
            }

            if (!HasValue)
            {
                return;
            }

            IsVariable    = path.StartsWith("@");
            IsInversion   = path.StartsWith("^");
            IsBlockHelper = path.StartsWith("#");
            IsBlockClose  = path.StartsWith("/");

            ContextChangeDepth = segments?.Count(o => o.IsContextChange) ?? 0;
            HasContextChange   = ContextChangeDepth > 0;
            var plainSegments = segments?.Where(o => !o.IsContextChange && !string.IsNullOrEmpty(o.ToString())).ToArray() ?? ArrayEx.Empty <PathSegment>();

            IsThis     = string.Equals(path, "this", StringComparison.OrdinalIgnoreCase) || path == "." || plainSegments.Any(o => o.IsThis);
            IsPureThis = string.Equals(path, "this", StringComparison.OrdinalIgnoreCase) || path == ".";

            var segment = plainSegments.SingleOrDefault(o => !o.IsThis);

            if (segment == null)
            {
                IsPureThis  = true;
                TrimmedPath = ".";
                PathChain   = ArrayEx.Empty <ChainSegment>();
                return;
            }

            TrimmedPath = string.Join(".", segment.PathChain.Select(o => o.TrimmedValue));
            PathChain   = segment.PathChain;

            unchecked
            {
                _trimmedHashCode = TrimmedPath.GetHashCode();
            }
        }
예제 #29
0
        public static ICollection <T> AsICollection <T>(this IEnumerable <T> source)
        {
            switch (source)
            {
            case null:
                return(ArrayEx.Empty <T>());

            case ICollection <T> result:
                return(result);

            default:
                return(new ProgressiveCollection <T>(source));
            }
        }
예제 #30
0
        public void NewBar()
        {
            var n = Expression.New(typeof(Bar));

            Assert.IsNotNull(n.Constructor);
            Assert.IsNotNull(n.Arguments);
            Assert.IsNull(n.Members); // wrong doc

            Assert.AreEqual("new Bar()", n.ToString());

            n = Expression.New(typeof(Bar).GetConstructor(ArrayEx.Empty <Type>()));

            Assert.AreEqual("new Bar()", n.ToString());
        }