From ee15da5d09c5b7df723510a8ebc226cfe17d2b0b Mon Sep 17 00:00:00 2001 From: fillefilip8 Date: Tue, 17 Apr 2018 12:53:37 +0200 Subject: [PATCH] Allows creating the layer in code. --- SetupMenuItem.cs | 47 + YamlDotNet/Core.meta | 9 + YamlDotNet/Core/AnchorNotFoundException.cs | 68 + .../Core/AnchorNotFoundException.cs.meta | 12 + YamlDotNet/Core/CharacterAnalyzer.cs | 182 ++ YamlDotNet/Core/CharacterAnalyzer.cs.meta | 12 + YamlDotNet/Core/Constants.cs | 44 + YamlDotNet/Core/Constants.cs.meta | 12 + YamlDotNet/Core/Cursor.cs | 72 + YamlDotNet/Core/Cursor.cs.meta | 12 + YamlDotNet/Core/Emitter.cs | 1918 +++++++++++++ YamlDotNet/Core/Emitter.cs.meta | 12 + YamlDotNet/Core/EmitterState.cs | 45 + YamlDotNet/Core/EmitterState.cs.meta | 12 + YamlDotNet/Core/Events.meta | 9 + YamlDotNet/Core/Events/AnchorAlias.cs | 106 + YamlDotNet/Core/Events/AnchorAlias.cs.meta | 12 + YamlDotNet/Core/Events/Comment.cs | 52 + YamlDotNet/Core/Events/Comment.cs.meta | 12 + YamlDotNet/Core/Events/DocumentEnd.cs | 116 + YamlDotNet/Core/Events/DocumentEnd.cs.meta | 12 + YamlDotNet/Core/Events/DocumentStart.cs | 168 ++ YamlDotNet/Core/Events/DocumentStart.cs.meta | 12 + YamlDotNet/Core/Events/EventType.cs | 39 + YamlDotNet/Core/Events/EventType.cs.meta | 12 + .../Core/Events/IParsingEventVisitor.cs | 42 + .../Core/Events/IParsingEventVisitor.cs.meta | 12 + YamlDotNet/Core/Events/MappingEnd.cs | 91 + YamlDotNet/Core/Events/MappingEnd.cs.meta | 12 + YamlDotNet/Core/Events/MappingStart.cs | 159 ++ YamlDotNet/Core/Events/MappingStart.cs.meta | 12 + YamlDotNet/Core/Events/MappingStyle.cs | 44 + YamlDotNet/Core/Events/MappingStyle.cs.meta | 12 + YamlDotNet/Core/Events/NodeEvent.cs | 111 + YamlDotNet/Core/Events/NodeEvent.cs.meta | 12 + YamlDotNet/Core/Events/ParsingEvent.cs | 90 + YamlDotNet/Core/Events/ParsingEvent.cs.meta | 12 + YamlDotNet/Core/Events/Scalar.cs | 198 ++ YamlDotNet/Core/Events/Scalar.cs.meta | 12 + YamlDotNet/Core/Events/SequenceEnd.cs | 91 + YamlDotNet/Core/Events/SequenceEnd.cs.meta | 12 + YamlDotNet/Core/Events/SequenceStart.cs | 148 ++ YamlDotNet/Core/Events/SequenceStart.cs.meta | 12 + YamlDotNet/Core/Events/SequenceStyle.cs | 44 + YamlDotNet/Core/Events/SequenceStyle.cs.meta | 12 + YamlDotNet/Core/Events/StreamEnd.cs | 91 + YamlDotNet/Core/Events/StreamEnd.cs.meta | 12 + YamlDotNet/Core/Events/StreamStart.cs | 91 + YamlDotNet/Core/Events/StreamStart.cs.meta | 12 + YamlDotNet/Core/FakeList.cs | 83 + YamlDotNet/Core/FakeList.cs.meta | 12 + .../ForwardAnchorNotSupportedException.cs | 69 + ...ForwardAnchorNotSupportedException.cs.meta | 12 + YamlDotNet/Core/HashCode.cs | 42 + YamlDotNet/Core/HashCode.cs.meta | 12 + YamlDotNet/Core/IEmitter.cs | 36 + YamlDotNet/Core/IEmitter.cs.meta | 12 + YamlDotNet/Core/ILookAheadBuffer.cs | 47 + YamlDotNet/Core/ILookAheadBuffer.cs.meta | 12 + YamlDotNet/Core/IParser.cs | 43 + YamlDotNet/Core/IParser.cs.meta | 12 + YamlDotNet/Core/IScanner.cs | 65 + YamlDotNet/Core/IScanner.cs.meta | 12 + YamlDotNet/Core/InsertionQueue.cs | 83 + YamlDotNet/Core/InsertionQueue.cs.meta | 12 + YamlDotNet/Core/LookAheadBuffer.cs | 148 ++ YamlDotNet/Core/LookAheadBuffer.cs.meta | 12 + YamlDotNet/Core/Mark.cs | 142 + YamlDotNet/Core/Mark.cs.meta | 12 + .../MaximumRecursionLevelReachedException.cs | 68 + ...imumRecursionLevelReachedException.cs.meta | 12 + YamlDotNet/Core/MergingParser.cs | 195 ++ YamlDotNet/Core/MergingParser.cs.meta | 12 + YamlDotNet/Core/Parser.cs | 988 +++++++ YamlDotNet/Core/Parser.cs.meta | 12 + YamlDotNet/Core/ParserExtensions.cs | 115 + YamlDotNet/Core/ParserExtensions.cs.meta | 12 + YamlDotNet/Core/ParserState.cs | 51 + YamlDotNet/Core/ParserState.cs.meta | 12 + YamlDotNet/Core/RecursionLevel.cs | 80 + YamlDotNet/Core/RecursionLevel.cs.meta | 12 + YamlDotNet/Core/ScalarStyle.cs | 61 + YamlDotNet/Core/ScalarStyle.cs.meta | 12 + YamlDotNet/Core/Scanner.cs | 2365 +++++++++++++++++ YamlDotNet/Core/Scanner.cs.meta | 12 + YamlDotNet/Core/SemanticErrorException.cs | 68 + .../Core/SemanticErrorException.cs.meta | 12 + YamlDotNet/Core/SimpleKey.cs | 54 + YamlDotNet/Core/SimpleKey.cs.meta | 12 + YamlDotNet/Core/StringLookAheadBuffer.cs | 74 + YamlDotNet/Core/StringLookAheadBuffer.cs.meta | 12 + YamlDotNet/Core/SyntaxErrorException.cs | 68 + YamlDotNet/Core/SyntaxErrorException.cs.meta | 12 + YamlDotNet/Core/TagDirectiveCollection.cs | 66 + .../Core/TagDirectiveCollection.cs.meta | 12 + YamlDotNet/Core/Tokens.meta | 9 + YamlDotNet/Core/Tokens/Anchor.cs | 67 + YamlDotNet/Core/Tokens/Anchor.cs.meta | 12 + YamlDotNet/Core/Tokens/AnchorAlias.cs | 66 + YamlDotNet/Core/Tokens/AnchorAlias.cs.meta | 12 + YamlDotNet/Core/Tokens/BlockEnd.cs | 51 + YamlDotNet/Core/Tokens/BlockEnd.cs.meta | 12 + YamlDotNet/Core/Tokens/BlockEntry.cs | 51 + YamlDotNet/Core/Tokens/BlockEntry.cs.meta | 12 + YamlDotNet/Core/Tokens/BlockMappingStart.cs | 51 + .../Core/Tokens/BlockMappingStart.cs.meta | 12 + YamlDotNet/Core/Tokens/BlockSequenceStart.cs | 51 + .../Core/Tokens/BlockSequenceStart.cs.meta | 12 + YamlDotNet/Core/Tokens/Comment.cs | 60 + YamlDotNet/Core/Tokens/Comment.cs.meta | 12 + YamlDotNet/Core/Tokens/DocumentEnd.cs | 51 + YamlDotNet/Core/Tokens/DocumentEnd.cs.meta | 12 + YamlDotNet/Core/Tokens/DocumentStart.cs | 51 + YamlDotNet/Core/Tokens/DocumentStart.cs.meta | 12 + YamlDotNet/Core/Tokens/FlowEntry.cs | 51 + YamlDotNet/Core/Tokens/FlowEntry.cs.meta | 12 + YamlDotNet/Core/Tokens/FlowMappingEnd.cs | 51 + YamlDotNet/Core/Tokens/FlowMappingEnd.cs.meta | 12 + YamlDotNet/Core/Tokens/FlowMappingStart.cs | 51 + .../Core/Tokens/FlowMappingStart.cs.meta | 12 + YamlDotNet/Core/Tokens/FlowSequenceEnd.cs | 51 + .../Core/Tokens/FlowSequenceEnd.cs.meta | 12 + YamlDotNet/Core/Tokens/FlowSequenceStart.cs | 51 + .../Core/Tokens/FlowSequenceStart.cs.meta | 12 + YamlDotNet/Core/Tokens/Key.cs | 51 + YamlDotNet/Core/Tokens/Key.cs.meta | 12 + YamlDotNet/Core/Tokens/Scalar.cs | 94 + YamlDotNet/Core/Tokens/Scalar.cs.meta | 12 + YamlDotNet/Core/Tokens/StreamEnd.cs | 51 + YamlDotNet/Core/Tokens/StreamEnd.cs.meta | 12 + YamlDotNet/Core/Tokens/StreamStart.cs | 50 + YamlDotNet/Core/Tokens/StreamStart.cs.meta | 12 + YamlDotNet/Core/Tokens/Tag.cs | 83 + YamlDotNet/Core/Tokens/Tag.cs.meta | 12 + YamlDotNet/Core/Tokens/TagDirective.cs | 133 + YamlDotNet/Core/Tokens/TagDirective.cs.meta | 12 + YamlDotNet/Core/Tokens/Token.cs | 69 + YamlDotNet/Core/Tokens/Token.cs.meta | 12 + YamlDotNet/Core/Tokens/Value.cs | 50 + YamlDotNet/Core/Tokens/Value.cs.meta | 12 + YamlDotNet/Core/Tokens/VersionDirective.cs | 91 + .../Core/Tokens/VersionDirective.cs.meta | 12 + YamlDotNet/Core/Version.cs | 77 + YamlDotNet/Core/Version.cs.meta | 12 + YamlDotNet/Core/YamlException.cs | 88 + YamlDotNet/Core/YamlException.cs.meta | 12 + YamlDotNet/Examples.meta | 9 + YamlDotNet/Examples.unity | 128 + YamlDotNet/Examples.unity.meta | 8 + YamlDotNet/Examples/ConvertYamlToJson.cs | 41 + YamlDotNet/Examples/ConvertYamlToJson.cs.meta | 12 + YamlDotNet/Examples/DeserializeObjectGraph.cs | 143 + .../Examples/DeserializeObjectGraph.cs.meta | 12 + .../DeserializingMultipleDocuments.cs | 58 + .../DeserializingMultipleDocuments.cs.meta | 12 + YamlDotNet/Examples/Helpers.meta | 9 + YamlDotNet/Examples/Helpers/ExampleRunner.cs | 146 + .../Examples/Helpers/ExampleRunner.cs.meta | 12 + .../Examples/Helpers/SampleAttribute.cs | 26 + .../Examples/Helpers/SampleAttribute.cs.meta | 12 + .../Helpers/TestOutputHelperExtensions.cs | 10 + .../TestOutputHelperExtensions.cs.meta | 12 + YamlDotNet/Examples/LoadingAYamlStream.cs | 85 + .../Examples/LoadingAYamlStream.cs.meta | 12 + YamlDotNet/Examples/SerializeObjectGraph.cs | 96 + .../Examples/SerializeObjectGraph.cs.meta | 12 + YamlDotNet/Helpers.meta | 9 + YamlDotNet/Helpers/ExpressionExtensions.cs | 62 + .../Helpers/ExpressionExtensions.cs.meta | 12 + .../GenericCollectionToNonGenericAdapter.cs | 136 + ...nericCollectionToNonGenericAdapter.cs.meta | 12 + .../GenericDictionaryToNonGenericAdapter.cs | 180 ++ ...nericDictionaryToNonGenericAdapter.cs.meta | 12 + YamlDotNet/Helpers/ITestOutputHelper.cs | 8 + YamlDotNet/Helpers/ITestOutputHelper.cs.meta | 12 + YamlDotNet/Helpers/Portability.cs | 152 ++ YamlDotNet/Helpers/Portability.cs.meta | 12 + YamlDotNet/Readme.txt | 9 + YamlDotNet/Readme.txt.meta | 8 + YamlDotNet/RepresentationModel.meta | 9 + .../DocumentLoadingState.cs | 105 + .../DocumentLoadingState.cs.meta | 12 + .../RepresentationModel/EmitterState.cs | 45 + .../RepresentationModel/EmitterState.cs.meta | 12 + .../RepresentationModel/IYamlVisitor.cs | 71 + .../RepresentationModel/IYamlVisitor.cs.meta | 12 + .../RepresentationModel/YamlAliasNode.cs | 120 + .../RepresentationModel/YamlAliasNode.cs.meta | 12 + .../RepresentationModel/YamlDocument.cs | 208 ++ .../RepresentationModel/YamlDocument.cs.meta | 12 + .../RepresentationModel/YamlMappingNode.cs | 427 +++ .../YamlMappingNode.cs.meta | 12 + YamlDotNet/RepresentationModel/YamlNode.cs | 288 ++ .../RepresentationModel/YamlNode.cs.meta | 12 + .../YamlNodeIdentityEqualityComparer.cs | 47 + .../YamlNodeIdentityEqualityComparer.cs.meta | 12 + .../RepresentationModel/YamlNodeType.cs | 33 + .../RepresentationModel/YamlNodeType.cs.meta | 12 + .../RepresentationModel/YamlScalarNode.cs | 183 ++ .../YamlScalarNode.cs.meta | 12 + .../RepresentationModel/YamlSequenceNode.cs | 300 +++ .../YamlSequenceNode.cs.meta | 12 + YamlDotNet/RepresentationModel/YamlStream.cs | 166 ++ .../RepresentationModel/YamlStream.cs.meta | 12 + YamlDotNet/RepresentationModel/YamlVisitor.cs | 233 ++ .../RepresentationModel/YamlVisitor.cs.meta | 12 + .../RepresentationModel/YamlVisitorBase.cs | 151 ++ .../YamlVisitorBase.cs.meta | 12 + YamlDotNet/Serialization.meta | 9 + YamlDotNet/Serialization/BuilderSkeleton.cs | 299 +++ .../Serialization/BuilderSkeleton.cs.meta | 12 + YamlDotNet/Serialization/Converters.meta | 9 + .../Converters/DateTimeConverter.cs | 118 + .../Converters/DateTimeConverter.cs.meta | 12 + .../Serialization/Converters/GuidConverter.cs | 56 + .../Converters/GuidConverter.cs.meta | 12 + YamlDotNet/Serialization/Deserializer.cs | 333 +++ YamlDotNet/Serialization/Deserializer.cs.meta | 12 + .../Serialization/DeserializerBuilder.cs | 357 +++ .../Serialization/DeserializerBuilder.cs.meta | 12 + .../EmissionPhaseObjectGraphVisitorArgs.cs | 111 + ...missionPhaseObjectGraphVisitorArgs.cs.meta | 12 + YamlDotNet/Serialization/EventEmitters.meta | 9 + .../EventEmitters/ChainedEventEmitter.cs | 75 + .../EventEmitters/ChainedEventEmitter.cs.meta | 12 + .../EventEmitters/CustomTagEventEmitter.cs | 26 + .../CustomTagEventEmitter.cs.meta | 12 + .../EventEmitters/JsonEventEmitter.cs | 111 + .../EventEmitters/JsonEventEmitter.cs.meta | 12 + .../TypeAssigningEventEmitter.cs | 139 + .../TypeAssigningEventEmitter.cs.meta | 12 + .../EventEmitters/WriterEventEmitter.cs | 59 + .../EventEmitters/WriterEventEmitter.cs.meta | 12 + YamlDotNet/Serialization/EventInfo.cs | 109 + YamlDotNet/Serialization/EventInfo.cs.meta | 12 + YamlDotNet/Serialization/IAliasProvider.cs | 28 + .../Serialization/IAliasProvider.cs.meta | 12 + YamlDotNet/Serialization/IEventEmitter.cs | 35 + .../Serialization/IEventEmitter.cs.meta | 12 + YamlDotNet/Serialization/INamingConvention.cs | 32 + .../Serialization/INamingConvention.cs.meta | 12 + YamlDotNet/Serialization/INodeDeserializer.cs | 31 + .../Serialization/INodeDeserializer.cs.meta | 12 + YamlDotNet/Serialization/INodeTypeResolver.cs | 40 + .../Serialization/INodeTypeResolver.cs.meta | 12 + YamlDotNet/Serialization/IObjectDescriptor.cs | 52 + .../Serialization/IObjectDescriptor.cs.meta | 12 + YamlDotNet/Serialization/IObjectFactory.cs | 39 + .../Serialization/IObjectFactory.cs.meta | 12 + .../IObjectGraphTraversalStrategy.cs | 39 + .../IObjectGraphTraversalStrategy.cs.meta | 12 + .../Serialization/IObjectGraphVisitor.cs | 99 + .../Serialization/IObjectGraphVisitor.cs.meta | 12 + .../Serialization/IPropertyDescriptor.cs | 41 + .../Serialization/IPropertyDescriptor.cs.meta | 12 + .../IRegistrationLocationSelectionSyntax.cs | 59 + ...egistrationLocationSelectionSyntax.cs.meta | 12 + YamlDotNet/Serialization/ITypeInspector.cs | 53 + .../Serialization/ITypeInspector.cs.meta | 12 + YamlDotNet/Serialization/ITypeResolver.cs | 33 + .../Serialization/ITypeResolver.cs.meta | 12 + .../Serialization/IValueDeserializer.cs | 32 + .../Serialization/IValueDeserializer.cs.meta | 12 + YamlDotNet/Serialization/IValuePromise.cs | 32 + .../Serialization/IValuePromise.cs.meta | 12 + YamlDotNet/Serialization/IValueSerializer.cs | 31 + .../Serialization/IValueSerializer.cs.meta | 12 + YamlDotNet/Serialization/IYamlConvertible.cs | 67 + .../Serialization/IYamlConvertible.cs.meta | 12 + YamlDotNet/Serialization/IYamlSerializable.cs | 43 + .../Serialization/IYamlSerializable.cs.meta | 12 + .../Serialization/IYamlTypeConverter.cs | 47 + .../Serialization/IYamlTypeConverter.cs.meta | 12 + .../LazyComponentRegistrationList.cs | 237 ++ .../LazyComponentRegistrationList.cs.meta | 12 + ...LazyComponentRegistrationListExtensions.cs | 64 + ...omponentRegistrationListExtensions.cs.meta | 12 + .../Serialization/NamingConventions.meta | 9 + .../CamelCaseNamingConvention.cs | 38 + .../CamelCaseNamingConvention.cs.meta | 12 + .../HyphenatedNamingConvention.cs | 36 + .../HyphenatedNamingConvention.cs.meta | 12 + .../NamingConventions/NullNamingConvention.cs | 35 + .../NullNamingConvention.cs.meta | 12 + .../PascalCaseNamingConvention.cs | 38 + .../PascalCaseNamingConvention.cs.meta | 12 + .../UnderscoredNamingConvention.cs | 36 + .../UnderscoredNamingConvention.cs.meta | 12 + .../Serialization/NodeDeserializers.meta | 9 + .../ArrayNodeDeserializer.cs | 153 ++ .../ArrayNodeDeserializer.cs.meta | 12 + .../CollectionNodeDeserializer.cs | 109 + .../CollectionNodeDeserializer.cs.meta | 12 + .../DictionaryNodeDeserializer.cs | 146 + .../DictionaryNodeDeserializer.cs.meta | 12 + .../EnumerableNodeDeserializer.cs | 57 + .../EnumerableNodeDeserializer.cs.meta | 12 + .../NodeDeserializers/NullNodeDeserializer.cs | 61 + .../NullNodeDeserializer.cs.meta | 12 + .../ObjectNodeDeserializer.cs | 87 + .../ObjectNodeDeserializer.cs.meta | 12 + .../ScalarNodeDeserializer.cs | 315 +++ .../ScalarNodeDeserializer.cs.meta | 12 + .../TypeConverterNodeDeserializer.cs | 57 + .../TypeConverterNodeDeserializer.cs.meta | 12 + .../YamlConvertibleNodeDeserializer.cs | 50 + .../YamlConvertibleNodeDeserializer.cs.meta | 12 + .../YamlSerializableNodeDeserializer.cs | 52 + .../YamlSerializableNodeDeserializer.cs.meta | 12 + .../Serialization/NodeTypeResolvers.meta | 9 + .../DefaultContainersNodeTypeResolver.cs | 49 + .../DefaultContainersNodeTypeResolver.cs.meta | 12 + .../NodeTypeResolvers/TagNodeTypeResolver.cs | 53 + .../TagNodeTypeResolver.cs.meta | 12 + .../TypeNameInTagNodeTypeResolver.cs | 41 + .../TypeNameInTagNodeTypeResolver.cs.meta | 12 + .../YamlConvertibleTypeResolver.cs | 34 + .../YamlConvertibleTypeResolver.cs.meta | 12 + .../YamlSerializableTypeResolver.cs | 36 + .../YamlSerializableTypeResolver.cs.meta | 12 + YamlDotNet/Serialization/Nothing.cs | 32 + YamlDotNet/Serialization/Nothing.cs.meta | 12 + YamlDotNet/Serialization/ObjectDescriptor.cs | 60 + .../Serialization/ObjectDescriptor.cs.meta | 12 + YamlDotNet/Serialization/ObjectFactories.meta | 9 + .../ObjectFactories/DefaultObjectFactory.cs | 62 + .../DefaultObjectFactory.cs.meta | 12 + .../ObjectFactories/LambdaObjectFactory.cs | 48 + .../LambdaObjectFactory.cs.meta | 12 + .../ObjectGraphTraversalStrategies.meta | 9 + .../FullObjectGraphTraversalStrategy.cs | 219 ++ .../FullObjectGraphTraversalStrategy.cs.meta | 12 + .../RoundtripObjectGraphTraversalStrategy.cs | 54 + ...ndtripObjectGraphTraversalStrategy.cs.meta | 12 + .../Serialization/ObjectGraphVisitors.meta | 9 + .../ObjectGraphVisitors/AnchorAssigner.cs | 106 + .../AnchorAssigner.cs.meta | 12 + .../AnchorAssigningObjectGraphVisitor.cs | 68 + .../AnchorAssigningObjectGraphVisitor.cs.meta | 12 + .../ChainedObjectGraphVisitor.cs | 76 + .../ChainedObjectGraphVisitor.cs.meta | 12 + .../CustomSerializationObjectGraphVisitor.cs | 71 + ...tomSerializationObjectGraphVisitor.cs.meta | 12 + .../DefaultExclusiveObjectGraphVisitor.cs | 60 + ...DefaultExclusiveObjectGraphVisitor.cs.meta | 12 + .../EmittingObjectGraphVisitor.cs | 76 + .../EmittingObjectGraphVisitor.cs.meta | 12 + ...ocessingPhaseObjectGraphVisitorSkeleton.cs | 111 + ...ingPhaseObjectGraphVisitorSkeleton.cs.meta | 12 + .../Serialization/PropertyDescriptor.cs | 75 + .../Serialization/PropertyDescriptor.cs.meta | 12 + .../Serialization/SerializationOptions.cs | 69 + .../SerializationOptions.cs.meta | 12 + YamlDotNet/Serialization/Serializer.cs | 304 +++ YamlDotNet/Serialization/Serializer.cs.meta | 12 + YamlDotNet/Serialization/SerializerBuilder.cs | 520 ++++ .../Serialization/SerializerBuilder.cs.meta | 12 + YamlDotNet/Serialization/StreamFragment.cs | 84 + .../Serialization/StreamFragment.cs.meta | 12 + YamlDotNet/Serialization/TagMappings.cs | 79 + YamlDotNet/Serialization/TagMappings.cs.meta | 12 + YamlDotNet/Serialization/TypeInspectors.meta | 9 + .../TypeInspectors/CachedTypeInspector.cs | 56 + .../CachedTypeInspector.cs.meta | 12 + .../NamingConventionTypeInspector.cs | 68 + .../NamingConventionTypeInspector.cs.meta | 12 + ...dableAndWritablePropertiesTypeInspector.cs | 46 + ...AndWritablePropertiesTypeInspector.cs.meta | 12 + .../ReadablePropertiesTypeInspector.cs | 99 + .../ReadablePropertiesTypeInspector.cs.meta | 12 + .../TypeInspectors/TypeInspectorSkeleton.cs | 77 + .../TypeInspectorSkeleton.cs.meta | 12 + YamlDotNet/Serialization/TypeResolvers.meta | 9 + .../TypeResolvers/DynamicTypeResolver.cs | 36 + .../TypeResolvers/DynamicTypeResolver.cs.meta | 12 + .../TypeResolvers/StaticTypeResolver.cs | 36 + .../TypeResolvers/StaticTypeResolver.cs.meta | 12 + YamlDotNet/Serialization/Utilities.meta | 9 + .../Utilities/IPostDeserializationCallback.cs | 32 + .../IPostDeserializationCallback.cs.meta | 12 + .../Utilities/ObjectAnchorCollection.cs | 76 + .../Utilities/ObjectAnchorCollection.cs.meta | 12 + .../Utilities/ReflectionUtility.cs | 54 + .../Utilities/ReflectionUtility.cs.meta | 12 + .../Utilities/SerializerState.cs | 68 + .../Utilities/SerializerState.cs.meta | 12 + .../Utilities/StringExtensions.cs | 79 + .../Utilities/StringExtensions.cs.meta | 12 + .../Serialization/Utilities/TypeConverter.cs | 234 ++ .../Utilities/TypeConverter.cs.meta | 12 + .../Serialization/ValueDeserializers.meta | 9 + .../AliasValueDeserializer.cs | 158 ++ .../AliasValueDeserializer.cs.meta | 12 + .../NodeValueDeserializer.cs | 100 + .../NodeValueDeserializer.cs.meta | 12 + .../Serialization/YamlAttributeOverrides.cs | 191 ++ .../YamlAttributeOverrides.cs.meta | 12 + .../YamlAttributeOverridesInspector.cs | 107 + .../YamlAttributeOverridesInspector.cs.meta | 12 + .../YamlAttributesTypeInspector.cs | 70 + .../YamlAttributesTypeInspector.cs.meta | 12 + YamlDotNet/Serialization/YamlFormatter.cs | 75 + .../Serialization/YamlFormatter.cs.meta | 12 + .../Serialization/YamlIgnoreAttribute.cs | 34 + .../Serialization/YamlIgnoreAttribute.cs.meta | 12 + YamlDotNet/Serialization/YamlMember.cs | 76 + YamlDotNet/Serialization/YamlMember.cs.meta | 12 + YamlDotNet/YamlDotNet.license.txt | 7 + YamlDotNet/YamlDotNet.license.txt.meta | 8 + 409 files changed, 25175 insertions(+) create mode 100644 SetupMenuItem.cs create mode 100644 YamlDotNet/Core.meta create mode 100644 YamlDotNet/Core/AnchorNotFoundException.cs create mode 100644 YamlDotNet/Core/AnchorNotFoundException.cs.meta create mode 100644 YamlDotNet/Core/CharacterAnalyzer.cs create mode 100644 YamlDotNet/Core/CharacterAnalyzer.cs.meta create mode 100644 YamlDotNet/Core/Constants.cs create mode 100644 YamlDotNet/Core/Constants.cs.meta create mode 100644 YamlDotNet/Core/Cursor.cs create mode 100644 YamlDotNet/Core/Cursor.cs.meta create mode 100644 YamlDotNet/Core/Emitter.cs create mode 100644 YamlDotNet/Core/Emitter.cs.meta create mode 100644 YamlDotNet/Core/EmitterState.cs create mode 100644 YamlDotNet/Core/EmitterState.cs.meta create mode 100644 YamlDotNet/Core/Events.meta create mode 100644 YamlDotNet/Core/Events/AnchorAlias.cs create mode 100644 YamlDotNet/Core/Events/AnchorAlias.cs.meta create mode 100644 YamlDotNet/Core/Events/Comment.cs create mode 100644 YamlDotNet/Core/Events/Comment.cs.meta create mode 100644 YamlDotNet/Core/Events/DocumentEnd.cs create mode 100644 YamlDotNet/Core/Events/DocumentEnd.cs.meta create mode 100644 YamlDotNet/Core/Events/DocumentStart.cs create mode 100644 YamlDotNet/Core/Events/DocumentStart.cs.meta create mode 100644 YamlDotNet/Core/Events/EventType.cs create mode 100644 YamlDotNet/Core/Events/EventType.cs.meta create mode 100644 YamlDotNet/Core/Events/IParsingEventVisitor.cs create mode 100644 YamlDotNet/Core/Events/IParsingEventVisitor.cs.meta create mode 100644 YamlDotNet/Core/Events/MappingEnd.cs create mode 100644 YamlDotNet/Core/Events/MappingEnd.cs.meta create mode 100644 YamlDotNet/Core/Events/MappingStart.cs create mode 100644 YamlDotNet/Core/Events/MappingStart.cs.meta create mode 100644 YamlDotNet/Core/Events/MappingStyle.cs create mode 100644 YamlDotNet/Core/Events/MappingStyle.cs.meta create mode 100644 YamlDotNet/Core/Events/NodeEvent.cs create mode 100644 YamlDotNet/Core/Events/NodeEvent.cs.meta create mode 100644 YamlDotNet/Core/Events/ParsingEvent.cs create mode 100644 YamlDotNet/Core/Events/ParsingEvent.cs.meta create mode 100644 YamlDotNet/Core/Events/Scalar.cs create mode 100644 YamlDotNet/Core/Events/Scalar.cs.meta create mode 100644 YamlDotNet/Core/Events/SequenceEnd.cs create mode 100644 YamlDotNet/Core/Events/SequenceEnd.cs.meta create mode 100644 YamlDotNet/Core/Events/SequenceStart.cs create mode 100644 YamlDotNet/Core/Events/SequenceStart.cs.meta create mode 100644 YamlDotNet/Core/Events/SequenceStyle.cs create mode 100644 YamlDotNet/Core/Events/SequenceStyle.cs.meta create mode 100644 YamlDotNet/Core/Events/StreamEnd.cs create mode 100644 YamlDotNet/Core/Events/StreamEnd.cs.meta create mode 100644 YamlDotNet/Core/Events/StreamStart.cs create mode 100644 YamlDotNet/Core/Events/StreamStart.cs.meta create mode 100644 YamlDotNet/Core/FakeList.cs create mode 100644 YamlDotNet/Core/FakeList.cs.meta create mode 100644 YamlDotNet/Core/ForwardAnchorNotSupportedException.cs create mode 100644 YamlDotNet/Core/ForwardAnchorNotSupportedException.cs.meta create mode 100644 YamlDotNet/Core/HashCode.cs create mode 100644 YamlDotNet/Core/HashCode.cs.meta create mode 100644 YamlDotNet/Core/IEmitter.cs create mode 100644 YamlDotNet/Core/IEmitter.cs.meta create mode 100644 YamlDotNet/Core/ILookAheadBuffer.cs create mode 100644 YamlDotNet/Core/ILookAheadBuffer.cs.meta create mode 100644 YamlDotNet/Core/IParser.cs create mode 100644 YamlDotNet/Core/IParser.cs.meta create mode 100644 YamlDotNet/Core/IScanner.cs create mode 100644 YamlDotNet/Core/IScanner.cs.meta create mode 100644 YamlDotNet/Core/InsertionQueue.cs create mode 100644 YamlDotNet/Core/InsertionQueue.cs.meta create mode 100644 YamlDotNet/Core/LookAheadBuffer.cs create mode 100644 YamlDotNet/Core/LookAheadBuffer.cs.meta create mode 100644 YamlDotNet/Core/Mark.cs create mode 100644 YamlDotNet/Core/Mark.cs.meta create mode 100644 YamlDotNet/Core/MaximumRecursionLevelReachedException.cs create mode 100644 YamlDotNet/Core/MaximumRecursionLevelReachedException.cs.meta create mode 100644 YamlDotNet/Core/MergingParser.cs create mode 100644 YamlDotNet/Core/MergingParser.cs.meta create mode 100644 YamlDotNet/Core/Parser.cs create mode 100644 YamlDotNet/Core/Parser.cs.meta create mode 100644 YamlDotNet/Core/ParserExtensions.cs create mode 100644 YamlDotNet/Core/ParserExtensions.cs.meta create mode 100644 YamlDotNet/Core/ParserState.cs create mode 100644 YamlDotNet/Core/ParserState.cs.meta create mode 100644 YamlDotNet/Core/RecursionLevel.cs create mode 100644 YamlDotNet/Core/RecursionLevel.cs.meta create mode 100644 YamlDotNet/Core/ScalarStyle.cs create mode 100644 YamlDotNet/Core/ScalarStyle.cs.meta create mode 100644 YamlDotNet/Core/Scanner.cs create mode 100644 YamlDotNet/Core/Scanner.cs.meta create mode 100644 YamlDotNet/Core/SemanticErrorException.cs create mode 100644 YamlDotNet/Core/SemanticErrorException.cs.meta create mode 100644 YamlDotNet/Core/SimpleKey.cs create mode 100644 YamlDotNet/Core/SimpleKey.cs.meta create mode 100644 YamlDotNet/Core/StringLookAheadBuffer.cs create mode 100644 YamlDotNet/Core/StringLookAheadBuffer.cs.meta create mode 100644 YamlDotNet/Core/SyntaxErrorException.cs create mode 100644 YamlDotNet/Core/SyntaxErrorException.cs.meta create mode 100644 YamlDotNet/Core/TagDirectiveCollection.cs create mode 100644 YamlDotNet/Core/TagDirectiveCollection.cs.meta create mode 100644 YamlDotNet/Core/Tokens.meta create mode 100644 YamlDotNet/Core/Tokens/Anchor.cs create mode 100644 YamlDotNet/Core/Tokens/Anchor.cs.meta create mode 100644 YamlDotNet/Core/Tokens/AnchorAlias.cs create mode 100644 YamlDotNet/Core/Tokens/AnchorAlias.cs.meta create mode 100644 YamlDotNet/Core/Tokens/BlockEnd.cs create mode 100644 YamlDotNet/Core/Tokens/BlockEnd.cs.meta create mode 100644 YamlDotNet/Core/Tokens/BlockEntry.cs create mode 100644 YamlDotNet/Core/Tokens/BlockEntry.cs.meta create mode 100644 YamlDotNet/Core/Tokens/BlockMappingStart.cs create mode 100644 YamlDotNet/Core/Tokens/BlockMappingStart.cs.meta create mode 100644 YamlDotNet/Core/Tokens/BlockSequenceStart.cs create mode 100644 YamlDotNet/Core/Tokens/BlockSequenceStart.cs.meta create mode 100644 YamlDotNet/Core/Tokens/Comment.cs create mode 100644 YamlDotNet/Core/Tokens/Comment.cs.meta create mode 100644 YamlDotNet/Core/Tokens/DocumentEnd.cs create mode 100644 YamlDotNet/Core/Tokens/DocumentEnd.cs.meta create mode 100644 YamlDotNet/Core/Tokens/DocumentStart.cs create mode 100644 YamlDotNet/Core/Tokens/DocumentStart.cs.meta create mode 100644 YamlDotNet/Core/Tokens/FlowEntry.cs create mode 100644 YamlDotNet/Core/Tokens/FlowEntry.cs.meta create mode 100644 YamlDotNet/Core/Tokens/FlowMappingEnd.cs create mode 100644 YamlDotNet/Core/Tokens/FlowMappingEnd.cs.meta create mode 100644 YamlDotNet/Core/Tokens/FlowMappingStart.cs create mode 100644 YamlDotNet/Core/Tokens/FlowMappingStart.cs.meta create mode 100644 YamlDotNet/Core/Tokens/FlowSequenceEnd.cs create mode 100644 YamlDotNet/Core/Tokens/FlowSequenceEnd.cs.meta create mode 100644 YamlDotNet/Core/Tokens/FlowSequenceStart.cs create mode 100644 YamlDotNet/Core/Tokens/FlowSequenceStart.cs.meta create mode 100644 YamlDotNet/Core/Tokens/Key.cs create mode 100644 YamlDotNet/Core/Tokens/Key.cs.meta create mode 100644 YamlDotNet/Core/Tokens/Scalar.cs create mode 100644 YamlDotNet/Core/Tokens/Scalar.cs.meta create mode 100644 YamlDotNet/Core/Tokens/StreamEnd.cs create mode 100644 YamlDotNet/Core/Tokens/StreamEnd.cs.meta create mode 100644 YamlDotNet/Core/Tokens/StreamStart.cs create mode 100644 YamlDotNet/Core/Tokens/StreamStart.cs.meta create mode 100644 YamlDotNet/Core/Tokens/Tag.cs create mode 100644 YamlDotNet/Core/Tokens/Tag.cs.meta create mode 100644 YamlDotNet/Core/Tokens/TagDirective.cs create mode 100644 YamlDotNet/Core/Tokens/TagDirective.cs.meta create mode 100644 YamlDotNet/Core/Tokens/Token.cs create mode 100644 YamlDotNet/Core/Tokens/Token.cs.meta create mode 100644 YamlDotNet/Core/Tokens/Value.cs create mode 100644 YamlDotNet/Core/Tokens/Value.cs.meta create mode 100644 YamlDotNet/Core/Tokens/VersionDirective.cs create mode 100644 YamlDotNet/Core/Tokens/VersionDirective.cs.meta create mode 100644 YamlDotNet/Core/Version.cs create mode 100644 YamlDotNet/Core/Version.cs.meta create mode 100644 YamlDotNet/Core/YamlException.cs create mode 100644 YamlDotNet/Core/YamlException.cs.meta create mode 100644 YamlDotNet/Examples.meta create mode 100644 YamlDotNet/Examples.unity create mode 100644 YamlDotNet/Examples.unity.meta create mode 100644 YamlDotNet/Examples/ConvertYamlToJson.cs create mode 100644 YamlDotNet/Examples/ConvertYamlToJson.cs.meta create mode 100644 YamlDotNet/Examples/DeserializeObjectGraph.cs create mode 100644 YamlDotNet/Examples/DeserializeObjectGraph.cs.meta create mode 100644 YamlDotNet/Examples/DeserializingMultipleDocuments.cs create mode 100644 YamlDotNet/Examples/DeserializingMultipleDocuments.cs.meta create mode 100644 YamlDotNet/Examples/Helpers.meta create mode 100644 YamlDotNet/Examples/Helpers/ExampleRunner.cs create mode 100644 YamlDotNet/Examples/Helpers/ExampleRunner.cs.meta create mode 100644 YamlDotNet/Examples/Helpers/SampleAttribute.cs create mode 100644 YamlDotNet/Examples/Helpers/SampleAttribute.cs.meta create mode 100644 YamlDotNet/Examples/Helpers/TestOutputHelperExtensions.cs create mode 100644 YamlDotNet/Examples/Helpers/TestOutputHelperExtensions.cs.meta create mode 100644 YamlDotNet/Examples/LoadingAYamlStream.cs create mode 100644 YamlDotNet/Examples/LoadingAYamlStream.cs.meta create mode 100644 YamlDotNet/Examples/SerializeObjectGraph.cs create mode 100644 YamlDotNet/Examples/SerializeObjectGraph.cs.meta create mode 100644 YamlDotNet/Helpers.meta create mode 100644 YamlDotNet/Helpers/ExpressionExtensions.cs create mode 100644 YamlDotNet/Helpers/ExpressionExtensions.cs.meta create mode 100644 YamlDotNet/Helpers/GenericCollectionToNonGenericAdapter.cs create mode 100644 YamlDotNet/Helpers/GenericCollectionToNonGenericAdapter.cs.meta create mode 100644 YamlDotNet/Helpers/GenericDictionaryToNonGenericAdapter.cs create mode 100644 YamlDotNet/Helpers/GenericDictionaryToNonGenericAdapter.cs.meta create mode 100644 YamlDotNet/Helpers/ITestOutputHelper.cs create mode 100644 YamlDotNet/Helpers/ITestOutputHelper.cs.meta create mode 100644 YamlDotNet/Helpers/Portability.cs create mode 100644 YamlDotNet/Helpers/Portability.cs.meta create mode 100644 YamlDotNet/Readme.txt create mode 100644 YamlDotNet/Readme.txt.meta create mode 100644 YamlDotNet/RepresentationModel.meta create mode 100644 YamlDotNet/RepresentationModel/DocumentLoadingState.cs create mode 100644 YamlDotNet/RepresentationModel/DocumentLoadingState.cs.meta create mode 100644 YamlDotNet/RepresentationModel/EmitterState.cs create mode 100644 YamlDotNet/RepresentationModel/EmitterState.cs.meta create mode 100644 YamlDotNet/RepresentationModel/IYamlVisitor.cs create mode 100644 YamlDotNet/RepresentationModel/IYamlVisitor.cs.meta create mode 100644 YamlDotNet/RepresentationModel/YamlAliasNode.cs create mode 100644 YamlDotNet/RepresentationModel/YamlAliasNode.cs.meta create mode 100644 YamlDotNet/RepresentationModel/YamlDocument.cs create mode 100644 YamlDotNet/RepresentationModel/YamlDocument.cs.meta create mode 100644 YamlDotNet/RepresentationModel/YamlMappingNode.cs create mode 100644 YamlDotNet/RepresentationModel/YamlMappingNode.cs.meta create mode 100644 YamlDotNet/RepresentationModel/YamlNode.cs create mode 100644 YamlDotNet/RepresentationModel/YamlNode.cs.meta create mode 100644 YamlDotNet/RepresentationModel/YamlNodeIdentityEqualityComparer.cs create mode 100644 YamlDotNet/RepresentationModel/YamlNodeIdentityEqualityComparer.cs.meta create mode 100644 YamlDotNet/RepresentationModel/YamlNodeType.cs create mode 100644 YamlDotNet/RepresentationModel/YamlNodeType.cs.meta create mode 100644 YamlDotNet/RepresentationModel/YamlScalarNode.cs create mode 100644 YamlDotNet/RepresentationModel/YamlScalarNode.cs.meta create mode 100644 YamlDotNet/RepresentationModel/YamlSequenceNode.cs create mode 100644 YamlDotNet/RepresentationModel/YamlSequenceNode.cs.meta create mode 100644 YamlDotNet/RepresentationModel/YamlStream.cs create mode 100644 YamlDotNet/RepresentationModel/YamlStream.cs.meta create mode 100644 YamlDotNet/RepresentationModel/YamlVisitor.cs create mode 100644 YamlDotNet/RepresentationModel/YamlVisitor.cs.meta create mode 100644 YamlDotNet/RepresentationModel/YamlVisitorBase.cs create mode 100644 YamlDotNet/RepresentationModel/YamlVisitorBase.cs.meta create mode 100644 YamlDotNet/Serialization.meta create mode 100644 YamlDotNet/Serialization/BuilderSkeleton.cs create mode 100644 YamlDotNet/Serialization/BuilderSkeleton.cs.meta create mode 100644 YamlDotNet/Serialization/Converters.meta create mode 100644 YamlDotNet/Serialization/Converters/DateTimeConverter.cs create mode 100644 YamlDotNet/Serialization/Converters/DateTimeConverter.cs.meta create mode 100644 YamlDotNet/Serialization/Converters/GuidConverter.cs create mode 100644 YamlDotNet/Serialization/Converters/GuidConverter.cs.meta create mode 100644 YamlDotNet/Serialization/Deserializer.cs create mode 100644 YamlDotNet/Serialization/Deserializer.cs.meta create mode 100644 YamlDotNet/Serialization/DeserializerBuilder.cs create mode 100644 YamlDotNet/Serialization/DeserializerBuilder.cs.meta create mode 100644 YamlDotNet/Serialization/EmissionPhaseObjectGraphVisitorArgs.cs create mode 100644 YamlDotNet/Serialization/EmissionPhaseObjectGraphVisitorArgs.cs.meta create mode 100644 YamlDotNet/Serialization/EventEmitters.meta create mode 100644 YamlDotNet/Serialization/EventEmitters/ChainedEventEmitter.cs create mode 100644 YamlDotNet/Serialization/EventEmitters/ChainedEventEmitter.cs.meta create mode 100644 YamlDotNet/Serialization/EventEmitters/CustomTagEventEmitter.cs create mode 100644 YamlDotNet/Serialization/EventEmitters/CustomTagEventEmitter.cs.meta create mode 100644 YamlDotNet/Serialization/EventEmitters/JsonEventEmitter.cs create mode 100644 YamlDotNet/Serialization/EventEmitters/JsonEventEmitter.cs.meta create mode 100644 YamlDotNet/Serialization/EventEmitters/TypeAssigningEventEmitter.cs create mode 100644 YamlDotNet/Serialization/EventEmitters/TypeAssigningEventEmitter.cs.meta create mode 100644 YamlDotNet/Serialization/EventEmitters/WriterEventEmitter.cs create mode 100644 YamlDotNet/Serialization/EventEmitters/WriterEventEmitter.cs.meta create mode 100644 YamlDotNet/Serialization/EventInfo.cs create mode 100644 YamlDotNet/Serialization/EventInfo.cs.meta create mode 100644 YamlDotNet/Serialization/IAliasProvider.cs create mode 100644 YamlDotNet/Serialization/IAliasProvider.cs.meta create mode 100644 YamlDotNet/Serialization/IEventEmitter.cs create mode 100644 YamlDotNet/Serialization/IEventEmitter.cs.meta create mode 100644 YamlDotNet/Serialization/INamingConvention.cs create mode 100644 YamlDotNet/Serialization/INamingConvention.cs.meta create mode 100644 YamlDotNet/Serialization/INodeDeserializer.cs create mode 100644 YamlDotNet/Serialization/INodeDeserializer.cs.meta create mode 100644 YamlDotNet/Serialization/INodeTypeResolver.cs create mode 100644 YamlDotNet/Serialization/INodeTypeResolver.cs.meta create mode 100644 YamlDotNet/Serialization/IObjectDescriptor.cs create mode 100644 YamlDotNet/Serialization/IObjectDescriptor.cs.meta create mode 100644 YamlDotNet/Serialization/IObjectFactory.cs create mode 100644 YamlDotNet/Serialization/IObjectFactory.cs.meta create mode 100644 YamlDotNet/Serialization/IObjectGraphTraversalStrategy.cs create mode 100644 YamlDotNet/Serialization/IObjectGraphTraversalStrategy.cs.meta create mode 100644 YamlDotNet/Serialization/IObjectGraphVisitor.cs create mode 100644 YamlDotNet/Serialization/IObjectGraphVisitor.cs.meta create mode 100644 YamlDotNet/Serialization/IPropertyDescriptor.cs create mode 100644 YamlDotNet/Serialization/IPropertyDescriptor.cs.meta create mode 100644 YamlDotNet/Serialization/IRegistrationLocationSelectionSyntax.cs create mode 100644 YamlDotNet/Serialization/IRegistrationLocationSelectionSyntax.cs.meta create mode 100644 YamlDotNet/Serialization/ITypeInspector.cs create mode 100644 YamlDotNet/Serialization/ITypeInspector.cs.meta create mode 100644 YamlDotNet/Serialization/ITypeResolver.cs create mode 100644 YamlDotNet/Serialization/ITypeResolver.cs.meta create mode 100644 YamlDotNet/Serialization/IValueDeserializer.cs create mode 100644 YamlDotNet/Serialization/IValueDeserializer.cs.meta create mode 100644 YamlDotNet/Serialization/IValuePromise.cs create mode 100644 YamlDotNet/Serialization/IValuePromise.cs.meta create mode 100644 YamlDotNet/Serialization/IValueSerializer.cs create mode 100644 YamlDotNet/Serialization/IValueSerializer.cs.meta create mode 100644 YamlDotNet/Serialization/IYamlConvertible.cs create mode 100644 YamlDotNet/Serialization/IYamlConvertible.cs.meta create mode 100644 YamlDotNet/Serialization/IYamlSerializable.cs create mode 100644 YamlDotNet/Serialization/IYamlSerializable.cs.meta create mode 100644 YamlDotNet/Serialization/IYamlTypeConverter.cs create mode 100644 YamlDotNet/Serialization/IYamlTypeConverter.cs.meta create mode 100644 YamlDotNet/Serialization/LazyComponentRegistrationList.cs create mode 100644 YamlDotNet/Serialization/LazyComponentRegistrationList.cs.meta create mode 100644 YamlDotNet/Serialization/LazyComponentRegistrationListExtensions.cs create mode 100644 YamlDotNet/Serialization/LazyComponentRegistrationListExtensions.cs.meta create mode 100644 YamlDotNet/Serialization/NamingConventions.meta create mode 100644 YamlDotNet/Serialization/NamingConventions/CamelCaseNamingConvention.cs create mode 100644 YamlDotNet/Serialization/NamingConventions/CamelCaseNamingConvention.cs.meta create mode 100644 YamlDotNet/Serialization/NamingConventions/HyphenatedNamingConvention.cs create mode 100644 YamlDotNet/Serialization/NamingConventions/HyphenatedNamingConvention.cs.meta create mode 100644 YamlDotNet/Serialization/NamingConventions/NullNamingConvention.cs create mode 100644 YamlDotNet/Serialization/NamingConventions/NullNamingConvention.cs.meta create mode 100644 YamlDotNet/Serialization/NamingConventions/PascalCaseNamingConvention.cs create mode 100644 YamlDotNet/Serialization/NamingConventions/PascalCaseNamingConvention.cs.meta create mode 100644 YamlDotNet/Serialization/NamingConventions/UnderscoredNamingConvention.cs create mode 100644 YamlDotNet/Serialization/NamingConventions/UnderscoredNamingConvention.cs.meta create mode 100644 YamlDotNet/Serialization/NodeDeserializers.meta create mode 100644 YamlDotNet/Serialization/NodeDeserializers/ArrayNodeDeserializer.cs create mode 100644 YamlDotNet/Serialization/NodeDeserializers/ArrayNodeDeserializer.cs.meta create mode 100644 YamlDotNet/Serialization/NodeDeserializers/CollectionNodeDeserializer.cs create mode 100644 YamlDotNet/Serialization/NodeDeserializers/CollectionNodeDeserializer.cs.meta create mode 100644 YamlDotNet/Serialization/NodeDeserializers/DictionaryNodeDeserializer.cs create mode 100644 YamlDotNet/Serialization/NodeDeserializers/DictionaryNodeDeserializer.cs.meta create mode 100644 YamlDotNet/Serialization/NodeDeserializers/EnumerableNodeDeserializer.cs create mode 100644 YamlDotNet/Serialization/NodeDeserializers/EnumerableNodeDeserializer.cs.meta create mode 100644 YamlDotNet/Serialization/NodeDeserializers/NullNodeDeserializer.cs create mode 100644 YamlDotNet/Serialization/NodeDeserializers/NullNodeDeserializer.cs.meta create mode 100644 YamlDotNet/Serialization/NodeDeserializers/ObjectNodeDeserializer.cs create mode 100644 YamlDotNet/Serialization/NodeDeserializers/ObjectNodeDeserializer.cs.meta create mode 100644 YamlDotNet/Serialization/NodeDeserializers/ScalarNodeDeserializer.cs create mode 100644 YamlDotNet/Serialization/NodeDeserializers/ScalarNodeDeserializer.cs.meta create mode 100644 YamlDotNet/Serialization/NodeDeserializers/TypeConverterNodeDeserializer.cs create mode 100644 YamlDotNet/Serialization/NodeDeserializers/TypeConverterNodeDeserializer.cs.meta create mode 100644 YamlDotNet/Serialization/NodeDeserializers/YamlConvertibleNodeDeserializer.cs create mode 100644 YamlDotNet/Serialization/NodeDeserializers/YamlConvertibleNodeDeserializer.cs.meta create mode 100644 YamlDotNet/Serialization/NodeDeserializers/YamlSerializableNodeDeserializer.cs create mode 100644 YamlDotNet/Serialization/NodeDeserializers/YamlSerializableNodeDeserializer.cs.meta create mode 100644 YamlDotNet/Serialization/NodeTypeResolvers.meta create mode 100644 YamlDotNet/Serialization/NodeTypeResolvers/DefaultContainersNodeTypeResolver.cs create mode 100644 YamlDotNet/Serialization/NodeTypeResolvers/DefaultContainersNodeTypeResolver.cs.meta create mode 100644 YamlDotNet/Serialization/NodeTypeResolvers/TagNodeTypeResolver.cs create mode 100644 YamlDotNet/Serialization/NodeTypeResolvers/TagNodeTypeResolver.cs.meta create mode 100644 YamlDotNet/Serialization/NodeTypeResolvers/TypeNameInTagNodeTypeResolver.cs create mode 100644 YamlDotNet/Serialization/NodeTypeResolvers/TypeNameInTagNodeTypeResolver.cs.meta create mode 100644 YamlDotNet/Serialization/NodeTypeResolvers/YamlConvertibleTypeResolver.cs create mode 100644 YamlDotNet/Serialization/NodeTypeResolvers/YamlConvertibleTypeResolver.cs.meta create mode 100644 YamlDotNet/Serialization/NodeTypeResolvers/YamlSerializableTypeResolver.cs create mode 100644 YamlDotNet/Serialization/NodeTypeResolvers/YamlSerializableTypeResolver.cs.meta create mode 100644 YamlDotNet/Serialization/Nothing.cs create mode 100644 YamlDotNet/Serialization/Nothing.cs.meta create mode 100644 YamlDotNet/Serialization/ObjectDescriptor.cs create mode 100644 YamlDotNet/Serialization/ObjectDescriptor.cs.meta create mode 100644 YamlDotNet/Serialization/ObjectFactories.meta create mode 100644 YamlDotNet/Serialization/ObjectFactories/DefaultObjectFactory.cs create mode 100644 YamlDotNet/Serialization/ObjectFactories/DefaultObjectFactory.cs.meta create mode 100644 YamlDotNet/Serialization/ObjectFactories/LambdaObjectFactory.cs create mode 100644 YamlDotNet/Serialization/ObjectFactories/LambdaObjectFactory.cs.meta create mode 100644 YamlDotNet/Serialization/ObjectGraphTraversalStrategies.meta create mode 100644 YamlDotNet/Serialization/ObjectGraphTraversalStrategies/FullObjectGraphTraversalStrategy.cs create mode 100644 YamlDotNet/Serialization/ObjectGraphTraversalStrategies/FullObjectGraphTraversalStrategy.cs.meta create mode 100644 YamlDotNet/Serialization/ObjectGraphTraversalStrategies/RoundtripObjectGraphTraversalStrategy.cs create mode 100644 YamlDotNet/Serialization/ObjectGraphTraversalStrategies/RoundtripObjectGraphTraversalStrategy.cs.meta create mode 100644 YamlDotNet/Serialization/ObjectGraphVisitors.meta create mode 100644 YamlDotNet/Serialization/ObjectGraphVisitors/AnchorAssigner.cs create mode 100644 YamlDotNet/Serialization/ObjectGraphVisitors/AnchorAssigner.cs.meta create mode 100644 YamlDotNet/Serialization/ObjectGraphVisitors/AnchorAssigningObjectGraphVisitor.cs create mode 100644 YamlDotNet/Serialization/ObjectGraphVisitors/AnchorAssigningObjectGraphVisitor.cs.meta create mode 100644 YamlDotNet/Serialization/ObjectGraphVisitors/ChainedObjectGraphVisitor.cs create mode 100644 YamlDotNet/Serialization/ObjectGraphVisitors/ChainedObjectGraphVisitor.cs.meta create mode 100644 YamlDotNet/Serialization/ObjectGraphVisitors/CustomSerializationObjectGraphVisitor.cs create mode 100644 YamlDotNet/Serialization/ObjectGraphVisitors/CustomSerializationObjectGraphVisitor.cs.meta create mode 100644 YamlDotNet/Serialization/ObjectGraphVisitors/DefaultExclusiveObjectGraphVisitor.cs create mode 100644 YamlDotNet/Serialization/ObjectGraphVisitors/DefaultExclusiveObjectGraphVisitor.cs.meta create mode 100644 YamlDotNet/Serialization/ObjectGraphVisitors/EmittingObjectGraphVisitor.cs create mode 100644 YamlDotNet/Serialization/ObjectGraphVisitors/EmittingObjectGraphVisitor.cs.meta create mode 100644 YamlDotNet/Serialization/ObjectGraphVisitors/PreProcessingPhaseObjectGraphVisitorSkeleton.cs create mode 100644 YamlDotNet/Serialization/ObjectGraphVisitors/PreProcessingPhaseObjectGraphVisitorSkeleton.cs.meta create mode 100644 YamlDotNet/Serialization/PropertyDescriptor.cs create mode 100644 YamlDotNet/Serialization/PropertyDescriptor.cs.meta create mode 100644 YamlDotNet/Serialization/SerializationOptions.cs create mode 100644 YamlDotNet/Serialization/SerializationOptions.cs.meta create mode 100644 YamlDotNet/Serialization/Serializer.cs create mode 100644 YamlDotNet/Serialization/Serializer.cs.meta create mode 100644 YamlDotNet/Serialization/SerializerBuilder.cs create mode 100644 YamlDotNet/Serialization/SerializerBuilder.cs.meta create mode 100644 YamlDotNet/Serialization/StreamFragment.cs create mode 100644 YamlDotNet/Serialization/StreamFragment.cs.meta create mode 100644 YamlDotNet/Serialization/TagMappings.cs create mode 100644 YamlDotNet/Serialization/TagMappings.cs.meta create mode 100644 YamlDotNet/Serialization/TypeInspectors.meta create mode 100644 YamlDotNet/Serialization/TypeInspectors/CachedTypeInspector.cs create mode 100644 YamlDotNet/Serialization/TypeInspectors/CachedTypeInspector.cs.meta create mode 100644 YamlDotNet/Serialization/TypeInspectors/NamingConventionTypeInspector.cs create mode 100644 YamlDotNet/Serialization/TypeInspectors/NamingConventionTypeInspector.cs.meta create mode 100644 YamlDotNet/Serialization/TypeInspectors/ReadableAndWritablePropertiesTypeInspector.cs create mode 100644 YamlDotNet/Serialization/TypeInspectors/ReadableAndWritablePropertiesTypeInspector.cs.meta create mode 100644 YamlDotNet/Serialization/TypeInspectors/ReadablePropertiesTypeInspector.cs create mode 100644 YamlDotNet/Serialization/TypeInspectors/ReadablePropertiesTypeInspector.cs.meta create mode 100644 YamlDotNet/Serialization/TypeInspectors/TypeInspectorSkeleton.cs create mode 100644 YamlDotNet/Serialization/TypeInspectors/TypeInspectorSkeleton.cs.meta create mode 100644 YamlDotNet/Serialization/TypeResolvers.meta create mode 100644 YamlDotNet/Serialization/TypeResolvers/DynamicTypeResolver.cs create mode 100644 YamlDotNet/Serialization/TypeResolvers/DynamicTypeResolver.cs.meta create mode 100644 YamlDotNet/Serialization/TypeResolvers/StaticTypeResolver.cs create mode 100644 YamlDotNet/Serialization/TypeResolvers/StaticTypeResolver.cs.meta create mode 100644 YamlDotNet/Serialization/Utilities.meta create mode 100644 YamlDotNet/Serialization/Utilities/IPostDeserializationCallback.cs create mode 100644 YamlDotNet/Serialization/Utilities/IPostDeserializationCallback.cs.meta create mode 100644 YamlDotNet/Serialization/Utilities/ObjectAnchorCollection.cs create mode 100644 YamlDotNet/Serialization/Utilities/ObjectAnchorCollection.cs.meta create mode 100644 YamlDotNet/Serialization/Utilities/ReflectionUtility.cs create mode 100644 YamlDotNet/Serialization/Utilities/ReflectionUtility.cs.meta create mode 100644 YamlDotNet/Serialization/Utilities/SerializerState.cs create mode 100644 YamlDotNet/Serialization/Utilities/SerializerState.cs.meta create mode 100644 YamlDotNet/Serialization/Utilities/StringExtensions.cs create mode 100644 YamlDotNet/Serialization/Utilities/StringExtensions.cs.meta create mode 100644 YamlDotNet/Serialization/Utilities/TypeConverter.cs create mode 100644 YamlDotNet/Serialization/Utilities/TypeConverter.cs.meta create mode 100644 YamlDotNet/Serialization/ValueDeserializers.meta create mode 100644 YamlDotNet/Serialization/ValueDeserializers/AliasValueDeserializer.cs create mode 100644 YamlDotNet/Serialization/ValueDeserializers/AliasValueDeserializer.cs.meta create mode 100644 YamlDotNet/Serialization/ValueDeserializers/NodeValueDeserializer.cs create mode 100644 YamlDotNet/Serialization/ValueDeserializers/NodeValueDeserializer.cs.meta create mode 100644 YamlDotNet/Serialization/YamlAttributeOverrides.cs create mode 100644 YamlDotNet/Serialization/YamlAttributeOverrides.cs.meta create mode 100644 YamlDotNet/Serialization/YamlAttributeOverridesInspector.cs create mode 100644 YamlDotNet/Serialization/YamlAttributeOverridesInspector.cs.meta create mode 100644 YamlDotNet/Serialization/YamlAttributesTypeInspector.cs create mode 100644 YamlDotNet/Serialization/YamlAttributesTypeInspector.cs.meta create mode 100644 YamlDotNet/Serialization/YamlFormatter.cs create mode 100644 YamlDotNet/Serialization/YamlFormatter.cs.meta create mode 100644 YamlDotNet/Serialization/YamlIgnoreAttribute.cs create mode 100644 YamlDotNet/Serialization/YamlIgnoreAttribute.cs.meta create mode 100644 YamlDotNet/Serialization/YamlMember.cs create mode 100644 YamlDotNet/Serialization/YamlMember.cs.meta create mode 100644 YamlDotNet/YamlDotNet.license.txt create mode 100644 YamlDotNet/YamlDotNet.license.txt.meta diff --git a/SetupMenuItem.cs b/SetupMenuItem.cs new file mode 100644 index 0000000..31236c4 --- /dev/null +++ b/SetupMenuItem.cs @@ -0,0 +1,47 @@ +using System.Collections.Generic; +using System.IO; +using UnityEditor; +using YamlDotNet.Serialization; +using YamlDotNet.Serialization.NamingConventions; + +#if UNITY_EDITOR +public static class SetupMenuItem +{ + [MenuItem("QFSW/SSIE/Setup")] + public static void Setup() + { + string text = + File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "ProjectSettings/TagManager.asset")); + text = text.Replace("%YAML 1.1", ""); + text = text.Replace("%TAG !u! tag:unity3d.com,2011:", ""); + text = text.Replace("--- !u!78 &1", ""); + var input = new StringReader(text); + + var deserializer = new DeserializerBuilder().WithNamingConvention(new CamelCaseNamingConvention()).Build(); + + var obj = deserializer.Deserialize>(input); + var tagManager = obj["TagManager"] as Dictionary; + if (tagManager != null) + { + List layers = tagManager["layers"] as List; + if (layers != null && !layers.Contains("SelectableInversion")) + { + layers.Add("SelectableInversion"); + + var serializer = new SerializerBuilder().Build(); + var yaml = serializer.Serialize(obj); + + File.WriteAllLines(Path.Combine(Directory.GetCurrentDirectory(), "ProjectSettings/TagManager.asset"), + new[] {"%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!78 &1", yaml}); + + EditorUtility.DisplayDialog("SSIE", "Layer has been added to your project.", "Okay"); + } + else + { + EditorUtility.DisplayDialog("SSIE", "Layer has already been added to your project.", "Okay"); + } + + } + } +} +#endif diff --git a/YamlDotNet/Core.meta b/YamlDotNet/Core.meta new file mode 100644 index 0000000..43b22e9 --- /dev/null +++ b/YamlDotNet/Core.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: cbe04dd6a5622cf4fb8a12e664da340d +folderAsset: yes +timeCreated: 1427145262 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/AnchorNotFoundException.cs b/YamlDotNet/Core/AnchorNotFoundException.cs new file mode 100644 index 0000000..2cd7a5f --- /dev/null +++ b/YamlDotNet/Core/AnchorNotFoundException.cs @@ -0,0 +1,68 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Runtime.Serialization; + +namespace YamlDotNet.Core +{ + /// + /// The exception that is thrown when an alias references an anchor that does not exist. + /// + [Serializable] + public class AnchorNotFoundException : YamlException + { + /// + /// Initializes a new instance of the class. + /// + public AnchorNotFoundException() + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The message. + public AnchorNotFoundException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class. + /// + public AnchorNotFoundException(Mark start, Mark end, string message) + : base(start, end, message) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The message. + /// The inner. + public AnchorNotFoundException(string message, Exception inner) + : base(message, inner) + { + } + + } +} diff --git a/YamlDotNet/Core/AnchorNotFoundException.cs.meta b/YamlDotNet/Core/AnchorNotFoundException.cs.meta new file mode 100644 index 0000000..6b50eb5 --- /dev/null +++ b/YamlDotNet/Core/AnchorNotFoundException.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: bef940054d2c25041ba1a961abae6c79 +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/CharacterAnalyzer.cs b/YamlDotNet/Core/CharacterAnalyzer.cs new file mode 100644 index 0000000..5e52a2d --- /dev/null +++ b/YamlDotNet/Core/CharacterAnalyzer.cs @@ -0,0 +1,182 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Diagnostics; +using System.Linq; + +namespace YamlDotNet.Core +{ + [Serializable] + internal class CharacterAnalyzer where TBuffer : ILookAheadBuffer + { + private readonly TBuffer buffer; + + public CharacterAnalyzer(TBuffer buffer) + { + this.buffer = buffer; + } + + public TBuffer Buffer + { + get + { + return buffer; + } + } + + public bool EndOfInput + { + get + { + return buffer.EndOfInput; + } + } + + public char Peek(int offset) + { + return buffer.Peek(offset); + } + + public void Skip(int length) + { + buffer.Skip(length); + } + + public bool IsAlphaNumericDashOrUnderscore(int offset = 0) + { + var character = buffer.Peek(offset); + return + (character >= '0' && character <= '9') || + (character >= 'A' && character <= 'Z') || + (character >= 'a' && character <= 'z') || + character == '_' || + character == '-'; + } + + public bool IsAscii(int offset = 0) + { + return buffer.Peek(offset) <= '\x7F'; + } + + public bool IsPrintable(int offset = 0) + { + var character = buffer.Peek(offset); + return + character == '\x9' || + character == '\xA' || + character == '\xD' || + (character >= '\x20' && character <= '\x7E') || + character == '\x85' || + (character >= '\xA0' && character <= '\xD7FF') || + (character >= '\xE000' && character <= '\xFFFD'); + } + + public bool IsDigit(int offset = 0) + { + var character = buffer.Peek(offset); + return character >= '0' && character <= '9'; + } + + public int AsDigit(int offset = 0) + { + return buffer.Peek(offset) - '0'; + } + + public bool IsHex(int offset) + { + var character = buffer.Peek(offset); + return + (character >= '0' && character <= '9') || + (character >= 'A' && character <= 'F') || + (character >= 'a' && character <= 'f'); + } + + public int AsHex(int offset) + { + var character = buffer.Peek(offset); + + if (character <= '9') + { + return character - '0'; + } + if (character <= 'F') + { + return character - 'A' + 10; + } + return character - 'a' + 10; + } + + public bool IsSpace(int offset = 0) + { + return Check(' ', offset); + } + + public bool IsZero(int offset = 0) + { + return Check('\0', offset); + } + + public bool IsTab(int offset = 0) + { + return Check('\t', offset); + } + + public bool IsWhite(int offset = 0) + { + return IsSpace(offset) || IsTab(offset); + } + + public bool IsBreak(int offset = 0) + { + return Check("\r\n\x85\x2028\x2029", offset); + } + + public bool IsCrLf(int offset = 0) + { + return Check('\r', offset) && Check('\n', offset + 1); + } + + public bool IsBreakOrZero(int offset = 0) + { + return IsBreak(offset) || IsZero(offset); + } + + public bool IsWhiteBreakOrZero(int offset = 0) + { + return IsWhite(offset) || IsBreakOrZero(offset); + } + + public bool Check(char expected, int offset = 0) + { + return buffer.Peek(offset) == expected; + } + + public bool Check(string expectedCharacters, int offset = 0) + { + // Todo: using it this way doesn't break anything, it's not realy wrong... + Debug.Assert(expectedCharacters.Length > 1, "Use Check(char, int) instead."); + + var character = buffer.Peek(offset); + return expectedCharacters.IndexOf(character) != -1; + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/CharacterAnalyzer.cs.meta b/YamlDotNet/Core/CharacterAnalyzer.cs.meta new file mode 100644 index 0000000..a89b5de --- /dev/null +++ b/YamlDotNet/Core/CharacterAnalyzer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: cdb65e878b6f92347849551efad9eb74 +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Constants.cs b/YamlDotNet/Core/Constants.cs new file mode 100644 index 0000000..7f03714 --- /dev/null +++ b/YamlDotNet/Core/Constants.cs @@ -0,0 +1,44 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using YamlDotNet.Core.Tokens; + +namespace YamlDotNet.Core +{ + /// + /// Defines constants thar relate to the YAML specification. + /// + internal static class Constants + { + public static readonly TagDirective[] DefaultTagDirectives = + { + new TagDirective("!", "!"), + new TagDirective("!!", "tag:yaml.org,2002:") + }; + + public const int MajorVersion = 1; + public const int MinorVersion = 1; + + public const char HandleCharacter = '!'; + public const string DefaultHandle = "!"; + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Constants.cs.meta b/YamlDotNet/Core/Constants.cs.meta new file mode 100644 index 0000000..22dd1d9 --- /dev/null +++ b/YamlDotNet/Core/Constants.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6143f3f95b0bcb74c92b9996309fab40 +timeCreated: 1427145264 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Cursor.cs b/YamlDotNet/Core/Cursor.cs new file mode 100644 index 0000000..966526e --- /dev/null +++ b/YamlDotNet/Core/Cursor.cs @@ -0,0 +1,72 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace YamlDotNet.Core +{ + [Serializable] + internal class Cursor + { + public int Index { get; set; } + public int Line { get; set; } + public int LineOffset { get; set; } + + public Cursor() + { + Line = 1; + } + + public Cursor(Cursor cursor) + { + Index = cursor.Index; + Line = cursor.Line; + LineOffset = cursor.LineOffset; + } + + public Mark Mark() + { + return new Mark(Index, Line, LineOffset + 1); + } + + public void Skip() + { + Index++; + LineOffset++; + } + + public void SkipLineByOffset(int offset) + { + Index += offset; + Line++; + LineOffset = 0; + } + + public void ForceSkipLineAfterNonBreak() + { + if (LineOffset != 0) + { + Line++; + LineOffset = 0; + } + } + } +} diff --git a/YamlDotNet/Core/Cursor.cs.meta b/YamlDotNet/Core/Cursor.cs.meta new file mode 100644 index 0000000..47cb0c6 --- /dev/null +++ b/YamlDotNet/Core/Cursor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b4262bdec0f3c254b9a29e755ba3a609 +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Emitter.cs b/YamlDotNet/Core/Emitter.cs new file mode 100644 index 0000000..d19b004 --- /dev/null +++ b/YamlDotNet/Core/Emitter.cs @@ -0,0 +1,1918 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using YamlDotNet.Core.Events; +using ParsingEvent = YamlDotNet.Core.Events.ParsingEvent; +using TagDirective = YamlDotNet.Core.Tokens.TagDirective; +using VersionDirective = YamlDotNet.Core.Tokens.VersionDirective; + +namespace YamlDotNet.Core +{ + /// + /// Emits YAML streams. + /// + public class Emitter : IEmitter + { + private const int MinBestIndent = 2; + private const int MaxBestIndent = 9; + private const int MaxAliasLength = 128; + + private static readonly Regex uriReplacer = new Regex(@"[^0-9A-Za-z_\-;?@=$~\\\)\]/:&+,\.\*\(\[!]", + StandardRegexOptions.Compiled | RegexOptions.Singleline); + + private readonly TextWriter output; + private readonly bool outputUsesUnicodeEncoding; + + private readonly bool isCanonical; + private readonly int bestIndent; + private readonly int bestWidth; + private EmitterState state; + + private readonly Stack states = new Stack(); + private readonly Queue events = new Queue(); + private readonly Stack indents = new Stack(); + private readonly TagDirectiveCollection tagDirectives = new TagDirectiveCollection(); + private int indent; + private int flowLevel; + private bool isMappingContext; + private bool isSimpleKeyContext; + private bool isRootContext; + + private int column; + private bool isWhitespace; + private bool isIndentation; + + private bool isOpenEnded; + private bool isDocumentEndWritten; + + private readonly AnchorData anchorData = new AnchorData(); + private readonly TagData tagData = new TagData(); + private readonly ScalarData scalarData = new ScalarData(); + + private class AnchorData + { + public string anchor; + public bool isAlias; + } + + private class TagData + { + public string handle; + public string suffix; + } + + private class ScalarData + { + public string value; + public bool isMultiline; + public bool isFlowPlainAllowed; + public bool isBlockPlainAllowed; + public bool isSingleQuotedAllowed; + public bool isBlockAllowed; + public bool hasSingleQuotes; + public ScalarStyle style; + } + + /// + /// Initializes a new instance of the class. + /// + /// The where the emitter will write. + public Emitter(TextWriter output) + : this(output, MinBestIndent) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The where the emitter will write. + /// The preferred indentation. + public Emitter(TextWriter output, int bestIndent) + : this(output, bestIndent, int.MaxValue) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The where the emitter will write. + /// The preferred indentation. + /// The preferred text width. + public Emitter(TextWriter output, int bestIndent, int bestWidth) + : this(output, bestIndent, bestWidth, false) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The where the emitter will write. + /// The preferred indentation. + /// The preferred text width. + /// If true, write the output in canonical form. + public Emitter(TextWriter output, int bestIndent, int bestWidth, bool isCanonical) + { + if (bestIndent < MinBestIndent || bestIndent > MaxBestIndent) + { + throw new ArgumentOutOfRangeException("bestIndent", string.Format(CultureInfo.InvariantCulture, + "The bestIndent parameter must be between {0} and {1}.", MinBestIndent, MaxBestIndent)); + } + + this.bestIndent = bestIndent; + + if (bestWidth <= bestIndent * 2) + { + throw new ArgumentOutOfRangeException("bestWidth", "The bestWidth parameter must be greater than bestIndent * 2."); + } + + this.bestWidth = bestWidth; + + this.isCanonical = isCanonical; + + this.output = output; + this.outputUsesUnicodeEncoding = IsUnicode(output.Encoding); + } + + /// + /// Emit an evt. + /// + public void Emit(ParsingEvent @event) + { + events.Enqueue(@event); + + while (!NeedMoreEvents()) + { + var current = events.Peek(); + try + { + + AnalyzeEvent(current); + StateMachine(current); + } + finally + { + // Only dequeue after calling state_machine because it checks how many events are in the queue. + // Todo: well, move into StateMachine() then + events.Dequeue(); + } + } + } + + /// + /// Check if we need to accumulate more events before emitting. + /// + /// We accumulate extra + /// - 1 event for DOCUMENT-START + /// - 2 events for SEQUENCE-START + /// - 3 events for MAPPING-START + /// + private bool NeedMoreEvents() + { + if (events.Count == 0) + { + return true; + } + + int accumulate; + switch (events.Peek().Type) + { + case EventType.DocumentStart: + accumulate = 1; + break; + + case EventType.SequenceStart: + accumulate = 2; + break; + + case EventType.MappingStart: + accumulate = 3; + break; + + default: + return false; + } + + if (events.Count > accumulate) + { + return false; + } + + var level = 0; + foreach (var evt in events) + { + switch (evt.Type) + { + case EventType.DocumentStart: + case EventType.SequenceStart: + case EventType.MappingStart: + ++level; + break; + + case EventType.DocumentEnd: + case EventType.SequenceEnd: + case EventType.MappingEnd: + --level; + break; + } + if (level == 0) + { + return false; + } + } + + return true; + } + + private void AnalyzeEvent(ParsingEvent evt) + { + anchorData.anchor = null; + tagData.handle = null; + tagData.suffix = null; + + var alias = evt as AnchorAlias; + if (alias != null) + { + AnalyzeAnchor(alias.Value, true); + return; + } + + var nodeEvent = evt as NodeEvent; + if (nodeEvent != null) + { + var scalar = evt as Scalar; + if (scalar != null) + { + AnalyzeScalar(scalar); + } + + AnalyzeAnchor(nodeEvent.Anchor, false); + + if (!string.IsNullOrEmpty(nodeEvent.Tag) && (isCanonical || nodeEvent.IsCanonical)) + { + AnalyzeTag(nodeEvent.Tag); + } + } + } + + private void AnalyzeAnchor(string anchor, bool isAlias) + { + anchorData.anchor = anchor; + anchorData.isAlias = isAlias; + } + + private void AnalyzeScalar(Scalar scalar) + { + var value = scalar.Value; + scalarData.value = value; + + if (value.Length == 0) + { + if (scalar.Tag == "tag:yaml.org,2002:null") + { + scalarData.isMultiline = false; + scalarData.isFlowPlainAllowed = false; + scalarData.isBlockPlainAllowed = true; + scalarData.isSingleQuotedAllowed = false; + scalarData.isBlockAllowed = false; + } + else + { + scalarData.isMultiline = false; + scalarData.isFlowPlainAllowed = false; + scalarData.isBlockPlainAllowed = false; + scalarData.isSingleQuotedAllowed = true; + scalarData.isBlockAllowed = false; + } + return; + } + + var flowIndicators = false; + var blockIndicators = false; + if (value.StartsWith("---", StringComparison.Ordinal) || value.StartsWith("...", StringComparison.Ordinal)) + { + flowIndicators = true; + blockIndicators = true; + } + + var buffer = new CharacterAnalyzer(new StringLookAheadBuffer(value)); + var preceededByWhitespace = true; + var followedByWhitespace = buffer.IsWhiteBreakOrZero(1); + + var leadingSpace = false; + var leadingBreak = false; + var trailingSpace = false; + var trailingBreak = false; + var leadingQuote = false; + + var breakSpace = false; + var spaceBreak = false; + var previousSpace = false; + var previousBreak = false; + + var lineBreaks = false; + + var specialCharacters = !ValueIsRepresentableInOutputEncoding(value); + var singleQuotes = false; + + var isFirst = true; + while (!buffer.EndOfInput) + { + if (isFirst) + { + if (buffer.Check(@"#,[]{}&*!|>\""%@`'")) + { + flowIndicators = true; + blockIndicators = true; + leadingQuote = buffer.Check('\''); + singleQuotes |= buffer.Check('\''); + } + + if (buffer.Check("?:")) + { + flowIndicators = true; + if (followedByWhitespace) + { + blockIndicators = true; + } + } + + if (buffer.Check('-') && followedByWhitespace) + { + flowIndicators = true; + blockIndicators = true; + } + } + else + { + if (buffer.Check(",?[]{}")) + { + flowIndicators = true; + } + + if (buffer.Check(':')) + { + flowIndicators = true; + if (followedByWhitespace) + { + blockIndicators = true; + } + } + + if (buffer.Check('#') && preceededByWhitespace) + { + flowIndicators = true; + blockIndicators = true; + } + + singleQuotes |= buffer.Check('\''); + } + + if (!specialCharacters && !buffer.IsPrintable()) + { + specialCharacters = true; + } + + if (buffer.IsBreak()) + { + lineBreaks = true; + } + + if (buffer.IsSpace()) + { + if (isFirst) + { + leadingSpace = true; + } + + if (buffer.Buffer.Position >= buffer.Buffer.Length - 1) + { + trailingSpace = true; + } + + if (previousBreak) + { + breakSpace = true; + } + + previousSpace = true; + previousBreak = false; + } + else if (buffer.IsBreak()) + { + if (isFirst) + { + leadingBreak = true; + } + + if (buffer.Buffer.Position >= buffer.Buffer.Length - 1) + { + trailingBreak = true; + } + + if (previousSpace) + { + spaceBreak = true; + } + + previousSpace = false; + previousBreak = true; + } + else + { + previousSpace = false; + previousBreak = false; + } + + preceededByWhitespace = buffer.IsWhiteBreakOrZero(); + buffer.Skip(1); + if (!buffer.EndOfInput) + { + followedByWhitespace = buffer.IsWhiteBreakOrZero(1); + } + + isFirst = false; + } + + scalarData.isFlowPlainAllowed = true; + scalarData.isBlockPlainAllowed = true; + scalarData.isSingleQuotedAllowed = true; + scalarData.isBlockAllowed = true; + + if (leadingSpace || leadingBreak || trailingSpace || trailingBreak || leadingQuote) + { + scalarData.isFlowPlainAllowed = false; + scalarData.isBlockPlainAllowed = false; + } + + if (trailingSpace) + { + scalarData.isBlockAllowed = false; + } + + if (breakSpace) + { + scalarData.isFlowPlainAllowed = false; + scalarData.isBlockPlainAllowed = false; + scalarData.isSingleQuotedAllowed = false; + } + + if (spaceBreak || specialCharacters) + { + scalarData.isFlowPlainAllowed = false; + scalarData.isBlockPlainAllowed = false; + scalarData.isSingleQuotedAllowed = false; + scalarData.isBlockAllowed = false; + } + + scalarData.isMultiline = lineBreaks; + if (lineBreaks) + { + scalarData.isFlowPlainAllowed = false; + scalarData.isBlockPlainAllowed = false; + } + + if (flowIndicators) + { + scalarData.isFlowPlainAllowed = false; + } + + if (blockIndicators) + { + scalarData.isBlockPlainAllowed = false; + } + + scalarData.hasSingleQuotes = singleQuotes; + } + + private bool ValueIsRepresentableInOutputEncoding(string value) + { + if (outputUsesUnicodeEncoding) + { + return true; + } + + try + { + var encodedBytes = output.Encoding.GetBytes(value); + var decodedString = output.Encoding.GetString(encodedBytes, 0, encodedBytes.Length); + return decodedString.Equals(value); + } + catch (EncoderFallbackException) + { + return false; + } + catch (ArgumentOutOfRangeException) + { + return false; + } + } + + private bool IsUnicode(Encoding encoding) + { + return encoding is UTF8Encoding || + encoding is UnicodeEncoding || + encoding is UTF7Encoding || + encoding is UTF8Encoding; + } + + private void AnalyzeTag(string tag) + { + tagData.handle = tag; + foreach (var tagDirective in tagDirectives) + { + if (tag.StartsWith(tagDirective.Prefix, StringComparison.Ordinal)) + { + tagData.handle = tagDirective.Handle; + tagData.suffix = tag.Substring(tagDirective.Prefix.Length); + break; + } + } + } + + private void StateMachine(ParsingEvent evt) + { + var comment = evt as Comment; + if (comment != null) + { + EmitComment(comment); + return; + } + + switch (state) + { + case EmitterState.StreamStart: + EmitStreamStart(evt); + break; + + case EmitterState.FirstDocumentStart: + EmitDocumentStart(evt, true); + break; + + case EmitterState.DocumentStart: + EmitDocumentStart(evt, false); + break; + + case EmitterState.DocumentContent: + EmitDocumentContent(evt); + break; + + case EmitterState.DocumentEnd: + EmitDocumentEnd(evt); + break; + + case EmitterState.FlowSequenceFirstItem: + EmitFlowSequenceItem(evt, true); + break; + + case EmitterState.FlowSequenceItem: + EmitFlowSequenceItem(evt, false); + break; + + case EmitterState.FlowMappingFirstKey: + EmitFlowMappingKey(evt, true); + break; + + case EmitterState.FlowMappingKey: + EmitFlowMappingKey(evt, false); + break; + + case EmitterState.FlowMappingSimpleValue: + EmitFlowMappingValue(evt, true); + break; + + case EmitterState.FlowMappingValue: + EmitFlowMappingValue(evt, false); + break; + + case EmitterState.BlockSequenceFirstItem: + EmitBlockSequenceItem(evt, true); + break; + + case EmitterState.BlockSequenceItem: + EmitBlockSequenceItem(evt, false); + break; + + case EmitterState.BlockMappingFirstKey: + EmitBlockMappingKey(evt, true); + break; + + case EmitterState.BlockMappingKey: + EmitBlockMappingKey(evt, false); + break; + + case EmitterState.BlockMappingSimpleValue: + EmitBlockMappingValue(evt, true); + break; + + case EmitterState.BlockMappingValue: + EmitBlockMappingValue(evt, false); + break; + + case EmitterState.StreamEnd: + throw new YamlException("Expected nothing after STREAM-END"); + + default: + throw new InvalidOperationException(); + } + } + + private void EmitComment(Comment comment) + { + if (comment.IsInline) + { + Write(' '); + } + else + { + WriteIndent(); + } + + Write("# "); + Write(comment.Value); + WriteBreak(); + + isIndentation = true; + } + + /// + /// Expect STREAM-START. + /// + private void EmitStreamStart(ParsingEvent evt) + { + if (!(evt is StreamStart)) + { + throw new ArgumentException("Expected STREAM-START.", "evt"); + } + + indent = -1; + column = 0; + isWhitespace = true; + isIndentation = true; + + state = EmitterState.FirstDocumentStart; + } + + /// + /// Expect DOCUMENT-START or STREAM-END. + /// + private void EmitDocumentStart(ParsingEvent evt, bool isFirst) + { + var documentStart = evt as DocumentStart; + if (documentStart != null) + { + var isImplicit = documentStart.IsImplicit && isFirst && !isCanonical; + + var documentTagDirectives = NonDefaultTagsAmong(documentStart.Tags); + + if (!isFirst && !isDocumentEndWritten && (documentStart.Version != null || documentTagDirectives.Count > 0)) + { + isDocumentEndWritten = false; + WriteIndicator("...", true, false, false); + WriteIndent(); + } + + if (documentStart.Version != null) + { + AnalyzeVersionDirective(documentStart.Version); + + isImplicit = false; + WriteIndicator("%YAML", true, false, false); + WriteIndicator(string.Format(CultureInfo.InvariantCulture, + "{0}.{1}", Constants.MajorVersion, Constants.MinorVersion), + true, false, false); + WriteIndent(); + } + + foreach (var tagDirective in documentTagDirectives) + { + AppendTagDirectiveTo(tagDirective, false, tagDirectives); + } + + foreach (var tagDirective in Constants.DefaultTagDirectives) + { + AppendTagDirectiveTo(tagDirective, true, tagDirectives); + } + + if (documentTagDirectives.Count > 0) + { + isImplicit = false; + foreach (var tagDirective in Constants.DefaultTagDirectives) + { + AppendTagDirectiveTo(tagDirective, true, documentTagDirectives); + } + + foreach (var tagDirective in documentTagDirectives) + { + WriteIndicator("%TAG", true, false, false); + WriteTagHandle(tagDirective.Handle); + WriteTagContent(tagDirective.Prefix, true); + WriteIndent(); + } + } + + if (CheckEmptyDocument()) + { + isImplicit = false; + } + + if (!isImplicit) + { + WriteIndent(); + WriteIndicator("---", true, false, false); + if (isCanonical) + { + WriteIndent(); + } + } + + state = EmitterState.DocumentContent; + } + + else if (evt is StreamEnd) + { + if (isOpenEnded) + { + WriteIndicator("...", true, false, false); + WriteIndent(); + } + + state = EmitterState.StreamEnd; + } + else + { + throw new YamlException("Expected DOCUMENT-START or STREAM-END"); + } + } + + private TagDirectiveCollection NonDefaultTagsAmong(IEnumerable tagCollection) + { + var directives = new TagDirectiveCollection(); + if (tagCollection == null) + return directives; + + foreach (var tagDirective in tagCollection) + { + AppendTagDirectiveTo(tagDirective, false, directives); + } + foreach (var tagDirective in Constants.DefaultTagDirectives) + { + directives.Remove(tagDirective); + } + return directives; + } + + // ReSharper disable UnusedParameter.Local + private void AnalyzeVersionDirective(VersionDirective versionDirective) + { + if (versionDirective.Version.Major != Constants.MajorVersion || versionDirective.Version.Minor != Constants.MinorVersion) + { + throw new YamlException("Incompatible %YAML directive"); + } + } + // ReSharper restore UnusedParameter.Local + + private static void AppendTagDirectiveTo(TagDirective value, bool allowDuplicates, TagDirectiveCollection tagDirectives) + { + if (tagDirectives.Contains(value)) + { + if (!allowDuplicates) + { + throw new YamlException("Duplicate %TAG directive."); + } + } + else + { + tagDirectives.Add(value); + } + } + + /// + /// Expect the root node. + /// + private void EmitDocumentContent(ParsingEvent evt) + { + states.Push(EmitterState.DocumentEnd); + EmitNode(evt, true, false, false); + } + + /// + /// Expect a node. + /// + private void EmitNode(ParsingEvent evt, bool isRoot, bool isMapping, bool isSimpleKey) + { + isRootContext = isRoot; + isMappingContext = isMapping; + isSimpleKeyContext = isSimpleKey; + + switch (evt.Type) + { + case EventType.Alias: + EmitAlias(); + break; + + case EventType.Scalar: + EmitScalar(evt); + break; + + case EventType.SequenceStart: + EmitSequenceStart(evt); + break; + + case EventType.MappingStart: + EmitMappingStart(evt); + break; + + default: + throw new YamlException(string.Format("Expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS, got {0}", evt.Type)); + } + } + + /// + /// Expect ALIAS. + /// + private void EmitAlias() + { + ProcessAnchor(); + state = states.Pop(); + } + + /// + /// Expect SCALAR. + /// + private void EmitScalar(ParsingEvent evt) + { + SelectScalarStyle(evt); + ProcessAnchor(); + ProcessTag(); + IncreaseIndent(true, false); + ProcessScalar(); + + indent = indents.Pop(); + state = states.Pop(); + } + + private void SelectScalarStyle(ParsingEvent evt) + { + var scalar = (Scalar)evt; + + var style = scalar.Style; + var noTag = tagData.handle == null && tagData.suffix == null; + + if (noTag && !scalar.IsPlainImplicit && !scalar.IsQuotedImplicit) + { + throw new YamlException("Neither tag nor isImplicit flags are specified."); + } + + if (style == ScalarStyle.Any) + { + style = scalarData.isMultiline ? ScalarStyle.Folded : ScalarStyle.Plain; + } + + if (isCanonical) + { + style = ScalarStyle.DoubleQuoted; + } + + if (isSimpleKeyContext && scalarData.isMultiline) + { + style = ScalarStyle.DoubleQuoted; + } + + if (style == ScalarStyle.Plain) + { + if ((flowLevel != 0 && !scalarData.isFlowPlainAllowed) || (flowLevel == 0 && !scalarData.isBlockPlainAllowed)) + { + style = (scalarData.isSingleQuotedAllowed && !scalarData.hasSingleQuotes) ? ScalarStyle.SingleQuoted : ScalarStyle.DoubleQuoted; + } + if (string.IsNullOrEmpty(scalarData.value) && (flowLevel != 0 || isSimpleKeyContext)) + { + style = ScalarStyle.SingleQuoted; + } + if (noTag && !scalar.IsPlainImplicit) + { + style = ScalarStyle.SingleQuoted; + } + } + + if (style == ScalarStyle.SingleQuoted) + { + if (!scalarData.isSingleQuotedAllowed) + { + style = ScalarStyle.DoubleQuoted; + } + } + + if (style == ScalarStyle.Literal || style == ScalarStyle.Folded) + { + if (!scalarData.isBlockAllowed || flowLevel != 0 || isSimpleKeyContext) + { + style = ScalarStyle.DoubleQuoted; + } + } + + scalarData.style = style; + } + + private void ProcessScalar() + { + switch (scalarData.style) + { + case ScalarStyle.Plain: + WritePlainScalar(scalarData.value, !isSimpleKeyContext); + break; + + case ScalarStyle.SingleQuoted: + WriteSingleQuotedScalar(scalarData.value, !isSimpleKeyContext); + break; + + case ScalarStyle.DoubleQuoted: + WriteDoubleQuotedScalar(scalarData.value, !isSimpleKeyContext); + break; + + case ScalarStyle.Literal: + WriteLiteralScalar(scalarData.value); + break; + + case ScalarStyle.Folded: + WriteFoldedScalar(scalarData.value); + break; + + default: + throw new InvalidOperationException(); + } + } + + #region Write scalar Methods + + private void WritePlainScalar(string value, bool allowBreaks) + { + if (!isWhitespace) + { + Write(' '); + } + + var previousSpace = false; + var previousBreak = false; + for (var index = 0; index < value.Length; ++index) + { + var character = value[index]; + char breakCharacter; + if (IsSpace(character)) + { + if (allowBreaks && !previousSpace && column > bestWidth && index + 1 < value.Length && value[index + 1] != ' ') + { + WriteIndent(); + } + else + { + Write(character); + } + previousSpace = true; + } + else if (IsBreak(character, out breakCharacter)) + { + if (!previousBreak && character == '\n') + { + WriteBreak(); + } + WriteBreak(breakCharacter); + isIndentation = true; + previousBreak = true; + } + else + { + if (previousBreak) + { + WriteIndent(); + } + Write(character); + isIndentation = false; + previousSpace = false; + previousBreak = false; + } + } + + isWhitespace = false; + isIndentation = false; + + if (isRootContext) + { + isOpenEnded = true; + } + } + + private void WriteSingleQuotedScalar(string value, bool allowBreaks) + { + WriteIndicator("'", true, false, false); + + var previousSpace = false; + var previousBreak = false; + + for (var index = 0; index < value.Length; ++index) + { + var character = value[index]; + char breakCharacter; + + if (character == ' ') + { + if (allowBreaks && !previousSpace && column > bestWidth && index != 0 && index + 1 < value.Length && + value[index + 1] != ' ') + { + WriteIndent(); + } + else + { + Write(character); + } + previousSpace = true; + } + else if (IsBreak(character, out breakCharacter)) + { + if (!previousBreak && character == '\n') + { + WriteBreak(); + } + WriteBreak(breakCharacter); + isIndentation = true; + previousBreak = true; + } + else + { + if (previousBreak) + { + WriteIndent(); + } + if (character == '\'') + { + Write(character); + } + Write(character); + isIndentation = false; + previousSpace = false; + previousBreak = false; + } + } + + WriteIndicator("'", false, false, false); + + isWhitespace = false; + isIndentation = false; + } + + private void WriteDoubleQuotedScalar(string value, bool allowBreaks) + { + WriteIndicator("\"", true, false, false); + + var previousSpace = false; + for (var index = 0; index < value.Length; ++index) + { + var character = value[index]; + + char breakCharacter; + if (!IsPrintable(character) || IsBreak(character, out breakCharacter) || character == '"' || character == '\\') + { + Write('\\'); + + switch (character) + { + case '\0': + Write('0'); + break; + + case '\x7': + Write('a'); + break; + + case '\x8': + Write('b'); + break; + + case '\x9': + Write('t'); + break; + + case '\xA': + Write('n'); + break; + + case '\xB': + Write('v'); + break; + + case '\xC': + Write('f'); + break; + + case '\xD': + Write('r'); + break; + + case '\x1B': + Write('e'); + break; + + case '\x22': + Write('"'); + break; + + case '\x5C': + Write('\\'); + break; + + case '\x85': + Write('N'); + break; + + case '\xA0': + Write('_'); + break; + + case '\x2028': + Write('L'); + break; + + case '\x2029': + Write('P'); + break; + + default: + var code = (ushort)character; + if (code <= 0xFF) + { + Write('x'); + Write(code.ToString("X02", CultureInfo.InvariantCulture)); + } + else if (IsHighSurrogate(character)) + { + if (index + 1 < value.Length && IsLowSurrogate(value[index + 1])) + { + Write('U'); + Write(char.ConvertToUtf32(character, value[index + 1]).ToString("X08", CultureInfo.InvariantCulture)); + index++; + } + else + { + throw new SyntaxErrorException("While writing a quoted scalar, found an orphaned high surrogate."); + } + } + else + { + Write('u'); + Write(code.ToString("X04", CultureInfo.InvariantCulture)); + } + break; + } + previousSpace = false; + } + else if (character == ' ') + { + if (allowBreaks && !previousSpace && column > bestWidth && index > 0 && index + 1 < value.Length) + { + WriteIndent(); + if (value[index + 1] == ' ') + { + Write('\\'); + } + } + else + { + Write(character); + } + previousSpace = true; + } + else + { + Write(character); + previousSpace = false; + } + } + + WriteIndicator("\"", false, false, false); + + isWhitespace = false; + isIndentation = false; + } + + private void WriteLiteralScalar(string value) + { + var previousBreak = true; + + WriteIndicator("|", true, false, false); + WriteBlockScalarHints(value); + WriteBreak(); + + isIndentation = true; + isWhitespace = true; + + for (int i = 0; i < value.Length; ++i) + { + var character = value[i]; + if (character == '\r' && (i + 1) < value.Length && value[i + 1] == '\n') + { + continue; + } + + char breakCharacter; + if (IsBreak(character, out breakCharacter)) + { + WriteBreak(breakCharacter); + isIndentation = true; + previousBreak = true; + } + else + { + if (previousBreak) + { + WriteIndent(); + } + Write(character); + isIndentation = false; + previousBreak = false; + } + } + } + + private void WriteFoldedScalar(string value) + { + var previousBreak = true; + var leadingSpaces = true; + + WriteIndicator(">", true, false, false); + WriteBlockScalarHints(value); + WriteBreak(); + + isIndentation = true; + isWhitespace = true; + + for (var i = 0; i < value.Length; ++i) + { + var character = value[i]; + char breakCharacter, ignoredBreak; + if (IsBreak(character, out breakCharacter)) + { + if (!previousBreak && !leadingSpaces && character == '\n') + { + var k = 0; + while (i + k < value.Length && IsBreak(value[i + k], out ignoredBreak)) + { + ++k; + } + if (i + k < value.Length && !(IsBlank(value[i + k]) || IsBreak(value[i + k], out ignoredBreak))) + { + WriteBreak(); + } + } + WriteBreak(breakCharacter); + isIndentation = true; + previousBreak = true; + } + else + { + if (previousBreak) + { + WriteIndent(); + leadingSpaces = IsBlank(character); + } + if (!previousBreak && character == ' ' && i + 1 < value.Length && value[i + 1] != ' ' && column > bestWidth) + { + WriteIndent(); + } + else + { + Write(character); + } + isIndentation = false; + previousBreak = false; + } + } + } + + // Todo: isn't this what CharacterAnalyser is for? + private static bool IsSpace(char character) + { + return character == ' '; + } + + private static bool IsBreak(char character, out char breakChar) + { + switch (character) + { + case '\r': + case '\n': + case '\x85': + breakChar = '\n'; + return true; + + case '\x2028': + case '\x2029': + breakChar = character; + return true; + + default: + breakChar = '\0'; + return false; + } + } + + private static bool IsBlank(char character) + { + return character == ' ' || character == '\t'; + } + + private static bool IsPrintable(char character) + { + return + character == '\x9' || + character == '\xA' || + character == '\xD' || + (character >= '\x20' && character <= '\x7E') || + character == '\x85' || + (character >= '\xA0' && character <= '\xD7FF') || + (character >= '\xE000' && character <= '\xFFFD'); + } + + private static bool IsHighSurrogate(char c) + { + return 0xD800 <= c && c <= 0xDBFF; + } + + private static bool IsLowSurrogate(char c) + { + return 0xDC00 <= c && c <= 0xDFFF; + } + + #endregion + + /// + /// Expect SEQUENCE-START. + /// + private void EmitSequenceStart(ParsingEvent evt) + { + ProcessAnchor(); + ProcessTag(); + + var sequenceStart = (SequenceStart)evt; + + if (flowLevel != 0 || isCanonical || sequenceStart.Style == SequenceStyle.Flow || CheckEmptySequence()) + { + state = EmitterState.FlowSequenceFirstItem; + } + else + { + state = EmitterState.BlockSequenceFirstItem; + } + } + + /// + /// Expect MAPPING-START. + /// + private void EmitMappingStart(ParsingEvent evt) + { + ProcessAnchor(); + ProcessTag(); + + var mappingStart = (MappingStart)evt; + + if (flowLevel != 0 || isCanonical || mappingStart.Style == MappingStyle.Flow || CheckEmptyMapping()) + { + state = EmitterState.FlowMappingFirstKey; + } + else + { + state = EmitterState.BlockMappingFirstKey; + } + } + + private void ProcessAnchor() + { + if (anchorData.anchor != null) + { + WriteIndicator(anchorData.isAlias ? "*" : "&", true, false, false); + WriteAnchor(anchorData.anchor); + } + } + + private void ProcessTag() + { + if (tagData.handle == null && tagData.suffix == null) + { + return; + } + + if (tagData.handle != null) + { + WriteTagHandle(tagData.handle); + if (tagData.suffix != null) + { + WriteTagContent(tagData.suffix, false); + } + } + else + { + WriteIndicator("!<", true, false, false); + WriteTagContent(tagData.suffix, false); + WriteIndicator(">", false, false, false); + } + } + + /// + /// Expect DOCUMENT-END. + /// + private void EmitDocumentEnd(ParsingEvent evt) + { + var documentEnd = evt as DocumentEnd; + if (documentEnd != null) + { + WriteIndent(); + if (!documentEnd.IsImplicit) + { + WriteIndicator("...", true, false, false); + WriteIndent(); + isDocumentEndWritten = true; + } + + state = EmitterState.DocumentStart; + + tagDirectives.Clear(); + } + else + { + throw new YamlException("Expected DOCUMENT-END."); + } + } + + /// + /// Expect a flow item node. + /// + private void EmitFlowSequenceItem(ParsingEvent evt, bool isFirst) + { + if (isFirst) + { + WriteIndicator("[", true, true, false); + IncreaseIndent(true, false); + ++flowLevel; + } + + if (evt is SequenceEnd) + { + --flowLevel; + indent = indents.Pop(); + if (isCanonical && !isFirst) + { + WriteIndicator(",", false, false, false); + WriteIndent(); + } + WriteIndicator("]", false, false, false); + state = states.Pop(); + return; + } + + if (!isFirst) + { + WriteIndicator(",", false, false, false); + } + + if (isCanonical || column > bestWidth) + { + WriteIndent(); + } + + states.Push(EmitterState.FlowSequenceItem); + + EmitNode(evt, false, false, false); + } + + /// + /// Expect a flow key node. + /// + private void EmitFlowMappingKey(ParsingEvent evt, bool isFirst) + { + if (isFirst) + { + WriteIndicator("{", true, true, false); + IncreaseIndent(true, false); + ++flowLevel; + } + + if (evt is MappingEnd) + { + --flowLevel; + indent = indents.Pop(); + if (isCanonical && !isFirst) + { + WriteIndicator(",", false, false, false); + WriteIndent(); + } + WriteIndicator("}", false, false, false); + state = states.Pop(); + return; + } + + if (!isFirst) + { + WriteIndicator(",", false, false, false); + } + if (isCanonical || column > bestWidth) + { + WriteIndent(); + } + + if (!isCanonical && CheckSimpleKey()) + { + states.Push(EmitterState.FlowMappingSimpleValue); + EmitNode(evt, false, true, true); + } + else + { + WriteIndicator("?", true, false, false); + states.Push(EmitterState.FlowMappingValue); + EmitNode(evt, false, true, false); + } + } + + /// + /// Expect a flow value node. + /// + private void EmitFlowMappingValue(ParsingEvent evt, bool isSimple) + { + if (isSimple) + { + WriteIndicator(":", false, false, false); + } + else + { + if (isCanonical || column > bestWidth) + { + WriteIndent(); + } + WriteIndicator(":", true, false, false); + } + states.Push(EmitterState.FlowMappingKey); + EmitNode(evt, false, true, false); + } + + /// + /// Expect a block item node. + /// + private void EmitBlockSequenceItem(ParsingEvent evt, bool isFirst) + { + if (isFirst) + { + IncreaseIndent(false, (isMappingContext && !isIndentation)); + } + + if (evt is SequenceEnd) + { + indent = indents.Pop(); + state = states.Pop(); + return; + } + + WriteIndent(); + WriteIndicator("-", true, false, true); + states.Push(EmitterState.BlockSequenceItem); + + EmitNode(evt, false, false, false); + } + + /// + /// Expect a block key node. + /// + private void EmitBlockMappingKey(ParsingEvent evt, bool isFirst) + { + if (isFirst) + { + IncreaseIndent(false, false); + } + + if (evt is MappingEnd) + { + indent = indents.Pop(); + state = states.Pop(); + return; + } + + WriteIndent(); + + if (CheckSimpleKey()) + { + states.Push(EmitterState.BlockMappingSimpleValue); + EmitNode(evt, false, true, true); + } + else + { + WriteIndicator("?", true, false, true); + states.Push(EmitterState.BlockMappingValue); + EmitNode(evt, false, true, false); + } + } + + /// + /// Expect a block value node. + /// + private void EmitBlockMappingValue(ParsingEvent evt, bool isSimple) + { + if (isSimple) + { + WriteIndicator(":", false, false, false); + } + else + { + WriteIndent(); + WriteIndicator(":", true, false, true); + } + states.Push(EmitterState.BlockMappingKey); + EmitNode(evt, false, true, false); + } + + private void IncreaseIndent(bool isFlow, bool isIndentless) + { + indents.Push(indent); + + if (indent < 0) + { + indent = isFlow ? bestIndent : 0; + } + else if (!isIndentless) + { + indent += bestIndent; + } + } + + #region Check Methods + + /// + /// Check if the document content is an empty scalar. + /// + private bool CheckEmptyDocument() + { + var index = 0; + foreach (var parsingEvent in events) + { + index++; + if (index == 2) + { + var scalar = parsingEvent as Scalar; + if (scalar != null) + { + return string.IsNullOrEmpty(scalar.Value); + } + break; + } + } + + return false; + } + + /// + /// Check if the next node can be expressed as a simple key. + /// + private bool CheckSimpleKey() + { + if (events.Count < 1) + { + return false; + } + + int length; + switch (events.Peek().Type) + { + case EventType.Alias: + length = SafeStringLength(anchorData.anchor); + break; + + case EventType.Scalar: + if (scalarData.isMultiline) + { + return false; + } + + length = + SafeStringLength(anchorData.anchor) + + SafeStringLength(tagData.handle) + + SafeStringLength(tagData.suffix) + + SafeStringLength(scalarData.value); + break; + + case EventType.SequenceStart: + if (!CheckEmptySequence()) + { + return false; + } + length = + SafeStringLength(anchorData.anchor) + + SafeStringLength(tagData.handle) + + SafeStringLength(tagData.suffix); + break; + + case EventType.MappingStart: + if (!CheckEmptySequence()) + { + return false; + } + length = + SafeStringLength(anchorData.anchor) + + SafeStringLength(tagData.handle) + + SafeStringLength(tagData.suffix); + break; + + default: + return false; + } + + return length <= MaxAliasLength; + } + + private int SafeStringLength(string value) + { + return value == null ? 0 : value.Length; + } + + private bool CheckEmptySequence() + { + if (events.Count < 2) + { + return false; + } + + // Todo: must be something better than this FakeList + var eventList = new FakeList(events); + return eventList[0] is SequenceStart && eventList[1] is SequenceEnd; + } + + private bool CheckEmptyMapping() + { + if (events.Count < 2) + { + return false; + } + + // Todo: must be something better than this FakeList + var eventList = new FakeList(events); + return eventList[0] is MappingStart && eventList[1] is MappingEnd; + } + + #endregion + + #region Write Methods + + private void WriteBlockScalarHints(string value) + { + var analyzer = new CharacterAnalyzer(new StringLookAheadBuffer(value)); + + if (analyzer.IsSpace() || analyzer.IsBreak()) + { + var indentHint = string.Format(CultureInfo.InvariantCulture, "{0}", bestIndent); + WriteIndicator(indentHint, false, false, false); + } + + isOpenEnded = false; + + string chompHint = null; + if (value.Length == 0 || !analyzer.IsBreak(value.Length - 1)) + { + chompHint = "-"; + } + else if (value.Length >= 2 && analyzer.IsBreak(value.Length - 2)) + { + chompHint = "+"; + isOpenEnded = true; + } + + if (chompHint != null) + { + WriteIndicator(chompHint, false, false, false); + } + } + + private void WriteIndicator(string indicator, bool needWhitespace, bool whitespace, bool indentation) + { + if (needWhitespace && !isWhitespace) + { + Write(' '); + } + + Write(indicator); + + isWhitespace = whitespace; + isIndentation &= indentation; + isOpenEnded = false; + } + + private void WriteIndent() + { + var currentIndent = Math.Max(indent, 0); + + if (!isIndentation || column > currentIndent || (column == currentIndent && !isWhitespace)) + { + WriteBreak(); + } + + while (column < currentIndent) + { + Write(' '); + } + + isWhitespace = true; + isIndentation = true; + } + + private void WriteAnchor(string value) + { + Write(value); + + isWhitespace = false; + isIndentation = false; + } + + private void WriteTagHandle(string value) + { + if (!isWhitespace) + { + Write(' '); + } + + Write(value); + + isWhitespace = false; + isIndentation = false; + } + + private void WriteTagContent(string value, bool needsWhitespace) + { + if (needsWhitespace && !isWhitespace) + { + Write(' '); + } + + Write(UrlEncode(value)); + + isWhitespace = false; + isIndentation = false; + } + + private string UrlEncode(string text) + { + return uriReplacer.Replace(text, delegate (Match match) + { + var buffer = new StringBuilder(); + foreach (var toEncode in Encoding.UTF8.GetBytes(match.Value)) + { + buffer.AppendFormat("%{0:X02}", toEncode); + } + return buffer.ToString(); + }); + } + + private void Write(char value) + { + output.Write(value); + ++column; + } + + private void Write(string value) + { + output.Write(value); + column += value.Length; + } + + private void WriteBreak(char breakCharacter = '\n') + { + if (breakCharacter == '\n') + { + output.WriteLine(); + } + else + { + output.Write(breakCharacter); + } + column = 0; + } + + #endregion + } +} diff --git a/YamlDotNet/Core/Emitter.cs.meta b/YamlDotNet/Core/Emitter.cs.meta new file mode 100644 index 0000000..f08bcf6 --- /dev/null +++ b/YamlDotNet/Core/Emitter.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f526134efcd8e424c86e492f85fc56ba +timeCreated: 1427145267 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/EmitterState.cs b/YamlDotNet/Core/EmitterState.cs new file mode 100644 index 0000000..84c1c18 --- /dev/null +++ b/YamlDotNet/Core/EmitterState.cs @@ -0,0 +1,45 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +namespace YamlDotNet.Core +{ + internal enum EmitterState + { + StreamStart, + StreamEnd, + FirstDocumentStart, + DocumentStart, + DocumentContent, + DocumentEnd, + FlowSequenceFirstItem, + FlowSequenceItem, + FlowMappingFirstKey, + FlowMappingKey, + FlowMappingSimpleValue, + FlowMappingValue, + BlockSequenceFirstItem, + BlockSequenceItem, + BlockMappingFirstKey, + BlockMappingKey, + BlockMappingSimpleValue, + BlockMappingValue + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/EmitterState.cs.meta b/YamlDotNet/Core/EmitterState.cs.meta new file mode 100644 index 0000000..e166772 --- /dev/null +++ b/YamlDotNet/Core/EmitterState.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 7127212075b19ce4f99a370f02d26037 +timeCreated: 1427145264 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Events.meta b/YamlDotNet/Core/Events.meta new file mode 100644 index 0000000..a8f34b4 --- /dev/null +++ b/YamlDotNet/Core/Events.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 2dd1df9756078164587ab6fc3579145d +folderAsset: yes +timeCreated: 1427145262 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Events/AnchorAlias.cs b/YamlDotNet/Core/Events/AnchorAlias.cs new file mode 100644 index 0000000..67ac9f5 --- /dev/null +++ b/YamlDotNet/Core/Events/AnchorAlias.cs @@ -0,0 +1,106 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System.Globalization; + +namespace YamlDotNet.Core.Events +{ + /// + /// Represents an alias event. + /// + public class AnchorAlias : ParsingEvent + { + /// + /// Gets the event type, which allows for simpler type comparisons. + /// + internal override EventType Type + { + get + { + return EventType.Alias; + } + } + + private readonly string value; + + /// + /// Gets the value of the alias. + /// + public string Value + { + get + { + return value; + } + } + + /// + /// Initializes a new instance of the class. + /// + /// The value of the alias. + /// The start position of the event. + /// The end position of the event. + public AnchorAlias(string value, Mark start, Mark end) + : base(start, end) + { + if (string.IsNullOrEmpty(value)) + { + throw new YamlException(start, end, "Anchor value must not be empty."); + } + + if (!NodeEvent.anchorValidator.IsMatch(value)) + { + throw new YamlException(start, end, "Anchor value must contain alphanumerical characters only."); + } + + this.value = value; + } + + /// + /// Initializes a new instance of the class. + /// + /// The value of the alias. + public AnchorAlias(string value) + : this(value, Mark.Empty, Mark.Empty) + { + } + + /// + /// Returns a that represents the current . + /// + /// + /// A that represents the current . + /// + public override string ToString() + { + return string.Format(CultureInfo.InvariantCulture, "Alias [value = {0}]", value); + } + + /// + /// Invokes run-time type specific Visit() method of the specified visitor. + /// + /// visitor, may not be null. + public override void Accept(IParsingEventVisitor visitor) + { + visitor.Visit(this); + } + } +} diff --git a/YamlDotNet/Core/Events/AnchorAlias.cs.meta b/YamlDotNet/Core/Events/AnchorAlias.cs.meta new file mode 100644 index 0000000..861492d --- /dev/null +++ b/YamlDotNet/Core/Events/AnchorAlias.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 09b29b54793d9644398fe8e4da326353 +timeCreated: 1427145262 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Events/Comment.cs b/YamlDotNet/Core/Events/Comment.cs new file mode 100644 index 0000000..2c27a5a --- /dev/null +++ b/YamlDotNet/Core/Events/Comment.cs @@ -0,0 +1,52 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + + +namespace YamlDotNet.Core.Events +{ + public class Comment : ParsingEvent + { + public string Value { get; private set; } + public bool IsInline { get; private set; } + + public Comment(string value, bool isInline) + : this(value, isInline, Mark.Empty, Mark.Empty) + { + } + + public Comment(string value, bool isInline, Mark start, Mark end) + : base(start, end) + { + Value = value; + IsInline = isInline; + } + + internal override EventType Type + { + get { return EventType.Comment; } + } + + public override void Accept(IParsingEventVisitor visitor) + { + visitor.Visit(this); + } + } +} diff --git a/YamlDotNet/Core/Events/Comment.cs.meta b/YamlDotNet/Core/Events/Comment.cs.meta new file mode 100644 index 0000000..6c0e75c --- /dev/null +++ b/YamlDotNet/Core/Events/Comment.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: e96511072ac5a30488623987ca605570 +timeCreated: 1427145267 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Events/DocumentEnd.cs b/YamlDotNet/Core/Events/DocumentEnd.cs new file mode 100644 index 0000000..7f75d24 --- /dev/null +++ b/YamlDotNet/Core/Events/DocumentEnd.cs @@ -0,0 +1,116 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System.Globalization; + +namespace YamlDotNet.Core.Events +{ + /// + /// Represents a document end event. + /// + public class DocumentEnd : ParsingEvent + { + /// + /// Gets a value indicating the variation of depth caused by this event. + /// The value can be either -1, 0 or 1. For start events, it will be 1, + /// for end events, it will be -1, and for the remaining events, it will be 0. + /// + public override int NestingIncrease + { + get + { + return -1; + } + } + + /// + /// Gets the event type, which allows for simpler type comparisons. + /// + internal override EventType Type + { + get + { + return EventType.DocumentEnd; + } + } + + private readonly bool isImplicit; + + /// + /// Gets a value indicating whether this instance is implicit. + /// + /// + /// true if this instance is implicit; otherwise, false. + /// + public bool IsImplicit + { + get + { + return isImplicit; + } + } + + /// + /// Initializes a new instance of the class. + /// + /// Indicates whether the event is implicit. + /// The start position of the event. + /// The end position of the event. + public DocumentEnd(bool isImplicit, Mark start, Mark end) + : base(start, end) + { + this.isImplicit = isImplicit; + } + + /// + /// Initializes a new instance of the class. + /// + /// Indicates whether the event is implicit. + public DocumentEnd(bool isImplicit) + : this(isImplicit, Mark.Empty, Mark.Empty) + { + } + + /// + /// Returns a that represents the current . + /// + /// + /// A that represents the current . + /// + public override string ToString() + { + return string.Format( + CultureInfo.InvariantCulture, + "Document end [isImplicit = {0}]", + isImplicit + ); + } + + /// + /// Invokes run-time type specific Visit() method of the specified visitor. + /// + /// visitor, may not be null. + public override void Accept(IParsingEventVisitor visitor) + { + visitor.Visit(this); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Events/DocumentEnd.cs.meta b/YamlDotNet/Core/Events/DocumentEnd.cs.meta new file mode 100644 index 0000000..700d967 --- /dev/null +++ b/YamlDotNet/Core/Events/DocumentEnd.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 99b4ea3b75d2e754cb5fea7cc0f1a4d3 +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Events/DocumentStart.cs b/YamlDotNet/Core/Events/DocumentStart.cs new file mode 100644 index 0000000..ce04401 --- /dev/null +++ b/YamlDotNet/Core/Events/DocumentStart.cs @@ -0,0 +1,168 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System.Globalization; +using YamlDotNet.Core.Tokens; + +namespace YamlDotNet.Core.Events +{ + /// + /// Represents a document start event. + /// + public class DocumentStart : ParsingEvent + { + /// + /// Gets a value indicating the variation of depth caused by this event. + /// The value can be either -1, 0 or 1. For start events, it will be 1, + /// for end events, it will be -1, and for the remaining events, it will be 0. + /// + public override int NestingIncrease + { + get + { + return 1; + } + } + + /// + /// Gets the event type, which allows for simpler type comparisons. + /// + internal override EventType Type + { + get + { + return EventType.DocumentStart; + } + } + + private readonly TagDirectiveCollection tags; + private readonly VersionDirective version; + + /// + /// Gets the tags. + /// + /// The tags. + public TagDirectiveCollection Tags + { + get + { + return tags; + } + } + + /// + /// Gets the version. + /// + /// The version. + public VersionDirective Version + { + get + { + return version; + } + } + + private readonly bool isImplicit; + + /// + /// Gets a value indicating whether this instance is implicit. + /// + /// + /// true if this instance is implicit; otherwise, false. + /// + public bool IsImplicit + { + get + { + return isImplicit; + } + } + + /// + /// Initializes a new instance of the class. + /// + /// The version. + /// The tags. + /// Indicates whether the event is implicit. + /// The start position of the event. + /// The end position of the event. + public DocumentStart(VersionDirective version, TagDirectiveCollection tags, bool isImplicit, Mark start, Mark end) + : base(start, end) + { + this.version = version; + this.tags = tags; + this.isImplicit = isImplicit; + } + + /// + /// Initializes a new instance of the class. + /// + /// The version. + /// The tags. + /// Indicates whether the event is implicit. + public DocumentStart(VersionDirective version, TagDirectiveCollection tags, bool isImplicit) + : this(version, tags, isImplicit, Mark.Empty, Mark.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The start position of the event. + /// The end position of the event. + public DocumentStart(Mark start, Mark end) + : this(null, null, true, start, end) + { + } + + /// + /// Initializes a new instance of the class. + /// + public DocumentStart() + : this(null, null, true, Mark.Empty, Mark.Empty) + { + } + + /// + /// Returns a that represents the current . + /// + /// + /// A that represents the current . + /// + public override string ToString() + { + return string.Format( + CultureInfo.InvariantCulture, + "Document start [isImplicit = {0}]", + isImplicit + ); + } + + /// + /// Invokes run-time type specific Visit() method of the specified visitor. + /// + /// visitor, may not be null. + public override void Accept(IParsingEventVisitor visitor) + { + visitor.Visit(this); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Events/DocumentStart.cs.meta b/YamlDotNet/Core/Events/DocumentStart.cs.meta new file mode 100644 index 0000000..731c733 --- /dev/null +++ b/YamlDotNet/Core/Events/DocumentStart.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 06cc13f1bc1622246924546d044eede9 +timeCreated: 1427145262 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Events/EventType.cs b/YamlDotNet/Core/Events/EventType.cs new file mode 100644 index 0000000..7d28df7 --- /dev/null +++ b/YamlDotNet/Core/Events/EventType.cs @@ -0,0 +1,39 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +namespace YamlDotNet.Core.Events +{ + internal enum EventType + { + None, + StreamStart, + StreamEnd, + DocumentStart, + DocumentEnd, + Alias, + Scalar, + SequenceStart, + SequenceEnd, + MappingStart, + MappingEnd, + Comment, + } +} diff --git a/YamlDotNet/Core/Events/EventType.cs.meta b/YamlDotNet/Core/Events/EventType.cs.meta new file mode 100644 index 0000000..835b42d --- /dev/null +++ b/YamlDotNet/Core/Events/EventType.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 3a7e249b62575e048929c7a3e0420470 +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Events/IParsingEventVisitor.cs b/YamlDotNet/Core/Events/IParsingEventVisitor.cs new file mode 100644 index 0000000..c80a4a6 --- /dev/null +++ b/YamlDotNet/Core/Events/IParsingEventVisitor.cs @@ -0,0 +1,42 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) 2014 Leon Mlakar +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +namespace YamlDotNet.Core.Events +{ + /// + /// Callback interface for external event Visitor. + /// + public interface IParsingEventVisitor + { + void Visit(AnchorAlias e); + void Visit(StreamStart e); + void Visit(StreamEnd e); + void Visit(DocumentStart e); + void Visit(DocumentEnd e); + void Visit(Scalar e); + void Visit(SequenceStart e); + void Visit(SequenceEnd e); + void Visit(MappingStart e); + void Visit(MappingEnd e); + void Visit(Comment e); + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Events/IParsingEventVisitor.cs.meta b/YamlDotNet/Core/Events/IParsingEventVisitor.cs.meta new file mode 100644 index 0000000..6f55079 --- /dev/null +++ b/YamlDotNet/Core/Events/IParsingEventVisitor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 34cdef8e5d4918149bf7185da865504b +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Events/MappingEnd.cs b/YamlDotNet/Core/Events/MappingEnd.cs new file mode 100644 index 0000000..f2c25fb --- /dev/null +++ b/YamlDotNet/Core/Events/MappingEnd.cs @@ -0,0 +1,91 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +namespace YamlDotNet.Core.Events +{ + /// + /// Represents a mapping end event. + /// + public class MappingEnd : ParsingEvent + { + /// + /// Gets a value indicating the variation of depth caused by this event. + /// The value can be either -1, 0 or 1. For start events, it will be 1, + /// for end events, it will be -1, and for the remaining events, it will be 0. + /// + public override int NestingIncrease + { + get + { + return -1; + } + } + + /// + /// Gets the event type, which allows for simpler type comparisons. + /// + internal override EventType Type + { + get + { + return EventType.MappingEnd; + } + } + + /// + /// Initializes a new instance of the class. + /// + /// The start position of the event. + /// The end position of the event. + public MappingEnd(Mark start, Mark end) + : base(start, end) + { + } + + /// + /// Initializes a new instance of the class. + /// + public MappingEnd() + : this(Mark.Empty, Mark.Empty) + { + } + + /// + /// Returns a that represents the current . + /// + /// + /// A that represents the current . + /// + public override string ToString() + { + return "Mapping end"; + } + + /// + /// Invokes run-time type specific Visit() method of the specified visitor. + /// + /// visitor, may not be null. + public override void Accept(IParsingEventVisitor visitor) + { + visitor.Visit(this); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Events/MappingEnd.cs.meta b/YamlDotNet/Core/Events/MappingEnd.cs.meta new file mode 100644 index 0000000..b2d10bf --- /dev/null +++ b/YamlDotNet/Core/Events/MappingEnd.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 32f12dd96a8cb4d4792ed76749f67b38 +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Events/MappingStart.cs b/YamlDotNet/Core/Events/MappingStart.cs new file mode 100644 index 0000000..a94f55d --- /dev/null +++ b/YamlDotNet/Core/Events/MappingStart.cs @@ -0,0 +1,159 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System.Globalization; + +namespace YamlDotNet.Core.Events +{ + /// + /// Represents a mapping start event. + /// + public class MappingStart : NodeEvent + { + /// + /// Gets a value indicating the variation of depth caused by this event. + /// The value can be either -1, 0 or 1. For start events, it will be 1, + /// for end events, it will be -1, and for the remaining events, it will be 0. + /// + public override int NestingIncrease + { + get + { + return 1; + } + } + + /// + /// Gets the event type, which allows for simpler type comparisons. + /// + internal override EventType Type + { + get + { + return EventType.MappingStart; + } + } + + private readonly bool isImplicit; + + /// + /// Gets a value indicating whether this instance is implicit. + /// + /// + /// true if this instance is implicit; otherwise, false. + /// + public bool IsImplicit + { + get + { + return isImplicit; + } + } + + /// + /// Gets a value indicating whether this instance is canonical. + /// + /// + public override bool IsCanonical + { + get + { + return !isImplicit; + } + } + + private readonly MappingStyle style; + + /// + /// Gets the style of the mapping. + /// + public MappingStyle Style + { + get + { + return style; + } + } + + /// + /// Initializes a new instance of the class. + /// + /// The anchor. + /// The tag. + /// Indicates whether the event is implicit. + /// The style of the mapping. + /// The start position of the event. + /// The end position of the event. + public MappingStart(string anchor, string tag, bool isImplicit, MappingStyle style, Mark start, Mark end) + : base(anchor, tag, start, end) + { + this.isImplicit = isImplicit; + this.style = style; + } + + /// + /// Initializes a new instance of the class. + /// + /// The anchor. + /// The tag. + /// Indicates whether the event is implicit. + /// The style of the mapping. + public MappingStart(string anchor, string tag, bool isImplicit, MappingStyle style) + : this(anchor, tag, isImplicit, style, Mark.Empty, Mark.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + public MappingStart() + : this(null, null, true, MappingStyle.Any, Mark.Empty, Mark.Empty) + { + } + + /// + /// Returns a that represents the current . + /// + /// + /// A that represents the current . + /// + public override string ToString() + { + return string.Format( + CultureInfo.InvariantCulture, + "Mapping start [anchor = {0}, tag = {1}, isImplicit = {2}, style = {3}]", + Anchor, + Tag, + isImplicit, + style + ); + } + + /// + /// Invokes run-time type specific Visit() method of the specified visitor. + /// + /// visitor, may not be null. + public override void Accept(IParsingEventVisitor visitor) + { + visitor.Visit(this); + } + } +} diff --git a/YamlDotNet/Core/Events/MappingStart.cs.meta b/YamlDotNet/Core/Events/MappingStart.cs.meta new file mode 100644 index 0000000..a018077 --- /dev/null +++ b/YamlDotNet/Core/Events/MappingStart.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 79e25e33bd9642a4ca1c8c5280b30984 +timeCreated: 1427145264 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Events/MappingStyle.cs b/YamlDotNet/Core/Events/MappingStyle.cs new file mode 100644 index 0000000..bb492c4 --- /dev/null +++ b/YamlDotNet/Core/Events/MappingStyle.cs @@ -0,0 +1,44 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +namespace YamlDotNet.Core.Events +{ + /// + /// Specifies the style of a mapping. + /// + public enum MappingStyle + { + /// + /// Let the emitter choose the style. + /// + Any, + + /// + /// The block mapping style. + /// + Block, + + /// + /// The flow mapping style. + /// + Flow + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Events/MappingStyle.cs.meta b/YamlDotNet/Core/Events/MappingStyle.cs.meta new file mode 100644 index 0000000..cbab46f --- /dev/null +++ b/YamlDotNet/Core/Events/MappingStyle.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 7bc885bebca1fac428d7482f06b4f41e +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Events/NodeEvent.cs b/YamlDotNet/Core/Events/NodeEvent.cs new file mode 100644 index 0000000..0399031 --- /dev/null +++ b/YamlDotNet/Core/Events/NodeEvent.cs @@ -0,0 +1,111 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Text.RegularExpressions; + +namespace YamlDotNet.Core.Events +{ + /// + /// Contains the behavior that is common between node events. + /// + public abstract class NodeEvent : ParsingEvent + { + internal static readonly Regex anchorValidator = new Regex(@"^[0-9a-zA-Z_\-]+$", StandardRegexOptions.Compiled); + + private readonly string anchor; + + /// + /// Gets the anchor. + /// + /// + public string Anchor + { + get + { + return anchor; + } + } + + private readonly string tag; + + /// + /// Gets the tag. + /// + /// + public string Tag + { + get + { + return tag; + } + } + + /// + /// Gets a value indicating whether this instance is canonical. + /// + /// + public abstract bool IsCanonical + { + get; + } + + /// + /// Initializes a new instance of the class. + /// + /// The anchor. + /// The tag. + /// The start position of the event. + /// The end position of the event. + protected NodeEvent(string anchor, string tag, Mark start, Mark end) + : base(start, end) + { + if (anchor != null) + { + if (anchor.Length == 0) + { + throw new ArgumentException("Anchor value must not be empty.", "anchor"); + } + + if (!anchorValidator.IsMatch(anchor)) + { + throw new ArgumentException("Anchor value must contain alphanumerical characters only.", "anchor"); + } + } + + if (tag != null && tag.Length == 0) + { + throw new ArgumentException("Tag value must not be empty.", "tag"); + } + + this.anchor = anchor; + this.tag = tag; + } + + /// + /// Initializes a new instance of the class. + /// + protected NodeEvent(string anchor, string tag) + : this(anchor, tag, Mark.Empty, Mark.Empty) + { + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Events/NodeEvent.cs.meta b/YamlDotNet/Core/Events/NodeEvent.cs.meta new file mode 100644 index 0000000..ff67e3b --- /dev/null +++ b/YamlDotNet/Core/Events/NodeEvent.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 4fa0681239f68a3468223fe925e01d33 +timeCreated: 1427145264 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Events/ParsingEvent.cs b/YamlDotNet/Core/Events/ParsingEvent.cs new file mode 100644 index 0000000..c606b15 --- /dev/null +++ b/YamlDotNet/Core/Events/ParsingEvent.cs @@ -0,0 +1,90 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +namespace YamlDotNet.Core.Events +{ + /// + /// Base class for parsing events. + /// + public abstract class ParsingEvent + { + /// + /// Gets a value indicating the variation of depth caused by this event. + /// The value can be either -1, 0 or 1. For start events, it will be 1, + /// for end events, it will be -1, and for the remaining events, it will be 0. + /// + public virtual int NestingIncrease + { + get { return 0; } + } + + /// + /// Gets the event type, which allows for simpler type comparisons. + /// + internal abstract EventType Type + { + get; + } + + private readonly Mark start; + + /// + /// Gets the position in the input stream where the event starts. + /// + public Mark Start + { + get + { + return start; + } + } + + private readonly Mark end; + + /// + /// Gets the position in the input stream where the event ends. + /// + public Mark End + { + get + { + return end; + } + } + + /// + /// Accepts the specified visitor. + /// + /// Visitor to accept, may not be null + public abstract void Accept(IParsingEventVisitor visitor); + + /// + /// Initializes a new instance of the class. + /// + /// The start position of the event. + /// The end position of the event. + internal ParsingEvent(Mark start, Mark end) + { + this.start = start; + this.end = end; + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Events/ParsingEvent.cs.meta b/YamlDotNet/Core/Events/ParsingEvent.cs.meta new file mode 100644 index 0000000..b6dc77a --- /dev/null +++ b/YamlDotNet/Core/Events/ParsingEvent.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 5dcecbbabc813c74bb16837d87a36f7e +timeCreated: 1427145264 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Events/Scalar.cs b/YamlDotNet/Core/Events/Scalar.cs new file mode 100644 index 0000000..43ceeee --- /dev/null +++ b/YamlDotNet/Core/Events/Scalar.cs @@ -0,0 +1,198 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System.Globalization; + +namespace YamlDotNet.Core.Events +{ + /// + /// Represents a scalar event. + /// + public class Scalar : NodeEvent + { + /// + /// Gets the event type, which allows for simpler type comparisons. + /// + internal override EventType Type + { + get + { + return EventType.Scalar; + } + } + + private readonly string value; + + /// + /// Gets the value. + /// + /// The value. + public string Value + { + get + { + return value; + } + } + + private readonly ScalarStyle style; + + /// + /// Gets the style of the scalar. + /// + /// The style. + public ScalarStyle Style + { + get + { + return style; + } + } + + private readonly bool isPlainImplicit; + + /// + /// Gets a value indicating whether the tag is optional for the plain style. + /// + public bool IsPlainImplicit + { + get + { + return isPlainImplicit; + } + } + + private readonly bool isQuotedImplicit; + + /// + /// Gets a value indicating whether the tag is optional for any non-plain style. + /// + public bool IsQuotedImplicit + { + get + { + return isQuotedImplicit; + } + } + + /// + /// Gets a value indicating whether this instance is canonical. + /// + /// + public override bool IsCanonical + { + get + { + return !isPlainImplicit && !isQuotedImplicit; + } + } + + /// + /// Initializes a new instance of the class. + /// + /// The anchor. + /// The tag. + /// The value. + /// The style. + /// . + /// . + /// The start position of the event. + /// The end position of the event. + public Scalar(string anchor, string tag, string value, ScalarStyle style, bool isPlainImplicit, bool isQuotedImplicit, Mark start, Mark end) + : base(anchor, tag, start, end) + { + this.value = value; + this.style = style; + this.isPlainImplicit = isPlainImplicit; + this.isQuotedImplicit = isQuotedImplicit; + } + + /// + /// Initializes a new instance of the class. + /// + /// The anchor. + /// The tag. + /// The value. + /// The style. + /// . + /// . + public Scalar(string anchor, string tag, string value, ScalarStyle style, bool isPlainImplicit, bool isQuotedImplicit) + : this(anchor, tag, value, style, isPlainImplicit, isQuotedImplicit, Mark.Empty, Mark.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The value. + public Scalar(string value) + : this(null, null, value, ScalarStyle.Any, true, true, Mark.Empty, Mark.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The tag. + /// The value. + public Scalar(string tag, string value) + : this(null, tag, value, ScalarStyle.Any, true, true, Mark.Empty, Mark.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + public Scalar(string anchor, string tag, string value) + : this(anchor, tag, value, ScalarStyle.Any, true, true, Mark.Empty, Mark.Empty) + { + } + + /// + /// Returns a that represents the current . + /// + /// + /// A that represents the current . + /// + public override string ToString() + { + return string.Format( + CultureInfo.InvariantCulture, + "Scalar [anchor = {0}, tag = {1}, value = {2}, style = {3}, isPlainImplicit = {4}, isQuotedImplicit = {5}]", + Anchor, + Tag, + value, + style, + isPlainImplicit, + isQuotedImplicit + ); + } + + /// + /// Invokes run-time type specific Visit() method of the specified visitor. + /// + /// visitor, may not be null. + public override void Accept(IParsingEventVisitor visitor) + { + visitor.Visit(this); + } + } +} diff --git a/YamlDotNet/Core/Events/Scalar.cs.meta b/YamlDotNet/Core/Events/Scalar.cs.meta new file mode 100644 index 0000000..7008241 --- /dev/null +++ b/YamlDotNet/Core/Events/Scalar.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 7c9ef7a4a2cc85b40aea8fda0d00cb33 +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Events/SequenceEnd.cs b/YamlDotNet/Core/Events/SequenceEnd.cs new file mode 100644 index 0000000..46b88b4 --- /dev/null +++ b/YamlDotNet/Core/Events/SequenceEnd.cs @@ -0,0 +1,91 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +namespace YamlDotNet.Core.Events +{ + /// + /// Represents a sequence end event. + /// + public class SequenceEnd : ParsingEvent + { + /// + /// Gets a value indicating the variation of depth caused by this event. + /// The value can be either -1, 0 or 1. For start events, it will be 1, + /// for end events, it will be -1, and for the remaining events, it will be 0. + /// + public override int NestingIncrease + { + get + { + return -1; + } + } + + /// + /// Gets the event type, which allows for simpler type comparisons. + /// + internal override EventType Type + { + get + { + return EventType.SequenceEnd; + } + } + + /// + /// Initializes a new instance of the class. + /// + /// The start position of the event. + /// The end position of the event. + public SequenceEnd(Mark start, Mark end) + : base(start, end) + { + } + + /// + /// Initializes a new instance of the class. + /// + public SequenceEnd() + : this(Mark.Empty, Mark.Empty) + { + } + + /// + /// Returns a that represents the current . + /// + /// + /// A that represents the current . + /// + public override string ToString() + { + return "Sequence end"; + } + + /// + /// Invokes run-time type specific Visit() method of the specified visitor. + /// + /// visitor, may not be null. + public override void Accept(IParsingEventVisitor visitor) + { + visitor.Visit(this); + } + } +} diff --git a/YamlDotNet/Core/Events/SequenceEnd.cs.meta b/YamlDotNet/Core/Events/SequenceEnd.cs.meta new file mode 100644 index 0000000..5bec23e --- /dev/null +++ b/YamlDotNet/Core/Events/SequenceEnd.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 37a7a63228a311b46ae903ea604105df +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Events/SequenceStart.cs b/YamlDotNet/Core/Events/SequenceStart.cs new file mode 100644 index 0000000..c329d1c --- /dev/null +++ b/YamlDotNet/Core/Events/SequenceStart.cs @@ -0,0 +1,148 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System.Globalization; + +namespace YamlDotNet.Core.Events +{ + /// + /// Represents a sequence start event. + /// + public class SequenceStart : NodeEvent + { + /// + /// Gets a value indicating the variation of depth caused by this event. + /// The value can be either -1, 0 or 1. For start events, it will be 1, + /// for end events, it will be -1, and for the remaining events, it will be 0. + /// + public override int NestingIncrease + { + get + { + return 1; + } + } + + /// + /// Gets the event type, which allows for simpler type comparisons. + /// + internal override EventType Type + { + get + { + return EventType.SequenceStart; + } + } + + private readonly bool isImplicit; + + /// + /// Gets a value indicating whether this instance is implicit. + /// + /// + /// true if this instance is implicit; otherwise, false. + /// + public bool IsImplicit + { + get + { + return isImplicit; + } + } + + /// + /// Gets a value indicating whether this instance is canonical. + /// + /// + public override bool IsCanonical + { + get + { + return !isImplicit; + } + } + + private readonly SequenceStyle style; + + /// + /// Gets the style. + /// + /// The style. + public SequenceStyle Style + { + get + { + return style; + } + } + + /// + /// Initializes a new instance of the class. + /// + /// The anchor. + /// The tag. + /// if set to true [is implicit]. + /// The style. + /// The start position of the event. + /// The end position of the event. + public SequenceStart(string anchor, string tag, bool isImplicit, SequenceStyle style, Mark start, Mark end) + : base(anchor, tag, start, end) + { + this.isImplicit = isImplicit; + this.style = style; + } + + /// + /// Initializes a new instance of the class. + /// + public SequenceStart(string anchor, string tag, bool isImplicit, SequenceStyle style) + : this(anchor, tag, isImplicit, style, Mark.Empty, Mark.Empty) + { + } + + /// + /// Returns a that represents the current . + /// + /// + /// A that represents the current . + /// + public override string ToString() + { + return string.Format( + CultureInfo.InvariantCulture, + "Sequence start [anchor = {0}, tag = {1}, isImplicit = {2}, style = {3}]", + Anchor, + Tag, + isImplicit, + style + ); + } + + /// + /// Invokes run-time type specific Visit() method of the specified visitor. + /// + /// visitor, may not be null. + public override void Accept(IParsingEventVisitor visitor) + { + visitor.Visit(this); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Events/SequenceStart.cs.meta b/YamlDotNet/Core/Events/SequenceStart.cs.meta new file mode 100644 index 0000000..f981f04 --- /dev/null +++ b/YamlDotNet/Core/Events/SequenceStart.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d0414698332e0c643ad3fddd1b907b5e +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Events/SequenceStyle.cs b/YamlDotNet/Core/Events/SequenceStyle.cs new file mode 100644 index 0000000..2b0efe4 --- /dev/null +++ b/YamlDotNet/Core/Events/SequenceStyle.cs @@ -0,0 +1,44 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +namespace YamlDotNet.Core.Events +{ + /// + /// Specifies the style of a sequence. + /// + public enum SequenceStyle + { + /// + /// Let the emitter choose the style. + /// + Any, + + /// + /// The block sequence style. + /// + Block, + + /// + /// The flow sequence style. + /// + Flow + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Events/SequenceStyle.cs.meta b/YamlDotNet/Core/Events/SequenceStyle.cs.meta new file mode 100644 index 0000000..769f9f2 --- /dev/null +++ b/YamlDotNet/Core/Events/SequenceStyle.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f66466d1eedabbe4db084d2d0e64415b +timeCreated: 1427145267 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Events/StreamEnd.cs b/YamlDotNet/Core/Events/StreamEnd.cs new file mode 100644 index 0000000..e55b600 --- /dev/null +++ b/YamlDotNet/Core/Events/StreamEnd.cs @@ -0,0 +1,91 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +namespace YamlDotNet.Core.Events +{ + /// + /// Represents a stream end event. + /// + public class StreamEnd : ParsingEvent + { + /// + /// Gets a value indicating the variation of depth caused by this event. + /// The value can be either -1, 0 or 1. For start events, it will be 1, + /// for end events, it will be -1, and for the remaining events, it will be 0. + /// + public override int NestingIncrease + { + get + { + return -1; + } + } + + /// + /// Gets the event type, which allows for simpler type comparisons. + /// + internal override EventType Type + { + get + { + return EventType.StreamEnd; + } + } + + /// + /// Initializes a new instance of the class. + /// + /// The start position of the event. + /// The end position of the event. + public StreamEnd(Mark start, Mark end) + : base(start, end) + { + } + + /// + /// Initializes a new instance of the class. + /// + public StreamEnd() + : this(Mark.Empty, Mark.Empty) + { + } + + /// + /// Returns a that represents the current . + /// + /// + /// A that represents the current . + /// + public override string ToString() + { + return "Stream end"; + } + + /// + /// Invokes run-time type specific Visit() method of the specified visitor. + /// + /// visitor, may not be null. + public override void Accept(IParsingEventVisitor visitor) + { + visitor.Visit(this); + } + } +} diff --git a/YamlDotNet/Core/Events/StreamEnd.cs.meta b/YamlDotNet/Core/Events/StreamEnd.cs.meta new file mode 100644 index 0000000..3ca648e --- /dev/null +++ b/YamlDotNet/Core/Events/StreamEnd.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 703673d959fca474691646e24e9ccedb +timeCreated: 1427145264 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Events/StreamStart.cs b/YamlDotNet/Core/Events/StreamStart.cs new file mode 100644 index 0000000..af21c59 --- /dev/null +++ b/YamlDotNet/Core/Events/StreamStart.cs @@ -0,0 +1,91 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +namespace YamlDotNet.Core.Events +{ + /// + /// Represents a stream start event. + /// + public class StreamStart : ParsingEvent + { + /// + /// Gets a value indicating the variation of depth caused by this event. + /// The value can be either -1, 0 or 1. For start events, it will be 1, + /// for end events, it will be -1, and for the remaining events, it will be 0. + /// + public override int NestingIncrease + { + get + { + return 1; + } + } + + /// + /// Gets the event type, which allows for simpler type comparisons. + /// + internal override EventType Type + { + get + { + return EventType.StreamStart; + } + } + + /// + /// Initializes a new instance of the class. + /// + public StreamStart() + : this(Mark.Empty, Mark.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The start position of the event. + /// The end position of the event. + public StreamStart(Mark start, Mark end) + : base(start, end) + { + } + + /// + /// Returns a that represents the current . + /// + /// + /// A that represents the current . + /// + public override string ToString() + { + return "Stream start"; + } + + /// + /// Invokes run-time type specific Visit() method of the specified visitor. + /// + /// visitor, may not be null. + public override void Accept(IParsingEventVisitor visitor) + { + visitor.Visit(this); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Events/StreamStart.cs.meta b/YamlDotNet/Core/Events/StreamStart.cs.meta new file mode 100644 index 0000000..c9dbf3d --- /dev/null +++ b/YamlDotNet/Core/Events/StreamStart.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 8127a5c9cbbe94547a9c1d39fee327db +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/FakeList.cs b/YamlDotNet/Core/FakeList.cs new file mode 100644 index 0000000..f546db1 --- /dev/null +++ b/YamlDotNet/Core/FakeList.cs @@ -0,0 +1,83 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; + +namespace YamlDotNet.Core +{ + /// + /// Implements an indexer through an IEnumerator<T>. + /// + public class FakeList + { + private readonly IEnumerator collection; + private int currentIndex = -1; + + /// + /// Initializes a new instance of FakeList<T>. + /// + /// The enumerator to use to implement the indexer. + public FakeList(IEnumerator collection) + { + this.collection = collection; + } + + /// + /// Initializes a new instance of FakeList<T>. + /// + /// The collection to use to implement the indexer. + public FakeList(IEnumerable collection) + : this(collection.GetEnumerator()) + { + } + + /// + /// Gets the element at the specified index. + /// + /// + /// If index is greater or equal than the last used index, this operation is O(index - lastIndex), + /// else this operation is O(index). + /// + public T this[int index] + { + get + { + if (index < currentIndex) + { + collection.Reset(); + currentIndex = -1; + } + + while (currentIndex < index) + { + if (!collection.MoveNext()) + { + throw new ArgumentOutOfRangeException("index"); + } + ++currentIndex; + } + + return collection.Current; + } + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/FakeList.cs.meta b/YamlDotNet/Core/FakeList.cs.meta new file mode 100644 index 0000000..6e5eb77 --- /dev/null +++ b/YamlDotNet/Core/FakeList.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2d01575f74bb894458c14178b7ee54d0 +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/ForwardAnchorNotSupportedException.cs b/YamlDotNet/Core/ForwardAnchorNotSupportedException.cs new file mode 100644 index 0000000..6e54cc5 --- /dev/null +++ b/YamlDotNet/Core/ForwardAnchorNotSupportedException.cs @@ -0,0 +1,69 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Runtime.Serialization; + +namespace YamlDotNet.Core +{ + /// + /// The exception that is thrown when an alias references an anchor + /// that has not yet been defined in a context that does not support forward references. + /// + [Serializable] + public class ForwardAnchorNotSupportedException : YamlException + { + /// + /// Initializes a new instance of the class. + /// + public ForwardAnchorNotSupportedException() + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The message. + public ForwardAnchorNotSupportedException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class. + /// + public ForwardAnchorNotSupportedException(Mark start, Mark end, string message) + : base(start, end, message) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The message. + /// The inner. + public ForwardAnchorNotSupportedException(string message, Exception inner) + : base(message, inner) + { + } + + } +} diff --git a/YamlDotNet/Core/ForwardAnchorNotSupportedException.cs.meta b/YamlDotNet/Core/ForwardAnchorNotSupportedException.cs.meta new file mode 100644 index 0000000..a0ad999 --- /dev/null +++ b/YamlDotNet/Core/ForwardAnchorNotSupportedException.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 4a2bedb057911514fb2a96c1cc2db68d +timeCreated: 1427145264 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/HashCode.cs b/YamlDotNet/Core/HashCode.cs new file mode 100644 index 0000000..b143003 --- /dev/null +++ b/YamlDotNet/Core/HashCode.cs @@ -0,0 +1,42 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace YamlDotNet.Core +{ + /// + /// Supports implementations of by providing methods to combine two hash codes. + /// + internal static class HashCode + { + /// + /// Combines two hash codes. + /// + /// The first hash code. + /// The second hash code. + /// + public static int CombineHashCodes(int h1, int h2) + { + return ((h1 << 5) + h1) ^ h2; + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/HashCode.cs.meta b/YamlDotNet/Core/HashCode.cs.meta new file mode 100644 index 0000000..ca0ef95 --- /dev/null +++ b/YamlDotNet/Core/HashCode.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2cb3fe21d8ebcf0458b6008e1ba2ac08 +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/IEmitter.cs b/YamlDotNet/Core/IEmitter.cs new file mode 100644 index 0000000..e3fb3c9 --- /dev/null +++ b/YamlDotNet/Core/IEmitter.cs @@ -0,0 +1,36 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using YamlDotNet.Core.Events; + +namespace YamlDotNet.Core +{ + /// + /// Represents a YAML stream emitter. + /// + public interface IEmitter + { + /// + /// Emits an event. + /// + void Emit(ParsingEvent @event); + } +} diff --git a/YamlDotNet/Core/IEmitter.cs.meta b/YamlDotNet/Core/IEmitter.cs.meta new file mode 100644 index 0000000..fb25424 --- /dev/null +++ b/YamlDotNet/Core/IEmitter.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: ea595b7247a52d84796adae58a272de0 +timeCreated: 1427145267 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/ILookAheadBuffer.cs b/YamlDotNet/Core/ILookAheadBuffer.cs new file mode 100644 index 0000000..b863ff2 --- /dev/null +++ b/YamlDotNet/Core/ILookAheadBuffer.cs @@ -0,0 +1,47 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace YamlDotNet.Core +{ + internal interface ILookAheadBuffer + { + /// + /// Gets a value indicating whether the end of the input reader has been reached. + /// + bool EndOfInput + { + get; + } + + /// + /// Gets the character at thhe specified offset. + /// + char Peek(int offset); + + /// + /// Skips the next characters. Those characters must have been + /// obtained first by calling the method. + /// + void Skip(int length); + } +} diff --git a/YamlDotNet/Core/ILookAheadBuffer.cs.meta b/YamlDotNet/Core/ILookAheadBuffer.cs.meta new file mode 100644 index 0000000..a5090d6 --- /dev/null +++ b/YamlDotNet/Core/ILookAheadBuffer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 574e18619ff79614f83b7fbaec47ae8c +timeCreated: 1427145264 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/IParser.cs b/YamlDotNet/Core/IParser.cs new file mode 100644 index 0000000..f4def50 --- /dev/null +++ b/YamlDotNet/Core/IParser.cs @@ -0,0 +1,43 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using YamlDotNet.Core.Events; + +namespace YamlDotNet.Core +{ + /// + /// Represents a YAML stream paser. + /// + public interface IParser + { + /// + /// Gets the current event. Returns null before the first call to , + /// and also after returns false. + /// + ParsingEvent Current { get; } + + /// + /// Moves to the next event. + /// + /// Returns true if there are more events available, otherwise returns false. + bool MoveNext(); + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/IParser.cs.meta b/YamlDotNet/Core/IParser.cs.meta new file mode 100644 index 0000000..53649ad --- /dev/null +++ b/YamlDotNet/Core/IParser.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: fc2416e849d87aa4598d335c421f7117 +timeCreated: 1427145267 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/IScanner.cs b/YamlDotNet/Core/IScanner.cs new file mode 100644 index 0000000..9fab03c --- /dev/null +++ b/YamlDotNet/Core/IScanner.cs @@ -0,0 +1,65 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System.Collections.Generic; +using YamlDotNet.Core.Tokens; + +namespace YamlDotNet.Core +{ + /// + /// Defines the interface for a stand-alone YAML scanner that + /// converts a sequence of characters into a sequence of YAML tokens. + /// + public interface IScanner + { + /// + /// Gets the current position inside the input stream. + /// + /// The current position. + Mark CurrentPosition + { + get; + } + + /// + /// Gets the current token. + /// + Token Current + { + get; + } + + /// + /// Moves to the next token and consumes the current token. + /// + bool MoveNext(); + + /// + /// Moves to the next token without consuming the current token. + /// + bool MoveNextWithoutConsuming(); + + /// + /// Consumes the current token. + /// + void ConsumeCurrent(); + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/IScanner.cs.meta b/YamlDotNet/Core/IScanner.cs.meta new file mode 100644 index 0000000..f646478 --- /dev/null +++ b/YamlDotNet/Core/IScanner.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f5c28b5ab2d236944a6f5f2858aa75d8 +timeCreated: 1427145267 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/InsertionQueue.cs b/YamlDotNet/Core/InsertionQueue.cs new file mode 100644 index 0000000..219ac62 --- /dev/null +++ b/YamlDotNet/Core/InsertionQueue.cs @@ -0,0 +1,83 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; + +namespace YamlDotNet.Core +{ + /// + /// Generic queue on which items may be inserted + /// + [Serializable] + public class InsertionQueue + { + // TODO: Use a more efficient data structure + + private readonly IList items = new List(); + + /// + /// Gets the number of items that are contained by the queue. + /// + public int Count + { + get + { + return items.Count; + } + } + + /// + /// Enqueues the specified item. + /// + /// The item to be enqueued. + public void Enqueue(T item) + { + items.Add(item); + } + + /// + /// Dequeues an item. + /// + /// Returns the item that been dequeued. + public T Dequeue() + { + if (Count == 0) + { + throw new InvalidOperationException("The queue is empty"); + } + + T item = items[0]; + items.RemoveAt(0); + return item; + } + + /// + /// Inserts an item at the specified index. + /// + /// The index where to insert the item. + /// The item to be inserted. + public void Insert(int index, T item) + { + items.Insert(index, item); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/InsertionQueue.cs.meta b/YamlDotNet/Core/InsertionQueue.cs.meta new file mode 100644 index 0000000..5f0eed1 --- /dev/null +++ b/YamlDotNet/Core/InsertionQueue.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d5ebdfa25d33598469684afe6f672277 +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/LookAheadBuffer.cs b/YamlDotNet/Core/LookAheadBuffer.cs new file mode 100644 index 0000000..99a4f3d --- /dev/null +++ b/YamlDotNet/Core/LookAheadBuffer.cs @@ -0,0 +1,148 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.IO; + +namespace YamlDotNet.Core +{ + /// + /// Provides access to a stream and allows to peek at the next characters, + /// up to the buffer's capacity. + /// + /// + /// This class implements a circular buffer with a fixed capacity. + /// + [Serializable] + public class LookAheadBuffer : ILookAheadBuffer + { + private readonly TextReader input; + private readonly char[] buffer; + private int firstIndex; + private int count; + private bool endOfInput; + + /// + /// Initializes a new instance of the class. + /// + /// The input. + /// The capacity. + public LookAheadBuffer(TextReader input, int capacity) + { + if (input == null) + { + throw new ArgumentNullException("input"); + } + if (capacity < 1) + { + throw new ArgumentOutOfRangeException("capacity", "The capacity must be positive."); + } + + this.input = input; + buffer = new char[capacity]; + } + + /// + /// Gets a value indicating whether the end of the input reader has been reached. + /// + public bool EndOfInput + { + get + { + return endOfInput && count == 0; + } + } + + /// + /// Gets the index of the character for the specified offset. + /// + private int GetIndexForOffset(int offset) + { + int index = firstIndex + offset; + if (index >= buffer.Length) + { + index -= buffer.Length; + } + return index; + } + + /// + /// Gets the character at thhe specified offset. + /// + public char Peek(int offset) + { + if (offset < 0 || offset >= buffer.Length) + { + throw new ArgumentOutOfRangeException("offset", "The offset must be betwwen zero and the capacity of the buffer."); + } + + Cache(offset); + + if (offset < count) + { + return buffer[GetIndexForOffset(offset)]; + } + else + { + return '\0'; + } + } + + /// + /// Reads characters until at least characters are in the buffer. + /// + /// + /// Number of characters to cache. + /// + public void Cache(int length) + { + while (length >= count) + { + var nextChar = input.Read(); + if (nextChar >= 0) + { + var lastIndex = GetIndexForOffset(count); + buffer[lastIndex] = (char)nextChar; + ++count; + } + else + { + endOfInput = true; + return; + } + } + } + + /// + /// Skips the next characters. Those characters must have been + /// obtained first by calling the or methods. + /// + public void Skip(int length) + { + if (length < 1 || length > count) + { + throw new ArgumentOutOfRangeException("length", "The length must be between 1 and the number of characters in the buffer. Use the Peek() and / or Cache() methods to fill the buffer."); + } + firstIndex = GetIndexForOffset(length); + count -= length; + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/LookAheadBuffer.cs.meta b/YamlDotNet/Core/LookAheadBuffer.cs.meta new file mode 100644 index 0000000..cdb1ab5 --- /dev/null +++ b/YamlDotNet/Core/LookAheadBuffer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 4d909b1f8d7468e4188667b8b706d225 +timeCreated: 1427145264 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Mark.cs b/YamlDotNet/Core/Mark.cs new file mode 100644 index 0000000..177a3f4 --- /dev/null +++ b/YamlDotNet/Core/Mark.cs @@ -0,0 +1,142 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace YamlDotNet.Core +{ + /// + /// Represents a location inside a file + /// + [Serializable] + public class Mark : IEquatable, IComparable, IComparable + { + /// + /// Gets a with empty values. + /// + public static readonly Mark Empty = new Mark(); + + /// + /// Gets / sets the absolute offset in the file + /// + public int Index { get; private set; } + + /// + /// Gets / sets the number of the line + /// + public int Line { get; private set; } + + /// + /// Gets / sets the index of the column + /// + public int Column { get; private set; } + + public Mark() + { + Line = 1; + Column = 1; + } + + public Mark(int index, int line, int column) + { + if (index < 0) + { + throw new ArgumentOutOfRangeException("index", "Index must be greater than or equal to zero."); + } + if (line < 1) + { + throw new ArgumentOutOfRangeException("line", "Line must be greater than or equal to 1."); + } + if (column < 1) + { + throw new ArgumentOutOfRangeException("column", "Column must be greater than or equal to 1."); + } + + Index = index; + Line = line; + Column = column; + } + + /// + /// Returns a that represents this instance. + /// + /// + /// A that represents this instance. + /// + public override string ToString() + { + return string.Format("Line: {0}, Col: {1}, Idx: {2}", Line, Column, Index); + } + + /// + public override bool Equals(object obj) + { + return Equals(obj as Mark); + } + + /// + public bool Equals(Mark other) + { + return other != null + && Index == other.Index + && Line == other.Line + && Column == other.Column; + } + + /// + public override int GetHashCode() + { + return HashCode.CombineHashCodes( + Index.GetHashCode(), + HashCode.CombineHashCodes( + Line.GetHashCode(), + Column.GetHashCode() + ) + ); + } + + /// + public int CompareTo(object obj) + { + if (obj == null) + { + throw new ArgumentNullException("obj"); + } + return CompareTo(obj as Mark); + } + + /// + public int CompareTo(Mark other) + { + if (other == null) + { + throw new ArgumentNullException("other"); + } + + var cmp = Line.CompareTo(other.Line); + if (cmp == 0) + { + cmp = Column.CompareTo(other.Column); + } + return cmp; + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Mark.cs.meta b/YamlDotNet/Core/Mark.cs.meta new file mode 100644 index 0000000..20bc281 --- /dev/null +++ b/YamlDotNet/Core/Mark.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 9a02d917bb4d2164ea20caaafce2bb0b +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/MaximumRecursionLevelReachedException.cs b/YamlDotNet/Core/MaximumRecursionLevelReachedException.cs new file mode 100644 index 0000000..2c68222 --- /dev/null +++ b/YamlDotNet/Core/MaximumRecursionLevelReachedException.cs @@ -0,0 +1,68 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Runtime.Serialization; + +namespace YamlDotNet.Core +{ + /// + /// Exception that is thrown when an infinite recursion is detected. + /// + [Serializable] + public class MaximumRecursionLevelReachedException : YamlException + { + /// + /// Initializes a new instance of the class. + /// + public MaximumRecursionLevelReachedException() + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The message. + public MaximumRecursionLevelReachedException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class. + /// + public MaximumRecursionLevelReachedException(Mark start, Mark end, string message) + : base(start, end, message) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The message. + /// The inner. + public MaximumRecursionLevelReachedException(string message, Exception inner) + : base(message, inner) + { + } + + } +} diff --git a/YamlDotNet/Core/MaximumRecursionLevelReachedException.cs.meta b/YamlDotNet/Core/MaximumRecursionLevelReachedException.cs.meta new file mode 100644 index 0000000..3869fb1 --- /dev/null +++ b/YamlDotNet/Core/MaximumRecursionLevelReachedException.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: e4964c5da9dbb7245bf01fd55f6fe5ed +timeCreated: 1485601085 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/MergingParser.cs b/YamlDotNet/Core/MergingParser.cs new file mode 100644 index 0000000..6ec11ef --- /dev/null +++ b/YamlDotNet/Core/MergingParser.cs @@ -0,0 +1,195 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Linq; +using YamlDotNet.Core.Events; + +namespace YamlDotNet.Core +{ + /// + /// Simple implementation of that implements merging: http://yaml.org/type/merge.html + /// + public sealed class MergingParser : IParser + { + private readonly List _allEvents = new List(); + private readonly IParser _innerParser; + private int _currentIndex = -1; + + public MergingParser(IParser innerParser) + { + _innerParser = innerParser; + } + + public ParsingEvent Current { get; private set; } + + public bool MoveNext() + { + if (_currentIndex < 0) + { + while (_innerParser.MoveNext()) + { + _allEvents.Add(_innerParser.Current); + } + + for (int i = _allEvents.Count - 2; i >= 0; --i) + { + var merge = _allEvents[i] as Scalar; + if (merge != null && merge.Value == "<<") + { + var anchorAlias = _allEvents[i + 1] as AnchorAlias; + if (anchorAlias != null) + { + var mergedEvents = GetMappingEvents(anchorAlias.Value); + _allEvents.RemoveRange(i, 2); + _allEvents.InsertRange(i, mergedEvents); + continue; + } + + var sequence = _allEvents[i + 1] as SequenceStart; + if (sequence != null) + { + var mergedEvents = new List>(); + var sequenceEndFound = false; + for (var itemIndex = i + 2; itemIndex < _allEvents.Count; ++itemIndex) + { + anchorAlias = _allEvents[itemIndex] as AnchorAlias; + if (anchorAlias != null) + { + mergedEvents.Add(GetMappingEvents(anchorAlias.Value)); + continue; + } + + if (_allEvents[itemIndex] is SequenceEnd) + { + _allEvents.RemoveRange(i, itemIndex - i + 1); + _allEvents.InsertRange(i, mergedEvents.SelectMany(e => e)); + sequenceEndFound = true; + break; + } + } + + if (sequenceEndFound) + { + continue; + } + } + + throw new SemanticErrorException(merge.Start, merge.End, "Unrecognized merge key pattern"); + } + } + } + + var nextIndex = _currentIndex + 1; + if (nextIndex < _allEvents.Count) + { + Current = _allEvents[nextIndex]; + _currentIndex = nextIndex; + return true; + } + return false; + } + + private IEnumerable GetMappingEvents(string mappingAlias) + { + var cloner = new ParsingEventCloner(); + + var nesting = 0; + return _allEvents + .SkipWhile(e => + { + var mappingStart = e as MappingStart; + return mappingStart == null || mappingStart.Anchor != mappingAlias; + }) + .Skip(1) + .TakeWhile(e => (nesting += e.NestingIncrease) >= 0) + .Select(e => cloner.Clone(e)) + .ToList(); + } + + private class ParsingEventCloner : IParsingEventVisitor + { + private ParsingEvent clonedEvent; + + public ParsingEvent Clone(ParsingEvent e) + { + e.Accept(this); + return clonedEvent; + } + + void IParsingEventVisitor.Visit(AnchorAlias e) + { + clonedEvent = new AnchorAlias(e.Value, e.Start, e.End); + } + + void IParsingEventVisitor.Visit(StreamStart e) + { + throw new NotSupportedException(); + } + + void IParsingEventVisitor.Visit(StreamEnd e) + { + throw new NotSupportedException(); + } + + void IParsingEventVisitor.Visit(DocumentStart e) + { + throw new NotSupportedException(); + } + + void IParsingEventVisitor.Visit(DocumentEnd e) + { + throw new NotSupportedException(); + } + + void IParsingEventVisitor.Visit(Scalar e) + { + clonedEvent = new Scalar(null, e.Tag, e.Value, e.Style, e.IsPlainImplicit, e.IsQuotedImplicit, e.Start, e.End); + } + + void IParsingEventVisitor.Visit(SequenceStart e) + { + clonedEvent = new SequenceStart(null, e.Tag, e.IsImplicit, e.Style, e.Start, e.End); + } + + void IParsingEventVisitor.Visit(SequenceEnd e) + { + clonedEvent = new SequenceEnd(e.Start, e.End); + } + + void IParsingEventVisitor.Visit(MappingStart e) + { + clonedEvent = new MappingStart(null, e.Tag, e.IsImplicit, e.Style, e.Start, e.End); + } + + void IParsingEventVisitor.Visit(MappingEnd e) + { + clonedEvent = new MappingEnd(e.Start, e.End); + } + + void IParsingEventVisitor.Visit(Comment e) + { + throw new NotSupportedException(); + } + } + } +} diff --git a/YamlDotNet/Core/MergingParser.cs.meta b/YamlDotNet/Core/MergingParser.cs.meta new file mode 100644 index 0000000..6828069 --- /dev/null +++ b/YamlDotNet/Core/MergingParser.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2aee5019246749c40a971ff855ffba79 +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Parser.cs b/YamlDotNet/Core/Parser.cs new file mode 100644 index 0000000..7314067 --- /dev/null +++ b/YamlDotNet/Core/Parser.cs @@ -0,0 +1,988 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using YamlDotNet.Core.Tokens; +using MappingStyle = YamlDotNet.Core.Events.MappingStyle; +using ParsingEvent = YamlDotNet.Core.Events.ParsingEvent; +using SequenceStyle = YamlDotNet.Core.Events.SequenceStyle; + +namespace YamlDotNet.Core +{ + /// + /// Parses YAML streams. + /// + public class Parser : IParser + { + private readonly Stack states = new Stack(); + private readonly TagDirectiveCollection tagDirectives = new TagDirectiveCollection(); + private ParserState state; + + private readonly IScanner scanner; + private ParsingEvent currentEvent; + + private Token currentToken; + + private Token GetCurrentToken() + { + if (currentToken == null) + { + while (scanner.MoveNextWithoutConsuming()) + { + currentToken = scanner.Current; + + var commentToken = currentToken as Comment; + if (commentToken != null) + { + pendingEvents.Enqueue(new Events.Comment(commentToken.Value, commentToken.IsInline, commentToken.Start, commentToken.End)); + } + else + { + break; + } + } + } + return currentToken; + } + + /// + /// Initializes a new instance of the class. + /// + /// The input where the YAML stream is to be read. + public Parser(TextReader input) + : this(new Scanner(input)) + { + } + + /// + /// Initializes a new instance of the class. + /// + public Parser(IScanner scanner) + { + this.scanner = scanner; + } + + /// + /// Gets the current event. + /// + public ParsingEvent Current + { + get + { + return currentEvent; + } + } + + private readonly EventQueue pendingEvents = new EventQueue(); + + /// + /// Moves to the next event. + /// + /// Returns true if there are more events available, otherwise returns false. + public bool MoveNext() + { + // No events after the end of the stream or error. + if (state == ParserState.StreamEnd) + { + currentEvent = null; + return false; + } + else if (pendingEvents.Count == 0) + { + // Generate the next event. + pendingEvents.Enqueue(StateMachine()); + } + + currentEvent = pendingEvents.Dequeue(); + return true; + } + + private ParsingEvent StateMachine() + { + switch (state) + { + case ParserState.StreamStart: + return ParseStreamStart(); + + case ParserState.ImplicitDocumentStart: + return ParseDocumentStart(true); + + case ParserState.DocumentStart: + return ParseDocumentStart(false); + + case ParserState.DocumentContent: + return ParseDocumentContent(); + + case ParserState.DocumentEnd: + return ParseDocumentEnd(); + + case ParserState.BlockNode: + return ParseNode(true, false); + + case ParserState.BlockNodeOrIndentlessSequence: + return ParseNode(true, true); + + case ParserState.FlowNode: + return ParseNode(false, false); + + case ParserState.BlockSequenceFirstEntry: + return ParseBlockSequenceEntry(true); + + case ParserState.BlockSequenceEntry: + return ParseBlockSequenceEntry(false); + + case ParserState.IndentlessSequenceEntry: + return ParseIndentlessSequenceEntry(); + + case ParserState.BlockMappingFirstKey: + return ParseBlockMappingKey(true); + + case ParserState.BlockMappingKey: + return ParseBlockMappingKey(false); + + case ParserState.BlockMappingValue: + return ParseBlockMappingValue(); + + case ParserState.FlowSequenceFirstEntry: + return ParseFlowSequenceEntry(true); + + case ParserState.FlowSequenceEntry: + return ParseFlowSequenceEntry(false); + + case ParserState.FlowSequenceEntryMappingKey: + return ParseFlowSequenceEntryMappingKey(); + + case ParserState.FlowSequenceEntryMappingValue: + return ParseFlowSequenceEntryMappingValue(); + + case ParserState.FlowSequenceEntryMappingEnd: + return ParseFlowSequenceEntryMappingEnd(); + + case ParserState.FlowMappingFirstKey: + return ParseFlowMappingKey(true); + + case ParserState.FlowMappingKey: + return ParseFlowMappingKey(false); + + case ParserState.FlowMappingValue: + return ParseFlowMappingValue(false); + + case ParserState.FlowMappingEmptyValue: + return ParseFlowMappingValue(true); + + default: + Debug.Assert(false, "Invalid state"); // Invalid state. + throw new InvalidOperationException(); + } + } + + private void Skip() + { + if (currentToken != null) + { + currentToken = null; + scanner.ConsumeCurrent(); + } + } + + /// + /// Parse the production: + /// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END + /// ************ + /// + private ParsingEvent ParseStreamStart() + { + var streamStart = GetCurrentToken() as StreamStart; + if (streamStart == null) + { + var current = GetCurrentToken(); + throw new SemanticErrorException(current.Start, current.End, "Did not find expected ."); + } + Skip(); + + state = ParserState.ImplicitDocumentStart; + return new Events.StreamStart(streamStart.Start, streamStart.End); + } + + /// + /// Parse the productions: + /// implicit_document ::= block_node DOCUMENT-END* + /// * + /// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* + /// ************************* + /// + private ParsingEvent ParseDocumentStart(bool isImplicit) + { + // Parse extra document end indicators. + + if (!isImplicit) + { + while (GetCurrentToken() is DocumentEnd) + { + Skip(); + } + } + + // Parse an isImplicit document. + + if (isImplicit && !(GetCurrentToken() is VersionDirective || GetCurrentToken() is TagDirective || GetCurrentToken() is DocumentStart || GetCurrentToken() is StreamEnd)) + { + var directives = new TagDirectiveCollection(); + ProcessDirectives(directives); + + states.Push(ParserState.DocumentEnd); + + state = ParserState.BlockNode; + + return new Events.DocumentStart(null, directives, true, GetCurrentToken().Start, GetCurrentToken().End); + } + + // Parse an explicit document. + + else if (!(GetCurrentToken() is StreamEnd)) + { + Mark start = GetCurrentToken().Start; + var directives = new TagDirectiveCollection(); + var versionDirective = ProcessDirectives(directives); + + var current = GetCurrentToken(); + if (!(current is DocumentStart)) + { + throw new SemanticErrorException(current.Start, current.End, "Did not find expected ."); + } + + states.Push(ParserState.DocumentEnd); + + state = ParserState.DocumentContent; + + ParsingEvent evt = new Events.DocumentStart(versionDirective, directives, false, start, current.End); + Skip(); + return evt; + } + + // Parse the stream end. + + else + { + state = ParserState.StreamEnd; + + ParsingEvent evt = new Events.StreamEnd(GetCurrentToken().Start, GetCurrentToken().End); + // Do not call skip here because that would throw an exception + if (scanner.MoveNextWithoutConsuming()) + { + throw new InvalidOperationException("The scanner should contain no more tokens."); + } + return evt; + } + } + + /// + /// Parse directives. + /// + private VersionDirective ProcessDirectives(TagDirectiveCollection tags) + { + VersionDirective version = null; + bool hasOwnDirectives = false; + + while (true) + { + VersionDirective currentVersion; + TagDirective tag; + + if ((currentVersion = GetCurrentToken() as VersionDirective) != null) + { + if (version != null) + { + throw new SemanticErrorException(currentVersion.Start, currentVersion.End, "Found duplicate %YAML directive."); + } + + if (currentVersion.Version.Major != Constants.MajorVersion || currentVersion.Version.Minor != Constants.MinorVersion) + { + throw new SemanticErrorException(currentVersion.Start, currentVersion.End, "Found incompatible YAML document."); + } + + version = currentVersion; + hasOwnDirectives = true; + } + else if ((tag = GetCurrentToken() as TagDirective) != null) + { + if (tags.Contains(tag.Handle)) + { + throw new SemanticErrorException(tag.Start, tag.End, "Found duplicate %TAG directive."); + } + tags.Add(tag); + hasOwnDirectives = true; + } + else + { + break; + } + + Skip(); + } + + AddTagDirectives(tags, Constants.DefaultTagDirectives); + + if (hasOwnDirectives) + { + tagDirectives.Clear(); + } + + AddTagDirectives(tagDirectives, tags); + + return version; + } + + private static void AddTagDirectives(TagDirectiveCollection directives, IEnumerable source) + { + foreach (var directive in source) + { + if (!directives.Contains(directive)) + { + directives.Add(directive); + } + } + } + + /// + /// Parse the productions: + /// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* + /// *********** + /// + private ParsingEvent ParseDocumentContent() + { + if ( + GetCurrentToken() is VersionDirective || + GetCurrentToken() is TagDirective || + GetCurrentToken() is DocumentStart || + GetCurrentToken() is DocumentEnd || + GetCurrentToken() is StreamEnd + ) + { + state = states.Pop(); + return ProcessEmptyScalar(scanner.CurrentPosition); + } + else + { + return ParseNode(true, false); + } + } + + /// + /// Generate an empty scalar event. + /// + private static ParsingEvent ProcessEmptyScalar(Mark position) + { + return new Events.Scalar(null, null, string.Empty, ScalarStyle.Plain, true, false, position, position); + } + + /// + /// Parse the productions: + /// block_node_or_indentless_sequence ::= + /// ALIAS + /// ***** + /// | properties (block_content | indentless_block_sequence)? + /// ********** * + /// | block_content | indentless_block_sequence + /// * + /// block_node ::= ALIAS + /// ***** + /// | properties block_content? + /// ********** * + /// | block_content + /// * + /// flow_node ::= ALIAS + /// ***** + /// | properties flow_content? + /// ********** * + /// | flow_content + /// * + /// properties ::= TAG ANCHOR? | ANCHOR TAG? + /// ************************* + /// block_content ::= block_collection | flow_collection | SCALAR + /// ****** + /// flow_content ::= flow_collection | SCALAR + /// ****** + /// + private ParsingEvent ParseNode(bool isBlock, bool isIndentlessSequence) + { + var alias = GetCurrentToken() as AnchorAlias; + if (alias != null) + { + state = states.Pop(); + ParsingEvent evt = new Events.AnchorAlias(alias.Value, alias.Start, alias.End); + Skip(); + return evt; + } + + Mark start = GetCurrentToken().Start; + + Anchor anchor = null; + Tag tag = null; + + // The anchor and the tag can be in any order. This loop repeats at most twice. + while (true) + { + if (anchor == null && (anchor = GetCurrentToken() as Anchor) != null) + { + Skip(); + } + else if (tag == null && (tag = GetCurrentToken() as Tag) != null) + { + Skip(); + } + else + { + break; + } + } + + string tagName = null; + if (tag != null) + { + if (string.IsNullOrEmpty(tag.Handle)) + { + tagName = tag.Suffix; + } + else if (tagDirectives.Contains(tag.Handle)) + { + tagName = string.Concat(tagDirectives[tag.Handle].Prefix, tag.Suffix); + } + else + { + throw new SemanticErrorException(tag.Start, tag.End, "While parsing a node, find undefined tag handle."); + } + } + if (string.IsNullOrEmpty(tagName)) + { + tagName = null; + } + + string anchorName = anchor != null ? string.IsNullOrEmpty(anchor.Value) ? null : anchor.Value : null; + + var isImplicit = string.IsNullOrEmpty(tagName); + + if (isIndentlessSequence && GetCurrentToken() is BlockEntry) + { + state = ParserState.IndentlessSequenceEntry; + + return new Events.SequenceStart( + anchorName, + tagName, + isImplicit, + SequenceStyle.Block, + start, + GetCurrentToken().End + ); + } + else + { + var scalar = GetCurrentToken() as Scalar; + if (scalar != null) + { + bool isPlainImplicit = false; + bool isQuotedImplicit = false; + if ((scalar.Style == ScalarStyle.Plain && tagName == null) || tagName == Constants.DefaultHandle) + { + isPlainImplicit = true; + } + else if (tagName == null) + { + isQuotedImplicit = true; + } + + state = states.Pop(); + ParsingEvent evt = new Events.Scalar(anchorName, tagName, scalar.Value, scalar.Style, isPlainImplicit, isQuotedImplicit, start, scalar.End); + + Skip(); + return evt; + } + + var flowSequenceStart = GetCurrentToken() as FlowSequenceStart; + if (flowSequenceStart != null) + { + state = ParserState.FlowSequenceFirstEntry; + return new Events.SequenceStart(anchorName, tagName, isImplicit, SequenceStyle.Flow, start, flowSequenceStart.End); + } + + var flowMappingStart = GetCurrentToken() as FlowMappingStart; + if (flowMappingStart != null) + { + state = ParserState.FlowMappingFirstKey; + return new Events.MappingStart(anchorName, tagName, isImplicit, MappingStyle.Flow, start, flowMappingStart.End); + } + + if (isBlock) + { + var blockSequenceStart = GetCurrentToken() as BlockSequenceStart; + if (blockSequenceStart != null) + { + state = ParserState.BlockSequenceFirstEntry; + return new Events.SequenceStart(anchorName, tagName, isImplicit, SequenceStyle.Block, start, blockSequenceStart.End); + } + + var blockMappingStart = GetCurrentToken() as BlockMappingStart; + if (blockMappingStart != null) + { + state = ParserState.BlockMappingFirstKey; + return new Events.MappingStart(anchorName, tagName, isImplicit, MappingStyle.Block, start, GetCurrentToken().End); + } + } + + if (anchorName != null || tag != null) + { + state = states.Pop(); + return new Events.Scalar(anchorName, tagName, string.Empty, ScalarStyle.Plain, isImplicit, false, start, GetCurrentToken().End); + } + + var current = GetCurrentToken(); + throw new SemanticErrorException(current.Start, current.End, "While parsing a node, did not find expected node content."); + } + } + + /// + /// Parse the productions: + /// implicit_document ::= block_node DOCUMENT-END* + /// ************* + /// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* + /// ************* + /// + + private ParsingEvent ParseDocumentEnd() + { + bool isImplicit = true; + Mark start = GetCurrentToken().Start; + Mark end = start; + + if (GetCurrentToken() is DocumentEnd) + { + end = GetCurrentToken().End; + Skip(); + isImplicit = false; + } + + state = ParserState.DocumentStart; + return new Events.DocumentEnd(isImplicit, start, end); + } + + /// + /// Parse the productions: + /// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END + /// ******************** *********** * ********* + /// + + private ParsingEvent ParseBlockSequenceEntry(bool isFirst) + { + if (isFirst) + { + GetCurrentToken(); + Skip(); + } + + if (GetCurrentToken() is BlockEntry) + { + Mark mark = GetCurrentToken().End; + + Skip(); + if (!(GetCurrentToken() is BlockEntry || GetCurrentToken() is BlockEnd)) + { + states.Push(ParserState.BlockSequenceEntry); + return ParseNode(true, false); + } + else + { + state = ParserState.BlockSequenceEntry; + return ProcessEmptyScalar(mark); + } + } + else if (GetCurrentToken() is BlockEnd) + { + state = states.Pop(); + ParsingEvent evt = new Events.SequenceEnd(GetCurrentToken().Start, GetCurrentToken().End); + Skip(); + return evt; + } + else + { + var current = GetCurrentToken(); + throw new SemanticErrorException(current.Start, current.End, "While parsing a block collection, did not find expected '-' indicator."); + } + } + + /// + /// Parse the productions: + /// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ + /// *********** * + /// + private ParsingEvent ParseIndentlessSequenceEntry() + { + if (GetCurrentToken() is BlockEntry) + { + Mark mark = GetCurrentToken().End; + Skip(); + + if (!(GetCurrentToken() is BlockEntry || GetCurrentToken() is Key || GetCurrentToken() is Value || GetCurrentToken() is BlockEnd)) + { + states.Push(ParserState.IndentlessSequenceEntry); + return ParseNode(true, false); + } + else + { + state = ParserState.IndentlessSequenceEntry; + return ProcessEmptyScalar(mark); + } + } + else + { + state = states.Pop(); + return new Events.SequenceEnd(GetCurrentToken().Start, GetCurrentToken().End); + } + } + + /// + /// Parse the productions: + /// block_mapping ::= BLOCK-MAPPING_START + /// ******************* + /// ((KEY block_node_or_indentless_sequence?)? + /// *** * + /// (VALUE block_node_or_indentless_sequence?)?)* + /// + /// BLOCK-END + /// ********* + /// + private ParsingEvent ParseBlockMappingKey(bool isFirst) + { + if (isFirst) + { + GetCurrentToken(); + Skip(); + } + + if (GetCurrentToken() is Key) + { + Mark mark = GetCurrentToken().End; + Skip(); + if (!(GetCurrentToken() is Key || GetCurrentToken() is Value || GetCurrentToken() is BlockEnd)) + { + states.Push(ParserState.BlockMappingValue); + return ParseNode(true, true); + } + else + { + state = ParserState.BlockMappingValue; + return ProcessEmptyScalar(mark); + } + } + + else if (GetCurrentToken() is BlockEnd) + { + state = states.Pop(); + ParsingEvent evt = new Events.MappingEnd(GetCurrentToken().Start, GetCurrentToken().End); + Skip(); + return evt; + } + + else + { + var current = GetCurrentToken(); + throw new SemanticErrorException(current.Start, current.End, "While parsing a block mapping, did not find expected key."); + } + } + + /// + /// Parse the productions: + /// block_mapping ::= BLOCK-MAPPING_START + /// + /// ((KEY block_node_or_indentless_sequence?)? + /// + /// (VALUE block_node_or_indentless_sequence?)?)* + /// ***** * + /// BLOCK-END + /// + /// + private ParsingEvent ParseBlockMappingValue() + { + if (GetCurrentToken() is Value) + { + Mark mark = GetCurrentToken().End; + Skip(); + + if (!(GetCurrentToken() is Key || GetCurrentToken() is Value || GetCurrentToken() is BlockEnd)) + { + states.Push(ParserState.BlockMappingKey); + return ParseNode(true, true); + } + else + { + state = ParserState.BlockMappingKey; + return ProcessEmptyScalar(mark); + } + } + + else + { + state = ParserState.BlockMappingKey; + return ProcessEmptyScalar(GetCurrentToken().Start); + } + } + + /// + /// Parse the productions: + /// flow_sequence ::= FLOW-SEQUENCE-START + /// ******************* + /// (flow_sequence_entry FLOW-ENTRY)* + /// * ********** + /// flow_sequence_entry? + /// * + /// FLOW-SEQUENCE-END + /// ***************** + /// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + /// * + /// + private ParsingEvent ParseFlowSequenceEntry(bool isFirst) + { + if (isFirst) + { + GetCurrentToken(); + Skip(); + } + + ParsingEvent evt; + if (!(GetCurrentToken() is FlowSequenceEnd)) + { + if (!isFirst) + { + if (GetCurrentToken() is FlowEntry) + { + Skip(); + } + else + { + var current = GetCurrentToken(); + throw new SemanticErrorException(current.Start, current.End, "While parsing a flow sequence, did not find expected ',' or ']'."); + } + } + + if (GetCurrentToken() is Key) + { + state = ParserState.FlowSequenceEntryMappingKey; + evt = new Events.MappingStart(null, null, true, MappingStyle.Flow); + Skip(); + return evt; + } + else if (!(GetCurrentToken() is FlowSequenceEnd)) + { + states.Push(ParserState.FlowSequenceEntry); + return ParseNode(false, false); + } + } + + state = states.Pop(); + evt = new Events.SequenceEnd(GetCurrentToken().Start, GetCurrentToken().End); + Skip(); + return evt; + } + + /// + /// Parse the productions: + /// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + /// *** * + /// + private ParsingEvent ParseFlowSequenceEntryMappingKey() + { + if (!(GetCurrentToken() is Value || GetCurrentToken() is FlowEntry || GetCurrentToken() is FlowSequenceEnd)) + { + states.Push(ParserState.FlowSequenceEntryMappingValue); + return ParseNode(false, false); + } + else + { + Mark mark = GetCurrentToken().End; + Skip(); + state = ParserState.FlowSequenceEntryMappingValue; + return ProcessEmptyScalar(mark); + } + } + + /// + /// Parse the productions: + /// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + /// ***** * + /// + private ParsingEvent ParseFlowSequenceEntryMappingValue() + { + if (GetCurrentToken() is Value) + { + Skip(); + if (!(GetCurrentToken() is FlowEntry || GetCurrentToken() is FlowSequenceEnd)) + { + states.Push(ParserState.FlowSequenceEntryMappingEnd); + return ParseNode(false, false); + } + } + state = ParserState.FlowSequenceEntryMappingEnd; + return ProcessEmptyScalar(GetCurrentToken().Start); + } + + /// + /// Parse the productions: + /// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + /// * + /// + private ParsingEvent ParseFlowSequenceEntryMappingEnd() + { + state = ParserState.FlowSequenceEntry; + return new Events.MappingEnd(GetCurrentToken().Start, GetCurrentToken().End); + } + + /// + /// Parse the productions: + /// flow_mapping ::= FLOW-MAPPING-START + /// ****************** + /// (flow_mapping_entry FLOW-ENTRY)* + /// * ********** + /// flow_mapping_entry? + /// ****************** + /// FLOW-MAPPING-END + /// **************** + /// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + /// * *** * + /// + private ParsingEvent ParseFlowMappingKey(bool isFirst) + { + if (isFirst) + { + GetCurrentToken(); + Skip(); + } + + if (!(GetCurrentToken() is FlowMappingEnd)) + { + if (!isFirst) + { + if (GetCurrentToken() is FlowEntry) + { + Skip(); + } + else + { + var current = GetCurrentToken(); + throw new SemanticErrorException(current.Start, current.End, "While parsing a flow mapping, did not find expected ',' or '}'."); + } + } + + if (GetCurrentToken() is Key) + { + Skip(); + + if (!(GetCurrentToken() is Value || GetCurrentToken() is FlowEntry || GetCurrentToken() is FlowMappingEnd)) + { + states.Push(ParserState.FlowMappingValue); + return ParseNode(false, false); + } + else + { + state = ParserState.FlowMappingValue; + return ProcessEmptyScalar(GetCurrentToken().Start); + } + } + else if (!(GetCurrentToken() is FlowMappingEnd)) + { + states.Push(ParserState.FlowMappingEmptyValue); + return ParseNode(false, false); + } + } + + state = states.Pop(); + ParsingEvent evt = new Events.MappingEnd(GetCurrentToken().Start, GetCurrentToken().End); + Skip(); + return evt; + } + + /// + /// Parse the productions: + /// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + /// * ***** * + /// + private ParsingEvent ParseFlowMappingValue(bool isEmpty) + { + if (isEmpty) + { + state = ParserState.FlowMappingKey; + return ProcessEmptyScalar(GetCurrentToken().Start); + } + + if (GetCurrentToken() is Value) + { + Skip(); + if (!(GetCurrentToken() is FlowEntry || GetCurrentToken() is FlowMappingEnd)) + { + states.Push(ParserState.FlowMappingKey); + return ParseNode(false, false); + } + } + + state = ParserState.FlowMappingKey; + return ProcessEmptyScalar(GetCurrentToken().Start); + } + + private class EventQueue + { + // This class is specialized for our specific use case where there are exactly two priority levels. + // If more levels are required, a more generic implementation should be used instead. + private readonly Queue highPriorityEvents = new Queue(); + private readonly Queue normalPriorityEvents = new Queue(); + + public void Enqueue(ParsingEvent @event) + { + switch (@event.Type) + { + case Events.EventType.StreamStart: + case Events.EventType.DocumentStart: + highPriorityEvents.Enqueue(@event); + break; + + default: + normalPriorityEvents.Enqueue(@event); + break; + } + } + + public ParsingEvent Dequeue() + { + return highPriorityEvents.Count > 0 + ? highPriorityEvents.Dequeue() + : normalPriorityEvents.Dequeue(); + } + + public int Count + { + get + { + return highPriorityEvents.Count + normalPriorityEvents.Count; + } + } + } + } +} diff --git a/YamlDotNet/Core/Parser.cs.meta b/YamlDotNet/Core/Parser.cs.meta new file mode 100644 index 0000000..38edd72 --- /dev/null +++ b/YamlDotNet/Core/Parser.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 26cca4bc9fdfb2d429b2181c273ab7b7 +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/ParserExtensions.cs b/YamlDotNet/Core/ParserExtensions.cs new file mode 100644 index 0000000..b9421d6 --- /dev/null +++ b/YamlDotNet/Core/ParserExtensions.cs @@ -0,0 +1,115 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System.Globalization; +using System.IO; +using YamlDotNet.Core.Events; + +namespace YamlDotNet.Core +{ + /// + /// Extension methods that provide useful abstractions over . + /// + public static class ParserExtensions + { + /// + /// Ensures that the current event is of the specified type, returns it and moves to the next event. + /// + /// Type of the . + /// Returns the current event. + /// If the current event is not of the specified type. + public static T Expect(this IParser parser) where T : ParsingEvent + { + var expectedEvent = parser.Allow(); + if (expectedEvent == null) + { + // TODO: Throw a better exception + var @event = parser.Current; + throw new YamlException(@event.Start, @event.End, string.Format(CultureInfo.InvariantCulture, + "Expected '{0}', got '{1}' (at {2}).", typeof(T).Name, @event.GetType().Name, @event.Start)); + } + return expectedEvent; + } + + /// + /// Checks whether the current event is of the specified type. + /// + /// Type of the event. + /// Returns true if the current event is of type . Otherwise returns false. + public static bool Accept(this IParser parser) where T : ParsingEvent + { + if(parser.Current == null) + { + if (!parser.MoveNext()) + { + throw new EndOfStreamException(); + } + } + return parser.Current is T; + } + + /// + /// 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. + /// + /// Type of the . + /// Returns the current event if it is of type T; otherwise returns null. + public static T Allow(this IParser parser) where T : ParsingEvent + { + if (!parser.Accept()) + { + return null; + } + var @event = (T)parser.Current; + parser.MoveNext(); + return @event; + } + + /// + /// Gets the next event without consuming it. + /// + /// Type of the . + /// Returns the current event if it is of type T; otherwise returns null. + public static T Peek(this IParser parser) where T : ParsingEvent + { + if (!parser.Accept()) + { + return null; + } + return (T)parser.Current; + } + + /// + /// Skips the current event and any nested event. + /// + public static void SkipThisAndNestedEvents(this IParser parser) + { + var depth = 0; + do + { + depth += parser.Peek().NestingIncrease; + parser.MoveNext(); + } + while (depth > 0); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/ParserExtensions.cs.meta b/YamlDotNet/Core/ParserExtensions.cs.meta new file mode 100644 index 0000000..b94f921 --- /dev/null +++ b/YamlDotNet/Core/ParserExtensions.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 66d3fba9b1372874692968ce91d5bdef +timeCreated: 1485601083 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/ParserState.cs b/YamlDotNet/Core/ParserState.cs new file mode 100644 index 0000000..52426b6 --- /dev/null +++ b/YamlDotNet/Core/ParserState.cs @@ -0,0 +1,51 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +namespace YamlDotNet.Core +{ + internal enum ParserState + { + StreamStart, + StreamEnd, + ImplicitDocumentStart, + DocumentStart, + DocumentContent, + DocumentEnd, + BlockNode, + BlockNodeOrIndentlessSequence, + FlowNode, + BlockSequenceFirstEntry, + BlockSequenceEntry, + IndentlessSequenceEntry, + BlockMappingFirstKey, + BlockMappingKey, + BlockMappingValue, + FlowSequenceFirstEntry, + FlowSequenceEntry, + FlowSequenceEntryMappingKey, + FlowSequenceEntryMappingValue, + FlowSequenceEntryMappingEnd, + FlowMappingFirstKey, + FlowMappingKey, + FlowMappingValue, + FlowMappingEmptyValue + } +} diff --git a/YamlDotNet/Core/ParserState.cs.meta b/YamlDotNet/Core/ParserState.cs.meta new file mode 100644 index 0000000..828e0f4 --- /dev/null +++ b/YamlDotNet/Core/ParserState.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 4c73f39f4ccd4a644bd851bffd5afa20 +timeCreated: 1427145264 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/RecursionLevel.cs b/YamlDotNet/Core/RecursionLevel.cs new file mode 100644 index 0000000..3555f08 --- /dev/null +++ b/YamlDotNet/Core/RecursionLevel.cs @@ -0,0 +1,80 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace YamlDotNet.Core +{ + /// + /// Keeps track of the recursion level, + /// and throws + /// whenever is reached. + /// + internal class RecursionLevel + { + private int current; + public int Maximum { get; private set; } + + public RecursionLevel(int maximum) + { + Maximum = maximum; + } + + /// + /// Increments the recursion level, + /// and throws + /// if is reached. + /// + public void Increment() + { + if (!TryIncrement()) + { + throw new MaximumRecursionLevelReachedException(); + } + } + + /// + /// Increments the recursion level, + /// and returns whether is still less than . + /// + public bool TryIncrement() + { + if (current < Maximum) + { + ++current; + return true; + } + return false; + } + + /// + /// Decrements the recursion level. + /// + public void Decrement() + { + if (current == 0) + { + throw new InvalidOperationException("Attempted to decrement RecursionLevel to a negative value"); + } + --current; + } + } +} diff --git a/YamlDotNet/Core/RecursionLevel.cs.meta b/YamlDotNet/Core/RecursionLevel.cs.meta new file mode 100644 index 0000000..2cb8d07 --- /dev/null +++ b/YamlDotNet/Core/RecursionLevel.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 1bfe84905c0dd5245908543c8cca9169 +timeCreated: 1485601082 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/ScalarStyle.cs b/YamlDotNet/Core/ScalarStyle.cs new file mode 100644 index 0000000..7f60578 --- /dev/null +++ b/YamlDotNet/Core/ScalarStyle.cs @@ -0,0 +1,61 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace YamlDotNet.Core +{ + /// + /// Specifies the style of a YAML scalar. + /// + public enum ScalarStyle + { + /// + /// Let the emitter choose the style. + /// + Any, + + /// + /// The plain scalar style. + /// + Plain, + + /// + /// The single-quoted scalar style. + /// + SingleQuoted, + + /// + /// The double-quoted scalar style. + /// + DoubleQuoted, + + /// + /// The literal scalar style. + /// + Literal, + + /// + /// The folded scalar style. + /// + Folded, + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/ScalarStyle.cs.meta b/YamlDotNet/Core/ScalarStyle.cs.meta new file mode 100644 index 0000000..648da81 --- /dev/null +++ b/YamlDotNet/Core/ScalarStyle.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d8499f656f1f893409f937b46c386cf2 +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Scanner.cs b/YamlDotNet/Core/Scanner.cs new file mode 100644 index 0000000..3532d43 --- /dev/null +++ b/YamlDotNet/Core/Scanner.cs @@ -0,0 +1,2365 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Text; +using YamlDotNet.Core.Tokens; + +namespace YamlDotNet.Core +{ + /// + /// Converts a sequence of characters into a sequence of YAML tokens. + /// + [Serializable] + public class Scanner : IScanner + { + private const int MaxVersionNumberLength = 9; + private const int MaxBufferLength = 8; + + private static readonly IDictionary simpleEscapeCodes = new SortedDictionary + { + { '0', '\0' }, + { 'a', '\x07' }, + { 'b', '\x08' }, + { 't', '\x09' }, + { '\t', '\x09' }, + { 'n', '\x0A' }, + { 'v', '\x0B' }, + { 'f', '\x0C' }, + { 'r', '\x0D' }, + { 'e', '\x1B' }, + { ' ', '\x20' }, + { '"', '"' }, + { '\'', '\'' }, + { '\\', '\\' }, + { 'N', '\x85' }, + { '_', '\xA0' }, + { 'L', '\x2028' }, + { 'P', '\x2029' } + }; + + private readonly Stack indents = new Stack(); + private readonly InsertionQueue tokens = new InsertionQueue(); + private readonly Stack simpleKeys = new Stack(); + private readonly CharacterAnalyzer analyzer; + + private readonly Cursor cursor; + private bool streamStartProduced; + private bool streamEndProduced; + private int indent = -1; + private bool simpleKeyAllowed; + private int flowLevel; + private int tokensParsed; + private bool tokenAvailable; + private Token previous; + + public bool SkipComments { get; private set; } + + /// + /// Gets the current token. + /// + public Token Current { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The input. + /// Indicates whether comments should be ignored + public Scanner(TextReader input, bool skipComments = true) + { + analyzer = new CharacterAnalyzer(new LookAheadBuffer(input, MaxBufferLength)); + cursor = new Cursor(); + SkipComments = skipComments; + } + + /// + /// Gets the current position inside the input stream. + /// + /// The current position. + public Mark CurrentPosition + { + get + { + return cursor.Mark(); + } + } + + /// + /// Moves to the next token. + /// + /// + public bool MoveNext() + { + if (Current != null) + { + ConsumeCurrent(); + } + + return MoveNextWithoutConsuming(); + } + + public bool MoveNextWithoutConsuming() + { + if (!tokenAvailable && !streamEndProduced) + { + FetchMoreTokens(); + } + if (tokens.Count > 0) + { + Current = tokens.Dequeue(); + tokenAvailable = false; + return true; + } + else + { + Current = null; + return false; + } + } + + /// + /// Consumes the current token and increments the parsed token count + /// + public void ConsumeCurrent() + { + ++tokensParsed; + tokenAvailable = false; + previous = Current; + Current = null; + } + + private char ReadCurrentCharacter() + { + var currentCharacter = analyzer.Peek(0); + Skip(); + return currentCharacter; + } + + private char ReadLine() + { + if (analyzer.Check("\r\n\x85")) // CR LF -> LF --- CR|LF|NEL -> LF + { + SkipLine(); + return '\n'; + } + + var nextChar = analyzer.Peek(0); // LS|PS -> LS|PS + SkipLine(); + return nextChar; + } + + private void FetchMoreTokens() + { + // While we need more tokens to fetch, do it. + + while (true) + { + // Check if we really need to fetch more tokens. + + bool needsMoreTokens = false; + + if (tokens.Count == 0) + { + // Queue is empty. + + needsMoreTokens = true; + } + else + { + // Check if any potential simple key may occupy the head position. + + StaleSimpleKeys(); + + foreach (var simpleKey in simpleKeys) + { + if (simpleKey.IsPossible && simpleKey.TokenNumber == tokensParsed) + { + needsMoreTokens = true; + break; + } + } + } + + // We are finished. + if (!needsMoreTokens) + { + break; + } + + // Fetch the next token. + + FetchNextToken(); + } + tokenAvailable = true; + } + + private static bool StartsWith(StringBuilder what, char start) + { + return what.Length > 0 && what[0] == start; + } + + /// + /// Check the list of potential simple keys and remove the positions that + /// cannot contain simple keys anymore. + /// + + private void StaleSimpleKeys() + { + // Check for a potential simple key for each flow level. + + foreach (var key in simpleKeys) + { + + // The specification requires that a simple key + + // - is limited to a single line, + // - is shorter than 1024 characters. + + + if (key.IsPossible && (key.Line < cursor.Line || key.Index + 1024 < cursor.Index)) + { + + // Check if the potential simple key to be removed is required. + + if (key.IsRequired) + { + var mark = cursor.Mark(); + throw new SyntaxErrorException(mark, mark, "While scanning a simple key, could not find expected ':'."); + } + + key.IsPossible = false; + } + } + } + + private void FetchNextToken() + { + // Check if we just started scanning. Fetch STREAM-START then. + + if (!streamStartProduced) + { + FetchStreamStart(); + return; + } + + // Eat whitespaces and comments until we reach the next token. + + ScanToNextToken(); + + // Remove obsolete potential simple keys. + + StaleSimpleKeys(); + + // Check the indentation level against the current column. + + UnrollIndent(cursor.LineOffset); + + + // Ensure that the buffer contains at least 4 characters. 4 is the length + // of the longest indicators ('--- ' and '... '). + + + analyzer.Buffer.Cache(4); + + // Is it the end of the stream? + + if (analyzer.Buffer.EndOfInput) + { + FetchStreamEnd(); + return; + } + + // Is it a directive? + + if (cursor.LineOffset == 0 && analyzer.Check('%')) + { + FetchDirective(); + return; + } + + // Is it the document start indicator? + + bool isDocumentStart = + cursor.LineOffset == 0 && + analyzer.Check('-', 0) && + analyzer.Check('-', 1) && + analyzer.Check('-', 2) && + analyzer.IsWhiteBreakOrZero(3); + + if (isDocumentStart) + { + FetchDocumentIndicator(true); + return; + } + + // Is it the document end indicator? + + bool isDocumentEnd = + cursor.LineOffset == 0 && + analyzer.Check('.', 0) && + analyzer.Check('.', 1) && + analyzer.Check('.', 2) && + analyzer.IsWhiteBreakOrZero(3); + + if (isDocumentEnd) + { + FetchDocumentIndicator(false); + return; + } + + // Is it the flow sequence start indicator? + + if (analyzer.Check('[')) + { + FetchFlowCollectionStart(true); + return; + } + + // Is it the flow mapping start indicator? + + if (analyzer.Check('{')) + { + FetchFlowCollectionStart(false); + return; + } + + // Is it the flow sequence end indicator? + + if (analyzer.Check(']')) + { + FetchFlowCollectionEnd(true); + return; + } + + // Is it the flow mapping end indicator? + + if (analyzer.Check('}')) + { + FetchFlowCollectionEnd(false); + return; + } + + // Is it the flow entry indicator? + + if (analyzer.Check(',')) + { + FetchFlowEntry(); + return; + } + + // Is it the block entry indicator? + + if (analyzer.Check('-') && analyzer.IsWhiteBreakOrZero(1)) + { + FetchBlockEntry(); + return; + } + + // Is it the key indicator? + + if (analyzer.Check('?') && (flowLevel > 0 || analyzer.IsWhiteBreakOrZero(1))) + { + FetchKey(); + return; + } + + // Is it the value indicator? + + if (analyzer.Check(':') && (flowLevel > 0 || analyzer.IsWhiteBreakOrZero(1))) + { + FetchValue(); + return; + } + + // Is it an alias? + + if (analyzer.Check('*')) + { + FetchAnchor(true); + return; + } + + // Is it an anchor? + + if (analyzer.Check('&')) + { + FetchAnchor(false); + return; + } + + // Is it a tag? + + if (analyzer.Check('!')) + { + FetchTag(); + return; + } + + // Is it a literal scalar? + + if (analyzer.Check('|') && flowLevel == 0) + { + FetchBlockScalar(true); + return; + } + + // Is it a folded scalar? + + if (analyzer.Check('>') && flowLevel == 0) + { + FetchBlockScalar(false); + return; + } + + // Is it a single-quoted scalar? + + if (analyzer.Check('\'')) + { + FetchFlowScalar(true); + return; + } + + // Is it a double-quoted scalar? + + if (analyzer.Check('"')) + { + FetchFlowScalar(false); + return; + } + + + // Is it a plain scalar? + + // A plain scalar may start with any non-blank characters except + + // '-', '?', ':', ',', '[', ']', '{', '}', + // '#', '&', '*', '!', '|', '>', '\'', '\"', + // '%', '@', '`'. + + // In the block context (and, for the '-' indicator, in the flow context + // too), it may also start with the characters + + // '-', '?', ':' + + // if it is followed by a non-space character. + + // The last rule is more restrictive than the specification requires. + + + bool isInvalidPlainScalarCharacter = analyzer.IsWhiteBreakOrZero() || analyzer.Check("-?:,[]{}#&*!|>'\"%@`"); + + bool isPlainScalar = + !isInvalidPlainScalarCharacter || + (analyzer.Check('-') && !analyzer.IsWhite(1)) || + (flowLevel == 0 && (analyzer.Check("?:")) && !analyzer.IsWhiteBreakOrZero(1)); + + if (isPlainScalar) + { + FetchPlainScalar(); + return; + } + + // If we don't determine the token type so far, it is an error. + var start = cursor.Mark(); + Skip(); + var end = cursor.Mark(); + + throw new SyntaxErrorException(start, end, "While scanning for the next token, find character that cannot start any token."); + } + + private bool CheckWhiteSpace() + { + return analyzer.Check(' ') || ((flowLevel > 0 || !simpleKeyAllowed) && analyzer.Check('\t')); + } + + private bool IsDocumentIndicator() + { + if (cursor.LineOffset == 0 && analyzer.IsWhiteBreakOrZero(3)) + { + bool isDocumentStart = analyzer.Check('-', 0) && analyzer.Check('-', 1) && analyzer.Check('-', 2); + bool isDocumentEnd = analyzer.Check('.', 0) && analyzer.Check('.', 1) && analyzer.Check('.', 2); + + return isDocumentStart || isDocumentEnd; + } + else + { + return false; + } + } + + private void Skip() + { + cursor.Skip(); + analyzer.Buffer.Skip(1); + } + + private void SkipLine() + { + if (analyzer.IsCrLf()) + { + cursor.SkipLineByOffset(2); + analyzer.Buffer.Skip(2); + } + else if (analyzer.IsBreak()) + { + cursor.SkipLineByOffset(1); + analyzer.Buffer.Skip(1); + } + else if (!analyzer.IsZero()) + { + throw new InvalidOperationException("Not at a break."); + } + } + + private void ScanToNextToken() + { + // Until the next token is not find. + + for (;;) + { + + // Eat whitespaces. + + // Tabs are allowed: + + // - in the flow context; + // - in the block context, but not at the beginning of the line or + // after '-', '?', or ':' (complex value). + + + while (CheckWhiteSpace()) + { + Skip(); + } + + ProcessComment(); + + // If it is a line break, eat it. + + if (analyzer.IsBreak()) + { + SkipLine(); + + // In the block context, a new line may start a simple key. + + if (flowLevel == 0) + { + simpleKeyAllowed = true; + } + } + else + { + // We have find a token. + + break; + } + } + } + + private void ProcessComment() + { + if (analyzer.Check('#')) + { + var start = cursor.Mark(); + + // Eat '#' + Skip(); + + // Eat leading whitespace + while (analyzer.IsSpace()) + { + Skip(); + } + + var text = new StringBuilder(); + while (!analyzer.IsBreakOrZero()) + { + text.Append(ReadCurrentCharacter()); + } + + if (!SkipComments) + { + var isInline = previous != null + && previous.End.Line == start.Line + && !(previous is StreamStart); + + tokens.Enqueue(new Comment(text.ToString(), isInline, start, cursor.Mark())); + } + } + } + + private void FetchStreamStart() + { + // Initialize the simple key stack. + + simpleKeys.Push(new SimpleKey()); + + // A simple key is allowed at the beginning of the stream. + + simpleKeyAllowed = true; + + // We have started. + + streamStartProduced = true; + + // Create the STREAM-START token and append it to the queue. + + var mark = cursor.Mark(); + tokens.Enqueue(new StreamStart(mark, mark)); + } + + /// + /// Pop indentation levels from the indents stack until the current level + /// becomes less or equal to the column. For each intendation level, append + /// the BLOCK-END token. + /// + + private void UnrollIndent(int column) + { + // In the flow context, do nothing. + + if (flowLevel != 0) + { + return; + } + + // Loop through the intendation levels in the stack. + + while (indent > column) + { + // Create a token and append it to the queue. + + var mark = cursor.Mark(); + tokens.Enqueue(new BlockEnd(mark, mark)); + + // Pop the indentation level. + + indent = indents.Pop(); + } + } + + /// + /// Produce the STREAM-END token and shut down the scanner. + /// + private void FetchStreamEnd() + { + cursor.ForceSkipLineAfterNonBreak(); + + // Reset the indentation level. + + UnrollIndent(-1); + + // Reset simple keys. + + RemoveSimpleKey(); + + simpleKeyAllowed = false; + + // Create the STREAM-END token and append it to the queue. + + streamEndProduced = true; + var mark = cursor.Mark(); + tokens.Enqueue(new StreamEnd(mark, mark)); + } + + private void FetchDirective() + { + // Reset the indentation level. + + UnrollIndent(-1); + + // Reset simple keys. + + RemoveSimpleKey(); + + simpleKeyAllowed = false; + + // Create the YAML-DIRECTIVE or TAG-DIRECTIVE token. + + var token = ScanDirective(); + + // Append the token to the queue. + + tokens.Enqueue(token); + } + + /// + /// Scan a YAML-DIRECTIVE or TAG-DIRECTIVE token. + /// + /// Scope: + /// %YAML 1.1 # a comment \n + /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + /// %TAG !yaml! tag:yaml.org,2002: \n + /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + /// + private Token ScanDirective() + { + // Eat '%'. + + var start = cursor.Mark(); + + Skip(); + + // Scan the directive name. + + var name = ScanDirectiveName(start); + + // Is it a YAML directive? + + Token directive; + switch (name) + { + case "YAML": + directive = ScanVersionDirectiveValue(start); + break; + + case "TAG": + directive = ScanTagDirectiveValue(start); + break; + + default: + throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a directive, find uknown directive name."); + } + + // Eat the rest of the line including any comments. + + while (analyzer.IsWhite()) + { + Skip(); + } + + ProcessComment(); + + // Check if we are at the end of the line. + + if (!analyzer.IsBreakOrZero()) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a directive, did not find expected comment or line break."); + } + + // Eat a line break. + + if (analyzer.IsBreak()) + { + SkipLine(); + } + + return directive; + } + + /// + /// Produce the DOCUMENT-START or DOCUMENT-END token. + /// + + private void FetchDocumentIndicator(bool isStartToken) + { + // Reset the indentation level. + + UnrollIndent(-1); + + // Reset simple keys. + + RemoveSimpleKey(); + + simpleKeyAllowed = false; + + // Consume the token. + + var start = cursor.Mark(); + + Skip(); + Skip(); + Skip(); + + Token token = isStartToken ? (Token)new DocumentStart(start, cursor.Mark()) : new DocumentEnd(start, start); + tokens.Enqueue(token); + } + + /// + /// Produce the FLOW-SEQUENCE-START or FLOW-MAPPING-START token. + /// + + private void FetchFlowCollectionStart(bool isSequenceToken) + { + // The indicators '[' and '{' may start a simple key. + + SaveSimpleKey(); + + // Increase the flow level. + + IncreaseFlowLevel(); + + // A simple key may follow the indicators '[' and '{'. + + simpleKeyAllowed = true; + + // Consume the token. + + var start = cursor.Mark(); + Skip(); + + // Create the FLOW-SEQUENCE-START of FLOW-MAPPING-START token. + + Token token; + if (isSequenceToken) + { + token = new FlowSequenceStart(start, start); + } + else + { + token = new FlowMappingStart(start, start); + } + + tokens.Enqueue(token); + } + + /// + /// Increase the flow level and resize the simple key list if needed. + /// + + private void IncreaseFlowLevel() + { + // Reset the simple key on the next level. + + simpleKeys.Push(new SimpleKey()); + + // Increase the flow level. + + ++flowLevel; + } + + /// + /// Produce the FLOW-SEQUENCE-END or FLOW-MAPPING-END token. + /// + + private void FetchFlowCollectionEnd(bool isSequenceToken) + { + // Reset any potential simple key on the current flow level. + + RemoveSimpleKey(); + + // Decrease the flow level. + + DecreaseFlowLevel(); + + // No simple keys after the indicators ']' and '}'. + + simpleKeyAllowed = false; + + // Consume the token. + + var start = cursor.Mark(); + Skip(); + + Token token; + if (isSequenceToken) + { + token = new FlowSequenceEnd(start, start); + } + else + { + token = new FlowMappingEnd(start, start); + } + + tokens.Enqueue(token); + } + + /// + /// Decrease the flow level. + /// + + private void DecreaseFlowLevel() + { + Debug.Assert(flowLevel > 0, "Could flowLevel be zero when this method is called?"); + if (flowLevel > 0) + { + --flowLevel; + simpleKeys.Pop(); + } + } + + /// + /// Produce the FLOW-ENTRY token. + /// + + private void FetchFlowEntry() + { + // Reset any potential simple keys on the current flow level. + + RemoveSimpleKey(); + + // Simple keys are allowed after ','. + + simpleKeyAllowed = true; + + // Consume the token. + + var start = cursor.Mark(); + Skip(); + + // Create the FLOW-ENTRY token and append it to the queue. + + tokens.Enqueue(new FlowEntry(start, cursor.Mark())); + } + + /// + /// Produce the BLOCK-ENTRY token. + /// + + private void FetchBlockEntry() + { + // Check if the scanner is in the block context. + + if (flowLevel == 0) + { + // Check if we are allowed to start a new entry. + + if (!simpleKeyAllowed) + { + var mark = cursor.Mark(); + throw new SyntaxErrorException(mark, mark, "Block sequence entries are not allowed in this context."); + } + + // Add the BLOCK-SEQUENCE-START token if needed. + RollIndent(cursor.LineOffset, -1, true, cursor.Mark()); + } + else + { + + // It is an error for the '-' indicator to occur in the flow context, + // but we let the Parser detect and report about it because the Parser + // is able to point to the context. + + } + + // Reset any potential simple keys on the current flow level. + + RemoveSimpleKey(); + + // Simple keys are allowed after '-'. + + simpleKeyAllowed = true; + + // Consume the token. + + var start = cursor.Mark(); + Skip(); + + // Create the BLOCK-ENTRY token and append it to the queue. + + tokens.Enqueue(new BlockEntry(start, cursor.Mark())); + } + + /// + /// Produce the KEY token. + /// + + private void FetchKey() + { + // In the block context, additional checks are required. + + if (flowLevel == 0) + { + // Check if we are allowed to start a new key (not nessesary simple). + + if (!simpleKeyAllowed) + { + var mark = cursor.Mark(); + throw new SyntaxErrorException(mark, mark, "Mapping keys are not allowed in this context."); + } + + // Add the BLOCK-MAPPING-START token if needed. + + RollIndent(cursor.LineOffset, -1, false, cursor.Mark()); + } + + // Reset any potential simple keys on the current flow level. + + RemoveSimpleKey(); + + // Simple keys are allowed after '?' in the block context. + + simpleKeyAllowed = flowLevel == 0; + + // Consume the token. + + var start = cursor.Mark(); + Skip(); + + // Create the KEY token and append it to the queue. + + tokens.Enqueue(new Key(start, cursor.Mark())); + } + + /// + /// Produce the VALUE token. + /// + + private void FetchValue() + { + var simpleKey = simpleKeys.Peek(); + + // Have we find a simple key? + + if (simpleKey.IsPossible) + { + // Create the KEY token and insert it into the queue. + + tokens.Insert(simpleKey.TokenNumber - tokensParsed, new Key(simpleKey.Mark, simpleKey.Mark)); + + // In the block context, we may need to add the BLOCK-MAPPING-START token. + + RollIndent(simpleKey.LineOffset, simpleKey.TokenNumber, false, simpleKey.Mark); + + // Remove the simple key. + + simpleKey.IsPossible = false; + + // A simple key cannot follow another simple key. + + simpleKeyAllowed = false; + } + else + { + // The ':' indicator follows a complex key. + + // In the block context, extra checks are required. + + if (flowLevel == 0) + { + // Check if we are allowed to start a complex value. + + if (!simpleKeyAllowed) + { + var mark = cursor.Mark(); + throw new SyntaxErrorException(mark, mark, "Mapping values are not allowed in this context."); + } + + // Add the BLOCK-MAPPING-START token if needed. + + RollIndent(cursor.LineOffset, -1, false, cursor.Mark()); + } + + // Simple keys after ':' are allowed in the block context. + + simpleKeyAllowed = flowLevel == 0; + } + + // Consume the token. + + var start = cursor.Mark(); + Skip(); + + // Create the VALUE token and append it to the queue. + + tokens.Enqueue(new Value(start, cursor.Mark())); + } + + /// + /// Push the current indentation level to the stack and set the new level + /// the current column is greater than the indentation level. In this case, + /// append or insert the specified token into the token queue. + /// + private void RollIndent(int column, int number, bool isSequence, Mark position) + { + // In the flow context, do nothing. + + if (flowLevel > 0) + { + return; + } + + if (indent < column) + { + + // Push the current indentation level to the stack and set the new + // indentation level. + + + indents.Push(indent); + + indent = column; + + // Create a token and insert it into the queue. + + Token token; + if (isSequence) + { + token = new BlockSequenceStart(position, position); + } + else + { + token = new BlockMappingStart(position, position); + } + + if (number == -1) + { + tokens.Enqueue(token); + } + else + { + tokens.Insert(number - tokensParsed, token); + } + } + } + + /// + /// Produce the ALIAS or ANCHOR token. + /// + + private void FetchAnchor(bool isAlias) + { + // An anchor or an alias could be a simple key. + + SaveSimpleKey(); + + // A simple key cannot follow an anchor or an alias. + + simpleKeyAllowed = false; + + // Create the ALIAS or ANCHOR token and append it to the queue. + + tokens.Enqueue(ScanAnchor(isAlias)); + } + + private Token ScanAnchor(bool isAlias) + { + // Eat the indicator character. + + var start = cursor.Mark(); + + Skip(); + + // Consume the value. + + var value = new StringBuilder(); + while (analyzer.IsAlphaNumericDashOrUnderscore()) + { + value.Append(ReadCurrentCharacter()); + } + + + // Check if length of the anchor is greater than 0 and it is followed by + // a whitespace character or one of the indicators: + + // '?', ':', ',', ']', '}', '%', '@', '`'. + + + if (value.Length == 0 || !(analyzer.IsWhiteBreakOrZero() || analyzer.Check("?:,]}%@`"))) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While scanning an anchor or alias, did not find expected alphabetic or numeric character."); + } + + // Create a token. + + if (isAlias) + { + return new AnchorAlias(value.ToString(), start, cursor.Mark()); + } + else + { + return new Anchor(value.ToString(), start, cursor.Mark()); + } + } + + /// + /// Produce the TAG token. + /// + + private void FetchTag() + { + // A tag could be a simple key. + + SaveSimpleKey(); + + // A simple key cannot follow a tag. + + simpleKeyAllowed = false; + + // Create the TAG token and append it to the queue. + + tokens.Enqueue(ScanTag()); + } + + /// + /// Scan a TAG token. + /// + + Token ScanTag() + { + var start = cursor.Mark(); + + // Check if the tag is in the canonical form. + + string handle; + string suffix; + + if (analyzer.Check('<', 1)) + { + // Set the handle to '' + + handle = string.Empty; + + // Eat '!<' + + Skip(); + Skip(); + + // Consume the tag value. + + suffix = ScanTagUri(null, start); + + // Check for '>' and eat it. + + if (!analyzer.Check('>')) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a tag, did not find the expected '>'."); + } + + Skip(); + } + else + { + // The tag has either the '!suffix' or the '!handle!suffix' form. + + // First, try to scan a handle. + + var firstPart = ScanTagHandle(false, start); + + // Check if it is, indeed, handle. + + if (firstPart.Length > 1 && firstPart[0] == '!' && firstPart[firstPart.Length - 1] == '!') + { + handle = firstPart; + + // Scan the suffix now. + + suffix = ScanTagUri(null, start); + } + else + { + // It wasn't a handle after all. Scan the rest of the tag. + + suffix = ScanTagUri(firstPart, start); + + // Set the handle to '!'. + + handle = "!"; + + + // A special case: the '!' tag. Set the handle to '' and the + // suffix to '!'. + + + if (suffix.Length == 0) + { + suffix = handle; + handle = string.Empty; + } + } + } + + // Check the character which ends the tag. + + if (!analyzer.IsWhiteBreakOrZero()) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a tag, did not find expected whitespace or line break."); + } + + // Create a token. + + return new Tag(handle, suffix, start, cursor.Mark()); + } + + /// + /// Produce the SCALAR(...,literal) or SCALAR(...,folded) tokens. + /// + + private void FetchBlockScalar(bool isLiteral) + { + // Remove any potential simple keys. + + RemoveSimpleKey(); + + // A simple key may follow a block scalar. + + simpleKeyAllowed = true; + + // Create the SCALAR token and append it to the queue. + + tokens.Enqueue(ScanBlockScalar(isLiteral)); + } + + /// + /// Scan a block scalar. + /// + + Token ScanBlockScalar(bool isLiteral) + { + var value = new StringBuilder(); + var leadingBreak = new StringBuilder(); + var trailingBreaks = new StringBuilder(); + + int chomping = 0; + int increment = 0; + int currentIndent = 0; + bool leadingBlank = false; + + // Eat the indicator '|' or '>'. + + var start = cursor.Mark(); + + Skip(); + + // Check for a chomping indicator. + + if (analyzer.Check("+-")) + { + // Set the chomping method and eat the indicator. + + chomping = analyzer.Check('+') ? +1 : -1; + + Skip(); + + // Check for an indentation indicator. + + if (analyzer.IsDigit()) + { + // Check that the intendation is greater than 0. + + if (analyzer.Check('0')) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a block scalar, find an intendation indicator equal to 0."); + } + + // Get the intendation level and eat the indicator. + + increment = analyzer.AsDigit(); + + Skip(); + } + } + + // Do the same as above, but in the opposite order. + + else if (analyzer.IsDigit()) + { + if (analyzer.Check('0')) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a block scalar, find an intendation indicator equal to 0."); + } + + increment = analyzer.AsDigit(); + + Skip(); + + if (analyzer.Check("+-")) + { + chomping = analyzer.Check('+') ? +1 : -1; + + Skip(); + } + } + + // Eat whitespaces and comments to the end of the line. + + while (analyzer.IsWhite()) + { + Skip(); + } + + ProcessComment(); + + // Check if we are at the end of the line. + + if (!analyzer.IsBreakOrZero()) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a block scalar, did not find expected comment or line break."); + } + + // Eat a line break. + + if (analyzer.IsBreak()) + { + SkipLine(); + } + + var end = cursor.Mark(); + + // Set the intendation level if it was specified. + + if (increment != 0) + { + currentIndent = indent >= 0 ? indent + increment : increment; + } + + // Scan the leading line breaks and determine the indentation level if needed. + + currentIndent = ScanBlockScalarBreaks(currentIndent, trailingBreaks, start, ref end); + + // Scan the block scalar content. + + while (cursor.LineOffset == currentIndent && !analyzer.IsZero()) + { + + // We are at the beginning of a non-empty line. + + + // Is it a trailing whitespace? + + var trailingBlank = analyzer.IsWhite(); + + // Check if we need to fold the leading line break. + + if (!isLiteral && StartsWith(leadingBreak, '\n') && !leadingBlank && !trailingBlank) + { + // Do we need to join the lines by space? + + if (trailingBreaks.Length == 0) + { + value.Append(' '); + } + + leadingBreak.Length = 0; + } + else + { + value.Append(leadingBreak.ToString()); + leadingBreak.Length = 0; + } + + // Append the remaining line breaks. + + value.Append(trailingBreaks.ToString()); + trailingBreaks.Length = 0; + + // Is it a leading whitespace? + + leadingBlank = analyzer.IsWhite(); + + // Consume the current line. + + while (!analyzer.IsBreakOrZero()) + { + value.Append(ReadCurrentCharacter()); + } + + // Consume the line break. + var lineBreak = ReadLine(); + if (lineBreak != '\0') + { + leadingBreak.Append(lineBreak); + } + + // Eat the following intendation spaces and line breaks. + + currentIndent = ScanBlockScalarBreaks(currentIndent, trailingBreaks, start, ref end); + } + + // Chomp the tail. + + if (chomping != -1) + { + value.Append(leadingBreak); + } + if (chomping == 1) + { + value.Append(trailingBreaks); + } + + // Create a token. + + ScalarStyle style = isLiteral ? ScalarStyle.Literal : ScalarStyle.Folded; + return new Scalar(value.ToString(), style, start, end); + } + + /// + /// Scan intendation spaces and line breaks for a block scalar. Determine the + /// intendation level if needed. + /// + + private int ScanBlockScalarBreaks(int currentIndent, StringBuilder breaks, Mark start, ref Mark end) + { + int maxIndent = 0; + + end = cursor.Mark(); + + // Eat the intendation spaces and line breaks. + + for (;;) + { + // Eat the intendation spaces. + + while ((currentIndent == 0 || cursor.LineOffset < currentIndent) && analyzer.IsSpace()) + { + Skip(); + } + + if (cursor.LineOffset > maxIndent) + { + maxIndent = cursor.LineOffset; + } + + // Check for a tab character messing the intendation. + + if ((currentIndent == 0 || cursor.LineOffset < currentIndent) && analyzer.IsTab()) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a block scalar, find a tab character where an intendation space is expected."); + } + + // Have we find a non-empty line? + + if (!analyzer.IsBreak()) + { + break; + } + + // Consume the line break. + + breaks.Append(ReadLine()); + + end = cursor.Mark(); + } + + // Determine the indentation level if needed. + + if (currentIndent == 0) + { + currentIndent = Math.Max(maxIndent, Math.Max(indent + 1, 1)); + } + + return currentIndent; + } + + /// + /// Produce the SCALAR(...,single-quoted) or SCALAR(...,double-quoted) tokens. + /// + + private void FetchFlowScalar(bool isSingleQuoted) + { + // A plain scalar could be a simple key. + + SaveSimpleKey(); + + // A simple key cannot follow a flow scalar. + + simpleKeyAllowed = false; + + // Create the SCALAR token and append it to the queue. + + tokens.Enqueue(ScanFlowScalar(isSingleQuoted)); + } + + /// + /// Scan a quoted scalar. + /// + + private Token ScanFlowScalar(bool isSingleQuoted) + { + // Eat the left quote. + + var start = cursor.Mark(); + + Skip(); + + // Consume the content of the quoted scalar. + + var value = new StringBuilder(); + var whitespaces = new StringBuilder(); + var leadingBreak = new StringBuilder(); + var trailingBreaks = new StringBuilder(); + for (;;) + { + // Check that there are no document indicators at the beginning of the line. + + if (IsDocumentIndicator()) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a quoted scalar, find unexpected document indicator."); + } + + // Check for EOF. + + if (analyzer.IsZero()) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a quoted scalar, find unexpected end of stream."); + } + + // Consume non-blank characters. + + bool hasLeadingBlanks = false; + + while (!analyzer.IsWhiteBreakOrZero()) + { + // Check for an escaped single quote. + + if (isSingleQuoted && analyzer.Check('\'', 0) && analyzer.Check('\'', 1)) + { + value.Append('\''); + Skip(); + Skip(); + } + + // Check for the right quote. + + else if (analyzer.Check(isSingleQuoted ? '\'' : '"')) + { + break; + } + + // Check for an escaped line break. + + else if (!isSingleQuoted && analyzer.Check('\\') && analyzer.IsBreak(1)) + { + Skip(); + SkipLine(); + hasLeadingBlanks = true; + break; + } + + // Check for an escape sequence. + + else if (!isSingleQuoted && analyzer.Check('\\')) + { + int codeLength = 0; + + // Check the escape character. + + var escapeCharacter = analyzer.Peek(1); + switch (escapeCharacter) + { + case 'x': + codeLength = 2; + break; + + case 'u': + codeLength = 4; + break; + + case 'U': + codeLength = 8; + break; + + default: + char unescapedCharacter; + if (simpleEscapeCodes.TryGetValue(escapeCharacter, out unescapedCharacter)) + { + value.Append(unescapedCharacter); + } + else + { + throw new SyntaxErrorException(start, cursor.Mark(), "While parsing a quoted scalar, find unknown escape character."); + } + break; + } + + Skip(); + Skip(); + + // Consume an arbitrary escape code. + + if (codeLength > 0) + { + int character = 0; + + // Scan the character value. + + for (int k = 0; k < codeLength; ++k) + { + if (!analyzer.IsHex(k)) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While parsing a quoted scalar, did not find expected hexdecimal number."); + } + character = ((character << 4) + analyzer.AsHex(k)); + } + + // Check the value and write the character. + + if ((character >= 0xD800 && character <= 0xDFFF) || character > 0x10FFFF) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While parsing a quoted scalar, find invalid Unicode character escape code."); + } + + value.Append(char.ConvertFromUtf32(character)); + + // Advance the pointer. + + for (int k = 0; k < codeLength; ++k) + { + Skip(); + } + } + } + else + { + // It is a non-escaped non-blank character. + + value.Append(ReadCurrentCharacter()); + } + } + + // Check if we are at the end of the scalar. + + if (analyzer.Check(isSingleQuoted ? '\'' : '"')) + break; + + // Consume blank characters. + + while (analyzer.IsWhite() || analyzer.IsBreak()) + { + if (analyzer.IsWhite()) + { + // Consume a space or a tab character. + + if (!hasLeadingBlanks) + { + whitespaces.Append(ReadCurrentCharacter()); + } + else + { + Skip(); + } + } + else + { + // Check if it is a first line break. + + if (!hasLeadingBlanks) + { + whitespaces.Length = 0; + leadingBreak.Append(ReadLine()); + hasLeadingBlanks = true; + } + else + { + trailingBreaks.Append(ReadLine()); + } + } + } + + // Join the whitespaces or fold line breaks. + + if (hasLeadingBlanks) + { + // Do we need to fold line breaks? + + if (StartsWith(leadingBreak, '\n')) + { + if (trailingBreaks.Length == 0) + { + value.Append(' '); + } + else + { + value.Append(trailingBreaks.ToString()); + } + } + else + { + value.Append(leadingBreak.ToString()); + value.Append(trailingBreaks.ToString()); + } + leadingBreak.Length = 0; + trailingBreaks.Length = 0; + } + else + { + value.Append(whitespaces.ToString()); + whitespaces.Length = 0; + } + } + + // Eat the right quote. + + Skip(); + + return new Scalar(value.ToString(), isSingleQuoted ? ScalarStyle.SingleQuoted : ScalarStyle.DoubleQuoted, start, cursor.Mark()); + } + + /// + /// Produce the SCALAR(...,plain) token. + /// + + private void FetchPlainScalar() + { + // A plain scalar could be a simple key. + + SaveSimpleKey(); + + // A simple key cannot follow a flow scalar. + + simpleKeyAllowed = false; + + // Create the SCALAR token and append it to the queue. + + tokens.Enqueue(ScanPlainScalar()); + } + + /// + /// Scan a plain scalar. + /// + + private Token ScanPlainScalar() + { + var value = new StringBuilder(); + var whitespaces = new StringBuilder(); + var leadingBreak = new StringBuilder(); + var trailingBreaks = new StringBuilder(); + + bool hasLeadingBlanks = false; + int currentIndent = indent + 1; + + var start = cursor.Mark(); + var end = start; + + // Consume the content of the plain scalar. + + for (;;) + { + // Check for a document indicator. + + if (IsDocumentIndicator()) + { + break; + } + + // Check for a comment. + + if (analyzer.Check('#')) + { + break; + } + + // Consume non-blank characters. + while (!analyzer.IsWhiteBreakOrZero()) + { + // Check for 'x:x' in the flow context. TODO: Fix the test "spec-08-13". + + if (flowLevel > 0 && analyzer.Check(':') && !analyzer.IsWhiteBreakOrZero(1)) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a plain scalar, find unexpected ':'."); + } + + // Check for indicators that may end a plain scalar. + + if ((analyzer.Check(':') && analyzer.IsWhiteBreakOrZero(1)) || (flowLevel > 0 && analyzer.Check(",:?[]{}"))) + { + break; + } + + // Check if we need to join whitespaces and breaks. + + if (hasLeadingBlanks || whitespaces.Length > 0) + { + if (hasLeadingBlanks) + { + // Do we need to fold line breaks? + + if (StartsWith(leadingBreak, '\n')) + { + if (trailingBreaks.Length == 0) + { + value.Append(' '); + } + else + { + value.Append(trailingBreaks); + } + } + else + { + value.Append(leadingBreak); + value.Append(trailingBreaks); + } + + leadingBreak.Length = 0; + trailingBreaks.Length = 0; + + hasLeadingBlanks = false; + } + else + { + value.Append(whitespaces); + whitespaces.Length = 0; + } + } + + // Copy the character. + + value.Append(ReadCurrentCharacter()); + + end = cursor.Mark(); + } + + // Is it the end? + + if (!(analyzer.IsWhite() || analyzer.IsBreak())) + { + break; + } + + // Consume blank characters. + + while (analyzer.IsWhite() || analyzer.IsBreak()) + { + if (analyzer.IsWhite()) + { + // Check for tab character that abuse intendation. + + if (hasLeadingBlanks && cursor.LineOffset < currentIndent && analyzer.IsTab()) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a plain scalar, find a tab character that violate intendation."); + } + + // Consume a space or a tab character. + + if (!hasLeadingBlanks) + { + whitespaces.Append(ReadCurrentCharacter()); + } + else + { + Skip(); + } + } + else + { + // Check if it is a first line break. + + if (!hasLeadingBlanks) + { + whitespaces.Length = 0; + leadingBreak.Append(ReadLine()); + hasLeadingBlanks = true; + } + else + { + trailingBreaks.Append(ReadLine()); + } + } + } + + // Check intendation level. + + if (flowLevel == 0 && cursor.LineOffset < currentIndent) + { + break; + } + } + + // Note that we change the 'simple_key_allowed' flag. + + if (hasLeadingBlanks) + { + simpleKeyAllowed = true; + } + + // Create a token. + + return new Scalar(value.ToString(), ScalarStyle.Plain, start, end); + } + + + /// + /// Remove a potential simple key at the current flow level. + /// + + private void RemoveSimpleKey() + { + var key = simpleKeys.Peek(); + + if (key.IsPossible && key.IsRequired) + { + // If the key is required, it is an error. + + throw new SyntaxErrorException(key.Mark, key.Mark, "While scanning a simple key, could not find expected ':'."); + } + + // Remove the key from the stack. + + key.IsPossible = false; + } + + /// + /// Scan the directive name. + /// + /// Scope: + /// %YAML 1.1 # a comment \n + /// ^^^^ + /// %TAG !yaml! tag:yaml.org,2002: \n + /// ^^^ + /// + private string ScanDirectiveName(Mark start) + { + var name = new StringBuilder(); + + // Consume the directive name. + + while (analyzer.IsAlphaNumericDashOrUnderscore()) + { + name.Append(ReadCurrentCharacter()); + } + + // Check if the name is empty. + + if (name.Length == 0) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a directive, could not find expected directive name."); + } + + // Check for an blank character after the name. + + if (!analyzer.IsWhiteBreakOrZero()) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a directive, find unexpected non-alphabetical character."); + } + + return name.ToString(); + } + + private void SkipWhitespaces() + { + // Eat whitespaces. + + while (analyzer.IsWhite()) + { + Skip(); + } + } + + /// + /// Scan the value of VERSION-DIRECTIVE. + /// + /// Scope: + /// %YAML 1.1 # a comment \n + /// ^^^^^^ + /// + private Token ScanVersionDirectiveValue(Mark start) + { + SkipWhitespaces(); + + // Consume the major version number. + + var major = ScanVersionDirectiveNumber(start); + + // Eat '.'. + + if (!analyzer.Check('.')) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a %YAML directive, did not find expected digit or '.' character."); + } + + Skip(); + + // Consume the minor version number. + + var minor = ScanVersionDirectiveNumber(start); + + return new VersionDirective(new Version(major, minor), start, start); + } + + /// + /// Scan the value of a TAG-DIRECTIVE token. + /// + /// Scope: + /// %TAG !yaml! tag:yaml.org,2002: \n + /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + /// + private Token ScanTagDirectiveValue(Mark start) + { + SkipWhitespaces(); + + // Scan a handle. + + var handle = ScanTagHandle(true, start); + + // Expect a whitespace. + + if (!analyzer.IsWhite()) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a %TAG directive, did not find expected whitespace."); + } + + SkipWhitespaces(); + + // Scan a prefix. + + var prefix = ScanTagUri(null, start); + + // Expect a whitespace or line break. + + if (!analyzer.IsWhiteBreakOrZero()) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a %TAG directive, did not find expected whitespace or line break."); + } + + return new TagDirective(handle, prefix, start, start); + } + + /// + /// Scan a tag. + /// + + private string ScanTagUri(string head, Mark start) + { + var tag = new StringBuilder(); + if (head != null && head.Length > 1) + { + tag.Append(head.Substring(1)); + } + + // Scan the tag. + + // The set of characters that may appear in URI is as follows: + + // '0'-'9', 'A'-'Z', 'a'-'z', '_', '-', ';', '/', '?', ':', '@', '&', + // '=', '+', '$', ',', '.', '!', '~', '*', '\'', '(', ')', '[', ']', + // '%'. + + + while (analyzer.IsAlphaNumericDashOrUnderscore() || analyzer.Check(";/?:@&=+$,.!~*'()[]%")) + { + // Check if it is a URI-escape sequence. + + if (analyzer.Check('%')) + { + tag.Append(ScanUriEscapes(start)); + } + else if (analyzer.Check('+')) + { + tag.Append(' '); + Skip(); + } + else + { + tag.Append(ReadCurrentCharacter()); + } + } + + // Check if the tag is non-empty. + + if (tag.Length == 0) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While parsing a tag, did not find expected tag URI."); + } + + return tag.ToString(); + } + + /// + /// Decode an URI-escape sequence corresponding to a single UTF-8 character. + /// + + private string ScanUriEscapes(Mark start) + { + // Decode the required number of characters. + + byte[] charBytes = null; + int nextInsertionIndex = 0; + int width = 0; + do + { + // Check for a URI-escaped octet. + + if (!(analyzer.Check('%') && analyzer.IsHex(1) && analyzer.IsHex(2))) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While parsing a tag, did not find URI escaped octet."); + } + + // Get the octet. + + int octet = (analyzer.AsHex(1) << 4) + analyzer.AsHex(2); + + // If it is the leading octet, determine the length of the UTF-8 sequence. + + if (width == 0) + { + width = (octet & 0x80) == 0x00 ? 1 : + (octet & 0xE0) == 0xC0 ? 2 : + (octet & 0xF0) == 0xE0 ? 3 : + (octet & 0xF8) == 0xF0 ? 4 : 0; + + if (width == 0) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While parsing a tag, find an incorrect leading UTF-8 octet."); + } + + charBytes = new byte[width]; + } + else + { + // Check if the trailing octet is correct. + + if ((octet & 0xC0) != 0x80) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While parsing a tag, find an incorrect trailing UTF-8 octet."); + } + } + + // Copy the octet and move the pointers. + + charBytes[nextInsertionIndex++] = (byte)octet; + + Skip(); + Skip(); + Skip(); + } + while (--width > 0); + + var result = Encoding.UTF8.GetString(charBytes, 0, nextInsertionIndex); + + if (result.Length == 0 || result.Length > 2) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While parsing a tag, find an incorrect UTF-8 sequence."); + } + + return result; + } + + /// + /// Scan a tag handle. + /// + + private string ScanTagHandle(bool isDirective, Mark start) + { + + // Check the initial '!' character. + + if (!analyzer.Check('!')) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a tag, did not find expected '!'."); + } + + // Copy the '!' character. + + var tagHandle = new StringBuilder(); + tagHandle.Append(ReadCurrentCharacter()); + + // Copy all subsequent alphabetical and numerical characters. + + while (analyzer.IsAlphaNumericDashOrUnderscore()) + { + tagHandle.Append(ReadCurrentCharacter()); + } + + // Check if the trailing character is '!' and copy it. + + if (analyzer.Check('!')) + { + tagHandle.Append(ReadCurrentCharacter()); + } + else + { + + // It's either the '!' tag or not really a tag handle. If it's a %TAG + // directive, it's an error. If it's a tag token, it must be a part of + // URI. + + + if (isDirective && (tagHandle.Length != 1 || tagHandle[0] != '!')) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While parsing a tag directive, did not find expected '!'."); + } + } + + return tagHandle.ToString(); + } + + /// + /// Scan the version number of VERSION-DIRECTIVE. + /// + /// Scope: + /// %YAML 1.1 # a comment \n + /// ^ + /// %YAML 1.1 # a comment \n + /// ^ + /// + private int ScanVersionDirectiveNumber(Mark start) + { + int value = 0; + int length = 0; + + // Repeat while the next character is digit. + + while (analyzer.IsDigit()) + { + // Check if the number is too long. + + if (++length > MaxVersionNumberLength) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a %YAML directive, find extremely long version number."); + } + + value = value * 10 + analyzer.AsDigit(); + + Skip(); + } + + // Check if the number was present. + + if (length == 0) + { + throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a %YAML directive, did not find expected version number."); + } + + return value; + } + + /// + /// Check if a simple key may start at the current position and add it if + /// needed. + /// + + private void SaveSimpleKey() + { + + // A simple key is required at the current position if the scanner is in + // the block context and the current column coincides with the indentation + // level. + + + bool isRequired = (flowLevel == 0 && indent == cursor.LineOffset); + + + // A simple key is required only when it is the first token in the current + // line. Therefore it is always allowed. But we add a check anyway. + + + Debug.Assert(simpleKeyAllowed || !isRequired, "Can't require a simple key and disallow it at the same time."); // Impossible. + + + // If the current position may start a simple key, save it. + + + if (simpleKeyAllowed) + { + var key = new SimpleKey(true, isRequired, tokensParsed + tokens.Count, cursor); + + RemoveSimpleKey(); + + simpleKeys.Pop(); + simpleKeys.Push(key); + } + } + } +} diff --git a/YamlDotNet/Core/Scanner.cs.meta b/YamlDotNet/Core/Scanner.cs.meta new file mode 100644 index 0000000..bcdc2a1 --- /dev/null +++ b/YamlDotNet/Core/Scanner.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: c0682a65176cd1c42807d5c990f0cc8f +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/SemanticErrorException.cs b/YamlDotNet/Core/SemanticErrorException.cs new file mode 100644 index 0000000..bf474cf --- /dev/null +++ b/YamlDotNet/Core/SemanticErrorException.cs @@ -0,0 +1,68 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Runtime.Serialization; + +namespace YamlDotNet.Core +{ + /// + /// Exception that is thrown when a semantic error is detected on a YAML stream. + /// + [Serializable] + public class SemanticErrorException : YamlException + { + /// + /// Initializes a new instance of the class. + /// + public SemanticErrorException() + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The message. + public SemanticErrorException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class. + /// + public SemanticErrorException(Mark start, Mark end, string message) + : base(start, end, message) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The message. + /// The inner. + public SemanticErrorException(string message, Exception inner) + : base(message, inner) + { + } + + } +} diff --git a/YamlDotNet/Core/SemanticErrorException.cs.meta b/YamlDotNet/Core/SemanticErrorException.cs.meta new file mode 100644 index 0000000..75d3846 --- /dev/null +++ b/YamlDotNet/Core/SemanticErrorException.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: ce6eb4a71fe0a504cb2efded3a4ad217 +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/SimpleKey.cs b/YamlDotNet/Core/SimpleKey.cs new file mode 100644 index 0000000..ecff2d7 --- /dev/null +++ b/YamlDotNet/Core/SimpleKey.cs @@ -0,0 +1,54 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace YamlDotNet.Core +{ + [Serializable] + internal class SimpleKey + { + private readonly Cursor cursor; + + public bool IsPossible { get; set; } + + public bool IsRequired { get; private set; } + public int TokenNumber { get; private set; } + public int Index { get { return cursor.Index; } } + public int Line { get { return cursor.Line; } } + public int LineOffset { get { return cursor.LineOffset; } } + + public Mark Mark { get { return cursor.Mark(); } } + + public SimpleKey() + { + cursor = new Cursor(); + } + + public SimpleKey(bool isPossible, bool isRequired, int tokenNumber, Cursor cursor) + { + IsPossible = isPossible; + IsRequired = isRequired; + TokenNumber = tokenNumber; + this.cursor = new Cursor(cursor); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/SimpleKey.cs.meta b/YamlDotNet/Core/SimpleKey.cs.meta new file mode 100644 index 0000000..60f23e7 --- /dev/null +++ b/YamlDotNet/Core/SimpleKey.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 98526770a341dd64aaf15fb3fe79a6c1 +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/StringLookAheadBuffer.cs b/YamlDotNet/Core/StringLookAheadBuffer.cs new file mode 100644 index 0000000..52d4b40 --- /dev/null +++ b/YamlDotNet/Core/StringLookAheadBuffer.cs @@ -0,0 +1,74 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace YamlDotNet.Core +{ + [Serializable] + internal class StringLookAheadBuffer : ILookAheadBuffer + { + private readonly string value; + + public int Position { get; private set; } + + public StringLookAheadBuffer(string value) + { + this.value = value; + } + + public int Length + { + get + { + return value.Length; + } + } + + public bool EndOfInput + { + get + { + return IsOutside(Position); + } + } + + public char Peek(int offset) + { + var index = Position + offset; + return IsOutside(index) ? '\0' : value[index]; + } + + private bool IsOutside(int index) + { + return index >= value.Length; + } + + public void Skip(int length) + { + if (length < 0) + { + throw new ArgumentOutOfRangeException("length", "The length must be positive."); + } + Position += length; + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/StringLookAheadBuffer.cs.meta b/YamlDotNet/Core/StringLookAheadBuffer.cs.meta new file mode 100644 index 0000000..ed006f9 --- /dev/null +++ b/YamlDotNet/Core/StringLookAheadBuffer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b821a24261c0caf46b4f2267068dfa19 +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/SyntaxErrorException.cs b/YamlDotNet/Core/SyntaxErrorException.cs new file mode 100644 index 0000000..4c6f639 --- /dev/null +++ b/YamlDotNet/Core/SyntaxErrorException.cs @@ -0,0 +1,68 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Runtime.Serialization; + +namespace YamlDotNet.Core +{ + /// + /// Exception that is thrown when a syntax error is detected on a YAML stream. + /// + [Serializable] + public class SyntaxErrorException : YamlException + { + /// + /// Initializes a new instance of the class. + /// + public SyntaxErrorException() + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The message. + public SyntaxErrorException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class. + /// + public SyntaxErrorException(Mark start, Mark end, string message) + : base(start, end, message) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The message. + /// The inner. + public SyntaxErrorException(string message, Exception inner) + : base(message, inner) + { + } + + } +} diff --git a/YamlDotNet/Core/SyntaxErrorException.cs.meta b/YamlDotNet/Core/SyntaxErrorException.cs.meta new file mode 100644 index 0000000..64413af --- /dev/null +++ b/YamlDotNet/Core/SyntaxErrorException.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: fd15bbcb74a3b3c49bcbbc67093b631d +timeCreated: 1427145267 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/TagDirectiveCollection.cs b/YamlDotNet/Core/TagDirectiveCollection.cs new file mode 100644 index 0000000..09dcbc1 --- /dev/null +++ b/YamlDotNet/Core/TagDirectiveCollection.cs @@ -0,0 +1,66 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System.Collections.Generic; +using System.Collections.ObjectModel; +using YamlDotNet.Core.Tokens; + +namespace YamlDotNet.Core +{ + /// + /// Collection of . + /// + public class TagDirectiveCollection : KeyedCollection + { + /// + /// Initializes a new instance of the class. + /// + public TagDirectiveCollection() + { + } + + /// + /// Initializes a new instance of the class. + /// + /// Initial content of the collection. + public TagDirectiveCollection(IEnumerable tagDirectives) + { + foreach (var tagDirective in tagDirectives) + { + Add(tagDirective); + } + } + + /// + protected override string GetKeyForItem(TagDirective item) + { + return item.Handle; + } + + /// + /// Gets a value indicating whether the collection contains a directive with the same handle + /// + public new bool Contains(TagDirective directive) + { + return Contains(GetKeyForItem(directive)); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/TagDirectiveCollection.cs.meta b/YamlDotNet/Core/TagDirectiveCollection.cs.meta new file mode 100644 index 0000000..e5595d9 --- /dev/null +++ b/YamlDotNet/Core/TagDirectiveCollection.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: c5901f69158709e4395e0e73e80c1fc2 +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Tokens.meta b/YamlDotNet/Core/Tokens.meta new file mode 100644 index 0000000..542e99e --- /dev/null +++ b/YamlDotNet/Core/Tokens.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: ae5f76f5c7a9e1849837fbe903e177c2 +folderAsset: yes +timeCreated: 1427145262 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Tokens/Anchor.cs b/YamlDotNet/Core/Tokens/Anchor.cs new file mode 100644 index 0000000..0732d60 --- /dev/null +++ b/YamlDotNet/Core/Tokens/Anchor.cs @@ -0,0 +1,67 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace YamlDotNet.Core.Tokens +{ + /// + /// Represents an anchor token. + /// + [Serializable] + public class Anchor : Token + { + private readonly string value; + + /// + /// Gets the value. + /// + /// The value. + public string Value + { + get + { + return value; + } + } + + /// + /// Initializes a new instance of the class. + /// + /// The value. + public Anchor(string value) + : this(value, Mark.Empty, Mark.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The value. + /// The start position of the token. + /// The end position of the token. + public Anchor(string value, Mark start, Mark end) + : base(start, end) + { + this.value = value; + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Tokens/Anchor.cs.meta b/YamlDotNet/Core/Tokens/Anchor.cs.meta new file mode 100644 index 0000000..ecf6119 --- /dev/null +++ b/YamlDotNet/Core/Tokens/Anchor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 20dff0ad997e6bf4fb74167f52869056 +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Tokens/AnchorAlias.cs b/YamlDotNet/Core/Tokens/AnchorAlias.cs new file mode 100644 index 0000000..4658bcc --- /dev/null +++ b/YamlDotNet/Core/Tokens/AnchorAlias.cs @@ -0,0 +1,66 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace YamlDotNet.Core.Tokens +{ + /// + /// Represents an alias token. + /// + [Serializable] + public class AnchorAlias : Token + { + private readonly string value; + + /// + /// Gets the value of the alias. + /// + public string Value + { + get + { + return value; + } + } + + /// + /// Initializes a new instance of the class. + /// + /// The value of the anchor. + public AnchorAlias(string value) + : this(value, Mark.Empty, Mark.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The value of the anchor. + /// The start position of the event. + /// The end position of the event. + public AnchorAlias(string value, Mark start, Mark end) + : base(start, end) + { + this.value = value; + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Tokens/AnchorAlias.cs.meta b/YamlDotNet/Core/Tokens/AnchorAlias.cs.meta new file mode 100644 index 0000000..ce4e5aa --- /dev/null +++ b/YamlDotNet/Core/Tokens/AnchorAlias.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 5888a3fb8858cd9419759f27390f4801 +timeCreated: 1427145264 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Tokens/BlockEnd.cs b/YamlDotNet/Core/Tokens/BlockEnd.cs new file mode 100644 index 0000000..c2c49c6 --- /dev/null +++ b/YamlDotNet/Core/Tokens/BlockEnd.cs @@ -0,0 +1,51 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + + +using System; + +namespace YamlDotNet.Core.Tokens +{ + /// + /// Represents a block end token. + /// + [Serializable] + public class BlockEnd : Token + { + /// + /// Initializes a new instance of the class. + /// + public BlockEnd() + : this(Mark.Empty, Mark.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The start position of the token. + /// The end position of the token. + public BlockEnd(Mark start, Mark end) + : base(start, end) + { + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Tokens/BlockEnd.cs.meta b/YamlDotNet/Core/Tokens/BlockEnd.cs.meta new file mode 100644 index 0000000..4233d42 --- /dev/null +++ b/YamlDotNet/Core/Tokens/BlockEnd.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 0ac69775d00ee4d4ba4b918c06086302 +timeCreated: 1427145262 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Tokens/BlockEntry.cs b/YamlDotNet/Core/Tokens/BlockEntry.cs new file mode 100644 index 0000000..ab4b51c --- /dev/null +++ b/YamlDotNet/Core/Tokens/BlockEntry.cs @@ -0,0 +1,51 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + + +using System; + +namespace YamlDotNet.Core.Tokens +{ + /// + /// Represents a block entry event. + /// + [Serializable] + public class BlockEntry : Token + { + /// + /// Initializes a new instance of the class. + /// + public BlockEntry() + : this(Mark.Empty, Mark.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The start position of the token. + /// The end position of the token. + public BlockEntry(Mark start, Mark end) + : base(start, end) + { + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Tokens/BlockEntry.cs.meta b/YamlDotNet/Core/Tokens/BlockEntry.cs.meta new file mode 100644 index 0000000..9c5e1e2 --- /dev/null +++ b/YamlDotNet/Core/Tokens/BlockEntry.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: c3a1850190300d5479da07fdb53767f0 +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Tokens/BlockMappingStart.cs b/YamlDotNet/Core/Tokens/BlockMappingStart.cs new file mode 100644 index 0000000..fba758f --- /dev/null +++ b/YamlDotNet/Core/Tokens/BlockMappingStart.cs @@ -0,0 +1,51 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + + +using System; + +namespace YamlDotNet.Core.Tokens +{ + /// + /// Represents a block mapping start token. + /// + [Serializable] + public class BlockMappingStart : Token + { + /// + /// Initializes a new instance of the class. + /// + public BlockMappingStart() + : this(Mark.Empty, Mark.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The start position of the token. + /// The end position of the token. + public BlockMappingStart(Mark start, Mark end) + : base(start, end) + { + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Tokens/BlockMappingStart.cs.meta b/YamlDotNet/Core/Tokens/BlockMappingStart.cs.meta new file mode 100644 index 0000000..b620483 --- /dev/null +++ b/YamlDotNet/Core/Tokens/BlockMappingStart.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 9f8bc35d16193164aaee492bc767e9f8 +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Tokens/BlockSequenceStart.cs b/YamlDotNet/Core/Tokens/BlockSequenceStart.cs new file mode 100644 index 0000000..18a7473 --- /dev/null +++ b/YamlDotNet/Core/Tokens/BlockSequenceStart.cs @@ -0,0 +1,51 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + + +using System; + +namespace YamlDotNet.Core.Tokens +{ + /// + /// Represents a block sequence start token. + /// + [Serializable] + public class BlockSequenceStart : Token + { + /// + /// Initializes a new instance of the class. + /// + public BlockSequenceStart() + : this(Mark.Empty, Mark.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The start position of the token. + /// The end position of the token. + public BlockSequenceStart(Mark start, Mark end) + : base(start, end) + { + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Tokens/BlockSequenceStart.cs.meta b/YamlDotNet/Core/Tokens/BlockSequenceStart.cs.meta new file mode 100644 index 0000000..fc4ef44 --- /dev/null +++ b/YamlDotNet/Core/Tokens/BlockSequenceStart.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 827b4413642f10d4891e4b1771c5ad45 +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Tokens/Comment.cs b/YamlDotNet/Core/Tokens/Comment.cs new file mode 100644 index 0000000..39a08c7 --- /dev/null +++ b/YamlDotNet/Core/Tokens/Comment.cs @@ -0,0 +1,60 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace YamlDotNet.Core.Tokens +{ + /// + /// Represents a comment + /// + [Serializable] + public class Comment : Token + { + /// + /// Gets the value of the comment + /// + public string Value { get; private set; } + + /// + /// Gets a value indicating whether the comment appears other tokens on that line. + /// + public bool IsInline { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + public Comment(string value, bool isInline) + : this(value, isInline, Mark.Empty, Mark.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + public Comment(string value, bool isInline, Mark start, Mark end) + : base(start, end) + { + IsInline = isInline; + Value = value; + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Tokens/Comment.cs.meta b/YamlDotNet/Core/Tokens/Comment.cs.meta new file mode 100644 index 0000000..4dc0be9 --- /dev/null +++ b/YamlDotNet/Core/Tokens/Comment.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 7faa8193237a87f41aa6e2a84836b348 +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Tokens/DocumentEnd.cs b/YamlDotNet/Core/Tokens/DocumentEnd.cs new file mode 100644 index 0000000..6d3a1b9 --- /dev/null +++ b/YamlDotNet/Core/Tokens/DocumentEnd.cs @@ -0,0 +1,51 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + + +using System; + +namespace YamlDotNet.Core.Tokens +{ + /// + /// Represents a document end token. + /// + [Serializable] + public class DocumentEnd : Token + { + /// + /// Initializes a new instance of the class. + /// + public DocumentEnd() + : this(Mark.Empty, Mark.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The start position of the token. + /// The end position of the token. + public DocumentEnd(Mark start, Mark end) + : base(start, end) + { + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Tokens/DocumentEnd.cs.meta b/YamlDotNet/Core/Tokens/DocumentEnd.cs.meta new file mode 100644 index 0000000..8cec158 --- /dev/null +++ b/YamlDotNet/Core/Tokens/DocumentEnd.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b70a27ee4c4c7c24e9df5b0ec3a2c6da +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Tokens/DocumentStart.cs b/YamlDotNet/Core/Tokens/DocumentStart.cs new file mode 100644 index 0000000..c84626a --- /dev/null +++ b/YamlDotNet/Core/Tokens/DocumentStart.cs @@ -0,0 +1,51 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + + +using System; + +namespace YamlDotNet.Core.Tokens +{ + /// + /// Represents a document start token. + /// + [Serializable] + public class DocumentStart : Token + { + /// + /// Initializes a new instance of the class. + /// + public DocumentStart() + : this(Mark.Empty, Mark.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The start position of the token. + /// The end position of the token. + public DocumentStart(Mark start, Mark end) + : base(start, end) + { + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Tokens/DocumentStart.cs.meta b/YamlDotNet/Core/Tokens/DocumentStart.cs.meta new file mode 100644 index 0000000..c490ffa --- /dev/null +++ b/YamlDotNet/Core/Tokens/DocumentStart.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2c86a143ce13faf4e90cece89b865c8a +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Tokens/FlowEntry.cs b/YamlDotNet/Core/Tokens/FlowEntry.cs new file mode 100644 index 0000000..077f8a6 --- /dev/null +++ b/YamlDotNet/Core/Tokens/FlowEntry.cs @@ -0,0 +1,51 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + + +using System; + +namespace YamlDotNet.Core.Tokens +{ + /// + /// Represents a flow entry event. + /// + [Serializable] + public class FlowEntry : Token + { + /// + /// Initializes a new instance of the class. + /// + public FlowEntry() + : this(Mark.Empty, Mark.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The start position of the token. + /// The end position of the token. + public FlowEntry(Mark start, Mark end) + : base(start, end) + { + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Tokens/FlowEntry.cs.meta b/YamlDotNet/Core/Tokens/FlowEntry.cs.meta new file mode 100644 index 0000000..0c22fad --- /dev/null +++ b/YamlDotNet/Core/Tokens/FlowEntry.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f6de9d5d89c756c49882403cf8b79eed +timeCreated: 1427145267 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Tokens/FlowMappingEnd.cs b/YamlDotNet/Core/Tokens/FlowMappingEnd.cs new file mode 100644 index 0000000..2209bf3 --- /dev/null +++ b/YamlDotNet/Core/Tokens/FlowMappingEnd.cs @@ -0,0 +1,51 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + + +using System; + +namespace YamlDotNet.Core.Tokens +{ + /// + /// Represents a flow mapping end token. + /// + [Serializable] + public class FlowMappingEnd : Token + { + /// + /// Initializes a new instance of the class. + /// + public FlowMappingEnd() + : this(Mark.Empty, Mark.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The start position of the token. + /// The end position of the token. + public FlowMappingEnd(Mark start, Mark end) + : base(start, end) + { + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Tokens/FlowMappingEnd.cs.meta b/YamlDotNet/Core/Tokens/FlowMappingEnd.cs.meta new file mode 100644 index 0000000..b3c7d58 --- /dev/null +++ b/YamlDotNet/Core/Tokens/FlowMappingEnd.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6e66c86850cf7a545bfa90d7c9b1831a +timeCreated: 1427145264 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Tokens/FlowMappingStart.cs b/YamlDotNet/Core/Tokens/FlowMappingStart.cs new file mode 100644 index 0000000..9cda540 --- /dev/null +++ b/YamlDotNet/Core/Tokens/FlowMappingStart.cs @@ -0,0 +1,51 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + + +using System; + +namespace YamlDotNet.Core.Tokens +{ + /// + /// Represents a flow mapping start token. + /// + [Serializable] + public class FlowMappingStart : Token + { + /// + /// Initializes a new instance of the class. + /// + public FlowMappingStart() + : this(Mark.Empty, Mark.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The start position of the token. + /// The end position of the token. + public FlowMappingStart(Mark start, Mark end) + : base(start, end) + { + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Tokens/FlowMappingStart.cs.meta b/YamlDotNet/Core/Tokens/FlowMappingStart.cs.meta new file mode 100644 index 0000000..24f8528 --- /dev/null +++ b/YamlDotNet/Core/Tokens/FlowMappingStart.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d357652b21a405949a837dbef084c7e3 +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Tokens/FlowSequenceEnd.cs b/YamlDotNet/Core/Tokens/FlowSequenceEnd.cs new file mode 100644 index 0000000..ba5669c --- /dev/null +++ b/YamlDotNet/Core/Tokens/FlowSequenceEnd.cs @@ -0,0 +1,51 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + + +using System; + +namespace YamlDotNet.Core.Tokens +{ + /// + /// Represents a flow sequence end token. + /// + [Serializable] + public class FlowSequenceEnd : Token + { + /// + /// Initializes a new instance of the class. + /// + public FlowSequenceEnd() + : this(Mark.Empty, Mark.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The start position of the token. + /// The end position of the token. + public FlowSequenceEnd(Mark start, Mark end) + : base(start, end) + { + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Tokens/FlowSequenceEnd.cs.meta b/YamlDotNet/Core/Tokens/FlowSequenceEnd.cs.meta new file mode 100644 index 0000000..14a5fb8 --- /dev/null +++ b/YamlDotNet/Core/Tokens/FlowSequenceEnd.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 5338410489b921f4c873cbed0c5b7754 +timeCreated: 1427145264 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Tokens/FlowSequenceStart.cs b/YamlDotNet/Core/Tokens/FlowSequenceStart.cs new file mode 100644 index 0000000..e0e1623 --- /dev/null +++ b/YamlDotNet/Core/Tokens/FlowSequenceStart.cs @@ -0,0 +1,51 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + + +using System; + +namespace YamlDotNet.Core.Tokens +{ + /// + /// Represents a flow sequence start token. + /// + [Serializable] + public class FlowSequenceStart : Token + { + /// + /// Initializes a new instance of the class. + /// + public FlowSequenceStart() + : this(Mark.Empty, Mark.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The start position of the token. + /// The end position of the token. + public FlowSequenceStart(Mark start, Mark end) + : base(start, end) + { + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Tokens/FlowSequenceStart.cs.meta b/YamlDotNet/Core/Tokens/FlowSequenceStart.cs.meta new file mode 100644 index 0000000..54f8b33 --- /dev/null +++ b/YamlDotNet/Core/Tokens/FlowSequenceStart.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 8248df61d7f1e7e4fbd6db14a760c5cd +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Tokens/Key.cs b/YamlDotNet/Core/Tokens/Key.cs new file mode 100644 index 0000000..93537f4 --- /dev/null +++ b/YamlDotNet/Core/Tokens/Key.cs @@ -0,0 +1,51 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + + +using System; + +namespace YamlDotNet.Core.Tokens +{ + /// + /// Represents a key token. + /// + [Serializable] + public class Key : Token + { + /// + /// Initializes a new instance of the class. + /// + public Key() + : this(Mark.Empty, Mark.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The start position of the token. + /// The end position of the token. + public Key(Mark start, Mark end) + : base(start, end) + { + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Tokens/Key.cs.meta b/YamlDotNet/Core/Tokens/Key.cs.meta new file mode 100644 index 0000000..68d9568 --- /dev/null +++ b/YamlDotNet/Core/Tokens/Key.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d3197efde30ce804d81b7698c3c9c5a6 +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Tokens/Scalar.cs b/YamlDotNet/Core/Tokens/Scalar.cs new file mode 100644 index 0000000..3524718 --- /dev/null +++ b/YamlDotNet/Core/Tokens/Scalar.cs @@ -0,0 +1,94 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + + +using System; + +namespace YamlDotNet.Core.Tokens +{ + /// + /// Represents a scalar token. + /// + [Serializable] + public class Scalar : Token + { + private readonly string value; + + /// + /// Gets the value. + /// + /// The value. + public string Value + { + get + { + return value; + } + } + + private readonly ScalarStyle style; + + /// + /// Gets the style. + /// + /// The style. + public ScalarStyle Style + { + get + { + return style; + } + } + + /// + /// Initializes a new instance of the class. + /// + /// The value. + public Scalar(string value) + : this(value, ScalarStyle.Any) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The value. + /// The style. + public Scalar(string value, ScalarStyle style) + : this(value, style, Mark.Empty, Mark.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The value. + /// The style. + /// The start position of the token. + /// The end position of the token. + public Scalar(string value, ScalarStyle style, Mark start, Mark end) + : base(start, end) + { + this.value = value; + this.style = style; + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Tokens/Scalar.cs.meta b/YamlDotNet/Core/Tokens/Scalar.cs.meta new file mode 100644 index 0000000..6c2c716 --- /dev/null +++ b/YamlDotNet/Core/Tokens/Scalar.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d8a37767e1f6b1949b357766c6f98776 +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Tokens/StreamEnd.cs b/YamlDotNet/Core/Tokens/StreamEnd.cs new file mode 100644 index 0000000..481f24b --- /dev/null +++ b/YamlDotNet/Core/Tokens/StreamEnd.cs @@ -0,0 +1,51 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + + +using System; + +namespace YamlDotNet.Core.Tokens +{ + /// + /// Represents a stream end event. + /// + [Serializable] + public class StreamEnd : Token + { + /// + /// Initializes a new instance of the class. + /// + public StreamEnd() + : this(Mark.Empty, Mark.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The start position of the token. + /// The end position of the token. + public StreamEnd(Mark start, Mark end) + : base(start, end) + { + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Tokens/StreamEnd.cs.meta b/YamlDotNet/Core/Tokens/StreamEnd.cs.meta new file mode 100644 index 0000000..cae53ef --- /dev/null +++ b/YamlDotNet/Core/Tokens/StreamEnd.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 7f214337aa3dd71439c3a1ee6e5ef79d +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Tokens/StreamStart.cs b/YamlDotNet/Core/Tokens/StreamStart.cs new file mode 100644 index 0000000..9d7b5e6 --- /dev/null +++ b/YamlDotNet/Core/Tokens/StreamStart.cs @@ -0,0 +1,50 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace YamlDotNet.Core.Tokens +{ + /// + /// Represents a stream start token. + /// + [Serializable] + public class StreamStart : Token + { + /// + /// Initializes a new instance of the class. + /// + public StreamStart() + : this(Mark.Empty, Mark.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The start position of the token. + /// The end position of the token. + public StreamStart(Mark start, Mark end) + : base(start, end) + { + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Tokens/StreamStart.cs.meta b/YamlDotNet/Core/Tokens/StreamStart.cs.meta new file mode 100644 index 0000000..3caeefa --- /dev/null +++ b/YamlDotNet/Core/Tokens/StreamStart.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: c0787d33a81177840836ef7dba3d0b75 +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Tokens/Tag.cs b/YamlDotNet/Core/Tokens/Tag.cs new file mode 100644 index 0000000..dd033f7 --- /dev/null +++ b/YamlDotNet/Core/Tokens/Tag.cs @@ -0,0 +1,83 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace YamlDotNet.Core.Tokens +{ + /// + /// Represents a tag token. + /// + [Serializable] + public class Tag : Token + { + private readonly string handle; + private readonly string suffix; + + /// + /// Gets the handle. + /// + /// The handle. + public string Handle + { + get + { + return handle; + } + } + + /// + /// Gets the suffix. + /// + /// The suffix. + public string Suffix + { + get + { + return suffix; + } + } + + /// + /// Initializes a new instance of the class. + /// + /// The handle. + /// The suffix. + public Tag(string handle, string suffix) + : this(handle, suffix, Mark.Empty, Mark.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The handle. + /// The suffix. + /// The start position of the token. + /// The end position of the token. + public Tag(string handle, string suffix, Mark start, Mark end) + : base(start, end) + { + this.handle = handle; + this.suffix = suffix; + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Tokens/Tag.cs.meta b/YamlDotNet/Core/Tokens/Tag.cs.meta new file mode 100644 index 0000000..2197cbd --- /dev/null +++ b/YamlDotNet/Core/Tokens/Tag.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2c6cb793327f6a349964aa8538bc1e33 +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Tokens/TagDirective.cs b/YamlDotNet/Core/Tokens/TagDirective.cs new file mode 100644 index 0000000..678d036 --- /dev/null +++ b/YamlDotNet/Core/Tokens/TagDirective.cs @@ -0,0 +1,133 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Globalization; +using System.Text.RegularExpressions; + +namespace YamlDotNet.Core.Tokens +{ + /// + /// Represents a tag directive token. + /// + [Serializable] + public class TagDirective : Token + { + private readonly string handle; + private readonly string prefix; + + /// + /// Gets the handle. + /// + /// The handle. + public string Handle + { + get + { + return handle; + } + } + + /// + /// Gets the prefix. + /// + /// The prefix. + public string Prefix + { + get + { + return prefix; + } + } + + /// + /// Initializes a new instance of the class. + /// + /// The handle. + /// The prefix. + public TagDirective(string handle, string prefix) + : this(handle, prefix, Mark.Empty, Mark.Empty) + { + } + + private static readonly Regex tagHandleValidator = new Regex(@"^!([0-9A-Za-z_\-]*!)?$", StandardRegexOptions.Compiled); + + /// + /// Initializes a new instance of the class. + /// + /// The handle. + /// The prefix. + /// The start position of the token. + /// The end position of the token. + public TagDirective(string handle, string prefix, Mark start, Mark end) + : base(start, end) + { + if (string.IsNullOrEmpty(handle)) + { + throw new ArgumentNullException("handle", "Tag handle must not be empty."); + } + + if (!tagHandleValidator.IsMatch(handle)) + { + throw new ArgumentException("Tag handle must start and end with '!' and contain alphanumerical characters only.", "handle"); + } + + this.handle = handle; + + if (string.IsNullOrEmpty(prefix)) + { + throw new ArgumentNullException("prefix", "Tag prefix must not be empty."); + } + + this.prefix = prefix; + } + + /// + /// Determines whether the specified System.Object is equal to the current System.Object. + /// + /// The System.Object to compare with the current System.Object. + /// + /// true if the specified System.Object is equal to the current System.Object; otherwise, false. + /// + public override bool Equals(object obj) + { + var other = obj as TagDirective; + return other != null && handle.Equals(other.handle) && prefix.Equals(other.prefix); + } + + /// + /// Serves as a hash function for a particular type. + /// + /// + /// A hash code for the current . + /// + public override int GetHashCode() + { + return handle.GetHashCode() ^ prefix.GetHashCode(); + } + + /// + public override string ToString() + { + return string.Format(CultureInfo.InvariantCulture, "{0} => {1}", handle, prefix); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Tokens/TagDirective.cs.meta b/YamlDotNet/Core/Tokens/TagDirective.cs.meta new file mode 100644 index 0000000..bb2a6b1 --- /dev/null +++ b/YamlDotNet/Core/Tokens/TagDirective.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: dc25c68d7148e424ba5d875871c1aec8 +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Tokens/Token.cs b/YamlDotNet/Core/Tokens/Token.cs new file mode 100644 index 0000000..8182417 --- /dev/null +++ b/YamlDotNet/Core/Tokens/Token.cs @@ -0,0 +1,69 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace YamlDotNet.Core.Tokens +{ + /// + /// Base class for YAML tokens. + /// + [Serializable] + public abstract class Token + { + private readonly Mark start; + + /// + /// Gets the start of the token in the input stream. + /// + public Mark Start + { + get + { + return start; + } + } + + private readonly Mark end; + + /// + /// Gets the end of the token in the input stream. + /// + public Mark End + { + get + { + return end; + } + } + + /// + /// Initializes a new instance of the class. + /// + /// The start position of the token. + /// The end position of the token. + protected Token(Mark start, Mark end) + { + this.start = start; + this.end = end; + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Tokens/Token.cs.meta b/YamlDotNet/Core/Tokens/Token.cs.meta new file mode 100644 index 0000000..76a6fe9 --- /dev/null +++ b/YamlDotNet/Core/Tokens/Token.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 9674e003fb73bba4cbf5ab487614a0d8 +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Tokens/Value.cs b/YamlDotNet/Core/Tokens/Value.cs new file mode 100644 index 0000000..ddad06a --- /dev/null +++ b/YamlDotNet/Core/Tokens/Value.cs @@ -0,0 +1,50 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace YamlDotNet.Core.Tokens +{ + /// + /// Represents a value token. + /// + [Serializable] + public class Value : Token + { + /// + /// Initializes a new instance of the class. + /// + public Value() + : this(Mark.Empty, Mark.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The start position of the token. + /// The end position of the token. + public Value(Mark start, Mark end) + : base(start, end) + { + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Tokens/Value.cs.meta b/YamlDotNet/Core/Tokens/Value.cs.meta new file mode 100644 index 0000000..b4923ec --- /dev/null +++ b/YamlDotNet/Core/Tokens/Value.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 0fe0dfc9c858f2248a691e2f52bdfdff +timeCreated: 1427145262 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Tokens/VersionDirective.cs b/YamlDotNet/Core/Tokens/VersionDirective.cs new file mode 100644 index 0000000..7b8f564 --- /dev/null +++ b/YamlDotNet/Core/Tokens/VersionDirective.cs @@ -0,0 +1,91 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace YamlDotNet.Core.Tokens +{ + /// + /// Represents a version directive token. + /// + [Serializable] + public class VersionDirective : Token + { + private readonly Version version; + + /// + /// Gets the version. + /// + /// The version. + public Version Version + { + get + { + return version; + } + } + + /// + /// Initializes a new instance of the class. + /// + /// The version. + public VersionDirective(Version version) + : this(version, Mark.Empty, Mark.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The version. + /// The start position of the token. + /// The end position of the token. + public VersionDirective(Version version, Mark start, Mark end) + : base(start, end) + { + this.version = version; + } + + /// + /// Determines whether the specified System.Object is equal to the current System.Object. + /// + /// The System.Object to compare with the current System.Object. + /// + /// true if the specified System.Object is equal to the current System.Object; otherwise, false. + /// + public override bool Equals(object obj) + { + var other = obj as VersionDirective; + return other != null && version.Equals(other.version); + } + + /// + /// Serves as a hash function for a particular type. + /// + /// + /// A hash code for the current . + /// + public override int GetHashCode() + { + return version.GetHashCode(); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Tokens/VersionDirective.cs.meta b/YamlDotNet/Core/Tokens/VersionDirective.cs.meta new file mode 100644 index 0000000..89b5f8f --- /dev/null +++ b/YamlDotNet/Core/Tokens/VersionDirective.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 5e236aab8cd03d94295778001f592ec1 +timeCreated: 1427145264 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/Version.cs b/YamlDotNet/Core/Version.cs new file mode 100644 index 0000000..899b641 --- /dev/null +++ b/YamlDotNet/Core/Version.cs @@ -0,0 +1,77 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace YamlDotNet.Core +{ + /// + /// Specifies the version of the YAML language. + /// + [Serializable] + public class Version + { + /// + /// Gets the major version number. + /// + public int Major { get; private set; } + + /// + /// Gets the minor version number. + /// + public int Minor { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The the major version number. + /// The the minor version number. + public Version(int major, int minor) + { + Major = major; + Minor = minor; + } + + /// + /// Determines whether the specified System.Object is equal to the current System.Object. + /// + /// The System.Object to compare with the current System.Object. + /// + /// true if the specified System.Object is equal to the current System.Object; otherwise, false. + /// + public override bool Equals(object obj) + { + var that = obj as Version; + return that != null && Major == that.Major && Minor == that.Minor; + } + + /// + /// Serves as a hash function for a particular type. + /// + /// + /// A hash code for the current . + /// + public override int GetHashCode() + { + return Major.GetHashCode() ^ Minor.GetHashCode(); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Core/Version.cs.meta b/YamlDotNet/Core/Version.cs.meta new file mode 100644 index 0000000..1b08246 --- /dev/null +++ b/YamlDotNet/Core/Version.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 03439ca56e1dbbc4882676e8255f06c1 +timeCreated: 1427145262 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Core/YamlException.cs b/YamlDotNet/Core/YamlException.cs new file mode 100644 index 0000000..d0b605b --- /dev/null +++ b/YamlDotNet/Core/YamlException.cs @@ -0,0 +1,88 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Runtime.Serialization; + +namespace YamlDotNet.Core +{ + /// + /// Base exception that is thrown when the a problem occurs in the YamlDotNet library. + /// + [Serializable] + public class YamlException : Exception + { + /// + /// Gets the position in the input stream where the event that originated the exception starts. + /// + public Mark Start { get; private set; } + + /// + /// Gets the position in the input stream where the event that originated the exception ends. + /// + public Mark End { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + public YamlException() + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The message. + public YamlException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class. + /// + public YamlException(Mark start, Mark end, string message) + : this(start, end, message, null) + { + } + + /// + /// Initializes a new instance of the class. + /// + public YamlException(Mark start, Mark end, string message, Exception innerException) + : base(string.Format("({0}) - ({1}): {2}", start, end, message), innerException) + { + Start = start; + End = end; + } + + /// + /// Initializes a new instance of the class. + /// + /// The message. + /// The inner. + public YamlException(string message, Exception inner) + : base(message, inner) + { + } + + } +} diff --git a/YamlDotNet/Core/YamlException.cs.meta b/YamlDotNet/Core/YamlException.cs.meta new file mode 100644 index 0000000..f3e1948 --- /dev/null +++ b/YamlDotNet/Core/YamlException.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 18ae75fcd5b1676418d42ac4d2c824c5 +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Examples.meta b/YamlDotNet/Examples.meta new file mode 100644 index 0000000..88c04bf --- /dev/null +++ b/YamlDotNet/Examples.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: f44c0df627c830e4d8e60525feb0c5a9 +folderAsset: yes +timeCreated: 1429640505 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Examples.unity b/YamlDotNet/Examples.unity new file mode 100644 index 0000000..c6eff80 --- /dev/null +++ b/YamlDotNet/Examples.unity @@ -0,0 +1,128 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!29 &1 +SceneSettings: + m_ObjectHideFlags: 0 + m_PVSData: + m_PVSObjectsArray: [] + m_PVSPortalsArray: [] + m_OcclusionBakeSettings: + smallestOccluder: 5 + smallestHole: 0.25 + backfaceThreshold: 100 +--- !u!104 &2 +RenderSettings: + m_ObjectHideFlags: 0 + serializedVersion: 6 + m_Fog: 0 + m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} + m_FogMode: 3 + m_FogDensity: 0.01 + m_LinearFogStart: 0 + m_LinearFogEnd: 300 + m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1} + m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1} + m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1} + m_AmbientIntensity: 1 + m_AmbientMode: 0 + m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0} + m_HaloStrength: 0.5 + m_FlareStrength: 1 + m_FlareFadeSpeed: 3 + m_HaloTexture: {fileID: 0} + m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0} + m_DefaultReflectionMode: 0 + m_DefaultReflectionResolution: 128 + m_ReflectionBounces: 1 + m_ReflectionIntensity: 1 + m_CustomReflection: {fileID: 0} + m_Sun: {fileID: 0} +--- !u!157 &4 +LightmapSettings: + m_ObjectHideFlags: 0 + serializedVersion: 6 + m_GIWorkflowMode: 0 + m_LightmapsMode: 1 + m_GISettings: + serializedVersion: 2 + m_BounceScale: 1 + m_IndirectOutputScale: 1 + m_AlbedoBoost: 1 + m_TemporalCoherenceThreshold: 1 + m_EnvironmentLightingMode: 0 + m_EnableBakedLightmaps: 1 + m_EnableRealtimeLightmaps: 1 + m_LightmapEditorSettings: + serializedVersion: 3 + m_Resolution: 2 + m_BakeResolution: 40 + m_TextureWidth: 1024 + m_TextureHeight: 1024 + m_AOMaxDistance: 1 + m_Padding: 2 + m_CompAOExponent: 0 + m_LightmapParameters: {fileID: 0} + m_TextureCompression: 1 + m_FinalGather: 0 + m_FinalGatherRayCount: 1024 + m_ReflectionCompression: 2 + m_LightingDataAsset: {fileID: 0} + m_RuntimeCPUUsage: 25 +--- !u!196 &5 +NavMeshSettings: + serializedVersion: 2 + m_ObjectHideFlags: 0 + m_BuildSettings: + serializedVersion: 2 + agentRadius: 0.5 + agentHeight: 2 + agentSlope: 45 + agentClimb: 0.4 + ledgeDropHeight: 0 + maxJumpAcrossDistance: 0 + accuratePlacement: 0 + minRegionArea: 2 + cellSize: 0.16666667 + manualCellSize: 0 + m_NavMeshData: {fileID: 0} +--- !u!1 &234401415 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + serializedVersion: 4 + m_Component: + - 4: {fileID: 234401416} + - 114: {fileID: 234401417} + m_Layer: 0 + m_Name: Play to run tests + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &234401416 +Transform: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 234401415} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 +--- !u!114 &234401417 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 234401415} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 6c2d347068a20b442a3cdbf631ad8ab3, type: 3} + m_Name: + m_EditorClassIdentifier: + disabledTests: [] diff --git a/YamlDotNet/Examples.unity.meta b/YamlDotNet/Examples.unity.meta new file mode 100644 index 0000000..c4ec1db --- /dev/null +++ b/YamlDotNet/Examples.unity.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0a9e040f29652374d912092d37f683fa +timeCreated: 1427501961 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Examples/ConvertYamlToJson.cs b/YamlDotNet/Examples/ConvertYamlToJson.cs new file mode 100644 index 0000000..0dc38f5 --- /dev/null +++ b/YamlDotNet/Examples/ConvertYamlToJson.cs @@ -0,0 +1,41 @@ +using System.IO; +using YamlDotNet.Serialization; +using YamlDotNet.Samples.Helpers; + +namespace YamlDotNet.Samples +{ + public class ConvertYamlToJson + { + private readonly ITestOutputHelper output; + + public ConvertYamlToJson(ITestOutputHelper output) + { + this.output = output; + } + + [Sample( + Title = "Convert YAML to JSON", + Description = "Shows how to convert a YAML document to JSON." + )] + public void Main() + { + // convert string/file to YAML object + var r = new StringReader(@" +scalar: a scalar +sequence: + - one + - two +"); + var deserializer = new DeserializerBuilder().Build(); + var yamlObject = deserializer.Deserialize(r); + + var serializer = new SerializerBuilder() + .JsonCompatible() + .Build(); + + var json = serializer.Serialize(yamlObject); + + output.WriteLine(json); + } + } +} diff --git a/YamlDotNet/Examples/ConvertYamlToJson.cs.meta b/YamlDotNet/Examples/ConvertYamlToJson.cs.meta new file mode 100644 index 0000000..c5936be --- /dev/null +++ b/YamlDotNet/Examples/ConvertYamlToJson.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 83e73fe5645753f4fbbca24d77bc6a66 +timeCreated: 1485603636 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Examples/DeserializeObjectGraph.cs b/YamlDotNet/Examples/DeserializeObjectGraph.cs new file mode 100644 index 0000000..51bf536 --- /dev/null +++ b/YamlDotNet/Examples/DeserializeObjectGraph.cs @@ -0,0 +1,143 @@ +using System; +using System.Collections.Generic; +using System.IO; +using YamlDotNet.Serialization; +using YamlDotNet.Serialization.NamingConventions; +using YamlDotNet.Samples.Helpers; + +namespace YamlDotNet.Samples +{ + public class DeserializeObjectGraph + { + private readonly ITestOutputHelper output; + + public DeserializeObjectGraph(ITestOutputHelper output) + { + this.output = output; + } + + [Sample( + Title = "Deserializing an object graph", + Description = "Shows how to convert a YAML document to an object graph." + )] + public void Main() + { + var input = new StringReader(Document); + + var deserializer = new DeserializerBuilder() + .WithNamingConvention(new CamelCaseNamingConvention()) + .Build(); + + var order = deserializer.Deserialize(input); + + output.WriteLine("Order"); + output.WriteLine("-----"); + output.WriteLine(); + foreach (var item in order.Items) + { + output.WriteLine("{0}\t{1}\t{2}\t{3}", item.PartNo, item.Quantity, item.Price, item.Descrip); + } + output.WriteLine(); + + output.WriteLine("Shipping"); + output.WriteLine("--------"); + output.WriteLine(); + output.WriteLine(order.ShipTo.Street); + output.WriteLine(order.ShipTo.City); + output.WriteLine(order.ShipTo.State); + output.WriteLine(); + + output.WriteLine("Billing"); + output.WriteLine("-------"); + output.WriteLine(); + if (order.BillTo == order.ShipTo) + { + output.WriteLine("*same as shipping address*"); + } + else + { + output.WriteLine(order.ShipTo.Street); + output.WriteLine(order.ShipTo.City); + output.WriteLine(order.ShipTo.State); + } + output.WriteLine(); + + output.WriteLine("Delivery instructions"); + output.WriteLine("---------------------"); + output.WriteLine(); + output.WriteLine(order.SpecialDelivery); + } + + public class Order + { + public string Receipt { get; set; } + public DateTime Date { get; set; } + public Customer Customer { get; set; } + public List Items { get; set; } + + [YamlMember(Alias = "bill-to", ApplyNamingConventions = false)] + public Address BillTo { get; set; } + + [YamlMember(Alias = "ship-to", ApplyNamingConventions = false)] + public Address ShipTo { get; set; } + + public string SpecialDelivery { get; set; } + } + + public class Customer + { + public string Given { get; set; } + public string Family { get; set; } + } + + public class OrderItem + { + [YamlMember(Alias = "part_no", ApplyNamingConventions = false)] + public string PartNo { get; set; } + public string Descrip { get; set; } + public decimal Price { get; set; } + public int Quantity { get; set; } + } + + public class Address + { + public string Street { get; set; } + public string City { get; set; } + public string State { get; set; } + } + + private const string Document = @"--- + receipt: Oz-Ware Purchase Invoice + date: 2007-08-06 + customer: + given: Dorothy + family: Gale + + items: + - part_no: A4786 + descrip: Water Bucket (Filled) + price: 1.47 + quantity: 4 + + - part_no: E1628 + descrip: High Heeled ""Ruby"" Slippers + price: 100.27 + quantity: 1 + + bill-to: &id001 + street: |- + 123 Tornado Alley + Suite 16 + city: East Westville + state: KS + + ship-to: *id001 + + specialDelivery: > + Follow the Yellow Brick + Road to the Emerald City. + Pay no attention to the + man behind the curtain. +..."; + } +} diff --git a/YamlDotNet/Examples/DeserializeObjectGraph.cs.meta b/YamlDotNet/Examples/DeserializeObjectGraph.cs.meta new file mode 100644 index 0000000..c0c47e7 --- /dev/null +++ b/YamlDotNet/Examples/DeserializeObjectGraph.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 97155601043b6734ab06eaf3989b828a +timeCreated: 1429640595 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Examples/DeserializingMultipleDocuments.cs b/YamlDotNet/Examples/DeserializingMultipleDocuments.cs new file mode 100644 index 0000000..5d03972 --- /dev/null +++ b/YamlDotNet/Examples/DeserializingMultipleDocuments.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using System.IO; +using YamlDotNet.Core; +using YamlDotNet.Core.Events; +using YamlDotNet.Serialization; +using YamlDotNet.Samples.Helpers; + +namespace YamlDotNet.Samples +{ + public class DeserializingMultipleDocuments + { + private readonly ITestOutputHelper output; + + public DeserializingMultipleDocuments(ITestOutputHelper output) + { + this.output = output; + } + + [Sample( + Title = "Deserializing multiple documents", + Description = "Explains how to load multiple YAML documents from a stream." + )] + public void Main() + { + var input = new StringReader(Document); + + var deserializer = new DeserializerBuilder().Build(); + + var parser = new Parser(input); + + // Consume the stream start event "manually" + parser.Expect(); + + while (parser.Accept()) + { + // Deserialize the document + var doc = deserializer.Deserialize>(parser); + + output.WriteLine("## Document"); + foreach (var item in doc) + { + output.WriteLine(item); + } + } + } + + private const string Document = @"--- +- Prisoner +- Goblet +- Phoenix +--- +- Memoirs +- Snow +- Ghost +..."; + } +} diff --git a/YamlDotNet/Examples/DeserializingMultipleDocuments.cs.meta b/YamlDotNet/Examples/DeserializingMultipleDocuments.cs.meta new file mode 100644 index 0000000..d880ce3 --- /dev/null +++ b/YamlDotNet/Examples/DeserializingMultipleDocuments.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f3200cc07f84b324e95a6e173a3a4206 +timeCreated: 1429644942 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Examples/Helpers.meta b/YamlDotNet/Examples/Helpers.meta new file mode 100644 index 0000000..20d7fb4 --- /dev/null +++ b/YamlDotNet/Examples/Helpers.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: e6d25873053ff2e4f8dd8e34c9cc9033 +folderAsset: yes +timeCreated: 1485603636 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Examples/Helpers/ExampleRunner.cs b/YamlDotNet/Examples/Helpers/ExampleRunner.cs new file mode 100644 index 0000000..909a7c1 --- /dev/null +++ b/YamlDotNet/Examples/Helpers/ExampleRunner.cs @@ -0,0 +1,146 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Text; + +using UnityEngine; +using UnityEngine.Serialization; + +#if UNITY_EDITOR +using UnityEditor; +#endif + +namespace YamlDotNet.Samples.Helpers { + public class ExampleRunner : MonoBehaviour { + + private StringTestOutputHelper helper = new StringTestOutputHelper(); + + public string[] disabledTests = new string[] {}; + + private class StringTestOutputHelper : ITestOutputHelper { + private StringBuilder output = new StringBuilder(); + public void WriteLine() { + output.AppendLine(); + } + public void WriteLine(string value) { + output.AppendLine(value); + } + public void WriteLine(string format, params object[] args) { + output.AppendFormat(format, args); + output.AppendLine(); + } + + public override string ToString() { return output.ToString(); } + public void Clear() { output = new StringBuilder(); } + } + + public static string[] GetAllTestNames() { + bool skipMethods; + var results = new List(); + foreach (Type t in Assembly.GetExecutingAssembly().GetTypes()) { + if (t.Namespace == "YamlDotNet.Samples" && t.IsClass) { + skipMethods = false; + foreach (MethodInfo mi in t.GetMethods()) { + if (mi.Name == "Main") { + SampleAttribute sa = (SampleAttribute) Attribute.GetCustomAttribute(mi, typeof(SampleAttribute)); + if (sa != null) { + results.Add(t.Name); + skipMethods = true; + break; + } + } + if (skipMethods) break; + } + } + } + return results.ToArray(); + } + + public static string[] GetAllTestTitles() { + bool skipMethods; + var results = new List(); + foreach (Type t in Assembly.GetExecutingAssembly().GetTypes()) { + if (t.Namespace == "YamlDotNet.Samples" && t.IsClass) { + skipMethods = false; + foreach (MethodInfo mi in t.GetMethods()) { + if (mi.Name == "Main") { + SampleAttribute sa = (SampleAttribute) Attribute.GetCustomAttribute(mi, typeof(SampleAttribute)); + if (sa != null) { + results.Add(sa.Title); + skipMethods = true; + break; + } + } + if (skipMethods) break; + } + } + } + return results.ToArray(); + } + + private void Start() { + bool skipMethods; + foreach (Type t in Assembly.GetExecutingAssembly().GetTypes()) { + if (t.Namespace == "YamlDotNet.Samples" && t.IsClass && Array.IndexOf(disabledTests, t.Name) == -1) { + skipMethods = false; + foreach (MethodInfo mi in t.GetMethods()) { + if (mi.Name == "Main") { + SampleAttribute sa = (SampleAttribute) Attribute.GetCustomAttribute(mi, typeof(SampleAttribute)); + if (sa != null) { + helper.WriteLine("{0} - {1}", sa.Title, sa.Description); + var testObject = t.GetConstructor(new Type[] { typeof(StringTestOutputHelper) }).Invoke(new object[] { helper }); + mi.Invoke(testObject, new object[] {}); + Debug.Log(helper.ToString()); + helper.Clear(); + skipMethods = true; + break; + } + } + if (skipMethods) break; + } + } + } + } + } + +#if UNITY_EDITOR + [CustomEditor(typeof(ExampleRunner))] + public class ExampleRunnerEditor : Editor { + private ExampleRunner runner; + private string[] allTests; + private string[] allTitles; + private bool[] enabledTests; + + public void OnEnable() { + runner = (ExampleRunner) target; + + allTests = ExampleRunner.GetAllTestNames(); + allTitles = ExampleRunner.GetAllTestTitles(); + enabledTests = new bool[allTests.Length]; + for (int i = 0; i < allTests.Length; i++) + enabledTests[i] = Array.IndexOf(runner.disabledTests, allTests[i]) == -1; + } + + public override void OnInspectorGUI() { + int nextDisabledIndex = 0; + for (int i = 0; i < allTests.Length; i++) { + EditorGUI.BeginChangeCheck(); + if (!enabledTests[i]) + nextDisabledIndex++; + enabledTests[i] = EditorGUILayout.Toggle(allTitles[i], enabledTests[i]); + if (EditorGUI.EndChangeCheck()) { + if (enabledTests[i]) { + var l = new List(runner.disabledTests); + l.Remove(allTests[i]); + runner.disabledTests = l.ToArray(); + } else { + var l = new List(runner.disabledTests); + l.Insert(nextDisabledIndex, allTests[i]); + runner.disabledTests = l.ToArray(); + } + } + } + } + } +#endif +} diff --git a/YamlDotNet/Examples/Helpers/ExampleRunner.cs.meta b/YamlDotNet/Examples/Helpers/ExampleRunner.cs.meta new file mode 100644 index 0000000..1dbf03a --- /dev/null +++ b/YamlDotNet/Examples/Helpers/ExampleRunner.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6c2d347068a20b442a3cdbf631ad8ab3 +timeCreated: 1485609837 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Examples/Helpers/SampleAttribute.cs b/YamlDotNet/Examples/Helpers/SampleAttribute.cs new file mode 100644 index 0000000..6c4e9f7 --- /dev/null +++ b/YamlDotNet/Examples/Helpers/SampleAttribute.cs @@ -0,0 +1,26 @@ +using System; + +namespace YamlDotNet.Samples.Helpers +{ + /// + /// Marks a test as being a code sample. + /// + internal class SampleAttribute : Attribute + { + private string title; + + public string DisplayName { get; private set; } + + public string Title + { + get { return title; } + set + { + title = value; + DisplayName = "Sample: " + value; + } + } + + public string Description { get; set; } + } +} diff --git a/YamlDotNet/Examples/Helpers/SampleAttribute.cs.meta b/YamlDotNet/Examples/Helpers/SampleAttribute.cs.meta new file mode 100644 index 0000000..e4ec822 --- /dev/null +++ b/YamlDotNet/Examples/Helpers/SampleAttribute.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6bda79cf503a621448a23f79270d7184 +timeCreated: 1485603636 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Examples/Helpers/TestOutputHelperExtensions.cs b/YamlDotNet/Examples/Helpers/TestOutputHelperExtensions.cs new file mode 100644 index 0000000..52f72db --- /dev/null +++ b/YamlDotNet/Examples/Helpers/TestOutputHelperExtensions.cs @@ -0,0 +1,10 @@ +namespace YamlDotNet.Samples.Helpers +{ + public static class TestOutputHelperExtensions + { + public static void WriteLine(this ITestOutputHelper output) + { + output.WriteLine(string.Empty); + } + } +} diff --git a/YamlDotNet/Examples/Helpers/TestOutputHelperExtensions.cs.meta b/YamlDotNet/Examples/Helpers/TestOutputHelperExtensions.cs.meta new file mode 100644 index 0000000..7b8216e --- /dev/null +++ b/YamlDotNet/Examples/Helpers/TestOutputHelperExtensions.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d8ac1e6d1ee681b4796f24feda0ca81d +timeCreated: 1485603636 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Examples/LoadingAYamlStream.cs b/YamlDotNet/Examples/LoadingAYamlStream.cs new file mode 100644 index 0000000..6225cb0 --- /dev/null +++ b/YamlDotNet/Examples/LoadingAYamlStream.cs @@ -0,0 +1,85 @@ +using System; +using System.IO; +using YamlDotNet.RepresentationModel; +using YamlDotNet.Samples.Helpers; + +namespace YamlDotNet.Samples +{ + public class LoadingAYamlStream + { + private readonly ITestOutputHelper output; + + public LoadingAYamlStream(ITestOutputHelper output) + { + this.output = output; + } + + [Sample( + Title = "Loading a YAML Stream", + Description = "Explains how to load YAML using the representation model." + )] + public void Main() + { + // Setup the input + var input = new StringReader(Document); + + // Load the stream + var yaml = new YamlStream(); + yaml.Load(input); + + // Examine the stream + var mapping = + (YamlMappingNode)yaml.Documents[0].RootNode; + + foreach (var entry in mapping.Children) + { + output.WriteLine(((YamlScalarNode)entry.Key).Value); + } + + // List all the items + var items = (YamlSequenceNode)mapping.Children[new YamlScalarNode("items")]; + foreach (YamlMappingNode item in items) + { + output.WriteLine( + "{0}\t{1}", + item.Children[new YamlScalarNode("part_no")], + item.Children[new YamlScalarNode("descrip")] + ); + } + } + + private const string Document = @"--- + receipt: Oz-Ware Purchase Invoice + date: 2007-08-06 + customer: + given: Dorothy + family: Gale + + items: + - part_no: A4786 + descrip: Water Bucket (Filled) + price: 1.47 + quantity: 4 + + - part_no: E1628 + descrip: High Heeled ""Ruby"" Slippers + price: 100.27 + quantity: 1 + + bill-to: &id001 + street: | + 123 Tornado Alley + Suite 16 + city: East Westville + state: KS + + ship-to: *id001 + + specialDelivery: > + Follow the Yellow Brick + Road to the Emerald City. + Pay no attention to the + man behind the curtain. +..."; + } +} diff --git a/YamlDotNet/Examples/LoadingAYamlStream.cs.meta b/YamlDotNet/Examples/LoadingAYamlStream.cs.meta new file mode 100644 index 0000000..89b202f --- /dev/null +++ b/YamlDotNet/Examples/LoadingAYamlStream.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 29c4a0e11ccbfef4bac57240ea978b91 +timeCreated: 1429642459 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Examples/SerializeObjectGraph.cs b/YamlDotNet/Examples/SerializeObjectGraph.cs new file mode 100644 index 0000000..659229b --- /dev/null +++ b/YamlDotNet/Examples/SerializeObjectGraph.cs @@ -0,0 +1,96 @@ +using System; +using YamlDotNet.Serialization; +using YamlDotNet.Samples.Helpers; + +namespace YamlDotNet.Samples +{ + public class SerializeObjectGraph + { + private readonly ITestOutputHelper output; + + public SerializeObjectGraph(ITestOutputHelper output) + { + this.output = output; + } + + [Sample( + Title = "Serializing an object graph", + Description = "Shows how to convert an object to its YAML representation." + )] + public void Main() + { + var address = new Address + { + street = "123 Tornado Alley\nSuite 16", + city = "East Westville", + state = "KS" + }; + + var receipt = new Receipt + { + receipt = "Oz-Ware Purchase Invoice", + date = new DateTime(2007, 8, 6), + customer = new Customer + { + given = "Dorothy", + family = "Gale" + }, + items = new Item[] + { + new Item + { + part_no = "A4786", + descrip = "Water Bucket (Filled)", + price = 1.47M, + quantity = 4 + }, + new Item + { + part_no = "E1628", + descrip = "High Heeled \"Ruby\" Slippers", + price = 100.27M, + quantity = 1 + } + }, + bill_to = address, + ship_to = address, + specialDelivery = "Follow the Yellow Brick\n" + + "Road to the Emerald City.\n" + + "Pay no attention to the\n" + + "man behind the curtain." + }; + + var serializer = new SerializerBuilder().Build(); + var yaml = serializer.Serialize(receipt); + output.WriteLine(yaml); + } + } + + public class Address { + public string street { get; set; } + public string city { get; set; } + public string state { get; set; } + } + + public class Receipt { + public string receipt { get; set; } + public DateTime date { get; set; } + public Customer customer { get; set; } + public Item[] items { get; set; } + public Address bill_to { get; set; } + public Address ship_to { get; set; } + public string specialDelivery { get; set; } + } + + public class Customer { + public string given { get; set; } + public string family { get; set; } + } + + public class Item { + public string part_no { get; set; } + public string descrip { get; set; } + public decimal price { get; set; } + public int quantity { get; set; } + } +} diff --git a/YamlDotNet/Examples/SerializeObjectGraph.cs.meta b/YamlDotNet/Examples/SerializeObjectGraph.cs.meta new file mode 100644 index 0000000..6b01a43 --- /dev/null +++ b/YamlDotNet/Examples/SerializeObjectGraph.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 61d71e4f1e5e17c469a4362b7b1a7665 +timeCreated: 1429641700 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Helpers.meta b/YamlDotNet/Helpers.meta new file mode 100644 index 0000000..ab0c8f0 --- /dev/null +++ b/YamlDotNet/Helpers.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 7ac880b702dadf24183b628b2243ab7d +folderAsset: yes +timeCreated: 1427145262 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Helpers/ExpressionExtensions.cs b/YamlDotNet/Helpers/ExpressionExtensions.cs new file mode 100644 index 0000000..2b52fed --- /dev/null +++ b/YamlDotNet/Helpers/ExpressionExtensions.cs @@ -0,0 +1,62 @@ +using System; +using System.Linq.Expressions; +using System.Reflection; + +namespace YamlDotNet.Helpers +{ + public static class ExpressionExtensions + { + /// + /// Returns the that describes the property that + /// is being returned in an expression in the form: + /// + /// x => x.SomeProperty + /// + /// + public static PropertyInfo AsProperty(this LambdaExpression propertyAccessor) + { + var property = TryGetMemberExpression(propertyAccessor); + if (property == null) + { + throw new ArgumentException("Expected a lambda expression in the form: x => x.SomeProperty", "propertyAccessor"); + } + + return property; + } + + private static TMemberInfo TryGetMemberExpression(LambdaExpression lambdaExpression) + where TMemberInfo : MemberInfo + { + if (lambdaExpression.Parameters.Count != 1) + { + return null; + } + + var body = lambdaExpression.Body; + + var castExpression = body as UnaryExpression; + if (castExpression != null) + { + if (castExpression.NodeType != ExpressionType.Convert) + { + return null; + } + + body = castExpression.Operand; + } + + var memberExpression = body as MemberExpression; + if (memberExpression == null) + { + return null; + } + + if (memberExpression.Expression != lambdaExpression.Parameters[0]) + { + return null; + } + + return memberExpression.Member as TMemberInfo; + } + } +} diff --git a/YamlDotNet/Helpers/ExpressionExtensions.cs.meta b/YamlDotNet/Helpers/ExpressionExtensions.cs.meta new file mode 100644 index 0000000..88b9e94 --- /dev/null +++ b/YamlDotNet/Helpers/ExpressionExtensions.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b3ef112ac5442354085c4e3adaf8c612 +timeCreated: 1485601085 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Helpers/GenericCollectionToNonGenericAdapter.cs b/YamlDotNet/Helpers/GenericCollectionToNonGenericAdapter.cs new file mode 100644 index 0000000..ffe9c1e --- /dev/null +++ b/YamlDotNet/Helpers/GenericCollectionToNonGenericAdapter.cs @@ -0,0 +1,136 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Collections; +using System.Reflection; + +namespace YamlDotNet.Helpers +{ + /// + /// Adapts an to + /// because not all generic collections implement . + /// + internal sealed class GenericCollectionToNonGenericAdapter : IList + { + private readonly object genericCollection; + private readonly MethodInfo addMethod; + private readonly MethodInfo indexerSetter; + private readonly MethodInfo countGetter; + + public GenericCollectionToNonGenericAdapter(object genericCollection, Type genericCollectionType, Type genericListType) + { + this.genericCollection = genericCollection; + + addMethod = genericCollectionType.GetPublicInstanceMethod("Add"); + countGetter = genericCollectionType.GetPublicProperty("Count").GetGetMethod(); + + if (genericListType != null) + { + indexerSetter = genericListType.GetPublicProperty("Item").GetSetMethod(); + } + } + + public int Add(object value) + { + var index = (int)countGetter.Invoke(genericCollection, null); + addMethod.Invoke(genericCollection, new object[] { value }); + return index; + } + + public void Clear() + { + throw new NotSupportedException(); + } + + public bool Contains(object value) + { + throw new NotSupportedException(); + } + + public int IndexOf(object value) + { + throw new NotSupportedException(); + } + + public void Insert(int index, object value) + { + throw new NotSupportedException(); + } + + public bool IsFixedSize + { + get { throw new NotSupportedException(); } + } + + public bool IsReadOnly + { + get { throw new NotSupportedException(); } + } + + public void Remove(object value) + { + throw new NotSupportedException(); + } + + public void RemoveAt(int index) + { + throw new NotSupportedException(); + } + + public object this[int index] + { + get + { + throw new NotSupportedException(); + } + set + { + indexerSetter.Invoke(genericCollection, new object[] { index, value }); + } + } + + public void CopyTo(Array array, int index) + { + throw new NotSupportedException(); + } + + public int Count + { + get { throw new NotSupportedException(); } + } + + public bool IsSynchronized + { + get { throw new NotSupportedException(); } + } + + public object SyncRoot + { + get { throw new NotSupportedException(); } + } + + public IEnumerator GetEnumerator() + { + return ((IEnumerable)genericCollection).GetEnumerator(); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Helpers/GenericCollectionToNonGenericAdapter.cs.meta b/YamlDotNet/Helpers/GenericCollectionToNonGenericAdapter.cs.meta new file mode 100644 index 0000000..a0fffef --- /dev/null +++ b/YamlDotNet/Helpers/GenericCollectionToNonGenericAdapter.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: c773704ccfcc20642a3e3fa7f77562b6 +timeCreated: 1454664016 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Helpers/GenericDictionaryToNonGenericAdapter.cs b/YamlDotNet/Helpers/GenericDictionaryToNonGenericAdapter.cs new file mode 100644 index 0000000..60dec94 --- /dev/null +++ b/YamlDotNet/Helpers/GenericDictionaryToNonGenericAdapter.cs @@ -0,0 +1,180 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; + +namespace YamlDotNet.Helpers +{ + /// + /// Adapts an to + /// because not all generic dictionaries implement . + /// + internal sealed class GenericDictionaryToNonGenericAdapter : IDictionary + { + private readonly object genericDictionary; + private readonly Type genericDictionaryType; + private readonly MethodInfo indexerSetter; + + public GenericDictionaryToNonGenericAdapter(object genericDictionary, Type genericDictionaryType) + { + this.genericDictionary = genericDictionary; + this.genericDictionaryType = genericDictionaryType; + + indexerSetter = genericDictionaryType.GetPublicProperty("Item").GetSetMethod(); + } + + public void Add(object key, object value) + { + throw new NotSupportedException(); + } + + public void Clear() + { + throw new NotSupportedException(); + } + + public bool Contains(object key) + { + throw new NotSupportedException(); + } + + public IDictionaryEnumerator GetEnumerator() + { + return new DictionaryEnumerator(genericDictionary, genericDictionaryType); + } + + public bool IsFixedSize + { + get { throw new NotSupportedException(); } + } + + public bool IsReadOnly + { + get { throw new NotSupportedException(); } + } + + public ICollection Keys + { + get { throw new NotSupportedException(); } + } + + public void Remove(object key) + { + throw new NotSupportedException(); + } + + public ICollection Values + { + get { throw new NotSupportedException(); } + } + + public object this[object key] + { + get + { + throw new NotSupportedException(); + } + set + { + indexerSetter.Invoke(genericDictionary, new object[] { key, value }); + } + } + + public void CopyTo(Array array, int index) + { + throw new NotSupportedException(); + } + + public int Count + { + get { throw new NotSupportedException(); } + } + + public bool IsSynchronized + { + get { throw new NotSupportedException(); } + } + + public object SyncRoot + { + get { throw new NotSupportedException(); } + } + + IEnumerator IEnumerable.GetEnumerator() + { + return ((IEnumerable)genericDictionary).GetEnumerator(); + } + + private class DictionaryEnumerator : IDictionaryEnumerator + { + private readonly IEnumerator enumerator; + private readonly MethodInfo getKeyMethod; + private readonly MethodInfo getValueMethod; + + public DictionaryEnumerator(object genericDictionary, Type genericDictionaryType) + { + var genericArguments = genericDictionaryType.GetGenericArguments(); + var keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); + + getKeyMethod = keyValuePairType.GetPublicProperty("Key").GetGetMethod(); + getValueMethod = keyValuePairType.GetPublicProperty("Value").GetGetMethod(); + + enumerator = ((IEnumerable)genericDictionary).GetEnumerator(); + } + + public DictionaryEntry Entry + { + get + { + return new DictionaryEntry(Key, Value); + } + } + + public object Key + { + get { return getKeyMethod.Invoke(enumerator.Current, null); } + } + + public object Value + { + get { return getValueMethod.Invoke(enumerator.Current, null); } + } + + public object Current + { + get { return Entry; } + } + + public bool MoveNext() + { + return enumerator.MoveNext(); + } + + public void Reset() + { + enumerator.Reset(); + } + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Helpers/GenericDictionaryToNonGenericAdapter.cs.meta b/YamlDotNet/Helpers/GenericDictionaryToNonGenericAdapter.cs.meta new file mode 100644 index 0000000..9e47647 --- /dev/null +++ b/YamlDotNet/Helpers/GenericDictionaryToNonGenericAdapter.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: cffb108910d12a64da4065701f0ae0bf +timeCreated: 1454664016 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Helpers/ITestOutputHelper.cs b/YamlDotNet/Helpers/ITestOutputHelper.cs new file mode 100644 index 0000000..592939b --- /dev/null +++ b/YamlDotNet/Helpers/ITestOutputHelper.cs @@ -0,0 +1,8 @@ +namespace YamlDotNet.Samples.Helpers +{ + public interface ITestOutputHelper { + void WriteLine(); + void WriteLine(string value); + void WriteLine(string format, params object[] args); + } +} diff --git a/YamlDotNet/Helpers/ITestOutputHelper.cs.meta b/YamlDotNet/Helpers/ITestOutputHelper.cs.meta new file mode 100644 index 0000000..81cf805 --- /dev/null +++ b/YamlDotNet/Helpers/ITestOutputHelper.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 8bf0bb99b386041429154edb2eec127f +timeCreated: 1485606138 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Helpers/Portability.cs b/YamlDotNet/Helpers/Portability.cs new file mode 100644 index 0000000..d0b457f --- /dev/null +++ b/YamlDotNet/Helpers/Portability.cs @@ -0,0 +1,152 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Reflection; +using System.Text.RegularExpressions; + +namespace YamlDotNet +{ + internal static class StandardRegexOptions + { + public const RegexOptions Compiled = RegexOptions.None; + } + + internal static class ReflectionExtensions + { + public static Type BaseType(this Type type) + { + return type.BaseType; + } + + public static bool IsValueType(this Type type) + { + return type.IsValueType; + } + + public static bool IsGenericType(this Type type) + { + return type.IsGenericType; + } + + public static bool IsInterface(this Type type) + { + return type.IsInterface; + } + + public static bool IsEnum(this Type type) + { + return type.IsEnum; + } + + /// + /// Determines whether the specified type has a default constructor. + /// + /// The type. + /// + /// true if the type has a default constructor; otherwise, false. + /// + public static bool HasDefaultConstructor(this Type type) + { + return type.IsValueType || type.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, Type.EmptyTypes, null) != null; + } + + public static TypeCode GetTypeCode(this Type type) + { + return Type.GetTypeCode(type); + } + + public static PropertyInfo GetPublicProperty(this Type type, string name) + { + return type.GetProperty(name); + } + + public static IEnumerable GetPublicProperties(this Type type) + { + var instancePublic = BindingFlags.Instance | BindingFlags.Public; + return type.IsInterface + ? (new Type[] { type }) + .Concat(type.GetInterfaces()) + .SelectMany(i => i.GetProperties(instancePublic)) + : type.GetProperties(instancePublic); + } + + public static IEnumerable GetPublicStaticMethods(this Type type) + { + return type.GetMethods(BindingFlags.Static | BindingFlags.Public); + } + + public static MethodInfo GetPublicStaticMethod(this Type type, string name, params Type[] parameterTypes) + { + return type.GetMethod(name, BindingFlags.Public | BindingFlags.Static, null, parameterTypes, null); + } + + public static MethodInfo GetPublicInstanceMethod(this Type type, string name) + { + return type.GetMethod(name, BindingFlags.Public | BindingFlags.Instance); + } + + private static readonly FieldInfo remoteStackTraceField = typeof(Exception) + .GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic); + + public static Exception Unwrap(this TargetInvocationException ex) + { + var result = ex.InnerException; + if (remoteStackTraceField != null) + { + remoteStackTraceField.SetValue(ex.InnerException, ex.InnerException.StackTrace + "\r\n"); + } + return result; + } + + public static bool IsInstanceOf(this Type type, object o) + { + return type.IsInstanceOfType(o); + } + } + + internal sealed class CultureInfoAdapter : CultureInfo + { + private readonly IFormatProvider _provider; + + public CultureInfoAdapter(CultureInfo baseCulture, IFormatProvider provider) + : base(baseCulture.LCID) + { + _provider = provider; + } + + public override object GetFormat(Type formatType) + { + return _provider.GetFormat(formatType); + } + } + + internal static class PropertyInfoExtensions + { + public static object ReadValue(this PropertyInfo property, object target) + { + return property.GetGetMethod().Invoke(target, null); + } + } +} diff --git a/YamlDotNet/Helpers/Portability.cs.meta b/YamlDotNet/Helpers/Portability.cs.meta new file mode 100644 index 0000000..39630ed --- /dev/null +++ b/YamlDotNet/Helpers/Portability.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 7ad2c6ea921f63842a2787da8eb89b15 +timeCreated: 1427495772 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Readme.txt b/YamlDotNet/Readme.txt new file mode 100644 index 0000000..11a4481 --- /dev/null +++ b/YamlDotNet/Readme.txt @@ -0,0 +1,9 @@ +This is a port of the YamlDotNet library for Unity. + +It has been tested and works with .net 2.0 subset, AOT compilation and even IL2CPP. +Platforms that have been tested includes PS Vita, Android, IOS and Desktop. + +Please read the example code for a quick introduction to the YamlDotNet library. + +If you get into trouble, you can browse the web for YamlDotNet information, +or you could send me an email ( post@fredrik.ludvigsen.name ). diff --git a/YamlDotNet/Readme.txt.meta b/YamlDotNet/Readme.txt.meta new file mode 100644 index 0000000..4466937 --- /dev/null +++ b/YamlDotNet/Readme.txt.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5878fe3c964cf444eae1b86940714d35 +timeCreated: 1429646563 +licenseType: Store +TextScriptImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/RepresentationModel.meta b/YamlDotNet/RepresentationModel.meta new file mode 100644 index 0000000..8d693ca --- /dev/null +++ b/YamlDotNet/RepresentationModel.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 5fc62dc1192c2f3449e48214d2e02c6a +folderAsset: yes +timeCreated: 1427145262 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/RepresentationModel/DocumentLoadingState.cs b/YamlDotNet/RepresentationModel/DocumentLoadingState.cs new file mode 100644 index 0000000..73ed968 --- /dev/null +++ b/YamlDotNet/RepresentationModel/DocumentLoadingState.cs @@ -0,0 +1,105 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Globalization; +using YamlDotNet.Core; + +namespace YamlDotNet.RepresentationModel +{ + /// + /// Manages the state of a while it is loading. + /// + internal class DocumentLoadingState + { + private readonly IDictionary anchors = new Dictionary(); + private readonly IList nodesWithUnresolvedAliases = new List(); + + /// + /// Adds the specified node to the anchor list. + /// + /// The node. + public void AddAnchor(YamlNode node) + { + if (node.Anchor == null) + { + throw new ArgumentException("The specified node does not have an anchor"); + } + + if (anchors.ContainsKey(node.Anchor)) + { + anchors[node.Anchor] = node; + } + else + { + anchors.Add(node.Anchor, node); + } + } + + /// + /// Gets the node with the specified anchor. + /// + /// The anchor. + /// if set to true, the method should throw an exception if there is no node with that anchor. + /// The start position. + /// The end position. + /// + public YamlNode GetNode(string anchor, bool throwException, Mark start, Mark end) + { + YamlNode target; + if (anchors.TryGetValue(anchor, out target)) + { + return target; + } + else if (throwException) + { + throw new AnchorNotFoundException(start, end, string.Format(CultureInfo.InvariantCulture, "The anchor '{0}' does not exists", anchor)); + } + else + { + return null; + } + } + + /// + /// Adds the specified node to the collection of nodes with unresolved aliases. + /// + /// + /// The that has unresolved aliases. + /// + public void AddNodeWithUnresolvedAliases(YamlNode node) + { + nodesWithUnresolvedAliases.Add(node); + } + + /// + /// Resolves the aliases that could not be resolved while loading the document. + /// + public void ResolveAliases() + { + foreach (var node in nodesWithUnresolvedAliases) + { + node.ResolveAliases(this); + } + } + } +} \ No newline at end of file diff --git a/YamlDotNet/RepresentationModel/DocumentLoadingState.cs.meta b/YamlDotNet/RepresentationModel/DocumentLoadingState.cs.meta new file mode 100644 index 0000000..14acc8a --- /dev/null +++ b/YamlDotNet/RepresentationModel/DocumentLoadingState.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 5b2c2b39b93a5fa4a973c6e52accea86 +timeCreated: 1427145264 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/RepresentationModel/EmitterState.cs b/YamlDotNet/RepresentationModel/EmitterState.cs new file mode 100644 index 0000000..4e02f9e --- /dev/null +++ b/YamlDotNet/RepresentationModel/EmitterState.cs @@ -0,0 +1,45 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System.Collections.Generic; + +namespace YamlDotNet.RepresentationModel +{ + /// + /// Holds state that is used when emitting a stream. + /// + internal class EmitterState + { + private readonly HashSet emittedAnchors = new HashSet(); + + /// + /// Gets the already emitted anchors. + /// + /// The emitted anchors. + public HashSet EmittedAnchors + { + get + { + return emittedAnchors; + } + } + } +} \ No newline at end of file diff --git a/YamlDotNet/RepresentationModel/EmitterState.cs.meta b/YamlDotNet/RepresentationModel/EmitterState.cs.meta new file mode 100644 index 0000000..ad6f241 --- /dev/null +++ b/YamlDotNet/RepresentationModel/EmitterState.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: c3761b6b22a04a24fade56273bbb3c5b +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/RepresentationModel/IYamlVisitor.cs b/YamlDotNet/RepresentationModel/IYamlVisitor.cs new file mode 100644 index 0000000..669e9e1 --- /dev/null +++ b/YamlDotNet/RepresentationModel/IYamlVisitor.cs @@ -0,0 +1,71 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace YamlDotNet.RepresentationModel +{ + /// + /// Defines the method needed to be able to visit Yaml elements. + /// + public interface IYamlVisitor + { + /// + /// Visits a . + /// + /// + /// The that is being visited. + /// + void Visit(YamlStream stream); + + /// + /// Visits a . + /// + /// + /// The that is being visited. + /// + void Visit(YamlDocument document); + + /// + /// Visits a . + /// + /// + /// The that is being visited. + /// + void Visit(YamlScalarNode scalar); + + /// + /// Visits a . + /// + /// + /// The that is being visited. + /// + void Visit(YamlSequenceNode sequence); + + /// + /// Visits a . + /// + /// + /// The that is being visited. + /// + void Visit(YamlMappingNode mapping); + } +} \ No newline at end of file diff --git a/YamlDotNet/RepresentationModel/IYamlVisitor.cs.meta b/YamlDotNet/RepresentationModel/IYamlVisitor.cs.meta new file mode 100644 index 0000000..ffa7249 --- /dev/null +++ b/YamlDotNet/RepresentationModel/IYamlVisitor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: e12b6dd8690a6674696c7a997fdbd895 +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/RepresentationModel/YamlAliasNode.cs b/YamlDotNet/RepresentationModel/YamlAliasNode.cs new file mode 100644 index 0000000..70fa389 --- /dev/null +++ b/YamlDotNet/RepresentationModel/YamlAliasNode.cs @@ -0,0 +1,120 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using YamlDotNet.Core; + +namespace YamlDotNet.RepresentationModel +{ + /// + /// Represents an alias node in the YAML document. + /// + [Serializable] + internal class YamlAliasNode : YamlNode + { + /// + /// Initializes a new instance of the class. + /// + /// The anchor. + internal YamlAliasNode(string anchor) + { + Anchor = anchor; + } + + /// + /// Resolves the aliases that could not be resolved when the node was created. + /// + /// The state of the document. + internal override void ResolveAliases(DocumentLoadingState state) + { + throw new NotSupportedException("Resolving an alias on an alias node does not make sense"); + } + + /// + /// Saves the current node to the specified emitter. + /// + /// The emitter where the node is to be saved. + /// The state. + internal override void Emit(IEmitter emitter, EmitterState state) + { + throw new NotSupportedException("A YamlAliasNode is an implementation detail and should never be saved."); + } + + /// + /// Accepts the specified visitor by calling the appropriate Visit method on it. + /// + /// + /// A . + /// + public override void Accept(IYamlVisitor visitor) + { + throw new NotSupportedException("A YamlAliasNode is an implementation detail and should never be visited."); + } + + /// + public override bool Equals(object obj) + { + var other = obj as YamlAliasNode; + return other != null && Equals(other) && SafeEquals(Anchor, other.Anchor); + } + + /// + /// Serves as a hash function for a particular type. + /// + /// + /// A hash code for the current . + /// + public override int GetHashCode() + { + return base.GetHashCode(); + } + + /// + /// Returns a that represents this instance. + /// + /// + /// A that represents this instance. + /// + internal override string ToString(RecursionLevel level) + { + return "*" + Anchor; + } + + /// + /// Recursively enumerates all the nodes from the document, starting on the current node, + /// and throwing + /// if is reached. + /// + internal override IEnumerable SafeAllNodes(RecursionLevel level) + { + yield return this; + } + + /// + /// Gets the type of node. + /// + public override YamlNodeType NodeType + { + get { return YamlNodeType.Alias; } + } + } +} \ No newline at end of file diff --git a/YamlDotNet/RepresentationModel/YamlAliasNode.cs.meta b/YamlDotNet/RepresentationModel/YamlAliasNode.cs.meta new file mode 100644 index 0000000..24fe21c --- /dev/null +++ b/YamlDotNet/RepresentationModel/YamlAliasNode.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 72c7427f0fab35849b7545d301debcd5 +timeCreated: 1427145264 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/RepresentationModel/YamlDocument.cs b/YamlDotNet/RepresentationModel/YamlDocument.cs new file mode 100644 index 0000000..9ad140d --- /dev/null +++ b/YamlDotNet/RepresentationModel/YamlDocument.cs @@ -0,0 +1,208 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using YamlDotNet.Core; +using YamlDotNet.Core.Events; + +namespace YamlDotNet.RepresentationModel +{ + /// + /// Represents an YAML document. + /// + [Serializable] + public class YamlDocument + { + /// + /// Gets or sets the root node. + /// + /// The root node. + public YamlNode RootNode { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + public YamlDocument(YamlNode rootNode) + { + RootNode = rootNode; + } + + /// + /// Initializes a new instance of the class with a single scalar node. + /// + public YamlDocument(string rootNode) + { + RootNode = new YamlScalarNode(rootNode); + } + + /// + /// Initializes a new instance of the class. + /// + internal YamlDocument(IParser parser) + { + var state = new DocumentLoadingState(); + + parser.Expect(); + + while (!parser.Accept()) + { + Debug.Assert(RootNode == null); + RootNode = YamlNode.ParseNode(parser, state); + + if (RootNode is YamlAliasNode) + { + throw new YamlException(); + } + } + + state.ResolveAliases(); + + parser.Expect(); + } + + /// + /// Visitor that assigns anchors to nodes that are referenced more than once. + /// Existing anchors are preserved as much as possible. + /// + private class AnchorAssigningVisitor : YamlVisitorBase + { + private readonly HashSet existingAnchors = new HashSet(); + /// + /// Key: Node, Value: IsDuplicate + /// + private readonly Dictionary visitedNodes = new Dictionary(); + + public void AssignAnchors(YamlDocument document) + { + existingAnchors.Clear(); + visitedNodes.Clear(); + + document.Accept(this); + + var random = new Random(); + foreach (var visitedNode in visitedNodes) + { + if (visitedNode.Value) + { + string anchor; + // If the existing anchor is not already used, we can have it + if (!string.IsNullOrEmpty(visitedNode.Key.Anchor) && !existingAnchors.Contains(visitedNode.Key.Anchor)) + { + anchor = visitedNode.Key.Anchor; + } + else + { + do + { + anchor = random.Next().ToString(CultureInfo.InvariantCulture); + } while (existingAnchors.Contains(anchor)); + } + + existingAnchors.Add(anchor); + visitedNode.Key.Anchor = anchor; + } + } + } + + /// + /// Returns whether the visited node is a duplicate. + /// + private bool VisitNodeAndFindDuplicates(YamlNode node) + { + bool isDuplicate; + if (visitedNodes.TryGetValue(node, out isDuplicate)) + { + if (!isDuplicate) + { + visitedNodes[node] = true; + } + return !isDuplicate; + } + else + { + visitedNodes.Add(node, false); + return false; + } + } + + public override void Visit(YamlScalarNode scalar) + { + VisitNodeAndFindDuplicates(scalar); + } + + public override void Visit(YamlMappingNode mapping) + { + if (!VisitNodeAndFindDuplicates(mapping)) + base.Visit(mapping); + } + + public override void Visit(YamlSequenceNode sequence) + { + if (!VisitNodeAndFindDuplicates(sequence)) + base.Visit(sequence); + } + } + + private void AssignAnchors() + { + var visitor = new AnchorAssigningVisitor(); + visitor.AssignAnchors(this); + } + + internal void Save(IEmitter emitter, bool assignAnchors = true) + { + if (assignAnchors) + { + AssignAnchors(); + } + + emitter.Emit(new DocumentStart()); + RootNode.Save(emitter, new EmitterState()); + emitter.Emit(new DocumentEnd(false)); + } + + /// + /// Accepts the specified visitor by calling the appropriate Visit method on it. + /// + /// + /// A . + /// + public void Accept(IYamlVisitor visitor) + { + visitor.Visit(this); + } + + /// + /// Gets all nodes from the document. + /// is thrown if an infinite recursion is detected. + /// + public IEnumerable AllNodes + { + get + { + return RootNode.AllNodes; + } + } + } +} \ No newline at end of file diff --git a/YamlDotNet/RepresentationModel/YamlDocument.cs.meta b/YamlDotNet/RepresentationModel/YamlDocument.cs.meta new file mode 100644 index 0000000..eb8d3f5 --- /dev/null +++ b/YamlDotNet/RepresentationModel/YamlDocument.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: aa500eae79de1e8429a325722afbf4e8 +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/RepresentationModel/YamlMappingNode.cs b/YamlDotNet/RepresentationModel/YamlMappingNode.cs new file mode 100644 index 0000000..cccae08 --- /dev/null +++ b/YamlDotNet/RepresentationModel/YamlMappingNode.cs @@ -0,0 +1,427 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors +// Copyright (c) 2011 Andy Pickett + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Text; +using YamlDotNet.Core; +using YamlDotNet.Core.Events; +using YamlDotNet.Serialization; + +namespace YamlDotNet.RepresentationModel +{ + /// + /// Represents a mapping node in the YAML document. + /// + [Serializable] + public sealed class YamlMappingNode : YamlNode, IEnumerable>, IYamlConvertible + { + private readonly IDictionary children = new Dictionary(); + + /// + /// Gets the children of the current node. + /// + /// The children. + public IDictionary Children + { + get + { + return children; + } + } + + /// + /// Gets or sets the style of the node. + /// + /// The style. + public MappingStyle Style { get; set; } + + /// + /// Initializes a new instance of the class. + /// + internal YamlMappingNode(IParser parser, DocumentLoadingState state) + { + Load(parser, state); + } + + private void Load(IParser parser, DocumentLoadingState state) + { + var mapping = parser.Expect(); + Load(mapping, state); + Style = mapping.Style; + + bool hasUnresolvedAliases = false; + while (!parser.Accept()) + { + 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(); + } + + /// + /// Initializes a new instance of the class. + /// + public YamlMappingNode() + { + } + + /// + /// Initializes a new instance of the class. + /// + public YamlMappingNode(int dummy) // dummy makes the call to the constructor unambiguous to buggy compilers like mono in Unity. + { + } + + /// + /// Initializes a new instance of the class. + /// + public YamlMappingNode(params KeyValuePair[] children) + : this((IEnumerable>)children) + { + } + + /// + /// Initializes a new instance of the class. + /// + public YamlMappingNode(IEnumerable> children) + { + foreach (var child in children) + { + this.children.Add(child); + } + } + + /// + /// Initializes a new instance of the class. + /// + /// A sequence of where even elements are keys and odd elements are values. + public YamlMappingNode(params YamlNode[] children) + : this((IEnumerable)children) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// A sequence of where even elements are keys and odd elements are values. + public YamlMappingNode(IEnumerable children) + { + using (var enumerator = children.GetEnumerator()) + { + while (enumerator.MoveNext()) + { + var key = enumerator.Current; + if (!enumerator.MoveNext()) + { + throw new ArgumentException("When constructing a mapping node with a sequence, the number of elements of the sequence must be even."); + } + + Add(key, enumerator.Current); + } + } + } + + /// + /// Adds the specified mapping to the collection. + /// + /// The key node. + /// The value node. + public void Add(YamlNode key, YamlNode value) + { + children.Add(key, value); + } + + /// + /// Adds the specified mapping to the collection. + /// + /// The key node. + /// The value node. + public void Add(string key, YamlNode value) + { + children.Add(new YamlScalarNode(key), value); + } + + /// + /// Adds the specified mapping to the collection. + /// + /// The key node. + /// The value node. + public void Add(YamlNode key, string value) + { + children.Add(key, new YamlScalarNode(value)); + } + + /// + /// Adds the specified mapping to the collection. + /// + /// The key node. + /// The value node. + public void Add(string key, string value) + { + children.Add(new YamlScalarNode(key), new YamlScalarNode(value)); + } + + /// + /// Resolves the aliases that could not be resolved when the node was created. + /// + /// The state of the document. + internal override void ResolveAliases(DocumentLoadingState state) + { + Dictionary keysToUpdate = null; + Dictionary valuesToUpdate = null; + foreach (var entry in children) + { + if (entry.Key is YamlAliasNode) + { + if (keysToUpdate == null) + { + keysToUpdate = new Dictionary(); + } + keysToUpdate.Add(entry.Key, state.GetNode(entry.Key.Anchor, true, entry.Key.Start, entry.Key.End)); + } + if (entry.Value is YamlAliasNode) + { + if (valuesToUpdate == null) + { + valuesToUpdate = new Dictionary(); + } + valuesToUpdate.Add(entry.Key, state.GetNode(entry.Value.Anchor, true, entry.Value.Start, entry.Value.End)); + } + } + if (valuesToUpdate != null) + { + foreach (var entry in valuesToUpdate) + { + children[entry.Key] = entry.Value; + } + } + if (keysToUpdate != null) + { + foreach (var entry in keysToUpdate) + { + YamlNode value = children[entry.Key]; + children.Remove(entry.Key); + children.Add(entry.Value, value); + } + } + } + + /// + /// Saves the current node to the specified emitter. + /// + /// The emitter where the node is to be saved. + /// The state. + internal override void Emit(IEmitter emitter, EmitterState state) + { + emitter.Emit(new MappingStart(Anchor, Tag, true, Style)); + foreach (var entry in children) + { + entry.Key.Save(emitter, state); + entry.Value.Save(emitter, state); + } + emitter.Emit(new MappingEnd()); + } + + /// + /// Accepts the specified visitor by calling the appropriate Visit method on it. + /// + /// + /// A . + /// + public override void Accept(IYamlVisitor visitor) + { + visitor.Visit(this); + } + + /// + public override bool Equals(object obj) + { + var other = obj as YamlMappingNode; + if (other == null || !Equals(other) || children.Count != other.children.Count) + { + return false; + } + + foreach (var entry in children) + { + YamlNode otherNode; + if (!other.children.TryGetValue(entry.Key, out otherNode) || !SafeEquals(entry.Value, otherNode)) + { + return false; + } + } + + return true; + } + + /// + /// Serves as a hash function for a particular type. + /// + /// + /// A hash code for the current . + /// + public override int GetHashCode() + { + var hashCode = base.GetHashCode(); + + foreach (var entry in children) + { + hashCode = CombineHashCodes(hashCode, GetHashCode(entry.Key)); + hashCode = CombineHashCodes(hashCode, GetHashCode(entry.Value)); + } + return hashCode; + } + + /// + /// Recursively enumerates all the nodes from the document, starting on the current node, + /// and throwing + /// if is reached. + /// + internal override IEnumerable SafeAllNodes(RecursionLevel level) + { + level.Increment(); + yield return this; + foreach (var child in children) + { + foreach (var node in child.Key.SafeAllNodes(level)) + { + yield return node; + } + foreach (var node in child.Value.SafeAllNodes(level)) + { + yield return node; + } + } + level.Decrement(); + } + + /// + /// Gets the type of node. + /// + public override YamlNodeType NodeType + { + get { return YamlNodeType.Mapping; } + } + + /// + /// Returns a that represents this instance. + /// + /// + /// A that represents this instance. + /// + internal override string ToString(RecursionLevel level) + { + if (!level.TryIncrement()) + { + return MaximumRecursionLevelReachedToStringValue; + } + + var text = new StringBuilder("{ "); + + foreach (var child in children) + { + if (text.Length > 2) + { + text.Append(", "); + } + text.Append("{ ").Append(child.Key.ToString(level)).Append(", ").Append(child.Value.ToString(level)).Append(" }"); + } + + text.Append(" }"); + + level.Decrement(); + + return text.ToString(); + } + + #region IEnumerable> Members + + /// + public IEnumerator> GetEnumerator() + { + return children.GetEnumerator(); + } + + #endregion + + #region IEnumerable Members + + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + #endregion + + void IYamlConvertible.Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) + { + Load(parser, new DocumentLoadingState()); + } + + void IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) + { + Emit(emitter, new EmitterState()); + } + + /// + /// Creates a containing a key-value pair for each property of the specified object. + /// + public static YamlMappingNode FromObject(object mapping) + { + if (mapping == null) + { + throw new ArgumentNullException("mapping"); + } + + var result = new YamlMappingNode(0); + foreach (var property in mapping.GetType().GetPublicProperties()) + { + if (property.CanRead && property.GetGetMethod().GetParameters().Length == 0) + { + var value = property.GetValue(mapping, null); + var valueNode = (value as YamlNode) ?? (Convert.ToString(value)); + result.Add(property.Name, valueNode); + } + } + return result; + } + } +} diff --git a/YamlDotNet/RepresentationModel/YamlMappingNode.cs.meta b/YamlDotNet/RepresentationModel/YamlMappingNode.cs.meta new file mode 100644 index 0000000..62ec437 --- /dev/null +++ b/YamlDotNet/RepresentationModel/YamlMappingNode.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 283c72dc1a159584988a79dd9d0a0a93 +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/RepresentationModel/YamlNode.cs b/YamlDotNet/RepresentationModel/YamlNode.cs new file mode 100644 index 0000000..a746796 --- /dev/null +++ b/YamlDotNet/RepresentationModel/YamlNode.cs @@ -0,0 +1,288 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Linq; +using YamlDotNet.Core; +using YamlDotNet.Core.Events; +using System.Collections.Generic; + +namespace YamlDotNet.RepresentationModel +{ + /// + /// Represents a single node in the YAML document. + /// + [Serializable] + public abstract class YamlNode + { + private const int MaximumRecursionLevel = 1000; + internal const string MaximumRecursionLevelReachedToStringValue = "WARNING! INFINITE RECURSION!"; + + /// + /// Gets or sets the anchor of the node. + /// + /// The anchor. + public string Anchor { get; set; } + + /// + /// Gets or sets the tag of the node. + /// + /// The tag. + public string Tag { get; set; } + + /// + /// Gets the position in the input stream where the event that originated the node starts. + /// + public Mark Start { get; private set; } + + /// + /// Gets the position in the input stream where the event that originated the node ends. + /// + public Mark End { get; private set; } + + /// + /// Loads the specified event. + /// + /// The event. + /// The state of the document. + internal void Load(NodeEvent yamlEvent, DocumentLoadingState state) + { + Tag = yamlEvent.Tag; + if (yamlEvent.Anchor != null) + { + Anchor = yamlEvent.Anchor; + state.AddAnchor(this); + } + Start = yamlEvent.Start; + End = yamlEvent.End; + } + + /// + /// Parses the node represented by the next event in . + /// + /// Returns the node that has been parsed. + static internal YamlNode ParseNode(IParser parser, DocumentLoadingState state) + { + if (parser.Accept()) + { + return new YamlScalarNode(parser, state); + } + + if (parser.Accept()) + { + return new YamlSequenceNode(parser, state); + } + + if (parser.Accept()) + { + return new YamlMappingNode(parser, state); + } + + if (parser.Accept()) + { + var alias = parser.Expect(); + 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"); + } + + /// + /// Resolves the aliases that could not be resolved when the node was created. + /// + /// The state of the document. + internal abstract void ResolveAliases(DocumentLoadingState state); + + /// + /// Saves the current node to the specified emitter. + /// + /// The emitter where the node is to be saved. + /// The state. + internal void Save(IEmitter emitter, EmitterState state) + { + if (!string.IsNullOrEmpty(Anchor) && !state.EmittedAnchors.Add(Anchor)) + { + emitter.Emit(new AnchorAlias(Anchor)); + } + else + { + Emit(emitter, state); + } + } + + /// + /// Saves the current node to the specified emitter. + /// + /// The emitter where the node is to be saved. + /// The state. + internal abstract void Emit(IEmitter emitter, EmitterState state); + + /// + /// Accepts the specified visitor by calling the appropriate Visit method on it. + /// + /// + /// A . + /// + public abstract void Accept(IYamlVisitor visitor); + + /// + /// Provides a basic implementation of Object.Equals + /// + protected bool Equals(YamlNode other) + { + // Do not use the anchor in the equality comparison because that would prevent anchored nodes from being found in dictionaries. + return SafeEquals(Tag, other.Tag); + } + + /// + /// Gets a value indicating whether two objects are equal. + /// + protected static bool SafeEquals(object first, object second) + { + if (first != null) + { + return first.Equals(second); + } + else if (second != null) + { + return second.Equals(first); + } + else + { + return true; + } + } + + /// + /// Serves as a hash function for a particular type. + /// + /// + /// A hash code for the current . + /// + public override int GetHashCode() + { + // Do not use the anchor in the hash code because that would prevent anchored nodes from being found in dictionaries. + return GetHashCode(Tag); + } + + /// + /// Gets the hash code of the specified object, or zero if the object is null. + /// + protected static int GetHashCode(object value) + { + return value == null ? 0 : value.GetHashCode(); + } + + /// + /// Combines two hash codes into one. + /// + protected static int CombineHashCodes(int h1, int h2) + { + return unchecked(((h1 << 5) + h1) ^ h2); + } + + public override string ToString() + { + var level = new RecursionLevel(MaximumRecursionLevel); + return ToString(level); + } + + internal abstract string ToString(RecursionLevel level); + + /// + /// Gets all nodes from the document, starting on the current node. + /// is thrown if an infinite recursion is detected. + /// + public IEnumerable AllNodes + { + get + { + var level = new RecursionLevel(MaximumRecursionLevel); + return SafeAllNodes(level); + } + } + + /// + /// When implemented, recursively enumerates all the nodes from the document, starting on the current node. + /// If is reached, a is thrown + /// instead of continuing and crashing with a . + /// + internal abstract IEnumerable SafeAllNodes(RecursionLevel level); + + /// + /// Gets the type of node. + /// + public abstract YamlNodeType NodeType + { + get; + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static implicit operator YamlNode(string value) + { + return new YamlScalarNode(value); + } + + /// + /// Performs an implicit conversion from string[] to . + /// + /// The value. + /// The result of the conversion. + public static implicit operator YamlNode(string[] sequence) + { + return new YamlSequenceNode(sequence.Select(i => (YamlNode)i)); + } + + /// + /// Converts a to a string by returning its value. + /// + public static explicit operator string(YamlNode scalar) + { + return ((YamlScalarNode)scalar).Value; + } + + /// + /// Gets the nth element in a . + /// + public YamlNode this[int index] + { + get + { + return ((YamlSequenceNode)this).Children[index]; + } + } + + /// + /// Gets the value associated with a key in a . + /// + public YamlNode this[YamlNode key] + { + get + { + return ((YamlMappingNode)this).Children[key]; + } + } + } +} \ No newline at end of file diff --git a/YamlDotNet/RepresentationModel/YamlNode.cs.meta b/YamlDotNet/RepresentationModel/YamlNode.cs.meta new file mode 100644 index 0000000..f12ddbe --- /dev/null +++ b/YamlDotNet/RepresentationModel/YamlNode.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b80625eae8f97124f832aed15c4c6b57 +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/RepresentationModel/YamlNodeIdentityEqualityComparer.cs b/YamlDotNet/RepresentationModel/YamlNodeIdentityEqualityComparer.cs new file mode 100644 index 0000000..e0af058 --- /dev/null +++ b/YamlDotNet/RepresentationModel/YamlNodeIdentityEqualityComparer.cs @@ -0,0 +1,47 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System.Collections.Generic; + +namespace YamlDotNet.RepresentationModel +{ + /// + /// Comparer that is based on identity comparisons. + /// + public sealed class YamlNodeIdentityEqualityComparer : IEqualityComparer + { + #region IEqualityComparer Members + + /// + public bool Equals(YamlNode x, YamlNode y) + { + return ReferenceEquals(x, y); + } + + /// + public int GetHashCode(YamlNode obj) + { + return obj.GetHashCode(); + } + + #endregion + } +} \ No newline at end of file diff --git a/YamlDotNet/RepresentationModel/YamlNodeIdentityEqualityComparer.cs.meta b/YamlDotNet/RepresentationModel/YamlNodeIdentityEqualityComparer.cs.meta new file mode 100644 index 0000000..c88e392 --- /dev/null +++ b/YamlDotNet/RepresentationModel/YamlNodeIdentityEqualityComparer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 70ec622c4d503a448ba4d5410c55d8bd +timeCreated: 1427145264 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/RepresentationModel/YamlNodeType.cs b/YamlDotNet/RepresentationModel/YamlNodeType.cs new file mode 100644 index 0000000..7ca3efd --- /dev/null +++ b/YamlDotNet/RepresentationModel/YamlNodeType.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace YamlDotNet.RepresentationModel +{ + /// + /// Specifies the type of node in the representation model. + /// + public enum YamlNodeType + { + /// + /// The node is a . + /// + Alias, + + /// + /// The node is a . + /// + Mapping, + + /// + /// The node is a . + /// + Scalar, + + /// + /// The node is a . + /// + Sequence + } +} diff --git a/YamlDotNet/RepresentationModel/YamlNodeType.cs.meta b/YamlDotNet/RepresentationModel/YamlNodeType.cs.meta new file mode 100644 index 0000000..5e8b55a --- /dev/null +++ b/YamlDotNet/RepresentationModel/YamlNodeType.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2e67e7d5ff0719c4ebac2a3aa246b96a +timeCreated: 1485601083 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/RepresentationModel/YamlScalarNode.cs b/YamlDotNet/RepresentationModel/YamlScalarNode.cs new file mode 100644 index 0000000..8ec8cd7 --- /dev/null +++ b/YamlDotNet/RepresentationModel/YamlScalarNode.cs @@ -0,0 +1,183 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors +// Copyright (c) 2011 Andy Pickett + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using YamlDotNet.Core; +using YamlDotNet.Core.Events; +using YamlDotNet.Serialization; + +namespace YamlDotNet.RepresentationModel +{ + /// + /// Represents a scalar node in the YAML document. + /// + [DebuggerDisplay("{Value}")] + [Serializable] + public sealed class YamlScalarNode : YamlNode, IYamlConvertible + { + /// + /// Gets or sets the value of the node. + /// + /// The value. + public string Value { get; set; } + + /// + /// Gets or sets the style of the node. + /// + /// The style. + public ScalarStyle Style { get; set; } + + /// + /// Initializes a new instance of the class. + /// + internal YamlScalarNode(IParser parser, DocumentLoadingState state) + { + Load(parser, state); + } + + private void Load(IParser parser, DocumentLoadingState state) + { + var scalar = parser.Expect(); + Load(scalar, state); + Value = scalar.Value; + Style = scalar.Style; + } + + /// + /// Initializes a new instance of the class. + /// + public YamlScalarNode() + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The value. + public YamlScalarNode(string value) + { + this.Value = value; + } + + /// + /// Resolves the aliases that could not be resolved when the node was created. + /// + /// The state of the document. + internal override void ResolveAliases(DocumentLoadingState state) + { + throw new NotSupportedException("Resolving an alias on a scalar node does not make sense"); + } + + /// + /// Saves the current node to the specified emitter. + /// + /// The emitter where the node is to be saved. + /// The state. + internal override void Emit(IEmitter emitter, EmitterState state) + { + emitter.Emit(new Scalar(Anchor, Tag, Value, Style, Tag == null, false)); + } + + /// + /// Accepts the specified visitor by calling the appropriate Visit method on it. + /// + /// + /// A . + /// + public override void Accept(IYamlVisitor visitor) + { + visitor.Visit(this); + } + + /// + public override bool Equals(object obj) + { + var other = obj as YamlScalarNode; + return other != null && Equals(other) && SafeEquals(Value, other.Value); + } + + /// + /// Serves as a hash function for a particular type. + /// + /// + /// A hash code for the current . + /// + public override int GetHashCode() + { + return CombineHashCodes( + base.GetHashCode(), + GetHashCode(Value) + ); + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator string(YamlScalarNode value) + { + return value.Value; + } + + /// + /// Returns a that represents this instance. + /// + /// + /// A that represents this instance. + /// + internal override string ToString(RecursionLevel level) + { + return Value; + } + + /// + /// Recursively enumerates all the nodes from the document, starting on the current node, + /// and throwing + /// if is reached. + /// + internal override IEnumerable SafeAllNodes(RecursionLevel level) + { + yield return this; + } + + /// + /// Gets the type of node. + /// + public override YamlNodeType NodeType + { + get { return YamlNodeType.Scalar; } + } + + void IYamlConvertible.Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) + { + Load(parser, new DocumentLoadingState()); + } + + void IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) + { + Emit(emitter, new EmitterState()); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/RepresentationModel/YamlScalarNode.cs.meta b/YamlDotNet/RepresentationModel/YamlScalarNode.cs.meta new file mode 100644 index 0000000..97f9795 --- /dev/null +++ b/YamlDotNet/RepresentationModel/YamlScalarNode.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d8152305d4536da4c91eb19aa04b401c +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/RepresentationModel/YamlSequenceNode.cs b/YamlDotNet/RepresentationModel/YamlSequenceNode.cs new file mode 100644 index 0000000..35e9975 --- /dev/null +++ b/YamlDotNet/RepresentationModel/YamlSequenceNode.cs @@ -0,0 +1,300 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors +// Copyright (c) 2011 Andy Pickett + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using YamlDotNet.Core; +using YamlDotNet.Core.Events; +using System.Text; +using YamlDotNet.Serialization; + +namespace YamlDotNet.RepresentationModel +{ + /// + /// Represents a sequence node in the YAML document. + /// + [DebuggerDisplay("Count = {children.Count}")] + [Serializable] + public sealed class YamlSequenceNode : YamlNode, IEnumerable, IYamlConvertible + { + private readonly IList children = new List(); + + /// + /// Gets the collection of child nodes. + /// + /// The children. + public IList Children + { + get + { + return children; + } + } + + /// + /// Gets or sets the style of the node. + /// + /// The style. + public SequenceStyle Style { get; set; } + + + /// + /// Initializes a new instance of the class. + /// + internal YamlSequenceNode(IParser parser, DocumentLoadingState state) + { + Load(parser, state); + } + + private void Load(IParser parser, DocumentLoadingState state) + { + var sequence = parser.Expect(); + Load(sequence, state); + Style = sequence.Style; + + bool hasUnresolvedAliases = false; + while (!parser.Accept()) + { + var child = ParseNode(parser, state); + children.Add(child); + hasUnresolvedAliases |= child is YamlAliasNode; + } + + if (hasUnresolvedAliases) + { + state.AddNodeWithUnresolvedAliases(this); + } + + parser.Expect(); + } + + /// + /// Initializes a new instance of the class. + /// + public YamlSequenceNode() + { + } + + /// + /// Initializes a new instance of the class. + /// + public YamlSequenceNode(params YamlNode[] children) + : this((IEnumerable)children) + { + } + + /// + /// Initializes a new instance of the class. + /// + public YamlSequenceNode(IEnumerable children) + { + foreach (var child in children) + { + this.children.Add(child); + } + } + + /// + /// Adds the specified child to the collection. + /// + /// The child. + public void Add(YamlNode child) + { + children.Add(child); + } + + /// + /// Adds a scalar node to the collection. + /// + /// The child. + public void Add(string child) + { + children.Add(new YamlScalarNode(child)); + } + + /// + /// Resolves the aliases that could not be resolved when the node was created. + /// + /// The state of the document. + internal override void ResolveAliases(DocumentLoadingState state) + { + for (int i = 0; i < children.Count; ++i) + { + if (children[i] is YamlAliasNode) + { + children[i] = state.GetNode(children[i].Anchor, true, children[i].Start, children[i].End); + } + } + } + + /// + /// Saves the current node to the specified emitter. + /// + /// The emitter where the node is to be saved. + /// The state. + internal override void Emit(IEmitter emitter, EmitterState state) + { + emitter.Emit(new SequenceStart(Anchor, Tag, true, Style)); + foreach (var node in children) + { + node.Save(emitter, state); + } + emitter.Emit(new SequenceEnd()); + } + + /// + /// Accepts the specified visitor by calling the appropriate Visit method on it. + /// + /// + /// A . + /// + public override void Accept(IYamlVisitor visitor) + { + visitor.Visit(this); + } + + /// + public override bool Equals(object obj) + { + var other = obj as YamlSequenceNode; + if (other == null || !Equals(other) || children.Count != other.children.Count) + { + return false; + } + + for (int i = 0; i < children.Count; ++i) + { + if (!SafeEquals(children[i], other.children[i])) + { + return false; + } + } + + return true; + } + + /// + /// Serves as a hash function for a particular type. + /// + /// + /// A hash code for the current . + /// + public override int GetHashCode() + { + var hashCode = base.GetHashCode(); + + foreach (var item in children) + { + hashCode = CombineHashCodes(hashCode, GetHashCode(item)); + } + return hashCode; + } + + /// + /// Recursively enumerates all the nodes from the document, starting on the current node, + /// and throwing + /// if is reached. + /// + internal override IEnumerable SafeAllNodes(RecursionLevel level) + { + level.Increment(); + yield return this; + foreach (var child in children) + { + foreach (var node in child.SafeAllNodes(level)) + { + yield return node; + } + } + level.Decrement(); + } + + /// + /// Gets the type of node. + /// + public override YamlNodeType NodeType + { + get { return YamlNodeType.Sequence; } + } + + /// + /// Returns a that represents this instance. + /// + /// + /// A that represents this instance. + /// + internal override string ToString(RecursionLevel level) + { + if (!level.TryIncrement()) + { + return MaximumRecursionLevelReachedToStringValue; + } + + var text = new StringBuilder("[ "); + + foreach (var child in children) + { + if (text.Length > 2) + { + text.Append(", "); + } + text.Append(child.ToString(level)); + } + + text.Append(" ]"); + + level.Decrement(); + + return text.ToString(); + } + + #region IEnumerable Members + + /// + public IEnumerator GetEnumerator() + { + return Children.GetEnumerator(); + } + + #endregion + + #region IEnumerable Members + + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + #endregion + + void IYamlConvertible.Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) + { + Load(parser, new DocumentLoadingState()); + } + + void IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) + { + Emit(emitter, new EmitterState()); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/RepresentationModel/YamlSequenceNode.cs.meta b/YamlDotNet/RepresentationModel/YamlSequenceNode.cs.meta new file mode 100644 index 0000000..26255b6 --- /dev/null +++ b/YamlDotNet/RepresentationModel/YamlSequenceNode.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 58e9eea9b495b2f478b639f1d20a8951 +timeCreated: 1427145264 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/RepresentationModel/YamlStream.cs b/YamlDotNet/RepresentationModel/YamlStream.cs new file mode 100644 index 0000000..a8f7868 --- /dev/null +++ b/YamlDotNet/RepresentationModel/YamlStream.cs @@ -0,0 +1,166 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.IO; +using YamlDotNet.Core; +using YamlDotNet.Core.Events; + +namespace YamlDotNet.RepresentationModel +{ + /// + /// Represents an YAML stream. + /// + [Serializable] + public class YamlStream : IEnumerable + { + private readonly IList documents = new List(); + + /// + /// Gets the documents inside the stream. + /// + /// The documents. + public IList Documents + { + get + { + return documents; + } + } + + /// + /// Initializes a new instance of the class. + /// + public YamlStream() + { + } + + /// + /// Initializes a new instance of the class. + /// + public YamlStream(params YamlDocument[] documents) + : this((IEnumerable)documents) + { + } + + /// + /// Initializes a new instance of the class. + /// + public YamlStream(IEnumerable documents) + { + foreach (var document in documents) + { + this.documents.Add(document); + } + } + + /// + /// Adds the specified document to the collection. + /// + /// The document. + public void Add(YamlDocument document) + { + documents.Add(document); + } + + /// + /// Loads the stream from the specified input. + /// + /// The input. + public void Load(TextReader input) + { + Load(new Parser(input)); + } + + /// + /// Loads the stream from the specified . + /// + public void Load(IParser parser) + { + documents.Clear(); + parser.Expect(); + while (!parser.Accept()) + { + var document = new YamlDocument(parser); + documents.Add(document); + } + parser.Expect(); + } + + /// + /// Saves the stream to the specified output. + /// + /// The output. + public void Save(TextWriter output) + { + Save(output, true); + } + + /// + /// Saves the stream to the specified output. + /// + /// The output. + /// Indicates whether or not to assign node anchors. + public void Save(TextWriter output, bool assignAnchors) + { + IEmitter emitter = new Emitter(output); + emitter.Emit(new StreamStart()); + + foreach (var document in documents) + { + document.Save(emitter, assignAnchors); + } + + emitter.Emit(new StreamEnd()); + } + + /// + /// Accepts the specified visitor by calling the appropriate Visit method on it. + /// + /// + /// A . + /// + public void Accept(IYamlVisitor visitor) + { + visitor.Visit(this); + } + + #region IEnumerable Members + + /// + public IEnumerator GetEnumerator() + { + return documents.GetEnumerator(); + } + + #endregion + + #region IEnumerable Members + + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + #endregion + } +} \ No newline at end of file diff --git a/YamlDotNet/RepresentationModel/YamlStream.cs.meta b/YamlDotNet/RepresentationModel/YamlStream.cs.meta new file mode 100644 index 0000000..527ef40 --- /dev/null +++ b/YamlDotNet/RepresentationModel/YamlStream.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 8da956833fe9bb440be293c2b18b1e29 +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/RepresentationModel/YamlVisitor.cs b/YamlDotNet/RepresentationModel/YamlVisitor.cs new file mode 100644 index 0000000..b6e91cd --- /dev/null +++ b/YamlDotNet/RepresentationModel/YamlVisitor.cs @@ -0,0 +1,233 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace YamlDotNet.RepresentationModel +{ + /// + /// Abstract implementation of that knows how to walk a complete Yaml object model. + /// + [Obsolete("Use YamlVisitorBase")] + public abstract class YamlVisitor : IYamlVisitor + { + /// + /// Called when this object is visiting a . + /// + /// + /// The that is being visited. + /// + protected virtual void Visit(YamlStream stream) + { + // Do nothing. + } + + /// + /// Called after this object finishes visiting a . + /// + /// + /// The that has been visited. + /// + protected virtual void Visited(YamlStream stream) + { + // Do nothing. + } + + /// + /// Called when this object is visiting a . + /// + /// + /// The that is being visited. + /// + protected virtual void Visit(YamlDocument document) + { + // Do nothing. + } + + /// + /// Called after this object finishes visiting a . + /// + /// + /// The that has been visited. + /// + protected virtual void Visited(YamlDocument document) + { + // Do nothing. + } + + /// + /// Called when this object is visiting a . + /// + /// + /// The that is being visited. + /// + protected virtual void Visit(YamlScalarNode scalar) + { + // Do nothing. + } + + /// + /// Called after this object finishes visiting a . + /// + /// + /// The that has been visited. + /// + protected virtual void Visited(YamlScalarNode scalar) + { + // Do nothing. + } + + /// + /// Called when this object is visiting a . + /// + /// + /// The that is being visited. + /// + protected virtual void Visit(YamlSequenceNode sequence) + { + // Do nothing. + } + + /// + /// Called after this object finishes visiting a . + /// + /// + /// The that has been visited. + /// + protected virtual void Visited(YamlSequenceNode sequence) + { + // Do nothing. + } + + /// + /// Called when this object is visiting a . + /// + /// + /// The that is being visited. + /// + protected virtual void Visit(YamlMappingNode mapping) + { + // Do nothing. + } + + /// + /// Called after this object finishes visiting a . + /// + /// + /// The that has been visited. + /// + protected virtual void Visited(YamlMappingNode mapping) + { + // Do nothing. + } + + /// + /// Visits every child of a . + /// + /// + /// The that is being visited. + /// + protected virtual void VisitChildren(YamlStream stream) + { + foreach (var document in stream.Documents) + { + document.Accept(this); + } + } + + /// + /// Visits every child of a . + /// + /// + /// The that is being visited. + /// + protected virtual void VisitChildren(YamlDocument document) + { + if (document.RootNode != null) + { + document.RootNode.Accept(this); + } + } + + /// + /// Visits every child of a . + /// + /// + /// The that is being visited. + /// + protected virtual void VisitChildren(YamlSequenceNode sequence) + { + foreach (var node in sequence.Children) + { + node.Accept(this); + } + } + + /// + /// Visits every child of a . + /// + /// + /// The that is being visited. + /// + protected virtual void VisitChildren(YamlMappingNode mapping) + { + foreach (var pair in mapping.Children) + { + pair.Key.Accept(this); + pair.Value.Accept(this); + } + } + + void IYamlVisitor.Visit(YamlStream stream) + { + Visit(stream); + VisitChildren(stream); + Visited(stream); + } + + void IYamlVisitor.Visit(YamlDocument document) + { + Visit(document); + VisitChildren(document); + Visited(document); + } + + void IYamlVisitor.Visit(YamlScalarNode scalar) + { + Visit(scalar); + Visited(scalar); + } + + void IYamlVisitor.Visit(YamlSequenceNode sequence) + { + Visit(sequence); + VisitChildren(sequence); + Visited(sequence); + } + + void IYamlVisitor.Visit(YamlMappingNode mapping) + { + Visit(mapping); + VisitChildren(mapping); + Visited(mapping); + } + } +} diff --git a/YamlDotNet/RepresentationModel/YamlVisitor.cs.meta b/YamlDotNet/RepresentationModel/YamlVisitor.cs.meta new file mode 100644 index 0000000..f66fde0 --- /dev/null +++ b/YamlDotNet/RepresentationModel/YamlVisitor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f0c6d456c0cd3544f98e1dac39bf17ed +timeCreated: 1427145267 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/RepresentationModel/YamlVisitorBase.cs b/YamlDotNet/RepresentationModel/YamlVisitorBase.cs new file mode 100644 index 0000000..370d704 --- /dev/null +++ b/YamlDotNet/RepresentationModel/YamlVisitorBase.cs @@ -0,0 +1,151 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +namespace YamlDotNet.RepresentationModel +{ + /// + /// Abstract implementation of that knows how to walk a complete YAML object model. + /// + public abstract class YamlVisitorBase : IYamlVisitor + { + /// + /// Called when this object is visiting a . + /// + /// + /// The that is being visited. + /// + public virtual void Visit(YamlStream stream) + { + VisitChildren(stream); + } + + /// + /// Called when this object is visiting a . + /// + /// + /// The that is being visited. + /// + public virtual void Visit(YamlDocument document) + { + VisitChildren(document); + } + + /// + /// Called when this object is visiting a . + /// + /// + /// The that is being visited. + /// + public virtual void Visit(YamlScalarNode scalar) + { + // Do nothing. + } + + /// + /// Called when this object is visiting a . + /// + /// + /// The that is being visited. + /// + public virtual void Visit(YamlSequenceNode sequence) + { + VisitChildren(sequence); + } + + /// + /// Called when this object is visiting a . + /// + /// + /// The that is being visited. + /// + public virtual void Visit(YamlMappingNode mapping) + { + VisitChildren(mapping); + } + + /// + /// Called when this object is visiting a key-value pair. + /// + /// The left (key) that is being visited. + /// The right (value) that is being visited. + protected virtual void VisitPair(YamlNode key, YamlNode value) + { + key.Accept(this); + value.Accept(this); + } + + /// + /// Visits every child of a . + /// + /// + /// The that is being visited. + /// + protected virtual void VisitChildren(YamlStream stream) + { + foreach (var document in stream.Documents) + { + document.Accept(this); + } + } + + /// + /// Visits every child of a . + /// + /// + /// The that is being visited. + /// + protected virtual void VisitChildren(YamlDocument document) + { + if (document.RootNode != null) + { + document.RootNode.Accept(this); + } + } + + /// + /// Visits every child of a . + /// + /// + /// The that is being visited. + /// + protected virtual void VisitChildren(YamlSequenceNode sequence) + { + foreach (var node in sequence.Children) + { + node.Accept(this); + } + } + + /// + /// Visits every child of a . + /// + /// + /// The that is being visited. + /// + protected virtual void VisitChildren(YamlMappingNode mapping) + { + foreach (var pair in mapping.Children) + { + VisitPair(pair.Key, pair.Value); + } + } + } +} diff --git a/YamlDotNet/RepresentationModel/YamlVisitorBase.cs.meta b/YamlDotNet/RepresentationModel/YamlVisitorBase.cs.meta new file mode 100644 index 0000000..f1641d4 --- /dev/null +++ b/YamlDotNet/RepresentationModel/YamlVisitorBase.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: a982636aeeff0ee41b6666f4ae01957e +timeCreated: 1454767645 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization.meta b/YamlDotNet/Serialization.meta new file mode 100644 index 0000000..2d19244 --- /dev/null +++ b/YamlDotNet/Serialization.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 921c26b7d8a14f44784b5de7fa74bba0 +folderAsset: yes +timeCreated: 1427145262 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/BuilderSkeleton.cs b/YamlDotNet/Serialization/BuilderSkeleton.cs new file mode 100644 index 0000000..21b9700 --- /dev/null +++ b/YamlDotNet/Serialization/BuilderSkeleton.cs @@ -0,0 +1,299 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Linq.Expressions; +using YamlDotNet.Serialization.Converters; +using YamlDotNet.Serialization.TypeInspectors; + +namespace YamlDotNet.Serialization +{ + /// + /// Common implementation of and . + /// + public abstract class BuilderSkeleton + where TBuilder : BuilderSkeleton + { + internal INamingConvention namingConvention; + internal ITypeResolver typeResolver; + internal readonly YamlAttributeOverrides overrides; + internal readonly LazyComponentRegistrationList typeConverterFactories; + internal readonly LazyComponentRegistrationList typeInspectorFactories; + + internal BuilderSkeleton() + { + overrides = new YamlAttributeOverrides(); + + typeConverterFactories = new LazyComponentRegistrationList(); + typeConverterFactories.Add(typeof(GuidConverter), _ => new GuidConverter(false)); + + typeInspectorFactories = new LazyComponentRegistrationList(); + } + + protected abstract TBuilder Self { get; } + + internal ITypeInspector BuildTypeInspector() + { + return typeInspectorFactories.BuildComponentChain( + new ReadablePropertiesTypeInspector(typeResolver) + ); + } + + /// + /// Sets the that will be used by the (de)serializer. + /// + public TBuilder WithNamingConvention(INamingConvention namingConvention) + { + if (namingConvention == null) + { + throw new ArgumentNullException("namingConvention"); + } + + this.namingConvention = namingConvention; + return Self; + } + + /// + /// Sets the that will be used by the (de)serializer. + /// + public TBuilder WithTypeResolver(ITypeResolver typeResolver) + { + if (typeResolver == null) + { + throw new ArgumentNullException("typeResolver"); + } + + this.typeResolver = typeResolver; + return Self; + } + + /// + /// Register an for for a given property. + /// + /// + /// An expression in the form: x => x.SomeProperty + /// The attribute to register. + /// + public TBuilder WithAttributeOverride(Expression> propertyAccessor, Attribute attribute) + { + overrides.Add(propertyAccessor, attribute); + return Self; + } + + /// + /// Register an for for a given property. + /// + public TBuilder WithAttributeOverride(Type type, string member, Attribute attribute) + { + overrides.Add(type, member, attribute); + return Self; + } + + /// + /// Registers an additional to be used by the (de)serializer. + /// + public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter) + { + return WithTypeConverter(typeConverter, w => w.OnTop()); + } + + /// + /// Registers an additional to be used by the (de)serializer. + /// + /// + /// Configures the location where to insert the + public TBuilder WithTypeConverter( + IYamlTypeConverter typeConverter, + Action> where + ) + { + if (typeConverter == null) + { + throw new ArgumentNullException("typeConverter"); + } + + if (where == null) + { + throw new ArgumentNullException("where"); + } + + where(typeConverterFactories.CreateRegistrationLocationSelector(typeConverter.GetType(), _ => typeConverter)); + return Self; + } + + /// + /// Registers an additional to be used by the (de)serializer. + /// + /// A factory that creates the based on a previously registered . + /// Configures the location where to insert the + public TBuilder WithTypeConverter( + WrapperFactory typeConverterFactory, + Action> where + ) + where TYamlTypeConverter : IYamlTypeConverter + { + if (typeConverterFactory == null) + { + throw new ArgumentNullException("typeConverterFactory"); + } + + if (where == null) + { + throw new ArgumentNullException("where"); + } + + where(typeConverterFactories.CreateTrackingRegistrationLocationSelector(typeof(TYamlTypeConverter), (wrapped, _) => typeConverterFactory(wrapped))); + return Self; + } + + /// + /// Unregisters an existing of type . + /// + public TBuilder WithoutTypeConverter() + where TYamlTypeConverter : IYamlTypeConverter + { + return WithoutTypeConverter(typeof(TYamlTypeConverter)); + } + + /// + /// Unregisters an existing of type . + /// + public TBuilder WithoutTypeConverter(Type converterType) + { + if (converterType == null) + { + throw new ArgumentNullException("converterType"); + } + + typeConverterFactories.Remove(converterType); + return Self; + } + + /// + /// Registers an additional to be used by the (de)serializer. + /// + /// A function that instantiates the type inspector. + public TBuilder WithTypeInspector(Func typeInspectorFactory) + where TTypeInspector : ITypeInspector + { + return WithTypeInspector(typeInspectorFactory, w => w.OnTop()); + } + + /// + /// Registers an additional to be used by the (de)serializer. + /// + /// A function that instantiates the type inspector. + /// Configures the location where to insert the + public TBuilder WithTypeInspector( + Func typeInspectorFactory, + Action> where + ) + where TTypeInspector : ITypeInspector + { + if (typeInspectorFactory == null) + { + throw new ArgumentNullException("typeInspectorFactory"); + } + + if (where == null) + { + throw new ArgumentNullException("where"); + } + + where(typeInspectorFactories.CreateRegistrationLocationSelector(typeof(TTypeInspector), inner => typeInspectorFactory(inner))); + return Self; + } + + /// + /// Registers an additional to be used by the (de)serializer. + /// + /// A function that instantiates the type inspector based on a previously registered .. + /// Configures the location where to insert the + public TBuilder WithTypeInspector( + WrapperFactory typeInspectorFactory, + Action> where + ) + where TTypeInspector : ITypeInspector + { + if (typeInspectorFactory == null) + { + throw new ArgumentNullException("typeInspectorFactory"); + } + + if (where == null) + { + throw new ArgumentNullException("where"); + } + + where(typeInspectorFactories.CreateTrackingRegistrationLocationSelector(typeof(TTypeInspector), (wrapped, inner) => typeInspectorFactory(wrapped, inner))); + return Self; + } + + /// + /// Unregisters an existing of type . + /// + public TBuilder WithoutTypeInspector() + where TTypeInspector : ITypeInspector + { + return WithoutTypeInspector(typeof(ITypeInspector)); + } + + /// + /// Unregisters an existing of type . + /// + public TBuilder WithoutTypeInspector(Type inspectorType) + { + if (inspectorType == null) + { + throw new ArgumentNullException("inspectorType"); + } + + typeInspectorFactories.Remove(inspectorType); + return Self; + } + + protected IEnumerable BuildTypeConverters() + { + return typeConverterFactories.BuildComponentList(); + } + } + + /// + /// A factory that creates instances of based on an existing . + /// + /// The type of the wrapped component. + /// The type of the component that this factory creates. + /// The component that is to be wrapped. + /// Returns a new instance of that is based on . + public delegate TComponent WrapperFactory(TComponentBase wrapped) where TComponent : TComponentBase; + + /// + /// A factory that creates instances of based on an existing and an argument. + /// + /// The type of the argument. + /// The type of the wrapped component. + /// The type of the component that this factory creates. + /// The component that is to be wrapped. + /// The argument of the factory. + /// Returns a new instance of that is based on and . + public delegate TComponent WrapperFactory(TComponentBase wrapped, TArgument argument) where TComponent : TComponentBase; +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/BuilderSkeleton.cs.meta b/YamlDotNet/Serialization/BuilderSkeleton.cs.meta new file mode 100644 index 0000000..b78984b --- /dev/null +++ b/YamlDotNet/Serialization/BuilderSkeleton.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: c7b13de2cbd93db41846cb9bcb2e3968 +timeCreated: 1485601085 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/Converters.meta b/YamlDotNet/Serialization/Converters.meta new file mode 100644 index 0000000..0e08b11 --- /dev/null +++ b/YamlDotNet/Serialization/Converters.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 272f43609d820fd4aa820cc0636fe694 +folderAsset: yes +timeCreated: 1427145262 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/Converters/DateTimeConverter.cs b/YamlDotNet/Serialization/Converters/DateTimeConverter.cs new file mode 100644 index 0000000..3a970a3 --- /dev/null +++ b/YamlDotNet/Serialization/Converters/DateTimeConverter.cs @@ -0,0 +1,118 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Globalization; +using System.Linq; + +using YamlDotNet.Core; +using YamlDotNet.Core.Events; + +namespace YamlDotNet.Serialization.Converters +{ + /// + /// This represents the YAML converter entity for . + /// + public class DateTimeConverter : IYamlTypeConverter + { + private readonly DateTimeKind kind; + private readonly IFormatProvider provider; + private readonly string[] formats; + + /// + /// Initializes a new instance of the class. + /// + /// value. Default value is . is considered as . + /// instance. Default value is . + /// List of date/time formats for parsing. Default value is "G". + /// On deserializing, all formats in the list are used for conversion, while on serializing, the first format in the list is used. + public DateTimeConverter(DateTimeKind kind = DateTimeKind.Utc, IFormatProvider provider = null, params string[] formats) + { + this.kind = kind == DateTimeKind.Unspecified ? DateTimeKind.Utc : kind; + this.provider = provider ?? CultureInfo.InvariantCulture; + this.formats = formats.DefaultIfEmpty("G").ToArray(); + } + + /// + /// Gets a value indicating whether the current converter supports converting the specified type. + /// + /// to check. + /// Returns True, if the current converter supports; otherwise returns False. + public bool Accepts(Type type) + { + return type == typeof(DateTime); + } + + /// + /// Reads an object's state from a YAML parser. + /// + /// instance. + /// to convert. + /// Returns the instance converted. + /// On deserializing, all formats in the list are used for conversion. + public object ReadYaml(IParser parser, Type type) + { + var value = ((Scalar)parser.Current).Value; + var style = this.kind == DateTimeKind.Local ? DateTimeStyles.AssumeLocal : DateTimeStyles.AssumeUniversal; + + var dt = DateTime.ParseExact(value, this.formats, this.provider, style); + dt = EnsureDateTimeKind(dt, this.kind); + + parser.MoveNext(); + + return dt; + } + + /// + /// Writes the specified object's state to a YAML emitter. + /// + /// instance. + /// Value to write. + /// to convert. + /// On serializing, the first format in the list is used. + public void WriteYaml(IEmitter emitter, object value, Type type) + { + var dt = (DateTime) value; + var adjusted = this.kind == DateTimeKind.Local ? dt.ToLocalTime() : dt.ToUniversalTime(); + var formatted = adjusted.ToString(this.formats.First(), this.provider); // Always take the first format of the list. + + emitter.Emit((ParsingEvent)new Scalar((string)null, (string)null, formatted, ScalarStyle.Any, true, false)); + } + + private static DateTime EnsureDateTimeKind(DateTime dt, DateTimeKind kind) + { + DateTime ensured; + if (dt.Kind == DateTimeKind.Local && kind == DateTimeKind.Utc) + { + ensured = dt.ToUniversalTime(); + return ensured; + } + + if (dt.Kind == DateTimeKind.Utc && kind == DateTimeKind.Local) + { + ensured = dt.ToLocalTime(); + return ensured; + } + + return dt; + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/Converters/DateTimeConverter.cs.meta b/YamlDotNet/Serialization/Converters/DateTimeConverter.cs.meta new file mode 100644 index 0000000..eec1bb3 --- /dev/null +++ b/YamlDotNet/Serialization/Converters/DateTimeConverter.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 605a13412ac29ee4498bff2668e80505 +timeCreated: 1485601083 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/Converters/GuidConverter.cs b/YamlDotNet/Serialization/Converters/GuidConverter.cs new file mode 100644 index 0000000..b173d1c --- /dev/null +++ b/YamlDotNet/Serialization/Converters/GuidConverter.cs @@ -0,0 +1,56 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization.Converters +{ + /// + /// Converter for System.Guid. + /// + public class GuidConverter : IYamlTypeConverter + { + private readonly bool jsonCompatible; + + public GuidConverter(bool jsonCompatible) + { + this.jsonCompatible = jsonCompatible; + } + + public bool Accepts(System.Type type) + { + return type == typeof(System.Guid); + } + + public object ReadYaml(Core.IParser parser, System.Type type) + { + var value = ((Core.Events.Scalar)parser.Current).Value; + parser.MoveNext(); + return new System.Guid(value); + } + + public void WriteYaml(Core.IEmitter emitter, object value, System.Type type) + { + var guid = (System.Guid)value; + emitter.Emit(new Core.Events.Scalar(null, null, guid.ToString("D"), jsonCompatible ? ScalarStyle.DoubleQuoted : ScalarStyle.Any, true, false)); + } + } +} diff --git a/YamlDotNet/Serialization/Converters/GuidConverter.cs.meta b/YamlDotNet/Serialization/Converters/GuidConverter.cs.meta new file mode 100644 index 0000000..78d0b23 --- /dev/null +++ b/YamlDotNet/Serialization/Converters/GuidConverter.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2034b2a36cbe85a438addb075cff648b +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/Deserializer.cs b/YamlDotNet/Serialization/Deserializer.cs new file mode 100644 index 0000000..064db62 --- /dev/null +++ b/YamlDotNet/Serialization/Deserializer.cs @@ -0,0 +1,333 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.IO; +using YamlDotNet.Core; +using YamlDotNet.Core.Events; +using YamlDotNet.Serialization.Converters; +using YamlDotNet.Serialization.NamingConventions; +using YamlDotNet.Serialization.NodeDeserializers; +using YamlDotNet.Serialization.NodeTypeResolvers; +using YamlDotNet.Serialization.ObjectFactories; +using YamlDotNet.Serialization.TypeInspectors; +using YamlDotNet.Serialization.TypeResolvers; +using YamlDotNet.Serialization.Utilities; +using YamlDotNet.Serialization.ValueDeserializers; + +namespace YamlDotNet.Serialization +{ + /// + /// Deserializes objects from the YAML format. + /// To customize the behavior of , + /// use the class. + /// + public sealed class Deserializer + { + #region Backwards compatibility + private class BackwardsCompatibleConfiguration + { + private static readonly Dictionary predefinedTagMappings = new Dictionary + { + { "tag:yaml.org,2002:map", typeof(Dictionary) }, + { "tag:yaml.org,2002:bool", typeof(bool) }, + { "tag:yaml.org,2002:float", typeof(double) }, + { "tag:yaml.org,2002:int", typeof(int) }, + { "tag:yaml.org,2002:str", typeof(string) }, + { "tag:yaml.org,2002:timestamp", typeof(DateTime) } + }; + + private readonly Dictionary tagMappings; + private readonly List converters; + private TypeDescriptorProxy typeDescriptor = new TypeDescriptorProxy(); + public IValueDeserializer valueDeserializer; + + public IList NodeDeserializers { get; private set; } + public IList TypeResolvers { get; private set; } + + private class TypeDescriptorProxy : ITypeInspector + { + public ITypeInspector TypeDescriptor; + + public IEnumerable GetProperties(Type type, object container) + { + return TypeDescriptor.GetProperties(type, container); + } + + public IPropertyDescriptor GetProperty(Type type, object container, string name, bool ignoreUnmatched) + { + return TypeDescriptor.GetProperty(type, container, name, ignoreUnmatched); + } + } + + public BackwardsCompatibleConfiguration( + IObjectFactory objectFactory, + INamingConvention namingConvention, + bool ignoreUnmatched, + YamlAttributeOverrides overrides) + { + objectFactory = objectFactory ?? new DefaultObjectFactory(); + namingConvention = namingConvention ?? new NullNamingConvention(); + + typeDescriptor.TypeDescriptor = + new CachedTypeInspector( + new NamingConventionTypeInspector( + new YamlAttributesTypeInspector( + new YamlAttributeOverridesInspector( + new ReadableAndWritablePropertiesTypeInspector( + new ReadablePropertiesTypeInspector( + new StaticTypeResolver() + ) + ), + overrides + ) + ), + namingConvention + ) + ); + + converters = new List(); + converters.Add(new GuidConverter(false)); + + NodeDeserializers = new List(); + NodeDeserializers.Add(new YamlConvertibleNodeDeserializer(objectFactory)); + NodeDeserializers.Add(new YamlSerializableNodeDeserializer(objectFactory)); + NodeDeserializers.Add(new TypeConverterNodeDeserializer(converters)); + NodeDeserializers.Add(new NullNodeDeserializer()); + NodeDeserializers.Add(new ScalarNodeDeserializer()); + NodeDeserializers.Add(new ArrayNodeDeserializer()); + NodeDeserializers.Add(new DictionaryNodeDeserializer(objectFactory)); + NodeDeserializers.Add(new CollectionNodeDeserializer(objectFactory)); + NodeDeserializers.Add(new EnumerableNodeDeserializer()); + NodeDeserializers.Add(new ObjectNodeDeserializer(objectFactory, typeDescriptor, ignoreUnmatched)); + + tagMappings = new Dictionary(predefinedTagMappings); + TypeResolvers = new List(); + TypeResolvers.Add(new YamlConvertibleTypeResolver()); + TypeResolvers.Add(new YamlSerializableTypeResolver()); + TypeResolvers.Add(new TagNodeTypeResolver(tagMappings)); + TypeResolvers.Add(new TypeNameInTagNodeTypeResolver()); + TypeResolvers.Add(new DefaultContainersNodeTypeResolver()); + + valueDeserializer = + new AliasValueDeserializer( + new NodeValueDeserializer( + NodeDeserializers, + TypeResolvers + ) + ); + } + + public void RegisterTagMapping(string tag, Type type) + { + tagMappings.Add(tag, type); + } + + public void RegisterTypeConverter(IYamlTypeConverter typeConverter) + { + converters.Insert(0, typeConverter); + } + } + + private readonly BackwardsCompatibleConfiguration backwardsCompatibleConfiguration; + + private void ThrowUnlessInBackwardsCompatibleMode() + { + if (backwardsCompatibleConfiguration == null) + { + throw new InvalidOperationException("This method / property exists for backwards compatibility reasons, but the Deserializer was created using the new configuration mechanism. To configure the Deserializer, use the DeserializerBuilder."); + } + } + + [Obsolete("Please use DeserializerBuilder to customize the Deserializer. This property will be removed in future releases.")] + public IList NodeDeserializers + { + get + { + ThrowUnlessInBackwardsCompatibleMode(); + return backwardsCompatibleConfiguration.NodeDeserializers; + } + } + + [Obsolete("Please use DeserializerBuilder to customize the Deserializer. This property will be removed in future releases.")] + public IList TypeResolvers + { + get + { + ThrowUnlessInBackwardsCompatibleMode(); + return backwardsCompatibleConfiguration.TypeResolvers; + } + } + + [Obsolete("Please use DeserializerBuilder to customize the Deserializer. This constructor will be removed in future releases.")] + public Deserializer( + IObjectFactory objectFactory = null, + INamingConvention namingConvention = null, + bool ignoreUnmatched = false, + YamlAttributeOverrides overrides = null) + { + backwardsCompatibleConfiguration = new BackwardsCompatibleConfiguration(objectFactory, namingConvention, ignoreUnmatched, overrides); + valueDeserializer = backwardsCompatibleConfiguration.valueDeserializer; + } + + [Obsolete("Please use DeserializerBuilder to customize the Deserializer. This method will be removed in future releases.")] + public void RegisterTagMapping(string tag, Type type) + { + ThrowUnlessInBackwardsCompatibleMode(); + backwardsCompatibleConfiguration.RegisterTagMapping(tag, type); + } + + [Obsolete("Please use DeserializerBuilder to customize the Deserializer. This method will be removed in future releases.")] + public void RegisterTypeConverter(IYamlTypeConverter typeConverter) + { + ThrowUnlessInBackwardsCompatibleMode(); + backwardsCompatibleConfiguration.RegisterTypeConverter(typeConverter); + } + #endregion + + private readonly IValueDeserializer valueDeserializer; + + /// + /// Initializes a new instance of using the default configuration. + /// + /// + /// To customize the bahavior of the deserializer, use . + /// + public Deserializer() + // TODO: When the backwards compatibility is dropped, uncomment the following line and remove the body of this constructor. + // : this(new DeserializerBuilder().BuildValueDeserializer()) + { + backwardsCompatibleConfiguration = new BackwardsCompatibleConfiguration(null, null, false, null); + valueDeserializer = backwardsCompatibleConfiguration.valueDeserializer; + } + + /// + /// This constructor is private to discourage its use. + /// To invoke it, call the method. + /// + private Deserializer(IValueDeserializer valueDeserializer) + { + if (valueDeserializer == null) + { + throw new ArgumentNullException("valueDeserializer"); + } + + this.valueDeserializer = valueDeserializer; + } + + /// + /// Creates a new that uses the specified . + /// This method is available for advanced scenarios. The preferred way to customize the bahavior of the + /// deserializer is to use . + /// + public static Deserializer FromValueDeserializer(IValueDeserializer valueDeserializer) + { + return new Deserializer(valueDeserializer); + } + + public T Deserialize(string input) + { + using (var reader = new StringReader(input)) + { + return (T)Deserialize(reader, typeof(T)); + } + } + + public T Deserialize(TextReader input) + { + return (T)Deserialize(input, typeof(T)); + } + + public object Deserialize(TextReader input) + { + return Deserialize(input, typeof(object)); + } + + public object Deserialize(string input, Type type) + { + using (var reader = new StringReader(input)) + { + return Deserialize(reader, type); + } + } + + public object Deserialize(TextReader input, Type type) + { + return Deserialize(new Parser(input), type); + } + + public T Deserialize(IParser parser) + { + return (T)Deserialize(parser, typeof(T)); + } + + public object Deserialize(IParser parser) + { + return Deserialize(parser, typeof(object)); + } + + /// + /// Deserializes an object of the specified type. + /// + /// The from where to deserialize the object. + /// The static type of the object to deserialize. + /// Returns the deserialized object. + public object Deserialize(IParser parser, Type type) + { + if (parser == null) + { + throw new ArgumentNullException("reader"); + } + + if (type == null) + { + throw new ArgumentNullException("type"); + } + + var hasStreamStart = parser.Allow() != null; + + var hasDocumentStart = parser.Allow() != null; + + object result = null; + if (!parser.Accept() && !parser.Accept()) + { + using (var state = new SerializerState()) + { + result = valueDeserializer.DeserializeValue(parser, type, state, valueDeserializer); + state.OnDeserialization(); + } + } + + if (hasDocumentStart) + { + parser.Expect(); + } + + if (hasStreamStart) + { + parser.Expect(); + } + + return result; + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/Deserializer.cs.meta b/YamlDotNet/Serialization/Deserializer.cs.meta new file mode 100644 index 0000000..173f3ee --- /dev/null +++ b/YamlDotNet/Serialization/Deserializer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: cee7b8e2c23b44c4c9d8b6fa9029e350 +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/DeserializerBuilder.cs b/YamlDotNet/Serialization/DeserializerBuilder.cs new file mode 100644 index 0000000..02f5cf1 --- /dev/null +++ b/YamlDotNet/Serialization/DeserializerBuilder.cs @@ -0,0 +1,357 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using YamlDotNet.Serialization.NodeDeserializers; +using YamlDotNet.Serialization.NodeTypeResolvers; +using YamlDotNet.Serialization.ObjectFactories; +using YamlDotNet.Serialization.TypeInspectors; +using YamlDotNet.Serialization.TypeResolvers; +using YamlDotNet.Serialization.ValueDeserializers; + +namespace YamlDotNet.Serialization +{ + /// + /// Creates and configures instances of . + /// This class is used to customize the behavior of . Use the relevant methods + /// to apply customizations, then call to create an instance of the deserializer + /// with the desired customizations. + /// + public sealed class DeserializerBuilder : BuilderSkeleton + { + private IObjectFactory objectFactory = new DefaultObjectFactory(); + private readonly LazyComponentRegistrationList nodeDeserializerFactories; + private readonly LazyComponentRegistrationList nodeTypeResolverFactories; + private readonly Dictionary tagMappings; + private bool ignoreUnmatched; + + /// + /// Initializes a new using the default component registrations. + /// + public DeserializerBuilder() + { + tagMappings = new Dictionary + { + { "tag:yaml.org,2002:map", typeof(Dictionary) }, + { "tag:yaml.org,2002:bool", typeof(bool) }, + { "tag:yaml.org,2002:float", typeof(double) }, + { "tag:yaml.org,2002:int", typeof(int) }, + { "tag:yaml.org,2002:str", typeof(string) }, + { "tag:yaml.org,2002:timestamp", typeof(DateTime) } + }; + + typeInspectorFactories.Add(typeof(CachedTypeInspector), inner => new CachedTypeInspector(inner)); + typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), inner => namingConvention != null ? new NamingConventionTypeInspector(inner, namingConvention) : inner); + typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), inner => new YamlAttributesTypeInspector(inner)); + typeInspectorFactories.Add(typeof(YamlAttributeOverridesInspector), inner => overrides != null ? new YamlAttributeOverridesInspector(inner, overrides.Clone()) : inner); + typeInspectorFactories.Add(typeof(ReadableAndWritablePropertiesTypeInspector), inner => new ReadableAndWritablePropertiesTypeInspector(inner)); + + nodeDeserializerFactories = new LazyComponentRegistrationList + { + { typeof(YamlConvertibleNodeDeserializer), _ => new YamlConvertibleNodeDeserializer(objectFactory) }, + { typeof(YamlSerializableNodeDeserializer), _ => new YamlSerializableNodeDeserializer(objectFactory) }, + { typeof(TypeConverterNodeDeserializer), _ => new TypeConverterNodeDeserializer(BuildTypeConverters()) }, + { typeof(NullNodeDeserializer), _ => new NullNodeDeserializer() }, + { typeof(ScalarNodeDeserializer), _ => new ScalarNodeDeserializer() }, + { typeof(ArrayNodeDeserializer), _ => new ArrayNodeDeserializer() }, + { typeof(DictionaryNodeDeserializer), _ => new DictionaryNodeDeserializer(objectFactory) }, + { typeof(CollectionNodeDeserializer), _ => new CollectionNodeDeserializer(objectFactory) }, + { typeof(EnumerableNodeDeserializer), _ => new EnumerableNodeDeserializer() }, + { typeof(ObjectNodeDeserializer), _ => new ObjectNodeDeserializer(objectFactory, BuildTypeInspector(), ignoreUnmatched) } + }; + + nodeTypeResolverFactories = new LazyComponentRegistrationList + { + { typeof(YamlConvertibleTypeResolver), _ => new YamlConvertibleTypeResolver() }, + { typeof(YamlSerializableTypeResolver), _ => new YamlSerializableTypeResolver() }, + { typeof(TagNodeTypeResolver), _ => new TagNodeTypeResolver(tagMappings) }, + { typeof(TypeNameInTagNodeTypeResolver), _ => new TypeNameInTagNodeTypeResolver() }, + { typeof(DefaultContainersNodeTypeResolver), _ => new DefaultContainersNodeTypeResolver() } + }; + + WithTypeResolver(new StaticTypeResolver()); + } + + protected override DeserializerBuilder Self { get { return this; } } + + /// + /// Sets the that will be used by the deserializer. + /// + public DeserializerBuilder WithObjectFactory(IObjectFactory objectFactory) + { + if (objectFactory == null) + { + throw new ArgumentNullException("objectFactory"); + } + + this.objectFactory = objectFactory; + return this; + } + + /// + /// Sets the that will be used by the deserializer. + /// + public DeserializerBuilder WithObjectFactory(Func objectFactory) + { + if (objectFactory == null) + { + throw new ArgumentNullException("objectFactory"); + } + + return WithObjectFactory(new LambdaObjectFactory(objectFactory)); + } + + /// + /// Registers an additional to be used by the deserializer. + /// + public DeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer) + { + return WithNodeDeserializer(nodeDeserializer, w => w.OnTop()); + } + + /// + /// Registers an additional to be used by the deserializer. + /// + /// + /// Configures the location where to insert the + public DeserializerBuilder WithNodeDeserializer( + INodeDeserializer nodeDeserializer, + Action> where + ) + { + if (nodeDeserializer == null) + { + throw new ArgumentNullException("nodeDeserializer"); + } + + if (where == null) + { + throw new ArgumentNullException("where"); + } + + where(nodeDeserializerFactories.CreateRegistrationLocationSelector(nodeDeserializer.GetType(), _ => nodeDeserializer)); + return this; + } + + /// + /// Registers an additional to be used by the deserializer. + /// + /// A factory that creates the based on a previously registered . + /// Configures the location where to insert the + public DeserializerBuilder WithNodeDeserializer( + WrapperFactory nodeDeserializerFactory, + Action> where + ) + where TNodeDeserializer : INodeDeserializer + { + if (nodeDeserializerFactory == null) + { + throw new ArgumentNullException("nodeDeserializerFactory"); + } + + if (where == null) + { + throw new ArgumentNullException("where"); + } + + where(nodeDeserializerFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeDeserializer), (wrapped, _) => nodeDeserializerFactory(wrapped))); + return this; + } + + /// + /// Unregisters an existing of type . + /// + public DeserializerBuilder WithoutNodeDeserializer() + where TNodeDeserializer : INodeDeserializer + { + return WithoutNodeDeserializer(typeof(TNodeDeserializer)); + } + + /// + /// Unregisters an existing of type . + /// + public DeserializerBuilder WithoutNodeDeserializer(Type nodeDeserializerType) + { + if (nodeDeserializerType == null) + { + throw new ArgumentNullException("nodeDeserializerType"); + } + + nodeDeserializerFactories.Remove(nodeDeserializerType); + return this; + } + + /// + /// Registers an additional to be used by the deserializer. + /// + public DeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver) + { + return WithNodeTypeResolver(nodeTypeResolver, w => w.OnTop()); + } + + /// + /// Registers an additional to be used by the deserializer. + /// + /// + /// Configures the location where to insert the + public DeserializerBuilder WithNodeTypeResolver( + INodeTypeResolver nodeTypeResolver, + Action> where + ) + { + if (nodeTypeResolver == null) + { + throw new ArgumentNullException("nodeTypeResolver"); + } + + if (where == null) + { + throw new ArgumentNullException("where"); + } + + where(nodeTypeResolverFactories.CreateRegistrationLocationSelector(nodeTypeResolver.GetType(), _ => nodeTypeResolver)); + return this; + } + + /// + /// Registers an additional to be used by the deserializer. + /// + /// A factory that creates the based on a previously registered . + /// Configures the location where to insert the + public DeserializerBuilder WithNodeTypeResolver( + WrapperFactory nodeTypeResolverFactory, + Action> where + ) + where TNodeTypeResolver : INodeTypeResolver + { + if (nodeTypeResolverFactory == null) + { + throw new ArgumentNullException("nodeTypeResolverFactory"); + } + + if (where == null) + { + throw new ArgumentNullException("where"); + } + + where(nodeTypeResolverFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeTypeResolver), (wrapped, _) => nodeTypeResolverFactory(wrapped))); + return this; + } + + /// + /// Unregisters an existing of type . + /// + public DeserializerBuilder WithoutNodeTypeResolver() + where TNodeTypeResolver : INodeTypeResolver + { + return WithoutNodeTypeResolver(typeof(TNodeTypeResolver)); + } + + /// + /// Unregisters an existing of type . + /// + public DeserializerBuilder WithoutNodeTypeResolver(Type nodeTypeResolverType) + { + if (nodeTypeResolverType == null) + { + throw new ArgumentNullException("nodeTypeResolverType"); + } + + nodeTypeResolverFactories.Remove(nodeTypeResolverType); + return this; + } + + /// + /// Registers a tag mapping. + /// + public DeserializerBuilder WithTagMapping(string tag, Type type) + { + if (tag == null) + { + throw new ArgumentNullException("tag"); + } + + if (type == null) + { + throw new ArgumentNullException("type"); + } + + Type alreadyRegisteredType; + if (tagMappings.TryGetValue(tag, out alreadyRegisteredType)) + { + throw new ArgumentException(string.Format("Type already has a registered type '{0}' for tag '{1}'", alreadyRegisteredType.FullName, tag), "tag"); + } + + tagMappings.Add(tag, type); + return this; + } + + /// + /// Unregisters an existing tag mapping. + /// + public DeserializerBuilder WithoutTagMapping(string tag) + { + if (tag == null) + { + throw new ArgumentNullException("tag"); + } + + if (!tagMappings.Remove(tag)) + { + throw new KeyNotFoundException(string.Format("Tag '{0}' is not registered", tag)); + } + return this; + } + + /// + /// Instructs the deserializer to ignore unmatched properties instead of throwing an exception. + /// + public DeserializerBuilder IgnoreUnmatchedProperties() + { + ignoreUnmatched = true; + return this; + } + + /// + /// Creates a new according to the current configuration. + /// + public Deserializer Build() + { + return Deserializer.FromValueDeserializer(BuildValueDeserializer()); + } + + /// + /// Creates a new that implements the current configuration. + /// This method is available for advanced scenarios. The preferred way to customize the bahavior of the + /// deserializer is to use the method. + /// + public IValueDeserializer BuildValueDeserializer() + { + return new AliasValueDeserializer( + new NodeValueDeserializer( + nodeDeserializerFactories.BuildComponentList(), + nodeTypeResolverFactories.BuildComponentList() + ) + ); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/DeserializerBuilder.cs.meta b/YamlDotNet/Serialization/DeserializerBuilder.cs.meta new file mode 100644 index 0000000..919eb6d --- /dev/null +++ b/YamlDotNet/Serialization/DeserializerBuilder.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f8eedbdb2d60b5c438d13b57396f5565 +timeCreated: 1485601086 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/EmissionPhaseObjectGraphVisitorArgs.cs b/YamlDotNet/Serialization/EmissionPhaseObjectGraphVisitorArgs.cs new file mode 100644 index 0000000..3421d6c --- /dev/null +++ b/YamlDotNet/Serialization/EmissionPhaseObjectGraphVisitorArgs.cs @@ -0,0 +1,111 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Linq; +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization +{ + public sealed class EmissionPhaseObjectGraphVisitorArgs + { + /// + /// Gets the next visitor that should be called by the current visitor. + /// + public IObjectGraphVisitor InnerVisitor { get; private set; } + + /// + /// Gets the that is to be used for serialization. + /// + public IEventEmitter EventEmitter { get; private set; } + + /// + /// Gets a function that, when called, serializes the specified object. + /// + public ObjectSerializer NestedObjectSerializer { get; private set; } + + public IEnumerable TypeConverters { get; private set; } + + private readonly IEnumerable> preProcessingPhaseVisitors; + + public EmissionPhaseObjectGraphVisitorArgs( + IObjectGraphVisitor innerVisitor, + IEventEmitter eventEmitter, + IEnumerable> preProcessingPhaseVisitors, + IEnumerable typeConverters, + ObjectSerializer nestedObjectSerializer + ) + { + if (innerVisitor == null) + { + throw new ArgumentNullException("innerVisitor"); + } + + InnerVisitor = innerVisitor; + + if (eventEmitter == null) + { + throw new ArgumentNullException("eventEmitter"); + } + + EventEmitter = eventEmitter; + + if (preProcessingPhaseVisitors == null) + { + throw new ArgumentNullException("preProcessingPhaseVisitors"); + } + + this.preProcessingPhaseVisitors = preProcessingPhaseVisitors; + + if (typeConverters == null) + { + throw new ArgumentNullException("typeConverters"); + } + + TypeConverters = typeConverters; + + if (nestedObjectSerializer == null) + { + throw new ArgumentNullException("nestedObjectSerializer"); + } + + NestedObjectSerializer = nestedObjectSerializer; + } + + /// + /// Gets the visitor of type that was used during the pre-processig phase. + /// + /// The type of the visitor.s + /// + /// + /// No visitor of that type has been registered, + /// or ore than one visitors registered are of type . + /// + public T GetPreProcessingPhaseObjectGraphVisitor() + where T : IObjectGraphVisitor + { + return preProcessingPhaseVisitors + .OfType() + .Single(); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/EmissionPhaseObjectGraphVisitorArgs.cs.meta b/YamlDotNet/Serialization/EmissionPhaseObjectGraphVisitorArgs.cs.meta new file mode 100644 index 0000000..6d8f224 --- /dev/null +++ b/YamlDotNet/Serialization/EmissionPhaseObjectGraphVisitorArgs.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: bb4122e230b42de4cb90854ba842578c +timeCreated: 1485601085 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/EventEmitters.meta b/YamlDotNet/Serialization/EventEmitters.meta new file mode 100644 index 0000000..3545ecb --- /dev/null +++ b/YamlDotNet/Serialization/EventEmitters.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: e9ef080653208014a9cc235469180344 +folderAsset: yes +timeCreated: 1427145262 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/EventEmitters/ChainedEventEmitter.cs b/YamlDotNet/Serialization/EventEmitters/ChainedEventEmitter.cs new file mode 100644 index 0000000..963ed98 --- /dev/null +++ b/YamlDotNet/Serialization/EventEmitters/ChainedEventEmitter.cs @@ -0,0 +1,75 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization.EventEmitters +{ + /// + /// Provided the base implementation for an IEventEmitter that is a + /// decorator for another IEventEmitter. + /// + public abstract class ChainedEventEmitter : IEventEmitter + { + protected readonly IEventEmitter nextEmitter; + + protected ChainedEventEmitter(IEventEmitter nextEmitter) + { + if (nextEmitter == null) + { + throw new ArgumentNullException("nextEmitter"); + } + + this.nextEmitter = nextEmitter; + } + + public virtual void Emit(AliasEventInfo eventInfo, IEmitter emitter) + { + nextEmitter.Emit(eventInfo, emitter); + } + + public virtual void Emit(ScalarEventInfo eventInfo, IEmitter emitter) + { + nextEmitter.Emit(eventInfo, emitter); + } + + public virtual void Emit(MappingStartEventInfo eventInfo, IEmitter emitter) + { + nextEmitter.Emit(eventInfo, emitter); + } + + public virtual void Emit(MappingEndEventInfo eventInfo, IEmitter emitter) + { + nextEmitter.Emit(eventInfo, emitter); + } + + public virtual void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter) + { + nextEmitter.Emit(eventInfo, emitter); + } + + public virtual void Emit(SequenceEndEventInfo eventInfo, IEmitter emitter) + { + nextEmitter.Emit(eventInfo, emitter); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/EventEmitters/ChainedEventEmitter.cs.meta b/YamlDotNet/Serialization/EventEmitters/ChainedEventEmitter.cs.meta new file mode 100644 index 0000000..192024d --- /dev/null +++ b/YamlDotNet/Serialization/EventEmitters/ChainedEventEmitter.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: ccb97ea0d5b5aff4d93a807363ef3ec7 +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/EventEmitters/CustomTagEventEmitter.cs b/YamlDotNet/Serialization/EventEmitters/CustomTagEventEmitter.cs new file mode 100644 index 0000000..f41b186 --- /dev/null +++ b/YamlDotNet/Serialization/EventEmitters/CustomTagEventEmitter.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization.EventEmitters +{ + internal class CustomTagEventEmitter: ChainedEventEmitter + { + private IDictionary tagMappings; + + public CustomTagEventEmitter(IEventEmitter inner, IDictionary tagMappings) + :base(inner) + { + this.tagMappings = tagMappings; + } + + public override void Emit(MappingStartEventInfo eventInfo, IEmitter emitter) + { + if(tagMappings.ContainsKey(eventInfo.Source.Type)) + { + eventInfo.Tag = tagMappings[eventInfo.Source.Type]; + } + base.Emit(eventInfo, emitter); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/EventEmitters/CustomTagEventEmitter.cs.meta b/YamlDotNet/Serialization/EventEmitters/CustomTagEventEmitter.cs.meta new file mode 100644 index 0000000..0a3af46 --- /dev/null +++ b/YamlDotNet/Serialization/EventEmitters/CustomTagEventEmitter.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 0cc50ca841931e244afaf9442602a1c7 +timeCreated: 1485601082 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/EventEmitters/JsonEventEmitter.cs b/YamlDotNet/Serialization/EventEmitters/JsonEventEmitter.cs new file mode 100644 index 0000000..e176a82 --- /dev/null +++ b/YamlDotNet/Serialization/EventEmitters/JsonEventEmitter.cs @@ -0,0 +1,111 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Globalization; +using YamlDotNet.Core; +using YamlDotNet.Core.Events; + +namespace YamlDotNet.Serialization.EventEmitters +{ + public sealed class JsonEventEmitter : ChainedEventEmitter + { + public JsonEventEmitter(IEventEmitter nextEmitter) + : base(nextEmitter) + { + } + + public override void Emit(AliasEventInfo eventInfo, IEmitter emitter) + { + throw new NotSupportedException("Aliases are not supported in JSON"); + } + + public override void Emit(ScalarEventInfo eventInfo, IEmitter emitter) + { + eventInfo.IsPlainImplicit = true; + eventInfo.Style = ScalarStyle.Plain; + + var typeCode = eventInfo.Source.Value != null + ? eventInfo.Source.Type.GetTypeCode() + : TypeCode.Empty; + + switch (typeCode) + { + case TypeCode.Boolean: + eventInfo.RenderedValue = YamlFormatter.FormatBoolean(eventInfo.Source.Value); + break; + + case TypeCode.Byte: + case TypeCode.Int16: + case TypeCode.Int32: + case TypeCode.Int64: + case TypeCode.SByte: + case TypeCode.UInt16: + case TypeCode.UInt32: + case TypeCode.UInt64: + case TypeCode.Single: + case TypeCode.Double: + case TypeCode.Decimal: + eventInfo.RenderedValue = YamlFormatter.FormatNumber(eventInfo.Source.Value); + break; + + case TypeCode.String: + case TypeCode.Char: + eventInfo.RenderedValue = eventInfo.Source.Value.ToString(); + eventInfo.Style = ScalarStyle.DoubleQuoted; + break; + + case TypeCode.DateTime: + eventInfo.RenderedValue = YamlFormatter.FormatDateTime(eventInfo.Source.Value); + break; + + case TypeCode.Empty: + eventInfo.RenderedValue = "null"; + break; + + default: + if (eventInfo.Source.Type == typeof(TimeSpan)) + { + eventInfo.RenderedValue = YamlFormatter.FormatTimeSpan(eventInfo.Source.Value); + break; + } + + throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "TypeCode.{0} is not supported.", typeCode)); + } + + base.Emit(eventInfo, emitter); + } + + public override void Emit(MappingStartEventInfo eventInfo, IEmitter emitter) + { + eventInfo.Style = MappingStyle.Flow; + + base.Emit(eventInfo, emitter); + } + + public override void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter) + { + eventInfo.Style = SequenceStyle.Flow; + + base.Emit(eventInfo, emitter); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/EventEmitters/JsonEventEmitter.cs.meta b/YamlDotNet/Serialization/EventEmitters/JsonEventEmitter.cs.meta new file mode 100644 index 0000000..ac1c142 --- /dev/null +++ b/YamlDotNet/Serialization/EventEmitters/JsonEventEmitter.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 62580a3e5f0e5314e83b62758257428e +timeCreated: 1427495771 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/EventEmitters/TypeAssigningEventEmitter.cs b/YamlDotNet/Serialization/EventEmitters/TypeAssigningEventEmitter.cs new file mode 100644 index 0000000..14210ad --- /dev/null +++ b/YamlDotNet/Serialization/EventEmitters/TypeAssigningEventEmitter.cs @@ -0,0 +1,139 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Globalization; +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization.EventEmitters +{ + public sealed class TypeAssigningEventEmitter : ChainedEventEmitter + { + private readonly bool _assignTypeWhenDifferent; + + public TypeAssigningEventEmitter(IEventEmitter nextEmitter, bool assignTypeWhenDifferent) + : base(nextEmitter) + { + _assignTypeWhenDifferent = assignTypeWhenDifferent; + } + + public override void Emit(ScalarEventInfo eventInfo, IEmitter emitter) + { + var suggestedStyle = ScalarStyle.Plain; + + var typeCode = eventInfo.Source.Value != null + ? eventInfo.Source.Type.GetTypeCode() + : TypeCode.Empty; + + switch (typeCode) + { + case TypeCode.Boolean: + eventInfo.Tag = "tag:yaml.org,2002:bool"; + eventInfo.RenderedValue = YamlFormatter.FormatBoolean(eventInfo.Source.Value); + break; + + case TypeCode.Byte: + case TypeCode.Int16: + case TypeCode.Int32: + case TypeCode.Int64: + case TypeCode.SByte: + case TypeCode.UInt16: + case TypeCode.UInt32: + case TypeCode.UInt64: + eventInfo.Tag = "tag:yaml.org,2002:int"; + eventInfo.RenderedValue = YamlFormatter.FormatNumber(eventInfo.Source.Value); + break; + + case TypeCode.Single: + eventInfo.Tag = "tag:yaml.org,2002:float"; + eventInfo.RenderedValue = YamlFormatter.FormatNumber((float)eventInfo.Source.Value); + break; + + case TypeCode.Double: + eventInfo.Tag = "tag:yaml.org,2002:float"; + eventInfo.RenderedValue = YamlFormatter.FormatNumber((double)eventInfo.Source.Value); + break; + + case TypeCode.Decimal: + eventInfo.Tag = "tag:yaml.org,2002:float"; + eventInfo.RenderedValue = YamlFormatter.FormatNumber(eventInfo.Source.Value); + break; + + case TypeCode.String: + case TypeCode.Char: + eventInfo.Tag = "tag:yaml.org,2002:str"; + eventInfo.RenderedValue = eventInfo.Source.Value.ToString(); + suggestedStyle = ScalarStyle.Any; + break; + + case TypeCode.DateTime: + eventInfo.Tag = "tag:yaml.org,2002:timestamp"; + eventInfo.RenderedValue = YamlFormatter.FormatDateTime(eventInfo.Source.Value); + break; + + case TypeCode.Empty: + eventInfo.Tag = "tag:yaml.org,2002:null"; + eventInfo.RenderedValue = ""; + break; + + default: + if (eventInfo.Source.Type == typeof(TimeSpan)) + { + eventInfo.RenderedValue = YamlFormatter.FormatTimeSpan(eventInfo.Source.Value); + break; + } + + throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "TypeCode.{0} is not supported.", typeCode)); + } + + eventInfo.IsPlainImplicit = true; + if (eventInfo.Style == ScalarStyle.Any) + { + eventInfo.Style = suggestedStyle; + } + + base.Emit(eventInfo, emitter); + } + + public override void Emit(MappingStartEventInfo eventInfo, IEmitter emitter) + { + AssignTypeIfDifferent(eventInfo); + base.Emit(eventInfo, emitter); + } + + public override void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter) + { + AssignTypeIfDifferent(eventInfo); + base.Emit(eventInfo, emitter); + } + + private void AssignTypeIfDifferent(ObjectEventInfo eventInfo) + { + if (_assignTypeWhenDifferent && eventInfo.Source.Value != null) + { + if (eventInfo.Source.Type != eventInfo.Source.StaticType) + { + eventInfo.Tag = "!" + eventInfo.Source.Type.AssemblyQualifiedName; + } + } + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/EventEmitters/TypeAssigningEventEmitter.cs.meta b/YamlDotNet/Serialization/EventEmitters/TypeAssigningEventEmitter.cs.meta new file mode 100644 index 0000000..c8f24b6 --- /dev/null +++ b/YamlDotNet/Serialization/EventEmitters/TypeAssigningEventEmitter.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: e1b82bb57f4eb7f4ba0ffad467f82555 +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/EventEmitters/WriterEventEmitter.cs b/YamlDotNet/Serialization/EventEmitters/WriterEventEmitter.cs new file mode 100644 index 0000000..d1a26c5 --- /dev/null +++ b/YamlDotNet/Serialization/EventEmitters/WriterEventEmitter.cs @@ -0,0 +1,59 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using YamlDotNet.Core; +using YamlDotNet.Core.Events; + +namespace YamlDotNet.Serialization.EventEmitters +{ + public sealed class WriterEventEmitter : IEventEmitter + { + void IEventEmitter.Emit(AliasEventInfo eventInfo, IEmitter emitter) + { + emitter.Emit(new AnchorAlias(eventInfo.Alias)); + } + + void IEventEmitter.Emit(ScalarEventInfo eventInfo, IEmitter emitter) + { + emitter.Emit(new Scalar(eventInfo.Anchor, eventInfo.Tag, eventInfo.RenderedValue, eventInfo.Style, eventInfo.IsPlainImplicit, eventInfo.IsQuotedImplicit)); + } + + void IEventEmitter.Emit(MappingStartEventInfo eventInfo, IEmitter emitter) + { + emitter.Emit(new MappingStart(eventInfo.Anchor, eventInfo.Tag, eventInfo.IsImplicit, eventInfo.Style)); + } + + void IEventEmitter.Emit(MappingEndEventInfo eventInfo, IEmitter emitter) + { + emitter.Emit(new MappingEnd()); + } + + void IEventEmitter.Emit(SequenceStartEventInfo eventInfo, IEmitter emitter) + { + emitter.Emit(new SequenceStart(eventInfo.Anchor, eventInfo.Tag, eventInfo.IsImplicit, eventInfo.Style)); + } + + void IEventEmitter.Emit(SequenceEndEventInfo eventInfo, IEmitter emitter) + { + emitter.Emit(new SequenceEnd()); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/EventEmitters/WriterEventEmitter.cs.meta b/YamlDotNet/Serialization/EventEmitters/WriterEventEmitter.cs.meta new file mode 100644 index 0000000..077fbed --- /dev/null +++ b/YamlDotNet/Serialization/EventEmitters/WriterEventEmitter.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f2ea019325fb629499443d6af969a295 +timeCreated: 1427145267 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/EventInfo.cs b/YamlDotNet/Serialization/EventInfo.cs new file mode 100644 index 0000000..56fb6b5 --- /dev/null +++ b/YamlDotNet/Serialization/EventInfo.cs @@ -0,0 +1,109 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using YamlDotNet.Core; +using YamlDotNet.Core.Events; + +namespace YamlDotNet.Serialization +{ + public abstract class EventInfo + { + public IObjectDescriptor Source { get; private set; } + + protected EventInfo(IObjectDescriptor source) + { + Source = source; + } + } + + public class AliasEventInfo : EventInfo + { + public AliasEventInfo(IObjectDescriptor source) + : base(source) + { + } + + public string Alias { get; set; } + } + + public class ObjectEventInfo : EventInfo + { + protected ObjectEventInfo(IObjectDescriptor source) + : base(source) + { + } + + public string Anchor { get; set; } + public string Tag { get; set; } + } + + public sealed class ScalarEventInfo : ObjectEventInfo + { + public ScalarEventInfo(IObjectDescriptor source) + : base(source) + { + Style = source.ScalarStyle; + } + + public string RenderedValue { get; set; } + public ScalarStyle Style { get; set; } + public bool IsPlainImplicit { get; set; } + public bool IsQuotedImplicit { get; set; } + } + + public sealed class MappingStartEventInfo : ObjectEventInfo + { + public MappingStartEventInfo(IObjectDescriptor source) + : base(source) + { + } + + public bool IsImplicit { get; set; } + public MappingStyle Style { get; set; } + } + + public sealed class MappingEndEventInfo : EventInfo + { + public MappingEndEventInfo(IObjectDescriptor source) + : base(source) + { + } + } + + public sealed class SequenceStartEventInfo : ObjectEventInfo + { + public SequenceStartEventInfo(IObjectDescriptor source) + : base(source) + { + } + + public bool IsImplicit { get; set; } + public SequenceStyle Style { get; set; } + } + + public sealed class SequenceEndEventInfo : EventInfo + { + public SequenceEndEventInfo(IObjectDescriptor source) + : base(source) + { + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/EventInfo.cs.meta b/YamlDotNet/Serialization/EventInfo.cs.meta new file mode 100644 index 0000000..0ec17ef --- /dev/null +++ b/YamlDotNet/Serialization/EventInfo.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: e72f96c4049a0dc4d97ad0d44f6b766d +timeCreated: 1427145267 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/IAliasProvider.cs b/YamlDotNet/Serialization/IAliasProvider.cs new file mode 100644 index 0000000..6d4b0cc --- /dev/null +++ b/YamlDotNet/Serialization/IAliasProvider.cs @@ -0,0 +1,28 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +namespace YamlDotNet.Serialization +{ + public interface IAliasProvider + { + string GetAlias(object target); + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/IAliasProvider.cs.meta b/YamlDotNet/Serialization/IAliasProvider.cs.meta new file mode 100644 index 0000000..66f6768 --- /dev/null +++ b/YamlDotNet/Serialization/IAliasProvider.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 3a934679d1d7f204e9d25f18f7f397bb +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/IEventEmitter.cs b/YamlDotNet/Serialization/IEventEmitter.cs new file mode 100644 index 0000000..bab3fe2 --- /dev/null +++ b/YamlDotNet/Serialization/IEventEmitter.cs @@ -0,0 +1,35 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization +{ + public interface IEventEmitter + { + void Emit(AliasEventInfo eventInfo, IEmitter emitter); + void Emit(ScalarEventInfo eventInfo, IEmitter emitter); + void Emit(MappingStartEventInfo eventInfo, IEmitter emitter); + void Emit(MappingEndEventInfo eventInfo, IEmitter emitter); + void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter); + void Emit(SequenceEndEventInfo eventInfo, IEmitter emitter); + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/IEventEmitter.cs.meta b/YamlDotNet/Serialization/IEventEmitter.cs.meta new file mode 100644 index 0000000..72ed122 --- /dev/null +++ b/YamlDotNet/Serialization/IEventEmitter.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 05f7588b91e030f438b48c4af7ecf613 +timeCreated: 1427145262 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/INamingConvention.cs b/YamlDotNet/Serialization/INamingConvention.cs new file mode 100644 index 0000000..2b5ebd5 --- /dev/null +++ b/YamlDotNet/Serialization/INamingConvention.cs @@ -0,0 +1,32 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + + +namespace YamlDotNet.Serialization +{ + /// + /// Translates property names according to a specific convention. + /// + public interface INamingConvention + { + string Apply(string value); + } +} diff --git a/YamlDotNet/Serialization/INamingConvention.cs.meta b/YamlDotNet/Serialization/INamingConvention.cs.meta new file mode 100644 index 0000000..d168bc2 --- /dev/null +++ b/YamlDotNet/Serialization/INamingConvention.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f9e2e0524133523428f9f2498f7c06f7 +timeCreated: 1427145267 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/INodeDeserializer.cs b/YamlDotNet/Serialization/INodeDeserializer.cs new file mode 100644 index 0000000..2cf1568 --- /dev/null +++ b/YamlDotNet/Serialization/INodeDeserializer.cs @@ -0,0 +1,31 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization +{ + public interface INodeDeserializer + { + bool Deserialize(IParser reader, Type expectedType, Func nestedObjectDeserializer, out object value); + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/INodeDeserializer.cs.meta b/YamlDotNet/Serialization/INodeDeserializer.cs.meta new file mode 100644 index 0000000..4ac62fd --- /dev/null +++ b/YamlDotNet/Serialization/INodeDeserializer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2f27d06ef3f08024d8a6ee848351527a +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/INodeTypeResolver.cs b/YamlDotNet/Serialization/INodeTypeResolver.cs new file mode 100644 index 0000000..ec98d58 --- /dev/null +++ b/YamlDotNet/Serialization/INodeTypeResolver.cs @@ -0,0 +1,40 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using YamlDotNet.Core.Events; + +namespace YamlDotNet.Serialization +{ + public interface INodeTypeResolver + { + /// + /// Determines the type of the specified node. + /// + /// The node to be deserialized. + /// The type that has been determined so far. + /// + /// true if has been resolved completely; + /// false if the next type should be invoked. + /// + bool Resolve(NodeEvent nodeEvent, ref Type currentType); + } +} diff --git a/YamlDotNet/Serialization/INodeTypeResolver.cs.meta b/YamlDotNet/Serialization/INodeTypeResolver.cs.meta new file mode 100644 index 0000000..15933fb --- /dev/null +++ b/YamlDotNet/Serialization/INodeTypeResolver.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: fc7c4eab6abbae74eb74eee44a52e6a7 +timeCreated: 1427145267 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/IObjectDescriptor.cs b/YamlDotNet/Serialization/IObjectDescriptor.cs new file mode 100644 index 0000000..257b443 --- /dev/null +++ b/YamlDotNet/Serialization/IObjectDescriptor.cs @@ -0,0 +1,52 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization +{ + /// + /// Represents an object along with its type. + /// + public interface IObjectDescriptor + { + /// + /// A reference to the object. + /// + object Value { get; } + + /// + /// The type that should be used when to interpret the . + /// + Type Type { get; } + + /// + /// The type of as determined by its container (e.g. a property). + /// + Type StaticType { get; } + + /// + /// The style to be used for scalars. + /// + ScalarStyle ScalarStyle { get; } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/IObjectDescriptor.cs.meta b/YamlDotNet/Serialization/IObjectDescriptor.cs.meta new file mode 100644 index 0000000..02e03e4 --- /dev/null +++ b/YamlDotNet/Serialization/IObjectDescriptor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: bcb0a1a8415e8714ab58565d3f392aec +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/IObjectFactory.cs b/YamlDotNet/Serialization/IObjectFactory.cs new file mode 100644 index 0000000..fd90a29 --- /dev/null +++ b/YamlDotNet/Serialization/IObjectFactory.cs @@ -0,0 +1,39 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace YamlDotNet.Serialization +{ + /// + /// Creates instances of types. + /// + /// + /// This interface allows to provide a custom logic for creating instances during deserialization. + /// + public interface IObjectFactory + { + /// + /// Creates an instance of the specified type. + /// + object Create(Type type); + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/IObjectFactory.cs.meta b/YamlDotNet/Serialization/IObjectFactory.cs.meta new file mode 100644 index 0000000..9628926 --- /dev/null +++ b/YamlDotNet/Serialization/IObjectFactory.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 86a19edb69863084e9364dec9fcda8c4 +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/IObjectGraphTraversalStrategy.cs b/YamlDotNet/Serialization/IObjectGraphTraversalStrategy.cs new file mode 100644 index 0000000..39ad92d --- /dev/null +++ b/YamlDotNet/Serialization/IObjectGraphTraversalStrategy.cs @@ -0,0 +1,39 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization +{ + /// + /// Defines a strategy that walks through an object graph. + /// + public interface IObjectGraphTraversalStrategy + { + /// + /// Traverses the specified object graph. + /// + /// The graph. + /// An that is to be notified during the traversal. + /// A that will be passed to the . + void Traverse(IObjectDescriptor graph, IObjectGraphVisitor visitor, TContext context); + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/IObjectGraphTraversalStrategy.cs.meta b/YamlDotNet/Serialization/IObjectGraphTraversalStrategy.cs.meta new file mode 100644 index 0000000..e34f5da --- /dev/null +++ b/YamlDotNet/Serialization/IObjectGraphTraversalStrategy.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 33215c487a2a3f04cbbe41c318253ee0 +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/IObjectGraphVisitor.cs b/YamlDotNet/Serialization/IObjectGraphVisitor.cs new file mode 100644 index 0000000..c72b614 --- /dev/null +++ b/YamlDotNet/Serialization/IObjectGraphVisitor.cs @@ -0,0 +1,99 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace YamlDotNet.Serialization +{ + /// + /// Defined the interface of a type that can be notified during an object graph traversal. + /// + public interface IObjectGraphVisitor + { + /// + /// Indicates whether the specified value should be entered. This allows the visitor to + /// override the handling of a particular object or type. + /// + /// The value that is about to be entered. + /// The context that this implementation depend on. + /// If the value is to be entered, returns true; otherwise returns false; + bool Enter(IObjectDescriptor value, TContext context); + + /// + /// Indicates whether the specified mapping should be entered. This allows the visitor to + /// override the handling of a particular pair. + /// + /// The key of the mapping that is about to be entered. + /// The value of the mapping that is about to be entered. + /// The context that this implementation depend on. + /// If the mapping is to be entered, returns true; otherwise returns false; + bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, TContext context); + + /// + /// Indicates whether the specified mapping should be entered. This allows the visitor to + /// override the handling of a particular pair. This overload should be invoked when the + /// mapping is produced by an object's property. + /// + /// The that provided access to . + /// The value of the mapping that is about to be entered. + /// The context that this implementation depend on. + /// If the mapping is to be entered, returns true; otherwise returns false; + bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, TContext context); + + /// + /// Notifies the visitor that a scalar value has been encountered. + /// + /// The value of the scalar. + /// The context that this implementation depend on. + void VisitScalar(IObjectDescriptor scalar, TContext context); + + /// + /// Notifies the visitor that the traversal of a mapping is about to begin. + /// + /// The value that corresponds to the mapping. + /// The static type of the keys of the mapping. + /// The static type of the values of the mapping. + /// The context that this implementation depend on. + void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, TContext context); + + /// + /// Notifies the visitor that the traversal of a mapping has ended. + /// + /// The value that corresponds to the mapping. + /// The context that this implementation depend on. + void VisitMappingEnd(IObjectDescriptor mapping, TContext context); + + /// + /// Notifies the visitor that the traversal of a sequence is about to begin. + /// + /// The value that corresponds to the sequence. + /// The static type of the elements of the sequence. + /// The context that this implementation depend on. + void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, TContext context); + + /// + /// Notifies the visitor that the traversal of a sequence has ended. + /// + /// The value that corresponds to the sequence. + /// The context that this implementation depend on. + void VisitSequenceEnd(IObjectDescriptor sequence, TContext context); + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/IObjectGraphVisitor.cs.meta b/YamlDotNet/Serialization/IObjectGraphVisitor.cs.meta new file mode 100644 index 0000000..690f1ee --- /dev/null +++ b/YamlDotNet/Serialization/IObjectGraphVisitor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d6232168616fce2428643fe75d1ed035 +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/IPropertyDescriptor.cs b/YamlDotNet/Serialization/IPropertyDescriptor.cs new file mode 100644 index 0000000..a854e60 --- /dev/null +++ b/YamlDotNet/Serialization/IPropertyDescriptor.cs @@ -0,0 +1,41 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization +{ + public interface IPropertyDescriptor + { + string Name { get; } + bool CanWrite { get; } + Type Type { get; } + Type TypeOverride { get; set; } + int Order { get; set; } + ScalarStyle ScalarStyle { get; set; } + + T GetCustomAttribute() where T : Attribute; + + IObjectDescriptor Read(object target); + void Write(object target, object value); + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/IPropertyDescriptor.cs.meta b/YamlDotNet/Serialization/IPropertyDescriptor.cs.meta new file mode 100644 index 0000000..5cedc3a --- /dev/null +++ b/YamlDotNet/Serialization/IPropertyDescriptor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: c5985b699bccf7548a76738be6b6e551 +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/IRegistrationLocationSelectionSyntax.cs b/YamlDotNet/Serialization/IRegistrationLocationSelectionSyntax.cs new file mode 100644 index 0000000..60f81ef --- /dev/null +++ b/YamlDotNet/Serialization/IRegistrationLocationSelectionSyntax.cs @@ -0,0 +1,59 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +namespace YamlDotNet.Serialization +{ + public interface IRegistrationLocationSelectionSyntax + { + /// + /// Registers the component in place of the already registered component of type . + /// + void InsteadOf() where TRegistrationType : TBaseRegistrationType; + + /// + /// Registers the component before the already registered component of type . + /// + void Before() where TRegistrationType : TBaseRegistrationType; + + /// + /// Registers the component after the already registered component of type . + /// + void After() where TRegistrationType : TBaseRegistrationType; + + /// + /// Registers the component before every other previously registered component. + /// + void OnTop(); + + /// + /// Registers the component after every other previously registered component. + /// + void OnBottom(); + } + + public interface ITrackingRegistrationLocationSelectionSyntax + { + /// + /// Registers the component in place of the already registered component of type . + /// + void InsteadOf() where TRegistrationType : TBaseRegistrationType; + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/IRegistrationLocationSelectionSyntax.cs.meta b/YamlDotNet/Serialization/IRegistrationLocationSelectionSyntax.cs.meta new file mode 100644 index 0000000..4ba6977 --- /dev/null +++ b/YamlDotNet/Serialization/IRegistrationLocationSelectionSyntax.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: e8b315e9dc4f0cc46a5996fd714949df +timeCreated: 1485601085 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/ITypeInspector.cs b/YamlDotNet/Serialization/ITypeInspector.cs new file mode 100644 index 0000000..eec47fa --- /dev/null +++ b/YamlDotNet/Serialization/ITypeInspector.cs @@ -0,0 +1,53 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; + +namespace YamlDotNet.Serialization +{ + /// + /// Provides access to the properties of a type. + /// + public interface ITypeInspector + { + /// + /// Gets all properties of the specified type. + /// + /// The type whose properties are to be enumerated. + /// The actual object of type whose properties are to be enumerated. Can be null. + /// + IEnumerable GetProperties(Type type, object container); + + /// + /// Gets the property of the type with the specified name. + /// + /// The type whose properties are to be searched. + /// The actual object of type whose properties are to be searched. Can be null. + /// The name of the property. + /// + /// Determines if an exception or null should be returned if can't be + /// found in + /// + /// + IPropertyDescriptor GetProperty(Type type, object container, string name, bool ignoreUnmatched); + } +} diff --git a/YamlDotNet/Serialization/ITypeInspector.cs.meta b/YamlDotNet/Serialization/ITypeInspector.cs.meta new file mode 100644 index 0000000..c7be049 --- /dev/null +++ b/YamlDotNet/Serialization/ITypeInspector.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 915f534464f498641ab97a0e2c651b77 +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/ITypeResolver.cs b/YamlDotNet/Serialization/ITypeResolver.cs new file mode 100644 index 0000000..ab4f844 --- /dev/null +++ b/YamlDotNet/Serialization/ITypeResolver.cs @@ -0,0 +1,33 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace YamlDotNet.Serialization +{ + /// + /// Resolves the type of values. + /// + public interface ITypeResolver + { + Type Resolve(Type staticType, object actualValue); + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/ITypeResolver.cs.meta b/YamlDotNet/Serialization/ITypeResolver.cs.meta new file mode 100644 index 0000000..b3312b7 --- /dev/null +++ b/YamlDotNet/Serialization/ITypeResolver.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6c3bd4a3f0eca6e4f92ba855bc058d25 +timeCreated: 1427145264 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/IValueDeserializer.cs b/YamlDotNet/Serialization/IValueDeserializer.cs new file mode 100644 index 0000000..8fbfd7b --- /dev/null +++ b/YamlDotNet/Serialization/IValueDeserializer.cs @@ -0,0 +1,32 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using YamlDotNet.Core; +using YamlDotNet.Serialization.Utilities; + +namespace YamlDotNet.Serialization +{ + public interface IValueDeserializer + { + object DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer); + } +} diff --git a/YamlDotNet/Serialization/IValueDeserializer.cs.meta b/YamlDotNet/Serialization/IValueDeserializer.cs.meta new file mode 100644 index 0000000..aef57e7 --- /dev/null +++ b/YamlDotNet/Serialization/IValueDeserializer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: c1356281a3d017849a3240d70d9cfacd +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/IValuePromise.cs b/YamlDotNet/Serialization/IValuePromise.cs new file mode 100644 index 0000000..96f6f21 --- /dev/null +++ b/YamlDotNet/Serialization/IValuePromise.cs @@ -0,0 +1,32 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Diagnostics.CodeAnalysis; + +namespace YamlDotNet.Serialization +{ + public interface IValuePromise + { + [SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")] + event Action ValueAvailable; + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/IValuePromise.cs.meta b/YamlDotNet/Serialization/IValuePromise.cs.meta new file mode 100644 index 0000000..a1470ad --- /dev/null +++ b/YamlDotNet/Serialization/IValuePromise.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 432dc17fcd3e2cb40990aab6122f075f +timeCreated: 1427145264 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/IValueSerializer.cs b/YamlDotNet/Serialization/IValueSerializer.cs new file mode 100644 index 0000000..4ace3c8 --- /dev/null +++ b/YamlDotNet/Serialization/IValueSerializer.cs @@ -0,0 +1,31 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization +{ + public interface IValueSerializer + { + void SerializeValue(IEmitter emitter, object value, Type type); + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/IValueSerializer.cs.meta b/YamlDotNet/Serialization/IValueSerializer.cs.meta new file mode 100644 index 0000000..f0691cf --- /dev/null +++ b/YamlDotNet/Serialization/IValueSerializer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: ff3525defc264b14c816465f47cdaff0 +timeCreated: 1485601086 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/IYamlConvertible.cs b/YamlDotNet/Serialization/IYamlConvertible.cs new file mode 100644 index 0000000..493dee2 --- /dev/null +++ b/YamlDotNet/Serialization/IYamlConvertible.cs @@ -0,0 +1,67 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization +{ + /// + /// Allows an object to customize how it is serialized and deserialized. + /// + public interface IYamlConvertible + { + /// + /// Reads this object's state from a YAML parser. + /// + /// The parser where the object's state should be read from. + /// The type that the deserializer is expecting. + /// + /// A function that will use the current deserializer + /// to read an object of the given type from the parser. + /// + void Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer); + + /// + /// Writes this object's state to a YAML emitter. + /// + /// The emitter where the object's state should be written to. + /// A function that will use the current serializer to write an object to the emitter. + void Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer); + } + + /// + /// Represents a function that is used to deserialize an object of the given type. + /// + /// The type that the deserializer should read. + /// Returns the object that was deserialized. + public delegate object ObjectDeserializer(Type type); + + /// + /// Represents a function that is used to serialize an object of the given type. + /// + /// The object to be serialized. + /// + /// The type that should be considered when emitting the object. + /// If null, the actual type of the is used. + /// + public delegate void ObjectSerializer(object value, Type type = null); +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/IYamlConvertible.cs.meta b/YamlDotNet/Serialization/IYamlConvertible.cs.meta new file mode 100644 index 0000000..913669f --- /dev/null +++ b/YamlDotNet/Serialization/IYamlConvertible.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: e935f5c26bd25144096157783aa4f6d6 +timeCreated: 1485601085 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/IYamlSerializable.cs b/YamlDotNet/Serialization/IYamlSerializable.cs new file mode 100644 index 0000000..5a1f9ab --- /dev/null +++ b/YamlDotNet/Serialization/IYamlSerializable.cs @@ -0,0 +1,43 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization +{ + /// + /// Allows an object to customize how it is serialized and deserialized. + /// + [Obsolete("Please use IYamlConvertible instead")] + public interface IYamlSerializable + { + /// + /// Reads this object's state from a YAML parser. + /// + void ReadYaml(IParser parser); + + /// + /// Writes this object's state to a YAML emitter. + /// + void WriteYaml(IEmitter emitter); + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/IYamlSerializable.cs.meta b/YamlDotNet/Serialization/IYamlSerializable.cs.meta new file mode 100644 index 0000000..96751b2 --- /dev/null +++ b/YamlDotNet/Serialization/IYamlSerializable.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f42bad1c9f9fdf242b696f20c2e66259 +timeCreated: 1427145267 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/IYamlTypeConverter.cs b/YamlDotNet/Serialization/IYamlTypeConverter.cs new file mode 100644 index 0000000..a025c5d --- /dev/null +++ b/YamlDotNet/Serialization/IYamlTypeConverter.cs @@ -0,0 +1,47 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization +{ + /// + /// Allows to customize how a type is serialized and deserialized. + /// + public interface IYamlTypeConverter + { + /// + /// Gets a value indicating whether the current converter supports converting the specified type. + /// + bool Accepts(Type type); + + /// + /// Reads an object's state from a YAML parser. + /// + object ReadYaml(IParser parser, Type type); + + /// + /// Writes the specified object's state to a YAML emitter. + /// + void WriteYaml(IEmitter emitter, object value, Type type); + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/IYamlTypeConverter.cs.meta b/YamlDotNet/Serialization/IYamlTypeConverter.cs.meta new file mode 100644 index 0000000..2469092 --- /dev/null +++ b/YamlDotNet/Serialization/IYamlTypeConverter.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f114886060e4acf46b36ac2c9f610cc3 +timeCreated: 1427145267 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/LazyComponentRegistrationList.cs b/YamlDotNet/Serialization/LazyComponentRegistrationList.cs new file mode 100644 index 0000000..3a1ebe4 --- /dev/null +++ b/YamlDotNet/Serialization/LazyComponentRegistrationList.cs @@ -0,0 +1,237 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +namespace YamlDotNet.Serialization +{ + internal sealed class LazyComponentRegistrationList : IEnumerable> + { + private readonly List entries = new List(); + + public LazyComponentRegistrationList Clone() + { + var clone = new LazyComponentRegistrationList(); + foreach (var entry in entries) + { + clone.entries.Add(entry); + } + return clone; + } + + public sealed class LazyComponentRegistration + { + public readonly Type ComponentType; + public readonly Func Factory; + + public LazyComponentRegistration(Type componentType, Func factory) + { + ComponentType = componentType; + Factory = factory; + } + } + + public sealed class TrackingLazyComponentRegistration + { + public readonly Type ComponentType; + public readonly Func Factory; + + public TrackingLazyComponentRegistration(Type componentType, Func factory) + { + ComponentType = componentType; + Factory = factory; + } + } + + public void Add(Type componentType, Func factory) + { + entries.Add(new LazyComponentRegistration(componentType, factory)); + } + + public void Remove(Type componentType) + { + for (int i = 0; i < entries.Count; ++i) + { + if(entries[i].ComponentType == componentType) + { + entries.RemoveAt(i); + return; + } + } + + throw new KeyNotFoundException(string.Format("A component registration of type '{0}' was not found.", componentType.FullName)); + } + + public int Count { get { return entries.Count; } } + + public IEnumerable> InReverseOrder + { + get + { + for (int i = entries.Count - 1; i >= 0; --i) + { + yield return entries[i].Factory; + } + } + } + + public IRegistrationLocationSelectionSyntax CreateRegistrationLocationSelector( + Type componentType, + Func factory + ) + { + return new RegistrationLocationSelector( + this, + new LazyComponentRegistration(componentType, factory) + ); + } + + public ITrackingRegistrationLocationSelectionSyntax CreateTrackingRegistrationLocationSelector( + Type componentType, + Func factory + ) + { + return new TrackingRegistrationLocationSelector( + this, + new TrackingLazyComponentRegistration(componentType, factory) + ); + } + + public IEnumerator> GetEnumerator() + { + return entries.Select(e => e.Factory).GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + private int IndexOfRegistration(Type registrationType) + { + for (int i = 0; i < entries.Count; ++i) + { + if (registrationType == entries[i].ComponentType) + { + return i; + } + } + return -1; + } + + private void EnsureNoDuplicateRegistrationType(Type componentType) + { + if (IndexOfRegistration(componentType) != -1) + { + throw new InvalidOperationException(string.Format("A component of type '{0}' has already been registered.", componentType.FullName)); + } + } + + private int EnsureRegistrationExists() + { + var registrationIndex = IndexOfRegistration(typeof(TRegistrationType)); + if (registrationIndex == -1) + { + throw new InvalidOperationException(string.Format("A component of type '{0}' has not been registered.", typeof(TRegistrationType).FullName)); + } + return registrationIndex; + } + + private class RegistrationLocationSelector : IRegistrationLocationSelectionSyntax + { + private readonly LazyComponentRegistrationList registrations; + private readonly LazyComponentRegistration newRegistration; + + public RegistrationLocationSelector(LazyComponentRegistrationList registrations, LazyComponentRegistration newRegistration) + { + this.registrations = registrations; + this.newRegistration = newRegistration; + } + + void IRegistrationLocationSelectionSyntax.InsteadOf() + { + if (newRegistration.ComponentType != typeof(TRegistrationType)) + { + registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); + } + + var registrationIndex = registrations.EnsureRegistrationExists(); + registrations.entries[registrationIndex] = newRegistration; + } + + void IRegistrationLocationSelectionSyntax.After() + { + registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); + var registrationIndex = registrations.EnsureRegistrationExists(); + registrations.entries.Insert(registrationIndex + 1, newRegistration); + } + + void IRegistrationLocationSelectionSyntax.Before() + { + registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); + var registrationIndex = registrations.EnsureRegistrationExists(); + registrations.entries.Insert(registrationIndex, newRegistration); + } + + void IRegistrationLocationSelectionSyntax.OnBottom() + { + registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); + registrations.entries.Add(newRegistration); + } + + void IRegistrationLocationSelectionSyntax.OnTop() + { + registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); + registrations.entries.Insert(0, newRegistration); + } + } + + private class TrackingRegistrationLocationSelector : ITrackingRegistrationLocationSelectionSyntax + { + private readonly LazyComponentRegistrationList registrations; + private readonly TrackingLazyComponentRegistration newRegistration; + + public TrackingRegistrationLocationSelector(LazyComponentRegistrationList registrations, TrackingLazyComponentRegistration newRegistration) + { + this.registrations = registrations; + this.newRegistration = newRegistration; + } + + void ITrackingRegistrationLocationSelectionSyntax.InsteadOf() + { + if (newRegistration.ComponentType != typeof(TRegistrationType)) + { + registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); + } + + var registrationIndex = registrations.EnsureRegistrationExists(); + var innerComponentFactory = registrations.entries[registrationIndex].Factory; + registrations.entries[registrationIndex] = new LazyComponentRegistration( + newRegistration.ComponentType, + arg => newRegistration.Factory(innerComponentFactory(arg), arg) + ); + } + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/LazyComponentRegistrationList.cs.meta b/YamlDotNet/Serialization/LazyComponentRegistrationList.cs.meta new file mode 100644 index 0000000..8b518c6 --- /dev/null +++ b/YamlDotNet/Serialization/LazyComponentRegistrationList.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: cd510436aeb100b4fbfef4b48e85fae6 +timeCreated: 1485601085 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/LazyComponentRegistrationListExtensions.cs b/YamlDotNet/Serialization/LazyComponentRegistrationListExtensions.cs new file mode 100644 index 0000000..996b6c8 --- /dev/null +++ b/YamlDotNet/Serialization/LazyComponentRegistrationListExtensions.cs @@ -0,0 +1,64 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace YamlDotNet.Serialization +{ + internal static class LazyComponentRegistrationListExtensions + { + public static TComponent BuildComponentChain(this LazyComponentRegistrationList registrations, TComponent innerComponent) + { + var outerComponent = registrations.InReverseOrder.Aggregate( + innerComponent, + (inner, factory) => factory(inner) + ); + + return outerComponent; + } + + public static TComponent BuildComponentChain(this LazyComponentRegistrationList registrations, TComponent innerComponent, Func argumentBuilder) + { + var outerComponent = registrations.InReverseOrder.Aggregate( + innerComponent, + (inner, factory) => factory(argumentBuilder(inner)) + ); + + return outerComponent; + } + + public static List BuildComponentList(this LazyComponentRegistrationList registrations) + { + return registrations + .Select(factory => factory(null)) + .ToList(); + } + + public static List BuildComponentList(this LazyComponentRegistrationList registrations, TArgument argument) + { + return registrations + .Select(factory => factory(argument)) + .ToList(); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/LazyComponentRegistrationListExtensions.cs.meta b/YamlDotNet/Serialization/LazyComponentRegistrationListExtensions.cs.meta new file mode 100644 index 0000000..1aa3340 --- /dev/null +++ b/YamlDotNet/Serialization/LazyComponentRegistrationListExtensions.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 7fb8445f98c5ea943ac8e7aabe5ece7b +timeCreated: 1485601084 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/NamingConventions.meta b/YamlDotNet/Serialization/NamingConventions.meta new file mode 100644 index 0000000..45c85fc --- /dev/null +++ b/YamlDotNet/Serialization/NamingConventions.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 767c978518279084085a6e65bcb24a43 +folderAsset: yes +timeCreated: 1427145262 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/NamingConventions/CamelCaseNamingConvention.cs b/YamlDotNet/Serialization/NamingConventions/CamelCaseNamingConvention.cs new file mode 100644 index 0000000..6e1c118 --- /dev/null +++ b/YamlDotNet/Serialization/NamingConventions/CamelCaseNamingConvention.cs @@ -0,0 +1,38 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using YamlDotNet.Serialization.Utilities; + +namespace YamlDotNet.Serialization.NamingConventions +{ + /// + /// Convert the string with underscores (this_is_a_test) or hyphens (this-is-a-test) to + /// camel case (thisIsATest). Camel case is the same as Pascal case, except the first letter + /// is lowercase. + /// + public sealed class CamelCaseNamingConvention : INamingConvention + { + public string Apply(string value) + { + return value.ToCamelCase(); + } + } +} diff --git a/YamlDotNet/Serialization/NamingConventions/CamelCaseNamingConvention.cs.meta b/YamlDotNet/Serialization/NamingConventions/CamelCaseNamingConvention.cs.meta new file mode 100644 index 0000000..5cb460e --- /dev/null +++ b/YamlDotNet/Serialization/NamingConventions/CamelCaseNamingConvention.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 32043fa3c3d7af6489b8238353dcf810 +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/NamingConventions/HyphenatedNamingConvention.cs b/YamlDotNet/Serialization/NamingConventions/HyphenatedNamingConvention.cs new file mode 100644 index 0000000..fdc7609 --- /dev/null +++ b/YamlDotNet/Serialization/NamingConventions/HyphenatedNamingConvention.cs @@ -0,0 +1,36 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using YamlDotNet.Serialization.Utilities; + +namespace YamlDotNet.Serialization.NamingConventions +{ + /// + /// Convert the string from camelcase (thisIsATest) to a hyphenated (this-is-a-test) string + /// + public sealed class HyphenatedNamingConvention : INamingConvention + { + public string Apply(string value) + { + return value.FromCamelCase("-"); + } + } +} diff --git a/YamlDotNet/Serialization/NamingConventions/HyphenatedNamingConvention.cs.meta b/YamlDotNet/Serialization/NamingConventions/HyphenatedNamingConvention.cs.meta new file mode 100644 index 0000000..49920c8 --- /dev/null +++ b/YamlDotNet/Serialization/NamingConventions/HyphenatedNamingConvention.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d393465f17a55814a8ecb04e77f1e25c +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/NamingConventions/NullNamingConvention.cs b/YamlDotNet/Serialization/NamingConventions/NullNamingConvention.cs new file mode 100644 index 0000000..62961ba --- /dev/null +++ b/YamlDotNet/Serialization/NamingConventions/NullNamingConvention.cs @@ -0,0 +1,35 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + + +namespace YamlDotNet.Serialization.NamingConventions +{ + /// + /// Performs no naming conversion. + /// + public sealed class NullNamingConvention : INamingConvention + { + public string Apply(string value) + { + return value; + } + } +} diff --git a/YamlDotNet/Serialization/NamingConventions/NullNamingConvention.cs.meta b/YamlDotNet/Serialization/NamingConventions/NullNamingConvention.cs.meta new file mode 100644 index 0000000..a27ad65 --- /dev/null +++ b/YamlDotNet/Serialization/NamingConventions/NullNamingConvention.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 1f1957c241ea377499c1656388ff9122 +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/NamingConventions/PascalCaseNamingConvention.cs b/YamlDotNet/Serialization/NamingConventions/PascalCaseNamingConvention.cs new file mode 100644 index 0000000..3e08770 --- /dev/null +++ b/YamlDotNet/Serialization/NamingConventions/PascalCaseNamingConvention.cs @@ -0,0 +1,38 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using YamlDotNet.Serialization.Utilities; + +namespace YamlDotNet.Serialization.NamingConventions +{ + /// + /// Convert the string with underscores (this_is_a_test) or hyphens (this-is-a-test) to + /// pascal case (ThisIsATest). Pascal case is the same as camel case, except the first letter + /// is uppercase. + /// + public sealed class PascalCaseNamingConvention : INamingConvention + { + public string Apply(string value) + { + return value.ToPascalCase(); + } + } +} diff --git a/YamlDotNet/Serialization/NamingConventions/PascalCaseNamingConvention.cs.meta b/YamlDotNet/Serialization/NamingConventions/PascalCaseNamingConvention.cs.meta new file mode 100644 index 0000000..6f134d1 --- /dev/null +++ b/YamlDotNet/Serialization/NamingConventions/PascalCaseNamingConvention.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 0514b2a4f30517e42bc79c445fe75383 +timeCreated: 1427145262 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/NamingConventions/UnderscoredNamingConvention.cs b/YamlDotNet/Serialization/NamingConventions/UnderscoredNamingConvention.cs new file mode 100644 index 0000000..750c1e8 --- /dev/null +++ b/YamlDotNet/Serialization/NamingConventions/UnderscoredNamingConvention.cs @@ -0,0 +1,36 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using YamlDotNet.Serialization.Utilities; + +namespace YamlDotNet.Serialization.NamingConventions +{ + /// + /// Convert the string from camelcase (thisIsATest) to a underscored (this_is_a_test) string + /// + public sealed class UnderscoredNamingConvention : INamingConvention + { + public string Apply(string value) + { + return value.FromCamelCase("_"); + } + } +} diff --git a/YamlDotNet/Serialization/NamingConventions/UnderscoredNamingConvention.cs.meta b/YamlDotNet/Serialization/NamingConventions/UnderscoredNamingConvention.cs.meta new file mode 100644 index 0000000..9cdbd87 --- /dev/null +++ b/YamlDotNet/Serialization/NamingConventions/UnderscoredNamingConvention.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: dc07ca72c2bad00498d0cd0594f69151 +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/NodeDeserializers.meta b/YamlDotNet/Serialization/NodeDeserializers.meta new file mode 100644 index 0000000..567bdfc --- /dev/null +++ b/YamlDotNet/Serialization/NodeDeserializers.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 4a4c2b9d6803c4b44ad65cedc400e3d1 +folderAsset: yes +timeCreated: 1427145262 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/NodeDeserializers/ArrayNodeDeserializer.cs b/YamlDotNet/Serialization/NodeDeserializers/ArrayNodeDeserializer.cs new file mode 100644 index 0000000..93359bb --- /dev/null +++ b/YamlDotNet/Serialization/NodeDeserializers/ArrayNodeDeserializer.cs @@ -0,0 +1,153 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections; +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization.NodeDeserializers +{ + public sealed class ArrayNodeDeserializer : INodeDeserializer + { + bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object value) + { + if (!expectedType.IsArray) + { + value = false; + return false; + } + + var itemType = expectedType.GetElementType(); + + var items = new ArrayList(); + CollectionNodeDeserializer.DeserializeHelper(itemType, parser, nestedObjectDeserializer, items, true); + + var array = Array.CreateInstance(itemType, items.Count); + items.CopyTo(array, 0); + + value = array; + return true; + } + + private sealed class ArrayList : IList + { + private object[] data; + private int count; + + public ArrayList() + { + Clear(); + } + + public int Add(object value) + { + if (count == data.Length) + { + Array.Resize(ref data, data.Length * 2); + } + data[count] = value; + return count++; + } + + public void Clear() + { + data = new object[10]; + count = 0; + } + + public bool Contains(object value) + { + throw new NotSupportedException(); + } + + public int IndexOf(object value) + { + throw new NotSupportedException(); + } + + public void Insert(int index, object value) + { + throw new NotSupportedException(); + } + + public bool IsFixedSize + { + get { return false; } + } + + public bool IsReadOnly + { + get { return false; } + } + + public void Remove(object value) + { + throw new NotSupportedException(); + } + + public void RemoveAt(int index) + { + throw new NotSupportedException(); + } + + public object this[int index] + { + get + { + return data[index]; + } + set + { + data[index] = value; + } + } + + public void CopyTo(Array array, int index) + { + Array.Copy(data, 0, array, index, count); + } + + public int Count + { + get { return count; } + } + + public bool IsSynchronized + { + get { return false; } + } + + public object SyncRoot + { + get { return data; } + } + + public IEnumerator GetEnumerator() + { + for (int i = 0; i < count; ++i) + { + yield return data[i]; + } + } + } + } +} + diff --git a/YamlDotNet/Serialization/NodeDeserializers/ArrayNodeDeserializer.cs.meta b/YamlDotNet/Serialization/NodeDeserializers/ArrayNodeDeserializer.cs.meta new file mode 100644 index 0000000..734f4df --- /dev/null +++ b/YamlDotNet/Serialization/NodeDeserializers/ArrayNodeDeserializer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 20118ab09905856488b432270429ae5b +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/NodeDeserializers/CollectionNodeDeserializer.cs b/YamlDotNet/Serialization/NodeDeserializers/CollectionNodeDeserializer.cs new file mode 100644 index 0000000..8823547 --- /dev/null +++ b/YamlDotNet/Serialization/NodeDeserializers/CollectionNodeDeserializer.cs @@ -0,0 +1,109 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Collections; +using System.Collections.Generic; +using YamlDotNet.Core; +using YamlDotNet.Core.Events; +using YamlDotNet.Helpers; +using YamlDotNet.Serialization.Utilities; + +namespace YamlDotNet.Serialization.NodeDeserializers +{ + public sealed class CollectionNodeDeserializer : INodeDeserializer + { + private readonly IObjectFactory _objectFactory; + + public CollectionNodeDeserializer(IObjectFactory objectFactory) + { + _objectFactory = objectFactory; + } + + bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object value) + { + IList list; + bool canUpdate = true; + Type itemType; + var genericCollectionType = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(ICollection<>)); + if (genericCollectionType != null) + { + var genericArguments = genericCollectionType.GetGenericArguments(); + itemType = genericArguments[0]; + + value = _objectFactory.Create(expectedType); + list = value as IList; + if (list == null) + { + var genericListType = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(IList<>)); + canUpdate = genericListType != null; + list = new GenericCollectionToNonGenericAdapter(value, genericCollectionType, genericListType); + } + } + else if (typeof(IList).IsAssignableFrom(expectedType)) + { + itemType = typeof(object); + + value = _objectFactory.Create(expectedType); + list = (IList)value; + } + else + { + value = null; + return false; + } + + DeserializeHelper(itemType, parser, nestedObjectDeserializer, list, canUpdate); + + return true; + } + + internal static void DeserializeHelper(Type tItem, IParser parser, Func nestedObjectDeserializer, IList result, bool canUpdate) + { + parser.Expect(); + while (!parser.Accept()) + { + 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(); + } + } +} diff --git a/YamlDotNet/Serialization/NodeDeserializers/CollectionNodeDeserializer.cs.meta b/YamlDotNet/Serialization/NodeDeserializers/CollectionNodeDeserializer.cs.meta new file mode 100644 index 0000000..d8741e1 --- /dev/null +++ b/YamlDotNet/Serialization/NodeDeserializers/CollectionNodeDeserializer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d789c999a074aa34fbf2ccddd0d570a2 +timeCreated: 1454664016 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/NodeDeserializers/DictionaryNodeDeserializer.cs b/YamlDotNet/Serialization/NodeDeserializers/DictionaryNodeDeserializer.cs new file mode 100644 index 0000000..af17006 --- /dev/null +++ b/YamlDotNet/Serialization/NodeDeserializers/DictionaryNodeDeserializer.cs @@ -0,0 +1,146 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Collections; +using System.Collections.Generic; +using YamlDotNet.Core; +using YamlDotNet.Core.Events; +using YamlDotNet.Helpers; +using YamlDotNet.Serialization.Utilities; + +namespace YamlDotNet.Serialization.NodeDeserializers +{ + public sealed class DictionaryNodeDeserializer : INodeDeserializer + { + private readonly IObjectFactory _objectFactory; + + public DictionaryNodeDeserializer(IObjectFactory objectFactory) + { + _objectFactory = objectFactory; + } + + bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object value) + { + IDictionary dictionary; + Type keyType, valueType; + var genericDictionaryType = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(IDictionary<,>)); + if (genericDictionaryType != null) + { + var genericArguments = genericDictionaryType.GetGenericArguments(); + keyType = genericArguments[0]; + valueType = genericArguments[1]; + + value = _objectFactory.Create(expectedType); + + dictionary = value as IDictionary; + if (dictionary == null) + { + dictionary = new GenericDictionaryToNonGenericAdapter(value, genericDictionaryType); + } + } + else if (typeof(IDictionary).IsAssignableFrom(expectedType)) + { + keyType = typeof(object); + valueType = typeof(object); + + value = _objectFactory.Create(expectedType); + dictionary = (IDictionary)value; + } + else + { + value = null; + return false; + } + + DeserializeHelper(keyType, valueType, parser, nestedObjectDeserializer, dictionary); + + return true; + } + + private static void DeserializeHelper(Type tKey, Type tValue, IParser parser, Func nestedObjectDeserializer, IDictionary result) + { + parser.Expect(); + while (!parser.Accept()) + { + 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(); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/NodeDeserializers/DictionaryNodeDeserializer.cs.meta b/YamlDotNet/Serialization/NodeDeserializers/DictionaryNodeDeserializer.cs.meta new file mode 100644 index 0000000..b8156e5 --- /dev/null +++ b/YamlDotNet/Serialization/NodeDeserializers/DictionaryNodeDeserializer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 57789f348c365ce439f2085df1b24b73 +timeCreated: 1454664016 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/NodeDeserializers/EnumerableNodeDeserializer.cs b/YamlDotNet/Serialization/NodeDeserializers/EnumerableNodeDeserializer.cs new file mode 100644 index 0000000..ad48619 --- /dev/null +++ b/YamlDotNet/Serialization/NodeDeserializers/EnumerableNodeDeserializer.cs @@ -0,0 +1,57 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections; +using System.Collections.Generic; +using YamlDotNet.Core; +using YamlDotNet.Serialization.Utilities; + +namespace YamlDotNet.Serialization.NodeDeserializers +{ + public sealed class EnumerableNodeDeserializer : INodeDeserializer + { + bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object value) + { + Type itemsType; + if (expectedType == typeof(IEnumerable)) + { + itemsType = typeof(object); + } + else + { + var iEnumerable = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(IEnumerable<>)); + if (iEnumerable != expectedType) + { + value = null; + return false; + } + + itemsType = iEnumerable.GetGenericArguments()[0]; + } + + var collectionType = typeof(List<>).MakeGenericType(itemsType); + value = nestedObjectDeserializer(parser, collectionType); + return true; + } + } +} + diff --git a/YamlDotNet/Serialization/NodeDeserializers/EnumerableNodeDeserializer.cs.meta b/YamlDotNet/Serialization/NodeDeserializers/EnumerableNodeDeserializer.cs.meta new file mode 100644 index 0000000..00fb3b9 --- /dev/null +++ b/YamlDotNet/Serialization/NodeDeserializers/EnumerableNodeDeserializer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 4b63af2cc4a9f5d4cbbadbdac863e5df +timeCreated: 1427145264 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/NodeDeserializers/NullNodeDeserializer.cs b/YamlDotNet/Serialization/NodeDeserializers/NullNodeDeserializer.cs new file mode 100644 index 0000000..6301fa4 --- /dev/null +++ b/YamlDotNet/Serialization/NodeDeserializers/NullNodeDeserializer.cs @@ -0,0 +1,61 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using YamlDotNet.Core; +using YamlDotNet.Core.Events; + +namespace YamlDotNet.Serialization.NodeDeserializers +{ + public sealed class NullNodeDeserializer : INodeDeserializer + { + bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object value) + { + value = null; + var evt = parser.Peek(); + var isNull = evt != null + && NodeIsNull(evt); + + if (isNull) + { + parser.SkipThisAndNestedEvents(); + } + return isNull; + } + + private bool NodeIsNull(NodeEvent nodeEvent) + { + // http://yaml.org/type/null.html + + if (nodeEvent.Tag == "tag:yaml.org,2002:null") + { + return true; + } + + var scalar = nodeEvent as Scalar; + if (scalar == null || scalar.Style != Core.ScalarStyle.Plain) + return false; + + var value = scalar.Value; + return value == "" || value == "~" || value == "null" || value == "Null" || value == "NULL"; + } + } +} diff --git a/YamlDotNet/Serialization/NodeDeserializers/NullNodeDeserializer.cs.meta b/YamlDotNet/Serialization/NodeDeserializers/NullNodeDeserializer.cs.meta new file mode 100644 index 0000000..dd1c119 --- /dev/null +++ b/YamlDotNet/Serialization/NodeDeserializers/NullNodeDeserializer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2dc4eb3386e00254a90e737f7663d298 +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/NodeDeserializers/ObjectNodeDeserializer.cs b/YamlDotNet/Serialization/NodeDeserializers/ObjectNodeDeserializer.cs new file mode 100644 index 0000000..3bda3f6 --- /dev/null +++ b/YamlDotNet/Serialization/NodeDeserializers/ObjectNodeDeserializer.cs @@ -0,0 +1,87 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using YamlDotNet.Core; +using YamlDotNet.Core.Events; +using YamlDotNet.Serialization.Utilities; + +namespace YamlDotNet.Serialization.NodeDeserializers +{ + public sealed class ObjectNodeDeserializer : INodeDeserializer + { + private readonly IObjectFactory _objectFactory; + private readonly ITypeInspector _typeDescriptor; + private readonly bool _ignoreUnmatched; + + public ObjectNodeDeserializer(IObjectFactory objectFactory, ITypeInspector typeDescriptor, bool ignoreUnmatched) + { + _objectFactory = objectFactory; + _typeDescriptor = typeDescriptor; + _ignoreUnmatched = ignoreUnmatched; + } + + bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object value) + { + var mapping = parser.Allow(); + if (mapping == null) + { + value = null; + return false; + } + + value = _objectFactory.Create(expectedType); + while (!parser.Accept()) + { + var propertyName = parser.Expect(); + 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(); + return true; + } + } +} diff --git a/YamlDotNet/Serialization/NodeDeserializers/ObjectNodeDeserializer.cs.meta b/YamlDotNet/Serialization/NodeDeserializers/ObjectNodeDeserializer.cs.meta new file mode 100644 index 0000000..6dcca9f --- /dev/null +++ b/YamlDotNet/Serialization/NodeDeserializers/ObjectNodeDeserializer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 203cafd2ca433854ab6bb7dcc51b861a +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/NodeDeserializers/ScalarNodeDeserializer.cs b/YamlDotNet/Serialization/NodeDeserializers/ScalarNodeDeserializer.cs new file mode 100644 index 0000000..5e62294 --- /dev/null +++ b/YamlDotNet/Serialization/NodeDeserializers/ScalarNodeDeserializer.cs @@ -0,0 +1,315 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Globalization; +using System.Text; +using System.Text.RegularExpressions; +using YamlDotNet.Core; +using YamlDotNet.Core.Events; +using YamlDotNet.Serialization.Utilities; + +namespace YamlDotNet.Serialization.NodeDeserializers +{ + public sealed class ScalarNodeDeserializer : INodeDeserializer + { + private const string BooleanTruePattern = "^(true|y|yes|on)$"; + private const string BooleanFalsePattern = "^(false|n|no|off)$"; + + bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object value) + { + var scalar = parser.Allow(); + if (scalar == null) + { + value = null; + return false; + } + + if (expectedType.IsEnum()) + { + value = Enum.Parse(expectedType, scalar.Value, true); + } + else + { + var typeCode = expectedType.GetTypeCode(); + switch (typeCode) + { + case TypeCode.Boolean: + value = DeserializeBooleanHelper(scalar.Value); + break; + + case TypeCode.Byte: + case TypeCode.Int16: + case TypeCode.Int32: + case TypeCode.Int64: + case TypeCode.SByte: + case TypeCode.UInt16: + case TypeCode.UInt32: + case TypeCode.UInt64: + value = DeserializeIntegerHelper(typeCode, scalar.Value); + break; + + case TypeCode.Single: + value = Single.Parse(scalar.Value, YamlFormatter.NumberFormat); + break; + + case TypeCode.Double: + value = Double.Parse(scalar.Value, YamlFormatter.NumberFormat); + break; + + case TypeCode.Decimal: + value = Decimal.Parse(scalar.Value, YamlFormatter.NumberFormat); + break; + + case TypeCode.String: + value = scalar.Value; + break; + + case TypeCode.Char: + value = scalar.Value[0]; + break; + + case TypeCode.DateTime: + // TODO: This is probably incorrect. Use the correct regular expression. + value = DateTime.Parse(scalar.Value, CultureInfo.InvariantCulture); + break; + + default: + if (expectedType == typeof(object)) + { + // Default to string + value = scalar.Value; + } + else + { + value = TypeConverter.ChangeType(scalar.Value, expectedType); + } + break; + } + } + return true; + } + + private object DeserializeBooleanHelper(string value) + { + bool result; + + if (Regex.IsMatch(value, ScalarNodeDeserializer.BooleanTruePattern, RegexOptions.IgnoreCase)) + { + result = true; + } + else if (Regex.IsMatch(value, ScalarNodeDeserializer.BooleanFalsePattern, RegexOptions.IgnoreCase)) + { + result = false; + } + else + { + throw new FormatException(String.Format("The value \"{0}\" is not a valid YAML Boolean", value)); + } + + return result; + } + + private object DeserializeIntegerHelper(TypeCode typeCode, string value) + { + var numberBuilder = new StringBuilder(); + int currentIndex = 0; + bool isNegative = false; + int numberBase = 0; + ulong result = 0; + + if (value[0] == '-') + { + currentIndex++; + isNegative = true; + } + + else if (value[0] == '+') + { + currentIndex++; + } + + if (value[currentIndex] == '0') + { + // Could be binary, octal, hex, decimal (0) + + // If there are no characters remaining, it's a decimal zero + if (currentIndex == value.Length - 1) + { + numberBase = 10; + result = 0; + } + + else + { + // Check the next character + currentIndex++; + + if (value[currentIndex] == 'b') + { + // Binary + numberBase = 2; + + currentIndex++; + } + + else if (value[currentIndex] == 'x') + { + // Hex + numberBase = 16; + + currentIndex++; + } + + else + { + // Octal + numberBase = 8; + } + } + + // Copy remaining digits to the number buffer (skip underscores) + while (currentIndex < value.Length) + { + if (value[currentIndex] != '_') + { + numberBuilder.Append(value[currentIndex]); + } + currentIndex++; + } + + // Parse the magnitude of the number + switch (numberBase) + { + case 2: + case 8: + // TODO: how to incorporate the numberFormat? + result = Convert.ToUInt64(numberBuilder.ToString(), numberBase); + break; + + case 16: + result = ulong.Parse(numberBuilder.ToString(), NumberStyles.HexNumber, YamlFormatter.NumberFormat); + break; + + case 10: + // Result is already zero + break; + } + } + + else + { + // Could be decimal or base 60 + var chunks = value.Substring(currentIndex).Split(':'); + result = 0; + + for (int chunkIndex = 0; chunkIndex < chunks.Length; chunkIndex++) + { + result *= 60; + + // TODO: verify that chunks after the first are non-negative and less than 60 + result += ulong.Parse(chunks[chunkIndex].Replace("_", "")); + } + } + + if (isNegative) + { + return CastInteger(checked(-(long)result), typeCode); + } + else + { + return CastInteger(result, typeCode); + } + } + + private static object CastInteger(long number, TypeCode typeCode) + { + checked + { + switch (typeCode) + { + case TypeCode.Byte: + return (byte)number; + + case TypeCode.Int16: + return (short)number; + + case TypeCode.Int32: + return (int)number; + + case TypeCode.Int64: + return number; + + case TypeCode.SByte: + return (sbyte)number; + + case TypeCode.UInt16: + return (ushort)number; + + case TypeCode.UInt32: + return (uint)number; + + case TypeCode.UInt64: + return (ulong)number; + + default: + return number; + } + } + } + + private static object CastInteger(ulong number, TypeCode typeCode) + { + checked + { + switch (typeCode) + { + case TypeCode.Byte: + return (byte)number; + + case TypeCode.Int16: + return (short)number; + + case TypeCode.Int32: + return (int)number; + + case TypeCode.Int64: + return (long)number; + + case TypeCode.SByte: + return (sbyte)number; + + case TypeCode.UInt16: + return (ushort)number; + + case TypeCode.UInt32: + return (uint)number; + + case TypeCode.UInt64: + return number; + + default: + return number; + } + } + } + } +} diff --git a/YamlDotNet/Serialization/NodeDeserializers/ScalarNodeDeserializer.cs.meta b/YamlDotNet/Serialization/NodeDeserializers/ScalarNodeDeserializer.cs.meta new file mode 100644 index 0000000..894f91b --- /dev/null +++ b/YamlDotNet/Serialization/NodeDeserializers/ScalarNodeDeserializer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: acae7a1311005a143be6454d8b86b947 +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/NodeDeserializers/TypeConverterNodeDeserializer.cs b/YamlDotNet/Serialization/NodeDeserializers/TypeConverterNodeDeserializer.cs new file mode 100644 index 0000000..d43b71e --- /dev/null +++ b/YamlDotNet/Serialization/NodeDeserializers/TypeConverterNodeDeserializer.cs @@ -0,0 +1,57 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Linq; +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization.NodeDeserializers +{ + public sealed class TypeConverterNodeDeserializer : INodeDeserializer + { + private readonly IEnumerable converters; + + public TypeConverterNodeDeserializer(IEnumerable converters) + { + if (converters == null) + { + throw new ArgumentNullException("converters"); + } + + this.converters = converters; + } + + bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object value) + { + var converter = converters.FirstOrDefault(c => c.Accepts(expectedType)); + if (converter == null) + { + value = null; + return false; + } + + value = converter.ReadYaml(parser, expectedType); + return true; + } + } +} + diff --git a/YamlDotNet/Serialization/NodeDeserializers/TypeConverterNodeDeserializer.cs.meta b/YamlDotNet/Serialization/NodeDeserializers/TypeConverterNodeDeserializer.cs.meta new file mode 100644 index 0000000..41a2e4d --- /dev/null +++ b/YamlDotNet/Serialization/NodeDeserializers/TypeConverterNodeDeserializer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: a4dc6d0569fe722448b3d925a66e2b45 +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/NodeDeserializers/YamlConvertibleNodeDeserializer.cs b/YamlDotNet/Serialization/NodeDeserializers/YamlConvertibleNodeDeserializer.cs new file mode 100644 index 0000000..03ff9f5 --- /dev/null +++ b/YamlDotNet/Serialization/NodeDeserializers/YamlConvertibleNodeDeserializer.cs @@ -0,0 +1,50 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization.NodeDeserializers +{ + public sealed class YamlConvertibleNodeDeserializer : INodeDeserializer + { + private readonly IObjectFactory objectFactory; + + public YamlConvertibleNodeDeserializer(IObjectFactory objectFactory) + { + this.objectFactory = objectFactory; + } + + public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object value) + { + if (typeof(IYamlConvertible).IsAssignableFrom(expectedType)) + { + var convertible = (IYamlConvertible)objectFactory.Create(expectedType); + convertible.Read(parser, expectedType, type => nestedObjectDeserializer(parser, type)); + value = convertible; + return true; + } + + value = null; + return false; + } + } +} diff --git a/YamlDotNet/Serialization/NodeDeserializers/YamlConvertibleNodeDeserializer.cs.meta b/YamlDotNet/Serialization/NodeDeserializers/YamlConvertibleNodeDeserializer.cs.meta new file mode 100644 index 0000000..e31eede --- /dev/null +++ b/YamlDotNet/Serialization/NodeDeserializers/YamlConvertibleNodeDeserializer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 4022214c4cbb6be40b7ad73e0620dc0c +timeCreated: 1485601083 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/NodeDeserializers/YamlSerializableNodeDeserializer.cs b/YamlDotNet/Serialization/NodeDeserializers/YamlSerializableNodeDeserializer.cs new file mode 100644 index 0000000..1689a9e --- /dev/null +++ b/YamlDotNet/Serialization/NodeDeserializers/YamlSerializableNodeDeserializer.cs @@ -0,0 +1,52 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization.NodeDeserializers +{ + public sealed class YamlSerializableNodeDeserializer : INodeDeserializer + { + private readonly IObjectFactory objectFactory; + + public YamlSerializableNodeDeserializer(IObjectFactory objectFactory) + { + this.objectFactory = objectFactory; + } + + public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object value) + { +#pragma warning disable 0618 // IYamlSerializable is obsolete + if (typeof(IYamlSerializable).IsAssignableFrom(expectedType)) + { + var serializable = (IYamlSerializable)objectFactory.Create(expectedType); + serializable.ReadYaml(parser); + value = serializable; + return true; + } +#pragma warning restore + + value = null; + return false; + } + } +} diff --git a/YamlDotNet/Serialization/NodeDeserializers/YamlSerializableNodeDeserializer.cs.meta b/YamlDotNet/Serialization/NodeDeserializers/YamlSerializableNodeDeserializer.cs.meta new file mode 100644 index 0000000..4f5d5a6 --- /dev/null +++ b/YamlDotNet/Serialization/NodeDeserializers/YamlSerializableNodeDeserializer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: dd9decb2273378147889a787cb6bb8e1 +timeCreated: 1485601085 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/NodeTypeResolvers.meta b/YamlDotNet/Serialization/NodeTypeResolvers.meta new file mode 100644 index 0000000..81e47f4 --- /dev/null +++ b/YamlDotNet/Serialization/NodeTypeResolvers.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: dcbf27d19b1e0ef4d8ba634760b0d3da +folderAsset: yes +timeCreated: 1427145262 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/NodeTypeResolvers/DefaultContainersNodeTypeResolver.cs b/YamlDotNet/Serialization/NodeTypeResolvers/DefaultContainersNodeTypeResolver.cs new file mode 100644 index 0000000..11d87c0 --- /dev/null +++ b/YamlDotNet/Serialization/NodeTypeResolvers/DefaultContainersNodeTypeResolver.cs @@ -0,0 +1,49 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Collections.Generic; +using YamlDotNet.Core.Events; + +namespace YamlDotNet.Serialization.NodeTypeResolvers +{ + public sealed class DefaultContainersNodeTypeResolver : INodeTypeResolver + { + bool INodeTypeResolver.Resolve(NodeEvent nodeEvent, ref Type currentType) + { + if (currentType == typeof(object)) + { + if (nodeEvent is SequenceStart) + { + currentType = typeof(List); + return true; + } + if (nodeEvent is MappingStart) + { + currentType = typeof(Dictionary); + return true; + } + } + + return false; + } + } +} diff --git a/YamlDotNet/Serialization/NodeTypeResolvers/DefaultContainersNodeTypeResolver.cs.meta b/YamlDotNet/Serialization/NodeTypeResolvers/DefaultContainersNodeTypeResolver.cs.meta new file mode 100644 index 0000000..d29887c --- /dev/null +++ b/YamlDotNet/Serialization/NodeTypeResolvers/DefaultContainersNodeTypeResolver.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: a96ce7ab22cdeb245a28967001844e3f +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/NodeTypeResolvers/TagNodeTypeResolver.cs b/YamlDotNet/Serialization/NodeTypeResolvers/TagNodeTypeResolver.cs new file mode 100644 index 0000000..ecab8d2 --- /dev/null +++ b/YamlDotNet/Serialization/NodeTypeResolvers/TagNodeTypeResolver.cs @@ -0,0 +1,53 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Collections.Generic; +using YamlDotNet.Core.Events; + +namespace YamlDotNet.Serialization.NodeTypeResolvers +{ + public sealed class TagNodeTypeResolver : INodeTypeResolver + { + private readonly IDictionary tagMappings; + + public TagNodeTypeResolver(IDictionary tagMappings) + { + if (tagMappings == null) + { + throw new ArgumentNullException("tagMappings"); + } + + this.tagMappings = tagMappings; + } + + bool INodeTypeResolver.Resolve(NodeEvent nodeEvent, ref Type currentType) + { + Type predefinedType; + if (!string.IsNullOrEmpty(nodeEvent.Tag) && tagMappings.TryGetValue(nodeEvent.Tag, out predefinedType)) + { + currentType = predefinedType; + return true; + } + return false; + } + } +} diff --git a/YamlDotNet/Serialization/NodeTypeResolvers/TagNodeTypeResolver.cs.meta b/YamlDotNet/Serialization/NodeTypeResolvers/TagNodeTypeResolver.cs.meta new file mode 100644 index 0000000..f277a5e --- /dev/null +++ b/YamlDotNet/Serialization/NodeTypeResolvers/TagNodeTypeResolver.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 699369e47bae32e4b87e9bcb955ee742 +timeCreated: 1427145264 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/NodeTypeResolvers/TypeNameInTagNodeTypeResolver.cs b/YamlDotNet/Serialization/NodeTypeResolvers/TypeNameInTagNodeTypeResolver.cs new file mode 100644 index 0000000..68527b9 --- /dev/null +++ b/YamlDotNet/Serialization/NodeTypeResolvers/TypeNameInTagNodeTypeResolver.cs @@ -0,0 +1,41 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using YamlDotNet.Core.Events; + +namespace YamlDotNet.Serialization.NodeTypeResolvers +{ + public sealed class TypeNameInTagNodeTypeResolver : INodeTypeResolver + { + bool INodeTypeResolver.Resolve(NodeEvent nodeEvent, ref Type currentType) + { + if (!string.IsNullOrEmpty(nodeEvent.Tag)) + { + // If type could not be loaded, make sure to pass resolving + // to the next resolver + currentType = Type.GetType(nodeEvent.Tag.Substring(1), throwOnError: false); + return currentType != null; + } + return false; + } + } +} diff --git a/YamlDotNet/Serialization/NodeTypeResolvers/TypeNameInTagNodeTypeResolver.cs.meta b/YamlDotNet/Serialization/NodeTypeResolvers/TypeNameInTagNodeTypeResolver.cs.meta new file mode 100644 index 0000000..d24905e --- /dev/null +++ b/YamlDotNet/Serialization/NodeTypeResolvers/TypeNameInTagNodeTypeResolver.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: abbd2aba7e216f54a8353afcce646479 +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/NodeTypeResolvers/YamlConvertibleTypeResolver.cs b/YamlDotNet/Serialization/NodeTypeResolvers/YamlConvertibleTypeResolver.cs new file mode 100644 index 0000000..87bdb5a --- /dev/null +++ b/YamlDotNet/Serialization/NodeTypeResolvers/YamlConvertibleTypeResolver.cs @@ -0,0 +1,34 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using YamlDotNet.Core.Events; + +namespace YamlDotNet.Serialization.NodeTypeResolvers +{ + public sealed class YamlConvertibleTypeResolver : INodeTypeResolver + { + public bool Resolve(NodeEvent nodeEvent, ref Type currentType) + { + return typeof(IYamlConvertible).IsAssignableFrom(currentType); + } + } +} diff --git a/YamlDotNet/Serialization/NodeTypeResolvers/YamlConvertibleTypeResolver.cs.meta b/YamlDotNet/Serialization/NodeTypeResolvers/YamlConvertibleTypeResolver.cs.meta new file mode 100644 index 0000000..d53ae6d --- /dev/null +++ b/YamlDotNet/Serialization/NodeTypeResolvers/YamlConvertibleTypeResolver.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: e5460e40e01a3dd49a5ad78b1e3ece14 +timeCreated: 1485601085 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/NodeTypeResolvers/YamlSerializableTypeResolver.cs b/YamlDotNet/Serialization/NodeTypeResolvers/YamlSerializableTypeResolver.cs new file mode 100644 index 0000000..4aa3f61 --- /dev/null +++ b/YamlDotNet/Serialization/NodeTypeResolvers/YamlSerializableTypeResolver.cs @@ -0,0 +1,36 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using YamlDotNet.Core.Events; + +namespace YamlDotNet.Serialization.NodeTypeResolvers +{ + public sealed class YamlSerializableTypeResolver : INodeTypeResolver + { + public bool Resolve(NodeEvent nodeEvent, ref Type currentType) + { +#pragma warning disable 0618 // IYamlSerializable is obsolete + return typeof(IYamlSerializable).IsAssignableFrom(currentType); +#pragma warning restore 0618 + } + } +} diff --git a/YamlDotNet/Serialization/NodeTypeResolvers/YamlSerializableTypeResolver.cs.meta b/YamlDotNet/Serialization/NodeTypeResolvers/YamlSerializableTypeResolver.cs.meta new file mode 100644 index 0000000..33e64f2 --- /dev/null +++ b/YamlDotNet/Serialization/NodeTypeResolvers/YamlSerializableTypeResolver.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 69c24ee7afe12c1479e4bfd7e8595b7f +timeCreated: 1485601084 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/Nothing.cs b/YamlDotNet/Serialization/Nothing.cs new file mode 100644 index 0000000..6eb9744 --- /dev/null +++ b/YamlDotNet/Serialization/Nothing.cs @@ -0,0 +1,32 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + + +namespace YamlDotNet.Serialization +{ + /// + /// An empty type for cases where a type needs to be provided but won't be used. + /// + public sealed class Nothing + { + private Nothing() { } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/Nothing.cs.meta b/YamlDotNet/Serialization/Nothing.cs.meta new file mode 100644 index 0000000..23a4198 --- /dev/null +++ b/YamlDotNet/Serialization/Nothing.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 8463bea3e5ea0764c8fde8598dcfe794 +timeCreated: 1485601084 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/ObjectDescriptor.cs b/YamlDotNet/Serialization/ObjectDescriptor.cs new file mode 100644 index 0000000..f0a4e5b --- /dev/null +++ b/YamlDotNet/Serialization/ObjectDescriptor.cs @@ -0,0 +1,60 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization +{ + public sealed class ObjectDescriptor : IObjectDescriptor + { + public object Value { get; private set; } + public Type Type { get; private set; } + public Type StaticType { get; private set; } + public ScalarStyle ScalarStyle { get; private set; } + + public ObjectDescriptor(object value, Type type, Type staticType) + : this(value, type, staticType, ScalarStyle.Any) + { + } + + public ObjectDescriptor(object value, Type type, Type staticType, ScalarStyle scalarStyle) + { + Value = value; + + if (type == null) + { + throw new ArgumentNullException("type"); + } + + Type = type; + + if (staticType == null) + { + throw new ArgumentNullException("staticType"); + } + + StaticType = staticType; + + ScalarStyle = scalarStyle; + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/ObjectDescriptor.cs.meta b/YamlDotNet/Serialization/ObjectDescriptor.cs.meta new file mode 100644 index 0000000..5f29254 --- /dev/null +++ b/YamlDotNet/Serialization/ObjectDescriptor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 13c3a8b94ac1de641806bb1733305bda +timeCreated: 1427145262 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/ObjectFactories.meta b/YamlDotNet/Serialization/ObjectFactories.meta new file mode 100644 index 0000000..345d7d4 --- /dev/null +++ b/YamlDotNet/Serialization/ObjectFactories.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 755993ac40163ac47a826c22a1797745 +folderAsset: yes +timeCreated: 1427145262 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/ObjectFactories/DefaultObjectFactory.cs b/YamlDotNet/Serialization/ObjectFactories/DefaultObjectFactory.cs new file mode 100644 index 0000000..4ae7459 --- /dev/null +++ b/YamlDotNet/Serialization/ObjectFactories/DefaultObjectFactory.cs @@ -0,0 +1,62 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; + +namespace YamlDotNet.Serialization.ObjectFactories +{ + /// + /// Creates objects using Activator.CreateInstance. + /// + public sealed class DefaultObjectFactory : IObjectFactory + { + private static readonly Dictionary defaultInterfaceImplementations = new Dictionary + { + { typeof(IEnumerable<>), typeof(List<>) }, + { typeof(ICollection<>), typeof(List<>) }, + { typeof(IList<>), typeof(List<>) }, + { typeof(IDictionary<,>), typeof(Dictionary<,>) } + }; + + public object Create(Type type) + { + if (type.IsInterface()) + { + Type implementationType; + if (defaultInterfaceImplementations.TryGetValue(type.GetGenericTypeDefinition(), out implementationType)) + { + type = implementationType.MakeGenericType(type.GetGenericArguments()); + } + } + + try + { + return Activator.CreateInstance(type); + } + catch (Exception err) + { + var message = string.Format("Failed to create an instance of type '{0}'.", type); + throw new InvalidOperationException(message, err); + } + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/ObjectFactories/DefaultObjectFactory.cs.meta b/YamlDotNet/Serialization/ObjectFactories/DefaultObjectFactory.cs.meta new file mode 100644 index 0000000..b5ba6cd --- /dev/null +++ b/YamlDotNet/Serialization/ObjectFactories/DefaultObjectFactory.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d85c04bcbb9823e428994436b556c0c4 +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/ObjectFactories/LambdaObjectFactory.cs b/YamlDotNet/Serialization/ObjectFactories/LambdaObjectFactory.cs new file mode 100644 index 0000000..14f94a1 --- /dev/null +++ b/YamlDotNet/Serialization/ObjectFactories/LambdaObjectFactory.cs @@ -0,0 +1,48 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace YamlDotNet.Serialization.ObjectFactories +{ + /// + /// Creates objects using a Func{Type,object}"/>. + /// + public sealed class LambdaObjectFactory : IObjectFactory + { + private readonly Func _factory; + + public LambdaObjectFactory(Func factory) + { + if (factory == null) + { + throw new ArgumentNullException("factory"); + } + + _factory = factory; + } + + public object Create(Type type) + { + return _factory(type); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/ObjectFactories/LambdaObjectFactory.cs.meta b/YamlDotNet/Serialization/ObjectFactories/LambdaObjectFactory.cs.meta new file mode 100644 index 0000000..92e0dfe --- /dev/null +++ b/YamlDotNet/Serialization/ObjectFactories/LambdaObjectFactory.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2ad19c2ee12f0cd41a32cf7dfe446c07 +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/ObjectGraphTraversalStrategies.meta b/YamlDotNet/Serialization/ObjectGraphTraversalStrategies.meta new file mode 100644 index 0000000..2c5a723 --- /dev/null +++ b/YamlDotNet/Serialization/ObjectGraphTraversalStrategies.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: a42ffc21fa040324dbd9991681d9654c +folderAsset: yes +timeCreated: 1427145262 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/ObjectGraphTraversalStrategies/FullObjectGraphTraversalStrategy.cs b/YamlDotNet/Serialization/ObjectGraphTraversalStrategies/FullObjectGraphTraversalStrategy.cs new file mode 100644 index 0000000..2bf0e05 --- /dev/null +++ b/YamlDotNet/Serialization/ObjectGraphTraversalStrategies/FullObjectGraphTraversalStrategy.cs @@ -0,0 +1,219 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using YamlDotNet.Helpers; +using YamlDotNet.Serialization.Utilities; + +namespace YamlDotNet.Serialization.ObjectGraphTraversalStrategies +{ + /// + /// An implementation of that traverses + /// readable properties, collections and dictionaries. + /// + public class FullObjectGraphTraversalStrategy : IObjectGraphTraversalStrategy + { + private readonly int maxRecursion; + private readonly ITypeInspector typeDescriptor; + private readonly ITypeResolver typeResolver; + private INamingConvention namingConvention; + + public FullObjectGraphTraversalStrategy(ITypeInspector typeDescriptor, ITypeResolver typeResolver, int maxRecursion, INamingConvention namingConvention) + { + if (maxRecursion <= 0) + { + throw new ArgumentOutOfRangeException("maxRecursion", maxRecursion, "maxRecursion must be greater than 1"); + } + + if (typeDescriptor == null) + { + throw new ArgumentNullException("typeDescriptor"); + } + + this.typeDescriptor = typeDescriptor; + + if (typeResolver == null) + { + throw new ArgumentNullException("typeResolver"); + } + + this.typeResolver = typeResolver; + + this.maxRecursion = maxRecursion; + this.namingConvention = namingConvention; + } + + void IObjectGraphTraversalStrategy.Traverse(IObjectDescriptor graph, IObjectGraphVisitor visitor, TContext context) + { + Traverse(graph, visitor, 0, context); + } + + protected virtual void Traverse(IObjectDescriptor value, IObjectGraphVisitor visitor, int currentDepth, TContext context) + { + if (++currentDepth > maxRecursion) + { + throw new InvalidOperationException("Too much recursion when traversing the object graph"); + } + + if (!visitor.Enter(value, context)) + { + return; + } + + var typeCode = value.Type.GetTypeCode(); + switch (typeCode) + { + case TypeCode.Boolean: + case TypeCode.Byte: + case TypeCode.Int16: + case TypeCode.Int32: + case TypeCode.Int64: + case TypeCode.SByte: + case TypeCode.UInt16: + case TypeCode.UInt32: + case TypeCode.UInt64: + case TypeCode.Single: + case TypeCode.Double: + case TypeCode.Decimal: + case TypeCode.String: + case TypeCode.Char: + case TypeCode.DateTime: + visitor.VisitScalar(value, context); + break; + + case TypeCode.DBNull: + visitor.VisitScalar(new ObjectDescriptor(null, typeof(object), typeof(object)), context); + break; + + case TypeCode.Empty: + throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "TypeCode.{0} is not supported.", typeCode)); + + default: + if (value.Value == null || value.Type == typeof(TimeSpan)) + { + visitor.VisitScalar(value, context); + break; + } + + var underlyingType = Nullable.GetUnderlyingType(value.Type); + if (underlyingType != null) + { + // This is a nullable type, recursively handle it with its underlying type. + // Note that if it contains null, the condition above already took care of it + Traverse(new ObjectDescriptor(value.Value, underlyingType, value.Type, value.ScalarStyle), visitor, currentDepth, context); + } + else + { + TraverseObject(value, visitor, currentDepth, context); + } + break; + } + } + + protected virtual void TraverseObject(IObjectDescriptor value, IObjectGraphVisitor visitor, int currentDepth, TContext context) + { + if (typeof(IDictionary).IsAssignableFrom(value.Type)) + { + TraverseDictionary(value, visitor, currentDepth, typeof(object), typeof(object), context); + return; + } + + var genericDictionaryType = ReflectionUtility.GetImplementedGenericInterface(value.Type, typeof(IDictionary<,>)); + if (genericDictionaryType != null) + { + var adaptedDictionary = new GenericDictionaryToNonGenericAdapter(value.Value, genericDictionaryType); + var genericArguments = genericDictionaryType.GetGenericArguments(); + TraverseDictionary(new ObjectDescriptor(adaptedDictionary, value.Type, value.StaticType, value.ScalarStyle), visitor, currentDepth, genericArguments[0], genericArguments[1], context); + return; + } + + if (typeof(IEnumerable).IsAssignableFrom(value.Type)) + { + TraverseList(value, visitor, currentDepth, context); + return; + } + + TraverseProperties(value, visitor, currentDepth, context); + } + + protected virtual void TraverseDictionary(IObjectDescriptor dictionary, IObjectGraphVisitor visitor, int currentDepth, Type keyType, Type valueType, TContext context) + { + visitor.VisitMappingStart(dictionary, keyType, valueType, context); + + var isDynamic = dictionary.Type.FullName.Equals("System.Dynamic.ExpandoObject"); + foreach (DictionaryEntry entry in (IDictionary)dictionary.Value) + { + var keyString = isDynamic ? namingConvention.Apply(entry.Key.ToString()) : entry.Key.ToString(); + var key = GetObjectDescriptor(keyString, keyType); + var value = GetObjectDescriptor(entry.Value, valueType); + + if (visitor.EnterMapping(key, value, context)) + { + Traverse(key, visitor, currentDepth, context); + Traverse(value, visitor, currentDepth, context); + } + } + + visitor.VisitMappingEnd(dictionary, context); + } + + private void TraverseList(IObjectDescriptor value, IObjectGraphVisitor visitor, int currentDepth, TContext context) + { + var enumerableType = ReflectionUtility.GetImplementedGenericInterface(value.Type, typeof(IEnumerable<>)); + var itemType = enumerableType != null ? enumerableType.GetGenericArguments()[0] : typeof(object); + + visitor.VisitSequenceStart(value, itemType, context); + + foreach (var item in (IEnumerable)value.Value) + { + Traverse(GetObjectDescriptor(item, itemType), visitor, currentDepth, context); + } + + visitor.VisitSequenceEnd(value, context); + } + + protected virtual void TraverseProperties(IObjectDescriptor value, IObjectGraphVisitor visitor, int currentDepth, TContext context) + { + visitor.VisitMappingStart(value, typeof(string), typeof(object), context); + + foreach (var propertyDescriptor in typeDescriptor.GetProperties(value.Type, value.Value)) + { + var propertyValue = propertyDescriptor.Read(value.Value); + + if (visitor.EnterMapping(propertyDescriptor, propertyValue, context)) + { + Traverse(new ObjectDescriptor(propertyDescriptor.Name, typeof(string), typeof(string)), visitor, currentDepth, context); + Traverse(propertyValue, visitor, currentDepth, context); + } + } + + visitor.VisitMappingEnd(value, context); + } + + private IObjectDescriptor GetObjectDescriptor(object value, Type staticType) + { + return new ObjectDescriptor(value, typeResolver.Resolve(staticType, value), staticType); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/ObjectGraphTraversalStrategies/FullObjectGraphTraversalStrategy.cs.meta b/YamlDotNet/Serialization/ObjectGraphTraversalStrategies/FullObjectGraphTraversalStrategy.cs.meta new file mode 100644 index 0000000..c48ec63 --- /dev/null +++ b/YamlDotNet/Serialization/ObjectGraphTraversalStrategies/FullObjectGraphTraversalStrategy.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 4d75872db0e63bf4e829d39ab3d05abd +timeCreated: 1427145264 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/ObjectGraphTraversalStrategies/RoundtripObjectGraphTraversalStrategy.cs b/YamlDotNet/Serialization/ObjectGraphTraversalStrategies/RoundtripObjectGraphTraversalStrategy.cs new file mode 100644 index 0000000..33a7f59 --- /dev/null +++ b/YamlDotNet/Serialization/ObjectGraphTraversalStrategies/RoundtripObjectGraphTraversalStrategy.cs @@ -0,0 +1,54 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; + +namespace YamlDotNet.Serialization.ObjectGraphTraversalStrategies +{ + /// + /// An implementation of that traverses + /// properties that are read/write, collections and dictionaries, while ensuring that + /// the graph can be regenerated from the resulting document. + /// + public class RoundtripObjectGraphTraversalStrategy : FullObjectGraphTraversalStrategy + { + private readonly IEnumerable converters; + + public RoundtripObjectGraphTraversalStrategy(IEnumerable converters, ITypeInspector typeDescriptor, ITypeResolver typeResolver, int maxRecursion) + : base(typeDescriptor, typeResolver, maxRecursion, null) + { + this.converters = converters; + } + + protected override void TraverseProperties(IObjectDescriptor value, IObjectGraphVisitor visitor, int currentDepth, TContext context) + { + if (!value.Type.HasDefaultConstructor() && !converters.Any(c => c.Accepts(value.Type))) + { + throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Type '{0}' cannot be deserialized because it does not have a default constructor or a type converter.", value.Type)); + } + + base.TraverseProperties(value, visitor, currentDepth, context); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/ObjectGraphTraversalStrategies/RoundtripObjectGraphTraversalStrategy.cs.meta b/YamlDotNet/Serialization/ObjectGraphTraversalStrategies/RoundtripObjectGraphTraversalStrategy.cs.meta new file mode 100644 index 0000000..763c65c --- /dev/null +++ b/YamlDotNet/Serialization/ObjectGraphTraversalStrategies/RoundtripObjectGraphTraversalStrategy.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: cc11b2a2ab4f92a4683501db76ecc278 +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/ObjectGraphVisitors.meta b/YamlDotNet/Serialization/ObjectGraphVisitors.meta new file mode 100644 index 0000000..cae5c80 --- /dev/null +++ b/YamlDotNet/Serialization/ObjectGraphVisitors.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 8c3c32412b4e3944c9d8e8f30f4f3001 +folderAsset: yes +timeCreated: 1427145262 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/ObjectGraphVisitors/AnchorAssigner.cs b/YamlDotNet/Serialization/ObjectGraphVisitors/AnchorAssigner.cs new file mode 100644 index 0000000..2ea2c66 --- /dev/null +++ b/YamlDotNet/Serialization/ObjectGraphVisitors/AnchorAssigner.cs @@ -0,0 +1,106 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Globalization; + +namespace YamlDotNet.Serialization.ObjectGraphVisitors +{ + public sealed class AnchorAssigner : PreProcessingPhaseObjectGraphVisitorSkeleton, IAliasProvider + { + private class AnchorAssignment + { + public string Anchor; + } + + private readonly IDictionary assignments = new Dictionary(); + private uint nextId; + + public AnchorAssigner(IEnumerable typeConverters) + : base(typeConverters) + { + } + + protected override bool Enter(IObjectDescriptor value) + { + AnchorAssignment assignment; + if (value.Value != null && assignments.TryGetValue(value.Value, out assignment)) + { + if (assignment.Anchor == null) + { + assignment.Anchor = "o" + nextId.ToString(CultureInfo.InvariantCulture); + ++nextId; + } + return false; + } + + return true; + } + + protected override bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value) + { + return true; + } + + protected override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value) + { + return true; + } + + protected override void VisitScalar(IObjectDescriptor scalar) + { + // Do not assign anchors to scalars + } + + protected override void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType) + { + VisitObject(mapping); + } + + protected override void VisitMappingEnd(IObjectDescriptor mapping) { } + + protected override void VisitSequenceStart(IObjectDescriptor sequence, Type elementType) + { + VisitObject(sequence); + } + + protected override void VisitSequenceEnd(IObjectDescriptor sequence) { } + + private void VisitObject(IObjectDescriptor value) + { + if(value.Value != null) + { + assignments.Add(value.Value, new AnchorAssignment()); + } + } + + string IAliasProvider.GetAlias(object target) + { + AnchorAssignment assignment; + if (target != null && assignments.TryGetValue(target, out assignment)) + { + return assignment.Anchor; + } + return null; + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/ObjectGraphVisitors/AnchorAssigner.cs.meta b/YamlDotNet/Serialization/ObjectGraphVisitors/AnchorAssigner.cs.meta new file mode 100644 index 0000000..adff831 --- /dev/null +++ b/YamlDotNet/Serialization/ObjectGraphVisitors/AnchorAssigner.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: c7a4420c17a267847b8d6973ad99346a +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/ObjectGraphVisitors/AnchorAssigningObjectGraphVisitor.cs b/YamlDotNet/Serialization/ObjectGraphVisitors/AnchorAssigningObjectGraphVisitor.cs new file mode 100644 index 0000000..0b272af --- /dev/null +++ b/YamlDotNet/Serialization/ObjectGraphVisitors/AnchorAssigningObjectGraphVisitor.cs @@ -0,0 +1,68 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization.ObjectGraphVisitors +{ + public sealed class AnchorAssigningObjectGraphVisitor : ChainedObjectGraphVisitor + { + private readonly IEventEmitter eventEmitter; + private readonly IAliasProvider aliasProvider; + private readonly HashSet emittedAliases = new HashSet(); + + public AnchorAssigningObjectGraphVisitor(IObjectGraphVisitor nextVisitor, IEventEmitter eventEmitter, IAliasProvider aliasProvider) + : base(nextVisitor) + { + this.eventEmitter = eventEmitter; + this.aliasProvider = aliasProvider; + } + + public override bool Enter(IObjectDescriptor value, IEmitter context) + { + var alias = aliasProvider.GetAlias(value.Value); + if (alias != null && !emittedAliases.Add(alias)) + { + eventEmitter.Emit(new AliasEventInfo(value) { Alias = alias }, context); + return false; + } + + return base.Enter(value, context); + } + + public override void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, IEmitter context) + { + eventEmitter.Emit(new MappingStartEventInfo(mapping) { Anchor = aliasProvider.GetAlias(mapping.Value) }, context); + } + + public override void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, IEmitter context) + { + eventEmitter.Emit(new SequenceStartEventInfo(sequence) { Anchor = aliasProvider.GetAlias(sequence.Value) }, context); + } + + public override void VisitScalar(IObjectDescriptor scalar, IEmitter context) + { + eventEmitter.Emit(new ScalarEventInfo(scalar) { Anchor = aliasProvider.GetAlias(scalar.Value) }, context); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/ObjectGraphVisitors/AnchorAssigningObjectGraphVisitor.cs.meta b/YamlDotNet/Serialization/ObjectGraphVisitors/AnchorAssigningObjectGraphVisitor.cs.meta new file mode 100644 index 0000000..091b66f --- /dev/null +++ b/YamlDotNet/Serialization/ObjectGraphVisitors/AnchorAssigningObjectGraphVisitor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 7c8b5b39c74f14248971b3c1a4ec83b2 +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/ObjectGraphVisitors/ChainedObjectGraphVisitor.cs b/YamlDotNet/Serialization/ObjectGraphVisitors/ChainedObjectGraphVisitor.cs new file mode 100644 index 0000000..4b35c3a --- /dev/null +++ b/YamlDotNet/Serialization/ObjectGraphVisitors/ChainedObjectGraphVisitor.cs @@ -0,0 +1,76 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization.ObjectGraphVisitors +{ + public abstract class ChainedObjectGraphVisitor : IObjectGraphVisitor + { + private readonly IObjectGraphVisitor nextVisitor; + + protected ChainedObjectGraphVisitor(IObjectGraphVisitor nextVisitor) + { + this.nextVisitor = nextVisitor; + } + + public virtual bool Enter(IObjectDescriptor value, IEmitter context) + { + return nextVisitor.Enter(value, context); + } + + public virtual bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, IEmitter context) + { + return nextVisitor.EnterMapping(key, value, context); + } + + public virtual bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context) + { + return nextVisitor.EnterMapping(key, value, context); + } + + public virtual void VisitScalar(IObjectDescriptor scalar, IEmitter context) + { + nextVisitor.VisitScalar(scalar, context); + } + + public virtual void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, IEmitter context) + { + nextVisitor.VisitMappingStart(mapping, keyType, valueType, context); + } + + public virtual void VisitMappingEnd(IObjectDescriptor mapping, IEmitter context) + { + nextVisitor.VisitMappingEnd(mapping, context); + } + + public virtual void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, IEmitter context) + { + nextVisitor.VisitSequenceStart(sequence, elementType, context); + } + + public virtual void VisitSequenceEnd(IObjectDescriptor sequence, IEmitter context) + { + nextVisitor.VisitSequenceEnd(sequence, context); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/ObjectGraphVisitors/ChainedObjectGraphVisitor.cs.meta b/YamlDotNet/Serialization/ObjectGraphVisitors/ChainedObjectGraphVisitor.cs.meta new file mode 100644 index 0000000..671c810 --- /dev/null +++ b/YamlDotNet/Serialization/ObjectGraphVisitors/ChainedObjectGraphVisitor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 91c55744c252b51459a0c70f40c47827 +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/ObjectGraphVisitors/CustomSerializationObjectGraphVisitor.cs b/YamlDotNet/Serialization/ObjectGraphVisitors/CustomSerializationObjectGraphVisitor.cs new file mode 100644 index 0000000..7e4283f --- /dev/null +++ b/YamlDotNet/Serialization/ObjectGraphVisitors/CustomSerializationObjectGraphVisitor.cs @@ -0,0 +1,71 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System.Collections.Generic; +using System.Linq; +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization.ObjectGraphVisitors +{ + public sealed class CustomSerializationObjectGraphVisitor : ChainedObjectGraphVisitor + { + private readonly IEnumerable typeConverters; + private readonly ObjectSerializer nestedObjectSerializer; + + public CustomSerializationObjectGraphVisitor(IObjectGraphVisitor nextVisitor, IEnumerable typeConverters, ObjectSerializer nestedObjectSerializer) + : base(nextVisitor) + { + this.typeConverters = typeConverters != null + ? typeConverters.ToList() + : Enumerable.Empty(); + + this.nestedObjectSerializer = nestedObjectSerializer; + } + + public override bool Enter(IObjectDescriptor value, IEmitter context) + { + var typeConverter = typeConverters.FirstOrDefault(t => t.Accepts(value.Type)); + if (typeConverter != null) + { + typeConverter.WriteYaml(context, value.Value, value.Type); + return false; + } + + var convertible = value.Value as IYamlConvertible; + if (convertible != null) + { + convertible.Write(context, nestedObjectSerializer); + return false; + } + +#pragma warning disable 0618 // IYamlSerializable is obsolete + var serializable = value.Value as IYamlSerializable; + if (serializable != null) + { + serializable.WriteYaml(context); + return false; + } +#pragma warning restore + + return base.Enter(value, context); + } + } +} diff --git a/YamlDotNet/Serialization/ObjectGraphVisitors/CustomSerializationObjectGraphVisitor.cs.meta b/YamlDotNet/Serialization/ObjectGraphVisitors/CustomSerializationObjectGraphVisitor.cs.meta new file mode 100644 index 0000000..313e704 --- /dev/null +++ b/YamlDotNet/Serialization/ObjectGraphVisitors/CustomSerializationObjectGraphVisitor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 180ba37056bdea24393986bdab81340d +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/ObjectGraphVisitors/DefaultExclusiveObjectGraphVisitor.cs b/YamlDotNet/Serialization/ObjectGraphVisitors/DefaultExclusiveObjectGraphVisitor.cs new file mode 100644 index 0000000..aa839c1 --- /dev/null +++ b/YamlDotNet/Serialization/ObjectGraphVisitors/DefaultExclusiveObjectGraphVisitor.cs @@ -0,0 +1,60 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization.ObjectGraphVisitors +{ + public sealed class DefaultExclusiveObjectGraphVisitor : ChainedObjectGraphVisitor + { + public DefaultExclusiveObjectGraphVisitor(IObjectGraphVisitor nextVisitor) + : base(nextVisitor) + { + } + + private static object GetDefault(Type type) + { + return type.IsValueType() ? Activator.CreateInstance(type) : null; + } + + private static readonly IEqualityComparer _objectComparer = EqualityComparer.Default; + + public override bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, IEmitter context) + { + return !_objectComparer.Equals(value, GetDefault(value.Type)) + && base.EnterMapping(key, value, context); + } + + public override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context) + { + var defaultValueAttribute = key.GetCustomAttribute(); + var defaultValue = defaultValueAttribute != null + ? defaultValueAttribute.Value + : GetDefault(key.Type); + + return !_objectComparer.Equals(value.Value, defaultValue) + && base.EnterMapping(key, value, context); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/ObjectGraphVisitors/DefaultExclusiveObjectGraphVisitor.cs.meta b/YamlDotNet/Serialization/ObjectGraphVisitors/DefaultExclusiveObjectGraphVisitor.cs.meta new file mode 100644 index 0000000..668c442 --- /dev/null +++ b/YamlDotNet/Serialization/ObjectGraphVisitors/DefaultExclusiveObjectGraphVisitor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6f0bed3472e6485468490ba7cf5c910e +timeCreated: 1427145264 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/ObjectGraphVisitors/EmittingObjectGraphVisitor.cs b/YamlDotNet/Serialization/ObjectGraphVisitors/EmittingObjectGraphVisitor.cs new file mode 100644 index 0000000..6331922 --- /dev/null +++ b/YamlDotNet/Serialization/ObjectGraphVisitors/EmittingObjectGraphVisitor.cs @@ -0,0 +1,76 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization.ObjectGraphVisitors +{ + public sealed class EmittingObjectGraphVisitor : IObjectGraphVisitor + { + private readonly IEventEmitter eventEmitter; + + public EmittingObjectGraphVisitor(IEventEmitter eventEmitter) + { + this.eventEmitter = eventEmitter; + } + + bool IObjectGraphVisitor.Enter(IObjectDescriptor value, IEmitter context) + { + return true; + } + + bool IObjectGraphVisitor.EnterMapping(IObjectDescriptor key, IObjectDescriptor value, IEmitter context) + { + return true; + } + + bool IObjectGraphVisitor.EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context) + { + return true; + } + + void IObjectGraphVisitor.VisitScalar(IObjectDescriptor scalar, IEmitter context) + { + eventEmitter.Emit(new ScalarEventInfo(scalar), context); + } + + void IObjectGraphVisitor.VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, IEmitter context) + { + eventEmitter.Emit(new MappingStartEventInfo(mapping), context); + } + + void IObjectGraphVisitor.VisitMappingEnd(IObjectDescriptor mapping, IEmitter context) + { + eventEmitter.Emit(new MappingEndEventInfo(mapping), context); + } + + void IObjectGraphVisitor.VisitSequenceStart(IObjectDescriptor sequence, Type elementType, IEmitter context) + { + eventEmitter.Emit(new SequenceStartEventInfo(sequence), context); + } + + void IObjectGraphVisitor.VisitSequenceEnd(IObjectDescriptor sequence, IEmitter context) + { + eventEmitter.Emit(new SequenceEndEventInfo(sequence), context); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/ObjectGraphVisitors/EmittingObjectGraphVisitor.cs.meta b/YamlDotNet/Serialization/ObjectGraphVisitors/EmittingObjectGraphVisitor.cs.meta new file mode 100644 index 0000000..574a8fe --- /dev/null +++ b/YamlDotNet/Serialization/ObjectGraphVisitors/EmittingObjectGraphVisitor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 23b01227eabbc3c4eb0e2658ac27b23d +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/ObjectGraphVisitors/PreProcessingPhaseObjectGraphVisitorSkeleton.cs b/YamlDotNet/Serialization/ObjectGraphVisitors/PreProcessingPhaseObjectGraphVisitorSkeleton.cs new file mode 100644 index 0000000..e43d526 --- /dev/null +++ b/YamlDotNet/Serialization/ObjectGraphVisitors/PreProcessingPhaseObjectGraphVisitorSkeleton.cs @@ -0,0 +1,111 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace YamlDotNet.Serialization.ObjectGraphVisitors +{ + /// + /// A base class that simplifies the correct implementation of . + /// + public abstract class PreProcessingPhaseObjectGraphVisitorSkeleton : IObjectGraphVisitor + { + protected readonly IEnumerable typeConverters; + + public PreProcessingPhaseObjectGraphVisitorSkeleton(IEnumerable typeConverters) + { + this.typeConverters = typeConverters != null + ? typeConverters.ToList() + : Enumerable.Empty(); + } + + bool IObjectGraphVisitor.Enter(IObjectDescriptor value, Nothing context) + { + var typeConverter = typeConverters.FirstOrDefault(t => t.Accepts(value.Type)); + if (typeConverter != null) + { + return false; + } + + var convertible = value.Value as IYamlConvertible; + if (convertible != null) + { + return false; + } + +#pragma warning disable 0618 // IYamlSerializable is obsolete + var serializable = value.Value as IYamlSerializable; + if (serializable != null) + { + return false; + } +#pragma warning restore + + return Enter(value); + } + + bool IObjectGraphVisitor.EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, Nothing context) + { + return EnterMapping(key, value); + } + + bool IObjectGraphVisitor.EnterMapping(IObjectDescriptor key, IObjectDescriptor value, Nothing context) + { + return EnterMapping(key, value); + } + + void IObjectGraphVisitor.VisitMappingEnd(IObjectDescriptor mapping, Nothing context) + { + VisitMappingEnd(mapping); + } + + void IObjectGraphVisitor.VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, Nothing context) + { + VisitMappingStart(mapping, keyType, valueType); + } + + void IObjectGraphVisitor.VisitScalar(IObjectDescriptor scalar, Nothing context) + { + VisitScalar(scalar); + } + + void IObjectGraphVisitor.VisitSequenceEnd(IObjectDescriptor sequence, Nothing context) + { + VisitSequenceEnd(sequence); + } + + void IObjectGraphVisitor.VisitSequenceStart(IObjectDescriptor sequence, Type elementType, Nothing context) + { + VisitSequenceStart(sequence, elementType); + } + + protected abstract bool Enter(IObjectDescriptor value); + protected abstract bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value); + protected abstract bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value); + protected abstract void VisitMappingEnd(IObjectDescriptor mapping); + protected abstract void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType); + protected abstract void VisitScalar(IObjectDescriptor scalar); + protected abstract void VisitSequenceEnd(IObjectDescriptor sequence); + protected abstract void VisitSequenceStart(IObjectDescriptor sequence, Type elementType); + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/ObjectGraphVisitors/PreProcessingPhaseObjectGraphVisitorSkeleton.cs.meta b/YamlDotNet/Serialization/ObjectGraphVisitors/PreProcessingPhaseObjectGraphVisitorSkeleton.cs.meta new file mode 100644 index 0000000..a89c955 --- /dev/null +++ b/YamlDotNet/Serialization/ObjectGraphVisitors/PreProcessingPhaseObjectGraphVisitorSkeleton.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f25be0bb475b7bc41b17713e640b1a93 +timeCreated: 1485601086 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/PropertyDescriptor.cs b/YamlDotNet/Serialization/PropertyDescriptor.cs new file mode 100644 index 0000000..47d45ee --- /dev/null +++ b/YamlDotNet/Serialization/PropertyDescriptor.cs @@ -0,0 +1,75 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization +{ + public sealed class PropertyDescriptor : IPropertyDescriptor + { + private readonly IPropertyDescriptor baseDescriptor; + + public PropertyDescriptor(IPropertyDescriptor baseDescriptor) + { + this.baseDescriptor = baseDescriptor; + Name = baseDescriptor.Name; + } + + public string Name { get; set; } + + public Type Type { get { return baseDescriptor.Type; } } + + public Type TypeOverride + { + get { return baseDescriptor.TypeOverride; } + set { baseDescriptor.TypeOverride = value; } + } + + public int Order { get; set; } + + public ScalarStyle ScalarStyle + { + get { return baseDescriptor.ScalarStyle; } + set { baseDescriptor.ScalarStyle = value; } + } + + public bool CanWrite + { + get { return baseDescriptor.CanWrite; } + } + + public void Write(object target, object value) + { + baseDescriptor.Write(target, value); + } + + public T GetCustomAttribute() where T : Attribute + { + return baseDescriptor.GetCustomAttribute(); + } + + public IObjectDescriptor Read(object target) + { + return baseDescriptor.Read(target); + } + } +} diff --git a/YamlDotNet/Serialization/PropertyDescriptor.cs.meta b/YamlDotNet/Serialization/PropertyDescriptor.cs.meta new file mode 100644 index 0000000..ebe592c --- /dev/null +++ b/YamlDotNet/Serialization/PropertyDescriptor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f8bf6f944f8b97c42924be110365cef7 +timeCreated: 1427145267 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/SerializationOptions.cs b/YamlDotNet/Serialization/SerializationOptions.cs new file mode 100644 index 0000000..1f99ab4 --- /dev/null +++ b/YamlDotNet/Serialization/SerializationOptions.cs @@ -0,0 +1,69 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace YamlDotNet.Serialization +{ + /// + /// Options that control the serialization process. + /// + [Flags] + public enum SerializationOptions + { + /// + /// Serializes using the default options + /// + None = 0, + + /// + /// Ensures that it will be possible to deserialize the serialized objects. + /// + Roundtrip = 1, + + /// + /// If this flag is specified, if the same object appears more than once in the + /// serialization graph, it will be serialized each time instead of just once. + /// + /// + /// If the serialization graph contains circular references and this flag is set, + /// a StackOverflowException will be thrown. + /// If this flag is not set, there is a performance penalty because the entire + /// object graph must be walked twice. + /// + DisableAliases = 2, + + /// + /// Forces every value to be serialized, even if it is the default value for that type. + /// + EmitDefaults = 4, + + /// + /// Ensures that the result of the serialization is valid JSON. + /// + JsonCompatible = 8, + + /// + /// Use the static type of values instead of their actual type. + /// + DefaultToStaticType = 16, + } +} diff --git a/YamlDotNet/Serialization/SerializationOptions.cs.meta b/YamlDotNet/Serialization/SerializationOptions.cs.meta new file mode 100644 index 0000000..4ff9d82 --- /dev/null +++ b/YamlDotNet/Serialization/SerializationOptions.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 0b7070fc0d7ceed47b84b18eb05b66cf +timeCreated: 1427145262 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/Serializer.cs b/YamlDotNet/Serialization/Serializer.cs new file mode 100644 index 0000000..c79622d --- /dev/null +++ b/YamlDotNet/Serialization/Serializer.cs @@ -0,0 +1,304 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.IO; +using YamlDotNet.Core; +using YamlDotNet.Core.Events; +using YamlDotNet.Serialization.Converters; +using YamlDotNet.Serialization.EventEmitters; +using YamlDotNet.Serialization.NamingConventions; +using YamlDotNet.Serialization.ObjectGraphTraversalStrategies; +using YamlDotNet.Serialization.ObjectGraphVisitors; +using YamlDotNet.Serialization.TypeInspectors; +using YamlDotNet.Serialization.TypeResolvers; + +namespace YamlDotNet.Serialization +{ + public sealed class Serializer + { + private readonly IValueSerializer valueSerializer; + + #region Backwards compatibility + private class BackwardsCompatibleConfiguration : IValueSerializer + { + public IList Converters { get; private set; } + private readonly SerializationOptions options; + private readonly INamingConvention namingConvention; + private readonly ITypeResolver typeResolver; + private readonly YamlAttributeOverrides overrides; + + public BackwardsCompatibleConfiguration(SerializationOptions options, INamingConvention namingConvention, YamlAttributeOverrides overrides) + { + this.options = options; + this.namingConvention = namingConvention ?? new NullNamingConvention(); + this.overrides = overrides; + + Converters = new List(); + Converters.Add(new GuidConverter(IsOptionSet(SerializationOptions.JsonCompatible))); + + typeResolver = IsOptionSet(SerializationOptions.DefaultToStaticType) + ? (ITypeResolver)new StaticTypeResolver() + : (ITypeResolver)new DynamicTypeResolver(); + } + + public bool IsOptionSet(SerializationOptions option) + { + return (options & option) != 0; + } + + private IObjectGraphVisitor CreateEmittingVisitor(IEmitter emitter, IObjectGraphTraversalStrategy traversalStrategy, IEventEmitter eventEmitter, IObjectDescriptor graph) + { + IObjectGraphVisitor emittingVisitor = new EmittingObjectGraphVisitor(eventEmitter); + + ObjectSerializer nestedObjectSerializer = (v, t) => SerializeValue(emitter, v, t); + + emittingVisitor = new CustomSerializationObjectGraphVisitor(emittingVisitor, Converters, nestedObjectSerializer); + + if (!IsOptionSet(SerializationOptions.DisableAliases)) + { + var anchorAssigner = new AnchorAssigner(Converters); + traversalStrategy.Traverse(graph, anchorAssigner, null); + + emittingVisitor = new AnchorAssigningObjectGraphVisitor(emittingVisitor, eventEmitter, anchorAssigner); + } + + if (!IsOptionSet(SerializationOptions.EmitDefaults)) + { + emittingVisitor = new DefaultExclusiveObjectGraphVisitor(emittingVisitor); + } + + return emittingVisitor; + } + + private IEventEmitter CreateEventEmitter() + { + var writer = new WriterEventEmitter(); + + if (IsOptionSet(SerializationOptions.JsonCompatible)) + { + return new JsonEventEmitter(writer); + } + else + { + return new TypeAssigningEventEmitter(writer, IsOptionSet(SerializationOptions.Roundtrip)); + } + } + + private IObjectGraphTraversalStrategy CreateTraversalStrategy() + { + ITypeInspector typeDescriptor = new ReadablePropertiesTypeInspector(typeResolver); + if (IsOptionSet(SerializationOptions.Roundtrip)) + { + typeDescriptor = new ReadableAndWritablePropertiesTypeInspector(typeDescriptor); + } + + typeDescriptor = new YamlAttributeOverridesInspector(typeDescriptor, overrides); + typeDescriptor = new YamlAttributesTypeInspector(typeDescriptor); + typeDescriptor = new NamingConventionTypeInspector(typeDescriptor, namingConvention); + + if (IsOptionSet(SerializationOptions.DefaultToStaticType)) + { + typeDescriptor = new CachedTypeInspector(typeDescriptor); + } + + if (IsOptionSet(SerializationOptions.Roundtrip)) + { + return new RoundtripObjectGraphTraversalStrategy(Converters, typeDescriptor, typeResolver, 50); + } + else + { + return new FullObjectGraphTraversalStrategy(typeDescriptor, typeResolver, 50, namingConvention); + } + } + + public void SerializeValue(IEmitter emitter, object value, Type type) + { + var graph = type != null + ? new ObjectDescriptor(value, type, type) + : new ObjectDescriptor(value, value != null ? value.GetType() : typeof(object), typeof(object)); + + var traversalStrategy = CreateTraversalStrategy(); + var emittingVisitor = CreateEmittingVisitor( + emitter, + traversalStrategy, + CreateEventEmitter(), + graph + ); + + traversalStrategy.Traverse(graph, emittingVisitor, emitter); + } + } + + private readonly BackwardsCompatibleConfiguration backwardsCompatibleConfiguration; + + private void ThrowUnlessInBackwardsCompatibleMode() + { + if (backwardsCompatibleConfiguration == null) + { + throw new InvalidOperationException("This method / property exists for backwards compatibility reasons, but the Serializer was created using the new configuration mechanism. To configure the Serializer, use the SerializerBuilder."); + } + } + + /// + /// + /// + /// Options that control how the serialization is to be performed. + /// Naming strategy to use for serialized property names + /// Yaml attribute overrides + [Obsolete("Please use SerializerBuilder to customize the Serializer. This constructor will be removed in future releases.")] + public Serializer(SerializationOptions options = SerializationOptions.None, INamingConvention namingConvention = null, YamlAttributeOverrides overrides = null) + { + backwardsCompatibleConfiguration = new BackwardsCompatibleConfiguration(options, namingConvention, overrides); + } + + /// + /// Registers a type converter to be used to serialize and deserialize specific types. + /// + [Obsolete("Please use SerializerBuilder to customize the Serializer. This method will be removed in future releases.")] + public void RegisterTypeConverter(IYamlTypeConverter converter) + { + ThrowUnlessInBackwardsCompatibleMode(); + backwardsCompatibleConfiguration.Converters.Insert(0, converter); + } + #endregion + + /// + /// Initializes a new instance of using the default configuration. + /// + /// + /// To customize the bahavior of the serializer, use . + /// + public Serializer() + // TODO: When the backwards compatibility is dropped, uncomment the following line and remove the body of this constructor. + //: this(new SerializerBuilder().BuildSerializerParams()) + { + backwardsCompatibleConfiguration = new BackwardsCompatibleConfiguration(SerializationOptions.None, null, null); + } + + /// + /// This constructor is private to discourage its use. + /// To invoke it, call the method. + /// + private Serializer(IValueSerializer valueSerializer) + { + if (valueSerializer == null) + { + throw new ArgumentNullException("valueSerializer"); + } + + this.valueSerializer = valueSerializer; + } + + /// + /// Creates a new that uses the specified . + /// This method is available for advanced scenarios. The preferred way to customize the bahavior of the + /// deserializer is to use . + /// + public static Serializer FromValueSerializer(IValueSerializer valueSerializer) + { + return new Serializer(valueSerializer); + } + + /// + /// Serializes the specified object. + /// + /// The where to serialize the object. + /// The object to serialize. + public void Serialize(TextWriter writer, object graph) + { + Serialize(new Emitter(writer), graph); + } + + /// + /// Serializes the specified object into a string. + /// + /// The object to serialize. + public string Serialize(object graph) + { + using (var buffer = new StringWriter()) + { + Serialize(buffer, graph); + return buffer.ToString(); + } + } + + /// + /// Serializes the specified object. + /// + /// The where to serialize the object. + /// The object to serialize. + /// The static type of the object to serialize. + public void Serialize(TextWriter writer, object graph, Type type) + { + Serialize(new Emitter(writer), graph, type); + } + + /// + /// Serializes the specified object. + /// + /// The where to serialize the object. + /// The object to serialize. + public void Serialize(IEmitter emitter, object graph) + { + if (emitter == null) + { + throw new ArgumentNullException("emitter"); + } + + EmitDocument(emitter, graph, null); + } + + /// + /// Serializes the specified object. + /// + /// The where to serialize the object. + /// The object to serialize. + /// The static type of the object to serialize. + public void Serialize(IEmitter emitter, object graph, Type type) + { + if (emitter == null) + { + throw new ArgumentNullException("emitter"); + } + + if (type == null) + { + throw new ArgumentNullException("type"); + } + + EmitDocument(emitter, graph, type); + } + + private void EmitDocument(IEmitter emitter, object graph, Type type) + { + emitter.Emit(new StreamStart()); + emitter.Emit(new DocumentStart()); + + IValueSerializer actualValueSerializer = backwardsCompatibleConfiguration ?? valueSerializer; + actualValueSerializer.SerializeValue(emitter, graph, type); + + emitter.Emit(new DocumentEnd(true)); + emitter.Emit(new StreamEnd()); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/Serializer.cs.meta b/YamlDotNet/Serialization/Serializer.cs.meta new file mode 100644 index 0000000..109e4ee --- /dev/null +++ b/YamlDotNet/Serialization/Serializer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 9c67f330b01d4f341af5108e0e1c3af7 +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/SerializerBuilder.cs b/YamlDotNet/Serialization/SerializerBuilder.cs new file mode 100644 index 0000000..a705b5b --- /dev/null +++ b/YamlDotNet/Serialization/SerializerBuilder.cs @@ -0,0 +1,520 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using YamlDotNet.Core; +using YamlDotNet.Serialization.Converters; +using YamlDotNet.Serialization.EventEmitters; +using YamlDotNet.Serialization.NamingConventions; +using YamlDotNet.Serialization.ObjectGraphTraversalStrategies; +using YamlDotNet.Serialization.ObjectGraphVisitors; +using YamlDotNet.Serialization.TypeInspectors; +using YamlDotNet.Serialization.TypeResolvers; + +namespace YamlDotNet.Serialization +{ + /// + /// Creates and configures instances of . + /// This class is used to customize the behavior of . Use the relevant methods + /// to apply customizations, then call to create an instance of the serializer + /// with the desired customizations. + /// + public sealed class SerializerBuilder : BuilderSkeleton + { + private Func, IObjectGraphTraversalStrategy> objectGraphTraversalStrategyFactory; + private readonly LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories; + private readonly LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories; + private readonly LazyComponentRegistrationList eventEmitterFactories; + private readonly IDictionary tagMappings = new Dictionary(); + + public SerializerBuilder() + { + typeInspectorFactories.Add(typeof(CachedTypeInspector), inner => new CachedTypeInspector(inner)); + typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), inner => namingConvention != null ? new NamingConventionTypeInspector(inner, namingConvention) : inner); + typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), inner => new YamlAttributesTypeInspector(inner)); + typeInspectorFactories.Add(typeof(YamlAttributeOverridesInspector), inner => overrides != null ? new YamlAttributeOverridesInspector(inner, overrides.Clone()) : inner); + + preProcessingPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList, IObjectGraphVisitor>(); + preProcessingPhaseObjectGraphVisitorFactories.Add(typeof(AnchorAssigner), typeConverters => new AnchorAssigner(typeConverters)); + + emissionPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList>(); + emissionPhaseObjectGraphVisitorFactories.Add(typeof(CustomSerializationObjectGraphVisitor), + args => new CustomSerializationObjectGraphVisitor(args.InnerVisitor, args.TypeConverters, args.NestedObjectSerializer)); + + emissionPhaseObjectGraphVisitorFactories.Add(typeof(AnchorAssigningObjectGraphVisitor), + args => new AnchorAssigningObjectGraphVisitor(args.InnerVisitor, args.EventEmitter, args.GetPreProcessingPhaseObjectGraphVisitor())); + + emissionPhaseObjectGraphVisitorFactories.Add(typeof(DefaultExclusiveObjectGraphVisitor), + args => new DefaultExclusiveObjectGraphVisitor(args.InnerVisitor)); + + eventEmitterFactories = new LazyComponentRegistrationList(); + eventEmitterFactories.Add(typeof(TypeAssigningEventEmitter), inner => new TypeAssigningEventEmitter(inner, false)); + + objectGraphTraversalStrategyFactory = (typeInspector, typeResolver, typeConverters) => new FullObjectGraphTraversalStrategy(typeInspector, typeResolver, 50, namingConvention ?? new NullNamingConvention()); + + WithTypeResolver(new DynamicTypeResolver()); + WithEventEmitter(inner => new CustomTagEventEmitter(inner, tagMappings)); + } + + protected override SerializerBuilder Self { get { return this; } } + + /// + /// Registers an additional to be used by the serializer. + /// + /// A function that instantiates the event emitter. + public SerializerBuilder WithEventEmitter(Func eventEmitterFactory) + where TEventEmitter : IEventEmitter + { + return WithEventEmitter(eventEmitterFactory, w => w.OnTop()); + } + + /// + /// Registers an additional to be used by the serializer. + /// + /// A function that instantiates the event emitter. + /// Configures the location where to insert the + public SerializerBuilder WithEventEmitter( + Func eventEmitterFactory, + Action> where + ) + where TEventEmitter : IEventEmitter + { + if (eventEmitterFactory == null) + { + throw new ArgumentNullException("eventEmitterFactory"); + } + + if (where == null) + { + throw new ArgumentNullException("where"); + } + + where(eventEmitterFactories.CreateRegistrationLocationSelector(typeof(TEventEmitter), inner => eventEmitterFactory(inner))); + return Self; + } + + /// + /// Registers an additional to be used by the serializer. + /// + /// A function that instantiates the event emitter based on a previously registered . + /// Configures the location where to insert the + public SerializerBuilder WithEventEmitter( + WrapperFactory eventEmitterFactory, + Action> where + ) + where TEventEmitter : IEventEmitter + { + if (eventEmitterFactory == null) + { + throw new ArgumentNullException("eventEmitterFactory"); + } + + if (where == null) + { + throw new ArgumentNullException("where"); + } + + where(eventEmitterFactories.CreateTrackingRegistrationLocationSelector(typeof(TEventEmitter), (wrapped, inner) => eventEmitterFactory(wrapped, inner))); + return Self; + } + + /// + /// Unregisters an existing of type . + /// + public SerializerBuilder WithoutEventEmitter() + where TEventEmitter : IEventEmitter + { + return WithoutEventEmitter(typeof(TEventEmitter)); + } + + /// + /// Unregisters an existing of type . + /// + public SerializerBuilder WithoutEventEmitter(Type eventEmitterType) + { + if (eventEmitterType == null) + { + throw new ArgumentNullException("eventEmitterType"); + } + + eventEmitterFactories.Remove(eventEmitterType); + return this; + } + + /// + /// Registers a tag mapping. + /// + public SerializerBuilder WithTagMapping(string tag, Type type) + { + if (tag == null) + { + throw new ArgumentNullException("tag"); + } + + if (type == null) + { + throw new ArgumentNullException("type"); + } + + string alreadyRegisteredTag; + if (tagMappings.TryGetValue(type, out alreadyRegisteredTag)) + { + throw new ArgumentException(string.Format("Type already has a registered tag '{0}' for type '{1}'", alreadyRegisteredTag, type.FullName), "type"); + } + + tagMappings.Add(type, tag); + return this; + } + + /// + /// Unregisters an existing tag mapping. + /// + public SerializerBuilder WithoutTagMapping(Type type) + { + if (type == null) + { + throw new ArgumentNullException("type"); + } + + if (!tagMappings.Remove(type)) + { + throw new KeyNotFoundException(string.Format("Tag for type '{0}' is not registered", type.FullName)); + } + return this; + } + + /// + /// Ensures that it will be possible to deserialize the serialized objects. + /// This option will force the emission of tags and emit only properties with setters. + /// + public SerializerBuilder EnsureRoundtrip() + { + objectGraphTraversalStrategyFactory = (typeInspector, typeResolver, typeConverters) => new RoundtripObjectGraphTraversalStrategy( + typeConverters, + typeInspector, + typeResolver, + 50 + ); + WithEventEmitter(inner => new TypeAssigningEventEmitter(inner, true), loc => loc.InsteadOf()); + return WithTypeInspector(inner => new ReadableAndWritablePropertiesTypeInspector(inner), loc => loc.OnBottom()); + } + + /// + /// Specifies that, if the same object appears more than once in the + /// serialization graph, it will be serialized each time instead of just once. + /// + /// + /// If the serialization graph contains circular references and this flag is set, + /// a StackOverflowException will be thrown. + /// If this flag is not set, there is a performance penalty because the entire + /// object graph must be walked twice. + /// + public SerializerBuilder DisableAliases() + { + preProcessingPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigner)); + emissionPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigningObjectGraphVisitor)); + return this; + } + + /// + /// Forces every value to be serialized, even if it is the default value for that type. + /// + public SerializerBuilder EmitDefaults() + { + emissionPhaseObjectGraphVisitorFactories.Remove(typeof(DefaultExclusiveObjectGraphVisitor)); + return this; + } + + /// + /// Ensures that the result of the serialization is valid JSON. + /// + public SerializerBuilder JsonCompatible() + { + return this + .WithTypeConverter(new GuidConverter(true), w => w.InsteadOf()) + .WithEventEmitter(inner => new JsonEventEmitter(inner), loc => loc.InsteadOf()); + } + + /// + /// Registers an additional to be used by the serializer + /// before emitting an object graph. + /// + /// + /// Registering a visitor in the pre-processing phase enables to traverse the object graph once + /// before actually emitting it. This allows a visitor to collect information about the graph that + /// can be used later by another visitor registered in the emission phase. + /// + /// The type inspector. + public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor(TObjectGraphVisitor objectGraphVisitor) + where TObjectGraphVisitor : IObjectGraphVisitor + { + return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitor, w => w.OnTop()); + } + + /// + /// Registers an additional to be used by the serializer + /// before emitting an object graph. + /// + /// + /// Registering a visitor in the pre-processing phase enables to traverse the object graph once + /// before actually emitting it. This allows a visitor to collect information about the graph that + /// can be used later by another visitor registered in the emission phase. + /// + /// The type inspector. + /// Configures the location where to insert the + public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor( + TObjectGraphVisitor objectGraphVisitor, + Action>> where + ) + where TObjectGraphVisitor : IObjectGraphVisitor + { + if (objectGraphVisitor == null) + { + throw new ArgumentNullException("objectGraphVisitor"); + } + + if (where == null) + { + throw new ArgumentNullException("where"); + } + + where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), _ => objectGraphVisitor)); + return this; + } + + /// + /// Registers an additional to be used by the serializer + /// before emitting an object graph. + /// + /// + /// Registering a visitor in the pre-processing phase enables to traverse the object graph once + /// before actually emitting it. This allows a visitor to collect information about the graph that + /// can be used later by another visitor registered in the emission phase. + /// + /// A factory that creates the based on a previously registered . + /// Configures the location where to insert the + public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor( + WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory, + Action>> where + ) + where TObjectGraphVisitor : IObjectGraphVisitor + { + if (objectGraphVisitorFactory == null) + { + throw new ArgumentNullException("objectGraphVisitorFactory"); + } + + if (where == null) + { + throw new ArgumentNullException("where"); + } + + where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (wrapped, _) => objectGraphVisitorFactory(wrapped))); + return this; + } + + /// + /// Unregisters an existing of type . + /// + public SerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor() + where TObjectGraphVisitor : IObjectGraphVisitor + { + return WithoutPreProcessingPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); + } + + /// + /// Unregisters an existing of type . + /// + public SerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor(Type objectGraphVisitorType) + { + if (objectGraphVisitorType == null) + { + throw new ArgumentNullException("objectGraphVisitorType"); + } + + preProcessingPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType); + return this; + } + + /// + /// Registers an additional to be used by the serializer + /// while emitting an object graph. + /// + /// A function that instantiates the type inspector. + public SerializerBuilder WithEmissionPhaseObjectGraphVisitor(Func objectGraphVisitorFactory) + where TObjectGraphVisitor : IObjectGraphVisitor + { + return WithEmissionPhaseObjectGraphVisitor(objectGraphVisitorFactory, w => w.OnTop()); + } + + /// + /// Registers an additional to be used by the serializer + /// while emitting an object graph. + /// + /// A function that instantiates the type inspector. + /// Configures the location where to insert the + public SerializerBuilder WithEmissionPhaseObjectGraphVisitor( + Func objectGraphVisitorFactory, + Action>> where + ) + where TObjectGraphVisitor : IObjectGraphVisitor + { + if (objectGraphVisitorFactory == null) + { + throw new ArgumentNullException("objectGraphVisitorFactory"); + } + + if (where == null) + { + throw new ArgumentNullException("where"); + } + + where(emissionPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), args => objectGraphVisitorFactory(args))); + return this; + } + + /// + /// Registers an additional to be used by the serializer + /// while emitting an object graph. + /// + /// A function that instantiates the type inspector based on a previously registered . + /// Configures the location where to insert the + public SerializerBuilder WithEmissionPhaseObjectGraphVisitor( + WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory, + Action>> where + ) + where TObjectGraphVisitor : IObjectGraphVisitor + { + if (objectGraphVisitorFactory == null) + { + throw new ArgumentNullException("objectGraphVisitorFactory"); + } + + if (where == null) + { + throw new ArgumentNullException("where"); + } + + where(emissionPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (wrapped, args) => objectGraphVisitorFactory(wrapped, args))); + return this; + } + + /// + /// Unregisters an existing of type . + /// + public SerializerBuilder WithoutEmissionPhaseObjectGraphVisitor() + where TObjectGraphVisitor : IObjectGraphVisitor + { + return WithoutEmissionPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); + } + + /// + /// Unregisters an existing of type . + /// + public SerializerBuilder WithoutEmissionPhaseObjectGraphVisitor(Type objectGraphVisitorType) + { + if (objectGraphVisitorType == null) + { + throw new ArgumentNullException("objectGraphVisitorType"); + } + + emissionPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType); + return this; + } + + /// + /// Creates a new according to the current configuration. + /// + public Serializer Build() + { + return Serializer.FromValueSerializer(BuildValueSerializer()); + } + + /// + /// Creates a new that implements the current configuration. + /// This method is available for advanced scenarios. The preferred way to customize the bahavior of the + /// deserializer is to use the method. + /// + public IValueSerializer BuildValueSerializer() + { + var typeConverters = BuildTypeConverters(); + var typeInspector = BuildTypeInspector(); + var traversalStrategy = objectGraphTraversalStrategyFactory(typeInspector, typeResolver, typeConverters); + var eventEmitter = eventEmitterFactories.BuildComponentChain(new WriterEventEmitter()); + + return new ValueSerializer( + traversalStrategy, + eventEmitter, + typeConverters, + preProcessingPhaseObjectGraphVisitorFactories.Clone(), + emissionPhaseObjectGraphVisitorFactories.Clone() + ); + } + + private class ValueSerializer : IValueSerializer + { + private readonly IObjectGraphTraversalStrategy traversalStrategy; + private readonly IEventEmitter eventEmitter; + private readonly IEnumerable typeConverters; + private readonly LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories; + private readonly LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories; + + public ValueSerializer( + IObjectGraphTraversalStrategy traversalStrategy, + IEventEmitter eventEmitter, + IEnumerable typeConverters, + LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories, + LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories + ) + { + this.traversalStrategy = traversalStrategy; + this.eventEmitter = eventEmitter; + this.typeConverters = typeConverters; + this.preProcessingPhaseObjectGraphVisitorFactories = preProcessingPhaseObjectGraphVisitorFactories; + this.emissionPhaseObjectGraphVisitorFactories = emissionPhaseObjectGraphVisitorFactories; + } + + public void SerializeValue(IEmitter emitter, object value, Type type) + { + var actualType = type != null ? type : value != null ? value.GetType() : typeof(object); + var staticType = type ?? typeof(object); + + var graph = new ObjectDescriptor(value, actualType, staticType); + + var preProcessingPhaseObjectGraphVisitors = preProcessingPhaseObjectGraphVisitorFactories.BuildComponentList(typeConverters); + foreach (var visitor in preProcessingPhaseObjectGraphVisitors) + { + traversalStrategy.Traverse(graph, visitor, null); + } + + ObjectSerializer nestedObjectSerializer = (v, t) => SerializeValue(emitter, v, t); + + var emittingVisitor = emissionPhaseObjectGraphVisitorFactories.BuildComponentChain( + new EmittingObjectGraphVisitor(eventEmitter), + inner => new EmissionPhaseObjectGraphVisitorArgs(inner, eventEmitter, preProcessingPhaseObjectGraphVisitors, typeConverters, nestedObjectSerializer) + ); + + traversalStrategy.Traverse(graph, emittingVisitor, emitter); + } + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/SerializerBuilder.cs.meta b/YamlDotNet/Serialization/SerializerBuilder.cs.meta new file mode 100644 index 0000000..60dd6d8 --- /dev/null +++ b/YamlDotNet/Serialization/SerializerBuilder.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 5b467b3e0a9a9784c9a6eb58c50eceea +timeCreated: 1485601083 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/StreamFragment.cs b/YamlDotNet/Serialization/StreamFragment.cs new file mode 100644 index 0000000..4f97c38 --- /dev/null +++ b/YamlDotNet/Serialization/StreamFragment.cs @@ -0,0 +1,84 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using YamlDotNet.Core; +using YamlDotNet.Core.Events; + +namespace YamlDotNet.Serialization +{ + /// + /// An object that contains part of a YAML stream. + /// + public sealed class StreamFragment : IYamlConvertible + { + private readonly List events = new List(); + + /// + /// Gets or sets the events. + /// + /// The events. + public IList Events + { + get + { + return events; + } + } + + #region IYamlConvertible Members + /// + /// Reads this object's state from a YAML parser. + /// + void IYamlConvertible.Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) + { + events.Clear(); + + int depth = 0; + do + { + if (!parser.MoveNext()) + { + throw new InvalidOperationException("The parser has reached the end before deserialization completed."); + } + + events.Add(parser.Current); + depth += parser.Current.NestingIncrease; + } while (depth > 0); + + Debug.Assert(depth == 0); + } + + /// + /// Writes this object's state to a YAML emitter. + /// + void IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) + { + foreach (var item in events) + { + emitter.Emit(item); + } + } + #endregion + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/StreamFragment.cs.meta b/YamlDotNet/Serialization/StreamFragment.cs.meta new file mode 100644 index 0000000..1f8dea7 --- /dev/null +++ b/YamlDotNet/Serialization/StreamFragment.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: ccef6dc01b4e9ac45998c14da7d14c3e +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/TagMappings.cs b/YamlDotNet/Serialization/TagMappings.cs new file mode 100644 index 0000000..2063234 --- /dev/null +++ b/YamlDotNet/Serialization/TagMappings.cs @@ -0,0 +1,79 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; + +namespace YamlDotNet.Serialization +{ + /// + /// Contains mappings between tags and types. + /// + public sealed class TagMappings + { + private readonly IDictionary mappings; + + /// + /// Initializes a new instance of the class. + /// + public TagMappings() + { + mappings = new Dictionary(); + } + + /// + /// Initializes a new instance of the class. + /// + /// The mappings. + public TagMappings(IDictionary mappings) + { + this.mappings = new Dictionary(mappings); + } + + /// + /// Adds the specified tag. + /// + /// The tag. + /// The mapping. + public void Add(string tag, Type mapping) + { + mappings.Add(tag, mapping); + } + + /// + /// Gets the mapping. + /// + /// The tag. + /// + internal Type GetMapping(string tag) + { + Type mapping; + if (mappings.TryGetValue(tag, out mapping)) + { + return mapping; + } + else + { + return null; + } + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/TagMappings.cs.meta b/YamlDotNet/Serialization/TagMappings.cs.meta new file mode 100644 index 0000000..e336b87 --- /dev/null +++ b/YamlDotNet/Serialization/TagMappings.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2cc976dab2b9f8a43b435abbe2687e5a +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/TypeInspectors.meta b/YamlDotNet/Serialization/TypeInspectors.meta new file mode 100644 index 0000000..3f8cf8f --- /dev/null +++ b/YamlDotNet/Serialization/TypeInspectors.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 05e3dfde0726c3f45ae1c40309796c14 +folderAsset: yes +timeCreated: 1427145262 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/TypeInspectors/CachedTypeInspector.cs b/YamlDotNet/Serialization/TypeInspectors/CachedTypeInspector.cs new file mode 100644 index 0000000..2aa44a9 --- /dev/null +++ b/YamlDotNet/Serialization/TypeInspectors/CachedTypeInspector.cs @@ -0,0 +1,56 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace YamlDotNet.Serialization.TypeInspectors +{ + /// + /// Wraps another and applies caching. + /// + public sealed class CachedTypeInspector : TypeInspectorSkeleton + { + private readonly ITypeInspector innerTypeDescriptor; + private readonly Dictionary> cache = new Dictionary>(); + + public CachedTypeInspector(ITypeInspector innerTypeDescriptor) + { + if (innerTypeDescriptor == null) + { + throw new ArgumentNullException("innerTypeDescriptor"); + } + + this.innerTypeDescriptor = innerTypeDescriptor; + } + + public override IEnumerable GetProperties(Type type, object container) + { + List list; + if (!cache.TryGetValue(type, out list)) + { + list = new List(innerTypeDescriptor.GetProperties(type, container)); + } + return list; + } + } +} diff --git a/YamlDotNet/Serialization/TypeInspectors/CachedTypeInspector.cs.meta b/YamlDotNet/Serialization/TypeInspectors/CachedTypeInspector.cs.meta new file mode 100644 index 0000000..d8957c5 --- /dev/null +++ b/YamlDotNet/Serialization/TypeInspectors/CachedTypeInspector.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2831decc4a6e7dd49b872c7ae62d2568 +timeCreated: 1453984095 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/TypeInspectors/NamingConventionTypeInspector.cs b/YamlDotNet/Serialization/TypeInspectors/NamingConventionTypeInspector.cs new file mode 100644 index 0000000..5976452 --- /dev/null +++ b/YamlDotNet/Serialization/TypeInspectors/NamingConventionTypeInspector.cs @@ -0,0 +1,68 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace YamlDotNet.Serialization.TypeInspectors +{ + /// + /// Wraps another and applies a + /// naming convention to the names of the properties. + /// + public sealed class NamingConventionTypeInspector : TypeInspectorSkeleton + { + private readonly ITypeInspector innerTypeDescriptor; + private readonly INamingConvention namingConvention; + + public NamingConventionTypeInspector(ITypeInspector innerTypeDescriptor, INamingConvention namingConvention) + { + if (innerTypeDescriptor == null) + { + throw new ArgumentNullException("innerTypeDescriptor"); + } + + this.innerTypeDescriptor = innerTypeDescriptor; + + if (namingConvention == null) + { + throw new ArgumentNullException("namingConvention"); + } + + this.namingConvention = namingConvention; + } + + public override IEnumerable GetProperties(Type type, object container) + { + return innerTypeDescriptor.GetProperties(type, container) + .Select(p => + { + var attribute = p.GetCustomAttribute(); + if (attribute != null && !attribute.ApplyNamingConventions) + { + return p; + } + return (IPropertyDescriptor)new PropertyDescriptor(p) { Name = namingConvention.Apply(p.Name) }; + }); + } + } +} diff --git a/YamlDotNet/Serialization/TypeInspectors/NamingConventionTypeInspector.cs.meta b/YamlDotNet/Serialization/TypeInspectors/NamingConventionTypeInspector.cs.meta new file mode 100644 index 0000000..82d04c9 --- /dev/null +++ b/YamlDotNet/Serialization/TypeInspectors/NamingConventionTypeInspector.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 3598909e9935cc3428cc982eb6802c40 +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/TypeInspectors/ReadableAndWritablePropertiesTypeInspector.cs b/YamlDotNet/Serialization/TypeInspectors/ReadableAndWritablePropertiesTypeInspector.cs new file mode 100644 index 0000000..13ae019 --- /dev/null +++ b/YamlDotNet/Serialization/TypeInspectors/ReadableAndWritablePropertiesTypeInspector.cs @@ -0,0 +1,46 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace YamlDotNet.Serialization.TypeInspectors +{ + /// + /// Returns the properties of a type that are both readable and writable. + /// + public sealed class ReadableAndWritablePropertiesTypeInspector : TypeInspectorSkeleton + { + private readonly ITypeInspector _innerTypeDescriptor; + + public ReadableAndWritablePropertiesTypeInspector(ITypeInspector innerTypeDescriptor) + { + _innerTypeDescriptor = innerTypeDescriptor; + } + + public override IEnumerable GetProperties(Type type, object container) + { + return _innerTypeDescriptor.GetProperties(type, container) + .Where(p => p.CanWrite); + } + } +} diff --git a/YamlDotNet/Serialization/TypeInspectors/ReadableAndWritablePropertiesTypeInspector.cs.meta b/YamlDotNet/Serialization/TypeInspectors/ReadableAndWritablePropertiesTypeInspector.cs.meta new file mode 100644 index 0000000..b2342a0 --- /dev/null +++ b/YamlDotNet/Serialization/TypeInspectors/ReadableAndWritablePropertiesTypeInspector.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b92a938ba5e921c4e92072dc91a2ab2b +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/TypeInspectors/ReadablePropertiesTypeInspector.cs b/YamlDotNet/Serialization/TypeInspectors/ReadablePropertiesTypeInspector.cs new file mode 100644 index 0000000..98cf292 --- /dev/null +++ b/YamlDotNet/Serialization/TypeInspectors/ReadablePropertiesTypeInspector.cs @@ -0,0 +1,99 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization.TypeInspectors +{ + /// + /// Returns the properties of a type that are readable. + /// + public sealed class ReadablePropertiesTypeInspector : TypeInspectorSkeleton + { + private readonly ITypeResolver _typeResolver; + + public ReadablePropertiesTypeInspector(ITypeResolver typeResolver) + { + if (typeResolver == null) + { + throw new ArgumentNullException("typeResolver"); + } + + _typeResolver = typeResolver; + } + + private static bool IsValidProperty(PropertyInfo property) + { + return property.CanRead + && property.GetGetMethod().GetParameters().Length == 0; + } + + public override IEnumerable GetProperties(Type type, object container) + { + return type + .GetPublicProperties() + .Where(IsValidProperty) + .Select(p => (IPropertyDescriptor)new ReflectionPropertyDescriptor(p, _typeResolver)); + } + + private sealed class ReflectionPropertyDescriptor : IPropertyDescriptor + { + private readonly PropertyInfo _propertyInfo; + private readonly ITypeResolver _typeResolver; + + public ReflectionPropertyDescriptor(PropertyInfo propertyInfo, ITypeResolver typeResolver) + { + _propertyInfo = propertyInfo; + _typeResolver = typeResolver; + ScalarStyle = ScalarStyle.Any; + } + + public string Name { get { return _propertyInfo.Name; } } + public Type Type { get { return _propertyInfo.PropertyType; } } + public Type TypeOverride { get; set; } + public int Order { get; set; } + public bool CanWrite { get { return _propertyInfo.CanWrite; } } + public ScalarStyle ScalarStyle { get; set; } + + public void Write(object target, object value) + { + _propertyInfo.SetValue(target, value, null); + } + + public T GetCustomAttribute() where T : Attribute + { + var attributes = _propertyInfo.GetCustomAttributes(typeof(T), true); + return (T)attributes.FirstOrDefault(); + } + + public IObjectDescriptor Read(object target) + { + var propertyValue = _propertyInfo.ReadValue(target); + var actualType = TypeOverride ?? _typeResolver.Resolve(Type, propertyValue); + return new ObjectDescriptor(propertyValue, actualType, Type, ScalarStyle); + } + } + } +} diff --git a/YamlDotNet/Serialization/TypeInspectors/ReadablePropertiesTypeInspector.cs.meta b/YamlDotNet/Serialization/TypeInspectors/ReadablePropertiesTypeInspector.cs.meta new file mode 100644 index 0000000..973695a --- /dev/null +++ b/YamlDotNet/Serialization/TypeInspectors/ReadablePropertiesTypeInspector.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: c9669f90a0f2f2a41b805a174d9be97e +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/TypeInspectors/TypeInspectorSkeleton.cs b/YamlDotNet/Serialization/TypeInspectors/TypeInspectorSkeleton.cs new file mode 100644 index 0000000..0e8c84b --- /dev/null +++ b/YamlDotNet/Serialization/TypeInspectors/TypeInspectorSkeleton.cs @@ -0,0 +1,77 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; + +namespace YamlDotNet.Serialization.TypeInspectors +{ + public abstract class TypeInspectorSkeleton : ITypeInspector + { + public abstract IEnumerable GetProperties(Type type, object container); + + public IPropertyDescriptor GetProperty(Type type, object container, string name, bool ignoreUnmatched) + { + var candidates = GetProperties(type, container) + .Where(p => p.Name == name); + + using (var enumerator = candidates.GetEnumerator()) + { + if (!enumerator.MoveNext()) + { + if (ignoreUnmatched) + { + return null; + } + + throw new SerializationException( + string.Format( + CultureInfo.InvariantCulture, + "Property '{0}' not found on type '{1}'.", + name, + type.FullName + ) + ); + } + + var property = enumerator.Current; + + if (enumerator.MoveNext()) + { + throw new SerializationException( + string.Format( + CultureInfo.InvariantCulture, + "Multiple properties with the name/alias '{0}' already exists on type '{1}', maybe you're misusing YamlAlias or maybe you are using the wrong naming convention? The matching properties are: {2}", + name, + type.FullName, + string.Join(", ", candidates.Select(p => p.Name).ToArray()) + ) + ); + } + + return property; + } + } + } +} diff --git a/YamlDotNet/Serialization/TypeInspectors/TypeInspectorSkeleton.cs.meta b/YamlDotNet/Serialization/TypeInspectors/TypeInspectorSkeleton.cs.meta new file mode 100644 index 0000000..6c8b981 --- /dev/null +++ b/YamlDotNet/Serialization/TypeInspectors/TypeInspectorSkeleton.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: ed437999b4d95dd4094909044396a0b2 +timeCreated: 1427145267 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/TypeResolvers.meta b/YamlDotNet/Serialization/TypeResolvers.meta new file mode 100644 index 0000000..a8ce58b --- /dev/null +++ b/YamlDotNet/Serialization/TypeResolvers.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 38df578a5c1d3024aa1e1052eaacbd43 +folderAsset: yes +timeCreated: 1427145262 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/TypeResolvers/DynamicTypeResolver.cs b/YamlDotNet/Serialization/TypeResolvers/DynamicTypeResolver.cs new file mode 100644 index 0000000..e96f3ac --- /dev/null +++ b/YamlDotNet/Serialization/TypeResolvers/DynamicTypeResolver.cs @@ -0,0 +1,36 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace YamlDotNet.Serialization.TypeResolvers +{ + /// + /// The type returned will be the actual type of the value, if available. + /// + public sealed class DynamicTypeResolver : ITypeResolver + { + public Type Resolve(Type staticType, object actualValue) + { + return actualValue != null ? actualValue.GetType() : staticType; + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/TypeResolvers/DynamicTypeResolver.cs.meta b/YamlDotNet/Serialization/TypeResolvers/DynamicTypeResolver.cs.meta new file mode 100644 index 0000000..78055ef --- /dev/null +++ b/YamlDotNet/Serialization/TypeResolvers/DynamicTypeResolver.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 28ddf494ebac7fe4fb7704de7713a111 +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/TypeResolvers/StaticTypeResolver.cs b/YamlDotNet/Serialization/TypeResolvers/StaticTypeResolver.cs new file mode 100644 index 0000000..3f46199 --- /dev/null +++ b/YamlDotNet/Serialization/TypeResolvers/StaticTypeResolver.cs @@ -0,0 +1,36 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace YamlDotNet.Serialization.TypeResolvers +{ + /// + /// The type returned will always be the static type. + /// + public sealed class StaticTypeResolver : ITypeResolver + { + public Type Resolve(Type staticType, object actualValue) + { + return staticType; + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/TypeResolvers/StaticTypeResolver.cs.meta b/YamlDotNet/Serialization/TypeResolvers/StaticTypeResolver.cs.meta new file mode 100644 index 0000000..8810141 --- /dev/null +++ b/YamlDotNet/Serialization/TypeResolvers/StaticTypeResolver.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 684d1820910272c41957060731567d5c +timeCreated: 1427145264 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/Utilities.meta b/YamlDotNet/Serialization/Utilities.meta new file mode 100644 index 0000000..d113c88 --- /dev/null +++ b/YamlDotNet/Serialization/Utilities.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: c788194c59eb2364fad0a9b407737368 +folderAsset: yes +timeCreated: 1427145262 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/Utilities/IPostDeserializationCallback.cs b/YamlDotNet/Serialization/Utilities/IPostDeserializationCallback.cs new file mode 100644 index 0000000..6f3133b --- /dev/null +++ b/YamlDotNet/Serialization/Utilities/IPostDeserializationCallback.cs @@ -0,0 +1,32 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +namespace YamlDotNet.Serialization.Utilities +{ + /// + /// Indicates that a class used as deserialization state + /// needs to be notified after deserialization. + /// + public interface IPostDeserializationCallback + { + void OnDeserialization(); + } +} diff --git a/YamlDotNet/Serialization/Utilities/IPostDeserializationCallback.cs.meta b/YamlDotNet/Serialization/Utilities/IPostDeserializationCallback.cs.meta new file mode 100644 index 0000000..e7c4ce1 --- /dev/null +++ b/YamlDotNet/Serialization/Utilities/IPostDeserializationCallback.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 0a1b0915df335f34aa94272237836de2 +timeCreated: 1427145262 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/Utilities/ObjectAnchorCollection.cs b/YamlDotNet/Serialization/Utilities/ObjectAnchorCollection.cs new file mode 100644 index 0000000..3bfd3a4 --- /dev/null +++ b/YamlDotNet/Serialization/Utilities/ObjectAnchorCollection.cs @@ -0,0 +1,76 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System.Collections.Generic; +using System.Globalization; +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization.Utilities +{ + internal sealed class ObjectAnchorCollection + { + private readonly IDictionary objectsByAnchor = new Dictionary(); + private readonly IDictionary anchorsByObject = new Dictionary(); + + /// + /// Adds the specified anchor. + /// + /// The anchor. + /// The @object. + public void Add(string anchor, object @object) + { + objectsByAnchor.Add(anchor, @object); + if (@object != null) + { + anchorsByObject.Add(@object, anchor); + } + } + + /// + /// Gets the anchor for the specified object. + /// + /// The object. + /// The anchor. + /// + public bool TryGetAnchor(object @object, out string anchor) + { + return anchorsByObject.TryGetValue(@object, out anchor); + } + + /// + /// Gets the with the specified anchor. + /// + /// + public object this[string anchor] + { + get + { + object value; + if (objectsByAnchor.TryGetValue(anchor, out value)) + { + return value; + } + + throw new AnchorNotFoundException(string.Format(CultureInfo.InvariantCulture, "The anchor '{0}' does not exists", anchor)); + } + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/Utilities/ObjectAnchorCollection.cs.meta b/YamlDotNet/Serialization/Utilities/ObjectAnchorCollection.cs.meta new file mode 100644 index 0000000..4913861 --- /dev/null +++ b/YamlDotNet/Serialization/Utilities/ObjectAnchorCollection.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2e3d78e3d62429040a9c8ab6066499ae +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/Utilities/ReflectionUtility.cs b/YamlDotNet/Serialization/Utilities/ReflectionUtility.cs new file mode 100644 index 0000000..7970afd --- /dev/null +++ b/YamlDotNet/Serialization/Utilities/ReflectionUtility.cs @@ -0,0 +1,54 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; + +namespace YamlDotNet.Serialization.Utilities +{ + internal static class ReflectionUtility + { + public static Type GetImplementedGenericInterface(Type type, Type genericInterfaceType) + { + foreach (var interfacetype in GetImplementedInterfaces(type)) + { + if (interfacetype.IsGenericType() && interfacetype.GetGenericTypeDefinition() == genericInterfaceType) + { + return interfacetype; + } + } + return null; + } + + public static IEnumerable GetImplementedInterfaces(Type type) + { + if (type.IsInterface()) + { + yield return type; + } + + foreach (var implementedInterface in type.GetInterfaces()) + { + yield return implementedInterface; + } + } + } +} diff --git a/YamlDotNet/Serialization/Utilities/ReflectionUtility.cs.meta b/YamlDotNet/Serialization/Utilities/ReflectionUtility.cs.meta new file mode 100644 index 0000000..ec18724 --- /dev/null +++ b/YamlDotNet/Serialization/Utilities/ReflectionUtility.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: a47e4ee72331a6b4aaf1b7abd7b76d6d +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/Utilities/SerializerState.cs b/YamlDotNet/Serialization/Utilities/SerializerState.cs new file mode 100644 index 0000000..5b3222b --- /dev/null +++ b/YamlDotNet/Serialization/Utilities/SerializerState.cs @@ -0,0 +1,68 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace YamlDotNet.Serialization.Utilities +{ + /// + /// A generic container that is preserved during the entire deserialization process. + /// Any disposable object added to this collecion will be disposed when this object is disposed. + /// + public sealed class SerializerState : IDisposable + { + private readonly IDictionary items = new Dictionary(); + + public T Get() + where T : class, new() + { + object value; + if (!items.TryGetValue(typeof(T), out value)) + { + value = new T(); + items.Add(typeof(T), value); + } + return (T)value; + } + + /// + /// Invokes on all + /// objects added to this collection that implement . + /// + public void OnDeserialization() + { + foreach (var callback in items.Values.OfType()) + { + callback.OnDeserialization(); + } + } + + public void Dispose() + { + foreach (var disposable in items.Values.OfType()) + { + disposable.Dispose(); + } + } + } +} diff --git a/YamlDotNet/Serialization/Utilities/SerializerState.cs.meta b/YamlDotNet/Serialization/Utilities/SerializerState.cs.meta new file mode 100644 index 0000000..1e8c202 --- /dev/null +++ b/YamlDotNet/Serialization/Utilities/SerializerState.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: c783e372f00ca8e42a66fe82bbbe3fd2 +timeCreated: 1427145266 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/Utilities/StringExtensions.cs b/YamlDotNet/Serialization/Utilities/StringExtensions.cs new file mode 100644 index 0000000..9c23e3f --- /dev/null +++ b/YamlDotNet/Serialization/Utilities/StringExtensions.cs @@ -0,0 +1,79 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Text.RegularExpressions; + +namespace YamlDotNet.Serialization.Utilities +{ + /// + /// Various string extension methods + /// + internal static class StringExtensions + { + private static string ToCamelOrPascalCase(string str, Func firstLetterTransform) + { + var text = Regex.Replace(str, "([_\\-])(?[a-z])", match => match.Groups["char"].Value.ToUpperInvariant(), RegexOptions.IgnoreCase); + return firstLetterTransform(text[0]) + text.Substring(1); + } + + + /// + /// Convert the string with underscores (this_is_a_test) or hyphens (this-is-a-test) to + /// camel case (thisIsATest). Camel case is the same as Pascal case, except the first letter + /// is lowercase. + /// + /// String to convert + /// Converted string + public static string ToCamelCase(this string str) + { + return ToCamelOrPascalCase(str, char.ToLowerInvariant); + } + + /// + /// Convert the string with underscores (this_is_a_test) or hyphens (this-is-a-test) to + /// pascal case (ThisIsATest). Pascal case is the same as camel case, except the first letter + /// is uppercase. + /// + /// String to convert + /// Converted string + public static string ToPascalCase(this string str) + { + return ToCamelOrPascalCase(str, char.ToUpperInvariant); + } + + /// + /// Convert the string from camelcase (thisIsATest) to a hyphenated (this-is-a-test) or + /// underscored (this_is_a_test) string + /// + /// String to convert + /// Separator to use between segments + /// Converted string + public static string FromCamelCase(this string str, string separator) + { + // Ensure first letter is always lowercase + str = char.ToLower(str[0]) + str.Substring(1); + + str = Regex.Replace(str.ToCamelCase(), "(?[A-Z])", match => separator + match.Groups["char"].Value.ToLowerInvariant()); + return str; + } + } +} diff --git a/YamlDotNet/Serialization/Utilities/StringExtensions.cs.meta b/YamlDotNet/Serialization/Utilities/StringExtensions.cs.meta new file mode 100644 index 0000000..6aa5cc8 --- /dev/null +++ b/YamlDotNet/Serialization/Utilities/StringExtensions.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b5dcdcf416fdbed4faabbba800ede39a +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/Utilities/TypeConverter.cs b/YamlDotNet/Serialization/Utilities/TypeConverter.cs new file mode 100644 index 0000000..7983462 --- /dev/null +++ b/YamlDotNet/Serialization/Utilities/TypeConverter.cs @@ -0,0 +1,234 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +// Remarks: This file is imported from the SixPack library. This is ok because +// the copyright holder has agreed to redistribute this file under the license +// used in YamlDotNet. + +using System; +using System.ComponentModel; +using System.Globalization; +using System.Linq; +using System.Reflection; + +namespace YamlDotNet.Serialization.Utilities +{ + /// + /// Performs type conversions using every standard provided by the .NET library. + /// + public static class TypeConverter + { + /// + /// Converts the specified value. + /// + /// The type to which the value is to be converted. + /// The value to convert. + /// + public static T ChangeType(object value) + { + return (T)ChangeType(value, typeof(T)); + } + + /// + /// Converts the specified value. + /// + /// The type to which the value is to be converted. + /// The value to convert. + /// The provider. + /// + public static T ChangeType(object value, IFormatProvider provider) + { + return (T)ChangeType(value, typeof(T), provider); + } + + /// + /// Converts the specified value. + /// + /// The type to which the value is to be converted. + /// The value to convert. + /// The culture. + /// + public static T ChangeType(object value, CultureInfo culture) + { + return (T)ChangeType(value, typeof(T), culture); + } + + /// + /// Converts the specified value using the invariant culture. + /// + /// The value to convert. + /// The type to which the value is to be converted. + /// + public static object ChangeType(object value, Type destinationType) + { + return ChangeType(value, destinationType, CultureInfo.InvariantCulture); + } + + /// + /// Converts the specified value. + /// + /// The value to convert. + /// The type to which the value is to be converted. + /// The format provider. + /// + public static object ChangeType(object value, Type destinationType, IFormatProvider provider) + { + return ChangeType(value, destinationType, new CultureInfoAdapter(CultureInfo.CurrentCulture, provider)); + } + + /// + /// Converts the specified value. + /// + /// The value to convert. + /// The type to which the value is to be converted. + /// The culture. + /// + public static object ChangeType(object value, Type destinationType, CultureInfo culture) + { + // Handle null and DBNull + if (value == null || value is DBNull) + { + return destinationType.IsValueType() ? Activator.CreateInstance(destinationType) : null; + } + + var sourceType = value.GetType(); + + // If the source type is compatible with the destination type, no conversion is needed + if (destinationType.IsAssignableFrom(sourceType)) + { + return value; + } + + // Nullable types get a special treatment + if (destinationType.IsGenericType()) + { + var genericTypeDefinition = destinationType.GetGenericTypeDefinition(); + if (genericTypeDefinition == typeof(Nullable<>)) + { + var innerType = destinationType.GetGenericArguments()[0]; + var convertedValue = ChangeType(value, innerType, culture); + return Activator.CreateInstance(destinationType, convertedValue); + } + } + + // Enums also require special handling + if (destinationType.IsEnum()) + { + var valueText = value as string; + return valueText != null ? Enum.Parse(destinationType, valueText, true) : value; + } + + // Special case for booleans to support parsing "1" and "0". This is + // necessary for compatibility with XML Schema. + if (destinationType == typeof(bool)) + { + if ("0".Equals(value)) + return false; + + if ("1".Equals(value)) + return true; + } + +#if !PORTABLE + // Try with the source type's converter + var sourceConverter = TypeDescriptor.GetConverter(value); + if (sourceConverter != null && sourceConverter.CanConvertTo(destinationType)) + { + return sourceConverter.ConvertTo(null, culture, value, destinationType); + } + + // Try with the destination type's converter + var destinationConverter = TypeDescriptor.GetConverter(destinationType); + if (destinationConverter != null && destinationConverter.CanConvertFrom(sourceType)) + { + return destinationConverter.ConvertFrom(null, culture, value); + } +#endif + + // Try to find a casting operator in the source or destination type + foreach (var type in new[] { sourceType, destinationType }) + { + foreach (var method in type.GetPublicStaticMethods()) + { + var isCastingOperator = + method.IsSpecialName && + (method.Name == "op_Implicit" || method.Name == "op_Explicit") && + destinationType.IsAssignableFrom(method.ReturnParameter.ParameterType); + + if (isCastingOperator) + { + var parameters = method.GetParameters(); + + var isCompatible = + parameters.Length == 1 && + parameters[0].ParameterType.IsAssignableFrom(sourceType); + + if (isCompatible) + { + try + { + return method.Invoke(null, new[] { value }); + } + catch (TargetInvocationException ex) + { + throw ex.Unwrap(); + } + } + } + } + } + + // If source type is string, try to find a Parse or TryParse method + if (sourceType == typeof(string)) + { + try + { + // Try with - public static T Parse(string, IFormatProvider) + var parseMethod = destinationType.GetPublicStaticMethod("Parse", typeof(string), typeof(IFormatProvider)); + if (parseMethod != null) + { + return parseMethod.Invoke(null, new object[] { value, culture }); + } + + // Try with - public static T Parse(string) + parseMethod = destinationType.GetPublicStaticMethod("Parse", typeof(string)); + if (parseMethod != null) + { + return parseMethod.Invoke(null, new object[] { value }); + } + } + catch (TargetInvocationException ex) + { + throw ex.Unwrap(); + } + } + + // Handle TimeSpan + if (destinationType == typeof(TimeSpan)) + { + return TimeSpan.Parse((string)ChangeType(value, typeof(string), CultureInfo.InvariantCulture)); + } + + // Default to the Convert class + return Convert.ChangeType(value, destinationType, CultureInfo.InvariantCulture); + } + } +} diff --git a/YamlDotNet/Serialization/Utilities/TypeConverter.cs.meta b/YamlDotNet/Serialization/Utilities/TypeConverter.cs.meta new file mode 100644 index 0000000..45885fb --- /dev/null +++ b/YamlDotNet/Serialization/Utilities/TypeConverter.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6450212473c552045b5fcfa8b6b759a3 +timeCreated: 1427145264 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/ValueDeserializers.meta b/YamlDotNet/Serialization/ValueDeserializers.meta new file mode 100644 index 0000000..5761972 --- /dev/null +++ b/YamlDotNet/Serialization/ValueDeserializers.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: d42ae4e770457104786ea4387344db74 +folderAsset: yes +timeCreated: 1427145262 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/ValueDeserializers/AliasValueDeserializer.cs b/YamlDotNet/Serialization/ValueDeserializers/AliasValueDeserializer.cs new file mode 100644 index 0000000..0b1558f --- /dev/null +++ b/YamlDotNet/Serialization/ValueDeserializers/AliasValueDeserializer.cs @@ -0,0 +1,158 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Collections.Generic; +using YamlDotNet.Core; +using YamlDotNet.Core.Events; +using YamlDotNet.Serialization.Utilities; + +namespace YamlDotNet.Serialization.ValueDeserializers +{ + public sealed class AliasValueDeserializer : IValueDeserializer + { + private readonly IValueDeserializer innerDeserializer; + + public AliasValueDeserializer(IValueDeserializer innerDeserializer) + { + if (innerDeserializer == null) + { + throw new ArgumentNullException("innerDeserializer"); + } + + this.innerDeserializer = innerDeserializer; + } + + private sealed class AliasState : Dictionary, IPostDeserializationCallback + { + public void OnDeserialization() + { + foreach (var promise in Values) + { + if (!promise.HasValue) + { + throw new AnchorNotFoundException(promise.Alias.Start, promise.Alias.End, string.Format( + "Anchor '{0}' not found", + promise.Alias.Value + )); + } + } + } + } + + private sealed class ValuePromise : IValuePromise + { + public event Action ValueAvailable; + + public bool HasValue { get; private set; } + + private object value; + + public readonly AnchorAlias Alias; + + public ValuePromise(AnchorAlias alias) + { + this.Alias = alias; + } + + public ValuePromise(object value) + { + HasValue = true; + this.value = value; + } + + public object Value + { + get + { + if (!HasValue) + { + throw new InvalidOperationException("Value not set"); + } + return value; + } + set + { + if (HasValue) + { + throw new InvalidOperationException("Value already set"); + } + HasValue = true; + this.value = value; + + if (ValueAvailable != null) + { + ValueAvailable(value); + } + } + } + } + + public object DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer) + { + object value; + var alias = parser.Allow(); + if (alias != null) + { + var aliasState = state.Get(); + ValuePromise valuePromise; + if (!aliasState.TryGetValue(alias.Value, out valuePromise)) + { + valuePromise = new ValuePromise(alias); + aliasState.Add(alias.Value, valuePromise); + } + + return valuePromise.HasValue ? valuePromise.Value : valuePromise; + } + + string anchor = null; + + var nodeEvent = parser.Peek(); + if (nodeEvent != null && !string.IsNullOrEmpty(nodeEvent.Anchor)) + { + anchor = nodeEvent.Anchor; + } + + value = innerDeserializer.DeserializeValue(parser, expectedType, state, nestedObjectDeserializer); + + if (anchor != null) + { + var aliasState = state.Get(); + + ValuePromise valuePromise; + if (!aliasState.TryGetValue(anchor, out valuePromise)) + { + aliasState.Add(anchor, new ValuePromise(value)); + } + else if (!valuePromise.HasValue) + { + valuePromise.Value = value; + } + else + { + aliasState[anchor] = new ValuePromise(value); + } + } + + return value; + } + } +} diff --git a/YamlDotNet/Serialization/ValueDeserializers/AliasValueDeserializer.cs.meta b/YamlDotNet/Serialization/ValueDeserializers/AliasValueDeserializer.cs.meta new file mode 100644 index 0000000..384575b --- /dev/null +++ b/YamlDotNet/Serialization/ValueDeserializers/AliasValueDeserializer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2b42e3b48f16da04d81b23e165d66fc3 +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/ValueDeserializers/NodeValueDeserializer.cs b/YamlDotNet/Serialization/ValueDeserializers/NodeValueDeserializer.cs new file mode 100644 index 0000000..144ce11 --- /dev/null +++ b/YamlDotNet/Serialization/ValueDeserializers/NodeValueDeserializer.cs @@ -0,0 +1,100 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; +using YamlDotNet.Core; +using YamlDotNet.Core.Events; +using YamlDotNet.Serialization.Utilities; + +namespace YamlDotNet.Serialization.ValueDeserializers +{ + public sealed class NodeValueDeserializer : IValueDeserializer + { + private readonly IList deserializers; + private readonly IList typeResolvers; + + public NodeValueDeserializer(IList deserializers, IList typeResolvers) + { + if (deserializers == null) + { + throw new ArgumentNullException("deserializers"); + } + + this.deserializers = deserializers; + + if (typeResolvers == null) + { + throw new ArgumentNullException("typeResolvers"); + } + this.typeResolvers = typeResolvers; + } + + public object DeserializeValue (IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer) + { + var nodeEvent = parser.Peek(); + + var nodeType = GetTypeFromEvent(nodeEvent, expectedType); + + try + { + foreach (var deserializer in deserializers) + { + object value; + if (deserializer.Deserialize(parser, nodeType, (r, t) => nestedObjectDeserializer.DeserializeValue(r, t, state, nestedObjectDeserializer), out value)) + { + return value; + } + } + } + catch (YamlException) + { + throw; + } + catch (Exception ex) + { + throw new YamlException(nodeEvent.Start, nodeEvent.End, "Exception during deserialization", ex); + } + + throw new YamlException( + nodeEvent.Start, + nodeEvent.End, + string.Format( + "No node deserializer was able to deserialize the node into type {0}", + expectedType.AssemblyQualifiedName + ) + ); + } + + private Type GetTypeFromEvent(NodeEvent nodeEvent, Type currentType) + { + foreach (var typeResolver in typeResolvers) + { + if (typeResolver.Resolve(nodeEvent, ref currentType)) + { + break; + } + } + return currentType; + } + } +} diff --git a/YamlDotNet/Serialization/ValueDeserializers/NodeValueDeserializer.cs.meta b/YamlDotNet/Serialization/ValueDeserializers/NodeValueDeserializer.cs.meta new file mode 100644 index 0000000..faeecb8 --- /dev/null +++ b/YamlDotNet/Serialization/ValueDeserializers/NodeValueDeserializer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 3782a2b6c58f1ae459162e3ce74fc25f +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/YamlAttributeOverrides.cs b/YamlDotNet/Serialization/YamlAttributeOverrides.cs new file mode 100644 index 0000000..6f9fe76 --- /dev/null +++ b/YamlDotNet/Serialization/YamlAttributeOverrides.cs @@ -0,0 +1,191 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Linq.Expressions; +using YamlDotNet.Core; +using YamlDotNet.Helpers; + +namespace YamlDotNet.Serialization +{ + /// + /// Define a collection of YamlAttribute Overrides for pre-defined object types. + /// + public sealed class YamlAttributeOverrides + { + private struct AttributeKey + { + public readonly Type AttributeType; + public readonly string PropertyName; + + public AttributeKey(Type attributeType, string propertyName) + { + AttributeType = attributeType; + PropertyName = propertyName; + } + + public override bool Equals(object obj) + { + var other = (AttributeKey)obj; + return AttributeType.Equals(other.AttributeType) + && PropertyName.Equals(other.PropertyName); + } + + public override int GetHashCode() + { + return HashCode.CombineHashCodes(AttributeType.GetHashCode(), PropertyName.GetHashCode()); + } + } + + private sealed class AttributeMapping + { + public readonly Type RegisteredType; + public readonly Attribute Attribute; + + public AttributeMapping(Type registeredType, Attribute attribute) + { + this.RegisteredType = registeredType; + Attribute = attribute; + } + + public override bool Equals(object obj) + { + var other = obj as AttributeMapping; + return other != null + && RegisteredType.Equals(other.RegisteredType) + && Attribute.Equals(other.Attribute); + } + + public override int GetHashCode() + { + return HashCode.CombineHashCodes(RegisteredType.GetHashCode(), Attribute.GetHashCode()); + } + + /// + /// Checks whether this mapping matches the specified type, and returns a value indicating the match priority. + /// + /// The priority of the match. Higher values have more priority. Zero indicates no match. + public int Matches(Type matchType) + { + var currentPriority = 0; + var currentType = matchType; + while (currentType != null) + { + ++currentPriority; + if (currentType == RegisteredType) + { + return currentPriority; + } + currentType = currentType.BaseType(); + } + + if (matchType.GetInterfaces().Contains(RegisteredType)) + { + return currentPriority; + } + + return 0; + } + } + + private readonly Dictionary> overrides = new Dictionary>(); + + public T GetAttribute(Type type, string member) where T : Attribute + { + List mappings; + if (overrides.TryGetValue(new AttributeKey(typeof(T), member), out mappings)) + { + int bestMatchPriority = 0; + AttributeMapping bestMatch = null; + + foreach (var mapping in mappings) + { + var priority = mapping.Matches(type); + if (priority > bestMatchPriority) + { + bestMatchPriority = priority; + bestMatch = mapping; + } + } + + if (bestMatchPriority > 0) + { + return (T)bestMatch.Attribute; + } + } + + return null; + } + + /// + /// Adds a Member Attribute Override + /// + /// Type + /// Class Member + /// Overriding Attribute + public void Add(Type type, string member, Attribute attribute) + { + var mapping = new AttributeMapping(type, attribute); + + List mappings; + var attributeKey = new AttributeKey(attribute.GetType(), member); + if (!overrides.TryGetValue(attributeKey, out mappings)) + { + mappings = new List(); + overrides.Add(attributeKey, mappings); + } + else if (mappings.Contains(mapping)) + { + throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Attribute ({2}) already set for Type {0}, Member {1}", type.FullName, member, attribute)); + } + + mappings.Add(mapping); + } + + /// + /// Adds a Member Attribute Override + /// + public void Add(Expression> propertyAccessor, Attribute attribute) + { + var property = propertyAccessor.AsProperty(); + Add(typeof(TClass), property.Name, attribute); + } + + /// + /// Creates a copy of this instance. + /// + public YamlAttributeOverrides Clone() + { + var clone = new YamlAttributeOverrides(); + foreach (var entry in overrides) + { + foreach (var item in entry.Value) + { + clone.Add(item.RegisteredType, entry.Key.PropertyName, item.Attribute); + } + } + return clone; + } + } +} diff --git a/YamlDotNet/Serialization/YamlAttributeOverrides.cs.meta b/YamlDotNet/Serialization/YamlAttributeOverrides.cs.meta new file mode 100644 index 0000000..aeb47a7 --- /dev/null +++ b/YamlDotNet/Serialization/YamlAttributeOverrides.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: fba02faec11e7ca41a8c8ce8ef7c4cc2 +timeCreated: 1485601086 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/YamlAttributeOverridesInspector.cs b/YamlDotNet/Serialization/YamlAttributeOverridesInspector.cs new file mode 100644 index 0000000..dd6ac95 --- /dev/null +++ b/YamlDotNet/Serialization/YamlAttributeOverridesInspector.cs @@ -0,0 +1,107 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Linq; +using YamlDotNet.Core; +using YamlDotNet.Serialization.TypeInspectors; + +namespace YamlDotNet.Serialization +{ + /// + /// Applies the Yaml attribute overrides to another . + /// + public sealed class YamlAttributeOverridesInspector : TypeInspectorSkeleton + { + private readonly ITypeInspector innerTypeDescriptor; + private readonly YamlAttributeOverrides overrides; + + public YamlAttributeOverridesInspector(ITypeInspector innerTypeDescriptor, YamlAttributeOverrides overrides) + { + this.innerTypeDescriptor = innerTypeDescriptor; + this.overrides = overrides; + } + + public override IEnumerable GetProperties(Type type, object container) + { + if (overrides == null) + return innerTypeDescriptor.GetProperties(type, container); + + return innerTypeDescriptor.GetProperties(type, container) + .Select(p => (IPropertyDescriptor)new OverridePropertyDescriptor(p, overrides, type)); + } + + public sealed class OverridePropertyDescriptor : IPropertyDescriptor + { + private readonly IPropertyDescriptor baseDescriptor; + private readonly YamlAttributeOverrides overrides; + private readonly Type classType; + + public OverridePropertyDescriptor(IPropertyDescriptor baseDescriptor, YamlAttributeOverrides overrides, Type classType) + { + this.baseDescriptor = baseDescriptor; + this.overrides = overrides; + this.classType = classType; + } + + public string Name { get { return baseDescriptor.Name; } } + + public bool CanWrite { get { return baseDescriptor.CanWrite; } } + + public Type Type { get { return baseDescriptor.Type; } } + + public Type TypeOverride + { + get { return baseDescriptor.TypeOverride; } + set { baseDescriptor.TypeOverride = value; } + } + + public int Order + { + get { return baseDescriptor.Order; } + set { baseDescriptor.Order = value; } + } + + public ScalarStyle ScalarStyle + { + get { return baseDescriptor.ScalarStyle; } + set { baseDescriptor.ScalarStyle = value; } + } + + public void Write(object target, object value) + { + baseDescriptor.Write(target, value); + } + + public T GetCustomAttribute() where T : Attribute + { + var attr = overrides.GetAttribute(classType, Name); + return attr ?? baseDescriptor.GetCustomAttribute(); + } + + public IObjectDescriptor Read(object target) + { + return baseDescriptor.Read(target); + } + } + } +} diff --git a/YamlDotNet/Serialization/YamlAttributeOverridesInspector.cs.meta b/YamlDotNet/Serialization/YamlAttributeOverridesInspector.cs.meta new file mode 100644 index 0000000..ce1d7f6 --- /dev/null +++ b/YamlDotNet/Serialization/YamlAttributeOverridesInspector.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 0f1b1e1d3f9f9b74a9b7a7511a5e6844 +timeCreated: 1485601082 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/YamlAttributesTypeInspector.cs b/YamlDotNet/Serialization/YamlAttributesTypeInspector.cs new file mode 100644 index 0000000..18b9727 --- /dev/null +++ b/YamlDotNet/Serialization/YamlAttributesTypeInspector.cs @@ -0,0 +1,70 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Linq; +using YamlDotNet.Serialization.TypeInspectors; + +namespace YamlDotNet.Serialization +{ + /// + /// Applies the Yaml* attributes to another . + /// + public sealed class YamlAttributesTypeInspector : TypeInspectorSkeleton + { + private readonly ITypeInspector innerTypeDescriptor; + + public YamlAttributesTypeInspector(ITypeInspector innerTypeDescriptor) + { + this.innerTypeDescriptor = innerTypeDescriptor; + } + + public override IEnumerable GetProperties(Type type, object container) + { + return innerTypeDescriptor.GetProperties(type, container) + .Where(p => p.GetCustomAttribute() == null) + .Select(p => + { + var descriptor = new PropertyDescriptor(p); + var member = p.GetCustomAttribute(); + if (member != null) + { + if (member.SerializeAs != null) + { + descriptor.TypeOverride = member.SerializeAs; + } + + descriptor.Order = member.Order; + descriptor.ScalarStyle = member.ScalarStyle; + + if (member.Alias != null) + { + descriptor.Name = member.Alias; + } + } + + return (IPropertyDescriptor)descriptor; + }) + .OrderBy(p => p.Order); + } + } +} diff --git a/YamlDotNet/Serialization/YamlAttributesTypeInspector.cs.meta b/YamlDotNet/Serialization/YamlAttributesTypeInspector.cs.meta new file mode 100644 index 0000000..71c912b --- /dev/null +++ b/YamlDotNet/Serialization/YamlAttributesTypeInspector.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 8bbeea575ee7a0b4cb53bf99b07e9949 +timeCreated: 1427145265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/YamlFormatter.cs b/YamlDotNet/Serialization/YamlFormatter.cs new file mode 100644 index 0000000..bb4ae0d --- /dev/null +++ b/YamlDotNet/Serialization/YamlFormatter.cs @@ -0,0 +1,75 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Globalization; + +namespace YamlDotNet.Serialization +{ + internal static class YamlFormatter + { + public static readonly NumberFormatInfo NumberFormat = new NumberFormatInfo + { + CurrencyDecimalSeparator = ".", + CurrencyGroupSeparator = "_", + CurrencyGroupSizes = new[] { 3 }, + CurrencySymbol = string.Empty, + CurrencyDecimalDigits = 99, + NumberDecimalSeparator = ".", + NumberGroupSeparator = "_", + NumberGroupSizes = new[] { 3 }, + NumberDecimalDigits = 99, + NaNSymbol = ".nan", + PositiveInfinitySymbol = ".inf", + NegativeInfinitySymbol = "-.inf" + }; + + public static string FormatNumber(object number) + { + return Convert.ToString(number, NumberFormat); + } + + public static string FormatNumber(double number) + { + return number.ToString("G17", NumberFormat); + } + + public static string FormatNumber(float number) + { + return number.ToString("G17", NumberFormat); + } + + public static string FormatBoolean(object boolean) + { + return boolean.Equals(true) ? "true" : "false"; + } + + public static string FormatDateTime(object dateTime) + { + return ((DateTime)dateTime).ToString("o", CultureInfo.InvariantCulture); + } + + public static string FormatTimeSpan(object timeSpan) + { + return ((TimeSpan)timeSpan).ToString(); + } + } +} \ No newline at end of file diff --git a/YamlDotNet/Serialization/YamlFormatter.cs.meta b/YamlDotNet/Serialization/YamlFormatter.cs.meta new file mode 100644 index 0000000..c778492 --- /dev/null +++ b/YamlDotNet/Serialization/YamlFormatter.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 197ec9064396a7c42bfa14c2edfd50ad +timeCreated: 1427145263 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/YamlIgnoreAttribute.cs b/YamlDotNet/Serialization/YamlIgnoreAttribute.cs new file mode 100644 index 0000000..9db36ef --- /dev/null +++ b/YamlDotNet/Serialization/YamlIgnoreAttribute.cs @@ -0,0 +1,34 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace YamlDotNet.Serialization +{ + /// + /// Instructs the YamlSerializer not to serialize the public field or public read/write property value. + /// + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)] + public sealed class YamlIgnoreAttribute : Attribute + { + } +} + diff --git a/YamlDotNet/Serialization/YamlIgnoreAttribute.cs.meta b/YamlDotNet/Serialization/YamlIgnoreAttribute.cs.meta new file mode 100644 index 0000000..4e81c74 --- /dev/null +++ b/YamlDotNet/Serialization/YamlIgnoreAttribute.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: ecf403b8b63963644a55535cb66115a5 +timeCreated: 1427145267 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/Serialization/YamlMember.cs b/YamlDotNet/Serialization/YamlMember.cs new file mode 100644 index 0000000..e6be6a7 --- /dev/null +++ b/YamlDotNet/Serialization/YamlMember.cs @@ -0,0 +1,76 @@ +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) Antoine Aubry and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using YamlDotNet.Core; + +namespace YamlDotNet.Serialization +{ + /// + /// Provides special Yaml serialization instructions. + /// + [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] + public sealed class YamlMemberAttribute : Attribute + { + /// + /// Specifies that this property should be serialized as the given type, rather than using the actual runtime value's type. + /// + public Type SerializeAs { get; set; } + + /// + /// Specifies the order priority of this property. + /// + public int Order { get; set; } + + /// + /// Instructs the to use a different field name for serialization. + /// + public string Alias { get; set; } + + /// + /// When false, naming conventions will not be applied to this member. Defaults to true. + /// + public bool ApplyNamingConventions { get; set; } + + /// + /// Specifies the scalar style of the property when serialized. This will only affect the serialization of scalar properties. + /// + public ScalarStyle ScalarStyle { get; set; } + + /// + /// Initializes a new instance of the class. + /// + public YamlMemberAttribute() + { + ScalarStyle = ScalarStyle.Any; + ApplyNamingConventions = true; + } + + /// + /// Initializes a new instance of the class. + /// + /// Specifies that this property should be serialized as the given type, rather than using the actual runtime value's type. + public YamlMemberAttribute(Type serializeAs) : this() + { + SerializeAs = serializeAs; + } + } +} diff --git a/YamlDotNet/Serialization/YamlMember.cs.meta b/YamlDotNet/Serialization/YamlMember.cs.meta new file mode 100644 index 0000000..06d5cd9 --- /dev/null +++ b/YamlDotNet/Serialization/YamlMember.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 77f1129984ccc56479428f6bd3758b91 +timeCreated: 1427145264 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/YamlDotNet/YamlDotNet.license.txt b/YamlDotNet/YamlDotNet.license.txt new file mode 100644 index 0000000..8cae53f --- /dev/null +++ b/YamlDotNet/YamlDotNet.license.txt @@ -0,0 +1,7 @@ +Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014 Antoine Aubry + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/YamlDotNet/YamlDotNet.license.txt.meta b/YamlDotNet/YamlDotNet.license.txt.meta new file mode 100644 index 0000000..14af1d9 --- /dev/null +++ b/YamlDotNet/YamlDotNet.license.txt.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ae757a5a9013c3543882d26d55092bc9 +timeCreated: 1431027192 +licenseType: Store +TextScriptImporter: + userData: + assetBundleName: + assetBundleVariant: