Beispiel #1
0
        public virtual void __construct(Traversable iterator, string classname = null)
        {
            if (classname != null)
            {
                //var downcast = ctx.ResolveType(PhpVariable.AsString(classname), null, this.iterator.TypeDesc, null, ResolveTypeFlags.ThrowErrors);

                PhpException.ArgumentValueNotSupported(nameof(classname), classname);
                throw new NotImplementedException();
            }

            _iterator   = iterator;
            _valid      = false;
            _enumerator = null;

            if (iterator is Iterator)
            {
                // ok
            }
            else
            {
                PhpException.InvalidArgument(nameof(iterator));
            }

            //rewind(context);  // not in PHP, performance reasons (foreach causes rewind() itself)
        }
Beispiel #2
0
        /// <summary>
        ///     Will walk the path by using the path seperator "." and evaluate the object at the end
        /// </summary>
        /// <returns></returns>
        internal ContextObject GetContextForPath(Traversable elements,
                                                 ScopeData scopeData,
                                                 IMorestachioExpression morestachioExpression)
        {
            if (_key == "x:null" || !elements.HasValue)
            {
                return(this);
            }
            //look at the first element if its an alias switch to that alias
            //var peekPathPart = elements.Peek();
            if (elements.Count == 1 && elements.Current.Value == PathType.Null)
            {
                return(scopeData.ParserOptions.CreateContextObject("x:null", null));
            }

            var targetContext = this;

            if (elements.Current.Value == PathType.DataPath)
            {
                var getFromAlias = scopeData.GetVariable(targetContext, elements.Current.Key);
                if (getFromAlias != null)
                {
                    elements      = elements.Next();
                    targetContext = getFromAlias;
                }
            }

            return(targetContext.LoopContextTraversable(elements, scopeData, morestachioExpression));
            //return await targetContext.GetContextForPathInternal(elements, scopeData, morestachioExpression);
        }
        public void TestTraverse()
        {
            var traversable = new Traversable();
            var child1      = new Traversable();

            child1.Children.Add(new Traversable());
            var child2 = new Traversable();

            child2.Children.Add(new Traversable());
            child2.Children.Add(new Traversable());
            var child3 = new Traversable();

            child3.Children.Add(new Traversable());
            child3.Children.Add(new Traversable());
            child3.Children.Add(new Traversable());
            traversable.Children.Add(child1);
            traversable.Children.Add(child2);
            traversable.Children.Add(child3);

            var expected = new[] { traversable }
            .Append(child1)
            .Append(child2)
            .Append(child3)
            .Concat(child1.Children)
            .Concat(child2.Children)
            .Concat(child3.Children);

            Check.That(new[] { traversable }.Traverse(t => t.Children)).ContainsExactly(expected);
        }
Beispiel #4
0
        /// <summary>
        ///     Will walk the path by using the path seperator "." and evaluate the object at the end
        /// </summary>
        /// <returns></returns>
        internal async ContextObjectPromise GetContextForPath(Traversable elements,
                                                              ScopeData scopeData,
                                                              IMorestachioExpression morestachioExpression)
        {
            if (Key == "x:null" || !elements.HasValue)
            {
                return(this);
            }
            //look at the first element if its an alias switch to that alias
            //var peekPathPart = elements.Peek();
            if (elements.Count == 1 && elements.Current.Value == PathType.Null)
            {
                return(Options.CreateContextObject("x:null", CancellationToken, null));
            }

            if (elements.Current.Value == PathType.DataPath)
            {
                var getFromAlias = scopeData.GetVariable(elements.Current.Key);
                if (getFromAlias != null)
                {
                    elements = elements.Next();
                    return(await getFromAlias.GetContextForPathInternal(elements, scopeData, morestachioExpression));
                }
            }

            return(await GetContextForPathInternal(elements, scopeData, morestachioExpression));
        }
Beispiel #5
0
        public override void __construct(Traversable iterator, string classname = null)
        {
            if (!(iterator is RecursiveIterator))
            {
                PhpException.InvalidArgument(nameof(iterator));
            }

            base.__construct(iterator, classname);
        }
Beispiel #6
0
        /// <inheritdoc />
        public void ReadXml(XmlReader reader)
        {
            Location          = CharacterLocation.FromFormatString(reader.GetAttribute(nameof(Location)));
            EndsWithDelimiter = reader.GetAttribute(nameof(EndsWithDelimiter)) == bool.TrueString;
            var pathParts = new List <KeyValuePair <string, PathType> >();

            reader.ReadStartElement();            //Path

            if (reader.Name == "Path")
            {
                reader.ReadStartElement();                //Any SubPath

                while (reader.Name != "Path" && reader.NodeType != XmlNodeType.EndElement)
                {
                    var    partName  = reader.Name;
                    string partValue = null;
                    if (reader.IsEmptyElement)
                    {
                        reader.ReadStartElement();
                    }
                    else
                    {
                        partValue = reader.ReadElementContentAsString();
                    }
                    pathParts.Add(new KeyValuePair <string, PathType>(partValue, (PathType)Enum.Parse(typeof(PathType), partName)));
                }
                reader.ReadEndElement();                //</Path>
            }
            PathParts = new Traversable(pathParts);
            if (reader.Name == "Format" && reader.NodeType == XmlNodeType.Element)
            {
                FormatterName = reader.GetAttribute(nameof(FormatterName));
                if (reader.IsEmptyElement)
                {
                    reader.ReadStartElement();
                }
                else
                {
                    reader.ReadStartElement();                     //<Argument>
                    while (reader.Name == "Argument" && reader.NodeType != XmlNodeType.EndElement)
                    {
                        var formatSubTree = reader.ReadSubtree();
                        formatSubTree.Read();

                        var expressionArgument = new ExpressionArgument();
                        Formats.Add(expressionArgument);

                        expressionArgument.ReadXml(formatSubTree);

                        reader.Skip();
                        reader.ReadEndElement();
                    }
                    reader.ReadEndElement();                    //</Format>
                }
            }
            reader.ReadEndElement();
        }
Beispiel #7
0
 /// <summary>
 ///		Serialization constructor
 /// </summary>
 /// <param name="info"></param>
 /// <param name="context"></param>
 protected MorestachioExpression(SerializationInfo info, StreamingContext context)
 {
     PathParts = new Traversable(info.GetValue(nameof(PathParts), typeof(KeyValuePair <string, PathType>[])) as KeyValuePair <string, PathType>[]);
     Formats   = info.GetValue(nameof(Formats), typeof(IList <ExpressionArgument>))
                 as IList <ExpressionArgument>;
     FormatterName     = info.GetString(nameof(FormatterName));
     Location          = CharacterLocation.FromFormatString(info.GetString(nameof(Location)));
     EndsWithDelimiter = info.GetBoolean(nameof(EndsWithDelimiter));
 }
Beispiel #8
0
        public virtual void __construct(Traversable iterator, long offset = 0, long count = -1)
        {
            base.__construct(iterator);

            if (offset < 0)
            {
                throw new OutOfRangeException();
            }

            _offset = offset;
            _max    = count >= 0 ? offset + count : long.MaxValue;
        }
Beispiel #9
0
        internal ContextObject LoopContextTraversable(Traversable elements,
                                                      ScopeData scopeData,
                                                      IMorestachioExpression morestachioExpression)
        {
            ContextObject context = this;

            while (elements != null && elements.HasValue)
            {
                context  = context.GetContextForPathInternal(elements, scopeData, morestachioExpression);
                elements = elements.Next();
            }

            return(context);
        }
        /// <inheritdoc />
        protected override ContextObject HandlePathContext(
            Traversable elements,
            KeyValuePair <string, PathType> currentElement,
            IMorestachioExpression morestachioExpression,
            ScopeData scopeData)
        {
            if (currentElement.Value != PathType.DataPath || !currentElement.Key.StartsWith("$"))
            {
                return(null);
            }
            object value = null;

            if (currentElement.Key.Equals("$first"))
            {
                value = scopeData.PartialDepth.Count;
            }
            return(value == null ? null : Options.CreateContextObject(currentElement.Key, CancellationToken, value, this));
        }
        public virtual void __construct(Traversable it, int flags = BYPASS_KEY, int cit_flags = CachingIterator.CATCH_GET_CHILD, int mode = SELF_FIRST)
        {
            if (it is IteratorAggregate ia)
            {
                it = ia.getIterator();
            }

            if (!(it is Iterator))
            {
                PhpException.InvalidArgument(nameof(it));
            }

            _flags = flags;

            var cachingIt = new RecursiveCachingIterator(_ctx, (Iterator)it, cit_flags);

            base.__construct(cachingIt, mode);
        }
        /// <summary>
        /// Copy the elements of an iterator into an array.
        /// </summary>
        /// <param name="iterator">The iterator being copied.</param>
        /// <param name="use_keys">Whether to use the iterator element keys as index.</param>
        /// <returns>An array containing the elements of the iterator.</returns>
        public static PhpArray iterator_to_array(Traversable iterator, bool use_keys = true)
        {
            // NULL
            if (iterator == null)
            {
                throw new ArgumentNullException(nameof(iterator));
            }

            // Iterator:
            if (iterator is Iterator real_iterator)
            {
                var array = new PhpArray();

                real_iterator.rewind();

                while (real_iterator.valid())
                {
                    var value = real_iterator.current();
                    if (use_keys)
                    {
                        array.Add(real_iterator.key().ToIntStringKey(), value);
                    }
                    else
                    {
                        array.Add(value);
                    }

                    //
                    real_iterator.next();
                }

                //
                return(array);
            }

            // IteratorAggregate
            if (iterator is IteratorAggregate aggr)
            {
                return(iterator_to_array(aggr.getIterator(), use_keys: use_keys));
            }

            // invalid argument
            throw new ArgumentException();
        }
