internal static IDictionary <String, Object> ReadMapping(IParser parser, Int32 depth = 1)
        {
            var mappingStart = parser.Expect <MappingStart>();

            if (depth > MaxObjectDepth)
            {
                throw new SyntaxErrorException(mappingStart.Start, mappingStart.End, $"Max object depth of {MaxObjectDepth} exceeded.");
            }

            var mapping = new Dictionary <String, Object>();

            depth++; // Optimistically increment the depth to avoid addition within the loop.
            while (!parser.Accept <MappingEnd>())
            {
                String key = parser.Expect <Scalar>().Value;
                Object value;
                if (parser.Accept <Scalar>())
                {
                    value = parser.Expect <Scalar>().Value;
                }
                else if (parser.Accept <SequenceStart>())
                {
                    value = ReadSequence(parser, depth);
                }
                else
                {
                    value = ReadMapping(parser, depth);
                }

                mapping.Add(key, value);
            }

            parser.Expect <MappingEnd>();
            return(mapping);
        }
        internal static IList <Object> ReadSequence(IParser parser, Int32 depth = 1)
        {
            var sequenceStart = parser.Expect <SequenceStart>();

            if (depth > MaxObjectDepth)
            {
                throw new SyntaxErrorException(sequenceStart.Start, sequenceStart.End, $"Max object depth of {MaxObjectDepth} exceeded.");
            }

            var sequence = new List <Object>();

            depth++; // Optimistically increment the depth to avoid addition within the loop.
            while (!parser.Accept <SequenceEnd>())
            {
                if (parser.Accept <Scalar>())
                {
                    sequence.Add(parser.Expect <Scalar>());
                }
                else if (parser.Accept <SequenceStart>())
                {
                    sequence.Add(ReadSequence(parser, depth));
                }
                else
                {
                    sequence.Add(ReadMapping(parser, depth));
                }
            }

            parser.Expect <SequenceEnd>();
            return(sequence);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Parses the node represented by the next event in <paramref name="parser" />.
        /// </summary>
        /// <returns>Returns the node that has been parsed.</returns>
        static internal YamlNode ParseNode(IParser parser, DocumentLoadingState state)
        {
            if (parser.Accept <Scalar>())
            {
                return(new YamlScalarNode(parser, state));
            }

            if (parser.Accept <SequenceStart>())
            {
                return(new YamlSequenceNode(parser, state));
            }

            if (parser.Accept <MappingStart>())
            {
                return(new YamlMappingNode(parser, state));
            }

            if (parser.Accept <AnchorAlias>())
            {
                var alias = parser.Expect <AnchorAlias>();
                return(state.GetNode(alias.Value, false, alias.Start, alias.End) ?? new YamlAliasNode(alias.Value));
            }

            throw new ArgumentException("The current event is of an unsupported type.", "events");
        }
Ejemplo n.º 4
0
        public object ReadYaml(IParser parser, Type type)
        {
            // Handle empty objects
            if (parser.Accept <Scalar>())
            {
                parser.Allow <Scalar>();
                return(null);
            }

            var result = new PSObject();

            if (parser.Accept <MappingStart>())
            {
                parser.MoveNext();
                while (!parser.Accept <MappingEnd>())
                {
                    var property = ReadNoteProperty(parser);
                    if (property == null)
                    {
                        throw new NotImplementedException();
                    }

                    result.Properties.Add(property);
                }
                parser.MoveNext();
            }
            return(result);
        }
        public object Deserialize(IParser parser, Type type)
        {
            if (parser == null)
            {
                throw new ArgumentNullException("reader");
            }
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            bool   flag   = parser.Allow <StreamStart>() != null;
            bool   flag2  = parser.Allow <DocumentStart>() != null;
            object result = null;

            if (!parser.Accept <DocumentEnd>() && !parser.Accept <StreamEnd>())
            {
                using (SerializerState serializerState = new SerializerState())
                {
                    result = valueDeserializer.DeserializeValue(parser, type, serializerState, valueDeserializer);
                    serializerState.OnDeserialization();
                }
            }
            if (flag2)
            {
                parser.Expect <DocumentEnd>();
            }
            if (flag)
            {
                parser.Expect <StreamEnd>();
            }
            return(result);
        }
Ejemplo n.º 6
0
        public object ReadYaml(IParser parser, Type type)
        {
            var result = new FieldMap();

            if (parser.Accept <MappingStart>())
            {
                parser.MoveNext();
                while (!parser.Accept <MappingEnd>())
                {
                    var fieldName = parser.Allow <Scalar>().Value;
                    if (parser.Accept <SequenceStart>())
                    {
                        parser.MoveNext();
                        var fields = new List <string>();

                        while (!parser.Accept <SequenceEnd>())
                        {
                            fields.Add(parser.Allow <Scalar>().Value);
                        }

                        result.Set(fieldName, fields.ToArray());
                        parser.MoveNext();
                    }
                }
                parser.MoveNext();
            }
            return(result);
        }
        public object ReadYaml(IParser parser, Type type)
        {
            if (parser.TryConsume <Scalar>(out var nameValueScalar))
            {
                var runtimeName = DeserializeName(nameValueScalar, type);
                return(new ProjectRuntime(runtimeName));
            }

            if (!parser.TryConsume <MappingStart>(out _))
            {
                throw new YamlException($"Unable to deserialize [{type.FullName}]. Expecting string or object.");
            }

            if (!parser.TryConsume <Scalar>(out var namePropertyScalar) ||
                !string.Equals(nameof(ProjectRuntime.Name), namePropertyScalar.Value, StringComparison.OrdinalIgnoreCase))
            {
                throw new YamlException($"Unable to deserialize [{type.FullName}]. Expecting runtime name property.");
            }

            if (!parser.TryConsume <Scalar>(out var nameValueScalar2))
            {
                throw new YamlException($"Unable to deserialize [{type.FullName}]. Runtime name property should be a string.");
            }

            var name = DeserializeName(nameValueScalar2, type);

            // early mapping end is ok
            if (parser.Accept <MappingEnd>(out _))
            {
                parser.MoveNext(); // read final MappingEnd since Accept doesn't call MoveNext
                return(new ProjectRuntime(name));
            }

            if (!parser.TryConsume <Scalar>(out var optionsPropertyScalar) ||
                !string.Equals(nameof(ProjectRuntime.Options), optionsPropertyScalar.Value, StringComparison.OrdinalIgnoreCase))
            {
                throw new YamlException($"Unable to deserialize [{type.FullName}]. Expecting runtime options property.");
            }

            if (!parser.Accept <MappingStart>(out _))
            {
                throw new YamlException($"Unable to deserialize [{type.FullName}]. Runtime options property should be an object.");
            }

            var runtimeOptionsObj = this._optionsConverter.ReadYaml(parser, _optionsType);

            if (!(runtimeOptionsObj is ProjectRuntimeOptions runtimeOptions))
            {
                throw new YamlException("There was an issue deserializing the runtime options object.");
            }

            parser.MoveNext(); // read final MappingEnd event
            return(new ProjectRuntime(name)
            {
                Options = runtimeOptions
            });
Ejemplo n.º 8
0
        public object ReadYaml(IParser parser, Type type)
        {
            var allowedFailuresCollection = new AllowedFailuresCollection();

            // discard SequenceStart
            parser.Expect <SequenceStart>();

            do
            {
                string os            = null;
                string configuration = null;
                string platform      = null;
                string testCategory  = null;
                var    variables     = new List <Variable>();

                parser.Expect <MappingStart>();

                do
                {
                    var possibleVar = _deserializer.Deserialize <InternalVariable>(parser);

                    switch (possibleVar.Name)
                    {
                    case "os":
                        os = possibleVar.Value;
                        break;

                    case "configuration":
                        configuration = possibleVar.Value;
                        break;

                    case "platform":
                        platform = possibleVar.Value;
                        break;

                    case "test_category":
                        testCategory = possibleVar.Value;
                        break;

                    default:
                        variables.Add(possibleVar.ToVariable());
                        break;
                    }
                } while (!parser.Accept <MappingEnd>());

                parser.Expect <MappingEnd>();

                allowedFailuresCollection.Add(
                    new AllowedJobFailureConditions(os, configuration, platform, testCategory, variables.AsReadOnly()));
            } while (!parser.Accept <SequenceEnd>());

            parser.Expect <SequenceEnd>();

            return(allowedFailuresCollection);
        }
Ejemplo n.º 9
0
        public object ReadYaml(IParser parser, Type type)
        {
            var env = new InternalEnvironmentVariables();

            parser.Expect <MappingStart>();

            do
            {
                var scalar = parser.Peek <Scalar>();

                if (scalar != null)
                {
                    if (scalar.Value == "matrix")
                    {
                        // discard "matrix" value itself
                        parser.Expect <Scalar>();

                        // discard SequenceStart
                        parser.Expect <SequenceStart>();

                        do
                        {
                            var matrixItemVariables = new List <InternalVariable>();

                            parser.Expect <MappingStart>();

                            do
                            {
                                matrixItemVariables.Add(deserializer.Deserialize <InternalVariable>(parser));
                            } while (!parser.Accept <MappingEnd>());

                            parser.Expect <MappingEnd>();

                            env.InternalMatrix.Add(matrixItemVariables.AsReadOnly());
                        } while (!parser.Accept <SequenceEnd>());

                        parser.Expect <SequenceEnd>();
                    }
                    else
                    {
                        var variable = deserializer.Deserialize <InternalVariable>(parser);
                        env.InternalCommonVariables.Add(variable);
                    }
                }
            } while (!parser.Accept <MappingEnd>());

            parser.Expect <MappingEnd>();

            return(env);
        }
Ejemplo n.º 10
0
 internal static void DeserializeHelper(Type tItem, IParser parser, Func <IParser, Type, object> nestedObjectDeserializer, IList result, bool canUpdate)
 {
     parser.Expect <SequenceStart>();
     while (!parser.Accept <SequenceEnd>())
     {
         ParsingEvent  current      = parser.Current;
         object        obj          = nestedObjectDeserializer(parser, tItem);
         IValuePromise valuePromise = obj as IValuePromise;
         if (valuePromise == null)
         {
             result.Add(TypeConverter.ChangeType(obj, tItem));
         }
         else
         {
             if (!canUpdate)
             {
                 throw new ForwardAnchorNotSupportedException(current.Start, current.End, "Forward alias references are not allowed because this type does not implement IList<>");
             }
             int index = result.Add((!tItem.IsValueType()) ? null : Activator.CreateInstance(tItem));
             valuePromise.ValueAvailable += delegate(object v)
             {
                 result[index] = TypeConverter.ChangeType(v, tItem);
             };
         }
     }
     parser.Expect <SequenceEnd>();
 }
Ejemplo n.º 11
0
        public object ReadYaml(IParser parser, Type type)
        {
            var result = new FieldMap();

            if (parser.TryConsume <MappingStart>(out _))
            {
                while (parser.TryConsume(out Scalar scalar))
                {
                    var fieldName = scalar.Value;
                    if (parser.TryConsume <SequenceStart>(out _))
                    {
                        var fields = new List <string>();
                        while (!parser.Accept <SequenceEnd>(out _))
                        {
                            if (parser.TryConsume <Scalar>(out scalar))
                            {
                                fields.Add(scalar.Value);
                            }
                        }
                        result.Set(fieldName, fields.ToArray());
                        parser.Require <SequenceEnd>();
                        parser.MoveNext();
                    }
                }
                parser.Require <MappingEnd>();
                parser.MoveNext();
            }
            return(result);
        }
Ejemplo n.º 12
0
        private void Load(IParser parser, DocumentLoadingState state)
        {
            MappingStart mappingStart = parser.Expect <MappingStart>();

            Load(mappingStart, state);
            Style = mappingStart.Style;
            bool flag = false;

            while (!parser.Accept <MappingEnd>())
            {
                YamlNode yamlNode  = YamlNode.ParseNode(parser, state);
                YamlNode yamlNode2 = YamlNode.ParseNode(parser, state);
                try
                {
                    children.Add(yamlNode, yamlNode2);
                }
                catch (ArgumentException innerException)
                {
                    throw new YamlException(yamlNode.Start, yamlNode.End, "Duplicate key", innerException);
                }
                flag |= (yamlNode is YamlAliasNode || yamlNode2 is YamlAliasNode);
            }
            if (flag)
            {
                state.AddNodeWithUnresolvedAliases(this);
            }
            parser.Expect <MappingEnd>();
        }
Ejemplo n.º 13
0
        private void Load(IParser parser, DocumentLoadingState state)
        {
            var sequence = parser.Expect <SequenceStart>();

            Load(sequence, state);
            Style = sequence.Style;

            bool hasUnresolvedAliases = false;

            while (!parser.Accept <SequenceEnd>())
            {
                var child = ParseNode(parser, state);
                children.Add(child);
                hasUnresolvedAliases |= child is YamlAliasNode;
            }

            if (hasUnresolvedAliases)
            {
                state.AddNodeWithUnresolvedAliases(this);
            }
#if DEBUG
            else
            {
                foreach (var child in children)
                {
                    if (child is YamlAliasNode)
                    {
                        throw new InvalidOperationException("Error in alias resolution.");
                    }
                }
            }
#endif

            parser.Expect <SequenceEnd>();
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="YamlDocument"/> class.
        /// </summary>
        internal YamlDocument(IParser parser)
        {
            var state = new DocumentLoadingState();

            parser.Expect <DocumentStart>();

            while (!parser.Accept <DocumentEnd>())
            {
                Debug.Assert(RootNode == null);
                RootNode = YamlNode.ParseNode(parser, state);

                if (RootNode is YamlAliasNode)
                {
                    throw new YamlException();
                }
            }

            state.ResolveAliases();

#if DEBUG
            foreach (var node in AllNodes)
            {
                if (node is YamlAliasNode)
                {
                    throw new InvalidOperationException("Error in alias resolution.");
                }
            }
#endif

            parser.Expect <DocumentEnd>();
        }
        bool INodeDeserializer.Deserialize(IParser reader, Type expectedType, Func <IParser, Type, object> nestedObjectDeserializer, out object value)
        {
            var mapping = reader.Allow <MappingStart>();

            if (mapping == null)
            {
                value = null;
                return(false);
            }

            value = _objectFactory.Create(expectedType);
            while (!reader.Accept <MappingEnd>())
            {
                var propertyName = reader.Expect <Scalar>();
                var property     = _typeDescriptor.GetProperty(expectedType, value, propertyName.Value, _ignoreUnmatched);
                if (property == null)
                {
                    reader.SkipThisAndNestedEvents();
                    continue;
                }

                var propertyValue = nestedObjectDeserializer(reader, property.Type);
                if (!(propertyValue is IValuePromise propertyValuePromise))
                {
                    var convertedValue = TypeConverter.ChangeType(propertyValue, property.Type);
                    property.Write(value, convertedValue);
                }
Ejemplo n.º 16
0
        public static void DeserializeHelper <TItem>(IParser reader, Type expectedType, Func <IParser, Type, object> nestedObjectDeserializer, ICollection <TItem> result)
        {
            var list = result as IList <TItem>;

            reader.Expect <SequenceStart>();
            while (!reader.Accept <SequenceEnd>())
            {
                var current = reader.Current;

                var value   = nestedObjectDeserializer(reader, typeof(TItem));
                var promise = value as IValuePromise;
                if (promise == null)
                {
                    result.Add(TypeConverter.ChangeType <TItem>(value));
                }
                else if (list != null)
                {
                    var index = list.Count;
                    result.Add(default(TItem));
                    promise.ValueAvailable += v => list[index] = TypeConverter.ChangeType <TItem>(v);
                }
                else
                {
                    throw new ForwardAnchorNotSupportedException(
                              current.Start,
                              current.End,
                              "Forward alias references are not allowed because this type does not implement IList<>"
                              );
                }
            }
            reader.Expect <SequenceEnd>();
        }
Ejemplo n.º 17
0
        private void Load(IParser parser, DocumentLoadingState state)
        {
            var mapping = parser.Expect <MappingStart>();

            Load(mapping, state);
            Style = mapping.Style;

            bool hasUnresolvedAliases = false;

            while (!parser.Accept <MappingEnd>())
            {
                var key   = ParseNode(parser, state);
                var value = ParseNode(parser, state);

                try
                {
                    children.Add(key, value);
                }
                catch (ArgumentException err)
                {
                    throw new YamlException(key.Start, key.End, "Duplicate key", err);
                }

                hasUnresolvedAliases |= key is YamlAliasNode || value is YamlAliasNode;
            }

            if (hasUnresolvedAliases)
            {
                state.AddNodeWithUnresolvedAliases(this);
            }

            parser.Expect <MappingEnd>();
        }
        internal static void DeserializeHelper(Type tItem, IParser parser, Func <IParser, Type, object> nestedObjectDeserializer, IList result, bool canUpdate)
        {
            parser.Expect <SequenceStart>();
            while (!parser.Accept <SequenceEnd>())
            {
                var current = parser.Current;

                var value   = nestedObjectDeserializer(parser, tItem);
                var promise = value as IValuePromise;
                if (promise == null)
                {
                    result.Add(TypeConverter.ChangeType(value, tItem));
                }
                else if (canUpdate)
                {
                    var index = result.Add(tItem.IsValueType() ? Activator.CreateInstance(tItem) : null);
                    promise.ValueAvailable += v => result[index] = TypeConverter.ChangeType(v, tItem);
                }
                else
                {
                    throw new ForwardAnchorNotSupportedException(
                              current.Start,
                              current.End,
                              "Forward alias references are not allowed because this type does not implement IList<>"
                              );
                }
            }
            parser.Expect <SequenceEnd>();
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Gets the next event without consuming it.
 /// </summary>
 /// <typeparam name="T">Type of the <see cref="ParsingEvent"/>.</typeparam>
 /// <returns>Returns the current event if it is of type T; otherwise returns null.</returns>
 public static T Peek <T>(this IParser parser) where T : ParsingEvent
 {
     if (!parser.Accept <T>())
     {
         return(null);
     }
     return((T)parser.Current);
 }
Ejemplo n.º 20
0
        internal static IList <ProcessResource> ReadProcessResources(IParser parser)
        {
            var result = new List <ProcessResource>();

            parser.Expect <SequenceStart>();
            while (parser.Allow <SequenceEnd>() == null)
            {
                parser.Expect <MappingStart>();
                Scalar scalar = parser.Expect <Scalar>();
                switch (scalar.Value ?? String.Empty)
                {
                case YamlConstants.Endpoint:
                case YamlConstants.Repo:
                    break;

                default:
                    throw new SyntaxErrorException(scalar.Start, scalar.End, $"Unexpected resource type: '{scalar.Value}'");
                }

                var resource = new ProcessResource {
                    Type = scalar.Value
                };
                resource.Name = ReadNonEmptyString(parser);;
                while (parser.Allow <MappingEnd>() == null)
                {
                    string dataKey = ReadNonEmptyString(parser);
                    if (parser.Accept <MappingStart>())
                    {
                        resource.Data[dataKey] = ReadMapping(parser);
                    }
                    else if (parser.Accept <SequenceStart>())
                    {
                        resource.Data[dataKey] = ReadSequence(parser);
                    }
                    else
                    {
                        resource.Data[dataKey] = parser.Expect <Scalar>().Value ?? String.Empty;
                    }
                }

                result.Add(resource);
            }

            return(result);
        }
Ejemplo n.º 21
0
        private IResource MapResource(IParser reader, Func <IParser, Type, object> nestedObjectDeserializer, CommentMetadata comment)
        {
            IResource        result   = null;
            string           kind     = null;
            ResourceMetadata metadata = null;

            if (reader.Accept <MappingStart>())
            {
                reader.MoveNext();
                while (!reader.Accept <MappingEnd>())
                {
                    // Read kind
                    var propertyName = reader.Allow <Scalar>().Value;

                    if (propertyName == "kind")
                    {
                        kind = reader.Allow <Scalar>().Value;
                    }
                    else if (propertyName == "metadata")
                    {
                        if (!TryMetadata(reader, nestedObjectDeserializer, out metadata))
                        {
                            reader.SkipThisAndNestedEvents();
                        }
                    }
                    else if (propertyName == "spec" && kind != null)
                    {
                        if (!TryResource(kind, reader, nestedObjectDeserializer, metadata, comment, out IResource resource))
                        {
                            reader.SkipThisAndNestedEvents();
                        }

                        result = resource;
                    }
                    else
                    {
                        reader.SkipThisAndNestedEvents();
                    }
                }
                reader.MoveNext();
            }
            return(result);
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Loads the stream from the specified <see cref="IParser"/>.
 /// </summary>
 public void Load(IParser parser)
 {
     documents.Clear();
     parser.Expect <StreamStart>();
     while (!parser.Accept <StreamEnd>())
     {
         var document = new YamlDocument(parser);
         documents.Add(document);
     }
     parser.Expect <StreamEnd>();
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Checks whether the current event is of the specified type.
        /// If the event is of the specified type, returns it and moves to the next event.
        /// Otherwise retruns null.
        /// </summary>
        /// <typeparam name="T">Type of the <see cref="ParsingEvent"/>.</typeparam>
        /// <returns>Returns the current event if it is of type T; otherwise returns null.</returns>
        public static T Allow <T>(this IParser parser) where T : ParsingEvent
        {
            if (!parser.Accept <T>())
            {
                return(null);
            }
            var @event = (T)parser.Current;

            parser.MoveNext();
            return(@event);
        }
Ejemplo n.º 24
0
        private PSNoteProperty ReadNoteProperty(IParser parser)
        {
            var name = parser.Allow <Scalar>().Value;

            if (parser.Accept <SequenceStart>())
            {
                parser.MoveNext();

                var values = new List <PSObject>();

                while (!parser.Accept <SequenceEnd>())
                {
                    if (parser.Accept <MappingStart>())
                    {
                        values.Add(PSObject.AsPSObject(ReadYaml(parser, typeof(PSObject))));
                    }
                    else if (parser.Accept <Scalar>())
                    {
                        values.Add(PSObject.AsPSObject(parser.Allow <Scalar>().Value));
                    }
                }
                parser.MoveNext();
                return(new PSNoteProperty(name, values.ToArray()));
            }
            else if (parser.Accept <MappingStart>())
            {
                return(new PSNoteProperty(name, ReadYaml(parser, typeof(PSObject))));
            }
            else if (parser.Accept <Scalar>())
            {
                return(new PSNoteProperty(name, parser.Allow <Scalar>().Value));
            }
            return(null);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Deserializes an object of the specified type.
        /// </summary>
        /// <param name="parser">The <see cref="IParser" /> where to deserialize the object.</param>
        /// <param name="type">The static type of the object to deserialize.</param>
        /// <returns>Returns the deserialized object.</returns>
        public object Deserialize(IParser parser, Type type, IValueDeserializer deserializer = null)
        {
            if (parser == null)
            {
                throw new ArgumentNullException("reader");
            }

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

            var hasStreamStart = parser.Allow <StreamStart>() != null;

            var hasDocumentStart = parser.Allow <DocumentStart>() != null;

            deserializer = deserializer ?? _valueDeserializer;
            object result = null;

            if (!parser.Accept <DocumentEnd>() && !parser.Accept <StreamEnd>())
            {
                using (var state = new SerializerState())
                {
                    result = deserializer.DeserializeValue(parser, type, state, deserializer);
                    state.OnDeserialization();
                }
            }

            if (hasDocumentStart)
            {
                parser.Expect <DocumentEnd>();
            }

            if (hasStreamStart)
            {
                parser.Expect <StreamEnd>();
            }

            return(result);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// 查找一个能解析buf中内容的parser
        /// </summary>
        /// <param name="supportedFamily">The supported family.</param>
        /// <param name="buf">The buf.</param>
        /// <returns></returns>
        private IParser FindParser(ProtocolFamily supportedFamily, ByteBuffer buf)
        {
            IParser parser = parsers[supportedFamily];

            if (parser != null)
            {
                if (parser.Accept(buf))
                {
                    return(parser);
                }
            }
            return(null);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Reads a mapping(string, string) from start to end using the specified <c>StringComparer</c>.
        /// </summary>
        /// <param name="parser">The parser instance from which to read</param>
        /// <returns>A dictionary instance with the specified comparer</returns>
        internal static IDictionary <String, String> ReadMappingOfStringString(IParser parser, StringComparer comparer)
        {
            parser.Expect <MappingStart>();
            var mappingValue = new Dictionary <String, String>(comparer);

            while (!parser.Accept <MappingEnd>())
            {
                mappingValue.Add(parser.Expect <Scalar>().Value, parser.Expect <Scalar>().Value);
            }

            parser.Expect <MappingEnd>();
            return(mappingValue);
        }
Ejemplo n.º 28
0
 public object ReadYaml(IParser parser, Type type)
 {
     if (parser.Accept <Scalar>())
     {
         var scalar = parser.Expect <Scalar>();
         return(new EntityMemberInfo {
             Type = scalar.Value
         });
     }
     else
     {
         return(_deserializerFactory().Deserialize <EntityMemberInfo>(parser));
     }
 }
        public static void DeserializeHelper <TItem>(IParser reader, Type expectedType, Func <IParser, Type, object> nestedObjectDeserializer, ICollection <TItem> result)
        {
            var list = result as IList <TItem>;

            reader.Expect <SequenceStart>();
            while (!reader.Accept <SequenceEnd>())
            {
                var current = reader.Current;

                var value = nestedObjectDeserializer(reader, typeof(TItem));
                if (!(value is IValuePromise promise))
                {
                    result.Add(TypeConverter.ChangeType <TItem>(value));
                }
Ejemplo n.º 30
0
        private void Load(IParser parser, DocumentLoadingState state)
        {
            var mapping = parser.Expect <MappingStart>();

            Load(mapping, state);
            Style = mapping.Style;

            bool hasUnresolvedAliases = false;

            while (!parser.Accept <MappingEnd>())
            {
                var key   = ParseNode(parser, state);
                var value = ParseNode(parser, state);

                try
                {
                    children.Add(key, value);
                }
                catch (ArgumentException err)
                {
                    throw new YamlException(key.Start, key.End, "Duplicate key", err);
                }

                hasUnresolvedAliases |= key is YamlAliasNode || value is YamlAliasNode;
            }

            if (hasUnresolvedAliases)
            {
                state.AddNodeWithUnresolvedAliases(this);
            }
#if DEBUG
            else
            {
                foreach (var child in children)
                {
                    if (child.Key is YamlAliasNode)
                    {
                        throw new InvalidOperationException("Error in alias resolution.");
                    }
                    if (child.Value is YamlAliasNode)
                    {
                        throw new InvalidOperationException("Error in alias resolution.");
                    }
                }
            }
#endif

            parser.Expect <MappingEnd>();
        }
Ejemplo n.º 31
0
        bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func<IParser, Type, object> nestedObjectDeserializer, out object value)
        {
            var mapping = parser.Allow<MappingStart>();
            if (mapping == null)
            {
                value = null;
                return false;
            }

            value = _objectFactory.Create(expectedType);
            while (!parser.Accept<MappingEnd>())
            {
                var propertyName = parser.Expect<Scalar>();
                var property = _typeDescriptor.GetProperty(expectedType, null, propertyName.Value, _ignoreUnmatched);
                if (property == null)
                {
                    parser.SkipThisAndNestedEvents();
                    continue;
                }

                var propertyValue = nestedObjectDeserializer(parser, property.Type);
                var propertyValuePromise = propertyValue as IValuePromise;
                if (propertyValuePromise == null)
                {
                    var convertedValue = TypeConverter.ChangeType(propertyValue, property.Type);
                    property.Write(value, convertedValue);
                }
                else
                {
                    var valueRef = value;
                    propertyValuePromise.ValueAvailable += v =>
                    {
                        var convertedValue = TypeConverter.ChangeType(v, property.Type);
                        property.Write(valueRef, convertedValue);
                    };
                }
            }

            parser.Expect<MappingEnd>();
            return true;
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Initializes a new instance of the <see cref="YamlDocument"/> class.
        /// </summary>
        internal YamlDocument(IParser parser)
        {
            var state = new DocumentLoadingState();

            parser.Expect<DocumentStart>();

            while (!parser.Accept<DocumentEnd>())
            {
                Debug.Assert(RootNode == null);
                RootNode = YamlNode.ParseNode(parser, state);

                if (RootNode is YamlAliasNode)
                {
                    throw new YamlException();
                }
            }

            state.ResolveAliases();

            parser.Expect<DocumentEnd>();
        }
Ejemplo n.º 33
0
        private static void DeserializeHelper(Type tKey, Type tValue, IParser parser, Func<IParser, Type, object> nestedObjectDeserializer, IDictionary result)
        {
            parser.Expect<MappingStart>();
            while (!parser.Accept<MappingEnd>())
            {
                var key = nestedObjectDeserializer(parser, tKey);
                var keyPromise = key as IValuePromise;

                var value = nestedObjectDeserializer(parser, tValue);
                var valuePromise = value as IValuePromise;

                if (keyPromise == null)
                {
                    if (valuePromise == null)
                    {
                        // Happy path: both key and value are known
                        result[key] = value;
                    }
                    else
                    {
                        // Key is known, value is pending
                        valuePromise.ValueAvailable += v => result[key] = v;
                    }
                }
                else
                {
                    if (valuePromise == null)
                    {
                        // Key is pending, value is known
                        keyPromise.ValueAvailable += v => result[v] = value;
                    }
                    else
                    {
                        // Both key and value are pending. We need to wait until both of them becom available.
                        var hasFirstPart = false;

                        keyPromise.ValueAvailable += v =>
                        {
                            if (hasFirstPart)
                            {
                                result[v] = value;
                            }
                            else
                            {
                                key = v;
                                hasFirstPart = true;
                            }
                        };

                        valuePromise.ValueAvailable += v =>
                        {
                            if (hasFirstPart)
                            {
                                result[key] = v;
                            }
                            else
                            {
                                value = v;
                                hasFirstPart = true;
                            }
                        };
                    }
                }
            }
            parser.Expect<MappingEnd>();
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Parses the node represented by the next event in <paramref name="parser" />.
        /// </summary>
        /// <returns>Returns the node that has been parsed.</returns>
        internal static YamlNode ParseNode(IParser parser, DocumentLoadingState state)
        {
            if (parser.Accept<Scalar>())
            {
                return new YamlScalarNode(parser, state);
            }

            if (parser.Accept<SequenceStart>())
            {
                return new YamlSequenceNode(parser, state);
            }

            if (parser.Accept<MappingStart>())
            {
                return new YamlMappingNode(parser, state);
            }

            if (parser.Accept<AnchorAlias>())
            {
                var alias = parser.Expect<AnchorAlias>();
                return state.GetNode(alias.Value, false, alias.Start, alias.End) ?? new YamlAliasNode(alias.Value);
            }

            throw new ArgumentException("The current event is of an unsupported type.", "events");
        }
Ejemplo n.º 35
0
        internal static void DeserializeHelper(Type tItem, IParser parser, Func<IParser, Type, object> nestedObjectDeserializer, IList result, bool canUpdate)
        {
            parser.Expect<SequenceStart>();
            while (!parser.Accept<SequenceEnd>())
            {
                var current = parser.Current;

                var value = nestedObjectDeserializer(parser, tItem);
                var promise = value as IValuePromise;
                if (promise == null)
                {
                    result.Add(TypeConverter.ChangeType(value, tItem));
                }
                else if (canUpdate)
                {
                    var index = result.Add(tItem.IsValueType() ? Activator.CreateInstance(tItem) : null);
                    promise.ValueAvailable += v => result[index] = TypeConverter.ChangeType(v, tItem);
                }
                else
                {
                    throw new ForwardAnchorNotSupportedException(
                        current.Start,
                        current.End,
                        "Forward alias references are not allowed because this type does not implement IList<>"
                    );
                }
            }
            parser.Expect<SequenceEnd>();
        }