Beispiel #13
0
        /// <summary>
        /// The method implements <c>...</c> unpack operator.
        /// Unpacks <paramref name="traversable"/> into <paramref name="stack"/>.
        /// </summary>
        /// <param name="stack">The list with unpacked arguments.</param>
        /// <param name="traversable">Value to be unpacked.</param>
        /// <param name="byrefs">Bit mask of parameters that are passed by reference. Arguments corresponding to <c>1</c>-bit are aliased.</param>
        public static void Unpack(List <PhpValue> stack, Traversable traversable, ulong byrefs)
        {
            Debug.Assert(traversable != null);
            Debug.Assert(traversable is Iterator, "Iterator expected.");

            var iterator = (Iterator)traversable;

            iterator.rewind();
            while (iterator.valid())
            {
                Debug.Assert((byrefs & (1ul << stack.Count)) == 0, "Cannot pass by-reference when unpacking a Traversable");
                //{
                //    // TODO: Warning: Cannot pass by-reference argument {stack.Count + 1} of {function_name}() by unpacking a Traversable, passing by-value instead
                //}

                stack.Add(iterator.current());
                iterator.next();
            }
        }
        /// <inheritdoc />
        protected override ContextObject HandlePathContext(Traversable elements,
                                                           KeyValuePair <string, PathType> path,
                                                           IMorestachioExpression expression, ScopeData scopeData)
        {
            if (path.Value != PathType.DataPath || !path.Key.StartsWith("$"))
            {
                return(null);
            }

            object value = null;

            if (path.Key.Equals("$first"))
            {
                value = Index == 0;
            }
            else if (path.Key.Equals("$index"))
            {
                value = Index;
            }
            else if (path.Key.Equals("$middel"))
            {
                value = Index != 0 && !Last;
            }
            else if (path.Key.Equals("$last"))
            {
                value = Last;
            }
            else if (path.Key.Equals("$odd"))
            {
                value = Index % 2 != 0;
            }
            else if (path.Key.Equals("$even"))
            {
                value = Index % 2 == 0;
            }
            return(value == null ? null : Options.CreateContextObject(path.Key, CancellationToken, value, this));
        }
 public virtual void __construct(Traversable iterator, int mode = LEAVES_ONLY, int flags = 0)
 {
     _iterator = (Iterator)iterator ?? throw new ArgumentNullException(nameof(iterator));
     _flags    = mode | flags;
 }
 public RecursiveIteratorIterator(Traversable iterator, int mode = LEAVES_ONLY, int flags = 0)
 {
     __construct(iterator, mode, flags);
 }
Beispiel #17
0
    void Update()
    {
        StatusText    statusText  = FindObjectOfType <StatusText>(); // TODO: UIHandler?
        PlayerHandler player      = FindObjectOfType <PlayerHandler>();
        GameObject    currentTile = player.GetCurrentTile();
        Inventory     inventory   = player.GetInventory();

        if (player.IsBusy())
        {
            return;              // Skip the rest if we are "busy"
        }
        if (!interactionCooldown)
        {
            status = "Overworld";
        }

        // Handle teleporting
        // TODO: Move
        if (currentTile && currentTile.tag == "Traversable")
        {
            status = "Press f to traverse!";

            if (Input.GetKey("f"))
            {
                Traversable traversable = currentTile.GetComponent <Traversable>();
                traversable.Traverse();
            }
        }

        // Handle collecting
        if (currentTile && !interactionCooldown && currentTile.tag == "Collectable")
        {
            status = "Press f to pick up!";

            if (Input.GetKey("f"))
            {
                Collectable collectable = currentTile.GetComponent <Collectable>();
                Item        drop        = collectable.Collect();

                if (drop != null)
                {
                    status = "Picked up item!";
                    inventory.addItem(drop);
                }
                else
                {
                    status = "You can't pick that up!";
                }
            }
        }

        // Handle attacking
        if (currentTile && !interactionCooldown && currentTile.tag == "Attackable")
        {
            status = "Press f to attack!";

            if (Input.GetKey("f"))
            {
                Attackable attackable = currentTile.GetComponent <Attackable>();
                Item       drop       = attackable.Attack();

                if (drop != null)
                {
                    status = "They dropped an item!";
                    inventory.addItem(drop);
                }
                else
                {
                    status = "Not dead yet!";
                }
            }
        }

        // Handle mining
        if (currentTile && !interactionCooldown && currentTile.tag == "Mineable")
        {
            status = "Press f to mine!";

            if (Input.GetKey("f"))
            {
                // Start cooldown timer
                StartCoroutine(InteractCooldown(0.2f));
                interactionCooldown = true;

                status = "Mining!";

                Mineable mineable = currentTile.GetComponent <Mineable>();
                Item     drop     = mineable.mine();

                if (drop != null)
                {
                    status = "Mining succeeded!";
                    inventory.addItem(drop);
                }
                else
                {
                    status = "Mining failed!";
                }
            }
        }

        // Handle interacting
        if (currentTile && !interactionCooldown && currentTile.tag == "Interactable")
        {
            status = "Press f to talk!";

            if (Input.GetKey("f"))
            {
                // Start cooldown timer
                StartCoroutine(InteractCooldown(1.0f));
                interactionCooldown = true;

                Interactable interactable = currentTile.GetComponent <Interactable>();

                if (interactable.Interact())
                {
                    status = "Talking... (Press Space to Continue)";
                }
                else
                {
                    status = "They don't seem to have much to say...";
                }
            }
        }

        // Update status
        statusText.SetStatusText(status);
    }
Beispiel #18
0
 public IteratorIterator(Traversable iterator, string classname = null) => __construct(iterator, classname);
Beispiel #19
0
 public virtual void __construct(Traversable iterator, IPhpCallable callback)
 {
     base.__construct(iterator);
     _callback = callback;
 }
Beispiel #20
0
 public CallbackFilterIterator(Context ctx, Traversable iterator, IPhpCallable callback)
     : base(iterator)
 {
     _ctx      = ctx;
     _callback = callback;
 }
Beispiel #21
0
 public FilterIterator(Traversable iterator) : base(iterator)
 {
 }
Beispiel #22
0
 public InfiniteIterator(Traversable iterator) : base(iterator)
 {
 }
Beispiel #23
0
 public override int GetHashCode() =>
 Position.GetHashCode()
 + Traversable.GetHashCode()
 + TraversalCostMultiplier.GetHashCode();
 public RecursiveTreeIterator(Context ctx, Traversable it, int flags = BYPASS_KEY, int cit_flags = CachingIterator.CATCH_GET_CHILD, int mode = SELF_FIRST) :
     this(ctx)
 {
     __construct(it, flags, cit_flags, mode);
 }
 public sealed override void __construct(Traversable iterator, int mode = 0, int flags = 0)
 {
     __construct(iterator, BYPASS_KEY, CATCH_GET_CHILD, mode);
 }
Beispiel #26
0
 public LimitIterator(Traversable iterator, long offset = 0, long count = -1) => __construct(iterator, offset, count);
Beispiel #27
0
        private ContextObject GetContextForPathInternal(
            Traversable elements,
            ScopeData scopeData,
            IMorestachioExpression morestachioExpression)
        {
            var retval = this;

            if (elements == null)
            {
                return(retval);
            }

            var preHandeld = HandlePathContext(elements.Current, morestachioExpression, scopeData);

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

            var type = _value?.GetType();

            if (elements.Current.Value == PathType.RootSelector)             //go the root object
            {
                return(ExecuteRootSelector() ?? this);
            }
            else if (elements.Current.Value == PathType.ParentSelector)             //go one level up
            {
                if (Parent != null)
                {
                    return(FindNextNaturalContextObject()?.Parent ?? this.Parent ?? this);
                }

                return(this);
            }
            else if (elements.Current.Value == PathType.ObjectSelector)
            //enumerate ether an IDictionary, an cs object or an IEnumerable to a KeyValuePair array
            {
                //await EnsureValue();
                if (_value is null)
                {
                    return(scopeData.ParserOptions.CreateContextObject("x:null", null));
                }

                //ALWAYS return the context, even if the value is null.
                return(ExecuteObjectSelector(elements.Current.Key, type, scopeData));
            }
            else if (elements.Current.Value == PathType.Boolean)
            {
                if (elements.Current.Key == "true" || elements.Current.Key == "false")
                {
                    var booleanContext =
                        scopeData.ParserOptions.CreateContextObject(".", elements.Current.Key == "true", this);
                    booleanContext.IsNaturalContext = IsNaturalContext;
                    return(booleanContext);
                }

                return(this);
            }
            else if (elements.Current.Value == PathType.Null)
            {
                return(scopeData.ParserOptions.CreateContextObject("x:null", null));
            }
            else if (elements.Current.Value == PathType.DataPath)
            {
                return(ExecuteDataPath(elements.Current.Key, morestachioExpression, type, scopeData));
            }
            return(retval);
        }
Beispiel #28
0
 public override sealed void __construct(Traversable iterator, string classname = null) => __construct(iterator, 0, -1);
Beispiel #29
0
 public sealed override void __construct(Traversable iterator, string classname = null) => base.__construct(iterator, classname);
Beispiel #30
0
 public NoRewindIterator(Traversable iterator) : base(iterator)
 {
 }