From ae4e3bd517742745ef07c7ead15d1c7c6d998dbb Mon Sep 17 00:00:00 2001 From: udaken <7896698+udaken@users.noreply.github.com> Date: Mon, 20 Jun 2022 13:19:00 +0900 Subject: [PATCH 1/5] Apply Roslyn style code format --- src/.editorconfig | 301 +++++++++++++ src/SharpYaml.Tests/DescriptorTests.cs | 4 +- src/SharpYaml.Tests/Dump.cs | 6 +- src/SharpYaml.Tests/EmitterTests.cs | 18 +- src/SharpYaml.Tests/InsertionQueueTests.cs | 10 +- src/SharpYaml.Tests/LookAheadBufferTests.cs | 4 +- src/SharpYaml.Tests/ParserTestHelper.cs | 4 +- src/SharpYaml.Tests/ParserTests.cs | 14 +- src/SharpYaml.Tests/PathTrieTest.cs | 23 +- src/SharpYaml.Tests/ScannerTestHelper.cs | 4 +- src/SharpYaml.Tests/ScannerTests.cs | 7 +- src/SharpYaml.Tests/SchemaTests.cs | 2 +- .../ExceptionWithNestedSerialization.cs | 8 +- .../Serialization/ObjectFactoryTests.cs | 2 +- src/SharpYaml.Tests/Serialization/Samples.cs | 8 +- .../Serialization/SerializationTests.cs | 121 ++--- .../Serialization/SerializationTests2.cs | 130 +++--- .../Serialization/TracingVisitor.cs | 4 +- .../Serialization/YamlStreamTests.cs | 22 +- src/SharpYaml.Tests/YamlNodeTest.cs | 41 +- src/SharpYaml.Tests/YamlNodeTrackerTest.cs | 96 ++-- src/SharpYaml.Tests/YamlTest.cs | 4 +- src/SharpYaml.sln | 1 + src/SharpYaml/CharHelper.cs | 4 +- src/SharpYaml/CharacterAnalyzer.cs | 4 +- src/SharpYaml/Constants.cs | 4 +- src/SharpYaml/Emitter.cs | 39 +- src/SharpYaml/EmitterState.cs | 4 +- src/SharpYaml/EventReader.cs | 12 +- src/SharpYaml/Events/AnchorAlias.cs | 4 +- src/SharpYaml/Events/DocumentEnd.cs | 4 +- src/SharpYaml/Events/DocumentStart.cs | 4 +- src/SharpYaml/Events/EventType.cs | 4 +- src/SharpYaml/Events/MappingEnd.cs | 4 +- src/SharpYaml/Events/MappingStart.cs | 4 +- src/SharpYaml/Events/NodeEvent.cs | 4 +- src/SharpYaml/Events/ParsingEvent.cs | 4 +- src/SharpYaml/Events/Scalar.cs | 6 +- src/SharpYaml/Events/SequenceEnd.cs | 4 +- src/SharpYaml/Events/SequenceStart.cs | 4 +- src/SharpYaml/Events/StreamEnd.cs | 4 +- src/SharpYaml/Events/StreamStart.cs | 4 +- src/SharpYaml/FakeList.cs | 4 +- src/SharpYaml/IEmitter.cs | 2 +- src/SharpYaml/ILookAheadBuffer.cs | 4 +- src/SharpYaml/IParser.cs | 2 +- src/SharpYaml/InsertionQueue.cs | 4 +- src/SharpYaml/LookAheadBuffer.cs | 6 +- src/SharpYaml/Mark.cs | 7 +- src/SharpYaml/MemoryParser.cs | 4 +- src/SharpYaml/Model/PathTrie.cs | 59 ++- src/SharpYaml/Model/YamlContainer.cs | 5 +- src/SharpYaml/Model/YamlDocument.cs | 49 +- src/SharpYaml/Model/YamlElement.cs | 5 +- src/SharpYaml/Model/YamlMapping.cs | 220 +++++---- src/SharpYaml/Model/YamlNode.cs | 41 +- .../Model/YamlNodeEventEnumerator.cs | 99 ++-- src/SharpYaml/Model/YamlNodeTracker.cs | 426 ++++++++++++------ src/SharpYaml/Model/YamlSequence.cs | 126 ++++-- src/SharpYaml/Model/YamlStream.cs | 93 ++-- src/SharpYaml/Model/YamlValue.cs | 59 ++- src/SharpYaml/Parser.cs | 18 +- src/SharpYaml/ParserState.cs | 4 +- src/SharpYaml/ScalarStyle.cs | 4 +- src/SharpYaml/Scanner.cs | 42 +- src/SharpYaml/Schemas/CoreSchema.cs | 6 +- src/SharpYaml/Schemas/ExtendedSchema.cs | 6 +- src/SharpYaml/Schemas/FailsafeSchema.cs | 4 +- src/SharpYaml/Schemas/IYamlSchema.cs | 4 +- src/SharpYaml/Schemas/JsonSchema.cs | 6 +- src/SharpYaml/Schemas/SchemaBase.cs | 4 +- src/SharpYaml/SemanticErrorException.cs | 4 +- .../Serialization/AnchorEventEmitter.cs | 4 +- .../Serialization/AnchorNotFoundException.cs | 4 +- .../Serialization/AssemblyRegistry.cs | 4 +- .../Serialization/AttributeRegistry.cs | 4 +- .../CamelCaseNamingConvention.cs | 4 +- .../Serialization/ChainedEventEmitter.cs | 4 +- .../Serialization/ChainedObjectFactory.cs | 2 +- .../Serialization/DefaultNamingConvention.cs | 4 +- .../Serialization/DefaultObjectFactory.cs | 4 +- .../Serialization/DescriptorCategory.cs | 4 +- .../Descriptors/ArrayDescriptor.cs | 4 +- .../Descriptors/CollectionDescriptor.cs | 22 +- .../Descriptors/DefaultKeyComparer.cs | 4 +- .../Descriptors/DictionaryDescriptor.cs | 22 +- .../Descriptors/FieldDescriptor.cs | 4 +- .../Descriptors/MemberDescriptorBase.cs | 4 +- .../Descriptors/NullableDescriptor.cs | 2 +- .../Descriptors/ObjectDescriptor.cs | 36 +- .../Descriptors/PrimitiveDescriptor.cs | 2 +- .../Descriptors/PropertyDescriptor.cs | 6 +- .../Descriptors/TypeDescriptorFactory.cs | 4 +- .../Serialization/DocumentLoadingState.cs | 4 +- .../Serialization/DuplicateAnchorException.cs | 4 +- .../DynamicMemberDescriptorBase.cs | 4 +- src/SharpYaml/Serialization/EmitterState.cs | 4 +- src/SharpYaml/Serialization/EventInfo.cs | 4 +- .../Serialization/FlatNamingConvention.cs | 4 +- .../Serialization/IAttributeRegistry.cs | 2 +- src/SharpYaml/Serialization/IEventEmitter.cs | 4 +- .../Serialization/IMemberDescriptor.cs | 4 +- .../Serialization/IMemberNamingConvention.cs | 2 +- src/SharpYaml/Serialization/IObjectFactory.cs | 2 +- .../Serialization/IObjectSerializerBackend.cs | 2 +- .../Serialization/IOrderedDictionary.cs | 4 +- .../Serialization/ITagTypeRegistry.cs | 2 +- .../Serialization/ITagTypeResolver.cs | 2 +- .../Serialization/ITypeDescriptor.cs | 4 +- .../Serialization/ITypeDescriptorFactory.cs | 4 +- .../Serialization/IYamlSerializable.cs | 4 +- .../Serialization/IYamlSerializableFactory.cs | 4 +- src/SharpYaml/Serialization/IYamlVisitor.cs | 4 +- .../Serialization/IdentityEqualityComparer.cs | 2 +- .../Serialization/JsonEventEmitter.cs | 4 +- .../Serialization/LambdaObjectFactory.cs | 2 +- .../Serialization/Logging/ILogger.cs | 4 +- .../Serialization/Logging/LogLevel.cs | 4 +- src/SharpYaml/Serialization/ObjectContext.cs | 4 +- .../Serialization/OrderedDictionary.cs | 4 +- .../Serialization/PascalNamingConvention.cs | 4 +- src/SharpYaml/Serialization/Serializer.cs | 34 +- .../Serialization/SerializerContext.cs | 4 +- .../SerializerContextSettings.cs | 4 +- .../Serialization/SerializerSettings.cs | 6 +- .../Serializers/AnchorSerializer.cs | 2 +- .../Serializers/ArraySerializer.cs | 10 +- .../Serializers/ChainedSerializer.cs | 2 +- .../Serializers/CollectionSerializer.cs | 12 +- .../DefaultObjectSerializerBackend.cs | 4 +- .../Serializers/DictionarySerializer.cs | 14 +- .../Serializers/ObjectSerializer.cs | 6 +- .../Serializers/PrimitiveSerializer.cs | 42 +- .../Serializers/RoutingSerializer.cs | 2 +- .../Serializers/ScalarSerializerBase.cs | 2 +- .../Serializers/TagTypeSerializer.cs | 10 +- .../Serialization/WriterEventEmitter.cs | 4 +- src/SharpYaml/Serialization/YamlAliasNode.cs | 4 +- src/SharpYaml/Serialization/YamlDocument.cs | 4 +- .../Serialization/YamlIgnoreAttribute.cs | 4 +- .../Serialization/YamlMappingNode.cs | 8 +- .../Serialization/YamlMemberAttribute.cs | 2 +- src/SharpYaml/Serialization/YamlNode.cs | 8 +- .../YamlNodeIdentityEqualityComparer.cs | 4 +- .../Serialization/YamlRemapAttribute.cs | 2 +- src/SharpYaml/Serialization/YamlScalarNode.cs | 4 +- .../Serialization/YamlSequenceNode.cs | 8 +- .../Serialization/YamlSerializableMethod.cs | 2 +- src/SharpYaml/Serialization/YamlStream.cs | 6 +- .../Serialization/YamlStyleAttribute.cs | 2 +- .../Serialization/YamlTagAttribute.cs | 2 +- src/SharpYaml/Serialization/YamlVisitor.cs | 4 +- src/SharpYaml/SimpleKey.cs | 4 +- src/SharpYaml/StringLookAheadBuffer.cs | 4 +- src/SharpYaml/SyntaxErrorException.cs | 4 +- src/SharpYaml/TagDirectiveCollection.cs | 4 +- src/SharpYaml/Tokens/Anchor.cs | 4 +- src/SharpYaml/Tokens/AnchorAlias.cs | 4 +- src/SharpYaml/Tokens/BlockEnd.cs | 4 +- src/SharpYaml/Tokens/BlockEntry.cs | 4 +- src/SharpYaml/Tokens/BlockMappingStart.cs | 4 +- src/SharpYaml/Tokens/BlockSequenceStart.cs | 4 +- src/SharpYaml/Tokens/DocumentEnd.cs | 4 +- src/SharpYaml/Tokens/DocumentStart.cs | 4 +- src/SharpYaml/Tokens/FlowEntry.cs | 4 +- src/SharpYaml/Tokens/FlowMappingEnd.cs | 4 +- src/SharpYaml/Tokens/FlowMappingStart.cs | 4 +- src/SharpYaml/Tokens/FlowSequenceEnd.cs | 4 +- src/SharpYaml/Tokens/FlowSequenceStart.cs | 4 +- src/SharpYaml/Tokens/Key.cs | 4 +- src/SharpYaml/Tokens/Scalar.cs | 4 +- src/SharpYaml/Tokens/StreamEnd.cs | 4 +- src/SharpYaml/Tokens/StreamStart.cs | 4 +- src/SharpYaml/Tokens/Tag.cs | 4 +- src/SharpYaml/Tokens/TagDirective.cs | 4 +- src/SharpYaml/Tokens/Token.cs | 4 +- src/SharpYaml/Tokens/Value.cs | 4 +- src/SharpYaml/Tokens/VersionDirective.cs | 4 +- src/SharpYaml/TypeExtensions.cs | 24 +- src/SharpYaml/Version.cs | 4 +- src/SharpYaml/YamlException.cs | 4 +- src/SharpYaml/YamlStyle.cs | 4 +- 182 files changed, 1802 insertions(+), 1076 deletions(-) create mode 100644 src/.editorconfig diff --git a/src/.editorconfig b/src/.editorconfig new file mode 100644 index 00000000..25b620a3 --- /dev/null +++ b/src/.editorconfig @@ -0,0 +1,301 @@ +# EditorConfig is awesome: https://EditorConfig.org + +# top-most EditorConfig file +root = true + +# Don't use tabs for indentation. +[*] +indent_style = space +# (Please don't specify an indent_size here; that has too many unintended consequences.) + +# Code files +[*.{cs,csx,vb,vbx}] +indent_size = 4 +insert_final_newline = true +charset = utf-8-bom + +# XML project files +[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}] +indent_size = 2 + +# XML config files +[*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}] +indent_size = 2 + +# JSON files +[*.json] +indent_size = 2 + +# Powershell files +[*.ps1] +indent_size = 2 + +# Shell script files +[*.sh] +end_of_line = lf +indent_size = 2 + +# Dotnet code style settings: +[*.{cs,vb}] + +# IDE0055: Fix formatting +dotnet_diagnostic.IDE0055.severity = warning + +# Sort using and Import directives with System.* appearing first +dotnet_sort_system_directives_first = true +dotnet_separate_import_directive_groups = false +# Avoid "this." and "Me." if not necessary +dotnet_style_qualification_for_field = false:refactoring +dotnet_style_qualification_for_property = false:refactoring +dotnet_style_qualification_for_method = false:refactoring +dotnet_style_qualification_for_event = false:refactoring + +# Use language keywords instead of framework type names for type references +dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion +dotnet_style_predefined_type_for_member_access = true:suggestion + +# Suggest more modern language features when available +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_explicit_tuple_names = true:suggestion + +# Whitespace options +dotnet_style_allow_multiple_blank_lines_experimental = false + +# Non-private static fields are PascalCase +dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.symbols = non_private_static_fields +dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.style = non_private_static_field_style + +dotnet_naming_symbols.non_private_static_fields.applicable_kinds = field +dotnet_naming_symbols.non_private_static_fields.applicable_accessibilities = public, protected, internal, protected_internal, private_protected +dotnet_naming_symbols.non_private_static_fields.required_modifiers = static + +dotnet_naming_style.non_private_static_field_style.capitalization = pascal_case + +# Non-private readonly fields are PascalCase +dotnet_naming_rule.non_private_readonly_fields_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.non_private_readonly_fields_should_be_pascal_case.symbols = non_private_readonly_fields +dotnet_naming_rule.non_private_readonly_fields_should_be_pascal_case.style = non_private_readonly_field_style + +dotnet_naming_symbols.non_private_readonly_fields.applicable_kinds = field +dotnet_naming_symbols.non_private_readonly_fields.applicable_accessibilities = public, protected, internal, protected_internal, private_protected +dotnet_naming_symbols.non_private_readonly_fields.required_modifiers = readonly + +dotnet_naming_style.non_private_readonly_field_style.capitalization = pascal_case + +# Constants are PascalCase +dotnet_naming_rule.constants_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.constants_should_be_pascal_case.symbols = constants +dotnet_naming_rule.constants_should_be_pascal_case.style = constant_style + +dotnet_naming_symbols.constants.applicable_kinds = field, local +dotnet_naming_symbols.constants.required_modifiers = const + +dotnet_naming_style.constant_style.capitalization = pascal_case + +# Static fields are camelCase and start with s_ +dotnet_naming_rule.static_fields_should_be_camel_case.severity = suggestion +dotnet_naming_rule.static_fields_should_be_camel_case.symbols = static_fields +dotnet_naming_rule.static_fields_should_be_camel_case.style = static_field_style + +dotnet_naming_symbols.static_fields.applicable_kinds = field +dotnet_naming_symbols.static_fields.required_modifiers = static + +dotnet_naming_style.static_field_style.capitalization = camel_case +dotnet_naming_style.static_field_style.required_prefix = s_ + +# Instance fields are camelCase and start with _ +dotnet_naming_rule.instance_fields_should_be_camel_case.severity = suggestion +dotnet_naming_rule.instance_fields_should_be_camel_case.symbols = instance_fields +dotnet_naming_rule.instance_fields_should_be_camel_case.style = instance_field_style + +dotnet_naming_symbols.instance_fields.applicable_kinds = field + +dotnet_naming_style.instance_field_style.capitalization = camel_case +dotnet_naming_style.instance_field_style.required_prefix = _ + +# Locals and parameters are camelCase +dotnet_naming_rule.locals_should_be_camel_case.severity = suggestion +dotnet_naming_rule.locals_should_be_camel_case.symbols = locals_and_parameters +dotnet_naming_rule.locals_should_be_camel_case.style = camel_case_style + +dotnet_naming_symbols.locals_and_parameters.applicable_kinds = parameter, local + +dotnet_naming_style.camel_case_style.capitalization = camel_case + +# Local functions are PascalCase +dotnet_naming_rule.local_functions_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.local_functions_should_be_pascal_case.symbols = local_functions +dotnet_naming_rule.local_functions_should_be_pascal_case.style = local_function_style + +dotnet_naming_symbols.local_functions.applicable_kinds = local_function + +dotnet_naming_style.local_function_style.capitalization = pascal_case + +# By default, name items with PascalCase +dotnet_naming_rule.members_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.members_should_be_pascal_case.symbols = all_members +dotnet_naming_rule.members_should_be_pascal_case.style = pascal_case_style + +dotnet_naming_symbols.all_members.applicable_kinds = * + +dotnet_naming_style.pascal_case_style.capitalization = pascal_case + +# error RS2008: Enable analyzer release tracking for the analyzer project containing rule '{0}' +dotnet_diagnostic.RS2008.severity = none + +# IDE0035: Remove unreachable code +dotnet_diagnostic.IDE0035.severity = warning + +# IDE0036: Order modifiers +dotnet_diagnostic.IDE0036.severity = warning + +# IDE0043: Format string contains invalid placeholder +dotnet_diagnostic.IDE0043.severity = warning + +# IDE0044: Make field readonly +dotnet_diagnostic.IDE0044.severity = warning + +# CONSIDER: Are IDE0051 and IDE0052 too noisy to be warnings for IDE editing scenarios? Should they be made build-only warnings? +# IDE0051: Remove unused private member +dotnet_diagnostic.IDE0051.severity = warning + +# IDE0170: Prefer extended property pattern +dotnet_diagnostic.IDE0170.severity = warning + +# RS0016: Only enable if API files are present +dotnet_public_api_analyzer.require_api_files = true + +# CSharp code style settings: +[*.cs] +# Newline settings +csharp_new_line_before_open_brace = all +csharp_new_line_before_else = true +csharp_new_line_before_catch = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_between_query_expression_clauses = true + +# Indentation preferences +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = true +csharp_indent_switch_labels = true +csharp_indent_labels = flush_left + +# Whitespace options +csharp_style_allow_embedded_statements_on_same_line_experimental = false +csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false +csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = false + +# Prefer "var" everywhere +csharp_style_var_for_built_in_types = true:suggestion +csharp_style_var_when_type_is_apparent = true:suggestion +csharp_style_var_elsewhere = true:suggestion + +# Prefer method-like constructs to have a block body +csharp_style_expression_bodied_methods = false:none +csharp_style_expression_bodied_constructors = false:none +csharp_style_expression_bodied_operators = false:none + +# Prefer property-like constructs to have an expression-body +csharp_style_expression_bodied_properties = true:none +csharp_style_expression_bodied_indexers = true:none +csharp_style_expression_bodied_accessors = true:none + +# Suggest more modern language features when available +csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion +csharp_style_pattern_matching_over_as_with_null_check = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion +csharp_style_throw_expression = true:suggestion +csharp_style_conditional_delegate_call = true:suggestion +csharp_style_prefer_extended_property_pattern = true:suggestion + +# Space preferences +csharp_space_after_cast = false +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_after_comma = true +csharp_space_after_dot = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_after_semicolon_in_for_statement = true +csharp_space_around_binary_operators = before_and_after +csharp_space_around_declaration_statements = do_not_ignore +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_before_comma = false +csharp_space_before_dot = false +csharp_space_before_open_square_brackets = false +csharp_space_before_semicolon_in_for_statement = false +csharp_space_between_empty_square_brackets = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_name_and_open_parenthesis = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_between_square_brackets = false + +# Blocks are allowed +csharp_prefer_braces = true:silent +csharp_preserve_single_line_blocks = true +csharp_preserve_single_line_statements = true + +# Currently only enabled for C# due to crash in VB analyzer. VB can be enabled once +# https://github.com/dotnet/roslyn/pull/54259 has been published. +dotnet_style_allow_statement_immediately_after_block_experimental = false + +[src/{Analyzers,CodeStyle,Features,Workspaces,EditorFeatures,VisualStudio}/**/*.{cs,vb}] + +# IDE0011: Add braces +csharp_prefer_braces = when_multiline:warning +# NOTE: We need the below severity entry for Add Braces due to https://github.com/dotnet/roslyn/issues/44201 +dotnet_diagnostic.IDE0011.severity = warning + +# IDE0040: Add accessibility modifiers +dotnet_diagnostic.IDE0040.severity = warning + +# IDE0052: Remove unread private member +dotnet_diagnostic.IDE0052.severity = warning + +# IDE0059: Unnecessary assignment to a value +dotnet_diagnostic.IDE0059.severity = warning + +# IDE0060: Remove unused parameter +dotnet_diagnostic.IDE0060.severity = warning + +# CA1012: Abstract types should not have public constructors +dotnet_diagnostic.CA1012.severity = warning + +# CA1822: Make member static +dotnet_diagnostic.CA1822.severity = warning + +# Prefer "var" everywhere +dotnet_diagnostic.IDE0007.severity = warning +csharp_style_var_for_built_in_types = true:warning +csharp_style_var_when_type_is_apparent = true:warning +csharp_style_var_elsewhere = true:warning + +# dotnet_style_allow_multiple_blank_lines_experimental +dotnet_diagnostic.IDE2000.severity = warning + +# csharp_style_allow_embedded_statements_on_same_line_experimental +dotnet_diagnostic.IDE2001.severity = warning + +# csharp_style_allow_blank_lines_between_consecutive_braces_experimental +dotnet_diagnostic.IDE2002.severity = warning + +# dotnet_style_allow_statement_immediately_after_block_experimental +dotnet_diagnostic.IDE2003.severity = warning + +# csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental +dotnet_diagnostic.IDE2004.severity = warning + +[src/{VisualStudio}/**/*.{cs,vb}] +# CA1822: Make member static +# There is a risk of accidentally breaking an internal API that partners rely on though IVT. +dotnet_code_quality.CA1822.api_surface = private diff --git a/src/SharpYaml.Tests/DescriptorTests.cs b/src/SharpYaml.Tests/DescriptorTests.cs index 980d6499..9cad052e 100644 --- a/src/SharpYaml.Tests/DescriptorTests.cs +++ b/src/SharpYaml.Tests/DescriptorTests.cs @@ -126,7 +126,7 @@ public void TestObjectDescriptor() "Value" }); - var instance = new TestObject {Name = "Yes", Property = "property"}; + var instance = new TestObject { Name = "Yes", Property = "property" }; // Check field accessor Assert.AreEqual("Yes", descriptor["Name"].Get(instance)); @@ -281,4 +281,4 @@ public void TestPrimitiveDescriptor() Assert.False(PrimitiveDescriptor.IsPrimitive(typeof(IList))); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml.Tests/Dump.cs b/src/SharpYaml.Tests/Dump.cs index 732a626d..f3716ebf 100644 --- a/src/SharpYaml.Tests/Dump.cs +++ b/src/SharpYaml.Tests/Dump.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -70,7 +70,7 @@ public static void WriteLine() [Conditional("TEST_DUMP")] public static void WriteLine(string value) { - WriteLine((object) value); + WriteLine((object)value); } [Conditional("TEST_DUMP")] @@ -85,4 +85,4 @@ public static void WriteLine(string format, params object[] args) Debug.WriteLine(format, args); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml.Tests/EmitterTests.cs b/src/SharpYaml.Tests/EmitterTests.cs index b5c9e801..77e4fbd3 100644 --- a/src/SharpYaml.Tests/EmitterTests.cs +++ b/src/SharpYaml.Tests/EmitterTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -170,7 +170,7 @@ public void EmitUnicodeEscapes() var encoding = new UTF8Encoding(false); var stream = new MemoryStream(); var input = "Test\U00010905Yo♥"; - using (var writer = new StreamWriter(stream, encoding) ) + using (var writer = new StreamWriter(stream, encoding)) { var emitter = new Emitter(writer); emitter.Emit(new StreamStart()); @@ -263,8 +263,8 @@ public void FoldedStyleDoesNotGenerateExtraLineBreaks() // Todo: Why involve the rep. model when testing the Emitter? Can we match using a regex? var stream = new YamlStream(); stream.Load(new StringReader(yaml)); - var sequence = (YamlSequenceNode) stream.Documents[0].RootNode; - var scalar = (YamlScalarNode) sequence.Children[0]; + var sequence = (YamlSequenceNode)stream.Documents[0].RootNode; + var scalar = (YamlScalarNode)sequence.Children[0]; Assert.AreEqual("hello\nworld", scalar.Value); } @@ -277,8 +277,8 @@ public void FoldedStyleDoesNotCollapseLineBreaks() var stream = new YamlStream(); stream.Load(new StringReader(yaml)); - var sequence = (YamlSequenceNode) stream.Documents[0].RootNode; - var scalar = (YamlScalarNode) sequence.Children[0]; + var sequence = (YamlSequenceNode)stream.Documents[0].RootNode; + var scalar = (YamlScalarNode)sequence.Children[0]; Assert.AreEqual(">+\n", scalar.Value); } @@ -299,12 +299,12 @@ public void FoldedStylePreservesNewLines() var stream = new YamlStream(); stream.Load(new StringReader(yaml)); - var mapping = (YamlMappingNode) stream.Documents[0].RootNode; - var value = (YamlScalarNode) mapping.Children.First().Value; + var mapping = (YamlMappingNode)stream.Documents[0].RootNode; + var value = (YamlScalarNode)mapping.Children.First().Value; var output = value.Value; Dump.WriteLine(output); Assert.AreEqual(input, output); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml.Tests/InsertionQueueTests.cs b/src/SharpYaml.Tests/InsertionQueueTests.cs index c27d80f8..7c3d78c0 100644 --- a/src/SharpYaml.Tests/InsertionQueueTests.cs +++ b/src/SharpYaml.Tests/InsertionQueueTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -78,7 +78,7 @@ public void ShouldCorrectlyDequeueElementsAfterEnqueuing() WithTheRange(0, 10).Perform(queue.Enqueue); - Assert.AreEqual(new List() {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, OrderOfElementsIn(queue)); + Assert.AreEqual(new List() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, OrderOfElementsIn(queue)); } [Test] @@ -90,7 +90,7 @@ public void ShouldCorrectlyDequeueElementsWhenIntermixingEnqueuing() PerformTimes(5, queue.Dequeue); WithTheRange(10, 15).Perform(queue.Enqueue); - Assert.AreEqual(new List() {5, 6, 7, 8, 9, 10, 11, 12, 13, 14}, OrderOfElementsIn(queue)); + Assert.AreEqual(new List() { 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 }, OrderOfElementsIn(queue)); } [Test] @@ -113,7 +113,7 @@ public void ShouldCorrectlyDequeueElementsWhenInserting() WithTheRange(0, 10).Perform(queue.Enqueue); queue.Insert(5, 99); - Assert.AreEqual(new List() {0, 1, 2, 3, 4, 99, 5, 6, 7, 8, 9}, OrderOfElementsIn(queue)); + Assert.AreEqual(new List() { 0, 1, 2, 3, 4, 99, 5, 6, 7, 8, 9 }, OrderOfElementsIn(queue)); } private static InsertionQueue CreateQueue() @@ -159,4 +159,4 @@ public static void Perform(this IEnumerable withRange, Action action) } } } -} \ No newline at end of file +} diff --git a/src/SharpYaml.Tests/LookAheadBufferTests.cs b/src/SharpYaml.Tests/LookAheadBufferTests.cs index 93d5a076..30fb38b5 100644 --- a/src/SharpYaml.Tests/LookAheadBufferTests.cs +++ b/src/SharpYaml.Tests/LookAheadBufferTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -256,4 +256,4 @@ private static LookAheadBuffer CreateBuffer(TextReader reader, int capacity) return new LookAheadBuffer(reader, capacity); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml.Tests/ParserTestHelper.cs b/src/SharpYaml.Tests/ParserTestHelper.cs index 41273b26..dde90b41 100644 --- a/src/SharpYaml.Tests/ParserTestHelper.cs +++ b/src/SharpYaml.Tests/ParserTestHelper.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -157,4 +157,4 @@ protected AnchorAlias AnchorAlias(string alias) return new AnchorAlias(alias); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml.Tests/ParserTests.cs b/src/SharpYaml.Tests/ParserTests.cs index d2da5362..79ed31cc 100644 --- a/src/SharpYaml.Tests/ParserTests.cs +++ b/src/SharpYaml.Tests/ParserTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -364,19 +364,19 @@ private void AssertEvent(ParsingEvent expected, ParsingEvent actual, int eventNu if (expectedValue is IEnumerable && !(expectedValue is string)) { Dump.Write("\t{0} = {{", property.Name); - Dump.Write(string.Join(", ", (IEnumerable) value)); + Dump.Write(string.Join(", ", (IEnumerable)value)); Dump.WriteLine("}"); if (expectedValue is ICollection && value is ICollection) { - var expectedCount = ((ICollection) expectedValue).Count; - var valueCount = ((ICollection) value).Count; + var expectedCount = ((ICollection)expectedValue).Count; + var valueCount = ((ICollection)value).Count; Assert.AreEqual(expectedCount, valueCount, "Compared size of collections in property {0} in parse event {1}", property.Name, eventNumber); } - var values = ((IEnumerable) value).GetEnumerator(); - var expectedValues = ((IEnumerable) expectedValue).GetEnumerator(); + var values = ((IEnumerable)value).GetEnumerator(); + var expectedValues = ((IEnumerable)expectedValue).GetEnumerator(); while (expectedValues.MoveNext()) { Assert.True(values.MoveNext(), "Property {0} in parse event {1} had too few elements", property.Name, eventNumber); @@ -393,4 +393,4 @@ private void AssertEvent(ParsingEvent expected, ParsingEvent actual, int eventNu } } } -} \ No newline at end of file +} diff --git a/src/SharpYaml.Tests/PathTrieTest.cs b/src/SharpYaml.Tests/PathTrieTest.cs index f9cb8ca3..6ed1ecc2 100644 --- a/src/SharpYaml.Tests/PathTrieTest.cs +++ b/src/SharpYaml.Tests/PathTrieTest.cs @@ -4,10 +4,13 @@ using Path = SharpYaml.Model.Path; using YamlStream = SharpYaml.Model.YamlStream; -namespace SharpYaml.Tests { - public class PathTrieTest { +namespace SharpYaml.Tests +{ + public class PathTrieTest + { [Test] - public void BasicTest() { + public void BasicTest() + { var trie = new PathTrie(); var root = new YamlStream(); var path = new Path(root, new[] { @@ -15,12 +18,12 @@ public void BasicTest() { new ChildIndex(-1, false), new ChildIndex(2, false) }); - + trie.Add(path); - + Assert.IsTrue(trie.Contains(path, false)); Assert.IsTrue(trie.Contains(path, true)); - + Assert.IsFalse(trie.Contains(path.GetParentPath().Value, false)); Assert.IsTrue(trie.Contains(path.GetParentPath().Value, true)); @@ -31,10 +34,10 @@ public void BasicTest() { Assert.IsFalse(trie.Contains(childPath, true)); var subPaths = trie.GetSubpaths(path).ToList(); - + Assert.AreEqual(1, subPaths.Count); Assert.AreEqual(path, subPaths[0]); - + trie.Add(childPath); Assert.IsTrue(trie.Contains(childPath, false)); @@ -56,7 +59,7 @@ public void BasicTest() { Assert.IsFalse(trie.Contains(path, false)); Assert.IsTrue(trie.Contains(path, true)); Assert.IsTrue(trie.Contains(childPath, false)); - + trie.Add(path); result = trie.Remove(path, true); @@ -66,4 +69,4 @@ public void BasicTest() { Assert.IsFalse(trie.Contains(childPath, false)); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml.Tests/ScannerTestHelper.cs b/src/SharpYaml.Tests/ScannerTestHelper.cs index 1693f254..369bd05e 100644 --- a/src/SharpYaml.Tests/ScannerTestHelper.cs +++ b/src/SharpYaml.Tests/ScannerTestHelper.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -129,4 +129,4 @@ protected static AnchorAlias AnchorAlias(string alias) return new AnchorAlias(alias); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml.Tests/ScannerTests.cs b/src/SharpYaml.Tests/ScannerTests.cs index 8f9b7b8e..232b75c4 100644 --- a/src/SharpYaml.Tests/ScannerTests.cs +++ b/src/SharpYaml.Tests/ScannerTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -330,7 +330,8 @@ public void VerifyTokensOnExample14() [Test] - public void VerifyTokensOnExample15() { + public void VerifyTokensOnExample15() + { AssertSequenceOfTokensFrom(ScannerFor("test15.yaml"), StreamStart, FlowMappingStart, @@ -387,4 +388,4 @@ private void AssertToken(Token expected, Token actual, int tokenNumber) } } } -} \ No newline at end of file +} diff --git a/src/SharpYaml.Tests/SchemaTests.cs b/src/SharpYaml.Tests/SchemaTests.cs index 88ef7dcd..9195f05d 100644 --- a/src/SharpYaml.Tests/SchemaTests.cs +++ b/src/SharpYaml.Tests/SchemaTests.cs @@ -157,4 +157,4 @@ private void TryParse(IYamlSchema schema, string scalar, string expectedShortTag Assert.AreEqual(expectedValue, value); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml.Tests/Serialization/ExceptionWithNestedSerialization.cs b/src/SharpYaml.Tests/Serialization/ExceptionWithNestedSerialization.cs index e1eb8cae..2b793483 100644 --- a/src/SharpYaml.Tests/Serialization/ExceptionWithNestedSerialization.cs +++ b/src/SharpYaml.Tests/Serialization/ExceptionWithNestedSerialization.cs @@ -54,15 +54,15 @@ public class ExceptionWithNestedSerialization [Test] public void NestedDocumentShouldDeserializeProperly() { - var serializer = new Serializer(new SerializerSettings() {EmitDefaultValues = true}); + var serializer = new Serializer(new SerializerSettings() { EmitDefaultValues = true }); // serialize AMessage var tw = new StringWriter(); - serializer.Serialize(tw, new AMessage {Payload = new PayloadA {X = 5, Y = 6}}); + serializer.Serialize(tw, new AMessage { Payload = new PayloadA { X = 5, Y = 6 } }); Dump.WriteLine(tw); // stick serialized AMessage in envelope and serialize it - var e = new Env {Type = "some-type", Payload = tw.ToString()}; + var e = new Env { Type = "some-type", Payload = tw.ToString() }; tw = new StringWriter(); serializer.Serialize(tw, e); @@ -107,4 +107,4 @@ public class AMessage : Message { } } -} \ No newline at end of file +} diff --git a/src/SharpYaml.Tests/Serialization/ObjectFactoryTests.cs b/src/SharpYaml.Tests/Serialization/ObjectFactoryTests.cs index 47f9624b..3e1ec86c 100644 --- a/src/SharpYaml.Tests/Serialization/ObjectFactoryTests.cs +++ b/src/SharpYaml.Tests/Serialization/ObjectFactoryTests.cs @@ -86,4 +86,4 @@ public void ObjectFactoryIsInvoked() Assert.IsInstanceOf(result); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml.Tests/Serialization/Samples.cs b/src/SharpYaml.Tests/Serialization/Samples.cs index 3dcf5b05..7abf92be 100644 --- a/src/SharpYaml.Tests/Serialization/Samples.cs +++ b/src/SharpYaml.Tests/Serialization/Samples.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -63,11 +63,11 @@ public void LoadYamlStream() yaml.Load(input); // Examine the stream - var mapping = (YamlMappingNode) yaml.Documents[0].RootNode; + var mapping = (YamlMappingNode)yaml.Documents[0].RootNode; foreach (var entry in mapping.Children) { - Console.WriteLine(((YamlScalarNode) entry.Key).Value); + Console.WriteLine(((YamlScalarNode)entry.Key).Value); } } @@ -105,4 +105,4 @@ Pay no attention to the man behind the curtain. ..."; } -} \ No newline at end of file +} diff --git a/src/SharpYaml.Tests/Serialization/SerializationTests.cs b/src/SharpYaml.Tests/Serialization/SerializationTests.cs index d45e0800..261c3af2 100644 --- a/src/SharpYaml.Tests/Serialization/SerializationTests.cs +++ b/src/SharpYaml.Tests/Serialization/SerializationTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -105,11 +105,11 @@ public void Roundtrip() [Test] public void RoundtripWithDefaults() - => Roundtrip(new SerializerSettings() {EmitDefaultValues = true}); + => Roundtrip(new SerializerSettings() { EmitDefaultValues = true }); [Test] public void RoundtripWithRespectPrivateSetters() - => Roundtrip(new SerializerSettings() {EmitDefaultValues = true}, true); + => Roundtrip(new SerializerSettings() { EmitDefaultValues = true }, true); [Test] public void RoundtripFloatingPointEdgeCases() @@ -124,7 +124,7 @@ public void RoundtripNoPrivateSetters() var modified = new PrivateSetters(); modified.ModifyPrivateProperties(); - + var buffer = new StringWriter(); serializer.Serialize(buffer, modified); @@ -189,7 +189,7 @@ public void DeserializeExplicitType() object result = serializer.Deserialize(YamlFile("explicitType.yaml"), typeof(object)); Assert.True(typeof(Z).IsAssignableFrom(result.GetType())); - Assert.AreEqual("bbb", ((Z) result).aaa); + Assert.AreEqual("bbb", ((Z)result).aaa); } [Test] @@ -200,7 +200,7 @@ public void DeserializeDictionary() Assert.True(typeof(IDictionary).IsAssignableFrom(result.GetType()), "The deserialized object has the wrong type."); - var dictionary = (IDictionary) result; + var dictionary = (IDictionary)result; Assert.AreEqual("value1", dictionary["key1"]); Assert.AreEqual("value2", dictionary["key2"]); } @@ -213,7 +213,7 @@ public void DeserializeExplicitDictionary() Assert.True(typeof(IDictionary).IsAssignableFrom(result.GetType()), "The deserialized object has the wrong type."); - var dictionary = (IDictionary) result; + var dictionary = (IDictionary)result; Assert.AreEqual(1, dictionary["key1"]); Assert.AreEqual(2, dictionary["key2"]); } @@ -226,7 +226,7 @@ public void DeserializeListOfDictionaries() Assert.IsInstanceOf>>(result); - var list = (List>) result; + var list = (List>)result; Assert.AreEqual("conn1", list[0]["connection"]); Assert.AreEqual("path1", list[0]["path"]); Assert.AreEqual("conn2", list[1]["connection"]); @@ -241,7 +241,7 @@ public void DeserializeList() Assert.True(typeof(IList).IsAssignableFrom(result.GetType())); - var list = (IList) result; + var list = (IList)result; Assert.AreEqual("one", list[0]); Assert.AreEqual("two", list[1]); Assert.AreEqual("three", list[2]); @@ -255,7 +255,7 @@ public void DeserializeExplicitList() Assert.True(typeof(IList).IsAssignableFrom(result.GetType())); - var list = (IList) result; + var list = (IList)result; Assert.AreEqual(3, list[0]); Assert.AreEqual(4, list[1]); Assert.AreEqual(5, list[2]); @@ -269,11 +269,11 @@ public void DeserializeEnumerable() var serializer = new Serializer(settings); var buffer = new StringWriter(); - var z = new[] {new Z {aaa = "Yo"}}; + var z = new[] { new Z { aaa = "Yo" } }; serializer.Serialize(buffer, z); var bufferAsText = buffer.ToString(); - var result = (IEnumerable) serializer.Deserialize(bufferAsText, typeof(IEnumerable)); + var result = (IEnumerable)serializer.Deserialize(bufferAsText, typeof(IEnumerable)); Assert.AreEqual(1, result.Count()); Assert.AreEqual("Yo", result.First().aaa); } @@ -284,12 +284,12 @@ public void RoundtripList() var serializer = new Serializer(); var buffer = new StringWriter(); - var original = new List {2, 4, 6}; + var original = new List { 2, 4, 6 }; serializer.Serialize(buffer, original, typeof(List)); Dump.WriteLine(buffer); - var copy = (List) serializer.Deserialize(new StringReader(buffer.ToString()), typeof(List)); + var copy = (List)serializer.Deserialize(new StringReader(buffer.ToString()), typeof(List)); Assert.AreEqual(original.Count, copy.Count); @@ -307,7 +307,7 @@ public void DeserializeArray() Assert.True(result is String[]); - var array = (String[]) result; + var array = (String[])result; Assert.AreEqual("one", array[0]); Assert.AreEqual("two", array[1]); Assert.AreEqual("three", array[2]); @@ -326,7 +326,7 @@ public void Enums() serializer.Serialize(buffer, flags); var bufferAsText = buffer.ToString(); - var deserialized = (BindingFlags) serializer.Deserialize(bufferAsText, typeof(BindingFlags)); + var deserialized = (BindingFlags)serializer.Deserialize(bufferAsText, typeof(BindingFlags)); Assert.AreEqual(flags, deserialized); } @@ -341,7 +341,7 @@ public void CustomTags() Assert.AreEqual(typeof(Point), result.GetType()); - var value = (Point) result; + var value = (Point)result; Assert.AreEqual(10, value.X); Assert.AreEqual(20, value.Y); } @@ -403,7 +403,7 @@ public override object ConvertFrom(ref ObjectContext context, Scalar fromScalar) public override string ConvertTo(ref ObjectContext objectContext) { - return ((SomeCustomType) objectContext.Instance).Value; + return ((SomeCustomType)objectContext.Instance).Value; } } @@ -434,7 +434,7 @@ public void RoundtripDictionary() [Test] public void SerializeAnonymousType() { - var data = new {Key = 3}; + var data = new { Key = 3 }; var serializer = new Serializer(); @@ -455,7 +455,7 @@ public void SerializeAnonymousType() [Test] public void SerializationIncludesDefaultValueWhenAsked() { - var settings = new SerializerSettings() {EmitDefaultValues = true}; + var settings = new SerializerSettings() { EmitDefaultValues = true }; settings.RegisterAssembly(typeof(X).Assembly); var serializer = new Serializer(settings); @@ -471,7 +471,7 @@ public void SerializationIncludesDefaultValueWhenAsked() [Test] public void SerializationDoesNotIncludeDefaultValueWhenNotAsked() { - var settings = new SerializerSettings() {EmitDefaultValues = false}; + var settings = new SerializerSettings() { EmitDefaultValues = false }; settings.RegisterAssembly(typeof(X).Assembly); var serializer = new Serializer(settings); @@ -488,12 +488,12 @@ public void SerializationDoesNotIncludeDefaultValueWhenNotAsked() [Test] public void SerializationOfNullWorksInJson() { - var settings = new SerializerSettings() {EmitDefaultValues = true, EmitJsonComptible = true}; + var settings = new SerializerSettings() { EmitDefaultValues = true, EmitJsonComptible = true }; settings.RegisterAssembly(typeof(X).Assembly); var serializer = new Serializer(settings); var buffer = new StringWriter(); - var original = new X {MyString = null}; + var original = new X { MyString = null }; serializer.Serialize(buffer, original, typeof(X)); Dump.WriteLine(buffer); @@ -502,13 +502,14 @@ public void SerializationOfNullWorksInJson() } [Test] - public void JsonKeysAreQuoted() { + public void JsonKeysAreQuoted() + { var settings = new SerializerSettings() { EmitDefaultValues = true, EmitJsonComptible = true, EmitTags = false }; var serializer = new Serializer(settings); var buffer = new StringWriter(); - - serializer.Serialize(buffer, new Dictionary {{ 5, 10 } }); + + serializer.Serialize(buffer, new Dictionary { { 5, 10 } }); Dump.WriteLine(buffer); var bufferText = buffer.ToString(); @@ -523,18 +524,18 @@ public void JsonKeysAreQuoted() { [Test] public void DeserializationOfNullWorksInJson() { - var settings = new SerializerSettings() {EmitDefaultValues = true, EmitJsonComptible = true}; + var settings = new SerializerSettings() { EmitDefaultValues = true, EmitJsonComptible = true }; settings.RegisterAssembly(typeof(X).Assembly); var serializer = new Serializer(settings); var buffer = new StringWriter(); - var original = new X {MyString = null}; + var original = new X { MyString = null }; serializer.Serialize(buffer, original, typeof(X)); Dump.WriteLine(buffer); var bufferText = buffer.ToString(); - var copy = (X) serializer.Deserialize(bufferText, typeof(X)); + var copy = (X)serializer.Deserialize(bufferText, typeof(X)); Assert.Null(copy.MyString); } @@ -552,7 +553,7 @@ public void SerializationRespectsYamlIgnoreAttribute() Dump.WriteLine(buffer); - var copy = (ContainsIgnore) serializer.Deserialize(new StringReader(buffer.ToString()), typeof(ContainsIgnore)); + var copy = (ContainsIgnore)serializer.Deserialize(new StringReader(buffer.ToString()), typeof(ContainsIgnore)); Assert.Throws(() => { @@ -571,9 +572,9 @@ class ContainsIgnore [Test] public void SerializeArrayOfIdenticalObjects() { - var obj1 = new Z {aaa = "abc"}; + var obj1 = new Z { aaa = "abc" }; - var objects = new[] {obj1, obj1, obj1}; + var objects = new[] { obj1, obj1, obj1 }; var result = SerializeThenDeserialize(objects); @@ -606,7 +607,7 @@ public class Z [Test] public void RoundtripAlias() { - var input = new ConventionTest {AliasTest = "Fourth"}; + var input = new ConventionTest { AliasTest = "Fourth" }; var serializer = new Serializer(); var writer = new StringWriter(); serializer.Serialize(writer, input, input.GetType()); @@ -642,7 +643,7 @@ private class ConventionTest [Test] public void DefaultValueAttributeIsUsedWhenPresentWithoutEmitDefaults() { - var input = new HasDefaults {Value = HasDefaults.DefaultValue}; + var input = new HasDefaults { Value = HasDefaults.DefaultValue }; var serializer = new Serializer(); var writer = new StringWriter(); @@ -656,8 +657,8 @@ public void DefaultValueAttributeIsUsedWhenPresentWithoutEmitDefaults() [Test] public void DefaultValueAttributeIsIgnoredWhenPresentWithEmitDefaults() { - var input = new HasDefaults {Value = HasDefaults.DefaultValue}; - var serializer = new Serializer(new SerializerSettings() {EmitDefaultValues = true}); + var input = new HasDefaults { Value = HasDefaults.DefaultValue }; + var serializer = new Serializer(new SerializerSettings() { EmitDefaultValues = true }); var writer = new StringWriter(); serializer.Serialize(writer, input); @@ -670,7 +671,7 @@ public void DefaultValueAttributeIsIgnoredWhenPresentWithEmitDefaults() [Test] public void DefaultValueAttributeIsIgnoredWhenValueIsDifferent() { - var input = new HasDefaults {Value = "non-default"}; + var input = new HasDefaults { Value = "non-default" }; var serializer = new Serializer(); var writer = new StringWriter(); @@ -693,8 +694,8 @@ public class HasDefaults [Test] public void NullValuesInListsAreAlwaysEmittedWithoutEmitDefaults() { - var input = new[] {"foo", null, "bar"}; - var serializer = new Serializer(new SerializerSettings() {LimitPrimitiveFlowSequence = 0}); + var input = new[] { "foo", null, "bar" }; + var serializer = new Serializer(new SerializerSettings() { LimitPrimitiveFlowSequence = 0 }); var writer = new StringWriter(); serializer.Serialize(writer, input); @@ -707,8 +708,8 @@ public void NullValuesInListsAreAlwaysEmittedWithoutEmitDefaults() [Test] public void NullValuesInListsAreAlwaysEmittedWithEmitDefaults() { - var input = new[] {"foo", null, "bar"}; - var serializer = new Serializer(new SerializerSettings() {EmitDefaultValues = true, LimitPrimitiveFlowSequence = 0}); + var input = new[] { "foo", null, "bar" }; + var serializer = new Serializer(new SerializerSettings() { EmitDefaultValues = true, LimitPrimitiveFlowSequence = 0 }); var writer = new StringWriter(); serializer.Serialize(writer, input); @@ -783,7 +784,7 @@ public class ExtendedPerson public void DeserializeIntoExisting() { var serializer = new Serializer(); - var andy = new ExtendedPerson {Name = "Not Andy", Age = 30}; + var andy = new ExtendedPerson { Name = "Not Andy", Age = 30 }; var yaml = @"--- Name: Andy ..."; @@ -791,8 +792,8 @@ public void DeserializeIntoExisting() Assert.AreEqual("Andy", andy.Name); Assert.AreEqual(30, andy.Age); - andy = new ExtendedPerson {Name = "Not Andy", Age = 30}; - andy = (ExtendedPerson) serializer.Deserialize(yaml, typeof(ExtendedPerson), andy); + andy = new ExtendedPerson { Name = "Not Andy", Age = 30 }; + andy = (ExtendedPerson)serializer.Deserialize(yaml, typeof(ExtendedPerson), andy); Assert.AreEqual("Andy", andy.Name); Assert.AreEqual(30, andy.Age); } @@ -801,12 +802,12 @@ public void DeserializeIntoExisting() public void DeserializeWithExistingObject() { var serializer = new Serializer(); - var andy = new ExtendedPerson {Name = "Not Andy", Age = 30}; + var andy = new ExtendedPerson { Name = "Not Andy", Age = 30 }; var yaml = @"--- Name: Andy ..."; - andy = new ExtendedPerson {Name = "Not Andy", Age = 30}; - andy = (ExtendedPerson) serializer.Deserialize(yaml, typeof(ExtendedPerson), andy); + andy = new ExtendedPerson { Name = "Not Andy", Age = 30 }; + andy = (ExtendedPerson)serializer.Deserialize(yaml, typeof(ExtendedPerson), andy); Assert.AreEqual("Andy", andy.Name); Assert.AreEqual(30, andy.Age); } @@ -821,9 +822,9 @@ public class Family public void DeserializeIntoExistingSubObjects() { var serializer = new Serializer(); - var andy = new ExtendedPerson {Name = "Not Andy", Age = 30}; - var amy = new ExtendedPerson {Name = "Amy", Age = 33}; - var family = new Family {Father = andy, Mother = amy}; + var andy = new ExtendedPerson { Name = "Not Andy", Age = 30 }; + var amy = new ExtendedPerson { Name = "Amy", Age = 33 }; + var family = new Family { Father = andy, Mother = amy }; var yaml = @"--- Mother: Name: Betty @@ -866,7 +867,7 @@ public void DeserializeWithRepeatedSubObjects() public void DeserializeEmptyDocument() { var serializer = new Serializer(); - var array = (int[]) serializer.Deserialize(new StringReader(""), typeof(int[])); + var array = (int[])serializer.Deserialize(new StringReader(""), typeof(int[])); Assert.Null(array); } @@ -886,7 +887,7 @@ private class OnlyGenericDictionary : IDictionary { private readonly Dictionary _dictionary = new Dictionary(); -#region IDictionary Members + #region IDictionary Members public void Add(string key, string value) { @@ -914,9 +915,9 @@ public bool TryGetValue(string key, out string value) public string this[string key] { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } -#endregion + #endregion -#region ICollection> Members + #region ICollection> Members public void Add(KeyValuePair item) { @@ -947,25 +948,25 @@ public bool Remove(KeyValuePair item) throw new NotImplementedException(); } -#endregion + #endregion -#region IEnumerable> Members + #region IEnumerable> Members public IEnumerator> GetEnumerator() { return _dictionary.GetEnumerator(); } -#endregion + #endregion -#region IEnumerable Members + #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return _dictionary.GetEnumerator(); } -#endregion + #endregion } [Test] @@ -1092,4 +1093,4 @@ public FloatingPointEdgeCases() } } } -} \ No newline at end of file +} diff --git a/src/SharpYaml.Tests/Serialization/SerializationTests2.cs b/src/SharpYaml.Tests/Serialization/SerializationTests2.cs index adc8afa0..f91e723a 100644 --- a/src/SharpYaml.Tests/Serialization/SerializationTests2.cs +++ b/src/SharpYaml.Tests/Serialization/SerializationTests2.cs @@ -77,7 +77,7 @@ public enum MyEnumWithFlags public void TestHelloWorld() { var serializer = new Serializer(); - var text = serializer.Serialize(new {List = new List() {1, 2, 3}, Name = "Hello", Value = "World!"}); + var text = serializer.Serialize(new { List = new List() { 1, 2, 3 }, Name = "Hello", Value = "World!" }); Console.WriteLine(text); Assert.AreEqual(@"List: - 1 @@ -137,8 +137,8 @@ public TestStructWithDefaultValues() public void TestSimpleStruct() { var serializer = new Serializer(); - var value = (TestStructColor) serializer.Deserialize(@"Color: {R: 255, G: 255, B: 255, A: 255}", typeof(TestStructColor)); - Assert.AreEqual(new Color() {R = 255, G = 255, B = 255, A = 255}, value.Color); + var value = (TestStructColor)serializer.Deserialize(@"Color: {R: 255, G: 255, B: 255, A: 255}", typeof(TestStructColor)); + Assert.AreEqual(new Color() { R = 255, G = 255, B = 255, A = 255 }, value.Color); var text = serializer.Serialize(value, typeof(TestStructColor)); Assert.AreEqual(@"Color: A: 255 @@ -163,9 +163,9 @@ public void TestSimpleStructWithDefaultValues() [Test] public void TestSimpleStructMemberOrdering() { - var settings = new SerializerSettings() {ComparerForKeySorting = null}; + var settings = new SerializerSettings() { ComparerForKeySorting = null }; var serializer = new Serializer(settings); - var value = new TestStructColor() {Color = new Color() {R = 255, G = 255, B = 255, A = 255}}; + var value = new TestStructColor() { Color = new Color() { R = 255, G = 255, B = 255, A = 255 } }; var text = serializer.Serialize(value, typeof(TestStructColor)); Assert.AreEqual(@"Color: R: 255 @@ -258,7 +258,7 @@ public void TestSimpleObjectAndPrimitive() UInt32: 6 UInt64: 8 ".Trim(); - var settings = new SerializerSettings() {LimitPrimitiveFlowSequence = 20}; + var settings = new SerializerSettings() { LimitPrimitiveFlowSequence = 20 }; settings.RegisterTagMapping("MyObject", typeof(MyObject)); SerialRoundTrip(settings, text); } @@ -283,7 +283,7 @@ public override object Get(object thisObject) public override void Set(object thisObject, object value) { - DynamicIds[thisObject] = (int) value; + DynamicIds[thisObject] = (int)value; } public override bool HasSet { get { return true; } } @@ -315,7 +315,7 @@ public void TestDynamicMember() // Make sure that the dynamic member is actually round trip copied Assert.True(dynamicMember.DynamicIds.ContainsKey(myObject1)); - Assert.AreEqual((object) 16, dynamicMember.DynamicIds[myObject1]); + Assert.AreEqual((object)16, dynamicMember.DynamicIds[myObject1]); } public class ObjectFloatDoublePrecision @@ -328,7 +328,7 @@ public class ObjectFloatDoublePrecision [Test] public void TestFloatDoublePrecision() { - var settings = new SerializerSettings() {LimitPrimitiveFlowSequence = 20}; + var settings = new SerializerSettings() { LimitPrimitiveFlowSequence = 20 }; settings.RegisterTagMapping("ObjectFloatDoublePrecision", typeof(ObjectFloatDoublePrecision)); var text = @"!ObjectFloatDoublePrecision @@ -357,7 +357,7 @@ public class ObjectFloatDoubleNaNInfinity [Test] public void TestFloatDoubleNaNInfinity() { - var settings = new SerializerSettings() {LimitPrimitiveFlowSequence = 20}; + var settings = new SerializerSettings() { LimitPrimitiveFlowSequence = 20 }; settings.RegisterTagMapping("ObjectFloatDoubleNaNInfinity", typeof(ObjectFloatDoubleNaNInfinity)); var text = @"!ObjectFloatDoubleNaNInfinity @@ -396,7 +396,7 @@ public void TestObjectWithCollection() Values: [a, b, c] ".Trim(); - var settings = new SerializerSettings() {LimitPrimitiveFlowSequence = 20}; + var settings = new SerializerSettings() { LimitPrimitiveFlowSequence = 20 }; settings.RegisterTagMapping("MyObjectAndCollection", typeof(MyObjectAndCollection)); SerialRoundTrip(settings, text); } @@ -427,7 +427,7 @@ public void TestCustomCollectionWithProperties() - c ".Trim(); - var settings = new SerializerSettings() {LimitPrimitiveFlowSequence = 0}; + var settings = new SerializerSettings() { LimitPrimitiveFlowSequence = 0 }; settings.RegisterTagMapping("MyCustomCollectionWithProperties", typeof(MyCustomCollectionWithProperties)); SerialRoundTrip(settings, text); } @@ -460,7 +460,7 @@ public void TestCustomDictionaryWithProperties() c: true ".Trim(); - var settings = new SerializerSettings() {LimitPrimitiveFlowSequence = 0}; + var settings = new SerializerSettings() { LimitPrimitiveFlowSequence = 0 }; settings.RegisterTagMapping("MyCustomDictionaryWithProperties", typeof(MyCustomDictionaryWithProperties)); SerialRoundTrip(settings, text); } @@ -481,7 +481,7 @@ public void TestCustomDictionaryWithItemsAsMembers() c: true ".Trim(); - var settings = new SerializerSettings() {LimitPrimitiveFlowSequence = 0, SerializeDictionaryItemsAsMembers = true}; + var settings = new SerializerSettings() { LimitPrimitiveFlowSequence = 0, SerializeDictionaryItemsAsMembers = true }; settings.RegisterTagMapping("MyCustomDictionaryWithProperties", typeof(MyCustomDictionaryWithProperties)); SerialRoundTrip(settings, text); } @@ -583,7 +583,7 @@ public void TestMyCustomClassWithSpecialMembers() Value: 0 ".Trim(); - var settings = new SerializerSettings() {LimitPrimitiveFlowSequence = 0}; + var settings = new SerializerSettings() { LimitPrimitiveFlowSequence = 0 }; settings.RegisterTagMapping("MyCustomClassWithSpecialMembers", typeof(MyCustomClassWithSpecialMembers)); SerialRoundTrip(settings, text); } @@ -641,7 +641,7 @@ public ClassMemberOrder() [Test] public void TestClassMemberOrder() { - var settings = new SerializerSettings() {LimitPrimitiveFlowSequence = 0}; + var settings = new SerializerSettings() { LimitPrimitiveFlowSequence = 0 }; settings.RegisterTagMapping("ClassMemberOrder", typeof(ClassMemberOrder)); SerialRoundTrip(settings, new ClassMemberOrder()); } @@ -681,7 +681,7 @@ public ClassWithObjectAndScalar() Value1 = 1; Value2 = 2.0f; Value3 = "3"; - Value4 = (byte) 4; + Value4 = (byte)4; } public object Value1; @@ -696,7 +696,7 @@ public ClassWithObjectAndScalar() [Test] public void TestClassWithObjectAndScalar() { - var settings = new SerializerSettings() {LimitPrimitiveFlowSequence = 0}; + var settings = new SerializerSettings() { LimitPrimitiveFlowSequence = 0 }; settings.RegisterTagMapping("ClassWithObjectAndScalar", typeof(ClassWithObjectAndScalar)); SerialRoundTrip(settings, new ClassWithObjectAndScalar()); } @@ -705,17 +705,17 @@ public void TestClassWithObjectAndScalar() [Test] public void TestNoEmitTags() { - var settings = new SerializerSettings() {EmitTags = false}; + var settings = new SerializerSettings() { EmitTags = false }; settings.RegisterTagMapping("ClassWithObjectAndScalar", typeof(ClassWithObjectAndScalar)); var serializer = new Serializer(settings); - var text = serializer.Serialize(new ClassWithObjectAndScalar {Value4 = new ClassWithObjectAndScalar()}); + var text = serializer.Serialize(new ClassWithObjectAndScalar { Value4 = new ClassWithObjectAndScalar() }); Assert.False(text.Contains("!")); } [Test] public void TestImplicitDictionaryAndList() { - var settings = new SerializerSettings() {LimitPrimitiveFlowSequence = 0}; + var settings = new SerializerSettings() { LimitPrimitiveFlowSequence = 0 }; var text = @"BasicList: - 1 @@ -766,14 +766,14 @@ public override bool Equals(object obj) return true; if (obj.GetType() != this.GetType()) return false; - return Equals((MemberInterface) obj); + return Equals((MemberInterface)obj); } public override int GetHashCode() { unchecked { - return ((Name != null ? Name.GetHashCode() : 0)*397) ^ (Value != null ? Value.GetHashCode() : 0); + return ((Name != null ? Name.GetHashCode() : 0) * 397) ^ (Value != null ? Value.GetHashCode() : 0); } } @@ -810,14 +810,14 @@ public override bool Equals(object obj) return true; if (obj.GetType() != this.GetType()) return false; - return Equals((MemberObject) obj); + return Equals((MemberObject)obj); } public override int GetHashCode() { unchecked { - return (base.GetHashCode()*397) ^ (Object != null ? Object.GetHashCode() : 0); + return (base.GetHashCode() * 397) ^ (Object != null ? Object.GetHashCode() : 0); } } } @@ -826,10 +826,10 @@ public class ClassMemberWithInheritance { public ClassMemberWithInheritance() { - ThroughObject = new MemberObject() {Object = "throughObject"}; + ThroughObject = new MemberObject() { Object = "throughObject" }; ThroughInterface = new MemberInterface(); - ThroughBase = new MemberObject() {Object = "throughBase"}; - Direct = new MemberObject() {Object = "direct"}; + ThroughBase = new MemberObject() { Object = "throughBase" }; + Direct = new MemberObject() { Object = "direct" }; } public object ThroughObject { get; set; } @@ -853,7 +853,7 @@ public override bool Equals(object obj) return true; if (obj.GetType() != this.GetType()) return false; - return Equals((ClassMemberWithInheritance) obj); + return Equals((ClassMemberWithInheritance)obj); } public override int GetHashCode() @@ -861,9 +861,9 @@ public override int GetHashCode() unchecked { int hashCode = (ThroughObject != null ? ThroughObject.GetHashCode() : 0); - hashCode = (hashCode*397) ^ (ThroughInterface != null ? ThroughInterface.GetHashCode() : 0); - hashCode = (hashCode*397) ^ (ThroughBase != null ? ThroughBase.GetHashCode() : 0); - hashCode = (hashCode*397) ^ (Direct != null ? Direct.GetHashCode() : 0); + hashCode = (hashCode * 397) ^ (ThroughInterface != null ? ThroughInterface.GetHashCode() : 0); + hashCode = (hashCode * 397) ^ (ThroughBase != null ? ThroughBase.GetHashCode() : 0); + hashCode = (hashCode * 397) ^ (Direct != null ? Direct.GetHashCode() : 0); return hashCode; } } @@ -872,7 +872,7 @@ public override int GetHashCode() [Test] public void TestClassMemberWithInheritance() { - var settings = new SerializerSettings() {LimitPrimitiveFlowSequence = 0}; + var settings = new SerializerSettings() { LimitPrimitiveFlowSequence = 0 }; settings.RegisterTagMapping("ClassMemberWithInheritance", typeof(ClassMemberWithInheritance)); settings.RegisterTagMapping("MemberInterface", typeof(MemberInterface)); settings.RegisterTagMapping("MemberObject", typeof(MemberObject)); @@ -885,7 +885,7 @@ public void TestClassMemberWithInheritance() [Test] public void TestEmitShortTypeName() { - var settings = new SerializerSettings() {EmitShortTypeName = true}; + var settings = new SerializerSettings() { EmitShortTypeName = true }; SerialRoundTrip(settings, new ClassWithObjectAndScalar()); } @@ -899,7 +899,7 @@ public class ClassWithChars [Test] public void TestClassWithChars() { - var settings = new SerializerSettings() {EmitShortTypeName = true}; + var settings = new SerializerSettings() { EmitShortTypeName = true }; SerialRoundTrip(settings, new ClassWithChars() { Start = ' ', @@ -910,13 +910,13 @@ public void TestClassWithChars() [Test] public void TestClassWithSpecialChars() { - var settings = new SerializerSettings() {EmitShortTypeName = true}; + var settings = new SerializerSettings() { EmitShortTypeName = true }; for (int i = 0; i < 32; i++) { SerialRoundTrip(settings, new ClassWithChars() { - Start = (char) i, - End = (char) (i + 1) + Start = (char)i, + End = (char)(i + 1) }); } } @@ -982,7 +982,7 @@ public override YamlStyle GetStyle(ref ObjectContext objectContext) [Test] public void TestStyles() { - var settings = new SerializerSettings() {LimitPrimitiveFlowSequence = 4}; + var settings = new SerializerSettings() { LimitPrimitiveFlowSequence = 4 }; settings.RegisterTagMapping("ClassNoStyle", typeof(ClassNoStyle)); settings.RegisterTagMapping("ClassWithStyle", typeof(ClassWithStyle)); settings.ObjectSerializerBackend = new FormatListObject(); @@ -991,8 +991,8 @@ public void TestStyles() classNoStyle.A_ListWithCustomStyle.Add("a"); classNoStyle.A_ListWithCustomStyle.Add("b"); classNoStyle.A_ListWithCustomStyle.Add("c"); - classNoStyle.B_ClassWithStyle = new ClassWithStyle() {Name = "name1", Value = 1}; - classNoStyle.C_ClassWithStyleOverridenByLocalYamlStyle = new ClassWithStyle() {Name = "name2", Value = 2}; + classNoStyle.B_ClassWithStyle = new ClassWithStyle() { Name = "name1", Value = 1 }; + classNoStyle.C_ClassWithStyleOverridenByLocalYamlStyle = new ClassWithStyle() { Name = "name2", Value = 2 }; classNoStyle.D_ListHandleByDynamicStyleFormat.Add(1); classNoStyle.D_ListHandleByDynamicStyleFormat.Add(2); classNoStyle.D_ListHandleByDynamicStyleFormat.Add(3); @@ -1003,7 +1003,7 @@ public void TestStyles() classNoStyle.E_ListDefaultPrimitiveLimitExceed.Add(3); classNoStyle.E_ListDefaultPrimitiveLimitExceed.Add(4); classNoStyle.E_ListDefaultPrimitiveLimitExceed.Add(5); - classNoStyle.F_ListClassWithStyleDefaultFormat.Add(new ClassWithStyle() {Name = "name3", Value = 3}); + classNoStyle.F_ListClassWithStyleDefaultFormat.Add(new ClassWithStyle() { Name = "name3", Value = 3 }); classNoStyle.G_ListCustom.Name = "name4"; classNoStyle.G_ListCustom.Add(1); classNoStyle.G_ListCustom.Add(2); @@ -1050,12 +1050,12 @@ public void TestDefaultStyle() Items = new[] { 1, 2, 3 }, }; - var settings1 = new SerializerSettings {DefaultStyle = YamlStyle.Flow}; + var settings1 = new SerializerSettings { DefaultStyle = YamlStyle.Flow }; var serializer1 = new Serializer(settings1); var yaml1 = serializer1.Serialize(testObject); Assert.AreEqual("{Items: [1, 2, 3], Name: John Doe, Value: 42}\r\n", yaml1); - var settings2 = new SerializerSettings {DefaultStyle = YamlStyle.Block}; + var settings2 = new SerializerSettings { DefaultStyle = YamlStyle.Block }; var serializer2 = new Serializer(settings2); var yaml2 = serializer2.Serialize(testObject); Assert.AreEqual("Items:\r\n - 1\r\n - 2\r\n - 3\r\nName: John Doe\r\nValue: 42\r\n", yaml2); @@ -1134,7 +1134,7 @@ public override void WriteMemberName(ref ObjectContext objectContext, IMemberDes public void TestKeyTransform() { var specialTransform = new MyMappingKeyTransform(); - var settings = new SerializerSettings() {LimitPrimitiveFlowSequence = 4}; + var settings = new SerializerSettings() { LimitPrimitiveFlowSequence = 4 }; settings.ObjectSerializerBackend = specialTransform; settings.RegisterTagMapping("ClassWithKeyTransform", typeof(ClassWithKeyTransform)); @@ -1148,7 +1148,7 @@ public void TestKeyTransform() var serializer = new Serializer(settings); var myCustomObjectText = serializer.Serialize(myCustomObject); - var myCustomObject2 = (ClassWithKeyTransform) serializer.Deserialize(myCustomObjectText); + var myCustomObject2 = (ClassWithKeyTransform)serializer.Deserialize(myCustomObjectText); Assert.AreEqual(3, specialTransform.SpecialKeys.Count); @@ -1161,7 +1161,7 @@ public void TestKeyTransform() Assert.AreEqual(myCustomObject2, specialTransform.SpecialKeys[0].Item1); Assert.IsInstanceOf(specialTransform.SpecialKeys[0].Item2); - Assert.AreEqual("Name", ((IMemberDescriptor) specialTransform.SpecialKeys[0].Item2).Name); + Assert.AreEqual("Name", ((IMemberDescriptor)specialTransform.SpecialKeys[0].Item2).Name); } @@ -1277,7 +1277,7 @@ public void TestYamlMember() var settings = new SerializerSettings(); settings.RegisterAssembly(typeof(TestWithMemberRenamed).Assembly); - var value = new TestWithMemberRenamed {Base = "Test"}; + var value = new TestWithMemberRenamed { Base = "Test" }; var serializer = new Serializer(settings); var text = serializer.Serialize(value); Assert.True(text.Contains("~Base")); @@ -1310,14 +1310,14 @@ public override bool Equals(object obj) return true; if (obj.GetType() != this.GetType()) return false; - return Equals((MyClassImmutable) obj); + return Equals((MyClassImmutable)obj); } public override int GetHashCode() { unchecked { - return ((Name != null ? Name.GetHashCode() : 0)*397) ^ Value; + return ((Name != null ? Name.GetHashCode() : 0) * 397) ^ Value; } } } @@ -1331,12 +1331,12 @@ public override IYamlSerializable TryCreate(SerializerContext context, ITypeDesc protected override void CreateOrTransformObject(ref ObjectContext objectContext) { - objectContext.Instance = objectContext.SerializerContext.IsSerializing ? new MyClassMutable((MyClassImmutable) objectContext.Instance) : new MyClassMutable(); + objectContext.Instance = objectContext.SerializerContext.IsSerializing ? new MyClassMutable((MyClassImmutable)objectContext.Instance) : new MyClassMutable(); } protected override void TransformObjectAfterRead(ref ObjectContext objectContext) { - objectContext.Instance = ((MyClassMutable) objectContext.Instance).ToImmutable(); + objectContext.Instance = ((MyClassMutable)objectContext.Instance).ToImmutable(); } /// @@ -1393,12 +1393,12 @@ public void TestDictionaryWithObjectValue() settings.RegisterTagMapping("ObjectWithDictionaryAndObjectValue", typeof(ObjectWithDictionaryAndObjectValue)); var item = new ObjectWithDictionaryAndObjectValue(); - item.Values.Add("Test", new Color() {R = 1, G = 2, B = 3, A = 4}); + item.Values.Add("Test", new Color() { R = 1, G = 2, B = 3, A = 4 }); var serializer = new Serializer(settings); var text = serializer.Serialize(item); - var newItem = (ObjectWithDictionaryAndObjectValue) serializer.Deserialize(text); + var newItem = (ObjectWithDictionaryAndObjectValue)serializer.Deserialize(text); Assert.AreEqual(1, newItem.Values.Count); Assert.IsTrue(newItem.Values.ContainsKey("Test")); Assert.AreEqual(item.Values["Test"], newItem.Values["Test"]); @@ -1420,12 +1420,12 @@ public void TestMaskSimple() var settings = new SerializerSettings(); settings.RegisterTagMapping("ObjectWithMask", typeof(ObjectWithMask)); - var item = new ObjectWithMask {Int1 = 1, Int2 = 2, Int3 = 3}; + var item = new ObjectWithMask { Int1 = 1, Int2 = 2, Int3 = 3 }; var serializer = new Serializer(settings); var text = serializer.Serialize(item); - var newItem = (ObjectWithMask) serializer.Deserialize(text); + var newItem = (ObjectWithMask)serializer.Deserialize(text); // Default: mask != 1 is ignored Assert.AreEqual(newItem.Int1, item.Int1); @@ -1433,9 +1433,9 @@ public void TestMaskSimple() Assert.AreEqual(newItem.Int3, 0); serializer = new Serializer(settings); - text = serializer.Serialize(item, null, new SerializerContextSettings {MemberMask = 4}); + text = serializer.Serialize(item, null, new SerializerContextSettings { MemberMask = 4 }); - newItem = (ObjectWithMask) serializer.Deserialize(text); + newItem = (ObjectWithMask)serializer.Deserialize(text); // Only Int2 and Int3 should be serialized Assert.AreEqual(newItem.Int1, 0); @@ -1443,9 +1443,9 @@ public void TestMaskSimple() Assert.AreEqual(newItem.Int3, item.Int3); serializer = new Serializer(settings); - text = serializer.Serialize(item, null, new SerializerContextSettings {MemberMask = 1 | 4}); + text = serializer.Serialize(item, null, new SerializerContextSettings { MemberMask = 1 | 4 }); - newItem = (ObjectWithMask) serializer.Deserialize(text); + newItem = (ObjectWithMask)serializer.Deserialize(text); // Everything should be serialized Assert.AreEqual(newItem.Int1, item.Int1); @@ -1467,7 +1467,7 @@ public class ObjectWithMask [Test] public void TestImplicitMemberType() { - var settings = new SerializerSettings() {LimitPrimitiveFlowSequence = 0}; + var settings = new SerializerSettings() { LimitPrimitiveFlowSequence = 0 }; var text = @"!ClassWithImplicitMemberType Test: @@ -1482,7 +1482,7 @@ public void TestImplicitMemberType() [Test] public void TestNonImplicitMemberType() { - var settings = new SerializerSettings() {LimitPrimitiveFlowSequence = 0}; + var settings = new SerializerSettings() { LimitPrimitiveFlowSequence = 0 }; var text = @"!ClassWithNonImplicitMemberType Test: !ClassWithImplicitMemberTypeInner @@ -1522,7 +1522,7 @@ public class ClassWithImplicitMemberType { public ClassWithImplicitMemberType() { - Test = new ClassWithImplicitMemberTypeInner {String = "test"}; + Test = new ClassWithImplicitMemberTypeInner { String = "test" }; } public object Test { get; protected set; } @@ -1532,7 +1532,7 @@ public class ClassWithNonImplicitMemberType { public ClassWithNonImplicitMemberType() { - Test = new ClassWithImplicitMemberTypeInner {String = "test"}; + Test = new ClassWithImplicitMemberTypeInner { String = "test" }; } public object Test { get; set; } @@ -1663,4 +1663,4 @@ private object SerialRoundTrip(SerializerSettings settings, object value, Type e return valueDeserialized; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml.Tests/Serialization/TracingVisitor.cs b/src/SharpYaml.Tests/Serialization/TracingVisitor.cs index 8926ea7a..23ff5f4c 100644 --- a/src/SharpYaml.Tests/Serialization/TracingVisitor.cs +++ b/src/SharpYaml.Tests/Serialization/TracingVisitor.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -130,4 +130,4 @@ protected override void Visited(YamlStream stream) Console.WriteLine("Visited(YamlStream)"); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml.Tests/Serialization/YamlStreamTests.cs b/src/SharpYaml.Tests/Serialization/YamlStreamTests.cs index fa354267..79e15bf5 100644 --- a/src/SharpYaml.Tests/Serialization/YamlStreamTests.cs +++ b/src/SharpYaml.Tests/Serialization/YamlStreamTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -61,7 +61,7 @@ public void LoadSimpleDocument() Assert.AreEqual(1, stream.Documents.Count); Assert.IsInstanceOf(stream.Documents[0].RootNode); - Assert.AreEqual("a scalar", ((YamlScalarNode) stream.Documents[0].RootNode).Value); + Assert.AreEqual("a scalar", ((YamlScalarNode)stream.Documents[0].RootNode).Value); } [Test] @@ -73,12 +73,12 @@ public void BackwardAliasReferenceWorks() Assert.AreEqual(1, stream.Documents.Count); Assert.IsInstanceOf(stream.Documents[0].RootNode); - var sequence = (YamlSequenceNode) stream.Documents[0].RootNode; + var sequence = (YamlSequenceNode)stream.Documents[0].RootNode; Assert.AreEqual(3, sequence.Children.Count); - Assert.AreEqual("a scalar", ((YamlScalarNode) sequence.Children[0]).Value); - Assert.AreEqual("another scalar", ((YamlScalarNode) sequence.Children[1]).Value); - Assert.AreEqual("a scalar", ((YamlScalarNode) sequence.Children[2]).Value); + Assert.AreEqual("a scalar", ((YamlScalarNode)sequence.Children[0]).Value); + Assert.AreEqual("another scalar", ((YamlScalarNode)sequence.Children[1]).Value); + Assert.AreEqual("a scalar", ((YamlScalarNode)sequence.Children[2]).Value); Assert.AreSame(sequence.Children[0], sequence.Children[2]); } @@ -91,12 +91,12 @@ public void ForwardAliasReferenceWorks() Assert.AreEqual(1, stream.Documents.Count); Assert.IsInstanceOf(stream.Documents[0].RootNode); - var sequence = (YamlSequenceNode) stream.Documents[0].RootNode; + var sequence = (YamlSequenceNode)stream.Documents[0].RootNode; Assert.AreEqual(3, sequence.Children.Count); - Assert.AreEqual("a scalar", ((YamlScalarNode) sequence.Children[0]).Value); - Assert.AreEqual("another scalar", ((YamlScalarNode) sequence.Children[1]).Value); - Assert.AreEqual("a scalar", ((YamlScalarNode) sequence.Children[2]).Value); + Assert.AreEqual("a scalar", ((YamlScalarNode)sequence.Children[0]).Value); + Assert.AreEqual("another scalar", ((YamlScalarNode)sequence.Children[1]).Value); + Assert.AreEqual("a scalar", ((YamlScalarNode)sequence.Children[2]).Value); Assert.AreSame(sequence.Children[0], sequence.Children[2]); } @@ -308,4 +308,4 @@ public void RoundtripSample() original.Accept(new TracingVisitor()); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml.Tests/YamlNodeTest.cs b/src/SharpYaml.Tests/YamlNodeTest.cs index d5192a77..df4050ce 100644 --- a/src/SharpYaml.Tests/YamlNodeTest.cs +++ b/src/SharpYaml.Tests/YamlNodeTest.cs @@ -4,14 +4,17 @@ using System.Text; using NUnit.Framework; using SharpYaml.Events; -using SharpYaml.Serialization; using SharpYaml.Model; +using SharpYaml.Serialization; using YamlStream = SharpYaml.Model.YamlStream; -namespace SharpYaml.Tests { - public class YamlNodeTest { +namespace SharpYaml.Tests +{ + public class YamlNodeTest + { [Test] - public void ReadYamlReference() { + public void ReadYamlReference() + { var file = System.Reflection.Assembly.GetExecutingAssembly() .GetManifestResourceStream("SharpYaml.Tests.files.YamlReferenceCard.yaml"); @@ -45,7 +48,8 @@ public void ReadYamlReference() { } [Test] - public void YamlValue() { + public void YamlValue() + { var file = System.Reflection.Assembly.GetExecutingAssembly() .GetManifestResourceStream("SharpYaml.Tests.files.test6.yaml"); @@ -70,7 +74,8 @@ public void YamlValue() { } [Test] - public void FromObject() { + public void FromObject() + { var stream = new YamlStream(); var document = new Model.YamlDocument(); stream.Add(document); @@ -89,7 +94,8 @@ public void FromObject() { } [Test] - public void DeepClone() { + public void DeepClone() + { var file = System.Reflection.Assembly.GetExecutingAssembly() .GetManifestResourceStream("SharpYaml.Tests.files.test11.yaml"); @@ -115,7 +121,8 @@ public void DeepClone() { } [Test] - public void MappingStringKey() { + public void MappingStringKey() + { var file = System.Reflection.Assembly.GetExecutingAssembly() .GetManifestResourceStream("SharpYaml.Tests.files.test11.yaml"); @@ -132,7 +139,8 @@ public void MappingStringKey() { [Test] - public void AllowMissingKeyLookup() { + public void AllowMissingKeyLookup() + { var file = System.Reflection.Assembly.GetExecutingAssembly() .GetManifestResourceStream("SharpYaml.Tests.files.test11.yaml"); @@ -144,7 +152,8 @@ public void AllowMissingKeyLookup() { [Test] - public void ToStringTest() { + public void ToStringTest() + { var file = System.Reflection.Assembly.GetExecutingAssembly() .GetManifestResourceStream("SharpYaml.Tests.files.test8.yaml"); @@ -157,7 +166,8 @@ public void ToStringTest() { } [Test] - public void StyleTest() { + public void StyleTest() + { var file = System.Reflection.Assembly.GetExecutingAssembly() .GetManifestResourceStream("SharpYaml.Tests.files.test10.yaml"); @@ -179,7 +189,8 @@ public void StyleTest() { } [Test] - public void TagTest() { + public void TagTest() + { var file = System.Reflection.Assembly.GetExecutingAssembly() .GetManifestResourceStream("SharpYaml.Tests.files.dictionaryExplicit.yaml"); @@ -200,7 +211,8 @@ public void TagTest() { [Test] - public void ScalarStyleTest() { + public void ScalarStyleTest() + { var file = System.Reflection.Assembly.GetExecutingAssembly() .GetManifestResourceStream("SharpYaml.Tests.files.test6.yaml"); @@ -218,7 +230,8 @@ public void ScalarStyleTest() { } [Test] - public void IsCanonicalTest() { + public void IsCanonicalTest() + { var file = System.Reflection.Assembly.GetExecutingAssembly() .GetManifestResourceStream("SharpYaml.Tests.files.test6.yaml"); diff --git a/src/SharpYaml.Tests/YamlNodeTrackerTest.cs b/src/SharpYaml.Tests/YamlNodeTrackerTest.cs index e10a8ae7..7619f4bd 100644 --- a/src/SharpYaml.Tests/YamlNodeTrackerTest.cs +++ b/src/SharpYaml.Tests/YamlNodeTrackerTest.cs @@ -6,10 +6,13 @@ using Path = SharpYaml.Model.Path; using YamlStream = SharpYaml.Model.YamlStream; -namespace SharpYaml.Tests { - public class YamlNodeTrackerTest { +namespace SharpYaml.Tests +{ + public class YamlNodeTrackerTest + { [Test] - public void DeserializeTest() { + public void DeserializeTest() + { var file = System.Reflection.Assembly.GetExecutingAssembly() .GetManifestResourceStream("SharpYaml.Tests.files.test11.yaml"); @@ -17,7 +20,8 @@ public void DeserializeTest() { var tracker = new YamlNodeTracker(); - tracker.TrackerEvent += (sender, args) => { + tracker.TrackerEvent += (sender, args) => + { if (args.EventType == TrackerEventType.MappingPairAdded || args.EventType == TrackerEventType.SequenceElementAdded || args.EventType == TrackerEventType.StreamDocumentAdded) @@ -31,7 +35,8 @@ public void DeserializeTest() { } [Test] - public void ValueSetTest() { + public void ValueSetTest() + { var file = System.Reflection.Assembly.GetExecutingAssembly() .GetManifestResourceStream("SharpYaml.Tests.files.test4.yaml"); @@ -39,7 +44,8 @@ public void ValueSetTest() { var tracker = new YamlNodeTracker(); - tracker.TrackerEvent += (sender, args) => { + tracker.TrackerEvent += (sender, args) => + { if (args.EventType == TrackerEventType.MappingPairAdded || args.EventType == TrackerEventType.SequenceElementAdded || args.EventType == TrackerEventType.StreamDocumentAdded) @@ -52,7 +58,8 @@ public void ValueSetTest() { Assert.AreEqual(3, childrenAdded); ScalarValueChanged valueChanged = null; - tracker.TrackerEvent += (sender, args) => { + tracker.TrackerEvent += (sender, args) => + { if (args is ScalarValueChanged) valueChanged = (ScalarValueChanged)args; }; @@ -66,27 +73,33 @@ public void ValueSetTest() { } - class SubscriberHandler { + class SubscriberHandler + { public int ACalls; public int BCalls; public int CCalls; - public void A(TrackerEventArgs args) { + public void A(TrackerEventArgs args) + { ACalls++; } - public void B(TrackerEventArgs args) { + public void B(TrackerEventArgs args) + { BCalls++; } - public void C(TrackerEventArgs args) { + public void C(TrackerEventArgs args) + { CCalls++; } } [Test] - public void DisposeTest() { - System.WeakReference GetWeakRef() { + public void DisposeTest() + { + System.WeakReference GetWeakRef() + { // In .NET versions higher than 3.5, the parents dictionary is replaced with // ConditionalWeakTable, allowing tracked YAML nodes to be freed properly. var file = System.Reflection.Assembly.GetExecutingAssembly() @@ -96,7 +109,8 @@ System.WeakReference GetWeakRef() { var tracker = new YamlNodeTracker(); - tracker.TrackerEvent += (sender, args) => { + tracker.TrackerEvent += (sender, args) => + { if (args.EventType == TrackerEventType.MappingPairAdded || args.EventType == TrackerEventType.SequenceElementAdded || args.EventType == TrackerEventType.StreamDocumentAdded) @@ -118,7 +132,8 @@ System.WeakReference GetWeakRef() { } [Test] - public void SubscriberTest() { + public void SubscriberTest() + { var file = System.Reflection.Assembly.GetExecutingAssembly() .GetManifestResourceStream("SharpYaml.Tests.files.test12.yaml"); @@ -158,14 +173,16 @@ public void SubscriberTest() { } [Test] - public void AddPairTest() { + public void AddPairTest() + { var tracker = new YamlNodeTracker(); var stream = new YamlStream(tracker); stream.Add(new YamlDocument()); stream[0].Contents = new YamlMapping(); TrackerEventArgs receivedArgs = null; - tracker.TrackerEvent += (sender, args) => { + tracker.TrackerEvent += (sender, args) => + { receivedArgs = args; }; @@ -181,7 +198,8 @@ public void AddPairTest() { [Test] - public void TrackerAssignmentTest() { + public void TrackerAssignmentTest() + { var tracker = new YamlNodeTracker(); var stream = new YamlStream(tracker); @@ -232,7 +250,8 @@ public void TrackerAssignmentTest() { } [Test] - public void UpdateMappingNextChildrenTest() { + public void UpdateMappingNextChildrenTest() + { var file = System.Reflection.Assembly.GetExecutingAssembly() .GetManifestResourceStream("SharpYaml.Tests.files.test11.yaml"); @@ -268,7 +287,8 @@ public void UpdateMappingNextChildrenTest() { [Test] - public void UpdateSequenceNextChildrenTest() { + public void UpdateSequenceNextChildrenTest() + { var file = System.Reflection.Assembly.GetExecutingAssembly() .GetManifestResourceStream("SharpYaml.Tests.files.test10.yaml"); @@ -304,7 +324,8 @@ public void UpdateSequenceNextChildrenTest() { [Test] - public void UpdateStreamNextChildrenTest() { + public void UpdateStreamNextChildrenTest() + { var file = System.Reflection.Assembly.GetExecutingAssembly() .GetManifestResourceStream("SharpYaml.Tests.files.test4.yaml"); @@ -315,7 +336,8 @@ public void UpdateStreamNextChildrenTest() { var val = (YamlValue)stream[2].Contents; Path modifiedPath = new Path(); - tracker.TrackerEvent += (sender, args) => { + tracker.TrackerEvent += (sender, args) => + { if (args.ParentPaths.Count > 0) modifiedPath = args.ParentPaths[0]; }; @@ -342,7 +364,8 @@ public void UpdateStreamNextChildrenTest() { } [Test] - public void UpdateSubscriberNextChildrenTest() { + public void UpdateSubscriberNextChildrenTest() + { var file = System.Reflection.Assembly.GetExecutingAssembly() .GetManifestResourceStream("SharpYaml.Tests.files.test11.yaml"); @@ -350,16 +373,16 @@ public void UpdateSubscriberNextChildrenTest() { var fileStream = new StreamReader(file); var stream = YamlStream.Load(fileStream, tracker); - var rootMapping = (YamlMapping) stream[0].Contents; - var val = (YamlValue) rootMapping["a simple key"]; - var map = (YamlMapping) rootMapping["a mapping"]; + var rootMapping = (YamlMapping)stream[0].Contents; + var val = (YamlValue)rootMapping["a simple key"]; + var map = (YamlMapping)rootMapping["a mapping"]; var seq = (YamlSequence)rootMapping["a sequence"]; - + var subscriber = new SubscriberHandler(); tracker.Subscribe(subscriber, tracker.GetPaths(seq)[0], "A"); tracker.Subscribe(subscriber, tracker.GetPaths(map)[0], "B"); tracker.Subscribe(subscriber, tracker.GetPaths(val)[0], "C"); - + seq[0] = new YamlValue("New item"); map["bla"] = new YamlValue("New item"); val.Tag = "bla"; @@ -381,18 +404,18 @@ public void UpdateSubscriberNextChildrenTest() { // Make sure we're still subscribed. Assert.AreEqual(2, subscriber.ACalls); Assert.AreEqual(2, subscriber.BCalls); - + // C should get unsubscribed and not get any seq or map changes. Assert.AreEqual(1, subscriber.CCalls); rootMapping.Insert(0, new KeyValuePair(new YamlValue("a mapping 1"), new YamlMapping())); - + seq[0] = new YamlValue("New item 3"); - + // Make sure we're still subscribed. Assert.AreEqual(3, subscriber.ACalls); Assert.AreEqual(2, subscriber.BCalls); - + map["bla"] = new YamlValue("New item 3"); // Make sure we're still subscribed. @@ -403,7 +426,8 @@ public void UpdateSubscriberNextChildrenTest() { [Test] - public void UpdateSubscriberNextChildrenTest2() { + public void UpdateSubscriberNextChildrenTest2() + { // As the indices of the parents change, the children also need to get re-subscribed. var file = System.Reflection.Assembly.GetExecutingAssembly() .GetManifestResourceStream("SharpYaml.Tests.files.test11.yaml"); @@ -415,7 +439,7 @@ public void UpdateSubscriberNextChildrenTest2() { var rootMapping = (YamlMapping)stream[0].Contents; var map = (YamlMapping)rootMapping["a mapping"]; var seq = (YamlSequence)rootMapping["a sequence"]; - + var subscriber = new SubscriberHandler(); tracker.Subscribe(subscriber, tracker.GetPaths(map["key 1"])[0], "A"); tracker.Subscribe(subscriber, tracker.GetPaths(seq[0])[0], "B"); @@ -433,7 +457,7 @@ public void UpdateSubscriberNextChildrenTest2() { // Make sure B is still subscribed and A isn't. Assert.AreEqual(1, subscriber.ACalls); Assert.AreEqual(2, subscriber.BCalls); - + rootMapping.Insert(0, new KeyValuePair(new YamlValue("a mapping 1"), new YamlMapping())); seq[0].Tag = "bla3"; @@ -442,4 +466,4 @@ public void UpdateSubscriberNextChildrenTest2() { Assert.AreEqual(3, subscriber.BCalls); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml.Tests/YamlTest.cs b/src/SharpYaml.Tests/YamlTest.cs index 7c2dfa3a..bbc610ef 100644 --- a/src/SharpYaml.Tests/YamlTest.cs +++ b/src/SharpYaml.Tests/YamlTest.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -91,4 +91,4 @@ protected static TextReader YamlText(string yaml) return new StringReader(string.Join("\n", lines.ToArray())); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml.sln b/src/SharpYaml.sln index 6a350b39..398fc36f 100644 --- a/src/SharpYaml.sln +++ b/src/SharpYaml.sln @@ -5,6 +5,7 @@ VisualStudioVersion = 17.1.32210.238 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{69EE9636-55BA-49C2-827E-D5684221C345}" ProjectSection(SolutionItems) = preProject + .editorconfig = .editorconfig ..\.gitignore = ..\.gitignore ..\changelog.md = ..\changelog.md ..\.github\workflows\ci.yml = ..\.github\workflows\ci.yml diff --git a/src/SharpYaml/CharHelper.cs b/src/SharpYaml/CharHelper.cs index b2ed7258..f8129b9b 100644 --- a/src/SharpYaml/CharHelper.cs +++ b/src/SharpYaml/CharHelper.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -70,4 +70,4 @@ public static string ConvertFromUtf32(int utf32) return char.ConvertFromUtf32(utf32); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/CharacterAnalyzer.cs b/src/SharpYaml/CharacterAnalyzer.cs index 22b007bb..932c902c 100644 --- a/src/SharpYaml/CharacterAnalyzer.cs +++ b/src/SharpYaml/CharacterAnalyzer.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -283,4 +283,4 @@ public static bool Check(this ILookAheadBuffer buffer, string expectedCharacters return false; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Constants.cs b/src/SharpYaml/Constants.cs index 47e588d2..41acbd94 100644 --- a/src/SharpYaml/Constants.cs +++ b/src/SharpYaml/Constants.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -65,4 +65,4 @@ internal static class Constants public const char HandleCharacter = '!'; public const string DefaultHandle = "!"; } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Emitter.cs b/src/SharpYaml/Emitter.cs index 299a2786..8606462e 100644 --- a/src/SharpYaml/Emitter.cs +++ b/src/SharpYaml/Emitter.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -82,20 +82,23 @@ public class Emitter : IEmitter private bool isWhitespace; private bool isIndentation; private bool forceIndentLess; - private bool emitKeyQuoted; + private readonly bool emitKeyQuoted; private bool isOpenEnded; private readonly MutableStringLookAheadBuffer buffer = new MutableStringLookAheadBuffer(); - private class MutableStringLookAheadBuffer : ILookAheadBuffer { + private class MutableStringLookAheadBuffer : ILookAheadBuffer + { private string value; private int currentIndex; - public string Value { + public string Value + { get { return value; } - set { + set + { this.value = value; currentIndex = 0; } @@ -105,7 +108,8 @@ public string Value { public int Position { get { return currentIndex; } } - public bool IsOutside(int index) { + public bool IsOutside(int index) + { return value == null || index >= value.Length; } @@ -113,13 +117,16 @@ public bool IsOutside(int index) { public MutableStringLookAheadBuffer() { } - public char Peek(int offset) { + public char Peek(int offset) + { int index = currentIndex + offset; return value[index]; } - public void Skip(int length) { - if (length < 0) { + public void Skip(int length) + { + if (length < 0) + { throw new ArgumentOutOfRangeException("length", "The length must be positive."); } currentIndex += length; @@ -185,7 +192,7 @@ public Emitter(TextWriter output, int bestIndent = MinBestIndent, int bestWidth this.bestIndent = bestIndent; - if (bestWidth <= bestIndent*2) + if (bestWidth <= bestIndent * 2) { throw new ArgumentOutOfRangeException("bestWidth", "The bestWidth parameter must be greater than bestIndent * 2."); } @@ -808,7 +815,7 @@ private void WriteTagHandle(string value) private static string UrlEncode(string text) { - return uriReplacer.Replace(text, delegate(Match match) + return uriReplacer.Replace(text, delegate (Match match) { StringBuilder buffer = new StringBuilder(); foreach (var toEncode in Encoding.UTF8.GetBytes(match.Value)) @@ -947,7 +954,7 @@ private void EmitSequenceStart(ParsingEvent evt) ProcessAnchor(); ProcessTag(); - SequenceStart sequenceStart = (SequenceStart) evt; + SequenceStart sequenceStart = (SequenceStart)evt; if (flowLevel != 0 || isCanonical || sequenceStart.Style == YamlStyle.Flow || CheckEmptySequence()) { @@ -1021,7 +1028,7 @@ private void EmitMappingStart(ParsingEvent evt) ProcessAnchor(); ProcessTag(); - MappingStart mappingStart = (MappingStart) evt; + MappingStart mappingStart = (MappingStart)evt; if (flowLevel != 0 || isCanonical || mappingStart.Style == YamlStyle.Flow || CheckEmptyMapping()) { @@ -1271,7 +1278,7 @@ private void WriteDoubleQuotedScalar(string value, bool allowBreaks) break; default: - short code = (short) character; + short code = (short)character; if (code <= 0xFF) { Write('x'); @@ -1288,7 +1295,7 @@ private void WriteDoubleQuotedScalar(string value, bool allowBreaks) } else { - throw new YamlException($"Unable to encode character low surrogate after high surrogate [{character}] at position {index+1} of text `{value}`"); + throw new YamlException($"Unable to encode character low surrogate after high surrogate [{character}] at position {index + 1} of text `{value}`"); } } else @@ -1464,7 +1471,7 @@ private void IncreaseIndent(bool isFlow, bool isIndentless) /// private void SelectScalarStyle(ParsingEvent evt) { - Scalar scalar = (Scalar) evt; + Scalar scalar = (Scalar)evt; ScalarStyle style = scalar.Style; bool noTag = tagData.handle == null && tagData.suffix == null; diff --git a/src/SharpYaml/EmitterState.cs b/src/SharpYaml/EmitterState.cs index bf7ca768..0bc2d06f 100644 --- a/src/SharpYaml/EmitterState.cs +++ b/src/SharpYaml/EmitterState.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -142,4 +142,4 @@ internal enum EmitterState /// YAML_EMIT_END_STATE } -} \ No newline at end of file +} diff --git a/src/SharpYaml/EventReader.cs b/src/SharpYaml/EventReader.cs index b876280a..be2a9407 100644 --- a/src/SharpYaml/EventReader.cs +++ b/src/SharpYaml/EventReader.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -44,11 +44,11 @@ // SOFTWARE. using System; +using System.Globalization; using System.IO; using SharpYaml; -using System.Globalization; -using Event = SharpYaml.Events.ParsingEvent; using SharpYaml.Events; +using Event = SharpYaml.Events.ParsingEvent; namespace SharpYaml { @@ -136,7 +136,7 @@ public T Allow() where T : Event { return null; } - T yamlEvent = (T) parser.Current; + T yamlEvent = (T)parser.Current; MoveNext(); return yamlEvent; } @@ -152,7 +152,7 @@ public T Peek() where T : Event { return null; } - T yamlEvent = (T) parser.Current; + T yamlEvent = (T)parser.Current; return yamlEvent; } @@ -200,4 +200,4 @@ private void EnsureNotAtEndOfStream() } } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Events/AnchorAlias.cs b/src/SharpYaml/Events/AnchorAlias.cs index 695c46c6..b802357f 100644 --- a/src/SharpYaml/Events/AnchorAlias.cs +++ b/src/SharpYaml/Events/AnchorAlias.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -114,4 +114,4 @@ public override string ToString() return FormattableString.Invariant($"Alias [value = {value}]"); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Events/DocumentEnd.cs b/src/SharpYaml/Events/DocumentEnd.cs index 6899bb08..20438d7c 100644 --- a/src/SharpYaml/Events/DocumentEnd.cs +++ b/src/SharpYaml/Events/DocumentEnd.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -107,4 +107,4 @@ public override string ToString() return FormattableString.Invariant($"Document end [isImplicit = {isImplicit}]"); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Events/DocumentStart.cs b/src/SharpYaml/Events/DocumentStart.cs index 35a0790e..4d8af754 100644 --- a/src/SharpYaml/Events/DocumentStart.cs +++ b/src/SharpYaml/Events/DocumentStart.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -147,4 +147,4 @@ public override string ToString() return FormattableString.Invariant($"Document start [isImplicit = {isImplicit}]"); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Events/EventType.cs b/src/SharpYaml/Events/EventType.cs index 08340c31..161566af 100644 --- a/src/SharpYaml/Events/EventType.cs +++ b/src/SharpYaml/Events/EventType.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -107,4 +107,4 @@ internal enum EventType /// YAML_MAPPING_END_EVENT, } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Events/MappingEnd.cs b/src/SharpYaml/Events/MappingEnd.cs index cc23cdf1..3cfd86df 100644 --- a/src/SharpYaml/Events/MappingEnd.cs +++ b/src/SharpYaml/Events/MappingEnd.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -93,4 +93,4 @@ public override string ToString() return "Mapping end"; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Events/MappingStart.cs b/src/SharpYaml/Events/MappingStart.cs index c3df8596..62b6e9b6 100644 --- a/src/SharpYaml/Events/MappingStart.cs +++ b/src/SharpYaml/Events/MappingStart.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -136,4 +136,4 @@ public override string ToString() $"Mapping start [anchor = {Anchor}, tag = {Tag}, isImplicit = {isImplicit}, style = {style}]"); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Events/NodeEvent.cs b/src/SharpYaml/Events/NodeEvent.cs index 4c181dba..1494153b 100644 --- a/src/SharpYaml/Events/NodeEvent.cs +++ b/src/SharpYaml/Events/NodeEvent.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -117,4 +117,4 @@ protected NodeEvent(string anchor, string tag) { } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Events/ParsingEvent.cs b/src/SharpYaml/Events/ParsingEvent.cs index 97c6e14d..8b8049cc 100644 --- a/src/SharpYaml/Events/ParsingEvent.cs +++ b/src/SharpYaml/Events/ParsingEvent.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -87,4 +87,4 @@ internal ParsingEvent(Mark start, Mark end) this.end = end; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Events/Scalar.cs b/src/SharpYaml/Events/Scalar.cs index 24aba83b..59a54977 100644 --- a/src/SharpYaml/Events/Scalar.cs +++ b/src/SharpYaml/Events/Scalar.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -53,7 +53,7 @@ namespace SharpYaml.Events /// public sealed class Scalar : NodeEvent { - private string value; + private readonly string value; /// /// Gets a value indicating the variation of depth caused by this event. @@ -184,4 +184,4 @@ public override string ToString() $"Scalar [anchor = {Anchor}, tag = {Tag}, value = {value}, style = {style}, isPlainImplicit = {isPlainImplicit}, isQuotedImplicit = {isQuotedImplicit}]"); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Events/SequenceEnd.cs b/src/SharpYaml/Events/SequenceEnd.cs index 2d00e4ff..c7dc6bfb 100644 --- a/src/SharpYaml/Events/SequenceEnd.cs +++ b/src/SharpYaml/Events/SequenceEnd.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -93,4 +93,4 @@ public override string ToString() return "Sequence end"; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Events/SequenceStart.cs b/src/SharpYaml/Events/SequenceStart.cs index 60445854..ea85a52f 100644 --- a/src/SharpYaml/Events/SequenceStart.cs +++ b/src/SharpYaml/Events/SequenceStart.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -132,4 +132,4 @@ public override string ToString() $"Sequence start [anchor = {Anchor}, tag = {Tag}, isImplicit = {isImplicit}, style = {style}]"); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Events/StreamEnd.cs b/src/SharpYaml/Events/StreamEnd.cs index 81ea1db2..7b61edba 100644 --- a/src/SharpYaml/Events/StreamEnd.cs +++ b/src/SharpYaml/Events/StreamEnd.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -93,4 +93,4 @@ public override string ToString() return "Stream end"; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Events/StreamStart.cs b/src/SharpYaml/Events/StreamStart.cs index b437fd02..30283f9b 100644 --- a/src/SharpYaml/Events/StreamStart.cs +++ b/src/SharpYaml/Events/StreamStart.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -93,4 +93,4 @@ public override string ToString() return "Stream start"; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/FakeList.cs b/src/SharpYaml/FakeList.cs index f4aa9bd8..630ac7e3 100644 --- a/src/SharpYaml/FakeList.cs +++ b/src/SharpYaml/FakeList.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -104,4 +104,4 @@ public T this[int index] } } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/IEmitter.cs b/src/SharpYaml/IEmitter.cs index fe5b16af..89b8ad06 100644 --- a/src/SharpYaml/IEmitter.cs +++ b/src/SharpYaml/IEmitter.cs @@ -57,4 +57,4 @@ public interface IEmitter /// void Emit(ParsingEvent @event); } -} \ No newline at end of file +} diff --git a/src/SharpYaml/ILookAheadBuffer.cs b/src/SharpYaml/ILookAheadBuffer.cs index 32fc9273..6a318d12 100644 --- a/src/SharpYaml/ILookAheadBuffer.cs +++ b/src/SharpYaml/ILookAheadBuffer.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -73,4 +73,4 @@ public interface ILookAheadBuffer /// void Cache(int length); } -} \ No newline at end of file +} diff --git a/src/SharpYaml/IParser.cs b/src/SharpYaml/IParser.cs index 1102830e..56c590a3 100644 --- a/src/SharpYaml/IParser.cs +++ b/src/SharpYaml/IParser.cs @@ -63,4 +63,4 @@ public interface IParser /// Returns true if there are more events available, otherwise returns false. bool MoveNext(); } -} \ No newline at end of file +} diff --git a/src/SharpYaml/InsertionQueue.cs b/src/SharpYaml/InsertionQueue.cs index 4e846f94..793e3f23 100644 --- a/src/SharpYaml/InsertionQueue.cs +++ b/src/SharpYaml/InsertionQueue.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -97,4 +97,4 @@ public void Insert(int index, T item) items.Insert(index, item); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/LookAheadBuffer.cs b/src/SharpYaml/LookAheadBuffer.cs index d8409c0e..d44a734d 100644 --- a/src/SharpYaml/LookAheadBuffer.cs +++ b/src/SharpYaml/LookAheadBuffer.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -137,7 +137,7 @@ public void Cache(int length) if (nextChar >= 0) { int lastIndex = GetIndexForOffset(count); - buffer[lastIndex] = (char) nextChar; + buffer[lastIndex] = (char)nextChar; ++count; } else @@ -162,4 +162,4 @@ public void Skip(int length) count -= length; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Mark.cs b/src/SharpYaml/Mark.cs index da48d3f1..e176b8d9 100644 --- a/src/SharpYaml/Mark.cs +++ b/src/SharpYaml/Mark.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -56,7 +56,8 @@ public readonly struct Mark private readonly int line; private readonly int column; - public Mark(int index, int line, int column) { + public Mark(int index, int line, int column) + { this.index = index; this.line = line; this.column = column; @@ -102,4 +103,4 @@ public override string ToString() return $"Lin: {line}, Col: {column}, Chr: {index}"; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/MemoryParser.cs b/src/SharpYaml/MemoryParser.cs index ef232afb..90a0c83e 100644 --- a/src/SharpYaml/MemoryParser.cs +++ b/src/SharpYaml/MemoryParser.cs @@ -1,4 +1,4 @@ -using System.Collections; +using System.Collections; using System.Collections.Generic; using SharpYaml.Events; @@ -20,4 +20,4 @@ public bool MoveNext() return parsingEvents.MoveNext(); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Model/PathTrie.cs b/src/SharpYaml/Model/PathTrie.cs index 9665c78e..b43f02e9 100644 --- a/src/SharpYaml/Model/PathTrie.cs +++ b/src/SharpYaml/Model/PathTrie.cs @@ -1,19 +1,25 @@ using System.Collections.Generic; using System.Linq; -namespace SharpYaml.Model { - public class PathTrie { - class PathTrieNode { +namespace SharpYaml.Model +{ + public class PathTrie + { + class PathTrieNode + { public bool Self { get; private set; } readonly Dictionary subPaths = new Dictionary(); - public void Add(IList indices, int start) { - if (start == indices.Count) { + public void Add(IList indices, int start) + { + if (start == indices.Count) + { Self = true; return; } - if (!subPaths.TryGetValue(indices[start], out PathTrieNode subPath)) { + if (!subPaths.TryGetValue(indices[start], out PathTrieNode subPath)) + { subPath = new PathTrieNode(); subPaths[indices[start]] = subPath; } @@ -21,10 +27,12 @@ public void Add(IList indices, int start) { subPath.Add(indices, start + 1); } - public bool Remove(IList indices, int start, bool removeChildren) { - if (start == indices.Count) { + public bool Remove(IList indices, int start, bool removeChildren) + { + if (start == indices.Count) + { var result = Self || (removeChildren && subPaths.Count > 0); - + Self = false; if (removeChildren) @@ -45,11 +53,13 @@ public bool Remove(IList indices, int start, bool removeChildren) { return true; } - public bool IsEmpty { + public bool IsEmpty + { get { return !Self && subPaths.Count == 0; } } - public PathTrieNode Find(IList indices, int start) { + public PathTrieNode Find(IList indices, int start) + { if (start == indices.Count) return this; @@ -59,12 +69,15 @@ public PathTrieNode Find(IList indices, int start) { return subPath.Find(indices, start + 1); } - public IEnumerable> GetReversePaths() { + public IEnumerable> GetReversePaths() + { if (Self) yield return new List(); - foreach (var pair in subPaths) { - foreach (var path in pair.Value.GetReversePaths()) { + foreach (var pair in subPaths) + { + foreach (var path in pair.Value.GetReversePaths()) + { path.Add(pair.Key); yield return path; } @@ -74,8 +87,10 @@ public IEnumerable> GetReversePaths() { private readonly Dictionary roots = new Dictionary(); - public void Add(Path path) { - if (!roots.TryGetValue(path.Root, out PathTrieNode root)) { + public void Add(Path path) + { + if (!roots.TryGetValue(path.Root, out PathTrieNode root)) + { root = new PathTrieNode(); roots[path.Root] = root; } @@ -83,7 +98,8 @@ public void Add(Path path) { root.Add(path.Indices, 0); } - public bool Remove(Path path, bool removeChildren) { + public bool Remove(Path path, bool removeChildren) + { if (!roots.TryGetValue(path.Root, out PathTrieNode root)) return false; @@ -96,7 +112,8 @@ public bool Remove(Path path, bool removeChildren) { return true; } - public bool Contains(Path path, bool orChildren) { + public bool Contains(Path path, bool orChildren) + { if (!roots.TryGetValue(path.Root, out PathTrieNode root)) return false; @@ -107,7 +124,8 @@ public bool Contains(Path path, bool orChildren) { return node.Self || orChildren; } - public IEnumerable GetSubpaths(Path path) { + public IEnumerable GetSubpaths(Path path) + { if (!roots.TryGetValue(path.Root, out PathTrieNode root)) yield break; @@ -115,7 +133,8 @@ public IEnumerable GetSubpaths(Path path) { if (node == null) yield break; - foreach (var reversePath in node.GetReversePaths()) { + foreach (var reversePath in node.GetReversePaths()) + { reversePath.AddRange(path.Indices.Reverse()); reversePath.Reverse(); yield return new Path(path.Root, reversePath.ToArray()); diff --git a/src/SharpYaml/Model/YamlContainer.cs b/src/SharpYaml/Model/YamlContainer.cs index 58510d80..b8ff716e 100644 --- a/src/SharpYaml/Model/YamlContainer.cs +++ b/src/SharpYaml/Model/YamlContainer.cs @@ -19,8 +19,9 @@ // THE SOFTWARE. namespace SharpYaml.Model { - public abstract class YamlContainer : YamlElement { + public abstract class YamlContainer : YamlElement + { public abstract YamlStyle Style { get; set; } public abstract bool IsImplicit { get; set; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Model/YamlDocument.cs b/src/SharpYaml/Model/YamlDocument.cs index 57fd2539..79718501 100644 --- a/src/SharpYaml/Model/YamlDocument.cs +++ b/src/SharpYaml/Model/YamlDocument.cs @@ -25,17 +25,20 @@ namespace SharpYaml.Model { - public class YamlDocument : YamlNode { + public class YamlDocument : YamlNode + { private DocumentStart _documentStart; private DocumentEnd _documentEnd; private YamlElement _contents; - public YamlDocument() { + public YamlDocument() + { _documentStart = new DocumentStart(null, new TagDirectiveCollection(), true); _documentEnd = new DocumentEnd(true); } - YamlDocument(DocumentStart documentStart, DocumentEnd documentEnd, YamlElement contents, YamlNodeTracker tracker) { + YamlDocument(DocumentStart documentStart, DocumentEnd documentEnd, YamlElement contents, YamlNodeTracker tracker) + { Tracker = tracker; DocumentStart = documentStart; @@ -43,7 +46,8 @@ public YamlDocument() { Contents = contents; } - public static YamlDocument Load(EventReader eventReader, YamlNodeTracker tracker = null) { + public static YamlDocument Load(EventReader eventReader, YamlNodeTracker tracker = null) + { var documentStart = eventReader.Allow(); var contents = ReadElement(eventReader, tracker); @@ -53,9 +57,11 @@ public static YamlDocument Load(EventReader eventReader, YamlNodeTracker tracker return new YamlDocument(documentStart, documentEnd, contents, tracker); } - public DocumentStart DocumentStart { + public DocumentStart DocumentStart + { get => _documentStart; - set { + set + { var oldValue = _documentStart; _documentStart = value; @@ -65,9 +71,11 @@ public DocumentStart DocumentStart { } } - public DocumentEnd DocumentEnd { + public DocumentEnd DocumentEnd + { get => _documentEnd; - set { + set + { var oldValue = _documentEnd; _documentEnd = value; @@ -77,37 +85,44 @@ public DocumentEnd DocumentEnd { } } - public YamlElement Contents { + public YamlElement Contents + { get { return _contents; } - set { + set + { var oldValue = _contents; _contents = value; - if (Tracker != null) { + if (Tracker != null) + { value.Tracker = Tracker; Tracker.OnDocumentContentsChanged(this, oldValue, value); } } } - public override YamlNodeTracker Tracker { + public override YamlNodeTracker Tracker + { get { return base.Tracker; } - internal set { + internal set + { if (Tracker == value) return; base.Tracker = value; - if (_contents != null) { + if (_contents != null) + { _contents.Tracker = value; Tracker.OnDocumentContentsChanged(this, null, _contents); } } } - public override YamlNode DeepClone(YamlNodeTracker tracker = null) { - return new YamlDocument(_documentStart, _documentEnd, (YamlElement) Contents?.DeepClone(), tracker); + public override YamlNode DeepClone(YamlNodeTracker tracker = null) + { + return new YamlDocument(_documentStart, _documentEnd, (YamlElement)Contents?.DeepClone(), tracker); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Model/YamlElement.cs b/src/SharpYaml/Model/YamlElement.cs index 02815430..a0204c21 100644 --- a/src/SharpYaml/Model/YamlElement.cs +++ b/src/SharpYaml/Model/YamlElement.cs @@ -19,9 +19,10 @@ // THE SOFTWARE. namespace SharpYaml.Model { - public abstract class YamlElement : YamlNode { + public abstract class YamlElement : YamlNode + { public abstract string Anchor { get; set; } public abstract string Tag { get; set; } public abstract bool IsCanonical { get; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Model/YamlMapping.cs b/src/SharpYaml/Model/YamlMapping.cs index 7d06c891..68d5ef1b 100644 --- a/src/SharpYaml/Model/YamlMapping.cs +++ b/src/SharpYaml/Model/YamlMapping.cs @@ -23,8 +23,10 @@ using System.Linq; using SharpYaml.Events; -namespace SharpYaml.Model { - public class YamlMapping : YamlContainer, IDictionary, IList> { +namespace SharpYaml.Model +{ + public class YamlMapping : YamlContainer, IDictionary, IList> + { private MappingStart _mappingStart; private readonly MappingEnd _mappingEnd; @@ -33,18 +35,23 @@ public class YamlMapping : YamlContainer, IDictionary, private Dictionary stringKeys; - public YamlMapping() { + public YamlMapping() + { _mappingStart = new MappingStart(); _mappingEnd = new MappingEnd(); _keys = new List(); _contents = new Dictionary(); } - YamlMapping(MappingStart mappingStart, MappingEnd mappingEnd, List keys, Dictionary contents, YamlNodeTracker tracker) { - if (tracker == null) { + YamlMapping(MappingStart mappingStart, MappingEnd mappingEnd, List keys, Dictionary contents, YamlNodeTracker tracker) + { + if (tracker == null) + { _keys = keys; _contents = contents; - } else { + } + else + { _keys = new List(); _contents = new Dictionary(); @@ -58,9 +65,11 @@ public YamlMapping() { this._mappingEnd = mappingEnd; } - public MappingStart MappingStart { + public MappingStart MappingStart + { get => _mappingStart; - set { + set + { var oldValue = _mappingStart; _mappingStart = value; @@ -69,12 +78,14 @@ public MappingStart MappingStart { Tracker.OnMappingStartChanged(this, oldValue, value); } } - - internal MappingEnd MappingEnd { get { return _mappingEnd; } } - public override string Anchor { + internal MappingEnd MappingEnd { get { return _mappingEnd; } } + + public override string Anchor + { get { return _mappingStart.Anchor; } - set { + set + { MappingStart = new MappingStart(value, _mappingStart.Tag, _mappingStart.IsImplicit, @@ -84,9 +95,11 @@ public override string Anchor { } } - public override string Tag { + public override string Tag + { get { return _mappingStart.Tag; } - set { + set + { MappingStart = new MappingStart(_mappingStart.Anchor, value, string.IsNullOrEmpty(value), @@ -96,9 +109,11 @@ public override string Tag { } } - public override YamlStyle Style { + public override YamlStyle Style + { get { return _mappingStart.Style; } - set { + set + { MappingStart = new MappingStart(_mappingStart.Anchor, _mappingStart.Tag, _mappingStart.IsImplicit, @@ -110,9 +125,11 @@ public override YamlStyle Style { public override bool IsCanonical { get { return _mappingStart.IsCanonical; } } - public override bool IsImplicit { + public override bool IsImplicit + { get { return _mappingStart.IsImplicit; } - set { + set + { MappingStart = new MappingStart(_mappingStart.Anchor, _mappingStart.Tag, value, @@ -122,12 +139,14 @@ public override bool IsImplicit { } } - public static YamlMapping Load(EventReader eventReader, YamlNodeTracker tracker) { + public static YamlMapping Load(EventReader eventReader, YamlNodeTracker tracker) + { var mappingStart = eventReader.Allow(); List keys = new List(); Dictionary contents = new Dictionary(); - while (!eventReader.Accept()) { + while (!eventReader.Accept()) + { var key = ReadElement(eventReader, tracker); var value = ReadElement(eventReader, tracker); @@ -142,20 +161,24 @@ public static YamlMapping Load(EventReader eventReader, YamlNodeTracker tracker) return new YamlMapping(mappingStart, mappingEnd, keys, contents, tracker); } - - IEnumerator IEnumerable.GetEnumerator() { + + IEnumerator IEnumerable.GetEnumerator() + { return GetEnumerator(); } - public IEnumerator> GetEnumerator() { + public IEnumerator> GetEnumerator() + { return _keys.Select(k => new KeyValuePair(k, _contents[k])).GetEnumerator(); } - void ICollection>.Add(KeyValuePair item) { + void ICollection>.Add(KeyValuePair item) + { Add(item.Key, item.Value); } - public void Clear() { + public void Clear() + { var values = Tracker == null ? null : this.ToList(); _contents.Clear(); @@ -163,36 +186,43 @@ public void Clear() { stringKeys = null; - if (Tracker != null) { + if (Tracker != null) + { for (int i = values.Count - 1; i >= 0; i--) Tracker.OnMappingRemovePair(this, values[i], i, null); } } - bool ICollection>.Contains(KeyValuePair item) { + bool ICollection>.Contains(KeyValuePair item) + { return _contents.ContainsKey(item.Key); } - void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) { + void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) + { ((ICollection>)_contents).CopyTo(array, arrayIndex); } - bool ICollection>.Remove(KeyValuePair item) { + bool ICollection>.Remove(KeyValuePair item) + { return Remove(item.Key); } public int Count { get { return _contents.Count; } } public bool IsReadOnly { get { return false; } } - public void Add(YamlElement key, YamlElement value) { + public void Add(YamlElement key, YamlElement value) + { _contents.Add(key, value); _keys.Add(key); - if (stringKeys != null && key is YamlValue value1) { + if (stringKeys != null && key is YamlValue value1) + { stringKeys[value1.Value] = value1; } - if (Tracker != null) { + if (Tracker != null) + { key.Tracker = Tracker; value.Tracker = Tracker; @@ -200,15 +230,18 @@ public void Add(YamlElement key, YamlElement value) { } } - public override YamlNodeTracker Tracker { + public override YamlNodeTracker Tracker + { get { return base.Tracker; } - internal set { + internal set + { if (Tracker == value) return; base.Tracker = value; - for (var i = 0; i < _keys.Count; i++) { + for (var i = 0; i < _keys.Count; i++) + { var val = _contents[_keys[i]]; _keys[i].Tracker = value; @@ -219,20 +252,24 @@ internal set { } } - public bool ContainsKey(YamlElement key) { + public bool ContainsKey(YamlElement key) + { return _contents.ContainsKey(key); } - public bool ContainsKey(string key) { + public bool ContainsKey(string key) + { if (stringKeys == null) stringKeys = Keys.OfType().ToDictionary(k => k.Value, k => k); return stringKeys.ContainsKey(key); } - public bool Remove(YamlElement key) { + public bool Remove(YamlElement key) + { var index = _keys.IndexOf(key); - if (index >= 0) { + if (index >= 0) + { RemoveAt(index); return true; } @@ -241,14 +278,16 @@ public bool Remove(YamlElement key) { } - public bool Remove(string key) { + public bool Remove(string key) + { if (stringKeys == null) stringKeys = Keys.OfType().ToDictionary(k => k.Value, k => k); if (!stringKeys.TryGetValue(key, out YamlValue yaml)) return false; - if (Remove(yaml)) { + if (Remove(yaml)) + { stringKeys.Remove(key); return true; } @@ -256,11 +295,13 @@ public bool Remove(string key) { return false; } - public bool TryGetValue(YamlElement key, out YamlElement value) { + public bool TryGetValue(YamlElement key, out YamlElement value) + { return _contents.TryGetValue(key, out value); } - public bool TryGetValue(string key, out YamlElement value) { + public bool TryGetValue(string key, out YamlElement value) + { if (stringKeys == null) stringKeys = Keys.OfType().ToDictionary(k => k.Value, k => k); @@ -273,42 +314,52 @@ public bool TryGetValue(string key, out YamlElement value) { return TryGetValue(yamlKey, out value); } - public YamlElement this[YamlElement key] { - get { + public YamlElement this[YamlElement key] + { + get + { if (!_contents.ContainsKey(key)) return null; return _contents[key]; } - set { + set + { var keyAdded = false; - if (!_contents.ContainsKey(key)) { + if (!_contents.ContainsKey(key)) + { _keys.Add(key); keyAdded = true; - if (stringKeys != null && key is YamlValue yamlValue) { + if (stringKeys != null && key is YamlValue yamlValue) + { stringKeys[yamlValue.Value] = yamlValue; } } YamlElement oldContents = null; - if (!keyAdded && Tracker != null) { + if (!keyAdded && Tracker != null) + { oldContents = _contents[key]; - - if (stringKeys != null && key is YamlValue yamlValue) { + + if (stringKeys != null && key is YamlValue yamlValue) + { stringKeys[yamlValue.Value] = yamlValue; } } _contents[key] = value; - if (Tracker != null) { - if (keyAdded) { + if (Tracker != null) + { + if (keyAdded) + { key.Tracker = Tracker; value.Tracker = Tracker; Tracker.OnMappingAddPair(this, new KeyValuePair(key, value), _keys.Count - 1, null); } - else { + else + { value.Tracker = Tracker; Tracker.OnMappingPairChanged(this, _keys.IndexOf(key), new KeyValuePair(key, oldContents), @@ -318,8 +369,10 @@ public YamlElement this[YamlElement key] { } } - public YamlElement this[string key] { - get { + public YamlElement this[string key] + { + get + { if (stringKeys == null) stringKeys = Keys.OfType().ToDictionary(k => k.Value, k => k); @@ -328,13 +381,14 @@ public YamlElement this[string key] { return this[stringKeys[key]]; } - set { + set + { if (stringKeys == null) stringKeys = Keys.OfType().ToDictionary(k => k.Value, k => k); - if (!stringKeys.ContainsKey(key)) + if (!stringKeys.ContainsKey(key)) stringKeys[key] = new YamlValue(key); - + this[stringKeys[key]] = value; } } @@ -342,45 +396,52 @@ public YamlElement this[string key] { public ICollection Keys { get { return _keys; } } public ICollection Values { get { return _contents.Values; } } - public int IndexOf(KeyValuePair item) { + public int IndexOf(KeyValuePair item) + { return _keys.IndexOf(item.Key); } - public void Insert(int index, KeyValuePair item) { + public void Insert(int index, KeyValuePair item) + { if (_contents.ContainsKey(item.Key)) throw new Exception("Key already present."); _keys.Insert(index, item.Key); _contents[item.Key] = item.Value; - if (stringKeys != null && item.Key is YamlValue yamlValue) { + if (stringKeys != null && item.Key is YamlValue yamlValue) + { stringKeys[yamlValue.Value] = yamlValue; } - if (Tracker != null) { + if (Tracker != null) + { item.Key.Tracker = Tracker; item.Value.Tracker = Tracker; ICollection> nextChildren = null; if (index < _contents.Count - 1) nextChildren = this.Skip(index + 1).ToArray(); - + Tracker.OnMappingAddPair(this, item, index, nextChildren); } } - public void RemoveAt(int index) { + public void RemoveAt(int index) + { var key = _keys[index]; var value = _contents[key]; _keys.RemoveAt(index); _contents.Remove(key); - if (stringKeys != null && key is YamlValue value1) { + if (stringKeys != null && key is YamlValue value1) + { stringKeys.Remove(value1.Value); } - if (Tracker != null) { + if (Tracker != null) + { IEnumerable> nextChildren = null; if (index < _contents.Count) nextChildren = this.Skip(index); @@ -389,24 +450,29 @@ public void RemoveAt(int index) { } } - public KeyValuePair this[int index] { + public KeyValuePair this[int index] + { get { return new KeyValuePair(_keys[index], _contents[_keys[index]]); } - set { + set + { if (_keys[index] != value.Key && _contents.ContainsKey(value.Key)) throw new Exception("Key already present at a different index."); var oldKey = _keys[index]; var oldValue = _contents[oldKey]; - if (_keys[index] != value.Key) { + if (_keys[index] != value.Key) + { _contents.Remove(_keys[index]); } - if (stringKeys != null && oldKey is YamlValue yamlValue) { + if (stringKeys != null && oldKey is YamlValue yamlValue) + { stringKeys[yamlValue.Value] = yamlValue; } - if (stringKeys != null && value.Key is YamlValue key) { + if (stringKeys != null && value.Key is YamlValue key) + { stringKeys[key.Value] = key; } @@ -414,7 +480,8 @@ public KeyValuePair this[int index] { _contents[value.Key] = value.Value; - if (Tracker != null) { + if (Tracker != null) + { value.Key.Tracker = Tracker; value.Value.Tracker = Tracker; Tracker.OnMappingPairChanged(this, index, @@ -424,7 +491,8 @@ public KeyValuePair this[int index] { } } - public override YamlNode DeepClone(YamlNodeTracker tracker = null) { + public override YamlNode DeepClone(YamlNodeTracker tracker = null) + { var keysClone = new List(_keys.Count); for (var i = 0; i < _keys.Count; i++) keysClone.Add((YamlElement)_keys[i].DeepClone()); @@ -432,7 +500,7 @@ public override YamlNode DeepClone(YamlNodeTracker tracker = null) { var cloneContents = new Dictionary(); for (var i = 0; i < _keys.Count; i++) - cloneContents[keysClone[i]] = (YamlElement) _contents[_keys[i]].DeepClone(); + cloneContents[keysClone[i]] = (YamlElement)_contents[_keys[i]].DeepClone(); return new YamlMapping(_mappingStart, _mappingEnd, @@ -441,4 +509,4 @@ public override YamlNode DeepClone(YamlNodeTracker tracker = null) { tracker); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Model/YamlNode.cs b/src/SharpYaml/Model/YamlNode.cs index 9224f0d7..026b4386 100644 --- a/src/SharpYaml/Model/YamlNode.cs +++ b/src/SharpYaml/Model/YamlNode.cs @@ -29,11 +29,14 @@ using Scalar = SharpYaml.Events.Scalar; using StreamStart = SharpYaml.Events.StreamStart; -namespace SharpYaml.Model { - public abstract class YamlNode { +namespace SharpYaml.Model +{ + public abstract class YamlNode + { public virtual YamlNodeTracker Tracker { get; internal set; } - protected static YamlElement ReadElement(EventReader eventReader, YamlNodeTracker tracker = null) { + protected static YamlElement ReadElement(EventReader eventReader, YamlNodeTracker tracker = null) + { if (eventReader.Accept()) return YamlMapping.Load(eventReader, tracker); @@ -46,15 +49,18 @@ protected static YamlElement ReadElement(EventReader eventReader, YamlNodeTracke return null; } - public IEnumerable EnumerateEvents() { + public IEnumerable EnumerateEvents() + { return new YamlNodeEventEnumerator(this); } - public void WriteTo(TextWriter writer, bool suppressDocumentTags = false) { + public void WriteTo(TextWriter writer, bool suppressDocumentTags = false) + { WriteTo(new Emitter(writer), suppressDocumentTags); } - public void WriteTo(IEmitter emitter, bool suppressDocumentTags = false) { + public void WriteTo(IEmitter emitter, bool suppressDocumentTags = false) + { var events = EnumerateEvents().ToList(); // Emitter will throw an exception if we attempt to use it without @@ -65,9 +71,12 @@ public void WriteTo(IEmitter emitter, bool suppressDocumentTags = false) { if (!(events[1] is DocumentStart)) events.Insert(1, new DocumentStart()); - foreach (var evnt in events) { - if (suppressDocumentTags) { - if (evnt is DocumentStart document && document.Tags != null) { + foreach (var evnt in events) + { + if (suppressDocumentTags) + { + if (evnt is DocumentStart document && document.Tags != null) + { document.Tags.Clear(); } } @@ -76,7 +85,8 @@ public void WriteTo(IEmitter emitter, bool suppressDocumentTags = false) { } } - public override string ToString() { + public override string ToString() + { var sb = new StringBuilder(); WriteTo(new StringWriter(sb), true); return sb.ToString().Trim(); @@ -84,7 +94,7 @@ public override string ToString() { public T ToObject(SerializerSettings settings = null) { - return (T) ToObject(typeof(T), settings); + return (T)ToObject(typeof(T), settings); } public object ToObject(Type type, SerializerSettings settings = null) @@ -95,15 +105,18 @@ public object ToObject(Type type, SerializerSettings settings = null) return context.ReadYaml(null, type); } - class MemoryEmitter : IEmitter { + class MemoryEmitter : IEmitter + { public List Events = new List(); - public void Emit(ParsingEvent evnt) { + public void Emit(ParsingEvent evnt) + { Events.Add(evnt); } } - public static YamlElement FromObject(object value, SerializerSettings settings = null, Type expectedType = null) { + public static YamlElement FromObject(object value, SerializerSettings settings = null, Type expectedType = null) + { var s = new Serializer(settings); var emitter = new MemoryEmitter(); diff --git a/src/SharpYaml/Model/YamlNodeEventEnumerator.cs b/src/SharpYaml/Model/YamlNodeEventEnumerator.cs index 28bb1b3e..358f53e6 100644 --- a/src/SharpYaml/Model/YamlNodeEventEnumerator.cs +++ b/src/SharpYaml/Model/YamlNodeEventEnumerator.cs @@ -1,4 +1,4 @@ -// Copyright (c) SharpYaml - Alexandre Mutel +// Copyright (c) SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -21,59 +21,71 @@ using System.Collections.Generic; using SharpYaml.Events; -namespace SharpYaml.Model { - public sealed class YamlNodeEventEnumerator : IEnumerable, IEnumerator { +namespace SharpYaml.Model +{ + public sealed class YamlNodeEventEnumerator : IEnumerable, IEnumerator + { private readonly YamlNode root; private YamlNode currentNode; private int currentIndex; private Stack nodePath; private Stack indexPath; - public YamlNodeEventEnumerator(YamlNode root) { + public YamlNodeEventEnumerator(YamlNode root) + { this.root = root; currentNode = root; currentIndex = -1; } - public IEnumerator GetEnumerator() { + public IEnumerator GetEnumerator() + { return this; } - IEnumerator IEnumerable.GetEnumerator() { + IEnumerator IEnumerable.GetEnumerator() + { return GetEnumerator(); } public void Dispose() { } - public bool MoveNext() { + public bool MoveNext() + { if (currentNode == null) return false; - - if (currentNode is YamlStream stream) { - if (currentIndex == -1) { + + if (currentNode is YamlStream stream) + { + if (currentIndex == -1) + { Current = stream.StreamStart; currentIndex++; return true; - } - - if (currentIndex < stream.Count) { + } + + if (currentIndex < stream.Count) + { Push(stream[currentIndex]); return true; - } - + } + Current = stream.StreamEnd; Pop(); return true; } - if (currentNode is YamlDocument document) { - if (currentIndex == -1) { + if (currentNode is YamlDocument document) + { + if (currentIndex == -1) + { Current = document.DocumentStart; currentIndex++; return true; } - if (currentIndex < 1) { + if (currentIndex < 1) + { Push(document.Contents); return true; } @@ -83,16 +95,19 @@ public bool MoveNext() { return true; } - if (currentNode is YamlMapping mapping) { - if (currentIndex == -1) { + if (currentNode is YamlMapping mapping) + { + if (currentIndex == -1) + { Current = mapping.MappingStart; currentIndex++; return true; } - if (currentIndex < mapping.Count * 2) { - if (currentIndex % 2 == 0) - Push(((List) mapping.Keys)[currentIndex / 2]); + if (currentIndex < mapping.Count * 2) + { + if (currentIndex % 2 == 0) + Push(((List)mapping.Keys)[currentIndex / 2]); else Push(mapping[(currentIndex - 1) / 2].Value); return true; @@ -103,14 +118,17 @@ public bool MoveNext() { return true; } - if (currentNode is YamlSequence sequence) { - if (currentIndex == -1) { + if (currentNode is YamlSequence sequence) + { + if (currentIndex == -1) + { Current = sequence.SequenceStart; currentIndex++; return true; } - if (currentIndex < sequence.Count) { + if (currentIndex < sequence.Count) + { Push(sequence[currentIndex]); return true; } @@ -120,7 +138,8 @@ public bool MoveNext() { return true; } - if (currentNode is YamlValue value) { + if (currentNode is YamlValue value) + { Current = value.Scalar; Pop(); return true; @@ -129,18 +148,21 @@ public bool MoveNext() { return false; } - void Push(YamlNode nextNode) { - if (nextNode is YamlValue value) { + void Push(YamlNode nextNode) + { + if (nextNode is YamlValue value) + { Current = value.Scalar; currentIndex++; return; } - if (nodePath == null) { + if (nodePath == null) + { nodePath = new Stack(); indexPath = new Stack(); } - + nodePath.Push(currentNode); indexPath.Push(currentIndex); currentNode = nextNode; @@ -148,17 +170,20 @@ void Push(YamlNode nextNode) { MoveNext(); } - void Pop() { - if (currentNode == root) { + void Pop() + { + if (currentNode == root) + { currentNode = null; return; } - + currentNode = nodePath.Pop(); currentIndex = indexPath.Pop() + 1; } - - public void Reset() { + + public void Reset() + { Current = null; nodePath.Clear(); indexPath.Clear(); @@ -170,4 +195,4 @@ public void Reset() { object IEnumerator.Current => Current; } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Model/YamlNodeTracker.cs b/src/SharpYaml/Model/YamlNodeTracker.cs index ca6feb16..fd39b7d0 100644 --- a/src/SharpYaml/Model/YamlNodeTracker.cs +++ b/src/SharpYaml/Model/YamlNodeTracker.cs @@ -2,21 +2,26 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; -using SharpYaml.Events; using System.Runtime.CompilerServices; +using SharpYaml.Events; -namespace SharpYaml.Model { - public struct ChildIndex { +namespace SharpYaml.Model +{ + public struct ChildIndex + { public int Index; public bool IsKey; - public ChildIndex(int index, bool isKey) { + public ChildIndex(int index, bool isKey) + { Index = index; IsKey = isKey; } - public YamlNode Resolve(YamlNode parent) { - if (parent is YamlStream stream) { + public YamlNode Resolve(YamlNode parent) + { + if (parent is YamlStream stream) + { if (IsKey) return null; if (Index < 0 || Index >= stream.Count) @@ -24,13 +29,15 @@ public YamlNode Resolve(YamlNode parent) { return stream[Index]; } - if (parent is YamlDocument document) { + if (parent is YamlDocument document) + { if (IsKey || Index != -1) return null; return document.Contents; } - if (parent is YamlSequence sequence) { + if (parent is YamlSequence sequence) + { if (IsKey) return null; if (Index < 0 || Index >= sequence.Count) @@ -38,7 +45,8 @@ public YamlNode Resolve(YamlNode parent) { return sequence[Index]; } - if (parent is YamlMapping mapping) { + if (parent is YamlMapping mapping) + { if (Index < 0 || Index >= mapping.Count) return null; return IsKey @@ -49,34 +57,42 @@ public YamlNode Resolve(YamlNode parent) { return null; } - public bool Equals(ChildIndex other) { + public bool Equals(ChildIndex other) + { return Index == other.Index && IsKey == other.IsKey; } - public override bool Equals(object obj) { + public override bool Equals(object obj) + { if (ReferenceEquals(null, obj)) return false; return obj is ChildIndex index && Equals(index); } - public override int GetHashCode() { - unchecked { + public override int GetHashCode() + { + unchecked + { return (Index * 397) ^ IsKey.GetHashCode(); } } } - public struct Path { + public struct Path + { public YamlNode Root; public ChildIndex[] Indices; - public Path(YamlNode root, ChildIndex[] indices) { + public Path(YamlNode root, ChildIndex[] indices) + { Root = root; Indices = indices; } - public YamlNode Resolve() { + public YamlNode Resolve() + { var node = Root; - foreach (var index in Indices) { + foreach (var index in Indices) + { if (node == null) return null; @@ -86,40 +102,48 @@ public YamlNode Resolve() { return node; } - public bool Equals(Path other) { + public bool Equals(Path other) + { return Equals(Root, other.Root) && Indices.SequenceEqual(other.Indices); } - public override bool Equals(object obj) { + public override bool Equals(object obj) + { if (ReferenceEquals(null, obj)) return false; return obj is Path path && Equals(path); } - public override int GetHashCode() { - unchecked { + public override int GetHashCode() + { + unchecked + { var rootHashCode = (Root != null ? Root.GetHashCode() : 0) * 397; return Indices == null ? rootHashCode : Indices.Aggregate(rootHashCode, (a, b) => a ^ (b.GetHashCode() * 397)); } } - public Path Clone() { + public Path Clone() + { return new Path(Root, Indices.ToArray()); } - - public void Append(ChildIndex childIndex) { + + public void Append(ChildIndex childIndex) + { Array.Resize(ref Indices, Indices.Length + 1); Indices[Indices.Length - 1] = childIndex; } - public Path? GetParentPath() { + public Path? GetParentPath() + { if (Indices.Length == 0) return null; - + return new Path(Root, Indices.Take(Indices.Length - 1).ToArray()); } } - - public enum TrackerEventType { + + public enum TrackerEventType + { StreamDocumentAdded, StreamDocumentRemoved, StreamDocumentChanged, @@ -138,8 +162,10 @@ public enum TrackerEventType { ScalarValueChanged } - public abstract class TrackerEventArgs : EventArgs { - public TrackerEventArgs(YamlNode node, IList parentPaths) { + public abstract class TrackerEventArgs : EventArgs + { + public TrackerEventArgs(YamlNode node, IList parentPaths) + { Node = node; ParentPaths = parentPaths; } @@ -149,9 +175,11 @@ public TrackerEventArgs(YamlNode node, IList parentPaths) { public abstract TrackerEventType EventType { get; } } - public abstract class ChildEventArgs : TrackerEventArgs where TParent : YamlNode { + public abstract class ChildEventArgs : TrackerEventArgs where TParent : YamlNode + { public ChildEventArgs(TParent node, IList parentPaths, TChild child, int index) : - base(node, parentPaths) { + base(node, parentPaths) + { Child = child; Index = index; } @@ -161,9 +189,11 @@ public ChildEventArgs(TParent node, IList parentPaths, TChild child, int i public int Index { get; } } - public abstract class ChildChangedEventArgs : TrackerEventArgs where TParent : YamlNode { + public abstract class ChildChangedEventArgs : TrackerEventArgs where TParent : YamlNode + { public ChildChangedEventArgs(TParent node, IList parentPaths, TChild oldChild, TChild newChild, int index) : - base(node, parentPaths) { + base(node, parentPaths) + { OldChild = oldChild; NewChild = newChild; Index = index; @@ -175,9 +205,11 @@ public ChildChangedEventArgs(TParent node, IList parentPaths, TChild oldCh public int Index { get; } } - public abstract class PropertyChangedEventArgs : TrackerEventArgs where TNode : YamlNode { + public abstract class PropertyChangedEventArgs : TrackerEventArgs where TNode : YamlNode + { public PropertyChangedEventArgs(TNode node, IList parentPaths, TProperty oldValue, TProperty newValue) - : base(node, parentPaths) { + : base(node, parentPaths) + { OldValue = oldValue; NewValue = newValue; } @@ -187,189 +219,231 @@ public PropertyChangedEventArgs(TNode node, IList parentPaths, TProperty o public TProperty NewValue { get; } } - public class StreamDocumentAdded : ChildEventArgs { + public class StreamDocumentAdded : ChildEventArgs + { public StreamDocumentAdded(YamlStream node, IList parentPaths, YamlDocument child, int index) : base(node, parentPaths, child, index) { } - public override TrackerEventType EventType { + public override TrackerEventType EventType + { get => TrackerEventType.StreamDocumentAdded; } } - public class StreamDocumentRemoved : ChildEventArgs { + public class StreamDocumentRemoved : ChildEventArgs + { public StreamDocumentRemoved(YamlStream node, IList parentPaths, YamlDocument child, int index) : base(node, parentPaths, child, index) { } - public override TrackerEventType EventType { + public override TrackerEventType EventType + { get => TrackerEventType.StreamDocumentRemoved; } } - public class StreamDocumentChanged : ChildChangedEventArgs { + public class StreamDocumentChanged : ChildChangedEventArgs + { public StreamDocumentChanged(YamlStream node, IList parentPaths, YamlDocument oldChild, YamlDocument newChild, int index) : base(node, parentPaths, oldChild, newChild, index) { } - public override TrackerEventType EventType { + public override TrackerEventType EventType + { get => TrackerEventType.StreamDocumentChanged; } } - public class DocumentStartChanged : PropertyChangedEventArgs { + public class DocumentStartChanged : PropertyChangedEventArgs + { public DocumentStartChanged(YamlDocument node, IList parentPaths, DocumentStart oldValue, DocumentStart newValue) : base(node, parentPaths, oldValue, newValue) { } - public override TrackerEventType EventType { + public override TrackerEventType EventType + { get => TrackerEventType.DocumentStartChanged; } } - public class DocumentEndChanged : PropertyChangedEventArgs { + public class DocumentEndChanged : PropertyChangedEventArgs + { public DocumentEndChanged(YamlDocument node, IList parentPaths, DocumentEnd oldValue, DocumentEnd newValue) : base(node, parentPaths, oldValue, newValue) { } - public override TrackerEventType EventType { + public override TrackerEventType EventType + { get => TrackerEventType.DocumentEndChanged; } } - public class DocumentContentsChanged : PropertyChangedEventArgs { + public class DocumentContentsChanged : PropertyChangedEventArgs + { public DocumentContentsChanged(YamlDocument node, IList parentPaths, YamlElement oldValue, YamlElement newValue) : base(node, parentPaths, oldValue, newValue) { } - public override TrackerEventType EventType { + public override TrackerEventType EventType + { get => TrackerEventType.DocumentContentsChanged; } } - public class SequenceStartChanged : PropertyChangedEventArgs { + public class SequenceStartChanged : PropertyChangedEventArgs + { public SequenceStartChanged(YamlSequence node, IList parentPaths, SequenceStart oldValue, SequenceStart newValue) : base(node, parentPaths, oldValue, newValue) { } - public override TrackerEventType EventType { + public override TrackerEventType EventType + { get => TrackerEventType.SequenceStartChanged; } } - public class SequenceElementAdded : ChildEventArgs { + public class SequenceElementAdded : ChildEventArgs + { public SequenceElementAdded(YamlSequence node, IList parentPaths, YamlElement child, int index) : base(node, parentPaths, child, index) { } - public override TrackerEventType EventType { + public override TrackerEventType EventType + { get => TrackerEventType.SequenceElementAdded; } } - public class SequenceElementRemoved : ChildEventArgs { + public class SequenceElementRemoved : ChildEventArgs + { public SequenceElementRemoved(YamlSequence node, IList parentPaths, YamlElement child, int index) : base(node, parentPaths, child, index) { } - public override TrackerEventType EventType { + public override TrackerEventType EventType + { get => TrackerEventType.SequenceElementRemoved; } } - public class SequenceElementChanged : ChildChangedEventArgs { + public class SequenceElementChanged : ChildChangedEventArgs + { public SequenceElementChanged(YamlSequence node, IList parentPaths, YamlElement oldChild, YamlElement newChild, int index) : base(node, parentPaths, oldChild, newChild, index) { } - public override TrackerEventType EventType { + public override TrackerEventType EventType + { get => TrackerEventType.SequenceElementChanged; } } - public class MappingStartChanged : PropertyChangedEventArgs { + public class MappingStartChanged : PropertyChangedEventArgs + { public MappingStartChanged(YamlMapping node, IList parentPaths, MappingStart oldValue, MappingStart newValue) : base(node, parentPaths, oldValue, newValue) { } - public override TrackerEventType EventType { + public override TrackerEventType EventType + { get => TrackerEventType.MappingStartChanged; } } - public class MappingPairAdded : ChildEventArgs> { + public class MappingPairAdded : ChildEventArgs> + { public MappingPairAdded(YamlMapping node, IList parentPaths, KeyValuePair child, int index) : base(node, parentPaths, child, index) { } - public override TrackerEventType EventType { + public override TrackerEventType EventType + { get => TrackerEventType.MappingPairAdded; } } - public class MappingPairRemoved : ChildEventArgs> { + public class MappingPairRemoved : ChildEventArgs> + { public MappingPairRemoved(YamlMapping node, IList parentPaths, KeyValuePair child, int index) : base(node, parentPaths, child, index) { } - public override TrackerEventType EventType { + public override TrackerEventType EventType + { get => TrackerEventType.MappingPairRemoved; } } - public class MappingPairChanged : ChildChangedEventArgs> { + public class MappingPairChanged : ChildChangedEventArgs> + { public MappingPairChanged(YamlMapping node, IList parentPaths, KeyValuePair oldChild, KeyValuePair newChild, int index) : base(node, parentPaths, oldChild, newChild, index) { } - public override TrackerEventType EventType { + public override TrackerEventType EventType + { get => TrackerEventType.MappingPairChanged; } } - public class ScalarPropertiesChanged : PropertyChangedEventArgs { + public class ScalarPropertiesChanged : PropertyChangedEventArgs + { public ScalarPropertiesChanged(YamlValue node, IList parentPaths, Scalar oldValue, Scalar newValue) : base(node, parentPaths, oldValue, newValue) { } - public override TrackerEventType EventType { + public override TrackerEventType EventType + { get => TrackerEventType.ScalarPropertiesChanged; } } - public class ScalarValueChanged : PropertyChangedEventArgs { + public class ScalarValueChanged : PropertyChangedEventArgs + { public ScalarValueChanged(YamlValue node, IList parentPaths, string oldValue, string newValue) : base(node, parentPaths, oldValue, newValue) { } - public override TrackerEventType EventType { + public override TrackerEventType EventType + { get => TrackerEventType.ScalarValueChanged; } } - public class YamlNodeTracker { - readonly struct ParentAndIndex { + public class YamlNodeTracker + { + readonly struct ParentAndIndex + { public readonly YamlNode Parent; public readonly ChildIndex Index; - public ParentAndIndex(YamlNode parent, ChildIndex index) { + public ParentAndIndex(YamlNode parent, ChildIndex index) + { Parent = parent; Index = index; } - public bool Equals(ParentAndIndex other) { + public bool Equals(ParentAndIndex other) + { return Equals(Parent, other.Parent) && Index.Equals(other.Index); } - public override bool Equals(object obj) { + public override bool Equals(object obj) + { if (ReferenceEquals(null, obj)) return false; return obj is ParentAndIndex index && Equals(index); } - public override int GetHashCode() { - unchecked { + public override int GetHashCode() + { + unchecked + { return ((Parent != null ? Parent.GetHashCode() : 0) * 397) ^ Index.GetHashCode(); } } } - private ConditionalWeakTable> parents = new ConditionalWeakTable>(); + private readonly ConditionalWeakTable> parents = new ConditionalWeakTable>(); - void AddChild(YamlNode child, YamlNode parent, ChildIndex relationship) { + void AddChild(YamlNode child, YamlNode parent, ChildIndex relationship) + { var pi = new ParentAndIndex(parent, relationship); - if (!parents.TryGetValue(child, out ICollection set)) { + if (!parents.TryGetValue(child, out ICollection set)) + { set = new[] { pi }; parents.Add(child, set); return; } - if (set is ParentAndIndex[] array) { + if (set is ParentAndIndex[] array) + { if (array[0].Equals(pi)) return; - + var newSet = new HashSet(); newSet.Add(array[0]); parents.Remove(child); @@ -380,7 +454,8 @@ void AddChild(YamlNode child, YamlNode parent, ChildIndex relationship) { set.Add(pi); } - void RemoveChild(YamlNode child, YamlNode parent, ChildIndex relationship) { + void RemoveChild(YamlNode child, YamlNode parent, ChildIndex relationship) + { if (!parents.TryGetValue(child, out ICollection set)) return; @@ -390,15 +465,18 @@ void RemoveChild(YamlNode child, YamlNode parent, ChildIndex relationship) { set.Remove(new ParentAndIndex(parent, relationship)); } - void RemoveChildSubscribers(IList parentPaths, ChildIndex childIndex) { + void RemoveChildSubscribers(IList parentPaths, ChildIndex childIndex) + { if (subscribers == null) return; - foreach (var parentPath in parentPaths) { + foreach (var parentPath in parentPaths) + { var childPath = parentPath.Clone(); childPath.Append(childIndex); - foreach (var subpath in pathTrie.GetSubpaths(childPath)) { + foreach (var subpath in pathTrie.GetSubpaths(childPath)) + { subscribers.Remove(subpath); } @@ -406,18 +484,22 @@ void RemoveChildSubscribers(IList parentPaths, ChildIndex childIndex) { } } - void ShiftChild(YamlNode child, YamlNode parent, ChildIndex relationship, int shift) { + void ShiftChild(YamlNode child, YamlNode parent, ChildIndex relationship, int shift) + { if (!parents.TryGetValue(child, out ICollection set)) return; var newChildIndex = new ChildIndex(relationship.Index + shift, relationship.IsKey); - if (subscribers != null) { + if (subscribers != null) + { var oldPaths = GetPaths(child); - foreach (var oldPath in oldPaths) { + foreach (var oldPath in oldPaths) + { var newPaths = new List(); - foreach (var subpath in pathTrie.GetSubpaths(oldPath)) { + foreach (var subpath in pathTrie.GetSubpaths(oldPath)) + { if (!subscribers.TryGetValue(subpath, out Dictionary subs)) continue; @@ -435,15 +517,19 @@ void ShiftChild(YamlNode child, YamlNode parent, ChildIndex relationship, int sh } } - if (set is ParentAndIndex[] array) { + if (set is ParentAndIndex[] array) + { array[0] = new ParentAndIndex(parent, newChildIndex); - } else { + } + else + { set.Remove(new ParentAndIndex(parent, relationship)); set.Add(new ParentAndIndex(parent, newChildIndex)); } } - public IList GetPaths(YamlNode child) { + public IList GetPaths(YamlNode child) + { if (child is YamlStream) return new Path[0]; @@ -452,11 +538,14 @@ public IList GetPaths(YamlNode child) { var result = new List(); - foreach (var childRelationship in relationships) { + foreach (var childRelationship in relationships) + { var prePaths = GetPaths(childRelationship.Parent); - if (prePaths.Count > 0) { - foreach (var prePath in prePaths) { + if (prePaths.Count > 0) + { + foreach (var prePath in prePaths) + { var path = prePath; path.Append(childRelationship.Index); result.Add(path); @@ -469,36 +558,41 @@ public IList GetPaths(YamlNode child) { return result; } - internal void OnStreamAddDocument(YamlStream sender, YamlDocument newDocument, int index, ICollection nextChildren) { + internal void OnStreamAddDocument(YamlStream sender, YamlDocument newDocument, int index, ICollection nextChildren) + { var paths = GetPaths(sender); AddChild(newDocument, sender, new ChildIndex(index, false)); - if (nextChildren != null) { + if (nextChildren != null) + { // Need to iterate children in reverse so that the subscribers don't get mixed up as each index is incremented. var nextIndex = index + nextChildren.Count - 1; foreach (var nextChild in nextChildren.Reverse()) ShiftChild(nextChild, sender, new ChildIndex(nextIndex--, false), 1); } - + OnTrackerEvent(new StreamDocumentAdded(sender, paths, newDocument, index)); } - internal void OnStreamRemoveDocument(YamlStream sender, YamlDocument removedDocument, int index, IEnumerable nextChildren) { + internal void OnStreamRemoveDocument(YamlStream sender, YamlDocument removedDocument, int index, IEnumerable nextChildren) + { var paths = GetPaths(sender); RemoveChild(removedDocument, sender, new ChildIndex(index, false)); OnTrackerEvent(new StreamDocumentRemoved(sender, paths, removedDocument, index)); RemoveChildSubscribers(paths, new ChildIndex(index, false)); - - if (nextChildren != null) { + + if (nextChildren != null) + { var nextIndex = index + 1; foreach (var nextChild in nextChildren) ShiftChild(nextChild, sender, new ChildIndex(nextIndex++, false), -1); } } - internal void OnStreamDocumentChanged(YamlStream sender, int index, YamlDocument oldDocument, YamlDocument newDocument) { + internal void OnStreamDocumentChanged(YamlStream sender, int index, YamlDocument oldDocument, YamlDocument newDocument) + { if (oldDocument == newDocument) return; @@ -511,21 +605,24 @@ internal void OnStreamDocumentChanged(YamlStream sender, int index, YamlDocument OnTrackerEvent(new StreamDocumentChanged(sender, paths, oldDocument, newDocument, index)); } - internal void OnDocumentStartChanged(YamlDocument sender, DocumentStart oldValue, DocumentStart newValue) { + internal void OnDocumentStartChanged(YamlDocument sender, DocumentStart oldValue, DocumentStart newValue) + { if (oldValue == newValue) return; OnTrackerEvent(new DocumentStartChanged(sender, GetPaths(sender), oldValue, newValue)); } - internal void OnDocumentEndChanged(YamlDocument sender, DocumentEnd oldValue, DocumentEnd newValue) { + internal void OnDocumentEndChanged(YamlDocument sender, DocumentEnd oldValue, DocumentEnd newValue) + { if (oldValue == newValue) return; OnTrackerEvent(new DocumentEndChanged(sender, GetPaths(sender), oldValue, newValue)); } - internal void OnDocumentContentsChanged(YamlDocument sender, YamlElement oldValue, YamlElement newValue) { + internal void OnDocumentContentsChanged(YamlDocument sender, YamlElement oldValue, YamlElement newValue) + { if (oldValue == newValue) return; @@ -540,43 +637,49 @@ internal void OnDocumentContentsChanged(YamlDocument sender, YamlElement oldValu OnTrackerEvent(new DocumentContentsChanged(sender, paths, oldValue, newValue)); } - internal void OnSequenceStartChanged(YamlSequence sender, SequenceStart oldValue, SequenceStart newValue) { + internal void OnSequenceStartChanged(YamlSequence sender, SequenceStart oldValue, SequenceStart newValue) + { if (oldValue == newValue) return; OnTrackerEvent(new SequenceStartChanged(sender, GetPaths(sender), oldValue, newValue)); } - internal void OnSequenceAddElement(YamlSequence sender, YamlElement newElement, int index, ICollection nextChildren) { + internal void OnSequenceAddElement(YamlSequence sender, YamlElement newElement, int index, ICollection nextChildren) + { var paths = GetPaths(sender); AddChild(newElement, sender, new ChildIndex(index, false)); - if (nextChildren != null) { + if (nextChildren != null) + { // Need to iterate children in reverse so that the subscribers don't get mixed up as each index is incremented. var nextIndex = index + nextChildren.Count - 1; - foreach (var nextChild in nextChildren.Reverse()) + foreach (var nextChild in nextChildren.Reverse()) ShiftChild(nextChild, sender, new ChildIndex(nextIndex--, false), 1); } - + OnTrackerEvent(new SequenceElementAdded(sender, paths, newElement, index)); } - internal void OnSequenceRemoveElement(YamlSequence sender, YamlElement removedElement, int index, IEnumerable nextChildren) { + internal void OnSequenceRemoveElement(YamlSequence sender, YamlElement removedElement, int index, IEnumerable nextChildren) + { var paths = GetPaths(sender); RemoveChild(removedElement, sender, new ChildIndex(index, false)); - + OnTrackerEvent(new SequenceElementRemoved(sender, paths, removedElement, index)); - + RemoveChildSubscribers(paths, new ChildIndex(index, false)); - if (nextChildren != null) { + if (nextChildren != null) + { var nextIndex = index + 1; foreach (var nextChild in nextChildren) ShiftChild(nextChild, sender, new ChildIndex(nextIndex++, false), -1); } } - internal void OnSequenceElementChanged(YamlSequence sender, int index, YamlElement oldElement, YamlElement newElement) { + internal void OnSequenceElementChanged(YamlSequence sender, int index, YamlElement oldElement, YamlElement newElement) + { if (newElement == oldElement) return; @@ -588,23 +691,27 @@ internal void OnSequenceElementChanged(YamlSequence sender, int index, YamlEleme OnTrackerEvent(new SequenceElementChanged(sender, paths, oldElement, newElement, index)); } - internal void OnMappingStartChanged(YamlMapping sender, MappingStart oldValue, MappingStart newValue) { + internal void OnMappingStartChanged(YamlMapping sender, MappingStart oldValue, MappingStart newValue) + { if (oldValue == newValue) return; OnTrackerEvent(new MappingStartChanged(sender, GetPaths(sender), oldValue, newValue)); } - internal void OnMappingAddPair(YamlMapping sender, KeyValuePair newPair, int index, ICollection> nextChildren) { + internal void OnMappingAddPair(YamlMapping sender, KeyValuePair newPair, int index, ICollection> nextChildren) + { var paths = GetPaths(sender); AddChild(newPair.Key, sender, new ChildIndex(index, true)); AddChild(newPair.Value, sender, new ChildIndex(index, false)); - if (nextChildren != null) { + if (nextChildren != null) + { // Need to iterate children in reverse so that the subscribers don't get mixed up as each index is incremented. var nextIndex = index + nextChildren.Count - 1; - foreach (var nextChild in nextChildren.Reverse()) { + foreach (var nextChild in nextChildren.Reverse()) + { ShiftChild(nextChild.Key, sender, new ChildIndex(nextIndex, true), 1); ShiftChild(nextChild.Value, sender, new ChildIndex(nextIndex--, false), 1); } @@ -613,36 +720,42 @@ internal void OnMappingAddPair(YamlMapping sender, KeyValuePair removedPair, int index, IEnumerable> nextChildren) { + internal void OnMappingRemovePair(YamlMapping sender, KeyValuePair removedPair, int index, IEnumerable> nextChildren) + { var paths = GetPaths(sender); RemoveChild(removedPair.Key, sender, new ChildIndex(index, true)); RemoveChild(removedPair.Value, sender, new ChildIndex(index, false)); - + OnTrackerEvent(new MappingPairRemoved(sender, paths, removedPair, index)); RemoveChildSubscribers(paths, new ChildIndex(index, true)); RemoveChildSubscribers(paths, new ChildIndex(index, false)); - if (nextChildren != null) { + if (nextChildren != null) + { var nextIndex = index + 1; - foreach (var nextChild in nextChildren) { + foreach (var nextChild in nextChildren) + { ShiftChild(nextChild.Key, sender, new ChildIndex(nextIndex, true), -1); ShiftChild(nextChild.Value, sender, new ChildIndex(nextIndex++, false), -1); } } } - internal void OnMappingPairChanged(YamlMapping sender, int index, KeyValuePair oldPair, KeyValuePair newPair) { + internal void OnMappingPairChanged(YamlMapping sender, int index, KeyValuePair oldPair, KeyValuePair newPair) + { var paths = GetPaths(sender); - if (oldPair.Key != newPair.Key) { + if (oldPair.Key != newPair.Key) + { var r = new ChildIndex(index, true); RemoveChild(oldPair.Key, sender, r); AddChild(newPair.Key, sender, r); } - if (oldPair.Value != newPair.Value) { + if (oldPair.Value != newPair.Value) + { var r = new ChildIndex(index, false); RemoveChild(oldPair.Value, sender, r); AddChild(newPair.Value, sender, r); @@ -651,55 +764,65 @@ internal void OnMappingPairChanged(YamlMapping sender, int index, KeyValuePair(); - foreach (var path in eventArgs.ParentPaths) { + foreach (var path in eventArgs.ParentPaths) + { allPaths.Add(path); Path? parentPath = path; - do { + do + { allPaths.Add(parentPath.Value); parentPath = parentPath.Value.GetParentPath(); } while (parentPath != null); } - foreach (var path in allPaths) { + foreach (var path in allPaths) + { InvokeSubscribers(path, eventArgs); } } } - void InvokeSubscribers(Path? path, TrackerEventArgs eventArgs) { + void InvokeSubscribers(Path? path, TrackerEventArgs eventArgs) + { Dictionary dict; - if (path.HasValue) { + if (path.HasValue) + { if (!subscribers.TryGetValue(path.Value, out dict)) return; } else dict = noFilterSubscribers; - foreach (var pair in dict) { + foreach (var pair in dict) + { if (!pair.Key.IsAlive) continue; @@ -716,29 +839,36 @@ void InvokeSubscribers(Path? path, TrackerEventArgs eventArgs) { private Dictionary noFilterSubscribers; private PathTrie pathTrie; - void CompactSubscribers() { - foreach (var path in subscribers.Keys.ToArray()) { + void CompactSubscribers() + { + foreach (var path in subscribers.Keys.ToArray()) + { var dict = subscribers[path]; - foreach (var key in dict.Keys.ToArray()) { + foreach (var key in dict.Keys.ToArray()) + { if (!key.IsAlive) dict.Remove(key); } - if (dict.Count == 0) { + if (dict.Count == 0) + { subscribers.Remove(path); pathTrie.Remove(path, false); } } - foreach (var key in noFilterSubscribers.Keys.ToArray()) { + foreach (var key in noFilterSubscribers.Keys.ToArray()) + { if (!key.IsAlive) noFilterSubscribers.Remove(key); } } - public void Subscribe(object subscriber, Path? filterPath, string methodName) { - if (subscribers == null) { + public void Subscribe(object subscriber, Path? filterPath, string methodName) + { + if (subscribers == null) + { subscribers = new Dictionary>(); noFilterSubscribers = new Dictionary(); pathTrie = new PathTrie(); @@ -747,8 +877,10 @@ public void Subscribe(object subscriber, Path? filterPath, string methodName) { CompactSubscribers(); Dictionary dict; - if (filterPath.HasValue) { - if (!subscribers.TryGetValue(filterPath.Value, out dict)) { + if (filterPath.HasValue) + { + if (!subscribers.TryGetValue(filterPath.Value, out dict)) + { dict = new Dictionary(); subscribers[filterPath.Value] = dict; pathTrie.Add(filterPath.Value); @@ -765,8 +897,10 @@ public void Subscribe(object subscriber, Path? filterPath, string methodName) { dict[reference] = methodName; } - public void Unsubscribe(object subscriber) { - foreach (var pair in subscribers) { + public void Unsubscribe(object subscriber) + { + foreach (var pair in subscribers) + { pair.Value.Remove(new WeakReference(subscriber)); } } diff --git a/src/SharpYaml/Model/YamlSequence.cs b/src/SharpYaml/Model/YamlSequence.cs index 153be0f9..b4c6106b 100644 --- a/src/SharpYaml/Model/YamlSequence.cs +++ b/src/SharpYaml/Model/YamlSequence.cs @@ -24,22 +24,26 @@ namespace SharpYaml.Model { - public class YamlSequence : YamlContainer, IList { + public class YamlSequence : YamlContainer, IList + { private SequenceStart _sequenceStart; private readonly SequenceEnd _sequenceEnd; private readonly List _contents; - public YamlSequence() { + public YamlSequence() + { _sequenceStart = new SequenceStart(); _sequenceEnd = new SequenceEnd(); _contents = new List(); } - YamlSequence(SequenceStart sequenceStart, SequenceEnd sequenceEnd, List contents, YamlNodeTracker tracker) { + YamlSequence(SequenceStart sequenceStart, SequenceEnd sequenceEnd, List contents, YamlNodeTracker tracker) + { if (tracker == null) _contents = contents; - else { + else + { _contents = new List(); Tracker = tracker; @@ -49,25 +53,29 @@ public YamlSequence() { } SequenceStart = sequenceStart; - + this._sequenceEnd = sequenceEnd; } - public SequenceStart SequenceStart { + public SequenceStart SequenceStart + { get => _sequenceStart; - set { + set + { _sequenceStart = value; if (Tracker != null) Tracker.OnSequenceStartChanged(this, _sequenceStart, value); } } - + internal SequenceEnd SequenceEnd { get { return _sequenceEnd; } } - public override string Anchor { + public override string Anchor + { get { return _sequenceStart.Anchor; } - set { + set + { SequenceStart = new SequenceStart(value, _sequenceStart.Tag, _sequenceStart.IsImplicit, @@ -77,9 +85,11 @@ public override string Anchor { } } - public override string Tag { + public override string Tag + { get { return _sequenceStart.Tag; } - set { + set + { SequenceStart = new SequenceStart(_sequenceStart.Anchor, value, string.IsNullOrEmpty(value), @@ -89,9 +99,11 @@ public override string Tag { } } - public override YamlStyle Style { + public override YamlStyle Style + { get { return _sequenceStart.Style; } - set { + set + { SequenceStart = new SequenceStart(_sequenceStart.Anchor, _sequenceStart.Tag, _sequenceStart.IsImplicit, @@ -103,9 +115,11 @@ public override YamlStyle Style { public override bool IsCanonical { get { return _sequenceStart.IsCanonical; } } - public override bool IsImplicit { + public override bool IsImplicit + { get { return _sequenceStart.IsImplicit; } - set { + set + { SequenceStart = new SequenceStart(_sequenceStart.Anchor, _sequenceStart.Tag, value, @@ -115,11 +129,13 @@ public override bool IsImplicit { } } - public static YamlSequence Load(EventReader eventReader, YamlNodeTracker tracker = null) { + public static YamlSequence Load(EventReader eventReader, YamlNodeTracker tracker = null) + { var sequenceStart = eventReader.Allow(); var contents = new List(); - while (!eventReader.Accept()) { + while (!eventReader.Accept()) + { var item = ReadElement(eventReader, tracker); if (item != null) contents.Add(item); @@ -130,32 +146,39 @@ public static YamlSequence Load(EventReader eventReader, YamlNodeTracker tracker return new YamlSequence(sequenceStart, sequenceEnd, contents, tracker); } - IEnumerator IEnumerable.GetEnumerator() { + IEnumerator IEnumerable.GetEnumerator() + { return GetEnumerator(); } - public IEnumerator GetEnumerator() { + public IEnumerator GetEnumerator() + { return _contents.GetEnumerator(); } - public void Add(YamlElement item) { + public void Add(YamlElement item) + { _contents.Add(item); - if (Tracker != null) { + if (Tracker != null) + { item.Tracker = Tracker; Tracker.OnSequenceAddElement(this, item, _contents.Count - 1, null); } } - public override YamlNodeTracker Tracker { + public override YamlNodeTracker Tracker + { get { return base.Tracker; } - internal set { + internal set + { if (Tracker == value) return; base.Tracker = value; - for (var index = 0; index < _contents.Count; index++) { + for (var index = 0; index < _contents.Count; index++) + { var item = _contents[index]; item.Tracker = value; Tracker.OnSequenceAddElement(this, item, index, null); @@ -163,28 +186,34 @@ internal set { } } - public void Clear() { + public void Clear() + { var copy = Tracker == null ? null : new List(_contents); _contents.Clear(); - if (Tracker != null) { + if (Tracker != null) + { for (int i = copy.Count - 1; i >= 0; i--) Tracker.OnSequenceRemoveElement(this, copy[i], i, null); } } - public bool Contains(YamlElement item) { + public bool Contains(YamlElement item) + { return _contents.Contains(item); } - public void CopyTo(YamlElement[] array, int arrayIndex) { + public void CopyTo(YamlElement[] array, int arrayIndex) + { _contents.CopyTo(array, arrayIndex); } - public bool Remove(YamlElement item) { + public bool Remove(YamlElement item) + { var index = IndexOf(item); - if (index >= 0) { + if (index >= 0) + { RemoveAt(index); return true; } @@ -196,58 +225,67 @@ public bool Remove(YamlElement item) { public bool IsReadOnly { get { return false; } } - public int IndexOf(YamlElement item) { + public int IndexOf(YamlElement item) + { return _contents.IndexOf(item); } - public void Insert(int index, YamlElement item) { + public void Insert(int index, YamlElement item) + { _contents.Insert(index, item); - if (Tracker != null) { + if (Tracker != null) + { item.Tracker = Tracker; ICollection nextChildren = null; if (index < _contents.Count - 1) nextChildren = _contents.Skip(index + 1).ToArray(); - + Tracker.OnSequenceAddElement(this, item, index, nextChildren); } } - public void RemoveAt(int index) { + public void RemoveAt(int index) + { var oldValue = _contents[index]; _contents.RemoveAt(index); - if (Tracker != null) { + if (Tracker != null) + { IEnumerable nextChildren = null; if (index < _contents.Count) nextChildren = _contents.Skip(index); - + Tracker.OnSequenceRemoveElement(this, oldValue, index, nextChildren); } } - public YamlElement this[int index] { + public YamlElement this[int index] + { get { return _contents[index]; } - set { + set + { var oldValue = _contents[index]; _contents[index] = value; - if (Tracker != null) { + if (Tracker != null) + { value.Tracker = Tracker; Tracker.OnSequenceElementChanged(this, index, oldValue, value); } } } - public override YamlNode DeepClone(YamlNodeTracker tracker = null) { + public override YamlNode DeepClone(YamlNodeTracker tracker = null) + { var contentsClone = new List(_contents.Count); for (var i = 0; i < _contents.Count; i++) - contentsClone.Add((YamlElement) _contents[i].DeepClone()); + contentsClone.Add((YamlElement)_contents[i].DeepClone()); return new YamlSequence(_sequenceStart, _sequenceEnd, contentsClone, tracker); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Model/YamlStream.cs b/src/SharpYaml/Model/YamlStream.cs index d00bad59..9acc22e4 100644 --- a/src/SharpYaml/Model/YamlStream.cs +++ b/src/SharpYaml/Model/YamlStream.cs @@ -23,27 +23,32 @@ using System.Linq; using SharpYaml.Events; -namespace SharpYaml.Model { - public class YamlStream : YamlNode, IList { +namespace SharpYaml.Model +{ + public class YamlStream : YamlNode, IList + { private readonly StreamStart _streamStart; private readonly StreamEnd _streamEnd; private readonly List _documents; - public YamlStream(YamlNodeTracker tracker = null) { + public YamlStream(YamlNodeTracker tracker = null) + { _streamStart = new StreamStart(); _streamEnd = new StreamEnd(); _documents = new List(); Tracker = tracker; } - YamlStream(StreamStart streamStart, StreamEnd streamEnd, List documents, YamlNodeTracker tracker = null) { + YamlStream(StreamStart streamStart, StreamEnd streamEnd, List documents, YamlNodeTracker tracker = null) + { this._streamStart = streamStart; this._streamEnd = streamEnd; if (tracker == null) _documents = documents; - else { + else + { _documents = new List(); Tracker = tracker; @@ -56,11 +61,13 @@ public YamlStream(YamlNodeTracker tracker = null) { internal StreamStart StreamStart { get { return _streamStart; } } internal StreamEnd StreamEnd { get { return _streamEnd; } } - public static YamlStream Load(TextReader stream, YamlNodeTracker tracker = null) { + public static YamlStream Load(TextReader stream, YamlNodeTracker tracker = null) + { return Load(new EventReader(Parser.CreateParser(stream)), tracker); } - public static YamlStream Load(EventReader eventReader, YamlNodeTracker tracker = null) { + public static YamlStream Load(EventReader eventReader, YamlNodeTracker tracker = null) + { var streamStart = eventReader.Allow(); var documents = new List(); @@ -72,32 +79,39 @@ public static YamlStream Load(EventReader eventReader, YamlNodeTracker tracker = return new YamlStream(streamStart, streamEnd, documents, tracker); } - IEnumerator IEnumerable.GetEnumerator() { + IEnumerator IEnumerable.GetEnumerator() + { return GetEnumerator(); } - public IEnumerator GetEnumerator() { + public IEnumerator GetEnumerator() + { return _documents.GetEnumerator(); } - public void Add(YamlDocument item) { + public void Add(YamlDocument item) + { _documents.Add(item); - if (Tracker != null) { + if (Tracker != null) + { item.Tracker = Tracker; Tracker.OnStreamAddDocument(this, item, _documents.Count - 1, null); } } - public override YamlNodeTracker Tracker { + public override YamlNodeTracker Tracker + { get { return base.Tracker; } - internal set { + internal set + { if (Tracker == value) return; base.Tracker = value; - for (var index = 0; index < _documents.Count; index++) { + for (var index = 0; index < _documents.Count; index++) + { var item = _documents[index]; item.Tracker = value; Tracker.OnStreamAddDocument(this, item, index, null); @@ -105,28 +119,34 @@ internal set { } } - public void Clear() { + public void Clear() + { var copy = Tracker == null ? null : new List(_documents); _documents.Clear(); - if (Tracker != null) { + if (Tracker != null) + { for (int i = copy.Count; i >= 0; i--) Tracker.OnStreamRemoveDocument(this, copy[i], i, null); } } - public bool Contains(YamlDocument item) { + public bool Contains(YamlDocument item) + { return _documents.Contains(item); } - public void CopyTo(YamlDocument[] array, int arrayIndex) { + public void CopyTo(YamlDocument[] array, int arrayIndex) + { _documents.CopyTo(array, arrayIndex); } - public bool Remove(YamlDocument item) { + public bool Remove(YamlDocument item) + { var index = IndexOf(item); - if (index >= 0) { + if (index >= 0) + { RemoveAt(index); return true; } @@ -138,53 +158,62 @@ public bool Remove(YamlDocument item) { public bool IsReadOnly { get { return false; } } - public int IndexOf(YamlDocument item) { + public int IndexOf(YamlDocument item) + { return _documents.IndexOf(item); } - public void Insert(int index, YamlDocument item) { + public void Insert(int index, YamlDocument item) + { _documents.Insert(index, item); - if (Tracker != null) { + if (Tracker != null) + { item.Tracker = Tracker; ICollection nextDocuments = null; if (index < _documents.Count - 1) nextDocuments = _documents.Skip(index + 1).ToArray(); - + Tracker.OnStreamAddDocument(this, item, index, nextDocuments); } } - public void RemoveAt(int index) { + public void RemoveAt(int index) + { var oldValue = _documents[index]; _documents.RemoveAt(index); - if (Tracker != null) { + if (Tracker != null) + { IEnumerable nextDocuments = null; if (index < _documents.Count) nextDocuments = _documents.Skip(index); - + Tracker.OnStreamRemoveDocument(this, oldValue, index, nextDocuments); } } - public YamlDocument this[int index] { + public YamlDocument this[int index] + { get { return _documents[index]; } - set { + set + { var oldValue = _documents[index]; _documents[index] = value; - if (Tracker != null) { + if (Tracker != null) + { value.Tracker = Tracker; Tracker.OnStreamDocumentChanged(this, index, oldValue, value); } } } - public override YamlNode DeepClone(YamlNodeTracker tracker = null) { + public override YamlNode DeepClone(YamlNodeTracker tracker = null) + { var documentsClone = new List(_documents.Count); for (var i = 0; i < _documents.Count; i++) documentsClone.Add((YamlDocument)_documents[i].DeepClone()); @@ -192,4 +221,4 @@ public override YamlNode DeepClone(YamlNodeTracker tracker = null) { return new YamlStream(_streamStart, _streamEnd, documentsClone, tracker); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Model/YamlValue.cs b/src/SharpYaml/Model/YamlValue.cs index adfee768..f2f5e12f 100644 --- a/src/SharpYaml/Model/YamlValue.cs +++ b/src/SharpYaml/Model/YamlValue.cs @@ -26,16 +26,19 @@ namespace SharpYaml.Model { - public class YamlValue : YamlElement { + public class YamlValue : YamlElement + { private Scalar _scalar; - YamlValue(Scalar scalar, YamlNodeTracker tracker) { + YamlValue(Scalar scalar, YamlNodeTracker tracker) + { Tracker = tracker; Scalar = scalar ?? throw new ArgumentNullException(nameof(scalar)); } - public YamlValue(object value, IYamlSchema schema = null) { + public YamlValue(object value, IYamlSchema schema = null) + { var valueString = PrimitiveSerializer.ConvertValue(value); if (schema == null) schema = CoreSchema.Instance; @@ -43,9 +46,11 @@ public YamlValue(object value, IYamlSchema schema = null) { Scalar = new Scalar(schema.GetDefaultTag(value.GetType()), valueString); } - internal Scalar Scalar { + internal Scalar Scalar + { get { return _scalar; } - set { + set + { var oldScalar = _scalar; _scalar = value; @@ -55,19 +60,23 @@ internal Scalar Scalar { } } - public static YamlValue Load(EventReader eventReader, YamlNodeTracker tracker = null) { + public static YamlValue Load(EventReader eventReader, YamlNodeTracker tracker = null) + { var scalar = eventReader.Allow(); return new YamlValue(scalar, tracker); } - public override YamlNode DeepClone(YamlNodeTracker tracker = null) { + public override YamlNode DeepClone(YamlNodeTracker tracker = null) + { return new YamlValue(_scalar, tracker); } - public override string Anchor { + public override string Anchor + { get { return _scalar.Anchor; } - set { + set + { Scalar = new Scalar(value, _scalar.Tag, _scalar.Value, @@ -79,9 +88,11 @@ public override string Anchor { } } - public override string Tag { + public override string Tag + { get { return _scalar.Tag; } - set { + set + { Scalar = new Scalar(_scalar.Anchor, value, _scalar.Value, @@ -93,9 +104,11 @@ public override string Tag { } } - public ScalarStyle Style { + public ScalarStyle Style + { get { return _scalar.Style; } - set { + set + { Scalar = new Scalar(_scalar.Anchor, _scalar.Tag, _scalar.Value, @@ -109,9 +122,11 @@ public ScalarStyle Style { public override bool IsCanonical { get { return _scalar.IsCanonical; } } - public bool IsPlainImplicit { + public bool IsPlainImplicit + { get { return _scalar.IsPlainImplicit; } - set { + set + { Scalar = new Scalar(_scalar.Anchor, _scalar.Tag, _scalar.Value, @@ -123,9 +138,11 @@ public bool IsPlainImplicit { } } - public bool IsQuotedImplicit { + public bool IsQuotedImplicit + { get { return _scalar.IsQuotedImplicit; } - set { + set + { Scalar = new Scalar(_scalar.Anchor, _scalar.Tag, _scalar.Value, @@ -137,9 +154,11 @@ public bool IsQuotedImplicit { } } - public string Value { + public string Value + { get { return _scalar.Value; } - set { + set + { var oldValue = _scalar.Value; Scalar = new Scalar(_scalar.Anchor, @@ -156,4 +175,4 @@ public string Value { } } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Parser.cs b/src/SharpYaml/Parser.cs index 238d4cbf..67e04b1c 100644 --- a/src/SharpYaml/Parser.cs +++ b/src/SharpYaml/Parser.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -44,8 +44,8 @@ // SOFTWARE. using System; -using System.Diagnostics; using System.Collections.Generic; +using System.Diagnostics; using System.IO; using SharpYaml.Events; using SharpYaml.Tokens; @@ -53,15 +53,17 @@ using DocumentEnd = SharpYaml.Tokens.DocumentEnd; using DocumentStart = SharpYaml.Tokens.DocumentStart; using Event = SharpYaml.Events.ParsingEvent; -using YamlStyle = SharpYaml.YamlStyle; using Scalar = SharpYaml.Tokens.Scalar; using StreamEnd = SharpYaml.Tokens.StreamEnd; using StreamStart = SharpYaml.Tokens.StreamStart; +using YamlStyle = SharpYaml.YamlStyle; namespace SharpYaml { - public static class Parser { - public static IParser CreateParser(TextReader reader) { + public static class Parser + { + public static IParser CreateParser(TextReader reader) + { var stringReader = reader as StringReader; if (stringReader != null) return new Parser(new StringLookAheadBuffer(stringReader.ReadToEnd())); @@ -69,7 +71,7 @@ public static IParser CreateParser(TextReader reader) { else return new Parser(new LookAheadBuffer(reader, Scanner.MaxBufferLength)); } } - + /// /// Parses YAML streams. /// @@ -95,7 +97,7 @@ private Token GetCurrentToken() } return currentToken; } - + /// /// Initializes a new instance of the class. /// @@ -959,4 +961,4 @@ private Event ParseFlowMappingValue(bool isEmpty) return ProcessEmptyScalar(GetCurrentToken().Start); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/ParserState.cs b/src/SharpYaml/ParserState.cs index 7d6fc9b8..044a0909 100644 --- a/src/SharpYaml/ParserState.cs +++ b/src/SharpYaml/ParserState.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -172,4 +172,4 @@ internal enum ParserState /// YAML_PARSE_END_STATE } -} \ No newline at end of file +} diff --git a/src/SharpYaml/ScalarStyle.cs b/src/SharpYaml/ScalarStyle.cs index cc763413..c729cfab 100644 --- a/src/SharpYaml/ScalarStyle.cs +++ b/src/SharpYaml/ScalarStyle.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -82,4 +82,4 @@ public enum ScalarStyle /// Folded, } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Scanner.cs b/src/SharpYaml/Scanner.cs index 67f0fc58..453f586d 100644 --- a/src/SharpYaml/Scanner.cs +++ b/src/SharpYaml/Scanner.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -78,7 +78,7 @@ public class Scanner where TBuffer : ILookAheadBuffer private int index = 0; private int line = 0; private int column = 0; - + /// /// Gets the current position inside the input stream. /// @@ -111,7 +111,7 @@ private static IDictionary InitializeSimpleEscapeCodes() codes.Add('"', '"'); codes.Add('\'', '\''); codes.Add('\\', '\\'); - codes.Add('/', '/'); + codes.Add('/', '/'); codes.Add('N', '\x85'); codes.Add('_', '\xA0'); codes.Add('L', '\x2028'); @@ -562,7 +562,7 @@ private void ScanToNextToken() { // Until the next token is not find. - for (;;) + for (; ; ) { // Eat whitespaces. @@ -800,7 +800,7 @@ private void FetchDocumentIndicator(bool isStartToken) Skip(); Skip(); - Token token = isStartToken ? (Token) new DocumentStart(start, CurrentPosition) : new DocumentEnd(start, start); + Token token = isStartToken ? (Token)new DocumentStart(start, CurrentPosition) : new DocumentEnd(start, start); tokens.Enqueue(token); } @@ -1497,7 +1497,7 @@ private int ScanBlockScalarBreaks(int currentIndent, StringBuilder breaks, Mark // Eat the intendation spaces and line breaks. - for (;;) + for (; ; ) { // Eat the intendation spaces. @@ -1577,7 +1577,7 @@ private Token ScanFlowScalar(bool isSingleQuoted) scanScalarWhitespaces.Length = 0; scanScalarLeadingBreak.Length = 0; scanScalarTrailingBreaks.Length = 0; - for (;;) + for (; ; ) { // Check that there are no document indicators at the beginning of the line. @@ -1689,27 +1689,33 @@ private Token ScanFlowScalar(bool isSingleQuoted) int nextCharacter = 0; // We might be dealing with a surrogate pair - try to read the next unicode character. - if (codeLength == 4 && analyzer.Check('\\', codeLength) && analyzer.Check('u', codeLength + 1)) { - for (int k = 0; k < codeLength; ++k) { - if (!analyzer.IsHex(k + codeLength + 2)) { + if (codeLength == 4 && analyzer.Check('\\', codeLength) && analyzer.Check('u', codeLength + 1)) + { + for (int k = 0; k < codeLength; ++k) + { + if (!analyzer.IsHex(k + codeLength + 2)) + { foundNextCharacter = false; break; } nextCharacter = (nextCharacter << 4) + analyzer.AsHex(k + codeLength + 2); } - if (foundNextCharacter) { + if (foundNextCharacter) + { for (int k = 0; k < codeLength + 2; ++k) Skip(); } - } else + } + else foundNextCharacter = false; if (foundNextCharacter) scanScalarValue.Append(CharHelper.ConvertFromUtf32(CharHelper.ConvertToUtf32((char)character, (char)nextCharacter))); else throw new SyntaxErrorException(start, CurrentPosition, "While parsing a quoted scalar, find invalid Unicode character escape code."); - } else + } + else scanScalarValue.Append(CharHelper.ConvertFromUtf32(character)); // Advance the pointer. @@ -1842,7 +1848,7 @@ private Token ScanPlainScalar() // Consume the content of the plain scalar. - for (;;) + for (; ; ) { // Check for a document indicator. @@ -1941,7 +1947,8 @@ private Token ScanPlainScalar() // Consume a space or a tab character. - if (!hasLeadingBlanks) { + if (!hasLeadingBlanks) + { scanScalarWhitespaces.Append(ReadCurrentCharacter()); } else @@ -1959,7 +1966,8 @@ private Token ScanPlainScalar() scanScalarLeadingBreak.Append(ReadLine()); hasLeadingBlanks = true; } - else { + else + { scanScalarTrailingBreaks.Append(ReadLine()); } } @@ -2302,7 +2310,7 @@ private int ScanVersionDirectiveNumber(Mark start) throw new SyntaxErrorException(start, CurrentPosition, "While scanning a %YAML directive, find extremely long version number."); } - value = value*10 + analyzer.AsDigit(); + value = value * 10 + analyzer.AsDigit(); Skip(); } diff --git a/src/SharpYaml/Schemas/CoreSchema.cs b/src/SharpYaml/Schemas/CoreSchema.cs index c93ada8e..d8add0b8 100644 --- a/src/SharpYaml/Schemas/CoreSchema.cs +++ b/src/SharpYaml/Schemas/CoreSchema.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -68,7 +68,7 @@ protected override void PrepareScalarRules() AddScalarRule("!!bool", @"true|True|TRUE", m => true, null); AddScalarRule("!!bool", @"false|False|FALSE", m => false, null); - AddScalarRule(new Type[] {typeof(ulong), typeof(long), typeof(int)}, "!!int", @"([-+]?(0|[1-9][0-9_]*))", DecodeInteger, null); + AddScalarRule(new Type[] { typeof(ulong), typeof(long), typeof(int) }, "!!int", @"([-+]?(0|[1-9][0-9_]*))", DecodeInteger, null); // Make float before 0x/0o to improve parsing as float are more common than 0x and 0o AddScalarRule("!!float", @"[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?", m => Convert.ToDouble(m.Value.Replace("_", ""), CultureInfo.InvariantCulture), null); @@ -86,4 +86,4 @@ protected override void PrepareScalarRules() // and in order to have a more concise set of regex } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Schemas/ExtendedSchema.cs b/src/SharpYaml/Schemas/ExtendedSchema.cs index 4cdb1812..d1baab48 100644 --- a/src/SharpYaml/Schemas/ExtendedSchema.cs +++ b/src/SharpYaml/Schemas/ExtendedSchema.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -90,7 +90,7 @@ public ExtendedSchema() protected override void PrepareScalarRules() { AddScalarRule("!!null", @"null|Null|NULL|\~|", m => null, null); - AddScalarRule(new Type[] {typeof(ulong), typeof(long), typeof(int)}, "!!int", @"([-+]?(0|[1-9][0-9_]*))", DecodeInteger, null); + AddScalarRule(new Type[] { typeof(ulong), typeof(long), typeof(int) }, "!!int", @"([-+]?(0|[1-9][0-9_]*))", DecodeInteger, null); AddScalarRule("!!int", @"([-+]?)0b([01_]+)", m => { var v = Convert.ToInt32(m.Groups[2].Value.Replace("_", ""), 2); @@ -164,4 +164,4 @@ protected override void RegisterDefaultTagMappings() RegisterDefaultTagMapping(TimestampShortTag, true); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Schemas/FailsafeSchema.cs b/src/SharpYaml/Schemas/FailsafeSchema.cs index 00467e53..a51e5b6e 100644 --- a/src/SharpYaml/Schemas/FailsafeSchema.cs +++ b/src/SharpYaml/Schemas/FailsafeSchema.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -122,4 +122,4 @@ public override bool TryParse(Scalar scalar, bool parseValue, out string default return false; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Schemas/IYamlSchema.cs b/src/SharpYaml/Schemas/IYamlSchema.cs index c5a5e78c..29e3e313 100644 --- a/src/SharpYaml/Schemas/IYamlSchema.cs +++ b/src/SharpYaml/Schemas/IYamlSchema.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -125,4 +125,4 @@ public interface IYamlSchema /// void RegisterTag(string shortTag, string longTag); } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Schemas/JsonSchema.cs b/src/SharpYaml/Schemas/JsonSchema.cs index 18d56b3d..047866f9 100644 --- a/src/SharpYaml/Schemas/JsonSchema.cs +++ b/src/SharpYaml/Schemas/JsonSchema.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -119,7 +119,7 @@ protected override void PrepareScalarRules() AddScalarRule("!!bool", @"false", m => false, null); // 10.2.1.3. Integer - AddScalarRule(new Type[] {typeof(ulong), typeof(long), typeof(int)}, "!!int", @"((0|-?[1-9][0-9_]*))", DecodeInteger, null); + AddScalarRule(new Type[] { typeof(ulong), typeof(long), typeof(int) }, "!!int", @"((0|-?[1-9][0-9_]*))", DecodeInteger, null); // 10.2.1.4. Floating Point AddScalarRule("!!float", @"-?(0|[1-9][0-9]*)(\.[0-9]*)?([eE][-+]?[0-9]+)?", m => Convert.ToDouble(m.Value.Replace("_", ""), CultureInfo.InvariantCulture), null); @@ -177,4 +177,4 @@ protected override void RegisterDefaultTagMappings() RegisterDefaultTagMapping(StrShortTag, true); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Schemas/SchemaBase.cs b/src/SharpYaml/Schemas/SchemaBase.cs index af2b7c31..1ff77871 100644 --- a/src/SharpYaml/Schemas/SchemaBase.cs +++ b/src/SharpYaml/Schemas/SchemaBase.cs @@ -316,7 +316,7 @@ protected void AddScalarRule(string tag, string regex, Func decode, { // Make sure the tag is expanded to its long form var longTag = ShortenTag(tag); - scalarTagResolutionRules.Add(new ScalarResolutionRule(longTag, regex, m => decode(m), m => encode((T) m), typeof(T))); + scalarTagResolutionRules.Add(new ScalarResolutionRule(longTag, regex, m => decode(m), m => encode((T)m), typeof(T))); } protected void AddScalarRule(Type[] types, string tag, string regex, Func decode, Func encode) @@ -466,4 +466,4 @@ public bool IsMatch(string value) } } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/SemanticErrorException.cs b/src/SharpYaml/SemanticErrorException.cs index 1821452e..c8464909 100644 --- a/src/SharpYaml/SemanticErrorException.cs +++ b/src/SharpYaml/SemanticErrorException.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -86,4 +86,4 @@ public SemanticErrorException(string message, Exception inner) { } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/AnchorEventEmitter.cs b/src/SharpYaml/Serialization/AnchorEventEmitter.cs index 7568fe8a..f3fb3745 100644 --- a/src/SharpYaml/Serialization/AnchorEventEmitter.cs +++ b/src/SharpYaml/Serialization/AnchorEventEmitter.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -141,4 +141,4 @@ public override void DocumentEnd() nextEmitter.DocumentEnd(); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/AnchorNotFoundException.cs b/src/SharpYaml/Serialization/AnchorNotFoundException.cs index 50ac212b..de3a4ac5 100644 --- a/src/SharpYaml/Serialization/AnchorNotFoundException.cs +++ b/src/SharpYaml/Serialization/AnchorNotFoundException.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -91,4 +91,4 @@ public AnchorNotFoundException(string anchorAlias, Mark start, Mark end, string /// The anchor alias. public string Alias { get; private set; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/AssemblyRegistry.cs b/src/SharpYaml/Serialization/AssemblyRegistry.cs index 60654fb9..78ce4111 100644 --- a/src/SharpYaml/Serialization/AssemblyRegistry.cs +++ b/src/SharpYaml/Serialization/AssemblyRegistry.cs @@ -137,7 +137,7 @@ public void RegisterAssembly(Assembly assembly, IAttributeRegistry attributeRegi { try { - SerializableFactories.Add((IYamlSerializableFactory) Activator.CreateInstance(type)); + SerializableFactories.Add((IYamlSerializableFactory)Activator.CreateInstance(type)); } catch { @@ -340,4 +340,4 @@ public MappedType(Type type, bool remapped) public readonly bool Remapped; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/AttributeRegistry.cs b/src/SharpYaml/Serialization/AttributeRegistry.cs index 026e07a1..cd0e55f3 100644 --- a/src/SharpYaml/Serialization/AttributeRegistry.cs +++ b/src/SharpYaml/Serialization/AttributeRegistry.cs @@ -165,9 +165,9 @@ public override int GetHashCode() { unchecked { - return (memberInfo.GetHashCode()*397) ^ inherit.GetHashCode(); + return (memberInfo.GetHashCode() * 397) ^ inherit.GetHashCode(); } } } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/CamelCaseNamingConvention.cs b/src/SharpYaml/Serialization/CamelCaseNamingConvention.cs index 5ebe5ff8..f3610026 100644 --- a/src/SharpYaml/Serialization/CamelCaseNamingConvention.cs +++ b/src/SharpYaml/Serialization/CamelCaseNamingConvention.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -38,4 +38,4 @@ public string Convert(string name) return name.Substring(0, 1).ToLowerInvariant() + name.Substring(1); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/ChainedEventEmitter.cs b/src/SharpYaml/Serialization/ChainedEventEmitter.cs index 4e7d1b17..4d0d100d 100644 --- a/src/SharpYaml/Serialization/ChainedEventEmitter.cs +++ b/src/SharpYaml/Serialization/ChainedEventEmitter.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -121,4 +121,4 @@ public virtual void StreamEnd() nextEmitter.StreamEnd(); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/ChainedObjectFactory.cs b/src/SharpYaml/Serialization/ChainedObjectFactory.cs index 63b02a83..09f3ea3b 100644 --- a/src/SharpYaml/Serialization/ChainedObjectFactory.cs +++ b/src/SharpYaml/Serialization/ChainedObjectFactory.cs @@ -68,4 +68,4 @@ public virtual object Create(Type type) return nextFactory != null ? nextFactory.Create(type) : null; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/DefaultNamingConvention.cs b/src/SharpYaml/Serialization/DefaultNamingConvention.cs index 8d86795d..32ae540f 100644 --- a/src/SharpYaml/Serialization/DefaultNamingConvention.cs +++ b/src/SharpYaml/Serialization/DefaultNamingConvention.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -34,4 +34,4 @@ public string Convert(string name) return name; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/DefaultObjectFactory.cs b/src/SharpYaml/Serialization/DefaultObjectFactory.cs index 69a5de22..957071f6 100644 --- a/src/SharpYaml/Serialization/DefaultObjectFactory.cs +++ b/src/SharpYaml/Serialization/DefaultObjectFactory.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -111,4 +111,4 @@ public object Create(Type type) return type.GetConstructor(EmptyTypes) != null || type.GetTypeInfo().IsValueType ? Activator.CreateInstance(type) : null; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/DescriptorCategory.cs b/src/SharpYaml/Serialization/DescriptorCategory.cs index a4efd8e9..a5f35543 100644 --- a/src/SharpYaml/Serialization/DescriptorCategory.cs +++ b/src/SharpYaml/Serialization/DescriptorCategory.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -85,4 +85,4 @@ public enum DescriptorCategory /// Custom } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/Descriptors/ArrayDescriptor.cs b/src/SharpYaml/Serialization/Descriptors/ArrayDescriptor.cs index 2b726106..25f77529 100644 --- a/src/SharpYaml/Serialization/Descriptors/ArrayDescriptor.cs +++ b/src/SharpYaml/Serialization/Descriptors/ArrayDescriptor.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -95,4 +95,4 @@ public Array CreateArray(int dimension) return Array.CreateInstance(ElementType, dimension); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/Descriptors/CollectionDescriptor.cs b/src/SharpYaml/Serialization/Descriptors/CollectionDescriptor.cs index 1b0731a1..870b25e7 100644 --- a/src/SharpYaml/Serialization/Descriptors/CollectionDescriptor.cs +++ b/src/SharpYaml/Serialization/Descriptors/CollectionDescriptor.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -56,7 +56,7 @@ namespace SharpYaml.Serialization.Descriptors /// public class CollectionDescriptor : ObjectDescriptor { - private static readonly List ListOfMembersToRemove = new List {"Capacity", "Count", "IsReadOnly", "IsFixedSize", "IsSynchronized", "SyncRoot", "Comparer"}; + private static readonly List ListOfMembersToRemove = new List { "Capacity", "Count", "IsReadOnly", "IsFixedSize", "IsSynchronized", "SyncRoot", "Comparer" }; private readonly Func IsReadOnlyFunction; private readonly Func GetCollectionCountFunction; @@ -86,20 +86,20 @@ public CollectionDescriptor(IAttributeRegistry attributeRegistry, Type type, boo Type itype; if ((itype = type.GetInterface(typeof(ICollection<>))) != null) { - var add = itype.GetMethod("Add", new[] {ElementType}); - CollectionAddFunction = (obj, value) => add.Invoke(obj, new[] {value}); + var add = itype.GetMethod("Add", new[] { ElementType }); + CollectionAddFunction = (obj, value) => add.Invoke(obj, new[] { value }); var countMethod = itype.GetProperty("Count").GetGetMethod(); - GetCollectionCountFunction = o => (int) countMethod.Invoke(o, null); + GetCollectionCountFunction = o => (int)countMethod.Invoke(o, null); var isReadOnly = itype.GetProperty("IsReadOnly").GetGetMethod(); - IsReadOnlyFunction = obj => (bool) isReadOnly.Invoke(obj, null); + IsReadOnlyFunction = obj => (bool)isReadOnly.Invoke(obj, null); isKeyedCollection = type.ExtendsGeneric(typeof(KeyedCollection<,>)); } // implements IList else if (typeof(IList).IsAssignableFrom(type)) { - CollectionAddFunction = (obj, value) => ((IList) obj).Add(value); - GetCollectionCountFunction = o => ((IList) o).Count; - IsReadOnlyFunction = obj => ((IList) obj).IsReadOnly; + CollectionAddFunction = (obj, value) => ((IList)obj).Add(value); + GetCollectionCountFunction = o => ((IList)o).Count; + IsReadOnlyFunction = obj => ((IList)obj).IsReadOnly; } } @@ -175,7 +175,7 @@ protected override bool PrepareMember(MemberDescriptorBase member) { // Filter members if (member is PropertyDescriptor && ListOfMembersToRemove.Contains(member.OriginalName)) - //if (member is PropertyDescriptor && (member.DeclaringType.Namespace ?? string.Empty).StartsWith(SystemCollectionsNamespace) && ListOfMembersToRemove.Contains(member.Name)) + //if (member is PropertyDescriptor && (member.DeclaringType.Namespace ?? string.Empty).StartsWith(SystemCollectionsNamespace) && ListOfMembersToRemove.Contains(member.Name)) { return false; } @@ -183,4 +183,4 @@ protected override bool PrepareMember(MemberDescriptorBase member) return !IsCompilerGenerated && base.PrepareMember(member); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/Descriptors/DefaultKeyComparer.cs b/src/SharpYaml/Serialization/Descriptors/DefaultKeyComparer.cs index 72b633aa..5a4df714 100644 --- a/src/SharpYaml/Serialization/Descriptors/DefaultKeyComparer.cs +++ b/src/SharpYaml/Serialization/Descriptors/DefaultKeyComparer.cs @@ -58,7 +58,7 @@ public virtual int Compare(object x, object y) if (x is string && y is string) { - return string.CompareOrdinal((string) x, (string) y); + return string.CompareOrdinal((string)x, (string)y); } var leftComparable = x as IComparable; @@ -71,4 +71,4 @@ public virtual int Compare(object x, object y) return rightComparable != null ? rightComparable.CompareTo(y) : 0; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/Descriptors/DictionaryDescriptor.cs b/src/SharpYaml/Serialization/Descriptors/DictionaryDescriptor.cs index dd637d65..d17730a9 100644 --- a/src/SharpYaml/Serialization/Descriptors/DictionaryDescriptor.cs +++ b/src/SharpYaml/Serialization/Descriptors/DictionaryDescriptor.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -56,7 +56,7 @@ namespace SharpYaml.Serialization.Descriptors /// public class DictionaryDescriptor : ObjectDescriptor { - private static readonly List ListOfMembersToRemove = new List {"Comparer", "Keys", "Values", "Capacity"}; + private static readonly List ListOfMembersToRemove = new List { "Comparer", "Keys", "Values", "Capacity" }; private readonly Type keyType; private readonly Type valueType; @@ -86,13 +86,13 @@ public DictionaryDescriptor(IAttributeRegistry attributeRegistry, Type type, boo valueType = interfaceType.GetGenericArguments()[1]; IsGenericDictionary = true; getEnumeratorGeneric = typeof(DictionaryDescriptor).GetMethod("GetGenericEnumerable").MakeGenericMethod(keyType, valueType); - addMethod = interfaceType.GetMethod("Add", new[] {keyType, valueType}); + addMethod = interfaceType.GetMethod("Add", new[] { keyType, valueType }); } else { keyType = typeof(object); valueType = typeof(object); - addMethod = type.GetMethod("Add", new[] {keyType, valueType}); + addMethod = type.GetMethod("Add", new[] { keyType, valueType }); } } @@ -137,7 +137,7 @@ public override void Initialize() /// true if [is read only] [the specified this object]; otherwise, false. public bool IsReadOnly(object thisObject) { - return ((IDictionary) thisObject).IsReadOnly; + return ((IDictionary)thisObject).IsReadOnly; } /// @@ -153,21 +153,21 @@ public IEnumerable> GetEnumerator(object dictionary throw new ArgumentNullException("dictionary"); if (IsGenericDictionary) { - foreach (var item in (IEnumerable>) getEnumeratorGeneric.Invoke(null, new[] {dictionary})) + foreach (var item in (IEnumerable>)getEnumeratorGeneric.Invoke(null, new[] { dictionary })) { yield return item; } } else { - var simpleDictionary = (IDictionary) dictionary; + var simpleDictionary = (IDictionary)dictionary; foreach (var keyValueObject in simpleDictionary) { if (!(keyValueObject is DictionaryEntry)) { throw new NotSupportedException($"Key value-pair type [{keyValueObject}] is not supported for IDictionary. Only DictionaryEntry"); } - var entry = (DictionaryEntry) keyValueObject; + var entry = (DictionaryEntry)keyValueObject; yield return new KeyValuePair(entry.Key, entry.Value); } } @@ -196,7 +196,7 @@ public void AddToDictionary(object dictionary, object key, object value) { throw new InvalidOperationException($"No Add() method found on dictionary [{Type}]"); } - addMethod.Invoke(dictionary, new object[] {key, value}); + addMethod.Invoke(dictionary, new object[] { key, value }); } } @@ -219,7 +219,7 @@ protected override bool PrepareMember(MemberDescriptorBase member) { // Filter members if (member is PropertyDescriptor && ListOfMembersToRemove.Contains(member.OriginalName)) - //if (member is PropertyDescriptor && (member.DeclaringType.Namespace ?? string.Empty).StartsWith(SystemCollectionsNamespace) && ListOfMembersToRemove.Contains(member.Name)) + //if (member is PropertyDescriptor && (member.DeclaringType.Namespace ?? string.Empty).StartsWith(SystemCollectionsNamespace) && ListOfMembersToRemove.Contains(member.Name)) { return false; } @@ -227,4 +227,4 @@ protected override bool PrepareMember(MemberDescriptorBase member) return base.PrepareMember(member); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/Descriptors/FieldDescriptor.cs b/src/SharpYaml/Serialization/Descriptors/FieldDescriptor.cs index c8a5100a..1b5ebb76 100644 --- a/src/SharpYaml/Serialization/Descriptors/FieldDescriptor.cs +++ b/src/SharpYaml/Serialization/Descriptors/FieldDescriptor.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -101,4 +101,4 @@ public override string ToString() return $"Field [{OriginalName}] from Type [{(FieldInfo.DeclaringType != null ? FieldInfo.DeclaringType.FullName : string.Empty)}]"; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/Descriptors/MemberDescriptorBase.cs b/src/SharpYaml/Serialization/Descriptors/MemberDescriptorBase.cs index 5220ee00..c71d8e3f 100644 --- a/src/SharpYaml/Serialization/Descriptors/MemberDescriptorBase.cs +++ b/src/SharpYaml/Serialization/Descriptors/MemberDescriptorBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -105,4 +105,4 @@ protected MemberDescriptorBase(MemberInfo memberInfo, StringComparer defaultName /// The member information. public MemberInfo MemberInfo { get; private set; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/Descriptors/NullableDescriptor.cs b/src/SharpYaml/Serialization/Descriptors/NullableDescriptor.cs index ff8768f1..cac9b7b0 100644 --- a/src/SharpYaml/Serialization/Descriptors/NullableDescriptor.cs +++ b/src/SharpYaml/Serialization/Descriptors/NullableDescriptor.cs @@ -94,4 +94,4 @@ protected override System.Collections.Generic.List PrepareMem return EmptyMembers; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/Descriptors/ObjectDescriptor.cs b/src/SharpYaml/Serialization/Descriptors/ObjectDescriptor.cs index 2724df8f..e6244031 100644 --- a/src/SharpYaml/Serialization/Descriptors/ObjectDescriptor.cs +++ b/src/SharpYaml/Serialization/Descriptors/ObjectDescriptor.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -62,17 +62,17 @@ public class ObjectDescriptor : ITypeDescriptor protected static readonly string SystemCollectionsNamespace = typeof(int).Namespace; - private readonly static object[] EmptyObjectArray = Array.Empty(); + private static readonly object[] EmptyObjectArray = Array.Empty(); private readonly Type type; private List members; private Dictionary mapMembers; private readonly bool emitDefaultValues; private readonly bool respectPrivateSetters; - private YamlStyle style; + private readonly YamlStyle style; private bool isSorted; private readonly IMemberNamingConvention memberNamingConvention; private HashSet remapMembers; - private List attributes; + private readonly List attributes; /// /// Initializes a new instance of the class. @@ -145,7 +145,7 @@ public virtual void Initialize() if (members.Count <= 0) return; - mapMembers = new Dictionary((int) (members.Count*1.2)); + mapMembers = new Dictionary((int)(members.Count * 1.2)); foreach (var member in members) { @@ -238,19 +238,19 @@ protected virtual List PrepareMembers() // Add all public properties with a readable get method var memberList = (from propertyInfo in type.GetProperties(bindingFlags) - where - propertyInfo.CanRead && propertyInfo.GetIndexParameters().Length == 0 - select new PropertyDescriptor(propertyInfo, NamingConvention.Comparer, respectPrivateSetters) + where + propertyInfo.CanRead && propertyInfo.GetIndexParameters().Length == 0 + select new PropertyDescriptor(propertyInfo, NamingConvention.Comparer, respectPrivateSetters) into member - where PrepareMember(member) - select member).Cast().ToList(); + where PrepareMember(member) + select member).Cast().ToList(); // Add all public fields foreach (var item in (from fieldInfo in type.GetFields(bindingFlags) - select new FieldDescriptor(fieldInfo, NamingConvention.Comparer) + select new FieldDescriptor(fieldInfo, NamingConvention.Comparer) into member - where PrepareMember(member) - select member)) + where PrepareMember(member) + select member)) { memberList.Add(item); } @@ -287,19 +287,19 @@ protected virtual bool PrepareMember(MemberDescriptorBase member) if (attribute is YamlMemberAttribute) { - memberAttribute = (YamlMemberAttribute) attribute; + memberAttribute = (YamlMemberAttribute)attribute; continue; } if (attribute is DefaultValueAttribute) { - defaultValueAttribute = (DefaultValueAttribute) attribute; + defaultValueAttribute = (DefaultValueAttribute)attribute; continue; } if (attribute is YamlStyleAttribute) { - styleAttribute = (YamlStyleAttribute) attribute; + styleAttribute = (YamlStyleAttribute)attribute; continue; } @@ -378,7 +378,7 @@ protected virtual bool PrepareMember(MemberDescriptorBase member) // otherwise => true var shouldSerialize = type.GetMethod("ShouldSerialize" + member.OriginalName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); if (shouldSerialize != null && shouldSerialize.ReturnType == typeof(bool) && member.ShouldSerialize == null) - member.ShouldSerialize = obj => (bool) shouldSerialize.Invoke(obj, EmptyObjectArray); + member.ShouldSerialize = obj => (bool)shouldSerialize.Invoke(obj, EmptyObjectArray); if (defaultValueAttribute != null && member.ShouldSerialize == null && !emitDefaultValues) { @@ -409,4 +409,4 @@ public override string ToString() return type.ToString(); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/Descriptors/PrimitiveDescriptor.cs b/src/SharpYaml/Serialization/Descriptors/PrimitiveDescriptor.cs index bad40304..21f07727 100644 --- a/src/SharpYaml/Serialization/Descriptors/PrimitiveDescriptor.cs +++ b/src/SharpYaml/Serialization/Descriptors/PrimitiveDescriptor.cs @@ -134,4 +134,4 @@ protected override System.Collections.Generic.List PrepareMem return EmptyMembers; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/Descriptors/PropertyDescriptor.cs b/src/SharpYaml/Serialization/Descriptors/PropertyDescriptor.cs index 176bb2b1..81aad7ca 100644 --- a/src/SharpYaml/Serialization/Descriptors/PropertyDescriptor.cs +++ b/src/SharpYaml/Serialization/Descriptors/PropertyDescriptor.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -95,7 +95,7 @@ public override object Get(object thisObject) public override void Set(object thisObject, object value) { if (HasSet) - setMethod.Invoke(thisObject, new[] {value}); + setMethod.Invoke(thisObject, new[] { value }); } public override bool HasSet { get { return setMethod != null; } } @@ -111,4 +111,4 @@ public override string ToString() return string.Format($"Property [{OriginalName}] from Type [{(PropertyInfo.DeclaringType != null ? PropertyInfo.DeclaringType.FullName : string.Empty)}]"); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/Descriptors/TypeDescriptorFactory.cs b/src/SharpYaml/Serialization/Descriptors/TypeDescriptorFactory.cs index 9d8542b5..f8c171a0 100644 --- a/src/SharpYaml/Serialization/Descriptors/TypeDescriptorFactory.cs +++ b/src/SharpYaml/Serialization/Descriptors/TypeDescriptorFactory.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -157,4 +157,4 @@ protected virtual ITypeDescriptor Create(Type type) return descriptor; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/DocumentLoadingState.cs b/src/SharpYaml/Serialization/DocumentLoadingState.cs index a036732e..2f34dcc2 100644 --- a/src/SharpYaml/Serialization/DocumentLoadingState.cs +++ b/src/SharpYaml/Serialization/DocumentLoadingState.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -133,4 +133,4 @@ public void ResolveAliases() } } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/DuplicateAnchorException.cs b/src/SharpYaml/Serialization/DuplicateAnchorException.cs index fc0cdd1e..66cd267b 100644 --- a/src/SharpYaml/Serialization/DuplicateAnchorException.cs +++ b/src/SharpYaml/Serialization/DuplicateAnchorException.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -86,4 +86,4 @@ public DuplicateAnchorException(string message, Exception inner) { } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/DynamicMemberDescriptorBase.cs b/src/SharpYaml/Serialization/DynamicMemberDescriptorBase.cs index b520ff8d..0ea3f490 100644 --- a/src/SharpYaml/Serialization/DynamicMemberDescriptorBase.cs +++ b/src/SharpYaml/Serialization/DynamicMemberDescriptorBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -73,4 +73,4 @@ protected DynamicMemberDescriptorBase(string name, Type type) public object Tag { get; set; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/EmitterState.cs b/src/SharpYaml/Serialization/EmitterState.cs index 6124fb52..5af22917 100644 --- a/src/SharpYaml/Serialization/EmitterState.cs +++ b/src/SharpYaml/Serialization/EmitterState.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -60,4 +60,4 @@ internal class EmitterState /// The emitted anchors. public HashSet EmittedAnchors { get { return emittedAnchors; } } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/EventInfo.cs b/src/SharpYaml/Serialization/EventInfo.cs index 7fe3a45e..db7c6c6e 100644 --- a/src/SharpYaml/Serialization/EventInfo.cs +++ b/src/SharpYaml/Serialization/EventInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -131,4 +131,4 @@ public SequenceEndEventInfo(object sourceValue, Type sourceType) { } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/FlatNamingConvention.cs b/src/SharpYaml/Serialization/FlatNamingConvention.cs index b304f70f..15c75fad 100644 --- a/src/SharpYaml/Serialization/FlatNamingConvention.cs +++ b/src/SharpYaml/Serialization/FlatNamingConvention.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -39,4 +39,4 @@ public string Convert(string name) return regex2.Replace(regex1.Replace(name, "$1_$2"), "$1_$2").ToLower(); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/IAttributeRegistry.cs b/src/SharpYaml/Serialization/IAttributeRegistry.cs index 771f93d1..e08c355a 100644 --- a/src/SharpYaml/Serialization/IAttributeRegistry.cs +++ b/src/SharpYaml/Serialization/IAttributeRegistry.cs @@ -114,4 +114,4 @@ public static T GetAttribute(this IAttributeRegistry attributeRegistry, Membe return attributeRegistry.GetAttributes(memberInfo, inherit).OfType().FirstOrDefault(); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/IEventEmitter.cs b/src/SharpYaml/Serialization/IEventEmitter.cs index 1888aad3..d98a8ff1 100644 --- a/src/SharpYaml/Serialization/IEventEmitter.cs +++ b/src/SharpYaml/Serialization/IEventEmitter.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -74,4 +74,4 @@ public interface IEventEmitter void StreamEnd(); } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/IMemberDescriptor.cs b/src/SharpYaml/Serialization/IMemberDescriptor.cs index c47ea158..4ee6f4c6 100644 --- a/src/SharpYaml/Serialization/IMemberDescriptor.cs +++ b/src/SharpYaml/Serialization/IMemberDescriptor.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -151,4 +151,4 @@ public interface IMemberDescriptor /// A custom tag object. object Tag { get; set; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/IMemberNamingConvention.cs b/src/SharpYaml/Serialization/IMemberNamingConvention.cs index de96c056..cde76588 100644 --- a/src/SharpYaml/Serialization/IMemberNamingConvention.cs +++ b/src/SharpYaml/Serialization/IMemberNamingConvention.cs @@ -40,4 +40,4 @@ public interface IMemberNamingConvention /// System.String. string Convert(string name); } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/IObjectFactory.cs b/src/SharpYaml/Serialization/IObjectFactory.cs index dfe5d4cd..a27dd121 100644 --- a/src/SharpYaml/Serialization/IObjectFactory.cs +++ b/src/SharpYaml/Serialization/IObjectFactory.cs @@ -60,4 +60,4 @@ public interface IObjectFactory /// object Create(Type type); } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/IObjectSerializerBackend.cs b/src/SharpYaml/Serialization/IObjectSerializerBackend.cs index 92717762..00daef59 100644 --- a/src/SharpYaml/Serialization/IObjectSerializerBackend.cs +++ b/src/SharpYaml/Serialization/IObjectSerializerBackend.cs @@ -115,4 +115,4 @@ public interface IObjectSerializerBackend /// The types. void WriteDictionaryItem(ref ObjectContext objectContext, KeyValuePair keyValue, KeyValuePair types); } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/IOrderedDictionary.cs b/src/SharpYaml/Serialization/IOrderedDictionary.cs index 87b6d59e..b9dd74ad 100644 --- a/src/SharpYaml/Serialization/IOrderedDictionary.cs +++ b/src/SharpYaml/Serialization/IOrderedDictionary.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2014 SharpYaml - Silicon Studio Corp. +// Copyright (c) 2014 SharpYaml - Silicon Studio Corp. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -54,4 +54,4 @@ public interface IOrderedDictionary : IDictionary int IndexOf(TKey key); KeyValuePair this[int index] { get; set; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/ITagTypeRegistry.cs b/src/SharpYaml/Serialization/ITagTypeRegistry.cs index 124bed55..7819b3b1 100644 --- a/src/SharpYaml/Serialization/ITagTypeRegistry.cs +++ b/src/SharpYaml/Serialization/ITagTypeRegistry.cs @@ -70,4 +70,4 @@ public interface ITagTypeRegistry : ITagTypeResolver /// if set to true the specified tag is an alias to an existing type that has already a tag associated with it (remap). void RegisterTagMapping(string tag, Type type, bool alias); } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/ITagTypeResolver.cs b/src/SharpYaml/Serialization/ITagTypeResolver.cs index d5e57178..ed475068 100644 --- a/src/SharpYaml/Serialization/ITagTypeResolver.cs +++ b/src/SharpYaml/Serialization/ITagTypeResolver.cs @@ -29,4 +29,4 @@ public interface ITagTypeResolver /// Type found for this typeName Type ResolveType(string typeName); } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/ITypeDescriptor.cs b/src/SharpYaml/Serialization/ITypeDescriptor.cs index 7e80c409..1b5e4160 100644 --- a/src/SharpYaml/Serialization/ITypeDescriptor.cs +++ b/src/SharpYaml/Serialization/ITypeDescriptor.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -116,4 +116,4 @@ public interface ITypeDescriptor /// true if this instance contains a member with the specified member name; otherwise, false. bool Contains(string memberName); } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/ITypeDescriptorFactory.cs b/src/SharpYaml/Serialization/ITypeDescriptorFactory.cs index 96e60fad..51e8db0d 100644 --- a/src/SharpYaml/Serialization/ITypeDescriptorFactory.cs +++ b/src/SharpYaml/Serialization/ITypeDescriptorFactory.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -61,4 +61,4 @@ internal interface ITypeDescriptorFactory /// ITypeDescriptor. ITypeDescriptor Find(Type type, IComparer memberComparer); } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/IYamlSerializable.cs b/src/SharpYaml/Serialization/IYamlSerializable.cs index 8e7b923d..8e3fc690 100644 --- a/src/SharpYaml/Serialization/IYamlSerializable.cs +++ b/src/SharpYaml/Serialization/IYamlSerializable.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -63,4 +63,4 @@ public interface IYamlSerializable /// The object context. void WriteYaml(ref ObjectContext objectContext); } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/IYamlSerializableFactory.cs b/src/SharpYaml/Serialization/IYamlSerializableFactory.cs index 49f6ee2c..f31aa434 100644 --- a/src/SharpYaml/Serialization/IYamlSerializableFactory.cs +++ b/src/SharpYaml/Serialization/IYamlSerializableFactory.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -60,4 +60,4 @@ public interface IYamlSerializableFactory /// If supported, return an instance of else return null. IYamlSerializable TryCreate(SerializerContext context, ITypeDescriptor typeDescriptor); } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/IYamlVisitor.cs b/src/SharpYaml/Serialization/IYamlVisitor.cs index 693bf958..ffaae98b 100644 --- a/src/SharpYaml/Serialization/IYamlVisitor.cs +++ b/src/SharpYaml/Serialization/IYamlVisitor.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -92,4 +92,4 @@ public interface IYamlVisitor /// void Visit(YamlMappingNode mapping); } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/IdentityEqualityComparer.cs b/src/SharpYaml/Serialization/IdentityEqualityComparer.cs index 2ccd7e3b..145c5f08 100644 --- a/src/SharpYaml/Serialization/IdentityEqualityComparer.cs +++ b/src/SharpYaml/Serialization/IdentityEqualityComparer.cs @@ -60,4 +60,4 @@ public int GetHashCode(T value) return RuntimeHelpers.GetHashCode(value); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/JsonEventEmitter.cs b/src/SharpYaml/Serialization/JsonEventEmitter.cs index 06506669..39fd0cbc 100644 --- a/src/SharpYaml/Serialization/JsonEventEmitter.cs +++ b/src/SharpYaml/Serialization/JsonEventEmitter.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -99,4 +99,4 @@ public override void Emit(SequenceStartEventInfo eventInfo) base.Emit(eventInfo); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/LambdaObjectFactory.cs b/src/SharpYaml/Serialization/LambdaObjectFactory.cs index 8fe13b8e..0a2589d2 100644 --- a/src/SharpYaml/Serialization/LambdaObjectFactory.cs +++ b/src/SharpYaml/Serialization/LambdaObjectFactory.cs @@ -83,4 +83,4 @@ public override object Create(Type type) return factory(type) ?? base.Create(type); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/Logging/ILogger.cs b/src/SharpYaml/Serialization/Logging/ILogger.cs index ef64fce5..cbc2cf71 100644 --- a/src/SharpYaml/Serialization/Logging/ILogger.cs +++ b/src/SharpYaml/Serialization/Logging/ILogger.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace SharpYaml.Serialization.Logging { @@ -9,4 +9,4 @@ public interface ILogger { void Log(LogLevel level, Exception ex, string message); } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/Logging/LogLevel.cs b/src/SharpYaml/Serialization/Logging/LogLevel.cs index 8e8dc98a..812f8297 100644 --- a/src/SharpYaml/Serialization/Logging/LogLevel.cs +++ b/src/SharpYaml/Serialization/Logging/LogLevel.cs @@ -1,4 +1,4 @@ -namespace SharpYaml.Serialization.Logging +namespace SharpYaml.Serialization.Logging { /// /// Severity log level. @@ -8,4 +8,4 @@ public enum LogLevel Error = 0, Warning = 1, } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/ObjectContext.cs b/src/SharpYaml/Serialization/ObjectContext.cs index 19a08f97..21e8ce9f 100644 --- a/src/SharpYaml/Serialization/ObjectContext.cs +++ b/src/SharpYaml/Serialization/ObjectContext.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -98,4 +98,4 @@ public ObjectContext(SerializerContext serializerContext, object instance, IType /// public YamlStyle Style { get; set; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/OrderedDictionary.cs b/src/SharpYaml/Serialization/OrderedDictionary.cs index e209c584..607d8a0c 100644 --- a/src/SharpYaml/Serialization/OrderedDictionary.cs +++ b/src/SharpYaml/Serialization/OrderedDictionary.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2014 SharpYaml - Silicon Studio Corp. +// Copyright (c) 2014 SharpYaml - Silicon Studio Corp. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -176,4 +176,4 @@ protected override TKey GetKeyForItem(KeyValuePair item) } } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/PascalNamingConvention.cs b/src/SharpYaml/Serialization/PascalNamingConvention.cs index c56b80bc..99ebd952 100644 --- a/src/SharpYaml/Serialization/PascalNamingConvention.cs +++ b/src/SharpYaml/Serialization/PascalNamingConvention.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -38,4 +38,4 @@ public string Convert(string name) return name.Substring(0, 1).ToUpperInvariant() + name.Substring(1); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/Serializer.cs b/src/SharpYaml/Serialization/Serializer.cs index 8f08448e..ba2dcacd 100644 --- a/src/SharpYaml/Serialization/Serializer.cs +++ b/src/SharpYaml/Serialization/Serializer.cs @@ -165,7 +165,7 @@ public void Serialize(Stream stream, object graph, Type expectedType, Serializer /// The object to serialize. public void Serialize(TextWriter writer, object graph) { - Serialize(new Emitter(writer, Settings.PreferredIndent, emitKeyQuoted:Settings.EmitJsonComptible), graph); + Serialize(new Emitter(writer, Settings.PreferredIndent, emitKeyQuoted: Settings.EmitJsonComptible), graph); } /// @@ -218,7 +218,7 @@ public void Serialize(IEmitter emitter, object graph, Type type, SerializerConte defaultEmitter.ForceIndentLess = settings.IndentLess; } - var context = new SerializerContext(this, contextSettings) {Emitter = emitter, Writer = CreateEmitter(emitter)}; + var context = new SerializerContext(this, contextSettings) { Emitter = emitter, Writer = CreateEmitter(emitter) }; // Serialize the document context.Writer.StreamStart(); @@ -245,7 +245,7 @@ public object Deserialize(Stream stream) /// A deserialized object. public object Deserialize(TextReader reader) { - return Deserialize((TextReader) reader, null); + return Deserialize((TextReader)reader, null); } /// @@ -290,7 +290,7 @@ public object Deserialize(Stream stream, Type expectedType, SerializerContextSet /// stream public T Deserialize(Stream stream) { - return (T) Deserialize(stream, typeof(T)); + return (T)Deserialize(stream, typeof(T)); } /// @@ -336,7 +336,7 @@ public object Deserialize(TextReader reader, Type expectedType, object existingO /// reader public T Deserialize(TextReader reader, object existingObject = null) { - return (T) Deserialize(reader, typeof(T), existingObject); + return (T)Deserialize(reader, typeof(T), existingObject); } /// @@ -390,7 +390,7 @@ public object Deserialize(string fromText, Type expectedType, object existingObj /// stream public T Deserialize(string fromText) { - return (T) Deserialize(fromText, typeof(T)); + return (T)Deserialize(fromText, typeof(T)); } /// @@ -402,7 +402,7 @@ public T Deserialize(string fromText) /// reader public T Deserialize(EventReader reader) { - return (T) Deserialize(reader, typeof(T)); + return (T)Deserialize(reader, typeof(T)); } /// @@ -417,7 +417,7 @@ public T Deserialize(EventReader reader) /// Note: These need a different name, because otherwise they will conflict with existing Deserialize(string,Type). They are new so the difference should not matter public T DeserializeInto(string fromText, T existingObject) { - return (T) Deserialize(fromText, typeof(T), existingObject); + return (T)Deserialize(fromText, typeof(T), existingObject); } /// @@ -430,7 +430,7 @@ public T DeserializeInto(string fromText, T existingObject) /// reader public T DeserializeInto(EventReader reader, T existingObject) { - return (T) Deserialize(reader, typeof(T), existingObject); + return (T)Deserialize(reader, typeof(T), existingObject); } /// @@ -443,7 +443,7 @@ public T DeserializeInto(EventReader reader, T existingObject) /// stream public T Deserialize(string fromText, out SerializerContext context) { - return (T) Deserialize(fromText, typeof(T), null, out context); + return (T)Deserialize(fromText, typeof(T), null, out context); } /// @@ -456,7 +456,7 @@ public T Deserialize(string fromText, out SerializerContext context) /// reader public T Deserialize(EventReader reader, out SerializerContext context) { - return (T) Deserialize(reader, typeof(T), null, null, out context); + return (T)Deserialize(reader, typeof(T), null, null, out context); } /// @@ -471,7 +471,7 @@ public T Deserialize(EventReader reader, out SerializerContext context) /// Note: These need a different name, because otherwise they will conflict with existing Deserialize(string,Type). They are new so the difference should not matter public T DeserializeInto(string fromText, T existingObject, out SerializerContext context) { - return (T) Deserialize(fromText, typeof(T), existingObject, out context); + return (T)Deserialize(fromText, typeof(T), existingObject, out context); } /// @@ -485,7 +485,7 @@ public T DeserializeInto(string fromText, T existingObject, out SerializerCon /// reader public T DeserializeInto(EventReader reader, T existingObject, out SerializerContext context) { - return (T) Deserialize(reader, typeof(T), existingObject, null, out context); + return (T)Deserialize(reader, typeof(T), existingObject, null, out context); } /// @@ -524,7 +524,7 @@ public object Deserialize(EventReader reader, Type expectedType, object existing object result = null; if (!reader.Accept() && !reader.Accept()) { - context = new SerializerContext(this, contextSettings) {Reader = reader}; + context = new SerializerContext(this, contextSettings) { Reader = reader }; result = context.ReadYaml(existingObject, expectedType); } @@ -565,7 +565,7 @@ private IYamlSerializable CreateProcessor(out RoutingSerializer routingSerialize } var typingSerializer = new TagTypeSerializer(routingSerializer); - return settings.EmitAlias ? (IYamlSerializable) new AnchorSerializer(typingSerializer) : typingSerializer; + return settings.EmitAlias ? (IYamlSerializable)new AnchorSerializer(typingSerializer) : typingSerializer; } private ITypeDescriptorFactory CreateTypeDescriptorFactory() @@ -575,7 +575,7 @@ private ITypeDescriptorFactory CreateTypeDescriptorFactory() private IEventEmitter CreateEmitter(IEmitter emitter) { - var writer = (IEventEmitter) new WriterEventEmitter(emitter); + var writer = (IEventEmitter)new WriterEventEmitter(emitter); if (settings.EmitJsonComptible) { @@ -584,4 +584,4 @@ private IEventEmitter CreateEmitter(IEmitter emitter) return Settings.EmitAlias ? new AnchorEventEmitter(writer) : writer; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/SerializerContext.cs b/src/SharpYaml/Serialization/SerializerContext.cs index e344a77e..f54cc60d 100644 --- a/src/SharpYaml/Serialization/SerializerContext.cs +++ b/src/SharpYaml/Serialization/SerializerContext.cs @@ -195,7 +195,7 @@ public object ReadYaml(object value, Type expectedType) /// public void WriteYaml(object value, Type expectedType, YamlStyle style = YamlStyle.Any) { - var objectContext = new ObjectContext(this, value, FindTypeDescriptor(expectedType)) {Style = style}; + var objectContext = new ObjectContext(this, value, FindTypeDescriptor(expectedType)) { Style = style }; ObjectSerializer.WriteYaml(ref objectContext); } @@ -252,4 +252,4 @@ public bool TryParseScalar(Scalar scalar, out string defaultTag, out object valu return Settings.Schema.TryParse(scalar, true, out defaultTag, out value); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/SerializerContextSettings.cs b/src/SharpYaml/Serialization/SerializerContextSettings.cs index 9a2c358d..22b2360b 100644 --- a/src/SharpYaml/Serialization/SerializerContextSettings.cs +++ b/src/SharpYaml/Serialization/SerializerContextSettings.cs @@ -1,4 +1,4 @@ -using SharpYaml.Serialization.Logging; +using SharpYaml.Serialization.Logging; namespace SharpYaml.Serialization { @@ -33,4 +33,4 @@ public SerializerContextSettings() /// public uint MemberMask { get; set; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/SerializerSettings.cs b/src/SharpYaml/Serialization/SerializerSettings.cs index 2ccd2936..ee36d97f 100644 --- a/src/SharpYaml/Serialization/SerializerSettings.cs +++ b/src/SharpYaml/Serialization/SerializerSettings.cs @@ -157,10 +157,10 @@ public int PreferredIndent /// /// true if to emit JSON compatible YAML; otherwise, false. [EditorBrowsable(EditorBrowsableState.Never)] - public bool EmitJsonComptible + public bool EmitJsonComptible { get => EmitJsonCompatible; - set => EmitJsonCompatible = value; + set => EmitJsonCompatible = value; } /// @@ -168,7 +168,7 @@ public bool EmitJsonComptible /// /// true if to emit JSON compatible YAML; otherwise, false. public bool EmitJsonCompatible { get; set; } - + /// /// Gets or sets a value indicating whether the property should be emitted. Default is false. /// diff --git a/src/SharpYaml/Serialization/Serializers/AnchorSerializer.cs b/src/SharpYaml/Serialization/Serializers/AnchorSerializer.cs index cb7321ed..c5661fe1 100644 --- a/src/SharpYaml/Serialization/Serializers/AnchorSerializer.cs +++ b/src/SharpYaml/Serialization/Serializers/AnchorSerializer.cs @@ -143,4 +143,4 @@ public override void WriteYaml(ref ObjectContext objectContext) base.WriteYaml(ref objectContext); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/Serializers/ArraySerializer.cs b/src/SharpYaml/Serialization/Serializers/ArraySerializer.cs index 398249b2..02458022 100644 --- a/src/SharpYaml/Serialization/Serializers/ArraySerializer.cs +++ b/src/SharpYaml/Serialization/Serializers/ArraySerializer.cs @@ -60,10 +60,10 @@ public IYamlSerializable TryCreate(SerializerContext context, ITypeDescriptor ty public virtual object ReadYaml(ref ObjectContext objectContext) { var reader = objectContext.Reader; - var arrayDescriptor = (ArrayDescriptor) objectContext.Descriptor; + var arrayDescriptor = (ArrayDescriptor)objectContext.Descriptor; bool isArray = objectContext.Instance != null && objectContext.Instance.GetType().IsArray; - var arrayList = (IList) objectContext.Instance; + var arrayList = (IList)objectContext.Instance; reader.Expect(); int index = 0; @@ -104,10 +104,10 @@ public virtual object ReadYaml(ref ObjectContext objectContext) public void WriteYaml(ref ObjectContext objectContext) { var value = objectContext.Instance; - var arrayDescriptor = (ArrayDescriptor) objectContext.Descriptor; + var arrayDescriptor = (ArrayDescriptor)objectContext.Descriptor; var valueType = value.GetType(); - var arrayList = (IList) value; + var arrayList = (IList)value; // Emit a Flow sequence or block sequence depending on settings objectContext.Writer.Emit(new SequenceStartEventInfo(value, valueType) @@ -124,4 +124,4 @@ public void WriteYaml(ref ObjectContext objectContext) objectContext.Writer.Emit(new SequenceEndEventInfo(value, valueType)); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/Serializers/ChainedSerializer.cs b/src/SharpYaml/Serialization/Serializers/ChainedSerializer.cs index bcfeaad8..56daf9f0 100644 --- a/src/SharpYaml/Serialization/Serializers/ChainedSerializer.cs +++ b/src/SharpYaml/Serialization/Serializers/ChainedSerializer.cs @@ -68,4 +68,4 @@ public virtual void WriteYaml(ref ObjectContext objectContext) next.WriteYaml(ref objectContext); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/Serializers/CollectionSerializer.cs b/src/SharpYaml/Serialization/Serializers/CollectionSerializer.cs index 8551aa20..1676c224 100644 --- a/src/SharpYaml/Serialization/Serializers/CollectionSerializer.cs +++ b/src/SharpYaml/Serialization/Serializers/CollectionSerializer.cs @@ -71,7 +71,7 @@ public override IYamlSerializable TryCreate(SerializerContext context, ITypeDesc protected override bool CheckIsSequence(ref ObjectContext objectContext) { - var collectionDescriptor = (CollectionDescriptor) objectContext.Descriptor; + var collectionDescriptor = (CollectionDescriptor)objectContext.Descriptor; // If the dictionary is pure, we can directly output a sequence instead of a mapping return collectionDescriptor.IsPureCollection; @@ -126,7 +126,7 @@ protected override void WriteMembers(ref ObjectContext objectContext) WriteMemberName(ref objectContext, null, objectContext.Settings.SpecialCollectionMember); - objectContext.Writer.Emit(new SequenceStartEventInfo(objectContext.Instance, objectContext.Instance.GetType()) {Anchor = objectContext.Anchor, Style = objectContext.Style}); + objectContext.Writer.Emit(new SequenceStartEventInfo(objectContext.Instance, objectContext.Instance.GetType()) { Anchor = objectContext.Anchor, Style = objectContext.Style }); WriteCollectionItems(ref objectContext); objectContext.Writer.Emit(new SequenceEndEventInfo(objectContext.Instance, objectContext.Instance.GetType())); } @@ -141,7 +141,7 @@ protected override void WriteMembers(ref ObjectContext objectContext) /// Cannot deserialize list to readonly collection type [{0}]..DoFormat(thisObject.GetType()) protected virtual void ReadCollectionItems(ref ObjectContext objectContext) { - var collectionDescriptor = (CollectionDescriptor) objectContext.Descriptor; + var collectionDescriptor = (CollectionDescriptor)objectContext.Descriptor; var thisObject = objectContext.Instance; if (!collectionDescriptor.HasAdd) @@ -216,8 +216,8 @@ protected virtual object ReadCollectionItem(ref ObjectContext objectContext, obj /// The object context. protected virtual void WriteCollectionItems(ref ObjectContext objectContext) { - var collectionDescriptor = (CollectionDescriptor) objectContext.Descriptor; - var collection = (IEnumerable) objectContext.Instance; + var collectionDescriptor = (CollectionDescriptor)objectContext.Descriptor; + var collection = (IEnumerable)objectContext.Instance; int index = 0; foreach (var item in collection) { @@ -238,4 +238,4 @@ protected virtual void WriteCollectionItem(ref ObjectContext objectContext, obje objectContext.ObjectSerializerBackend.WriteCollectionItem(ref objectContext, item, itemType, index); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/Serializers/DefaultObjectSerializerBackend.cs b/src/SharpYaml/Serialization/Serializers/DefaultObjectSerializerBackend.cs index 14ae2bfd..aca66cf0 100644 --- a/src/SharpYaml/Serialization/Serializers/DefaultObjectSerializerBackend.cs +++ b/src/SharpYaml/Serialization/Serializers/DefaultObjectSerializerBackend.cs @@ -64,7 +64,7 @@ public virtual YamlStyle GetStyle(ref ObjectContext objectContext) if (arrayDescriptor != null) { isPrimitiveElementType = PrimitiveDescriptor.IsPrimitive(arrayDescriptor.ElementType); - count = objectContext.Instance != null ? ((Array) objectContext.Instance).Length : -1; + count = objectContext.Instance != null ? ((Array)objectContext.Instance).Length : -1; } } @@ -145,4 +145,4 @@ public virtual void WriteDictionaryItem(ref ObjectContext objectContext, KeyValu objectContext.SerializerContext.WriteYaml(keyValue.Value, types.Value); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/Serializers/DictionarySerializer.cs b/src/SharpYaml/Serialization/Serializers/DictionarySerializer.cs index de03e49a..cc19395f 100644 --- a/src/SharpYaml/Serialization/Serializers/DictionarySerializer.cs +++ b/src/SharpYaml/Serialization/Serializers/DictionarySerializer.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -74,7 +74,7 @@ public override IYamlSerializable TryCreate(SerializerContext context, ITypeDesc protected override void ReadMember(ref ObjectContext objectContext) { - var dictionaryDescriptor = (DictionaryDescriptor) objectContext.Descriptor; + var dictionaryDescriptor = (DictionaryDescriptor)objectContext.Descriptor; if (dictionaryDescriptor.IsPureDictionary) { @@ -109,7 +109,7 @@ protected override void ReadMember(ref ObjectContext objectContext) protected override void WriteMembers(ref ObjectContext objectContext) { - var dictionaryDescriptor = (DictionaryDescriptor) objectContext.Descriptor; + var dictionaryDescriptor = (DictionaryDescriptor)objectContext.Descriptor; if (dictionaryDescriptor.IsPureDictionary) { WriteDictionaryItems(ref objectContext); @@ -133,7 +133,7 @@ protected override void WriteMembers(ref ObjectContext objectContext) WriteMemberName(ref objectContext, null, objectContext.Settings.SpecialCollectionMember); - objectContext.Writer.Emit(new MappingStartEventInfo(objectContext.Instance, objectContext.Instance.GetType()) { Anchor = objectContext.Anchor, Style = objectContext.Style}); + objectContext.Writer.Emit(new MappingStartEventInfo(objectContext.Instance, objectContext.Instance.GetType()) { Anchor = objectContext.Anchor, Style = objectContext.Style }); WriteDictionaryItems(ref objectContext); objectContext.Writer.Emit(new MappingEndEventInfo(objectContext.Instance, objectContext.Instance.GetType())); } @@ -145,7 +145,7 @@ protected override void WriteMembers(ref ObjectContext objectContext) /// protected virtual void ReadDictionaryItems(ref ObjectContext objectContext) { - var dictionaryDescriptor = (DictionaryDescriptor) objectContext.Descriptor; + var dictionaryDescriptor = (DictionaryDescriptor)objectContext.Descriptor; var reader = objectContext.Reader; while (!reader.Accept()) @@ -194,7 +194,7 @@ protected virtual KeyValuePair ReadDictionaryItem(ref ObjectCont /// The object context. protected virtual void WriteDictionaryItems(ref ObjectContext objectContext) { - var dictionaryDescriptor = (DictionaryDescriptor) objectContext.Descriptor; + var dictionaryDescriptor = (DictionaryDescriptor)objectContext.Descriptor; var keyValues = dictionaryDescriptor.GetEnumerator(objectContext.Instance).ToList(); var settings = objectContext.Settings; @@ -223,4 +223,4 @@ protected virtual void WriteDictionaryItem(ref ObjectContext objectContext, KeyV objectContext.ObjectSerializerBackend.WriteDictionaryItem(ref objectContext, keyValue, types); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/Serializers/ObjectSerializer.cs b/src/SharpYaml/Serialization/Serializers/ObjectSerializer.cs index 4554502f..55fcce83 100644 --- a/src/SharpYaml/Serialization/Serializers/ObjectSerializer.cs +++ b/src/SharpYaml/Serialization/Serializers/ObjectSerializer.cs @@ -362,13 +362,13 @@ public virtual void WriteYaml(ref ObjectContext objectContext) var context = objectContext.SerializerContext; if (isSequence) { - context.Writer.Emit(new SequenceStartEventInfo(value, typeOfValue) {Tag = objectContext.Tag, Anchor = objectContext.Anchor, Style = style}); + context.Writer.Emit(new SequenceStartEventInfo(value, typeOfValue) { Tag = objectContext.Tag, Anchor = objectContext.Anchor, Style = style }); WriteMembers(ref objectContext); context.Writer.Emit(new SequenceEndEventInfo(value, typeOfValue)); } else { - context.Writer.Emit(new MappingStartEventInfo(value, typeOfValue) {Tag = objectContext.Tag, Anchor = objectContext.Anchor, Style = style}); + context.Writer.Emit(new MappingStartEventInfo(value, typeOfValue) { Tag = objectContext.Tag, Anchor = objectContext.Anchor, Style = style }); WriteMembers(ref objectContext); context.Writer.Emit(new MappingEndEventInfo(value, typeOfValue)); } @@ -437,4 +437,4 @@ protected virtual void WriteMemberValue(ref ObjectContext objectContext, IMember objectContext.ObjectSerializerBackend.WriteMemberValue(ref objectContext, member, memberValue, memberType); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/Serializers/PrimitiveSerializer.cs b/src/SharpYaml/Serialization/Serializers/PrimitiveSerializer.cs index 41099908..622f4f94 100644 --- a/src/SharpYaml/Serialization/Serializers/PrimitiveSerializer.cs +++ b/src/SharpYaml/Serialization/Serializers/PrimitiveSerializer.cs @@ -60,7 +60,7 @@ public IYamlSerializable TryCreate(SerializerContext context, ITypeDescriptor ty public override object ConvertFrom(ref ObjectContext context, Scalar scalar) { - var primitiveType = (PrimitiveDescriptor) context.Descriptor; + var primitiveType = (PrimitiveDescriptor)context.Descriptor; var type = primitiveType.Type; var text = scalar.Value; @@ -193,11 +193,13 @@ private static string AppendDecimalPoint(string text, bool hasNaN) return text + ".0"; } - public override string ConvertTo(ref ObjectContext objectContext) { + public override string ConvertTo(ref ObjectContext objectContext) + { return ConvertValue(objectContext.Instance); } - public static string ConvertValue(object value) { + public static string ConvertValue(object value) + { var text = string.Empty; // Return null if expected type is an object and scalar is null @@ -211,7 +213,7 @@ public static string ConvertValue(object value) { // Handle string if (valueType.GetTypeInfo().IsEnum) { - text = ((Enum) Enum.ToObject(valueType, value)).ToString("G"); + text = ((Enum)Enum.ToObject(valueType, value)).ToString("G"); } else { @@ -223,31 +225,31 @@ public static string ConvertValue(object value) { text = value.ToString(); break; case TypeCode.Boolean: - text = (bool) value ? "true" : "false"; + text = (bool)value ? "true" : "false"; break; case TypeCode.Byte: - text = ((byte) value).ToString("G", CultureInfo.InvariantCulture); + text = ((byte)value).ToString("G", CultureInfo.InvariantCulture); break; case TypeCode.SByte: - text = ((sbyte) value).ToString("G", CultureInfo.InvariantCulture); + text = ((sbyte)value).ToString("G", CultureInfo.InvariantCulture); break; case TypeCode.Int16: - text = ((short) value).ToString("G", CultureInfo.InvariantCulture); + text = ((short)value).ToString("G", CultureInfo.InvariantCulture); break; case TypeCode.UInt16: - text = ((ushort) value).ToString("G", CultureInfo.InvariantCulture); + text = ((ushort)value).ToString("G", CultureInfo.InvariantCulture); break; case TypeCode.Int32: - text = ((int) value).ToString("G", CultureInfo.InvariantCulture); + text = ((int)value).ToString("G", CultureInfo.InvariantCulture); break; case TypeCode.UInt32: - text = ((uint) value).ToString("G", CultureInfo.InvariantCulture); + text = ((uint)value).ToString("G", CultureInfo.InvariantCulture); break; case TypeCode.Int64: - text = ((long) value).ToString("G", CultureInfo.InvariantCulture); + text = ((long)value).ToString("G", CultureInfo.InvariantCulture); break; case TypeCode.UInt64: - text = ((ulong) value).ToString("G", CultureInfo.InvariantCulture); + text = ((ulong)value).ToString("G", CultureInfo.InvariantCulture); break; case TypeCode.Single: // Append decimal point to floating point type values @@ -256,26 +258,26 @@ public static string ConvertValue(object value) { // G9 is used instead of R as per the following documentation: // https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings#the-round-trip-r-format-specifier // R can cause issues on x64 systems, see https://github.com/dotnet/coreclr/issues/13106 for details. - text = AppendDecimalPoint(((float) value).ToString("G9", CultureInfo.InvariantCulture), true); + text = AppendDecimalPoint(((float)value).ToString("G9", CultureInfo.InvariantCulture), true); break; case TypeCode.Double: // G17 is used instead of R due to issues on x64 systems. See documentation on TypeCode.Single case above. - text = AppendDecimalPoint(((double) value).ToString("G17", CultureInfo.InvariantCulture), true); + text = AppendDecimalPoint(((double)value).ToString("G17", CultureInfo.InvariantCulture), true); break; case TypeCode.Decimal: - text = AppendDecimalPoint(((decimal) value).ToString("G", CultureInfo.InvariantCulture), false); + text = AppendDecimalPoint(((decimal)value).ToString("G", CultureInfo.InvariantCulture), false); break; case TypeCode.DateTime: - text = ((DateTime) value).ToString("o", CultureInfo.InvariantCulture); + text = ((DateTime)value).ToString("o", CultureInfo.InvariantCulture); break; default: if (valueType == typeof(TimeSpan)) { - text = ((TimeSpan) value).ToString("G", CultureInfo.InvariantCulture); + text = ((TimeSpan)value).ToString("G", CultureInfo.InvariantCulture); } else if (valueType == typeof(DateTimeOffset)) { - text = ((DateTimeOffset) value).ToString("o", CultureInfo.InvariantCulture); + text = ((DateTimeOffset)value).ToString("o", CultureInfo.InvariantCulture); } else if (valueType == typeof(Guid)) { @@ -293,4 +295,4 @@ public static string ConvertValue(object value) { return text; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/Serializers/RoutingSerializer.cs b/src/SharpYaml/Serialization/Serializers/RoutingSerializer.cs index eb7a5a30..335f9b3a 100644 --- a/src/SharpYaml/Serialization/Serializers/RoutingSerializer.cs +++ b/src/SharpYaml/Serialization/Serializers/RoutingSerializer.cs @@ -109,4 +109,4 @@ private IYamlSerializable GetSerializer(SerializerContext context, ITypeDescript return serializer; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/Serializers/ScalarSerializerBase.cs b/src/SharpYaml/Serialization/Serializers/ScalarSerializerBase.cs index d66e3196..13dd7b62 100644 --- a/src/SharpYaml/Serialization/Serializers/ScalarSerializerBase.cs +++ b/src/SharpYaml/Serialization/Serializers/ScalarSerializerBase.cs @@ -116,4 +116,4 @@ protected virtual void WriteScalar(ref ObjectContext objectContext, ScalarEventI public abstract string ConvertTo(ref ObjectContext objectContext); } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/Serializers/TagTypeSerializer.cs b/src/SharpYaml/Serialization/Serializers/TagTypeSerializer.cs index 7c0748a0..3efad569 100644 --- a/src/SharpYaml/Serialization/Serializers/TagTypeSerializer.cs +++ b/src/SharpYaml/Serialization/Serializers/TagTypeSerializer.cs @@ -102,7 +102,7 @@ public override object ReadYaml(ref ObjectContext objectContext) object value = objectContext.Instance; // Handle explicit null scalar - if (node is Scalar && objectContext.SerializerContext.Schema.TryParse((Scalar) node, typeof(object), out value)) + if (node is Scalar && objectContext.SerializerContext.Schema.TryParse((Scalar)node, typeof(object), out value)) { // The value was pick up, go to next objectContext.Reader.Parser.MoveNext(); @@ -150,7 +150,7 @@ public override object ReadYaml(ref ObjectContext objectContext) // If this is a nullable descriptor, use its underlying type directly if (objectContext.Descriptor is NullableDescriptor) { - objectContext.Descriptor = objectContext.SerializerContext.FindTypeDescriptor(((NullableDescriptor) objectContext.Descriptor).UnderlyingType); + objectContext.Descriptor = objectContext.SerializerContext.FindTypeDescriptor(((NullableDescriptor)objectContext.Descriptor).UnderlyingType); } return base.ReadYaml(ref objectContext); } @@ -162,7 +162,7 @@ public override void WriteYaml(ref ObjectContext objectContext) // If value is null, then just output a plain null scalar if (value == null) { - objectContext.Writer.Emit(new ScalarEventInfo(null, typeof(object)) {RenderedValue = "null", IsPlainImplicit = true, Style = ScalarStyle.Plain}); + objectContext.Writer.Emit(new ScalarEventInfo(null, typeof(object)) { RenderedValue = "null", IsPlainImplicit = true, Style = ScalarStyle.Plain }); return; } @@ -172,7 +172,7 @@ public override void WriteYaml(ref ObjectContext objectContext) // If we have a nullable value, get its type directly and replace the descriptor if (objectContext.Descriptor is NullableDescriptor) { - objectContext.Descriptor = objectContext.SerializerContext.FindTypeDescriptor(((NullableDescriptor) objectContext.Descriptor).UnderlyingType); + objectContext.Descriptor = objectContext.SerializerContext.FindTypeDescriptor(((NullableDescriptor)objectContext.Descriptor).UnderlyingType); } // Expected type @@ -211,4 +211,4 @@ public override void WriteYaml(ref ObjectContext objectContext) base.WriteYaml(ref objectContext); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/WriterEventEmitter.cs b/src/SharpYaml/Serialization/WriterEventEmitter.cs index db8a3388..933425da 100644 --- a/src/SharpYaml/Serialization/WriterEventEmitter.cs +++ b/src/SharpYaml/Serialization/WriterEventEmitter.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -112,4 +112,4 @@ void IEventEmitter.StreamEnd() emitter.Emit(new StreamEnd()); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/YamlAliasNode.cs b/src/SharpYaml/Serialization/YamlAliasNode.cs index e1e9ee14..1f8abf8d 100644 --- a/src/SharpYaml/Serialization/YamlAliasNode.cs +++ b/src/SharpYaml/Serialization/YamlAliasNode.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -127,4 +127,4 @@ public override string ToString() /// public override IEnumerable AllNodes { get { yield return this; } } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/YamlDocument.cs b/src/SharpYaml/Serialization/YamlDocument.cs index c943fd39..ae5266ac 100644 --- a/src/SharpYaml/Serialization/YamlDocument.cs +++ b/src/SharpYaml/Serialization/YamlDocument.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -216,4 +216,4 @@ public void Accept(IYamlVisitor visitor) /// public IEnumerable AllNodes { get { return RootNode.AllNodes; } } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/YamlIgnoreAttribute.cs b/src/SharpYaml/Serialization/YamlIgnoreAttribute.cs index 5ad35008..3b380b15 100644 --- a/src/SharpYaml/Serialization/YamlIgnoreAttribute.cs +++ b/src/SharpYaml/Serialization/YamlIgnoreAttribute.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -54,4 +54,4 @@ namespace SharpYaml.Serialization public sealed class YamlIgnoreAttribute : Attribute { } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/YamlMappingNode.cs b/src/SharpYaml/Serialization/YamlMappingNode.cs index 4a67e43f..9e03fc53 100644 --- a/src/SharpYaml/Serialization/YamlMappingNode.cs +++ b/src/SharpYaml/Serialization/YamlMappingNode.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -134,7 +134,7 @@ public YamlMappingNode() /// Initializes a new instance of the class. /// public YamlMappingNode(params KeyValuePair[] children) - : this((IEnumerable>) children) + : this((IEnumerable>)children) { } @@ -154,7 +154,7 @@ public YamlMappingNode(IEnumerable> children) /// /// A sequence of where even elements are keys and odd elements are values. public YamlMappingNode(params YamlNode[] children) - : this((IEnumerable) children) + : this((IEnumerable)children) { } @@ -394,4 +394,4 @@ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() #endregion } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/YamlMemberAttribute.cs b/src/SharpYaml/Serialization/YamlMemberAttribute.cs index 5f76deca..122025e5 100644 --- a/src/SharpYaml/Serialization/YamlMemberAttribute.cs +++ b/src/SharpYaml/Serialization/YamlMemberAttribute.cs @@ -128,4 +128,4 @@ public YamlMemberAttribute(SerializeMemberMode serializeMethod) /// The mask. public uint Mask { get { return mask; } set { mask = value; } } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/YamlNode.cs b/src/SharpYaml/Serialization/YamlNode.cs index f275082b..2d412caa 100644 --- a/src/SharpYaml/Serialization/YamlNode.cs +++ b/src/SharpYaml/Serialization/YamlNode.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -44,9 +44,9 @@ // SOFTWARE. using System; +using System.Collections.Generic; using SharpYaml; using SharpYaml.Events; -using System.Collections.Generic; namespace SharpYaml.Serialization { @@ -100,7 +100,7 @@ internal void Load(NodeEvent yamlEvent, DocumentLoadingState state) /// The events. /// The state. /// Returns the node that has been parsed. - static internal YamlNode ParseNode(EventReader events, DocumentLoadingState state) + internal static YamlNode ParseNode(EventReader events, DocumentLoadingState state) { if (events.Accept()) { @@ -225,4 +225,4 @@ protected static int CombineHashCodes(int h1, int h2) /// public abstract IEnumerable AllNodes { get; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/YamlNodeIdentityEqualityComparer.cs b/src/SharpYaml/Serialization/YamlNodeIdentityEqualityComparer.cs index 4442ccc2..c5822a75 100644 --- a/src/SharpYaml/Serialization/YamlNodeIdentityEqualityComparer.cs +++ b/src/SharpYaml/Serialization/YamlNodeIdentityEqualityComparer.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -68,4 +68,4 @@ public int GetHashCode(YamlNode obj) #endregion } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/YamlRemapAttribute.cs b/src/SharpYaml/Serialization/YamlRemapAttribute.cs index 7d66d284..becb7049 100644 --- a/src/SharpYaml/Serialization/YamlRemapAttribute.cs +++ b/src/SharpYaml/Serialization/YamlRemapAttribute.cs @@ -45,4 +45,4 @@ public YamlRemapAttribute(string name) /// The previous name. public string Name { get { return name; } } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/YamlScalarNode.cs b/src/SharpYaml/Serialization/YamlScalarNode.cs index 90d3ab43..32891989 100644 --- a/src/SharpYaml/Serialization/YamlScalarNode.cs +++ b/src/SharpYaml/Serialization/YamlScalarNode.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -185,4 +185,4 @@ public override string ToString() /// public override IEnumerable AllNodes { get { yield return this; } } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/YamlSequenceNode.cs b/src/SharpYaml/Serialization/YamlSequenceNode.cs index ec2980aa..ad7c77d9 100644 --- a/src/SharpYaml/Serialization/YamlSequenceNode.cs +++ b/src/SharpYaml/Serialization/YamlSequenceNode.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -46,9 +46,9 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Text; using SharpYaml; using SharpYaml.Events; -using System.Text; namespace SharpYaml.Serialization { @@ -123,7 +123,7 @@ public YamlSequenceNode() /// Initializes a new instance of the class. /// public YamlSequenceNode(params YamlNode[] children) - : this((IEnumerable) children) + : this((IEnumerable)children) { } @@ -295,4 +295,4 @@ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() #endregion } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/YamlSerializableMethod.cs b/src/SharpYaml/Serialization/YamlSerializableMethod.cs index 3e24d483..112e3370 100644 --- a/src/SharpYaml/Serialization/YamlSerializableMethod.cs +++ b/src/SharpYaml/Serialization/YamlSerializableMethod.cs @@ -83,4 +83,4 @@ public enum SerializeMemberMode /// Never, } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/YamlStream.cs b/src/SharpYaml/Serialization/YamlStream.cs index c8573df8..8cd62383 100644 --- a/src/SharpYaml/Serialization/YamlStream.cs +++ b/src/SharpYaml/Serialization/YamlStream.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -74,7 +74,7 @@ public YamlStream() /// Initializes a new instance of the class. /// public YamlStream(params YamlDocument[] documents) - : this((IEnumerable) documents) + : this((IEnumerable)documents) { } @@ -170,4 +170,4 @@ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() #endregion } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/YamlStyleAttribute.cs b/src/SharpYaml/Serialization/YamlStyleAttribute.cs index 6c391030..c63a928e 100644 --- a/src/SharpYaml/Serialization/YamlStyleAttribute.cs +++ b/src/SharpYaml/Serialization/YamlStyleAttribute.cs @@ -71,4 +71,4 @@ public YamlStyleAttribute(YamlStyle style) /// The style. public YamlStyle Style { get { return style; } } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/YamlTagAttribute.cs b/src/SharpYaml/Serialization/YamlTagAttribute.cs index ce7d03b5..4b50a31a 100644 --- a/src/SharpYaml/Serialization/YamlTagAttribute.cs +++ b/src/SharpYaml/Serialization/YamlTagAttribute.cs @@ -70,4 +70,4 @@ public YamlTagAttribute(string tag) /// The tag. public string Tag { get { return tag; } } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Serialization/YamlVisitor.cs b/src/SharpYaml/Serialization/YamlVisitor.cs index 6af0d546..8eaebc68 100644 --- a/src/SharpYaml/Serialization/YamlVisitor.cs +++ b/src/SharpYaml/Serialization/YamlVisitor.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -253,4 +253,4 @@ void IYamlVisitor.Visit(YamlMappingNode mapping) Visited(mapping); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/SimpleKey.cs b/src/SharpYaml/SimpleKey.cs index 33a627e1..9850a4d7 100644 --- a/src/SharpYaml/SimpleKey.cs +++ b/src/SharpYaml/SimpleKey.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -103,4 +103,4 @@ public SimpleKey(bool isPossible, bool isRequired, int tokenNumber, Mark mark) this.mark = mark; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/StringLookAheadBuffer.cs b/src/SharpYaml/StringLookAheadBuffer.cs index 8aa82622..5d350d6c 100644 --- a/src/SharpYaml/StringLookAheadBuffer.cs +++ b/src/SharpYaml/StringLookAheadBuffer.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -85,4 +85,4 @@ public void Skip(int length) public void Cache(int length) { } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/SyntaxErrorException.cs b/src/SharpYaml/SyntaxErrorException.cs index cddf20e6..959e31af 100644 --- a/src/SharpYaml/SyntaxErrorException.cs +++ b/src/SharpYaml/SyntaxErrorException.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -86,4 +86,4 @@ public SyntaxErrorException(string message, Exception inner) { } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/TagDirectiveCollection.cs b/src/SharpYaml/TagDirectiveCollection.cs index 2ec16ec5..646322c1 100644 --- a/src/SharpYaml/TagDirectiveCollection.cs +++ b/src/SharpYaml/TagDirectiveCollection.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -88,4 +88,4 @@ protected override string GetKeyForItem(TagDirective item) return Contains(GetKeyForItem(directive)); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Tokens/Anchor.cs b/src/SharpYaml/Tokens/Anchor.cs index 2d245a24..76efdcae 100644 --- a/src/SharpYaml/Tokens/Anchor.cs +++ b/src/SharpYaml/Tokens/Anchor.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -81,4 +81,4 @@ public Anchor(string value, Mark start, Mark end) this.value = value; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Tokens/AnchorAlias.cs b/src/SharpYaml/Tokens/AnchorAlias.cs index 9f6c6ac2..2e4390ef 100644 --- a/src/SharpYaml/Tokens/AnchorAlias.cs +++ b/src/SharpYaml/Tokens/AnchorAlias.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -80,4 +80,4 @@ public AnchorAlias(string value, Mark start, Mark end) this.value = value; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Tokens/BlockEnd.cs b/src/SharpYaml/Tokens/BlockEnd.cs index 711d70d9..34d7d3f6 100644 --- a/src/SharpYaml/Tokens/BlockEnd.cs +++ b/src/SharpYaml/Tokens/BlockEnd.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -70,4 +70,4 @@ public BlockEnd(Mark start, Mark end) { } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Tokens/BlockEntry.cs b/src/SharpYaml/Tokens/BlockEntry.cs index 156ac193..d19a8a8f 100644 --- a/src/SharpYaml/Tokens/BlockEntry.cs +++ b/src/SharpYaml/Tokens/BlockEntry.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -70,4 +70,4 @@ public BlockEntry(Mark start, Mark end) { } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Tokens/BlockMappingStart.cs b/src/SharpYaml/Tokens/BlockMappingStart.cs index 0b4f41f8..ff2d5d2e 100644 --- a/src/SharpYaml/Tokens/BlockMappingStart.cs +++ b/src/SharpYaml/Tokens/BlockMappingStart.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -70,4 +70,4 @@ public BlockMappingStart(Mark start, Mark end) { } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Tokens/BlockSequenceStart.cs b/src/SharpYaml/Tokens/BlockSequenceStart.cs index 0b93d24d..1baa5f1f 100644 --- a/src/SharpYaml/Tokens/BlockSequenceStart.cs +++ b/src/SharpYaml/Tokens/BlockSequenceStart.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -70,4 +70,4 @@ public BlockSequenceStart(Mark start, Mark end) { } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Tokens/DocumentEnd.cs b/src/SharpYaml/Tokens/DocumentEnd.cs index b21fd713..a7d56f38 100644 --- a/src/SharpYaml/Tokens/DocumentEnd.cs +++ b/src/SharpYaml/Tokens/DocumentEnd.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -70,4 +70,4 @@ public DocumentEnd(Mark start, Mark end) { } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Tokens/DocumentStart.cs b/src/SharpYaml/Tokens/DocumentStart.cs index db4e0684..b376b338 100644 --- a/src/SharpYaml/Tokens/DocumentStart.cs +++ b/src/SharpYaml/Tokens/DocumentStart.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -70,4 +70,4 @@ public DocumentStart(Mark start, Mark end) { } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Tokens/FlowEntry.cs b/src/SharpYaml/Tokens/FlowEntry.cs index ec78ec07..44f50c26 100644 --- a/src/SharpYaml/Tokens/FlowEntry.cs +++ b/src/SharpYaml/Tokens/FlowEntry.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -70,4 +70,4 @@ public FlowEntry(Mark start, Mark end) { } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Tokens/FlowMappingEnd.cs b/src/SharpYaml/Tokens/FlowMappingEnd.cs index 616d7721..63b6ed82 100644 --- a/src/SharpYaml/Tokens/FlowMappingEnd.cs +++ b/src/SharpYaml/Tokens/FlowMappingEnd.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -70,4 +70,4 @@ public FlowMappingEnd(Mark start, Mark end) { } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Tokens/FlowMappingStart.cs b/src/SharpYaml/Tokens/FlowMappingStart.cs index ba05d45e..59a35e0e 100644 --- a/src/SharpYaml/Tokens/FlowMappingStart.cs +++ b/src/SharpYaml/Tokens/FlowMappingStart.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -70,4 +70,4 @@ public FlowMappingStart(Mark start, Mark end) { } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Tokens/FlowSequenceEnd.cs b/src/SharpYaml/Tokens/FlowSequenceEnd.cs index d690de35..f107a2d3 100644 --- a/src/SharpYaml/Tokens/FlowSequenceEnd.cs +++ b/src/SharpYaml/Tokens/FlowSequenceEnd.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -70,4 +70,4 @@ public FlowSequenceEnd(Mark start, Mark end) { } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Tokens/FlowSequenceStart.cs b/src/SharpYaml/Tokens/FlowSequenceStart.cs index 860be1a7..906d2b10 100644 --- a/src/SharpYaml/Tokens/FlowSequenceStart.cs +++ b/src/SharpYaml/Tokens/FlowSequenceStart.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -70,4 +70,4 @@ public FlowSequenceStart(Mark start, Mark end) { } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Tokens/Key.cs b/src/SharpYaml/Tokens/Key.cs index 24a6c485..786ab2b0 100644 --- a/src/SharpYaml/Tokens/Key.cs +++ b/src/SharpYaml/Tokens/Key.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -70,4 +70,4 @@ public Key(Mark start, Mark end) { } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Tokens/Scalar.cs b/src/SharpYaml/Tokens/Scalar.cs index 7382592b..c59ede85 100644 --- a/src/SharpYaml/Tokens/Scalar.cs +++ b/src/SharpYaml/Tokens/Scalar.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -101,4 +101,4 @@ public Scalar(string value, ScalarStyle style, Mark start, Mark end) this.style = style; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Tokens/StreamEnd.cs b/src/SharpYaml/Tokens/StreamEnd.cs index 1c2f4702..c542cf98 100644 --- a/src/SharpYaml/Tokens/StreamEnd.cs +++ b/src/SharpYaml/Tokens/StreamEnd.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -70,4 +70,4 @@ public StreamEnd(Mark start, Mark end) { } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Tokens/StreamStart.cs b/src/SharpYaml/Tokens/StreamStart.cs index bcb99bc8..cd0b218f 100644 --- a/src/SharpYaml/Tokens/StreamStart.cs +++ b/src/SharpYaml/Tokens/StreamStart.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -70,4 +70,4 @@ public StreamStart(Mark start, Mark end) { } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Tokens/Tag.cs b/src/SharpYaml/Tokens/Tag.cs index 79240c35..26f70575 100644 --- a/src/SharpYaml/Tokens/Tag.cs +++ b/src/SharpYaml/Tokens/Tag.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -91,4 +91,4 @@ public Tag(string handle, string suffix, Mark start, Mark end) this.suffix = suffix; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Tokens/TagDirective.cs b/src/SharpYaml/Tokens/TagDirective.cs index 4e3f6e2e..e87fdf42 100644 --- a/src/SharpYaml/Tokens/TagDirective.cs +++ b/src/SharpYaml/Tokens/TagDirective.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -141,4 +141,4 @@ public override string ToString() return FormattableString.Invariant($"{handle} => {prefix}"); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Tokens/Token.cs b/src/SharpYaml/Tokens/Token.cs index f70586dc..d4af0a24 100644 --- a/src/SharpYaml/Tokens/Token.cs +++ b/src/SharpYaml/Tokens/Token.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -77,4 +77,4 @@ protected Token(Mark start, Mark end) this.end = end; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Tokens/Value.cs b/src/SharpYaml/Tokens/Value.cs index be8a8d45..3ebd8979 100644 --- a/src/SharpYaml/Tokens/Value.cs +++ b/src/SharpYaml/Tokens/Value.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -70,4 +70,4 @@ public Value(Mark start, Mark end) { } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Tokens/VersionDirective.cs b/src/SharpYaml/Tokens/VersionDirective.cs index f8e65615..4e25062e 100644 --- a/src/SharpYaml/Tokens/VersionDirective.cs +++ b/src/SharpYaml/Tokens/VersionDirective.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -105,4 +105,4 @@ public override int GetHashCode() return version.GetHashCode(); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/TypeExtensions.cs b/src/SharpYaml/TypeExtensions.cs index 767029df..16fc0001 100644 --- a/src/SharpYaml/TypeExtensions.cs +++ b/src/SharpYaml/TypeExtensions.cs @@ -59,7 +59,7 @@ public static TypeCode GetTypeCode(this Type type) return Type.GetTypeCode(type); } - private static Dictionary anonymousTypes = new Dictionary(); + private static readonly Dictionary anonymousTypes = new Dictionary(); public static bool HasInterface(this Type type, Type lookInterfaceType) { @@ -306,27 +306,27 @@ public static object CastToNumericType(this Type type, object obj) object result = null; if (type == typeof(sbyte)) - result = (sbyte) doubleValue; + result = (sbyte)doubleValue; if (type == typeof(byte)) - result = (byte) doubleValue; + result = (byte)doubleValue; if (type == typeof(short)) - result = (short) doubleValue; + result = (short)doubleValue; if (type == typeof(ushort)) - result = (ushort) doubleValue; + result = (ushort)doubleValue; if (type == typeof(int)) - result = (int) doubleValue; + result = (int)doubleValue; if (type == typeof(uint)) - result = (uint) doubleValue; + result = (uint)doubleValue; if (type == typeof(long)) - result = (long) doubleValue; + result = (long)doubleValue; if (type == typeof(ulong)) - result = (ulong) doubleValue; + result = (ulong)doubleValue; if (type == typeof(float)) - result = (float) doubleValue; + result = (float)doubleValue; if (type == typeof(double)) result = doubleValue; if (type == typeof(decimal)) - result = (decimal) doubleValue; + result = (decimal)doubleValue; return result; } @@ -365,4 +365,4 @@ public static double CastToDouble(object obj) return double.NaN; } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/Version.cs b/src/SharpYaml/Version.cs index ffd62071..5f1f4771 100644 --- a/src/SharpYaml/Version.cs +++ b/src/SharpYaml/Version.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -101,4 +101,4 @@ public override int GetHashCode() return major.GetHashCode() ^ minor.GetHashCode(); } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/YamlException.cs b/src/SharpYaml/YamlException.cs index 0433cad0..72765520 100644 --- a/src/SharpYaml/YamlException.cs +++ b/src/SharpYaml/YamlException.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -106,4 +106,4 @@ public YamlException(string message, Exception inner) { } } -} \ No newline at end of file +} diff --git a/src/SharpYaml/YamlStyle.cs b/src/SharpYaml/YamlStyle.cs index 3a558bdb..3ed40fcf 100644 --- a/src/SharpYaml/YamlStyle.cs +++ b/src/SharpYaml/YamlStyle.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2015 SharpYaml - Alexandre Mutel +// Copyright (c) 2015 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -67,4 +67,4 @@ public enum YamlStyle /// Flow } -} \ No newline at end of file +} From 585579a68a3d15db8cceb89396daa42e5c0a4abb Mon Sep 17 00:00:00 2001 From: udaken <7896698+udaken@users.noreply.github.com> Date: Mon, 20 Jun 2022 10:53:09 +0900 Subject: [PATCH 2/5] Make use pattern matching. --- src/SharpYaml.Tests/ParserTests.cs | 10 ++--- src/SharpYaml.Tests/SchemaTests.cs | 4 +- .../Serialization/SerializationTests2.cs | 6 +-- src/SharpYaml.Tests/YamlNodeTrackerTest.cs | 4 +- src/SharpYaml/Emitter.cs | 2 +- src/SharpYaml/Model/YamlNode.cs | 4 +- src/SharpYaml/Parser.cs | 43 +++++++------------ src/SharpYaml/Schemas/SchemaBase.cs | 9 ++-- .../Descriptors/DefaultKeyComparer.cs | 10 ++--- .../Descriptors/DictionaryDescriptor.cs | 11 ++--- .../Descriptors/ObjectDescriptor.cs | 18 ++++---- .../Descriptors/PrimitiveDescriptor.cs | 3 +- .../Descriptors/TypeDescriptorFactory.cs | 3 +- src/SharpYaml/Serialization/Serializer.cs | 3 +- .../DefaultObjectSerializerBackend.cs | 6 +-- .../Serializers/TagTypeSerializer.cs | 13 +++--- src/SharpYaml/Serialization/YamlAliasNode.cs | 3 +- .../Serialization/YamlMappingNode.cs | 3 +- src/SharpYaml/Serialization/YamlScalarNode.cs | 3 +- .../Serialization/YamlSequenceNode.cs | 3 +- src/SharpYaml/SharpYaml.csproj | 3 +- src/SharpYaml/Tokens/TagDirective.cs | 3 +- src/SharpYaml/Tokens/VersionDirective.cs | 3 +- src/SharpYaml/Version.cs | 3 +- 24 files changed, 69 insertions(+), 104 deletions(-) diff --git a/src/SharpYaml.Tests/ParserTests.cs b/src/SharpYaml.Tests/ParserTests.cs index 79ed31cc..f6e4253e 100644 --- a/src/SharpYaml.Tests/ParserTests.cs +++ b/src/SharpYaml.Tests/ParserTests.cs @@ -361,22 +361,22 @@ private void AssertEvent(ParsingEvent expected, ParsingEvent actual, int eventNu var value = property.GetValue(actual, null); var expectedValue = property.GetValue(expected, null); - if (expectedValue is IEnumerable && !(expectedValue is string)) + if (expectedValue is IEnumerable enumerable && !(expectedValue is string)) { Dump.Write("\t{0} = {{", property.Name); Dump.Write(string.Join(", ", (IEnumerable)value)); Dump.WriteLine("}"); - if (expectedValue is ICollection && value is ICollection) + if (expectedValue is ICollection expectedCollection && value is ICollection collection) { - var expectedCount = ((ICollection)expectedValue).Count; - var valueCount = ((ICollection)value).Count; + var expectedCount = expectedCollection.Count; + var valueCount = collection.Count; Assert.AreEqual(expectedCount, valueCount, "Compared size of collections in property {0} in parse event {1}", property.Name, eventNumber); } var values = ((IEnumerable)value).GetEnumerator(); - var expectedValues = ((IEnumerable)expectedValue).GetEnumerator(); + var expectedValues = enumerable.GetEnumerator(); while (expectedValues.MoveNext()) { Assert.True(values.MoveNext(), "Property {0} in parse event {1} had too few elements", property.Name, eventNumber); diff --git a/src/SharpYaml.Tests/SchemaTests.cs b/src/SharpYaml.Tests/SchemaTests.cs index 9195f05d..9b8aa4a4 100644 --- a/src/SharpYaml.Tests/SchemaTests.cs +++ b/src/SharpYaml.Tests/SchemaTests.cs @@ -150,9 +150,7 @@ public void TestCoreSchemaCommon(IYamlSchema schema) private void TryParse(IYamlSchema schema, string scalar, string expectedShortTag, object expectedValue) { - string tag; - object value; - Assert.True(schema.TryParse(new Scalar(scalar), true, out tag, out value)); + Assert.True(schema.TryParse(new Scalar(scalar), true, out var tag, out var value)); Assert.AreEqual(expectedShortTag, tag); Assert.AreEqual(expectedValue, value); } diff --git a/src/SharpYaml.Tests/Serialization/SerializationTests2.cs b/src/SharpYaml.Tests/Serialization/SerializationTests2.cs index f91e723a..08d42169 100644 --- a/src/SharpYaml.Tests/Serialization/SerializationTests2.cs +++ b/src/SharpYaml.Tests/Serialization/SerializationTests2.cs @@ -1111,8 +1111,7 @@ public override KeyValuePair ReadDictionaryItem(ref ObjectContex public override void WriteDictionaryItem(ref ObjectContext objectContext, KeyValuePair keyValue, KeyValuePair types) { - var itemKey = keyValue.Key as string; - if (itemKey != null && (itemKey.Contains("Name") || itemKey.Contains("Test"))) + if (keyValue.Key is string itemKey && (itemKey.Contains("Name") || itemKey.Contains("Test"))) { keyValue = new KeyValuePair(itemKey + "!", keyValue.Value); } @@ -1221,13 +1220,12 @@ public void TestRemap() settings.RegisterAssembly(typeof(TestRemapObject).Assembly); var serializer = new Serializer(settings); - SerializerContext context; // Test no-remap var myCustomObjectText = serializer.Deserialize(@"!TestRemapObject Name: Test1 Enum: Value2 -", out context); +", out var context); Assert.AreEqual("Test1", myCustomObjectText.Name); Assert.AreEqual(MyRemapEnum.Value2, myCustomObjectText.Enum); Assert.IsFalse(context.HasRemapOccurred); diff --git a/src/SharpYaml.Tests/YamlNodeTrackerTest.cs b/src/SharpYaml.Tests/YamlNodeTrackerTest.cs index 7619f4bd..0c1e37cb 100644 --- a/src/SharpYaml.Tests/YamlNodeTrackerTest.cs +++ b/src/SharpYaml.Tests/YamlNodeTrackerTest.cs @@ -60,8 +60,8 @@ public void ValueSetTest() ScalarValueChanged valueChanged = null; tracker.TrackerEvent += (sender, args) => { - if (args is ScalarValueChanged) - valueChanged = (ScalarValueChanged)args; + if (args is ScalarValueChanged changed) + valueChanged = changed; }; ((YamlValue)stream[0].Contents).Value = "a silly scalar"; diff --git a/src/SharpYaml/Emitter.cs b/src/SharpYaml/Emitter.cs index 8606462e..29a11b64 100644 --- a/src/SharpYaml/Emitter.cs +++ b/src/SharpYaml/Emitter.cs @@ -679,7 +679,7 @@ private void StateMachine(ParsingEvent evt) /// private void EmitStreamStart(ParsingEvent evt) { - if (!(evt is StreamStart)) + if (evt is not StreamStart) { throw new ArgumentException("Expected STREAM-START.", "evt"); } diff --git a/src/SharpYaml/Model/YamlNode.cs b/src/SharpYaml/Model/YamlNode.cs index 026b4386..7e67e6a0 100644 --- a/src/SharpYaml/Model/YamlNode.cs +++ b/src/SharpYaml/Model/YamlNode.cs @@ -65,10 +65,10 @@ public void WriteTo(IEmitter emitter, bool suppressDocumentTags = false) // Emitter will throw an exception if we attempt to use it without // starting StremStart and DocumentStart events. - if (!(events[0] is StreamStart)) + if (events[0] is not StreamStart) events.Insert(0, new StreamStart()); - if (!(events[1] is DocumentStart)) + if (events[1] is not DocumentStart) events.Insert(1, new DocumentStart()); foreach (var evnt in events) diff --git a/src/SharpYaml/Parser.cs b/src/SharpYaml/Parser.cs index 67e04b1c..ee3f5974 100644 --- a/src/SharpYaml/Parser.cs +++ b/src/SharpYaml/Parser.cs @@ -64,8 +64,7 @@ public static class Parser { public static IParser CreateParser(TextReader reader) { - var stringReader = reader as StringReader; - if (stringReader != null) + if (reader is StringReader stringReader) return new Parser(new StringLookAheadBuffer(stringReader.ReadToEnd())); else return new Parser(new LookAheadBuffer(reader, Scanner.MaxBufferLength)); @@ -227,8 +226,7 @@ private void Skip() /// private Event ParseStreamStart() { - StreamStart streamStart = GetCurrentToken() as StreamStart; - if (streamStart == null) + if (GetCurrentToken() is not StreamStart streamStart) { var current = GetCurrentToken(); throw new SemanticErrorException(current.Start, current.End, "Did not find expected ."); @@ -274,14 +272,14 @@ private Event ParseDocumentStart(bool isImplicit) // Parse an explicit document. - else if (!(GetCurrentToken() is StreamEnd)) + else if (GetCurrentToken() is not StreamEnd) { Mark start = GetCurrentToken().Start; TagDirectiveCollection directives = new TagDirectiveCollection(); VersionDirective versionDirective = ProcessDirectives(directives); var current = GetCurrentToken(); - if (!(current is DocumentStart)) + if (current is not DocumentStart) { throw new SemanticErrorException(current.Start, current.End, "Did not find expected ."); } @@ -320,10 +318,7 @@ private VersionDirective ProcessDirectives(TagDirectiveCollection tags) while (true) { - VersionDirective currentVersion; - TagDirective tag; - - if ((currentVersion = GetCurrentToken() as VersionDirective) != null) + if (GetCurrentToken() is VersionDirective currentVersion) { if (version != null) { @@ -337,7 +332,7 @@ private VersionDirective ProcessDirectives(TagDirectiveCollection tags) version = currentVersion; } - else if ((tag = GetCurrentToken() as TagDirective) != null) + else if (GetCurrentToken() is TagDirective tag) { if (tagDirectives.Contains(tag.Handle)) { @@ -439,8 +434,7 @@ private static Event ProcessEmptyScalar(Mark position) /// private Event ParseNode(bool isBlock, bool isIndentlessSequence) { - AnchorAlias alias = GetCurrentToken() as AnchorAlias; - if (alias != null) + if (GetCurrentToken() is AnchorAlias alias) { state = states.Pop(); Event evt = new Events.AnchorAlias(alias.Value, alias.Start, alias.End); @@ -510,8 +504,7 @@ private Event ParseNode(bool isBlock, bool isIndentlessSequence) } else { - Scalar scalar = GetCurrentToken() as Scalar; - if (scalar != null) + if (GetCurrentToken() is Scalar scalar) { bool isPlainImplicit = false; bool isQuotedImplicit = false; @@ -531,15 +524,13 @@ private Event ParseNode(bool isBlock, bool isIndentlessSequence) return evt; } - FlowSequenceStart flowSequenceStart = GetCurrentToken() as FlowSequenceStart; - if (flowSequenceStart != null) + if (GetCurrentToken() is FlowSequenceStart flowSequenceStart) { state = ParserState.YAML_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE; return new Events.SequenceStart(anchorName, tagName, isImplicit, YamlStyle.Flow, start, flowSequenceStart.End); } - FlowMappingStart flowMappingStart = GetCurrentToken() as FlowMappingStart; - if (flowMappingStart != null) + if (GetCurrentToken() is FlowMappingStart flowMappingStart) { state = ParserState.YAML_PARSE_FLOW_MAPPING_FIRST_KEY_STATE; return new Events.MappingStart(anchorName, tagName, isImplicit, YamlStyle.Flow, start, flowMappingStart.End); @@ -547,15 +538,13 @@ private Event ParseNode(bool isBlock, bool isIndentlessSequence) if (isBlock) { - BlockSequenceStart blockSequenceStart = GetCurrentToken() as BlockSequenceStart; - if (blockSequenceStart != null) + if (GetCurrentToken() is BlockSequenceStart blockSequenceStart) { state = ParserState.YAML_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE; return new Events.SequenceStart(anchorName, tagName, isImplicit, YamlStyle.Block, start, blockSequenceStart.End); } - BlockMappingStart blockMappingStart = GetCurrentToken() as BlockMappingStart; - if (blockMappingStart != null) + if (GetCurrentToken() is BlockMappingStart blockMappingStart) { state = ParserState.YAML_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE; return new Events.MappingStart(anchorName, tagName, isImplicit, YamlStyle.Block, start, GetCurrentToken().End); @@ -783,7 +772,7 @@ private Event ParseFlowSequenceEntry(bool isFirst) } Event evt; - if (!(GetCurrentToken() is FlowSequenceEnd)) + if (GetCurrentToken() is not FlowSequenceEnd) { if (!isFirst) { @@ -805,7 +794,7 @@ private Event ParseFlowSequenceEntry(bool isFirst) Skip(); return evt; } - else if (!(GetCurrentToken() is FlowSequenceEnd)) + else if (GetCurrentToken() is not FlowSequenceEnd) { states.Push(ParserState.YAML_PARSE_FLOW_SEQUENCE_ENTRY_STATE); return ParseNode(false, false); @@ -891,7 +880,7 @@ private Event ParseFlowMappingKey(bool isFirst) Skip(); } - if (!(GetCurrentToken() is FlowMappingEnd)) + if (GetCurrentToken() is not FlowMappingEnd) { if (!isFirst) { @@ -921,7 +910,7 @@ private Event ParseFlowMappingKey(bool isFirst) return ProcessEmptyScalar(GetCurrentToken().Start); } } - else if (!(GetCurrentToken() is FlowMappingEnd)) + else if (GetCurrentToken() is not FlowMappingEnd) { states.Push(ParserState.YAML_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE); return ParseNode(false, false); diff --git a/src/SharpYaml/Schemas/SchemaBase.cs b/src/SharpYaml/Schemas/SchemaBase.cs index 1ff77871..6b25d1c6 100644 --- a/src/SharpYaml/Schemas/SchemaBase.cs +++ b/src/SharpYaml/Schemas/SchemaBase.cs @@ -110,20 +110,17 @@ public string GetDefaultTag(NodeEvent nodeEvent) if (nodeEvent == null) throw new ArgumentNullException("nodeEvent"); - var mapping = nodeEvent as MappingStart; - if (mapping != null) + if (nodeEvent is MappingStart mapping) { return GetDefaultTag(mapping); } - var sequence = nodeEvent as SequenceStart; - if (sequence != null) + if (nodeEvent is SequenceStart sequence) { return GetDefaultTag(sequence); } - var scalar = nodeEvent as Scalar; - if (scalar != null) + if (nodeEvent is Scalar scalar) { TryParse(scalar, false, out string tag, out object value); return tag; diff --git a/src/SharpYaml/Serialization/Descriptors/DefaultKeyComparer.cs b/src/SharpYaml/Serialization/Descriptors/DefaultKeyComparer.cs index 5a4df714..d539b99d 100644 --- a/src/SharpYaml/Serialization/Descriptors/DefaultKeyComparer.cs +++ b/src/SharpYaml/Serialization/Descriptors/DefaultKeyComparer.cs @@ -40,9 +40,7 @@ public class DefaultKeyComparer : IComparer { public virtual int Compare(object x, object y) { - var left = x as IMemberDescriptor; - var right = y as IMemberDescriptor; - if (left != null && right != null) + if (x is IMemberDescriptor left && y is IMemberDescriptor right) { // If order is defined, first order by order if (left.Order.HasValue | right.Order.HasValue) @@ -61,14 +59,12 @@ public virtual int Compare(object x, object y) return string.CompareOrdinal((string)x, (string)y); } - var leftComparable = x as IComparable; - if (leftComparable != null) + if (x is IComparable leftComparable) { return leftComparable.CompareTo(y); } - var rightComparable = y as IComparable; - return rightComparable != null ? rightComparable.CompareTo(y) : 0; + return y is IComparable rightComparable ? rightComparable.CompareTo(y) : 0; } } } diff --git a/src/SharpYaml/Serialization/Descriptors/DictionaryDescriptor.cs b/src/SharpYaml/Serialization/Descriptors/DictionaryDescriptor.cs index d17730a9..e09c71c2 100644 --- a/src/SharpYaml/Serialization/Descriptors/DictionaryDescriptor.cs +++ b/src/SharpYaml/Serialization/Descriptors/DictionaryDescriptor.cs @@ -163,12 +163,14 @@ public IEnumerable> GetEnumerator(object dictionary var simpleDictionary = (IDictionary)dictionary; foreach (var keyValueObject in simpleDictionary) { - if (!(keyValueObject is DictionaryEntry)) + if (keyValueObject is not DictionaryEntry entry) { throw new NotSupportedException($"Key value-pair type [{keyValueObject}] is not supported for IDictionary. Only DictionaryEntry"); } - var entry = (DictionaryEntry)keyValueObject; - yield return new KeyValuePair(entry.Key, entry.Value); + else + { + yield return new KeyValuePair(entry.Key, entry.Value); + } } } } @@ -184,8 +186,7 @@ public void AddToDictionary(object dictionary, object key, object value) { if (dictionary == null) throw new ArgumentNullException("dictionary"); - var simpleDictionary = dictionary as IDictionary; - if (simpleDictionary != null) + if (dictionary is IDictionary simpleDictionary) { simpleDictionary.Add(key, value); } diff --git a/src/SharpYaml/Serialization/Descriptors/ObjectDescriptor.cs b/src/SharpYaml/Serialization/Descriptors/ObjectDescriptor.cs index e6244031..a03bc167 100644 --- a/src/SharpYaml/Serialization/Descriptors/ObjectDescriptor.cs +++ b/src/SharpYaml/Serialization/Descriptors/ObjectDescriptor.cs @@ -104,8 +104,7 @@ public ObjectDescriptor(IAttributeRegistry attributeRegistry, Type type, bool em this.style = YamlStyle.Any; foreach (var attribute in attributes) { - var styleAttribute = attribute as YamlStyleAttribute; - if (styleAttribute != null) + if (attribute is YamlStyleAttribute styleAttribute) { style = styleAttribute.Style; continue; @@ -285,26 +284,25 @@ protected virtual bool PrepareMember(MemberDescriptorBase member) return false; } - if (attribute is YamlMemberAttribute) + if (attribute is YamlMemberAttribute yamlMemberAttribute) { - memberAttribute = (YamlMemberAttribute)attribute; + memberAttribute = yamlMemberAttribute; continue; } - if (attribute is DefaultValueAttribute) + if (attribute is DefaultValueAttribute defaultValueAttribute1) { - defaultValueAttribute = (DefaultValueAttribute)attribute; + defaultValueAttribute = defaultValueAttribute1; continue; } - if (attribute is YamlStyleAttribute) + if (attribute is YamlStyleAttribute yamlStyleAttribute) { - styleAttribute = (YamlStyleAttribute)attribute; + styleAttribute = yamlStyleAttribute; continue; } - var yamlRemap = attribute as YamlRemapAttribute; - if (yamlRemap != null) + if (attribute is YamlRemapAttribute yamlRemap) { if (member.AlternativeNames == null) { diff --git a/src/SharpYaml/Serialization/Descriptors/PrimitiveDescriptor.cs b/src/SharpYaml/Serialization/Descriptors/PrimitiveDescriptor.cs index 21f07727..af8143a5 100644 --- a/src/SharpYaml/Serialization/Descriptors/PrimitiveDescriptor.cs +++ b/src/SharpYaml/Serialization/Descriptors/PrimitiveDescriptor.cs @@ -79,8 +79,7 @@ public PrimitiveDescriptor(IAttributeRegistry attributeRegistry, Type type, IMem var attributes = attributeRegistry.GetAttributes(member); foreach (var attribute in attributes) { - var yamlRemap = attribute as YamlRemapAttribute; - if (yamlRemap != null) + if (attribute is YamlRemapAttribute yamlRemap) { if (enumRemap == null) { diff --git a/src/SharpYaml/Serialization/Descriptors/TypeDescriptorFactory.cs b/src/SharpYaml/Serialization/Descriptors/TypeDescriptorFactory.cs index f8c171a0..7cf3b0a4 100644 --- a/src/SharpYaml/Serialization/Descriptors/TypeDescriptorFactory.cs +++ b/src/SharpYaml/Serialization/Descriptors/TypeDescriptorFactory.cs @@ -94,8 +94,7 @@ public ITypeDescriptor Find(Type type, IComparer memberComparer) descriptor = Create(type); - var objectDescriptor = descriptor as ObjectDescriptor; - if (objectDescriptor != null) + if (descriptor is ObjectDescriptor objectDescriptor) { objectDescriptor.SortMembers(memberComparer); } diff --git a/src/SharpYaml/Serialization/Serializer.cs b/src/SharpYaml/Serialization/Serializer.cs index ba2dcacd..59e5d8dd 100644 --- a/src/SharpYaml/Serialization/Serializer.cs +++ b/src/SharpYaml/Serialization/Serializer.cs @@ -212,8 +212,7 @@ public void Serialize(IEmitter emitter, object graph, Type type, SerializerConte // Configure the emitter // TODO the current emitter is not enough configurable to format its output // This should be improved - var defaultEmitter = emitter as Emitter; - if (defaultEmitter != null) + if (emitter is Emitter defaultEmitter) { defaultEmitter.ForceIndentLess = settings.IndentLess; } diff --git a/src/SharpYaml/Serialization/Serializers/DefaultObjectSerializerBackend.cs b/src/SharpYaml/Serialization/Serializers/DefaultObjectSerializerBackend.cs index aca66cf0..f76ba019 100644 --- a/src/SharpYaml/Serialization/Serializers/DefaultObjectSerializerBackend.cs +++ b/src/SharpYaml/Serialization/Serializers/DefaultObjectSerializerBackend.cs @@ -51,17 +51,15 @@ public virtual YamlStyle GetStyle(ref ObjectContext objectContext) if (style == YamlStyle.Any) { bool isPrimitiveElementType = false; - var collectionDescriptor = objectContext.Descriptor as CollectionDescriptor; int count = 0; - if (collectionDescriptor != null) + if (objectContext.Descriptor is CollectionDescriptor collectionDescriptor) { isPrimitiveElementType = PrimitiveDescriptor.IsPrimitive(collectionDescriptor.ElementType); count = collectionDescriptor.GetCollectionCount(objectContext.Instance); } else { - var arrayDescriptor = objectContext.Descriptor as ArrayDescriptor; - if (arrayDescriptor != null) + if (objectContext.Descriptor is ArrayDescriptor arrayDescriptor) { isPrimitiveElementType = PrimitiveDescriptor.IsPrimitive(arrayDescriptor.ElementType); count = objectContext.Instance != null ? ((Array)objectContext.Instance).Length : -1; diff --git a/src/SharpYaml/Serialization/Serializers/TagTypeSerializer.cs b/src/SharpYaml/Serialization/Serializers/TagTypeSerializer.cs index 3efad569..aa00ce01 100644 --- a/src/SharpYaml/Serialization/Serializers/TagTypeSerializer.cs +++ b/src/SharpYaml/Serialization/Serializers/TagTypeSerializer.cs @@ -66,8 +66,7 @@ public override object ReadYaml(ref ObjectContext objectContext) throw new YamlException("Unable to parse input"); } - var node = parsingEvent as NodeEvent; - if (node == null) + if (parsingEvent is not NodeEvent node) { throw new YamlException(parsingEvent.Start, parsingEvent.End, $"Unexpected parsing event found [{parsingEvent}]. Expecting Scalar, Mapping or Sequence"); } @@ -102,7 +101,7 @@ public override object ReadYaml(ref ObjectContext objectContext) object value = objectContext.Instance; // Handle explicit null scalar - if (node is Scalar && objectContext.SerializerContext.Schema.TryParse((Scalar)node, typeof(object), out value)) + if (node is Scalar scalar && objectContext.SerializerContext.Schema.TryParse(scalar, typeof(object), out value)) { // The value was pick up, go to next objectContext.Reader.Parser.MoveNext(); @@ -148,9 +147,9 @@ public override object ReadYaml(ref ObjectContext objectContext) objectContext.Descriptor = objectContext.SerializerContext.FindTypeDescriptor(type); // If this is a nullable descriptor, use its underlying type directly - if (objectContext.Descriptor is NullableDescriptor) + if (objectContext.Descriptor is NullableDescriptor descriptor) { - objectContext.Descriptor = objectContext.SerializerContext.FindTypeDescriptor(((NullableDescriptor)objectContext.Descriptor).UnderlyingType); + objectContext.Descriptor = objectContext.SerializerContext.FindTypeDescriptor(descriptor.UnderlyingType); } return base.ReadYaml(ref objectContext); } @@ -170,9 +169,9 @@ public override void WriteYaml(ref ObjectContext objectContext) // If we have a nullable value, get its type directly and replace the descriptor - if (objectContext.Descriptor is NullableDescriptor) + if (objectContext.Descriptor is NullableDescriptor descriptor) { - objectContext.Descriptor = objectContext.SerializerContext.FindTypeDescriptor(((NullableDescriptor)objectContext.Descriptor).UnderlyingType); + objectContext.Descriptor = objectContext.SerializerContext.FindTypeDescriptor(descriptor.UnderlyingType); } // Expected type diff --git a/src/SharpYaml/Serialization/YamlAliasNode.cs b/src/SharpYaml/Serialization/YamlAliasNode.cs index 1f8abf8d..962c7642 100644 --- a/src/SharpYaml/Serialization/YamlAliasNode.cs +++ b/src/SharpYaml/Serialization/YamlAliasNode.cs @@ -96,8 +96,7 @@ public override void Accept(IYamlVisitor visitor) /// public override bool Equals(object other) { - var obj = other as YamlAliasNode; - return obj != null && Equals(obj) && SafeEquals(Anchor, obj.Anchor); + return other is YamlAliasNode obj && Equals(obj) && SafeEquals(Anchor, obj.Anchor); } /// diff --git a/src/SharpYaml/Serialization/YamlMappingNode.cs b/src/SharpYaml/Serialization/YamlMappingNode.cs index 9e03fc53..dc884fc0 100644 --- a/src/SharpYaml/Serialization/YamlMappingNode.cs +++ b/src/SharpYaml/Serialization/YamlMappingNode.cs @@ -294,8 +294,7 @@ public override void Accept(IYamlVisitor visitor) /// public override bool Equals(object other) { - var obj = other as YamlMappingNode; - if (obj == null || !Equals(obj) || children.Count != obj.children.Count) + if (other is not YamlMappingNode obj || !Equals(obj) || children.Count != obj.children.Count) { return false; } diff --git a/src/SharpYaml/Serialization/YamlScalarNode.cs b/src/SharpYaml/Serialization/YamlScalarNode.cs index 32891989..ff1ed82c 100644 --- a/src/SharpYaml/Serialization/YamlScalarNode.cs +++ b/src/SharpYaml/Serialization/YamlScalarNode.cs @@ -131,8 +131,7 @@ public override void Accept(IYamlVisitor visitor) /// public override bool Equals(object other) { - var obj = other as YamlScalarNode; - return obj != null && Equals(obj) && SafeEquals(Value, obj.Value); + return other is YamlScalarNode obj && Equals(obj) && SafeEquals(Value, obj.Value); } /// diff --git a/src/SharpYaml/Serialization/YamlSequenceNode.cs b/src/SharpYaml/Serialization/YamlSequenceNode.cs index ad7c77d9..914c2e46 100644 --- a/src/SharpYaml/Serialization/YamlSequenceNode.cs +++ b/src/SharpYaml/Serialization/YamlSequenceNode.cs @@ -200,8 +200,7 @@ public override void Accept(IYamlVisitor visitor) /// public override bool Equals(object other) { - var obj = other as YamlSequenceNode; - if (obj == null || !Equals(obj) || children.Count != obj.children.Count) + if (other is not YamlSequenceNode obj || !Equals(obj) || children.Count != obj.children.Count) { return false; } diff --git a/src/SharpYaml/SharpYaml.csproj b/src/SharpYaml/SharpYaml.csproj index 406ebf93..9ca781b3 100644 --- a/src/SharpYaml/SharpYaml.csproj +++ b/src/SharpYaml/SharpYaml.csproj @@ -16,7 +16,8 @@ true true - snupkg + snupkg + 10 diff --git a/src/SharpYaml/Tokens/TagDirective.cs b/src/SharpYaml/Tokens/TagDirective.cs index e87fdf42..e0977cc8 100644 --- a/src/SharpYaml/Tokens/TagDirective.cs +++ b/src/SharpYaml/Tokens/TagDirective.cs @@ -120,8 +120,7 @@ public TagDirective(string handle, string prefix, Mark start, Mark end) /// public override bool Equals(object obj) { - TagDirective other = obj as TagDirective; - return other != null && handle.Equals(other.handle) && prefix.Equals(other.prefix); + return obj is TagDirective other && handle.Equals(other.handle) && prefix.Equals(other.prefix); } /// diff --git a/src/SharpYaml/Tokens/VersionDirective.cs b/src/SharpYaml/Tokens/VersionDirective.cs index 4e25062e..8dd2eced 100644 --- a/src/SharpYaml/Tokens/VersionDirective.cs +++ b/src/SharpYaml/Tokens/VersionDirective.cs @@ -90,8 +90,7 @@ public VersionDirective(Version version, Mark start, Mark end) /// public override bool Equals(object obj) { - VersionDirective other = obj as VersionDirective; - return other != null && version.Equals(other.version); + return obj is VersionDirective other && version.Equals(other.version); } /// diff --git a/src/SharpYaml/Version.cs b/src/SharpYaml/Version.cs index 5f1f4771..1dfad5e2 100644 --- a/src/SharpYaml/Version.cs +++ b/src/SharpYaml/Version.cs @@ -86,8 +86,7 @@ public Version(int major, int minor) /// public override bool Equals(object obj) { - Version other = obj as Version; - return other != null && major == other.major && minor == other.minor; + return obj is Version other && major == other.major && minor == other.minor; } /// From 5ad112a2d6aca40233f82b9df4362e9ae6174b45 Mon Sep 17 00:00:00 2001 From: udaken <7896698+udaken@users.noreply.github.com> Date: Mon, 20 Jun 2022 11:25:02 +0900 Subject: [PATCH 3/5] Make use auto implemented properties. --- src/SharpYaml/Emitter.cs | 18 ++++---- src/SharpYaml/EventReader.cs | 26 +++++------ src/SharpYaml/Events/AnchorAlias.cs | 8 ++-- src/SharpYaml/Events/DocumentEnd.cs | 8 ++-- src/SharpYaml/Events/DocumentStart.cs | 19 +++----- src/SharpYaml/Events/MappingStart.cs | 16 +++---- src/SharpYaml/Events/NodeEvent.cs | 12 ++--- src/SharpYaml/Events/ParsingEvent.cs | 12 ++--- src/SharpYaml/Events/Scalar.cs | 27 ++++------- src/SharpYaml/Events/SequenceStart.cs | 16 +++---- src/SharpYaml/Mark.cs | 27 +++-------- src/SharpYaml/Model/YamlMapping.cs | 10 ++-- src/SharpYaml/Model/YamlSequence.cs | 10 ++-- src/SharpYaml/Model/YamlStream.cs | 17 +++---- src/SharpYaml/Parser.cs | 8 ++-- src/SharpYaml/Scanner.cs | 12 ++--- .../Serialization/AnchorNotFoundException.cs | 2 +- .../Serialization/AssemblyRegistry.cs | 2 +- .../Descriptors/ArrayDescriptor.cs | 5 +- .../Descriptors/CollectionDescriptor.cs | 2 +- .../Descriptors/DictionaryDescriptor.cs | 23 ++++------ .../Descriptors/FieldDescriptor.cs | 13 +++--- .../Descriptors/MemberDescriptorBase.cs | 8 ++-- .../Descriptors/NullableDescriptor.cs | 2 +- .../Descriptors/ObjectDescriptor.cs | 46 +++++++++---------- .../Descriptors/PropertyDescriptor.cs | 7 ++- .../Descriptors/TypeDescriptorFactory.cs | 17 ++++--- src/SharpYaml/Serialization/EmitterState.cs | 4 +- src/SharpYaml/Serialization/EventInfo.cs | 4 +- src/SharpYaml/Serialization/Serializer.cs | 16 +++---- .../Serialization/SerializerContext.cs | 27 +++++------ .../Serialization/SerializerSettings.cs | 5 +- src/SharpYaml/Serialization/YamlDocument.cs | 2 +- .../Serialization/YamlMappingNode.cs | 44 +++++++++--------- .../Serialization/YamlMemberAttribute.cs | 18 +++----- .../Serialization/YamlRemapAttribute.cs | 5 +- .../Serialization/YamlSequenceNode.cs | 34 +++++++------- src/SharpYaml/Serialization/YamlStream.cs | 18 ++++---- .../Serialization/YamlStyleAttribute.cs | 5 +- .../Serialization/YamlTagAttribute.cs | 5 +- src/SharpYaml/SimpleKey.cs | 20 ++++---- src/SharpYaml/StringLookAheadBuffer.cs | 9 ++-- src/SharpYaml/Tokens/Anchor.cs | 6 +-- src/SharpYaml/Tokens/AnchorAlias.cs | 6 +-- src/SharpYaml/Tokens/Scalar.cs | 12 ++--- src/SharpYaml/Tokens/Tag.cs | 10 ++-- src/SharpYaml/Tokens/TagDirective.cs | 16 +++---- src/SharpYaml/Tokens/Token.cs | 12 ++--- src/SharpYaml/Tokens/VersionDirective.cs | 10 ++-- src/SharpYaml/Version.cs | 16 +++---- src/SharpYaml/YamlException.cs | 4 +- 51 files changed, 281 insertions(+), 400 deletions(-) diff --git a/src/SharpYaml/Emitter.cs b/src/SharpYaml/Emitter.cs index 29a11b64..80457337 100644 --- a/src/SharpYaml/Emitter.cs +++ b/src/SharpYaml/Emitter.cs @@ -81,7 +81,6 @@ public class Emitter : IEmitter private int column; private bool isWhitespace; private bool isIndentation; - private bool forceIndentLess; private readonly bool emitKeyQuoted; private bool isOpenEnded; @@ -92,7 +91,6 @@ public class Emitter : IEmitter private class MutableStringLookAheadBuffer : ILookAheadBuffer { private string value; - private int currentIndex; public string Value { @@ -100,26 +98,26 @@ public string Value set { this.value = value; - currentIndex = 0; + Position = 0; } } public int Length { get { return value?.Length ?? 0; } } - public int Position { get { return currentIndex; } } + public int Position { get; private set; } public bool IsOutside(int index) { return value == null || index >= value.Length; } - public bool EndOfInput { get { return IsOutside(currentIndex); } } + public bool EndOfInput { get { return IsOutside(Position); } } public MutableStringLookAheadBuffer() { } public char Peek(int offset) { - int index = currentIndex + offset; + int index = Position + offset; return value[index]; } @@ -129,7 +127,7 @@ public void Skip(int length) { throw new ArgumentOutOfRangeException("length", "The length must be positive."); } - currentIndex += length; + Position += length; } public void Cache(int length) { } @@ -200,7 +198,7 @@ public Emitter(TextWriter output, int bestIndent = MinBestIndent, int bestWidth this.bestWidth = bestWidth; this.isCanonical = isCanonical; - this.forceIndentLess = forceIndentLess; + this.ForceIndentLess = forceIndentLess; this.emitKeyQuoted = emitKeyQuoted; this.output = output; @@ -211,7 +209,7 @@ public Emitter(TextWriter output, int bestIndent = MinBestIndent, int bestWidth /// Gets or sets a value indicating whether [always indent]. /// /// true if [always indent]; otherwise, false. - public bool ForceIndentLess { get { return forceIndentLess; } set { forceIndentLess = value; } } + public bool ForceIndentLess { get; set; } private void Write(char value) @@ -1460,7 +1458,7 @@ private void IncreaseIndent(bool isFlow, bool isIndentless) { indent = isFlow ? bestIndent : 0; } - else if (!isIndentless || !forceIndentLess) + else if (!isIndentless || !ForceIndentLess) { indent += bestIndent; } diff --git a/src/SharpYaml/EventReader.cs b/src/SharpYaml/EventReader.cs index be2a9407..73846869 100644 --- a/src/SharpYaml/EventReader.cs +++ b/src/SharpYaml/EventReader.cs @@ -57,9 +57,7 @@ namespace SharpYaml /// public class EventReader { - private readonly IParser parser; private bool endOfStream; - private int currentDepth = 0; /// /// Initializes a new instance of the class. @@ -67,7 +65,7 @@ public class EventReader /// The parser that provides the events. public EventReader(IParser parser) { - this.parser = parser; + this.Parser = parser; MoveNext(); } @@ -75,9 +73,9 @@ public EventReader(IParser parser) /// Gets the underlying parser. /// /// The parser. - public IParser Parser { get { return parser; } } + public IParser Parser { get; } - public int CurrentDepth { get { return currentDepth; } } + public int CurrentDepth { get; private set; } = 0; /// /// Ensures that the current event is of the specified type, returns it and moves to the next event. @@ -92,10 +90,10 @@ public T Expect() where T : Event { // TODO: Throw a better exception throw new YamlException( - parser.Current.Start, - parser.Current.End, + Parser.Current.Start, + Parser.Current.End, FormattableString.Invariant( - $"Expected '{typeof(T).Name}', got '{parser.Current.GetType().Name}' (at line {parser.Current.Start.Line}, character {parser.Current.Start.Column}).") + $"Expected '{typeof(T).Name}', got '{Parser.Current.GetType().Name}' (at line {Parser.Current.Start.Line}, character {Parser.Current.Start.Column}).") ); } return yamlEvent; @@ -106,9 +104,9 @@ public T Expect() where T : Event /// private void MoveNext() { - if (parser.Current != null) - currentDepth += parser.Current.NestingIncrease; - endOfStream = !parser.MoveNext(); + if (Parser.Current != null) + CurrentDepth += Parser.Current.NestingIncrease; + endOfStream = !Parser.MoveNext(); } /// @@ -120,7 +118,7 @@ public bool Accept() where T : Event { EnsureNotAtEndOfStream(); - return parser.Current is T; + return Parser.Current is T; } /// @@ -136,7 +134,7 @@ public T Allow() where T : Event { return null; } - T yamlEvent = (T)parser.Current; + T yamlEvent = (T)Parser.Current; MoveNext(); return yamlEvent; } @@ -152,7 +150,7 @@ public T Peek() where T : Event { return null; } - T yamlEvent = (T)parser.Current; + T yamlEvent = (T)Parser.Current; return yamlEvent; } diff --git a/src/SharpYaml/Events/AnchorAlias.cs b/src/SharpYaml/Events/AnchorAlias.cs index b802357f..678a6842 100644 --- a/src/SharpYaml/Events/AnchorAlias.cs +++ b/src/SharpYaml/Events/AnchorAlias.cs @@ -65,12 +65,10 @@ public class AnchorAlias : ParsingEvent /// internal override EventType Type { get { return EventType.YAML_ALIAS_EVENT; } } - private readonly string value; - /// /// Gets the value of the alias. /// - public string Value { get { return value; } } + public string Value { get; } /// /// Initializes a new instance of the class. @@ -91,7 +89,7 @@ public AnchorAlias(string value, Mark start, Mark end) throw new YamlException(start, end, "Anchor value must contain alphanumerical characters only."); } - this.value = value; + this.Value = value; } /// @@ -111,7 +109,7 @@ public AnchorAlias(string value) /// public override string ToString() { - return FormattableString.Invariant($"Alias [value = {value}]"); + return FormattableString.Invariant($"Alias [value = {Value}]"); } } } diff --git a/src/SharpYaml/Events/DocumentEnd.cs b/src/SharpYaml/Events/DocumentEnd.cs index 20438d7c..c491ef4b 100644 --- a/src/SharpYaml/Events/DocumentEnd.cs +++ b/src/SharpYaml/Events/DocumentEnd.cs @@ -65,15 +65,13 @@ public class DocumentEnd : ParsingEvent /// internal override EventType Type { get { return EventType.YAML_DOCUMENT_END_EVENT; } } - 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; } } + public bool IsImplicit { get; } /// /// Initializes a new instance of the class. @@ -84,7 +82,7 @@ public class DocumentEnd : ParsingEvent public DocumentEnd(bool isImplicit, Mark start, Mark end) : base(start, end) { - this.isImplicit = isImplicit; + this.IsImplicit = isImplicit; } /// @@ -104,7 +102,7 @@ public DocumentEnd(bool isImplicit) /// public override string ToString() { - return FormattableString.Invariant($"Document end [isImplicit = {isImplicit}]"); + return FormattableString.Invariant($"Document end [isImplicit = {IsImplicit}]"); } } } diff --git a/src/SharpYaml/Events/DocumentStart.cs b/src/SharpYaml/Events/DocumentStart.cs index 4d8af754..b15e2394 100644 --- a/src/SharpYaml/Events/DocumentStart.cs +++ b/src/SharpYaml/Events/DocumentStart.cs @@ -66,22 +66,17 @@ public sealed class DocumentStart : ParsingEvent /// internal override EventType Type { get { return EventType.YAML_DOCUMENT_START_EVENT; } } - private readonly TagDirectiveCollection tags; - private readonly VersionDirective version; - /// /// Gets the tags. /// /// The tags. - public TagDirectiveCollection Tags { get { return tags; } } + public TagDirectiveCollection Tags { get; } /// /// Gets the version. /// /// The version. - public VersionDirective Version { get { return version; } } - - private readonly bool isImplicit; + public VersionDirective Version { get; } /// /// Gets a value indicating whether this instance is implicit. @@ -89,7 +84,7 @@ public sealed class DocumentStart : ParsingEvent /// /// true if this instance is implicit; otherwise, false. /// - public bool IsImplicit { get { return isImplicit; } } + public bool IsImplicit { get; } /// /// Initializes a new instance of the class. @@ -102,9 +97,9 @@ public sealed class DocumentStart : ParsingEvent public DocumentStart(VersionDirective version, TagDirectiveCollection tags, bool isImplicit, Mark start, Mark end) : base(start, end) { - this.version = version; - this.tags = tags; - this.isImplicit = isImplicit; + this.Version = version; + this.Tags = tags; + this.IsImplicit = isImplicit; } /// @@ -144,7 +139,7 @@ public DocumentStart() /// public override string ToString() { - return FormattableString.Invariant($"Document start [isImplicit = {isImplicit}]"); + return FormattableString.Invariant($"Document start [isImplicit = {IsImplicit}]"); } } } diff --git a/src/SharpYaml/Events/MappingStart.cs b/src/SharpYaml/Events/MappingStart.cs index 62b6e9b6..6caf86ad 100644 --- a/src/SharpYaml/Events/MappingStart.cs +++ b/src/SharpYaml/Events/MappingStart.cs @@ -65,28 +65,24 @@ public sealed class MappingStart : NodeEvent /// internal override EventType Type { get { return EventType.YAML_MAPPING_START_EVENT; } } - 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; } } + public bool IsImplicit { get; } /// /// Gets a value indicating whether this instance is canonical. /// /// - public override bool IsCanonical { get { return !isImplicit; } } - - private readonly YamlStyle style; + public override bool IsCanonical { get { return !IsImplicit; } } /// /// Gets the style of the mapping. /// - public YamlStyle Style { get { return style; } } + public YamlStyle Style { get; } /// /// Initializes a new instance of the class. @@ -100,8 +96,8 @@ public sealed class MappingStart : NodeEvent public MappingStart(string anchor, string tag, bool isImplicit, YamlStyle style, Mark start, Mark end) : base(anchor, tag, start, end) { - this.isImplicit = isImplicit; - this.style = style; + this.IsImplicit = isImplicit; + this.Style = style; } /// @@ -133,7 +129,7 @@ public MappingStart() public override string ToString() { return FormattableString.Invariant( - $"Mapping start [anchor = {Anchor}, tag = {Tag}, isImplicit = {isImplicit}, style = {style}]"); + $"Mapping start [anchor = {Anchor}, tag = {Tag}, isImplicit = {IsImplicit}, style = {Style}]"); } } } diff --git a/src/SharpYaml/Events/NodeEvent.cs b/src/SharpYaml/Events/NodeEvent.cs index 1494153b..539da44e 100644 --- a/src/SharpYaml/Events/NodeEvent.cs +++ b/src/SharpYaml/Events/NodeEvent.cs @@ -55,21 +55,17 @@ public abstract class NodeEvent : ParsingEvent { internal static readonly Regex anchorValidator = new Regex(@"^[0-9a-zA-Z_\-]+$", RegexOptions.Compiled); - private readonly string anchor; - /// /// Gets the anchor. /// /// - public string Anchor { get { return anchor; } } - - private readonly string tag; + public string Anchor { get; } /// /// Gets the tag. /// /// - public string Tag { get { return tag; } } + public string Tag { get; } /// /// Gets a value indicating whether this instance is canonical. @@ -105,8 +101,8 @@ protected NodeEvent(string anchor, string tag, Mark start, Mark end) throw new ArgumentException("Tag value must not be empty.", "tag"); } - this.anchor = anchor; - this.tag = tag; + this.Anchor = anchor; + this.Tag = tag; } /// diff --git a/src/SharpYaml/Events/ParsingEvent.cs b/src/SharpYaml/Events/ParsingEvent.cs index 8b8049cc..3c908bf6 100644 --- a/src/SharpYaml/Events/ParsingEvent.cs +++ b/src/SharpYaml/Events/ParsingEvent.cs @@ -62,19 +62,15 @@ public abstract class ParsingEvent /// 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; + public Mark Start { get; } /// /// Gets the position in the input stream where the event ends. /// - public Mark End { get { return end; } } + public Mark End { get; } /// /// Initializes a new instance of the class. @@ -83,8 +79,8 @@ public abstract class ParsingEvent /// The end position of the event. internal ParsingEvent(Mark start, Mark end) { - this.start = start; - this.end = end; + this.Start = start; + this.End = end; } } } diff --git a/src/SharpYaml/Events/Scalar.cs b/src/SharpYaml/Events/Scalar.cs index 59a54977..b4598799 100644 --- a/src/SharpYaml/Events/Scalar.cs +++ b/src/SharpYaml/Events/Scalar.cs @@ -53,7 +53,6 @@ namespace SharpYaml.Events /// public sealed class Scalar : NodeEvent { - private readonly string value; /// /// Gets a value indicating the variation of depth caused by this event. @@ -71,35 +70,29 @@ public sealed class Scalar : NodeEvent /// Gets the value. /// /// The value. - public string Value { get { return value; } } - - private readonly ScalarStyle style; + public string Value { get; } /// /// Gets the style of the scalar. /// /// The style. - public ScalarStyle Style { get { return style; } } - - private readonly bool isPlainImplicit; + public ScalarStyle Style { get; } /// /// Gets a value indicating whether the tag is optional for the plain style. /// - public bool IsPlainImplicit { get { return isPlainImplicit; } } - - private readonly bool isQuotedImplicit; + public bool IsPlainImplicit { get; } /// /// Gets a value indicating whether the tag is optional for any non-plain style. /// - public bool IsQuotedImplicit { get { return isQuotedImplicit; } } + public bool IsQuotedImplicit { get; } /// /// Gets a value indicating whether this instance is canonical. /// /// - public override bool IsCanonical { get { return !isPlainImplicit && !isQuotedImplicit; } } + public override bool IsCanonical { get { return !IsPlainImplicit && !IsQuotedImplicit; } } /// /// Initializes a new instance of the class. @@ -115,10 +108,10 @@ public sealed class Scalar : NodeEvent 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; + this.Value = value; + this.Style = style; + this.IsPlainImplicit = isPlainImplicit; + this.IsQuotedImplicit = isQuotedImplicit; } /// @@ -181,7 +174,7 @@ public Scalar(string anchor, string tag, string value) public override string ToString() { return FormattableString.Invariant( - $"Scalar [anchor = {Anchor}, tag = {Tag}, value = {value}, style = {style}, isPlainImplicit = {isPlainImplicit}, isQuotedImplicit = {isQuotedImplicit}]"); + $"Scalar [anchor = {Anchor}, tag = {Tag}, value = {Value}, style = {Style}, isPlainImplicit = {IsPlainImplicit}, isQuotedImplicit = {IsQuotedImplicit}]"); } } } diff --git a/src/SharpYaml/Events/SequenceStart.cs b/src/SharpYaml/Events/SequenceStart.cs index ea85a52f..ab3377de 100644 --- a/src/SharpYaml/Events/SequenceStart.cs +++ b/src/SharpYaml/Events/SequenceStart.cs @@ -65,29 +65,25 @@ public sealed class SequenceStart : NodeEvent /// internal override EventType Type { get { return EventType.YAML_SEQUENCE_START_EVENT; } } - 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; } } + public bool IsImplicit { get; } /// /// Gets a value indicating whether this instance is canonical. /// /// - public override bool IsCanonical { get { return !isImplicit; } } - - private readonly YamlStyle style; + public override bool IsCanonical { get { return !IsImplicit; } } /// /// Gets the style. /// /// The style. - public YamlStyle Style { get { return style; } } + public YamlStyle Style { get; } /// /// Initializes a new instance of the class. @@ -108,8 +104,8 @@ public SequenceStart() : base(null, null) public SequenceStart(string anchor, string tag, bool isImplicit, YamlStyle style, Mark start, Mark end) : base(anchor, tag, start, end) { - this.isImplicit = isImplicit; - this.style = style; + this.IsImplicit = isImplicit; + this.Style = style; } /// @@ -129,7 +125,7 @@ public SequenceStart(string anchor, string tag, bool isImplicit, YamlStyle style public override string ToString() { return FormattableString.Invariant( - $"Sequence start [anchor = {Anchor}, tag = {Tag}, isImplicit = {isImplicit}, style = {style}]"); + $"Sequence start [anchor = {Anchor}, tag = {Tag}, isImplicit = {IsImplicit}, style = {Style}]"); } } } diff --git a/src/SharpYaml/Mark.cs b/src/SharpYaml/Mark.cs index e176b8d9..5aa77f77 100644 --- a/src/SharpYaml/Mark.cs +++ b/src/SharpYaml/Mark.cs @@ -52,40 +52,27 @@ namespace SharpYaml /// public readonly struct Mark { - private readonly int index; - private readonly int line; - private readonly int column; - public Mark(int index, int line, int column) { - this.index = index; - this.line = line; - this.column = column; + this.Index = index; + this.Line = line; + this.Column = column; } /// /// Gets / sets the absolute offset in the file /// - public int Index - { - get { return index; } - } + public int Index { get; } /// /// Gets / sets the number of the line /// - public int Line - { - get { return line; } - } + public int Line { get; } /// /// Gets / sets the index of the column /// - public int Column - { - get { return column; } - } + public int Column { get; } /// /// Gets a with empty values. @@ -100,7 +87,7 @@ public int Column /// public override string ToString() { - return $"Lin: {line}, Col: {column}, Chr: {index}"; + return $"Lin: {Line}, Col: {Column}, Chr: {Index}"; } } } diff --git a/src/SharpYaml/Model/YamlMapping.cs b/src/SharpYaml/Model/YamlMapping.cs index 68d5ef1b..2b0af847 100644 --- a/src/SharpYaml/Model/YamlMapping.cs +++ b/src/SharpYaml/Model/YamlMapping.cs @@ -28,8 +28,6 @@ namespace SharpYaml.Model public class YamlMapping : YamlContainer, IDictionary, IList> { private MappingStart _mappingStart; - private readonly MappingEnd _mappingEnd; - private readonly List _keys; private readonly Dictionary _contents; @@ -38,7 +36,7 @@ public class YamlMapping : YamlContainer, IDictionary, public YamlMapping() { _mappingStart = new MappingStart(); - _mappingEnd = new MappingEnd(); + MappingEnd = new MappingEnd(); _keys = new List(); _contents = new Dictionary(); } @@ -62,7 +60,7 @@ public YamlMapping() } MappingStart = mappingStart; - this._mappingEnd = mappingEnd; + this.MappingEnd = mappingEnd; } public MappingStart MappingStart @@ -79,7 +77,7 @@ public MappingStart MappingStart } } - internal MappingEnd MappingEnd { get { return _mappingEnd; } } + internal MappingEnd MappingEnd { get; } public override string Anchor { @@ -503,7 +501,7 @@ public override YamlNode DeepClone(YamlNodeTracker tracker = null) cloneContents[keysClone[i]] = (YamlElement)_contents[_keys[i]].DeepClone(); return new YamlMapping(_mappingStart, - _mappingEnd, + MappingEnd, keysClone, cloneContents, tracker); diff --git a/src/SharpYaml/Model/YamlSequence.cs b/src/SharpYaml/Model/YamlSequence.cs index b4c6106b..c0f291df 100644 --- a/src/SharpYaml/Model/YamlSequence.cs +++ b/src/SharpYaml/Model/YamlSequence.cs @@ -27,14 +27,12 @@ namespace SharpYaml.Model public class YamlSequence : YamlContainer, IList { private SequenceStart _sequenceStart; - private readonly SequenceEnd _sequenceEnd; - private readonly List _contents; public YamlSequence() { _sequenceStart = new SequenceStart(); - _sequenceEnd = new SequenceEnd(); + SequenceEnd = new SequenceEnd(); _contents = new List(); } @@ -54,7 +52,7 @@ public YamlSequence() SequenceStart = sequenceStart; - this._sequenceEnd = sequenceEnd; + this.SequenceEnd = sequenceEnd; } public SequenceStart SequenceStart @@ -69,7 +67,7 @@ public SequenceStart SequenceStart } } - internal SequenceEnd SequenceEnd { get { return _sequenceEnd; } } + internal SequenceEnd SequenceEnd { get; } public override string Anchor { @@ -285,7 +283,7 @@ public override YamlNode DeepClone(YamlNodeTracker tracker = null) for (var i = 0; i < _contents.Count; i++) contentsClone.Add((YamlElement)_contents[i].DeepClone()); - return new YamlSequence(_sequenceStart, _sequenceEnd, contentsClone, tracker); + return new YamlSequence(_sequenceStart, SequenceEnd, contentsClone, tracker); } } } diff --git a/src/SharpYaml/Model/YamlStream.cs b/src/SharpYaml/Model/YamlStream.cs index 9acc22e4..d127c26e 100644 --- a/src/SharpYaml/Model/YamlStream.cs +++ b/src/SharpYaml/Model/YamlStream.cs @@ -27,23 +27,20 @@ namespace SharpYaml.Model { public class YamlStream : YamlNode, IList { - private readonly StreamStart _streamStart; - private readonly StreamEnd _streamEnd; - private readonly List _documents; public YamlStream(YamlNodeTracker tracker = null) { - _streamStart = new StreamStart(); - _streamEnd = new StreamEnd(); + StreamStart = new StreamStart(); + StreamEnd = new StreamEnd(); _documents = new List(); Tracker = tracker; } YamlStream(StreamStart streamStart, StreamEnd streamEnd, List documents, YamlNodeTracker tracker = null) { - this._streamStart = streamStart; - this._streamEnd = streamEnd; + this.StreamStart = streamStart; + this.StreamEnd = streamEnd; if (tracker == null) _documents = documents; @@ -58,8 +55,8 @@ public YamlStream(YamlNodeTracker tracker = null) } } - internal StreamStart StreamStart { get { return _streamStart; } } - internal StreamEnd StreamEnd { get { return _streamEnd; } } + internal StreamStart StreamStart { get; } + internal StreamEnd StreamEnd { get; } public static YamlStream Load(TextReader stream, YamlNodeTracker tracker = null) { @@ -218,7 +215,7 @@ public override YamlNode DeepClone(YamlNodeTracker tracker = null) for (var i = 0; i < _documents.Count; i++) documentsClone.Add((YamlDocument)_documents[i].DeepClone()); - return new YamlStream(_streamStart, _streamEnd, documentsClone, tracker); + return new YamlStream(StreamStart, StreamEnd, documentsClone, tracker); } } } diff --git a/src/SharpYaml/Parser.cs b/src/SharpYaml/Parser.cs index ee3f5974..a74dba4f 100644 --- a/src/SharpYaml/Parser.cs +++ b/src/SharpYaml/Parser.cs @@ -81,8 +81,6 @@ public class Parser : IParser where TBuffer : ILookAheadBuffer private ParserState state; private readonly Scanner scanner; - private Event current; - private Token currentToken; private Token GetCurrentToken() @@ -109,7 +107,7 @@ public Parser(TBuffer buffer) /// /// Gets the current event. /// - public Event Current { get { return current; } } + public Event Current { get; private set; } /// /// Moves to the next event. @@ -120,13 +118,13 @@ public bool MoveNext() // No events after the end of the stream or error. if (state == ParserState.YAML_PARSE_END_STATE) { - current = null; + Current = null; return false; } else { // Generate the next event. - current = StateMachine(); + Current = StateMachine(); return true; } } diff --git a/src/SharpYaml/Scanner.cs b/src/SharpYaml/Scanner.cs index 453f586d..cc7727d3 100644 --- a/src/SharpYaml/Scanner.cs +++ b/src/SharpYaml/Scanner.cs @@ -148,12 +148,10 @@ public Scanner(TBuffer buffer) analyzer = buffer; } - private Token current; - /// /// Gets the current token. /// - public Token Current { get { return current; } } + public Token Current { get; private set; } /// /// Moves to the next token. @@ -161,7 +159,7 @@ public Scanner(TBuffer buffer) /// public bool MoveNext() { - if (current != null) + if (Current != null) { ConsumeCurrent(); } @@ -177,13 +175,13 @@ internal bool InternalMoveNext() } if (tokens.Count > 0) { - current = tokens.Dequeue(); + Current = tokens.Dequeue(); tokenAvailable = false; return true; } else { - current = null; + Current = null; return false; } } @@ -195,7 +193,7 @@ internal void ConsumeCurrent() { ++tokensParsed; tokenAvailable = false; - current = null; + Current = null; } private void FetchMoreTokens() diff --git a/src/SharpYaml/Serialization/AnchorNotFoundException.cs b/src/SharpYaml/Serialization/AnchorNotFoundException.cs index de3a4ac5..1e043bad 100644 --- a/src/SharpYaml/Serialization/AnchorNotFoundException.cs +++ b/src/SharpYaml/Serialization/AnchorNotFoundException.cs @@ -89,6 +89,6 @@ public AnchorNotFoundException(string anchorAlias, Mark start, Mark end, string /// Gets or sets the anchor alias. /// /// The anchor alias. - public string Alias { get; private set; } + public string Alias { get; } } } diff --git a/src/SharpYaml/Serialization/AssemblyRegistry.cs b/src/SharpYaml/Serialization/AssemblyRegistry.cs index 78ce4111..20b003a5 100644 --- a/src/SharpYaml/Serialization/AssemblyRegistry.cs +++ b/src/SharpYaml/Serialization/AssemblyRegistry.cs @@ -84,7 +84,7 @@ public AssemblyRegistry(IYamlSchema schema) /// Gets the serializable factories. /// /// The serializable factories. - public List SerializableFactories { get; private set; } + public List SerializableFactories { get; } /// /// Gets or sets a value indicating whether [use short type name]. diff --git a/src/SharpYaml/Serialization/Descriptors/ArrayDescriptor.cs b/src/SharpYaml/Serialization/Descriptors/ArrayDescriptor.cs index 25f77529..336e20d5 100644 --- a/src/SharpYaml/Serialization/Descriptors/ArrayDescriptor.cs +++ b/src/SharpYaml/Serialization/Descriptors/ArrayDescriptor.cs @@ -55,7 +55,6 @@ namespace SharpYaml.Serialization.Descriptors /// public class ArrayDescriptor : ObjectDescriptor { - private readonly Type elementType; /// /// Initializes a new instance of the class. @@ -75,7 +74,7 @@ public ArrayDescriptor(IAttributeRegistry attributeRegistry, Type type, IMemberN throw new ArgumentException($"Cannot support dimension [{type.GetArrayRank()}] for type [{type.FullName}]. Only supporting dimension of 1"); } - elementType = type.GetElementType(); + ElementType = type.GetElementType(); } public override DescriptorCategory Category { get { return DescriptorCategory.Array; } } @@ -84,7 +83,7 @@ public ArrayDescriptor(IAttributeRegistry attributeRegistry, Type type, IMemberN /// Gets the type of the array element. /// /// The type of the element. - public Type ElementType { get { return elementType; } } + public Type ElementType { get; } /// /// Creates the equivalent of list type for this array. diff --git a/src/SharpYaml/Serialization/Descriptors/CollectionDescriptor.cs b/src/SharpYaml/Serialization/Descriptors/CollectionDescriptor.cs index 870b25e7..83601419 100644 --- a/src/SharpYaml/Serialization/Descriptors/CollectionDescriptor.cs +++ b/src/SharpYaml/Serialization/Descriptors/CollectionDescriptor.cs @@ -116,7 +116,7 @@ public override void Initialize() /// Gets or sets the type of the element. /// /// The type of the element. - public Type ElementType { get; private set; } + public Type ElementType { get; } /// /// Gets a value indicating whether this instance is a pure collection (no public property/field) diff --git a/src/SharpYaml/Serialization/Descriptors/DictionaryDescriptor.cs b/src/SharpYaml/Serialization/Descriptors/DictionaryDescriptor.cs index e09c71c2..6cbf75c8 100644 --- a/src/SharpYaml/Serialization/Descriptors/DictionaryDescriptor.cs +++ b/src/SharpYaml/Serialization/Descriptors/DictionaryDescriptor.cs @@ -57,9 +57,6 @@ namespace SharpYaml.Serialization.Descriptors public class DictionaryDescriptor : ObjectDescriptor { private static readonly List ListOfMembersToRemove = new List { "Comparer", "Keys", "Values", "Capacity" }; - - private readonly Type keyType; - private readonly Type valueType; private readonly MethodInfo getEnumeratorGeneric; private readonly MethodInfo addMethod; @@ -82,17 +79,17 @@ public DictionaryDescriptor(IAttributeRegistry attributeRegistry, Type type, boo var interfaceType = type.GetInterface(typeof(IDictionary<,>)); if (interfaceType != null) { - keyType = interfaceType.GetGenericArguments()[0]; - valueType = interfaceType.GetGenericArguments()[1]; + KeyType = interfaceType.GetGenericArguments()[0]; + ValueType = interfaceType.GetGenericArguments()[1]; IsGenericDictionary = true; - getEnumeratorGeneric = typeof(DictionaryDescriptor).GetMethod("GetGenericEnumerable").MakeGenericMethod(keyType, valueType); - addMethod = interfaceType.GetMethod("Add", new[] { keyType, valueType }); + getEnumeratorGeneric = typeof(DictionaryDescriptor).GetMethod("GetGenericEnumerable").MakeGenericMethod(KeyType, ValueType); + addMethod = interfaceType.GetMethod("Add", new[] { KeyType, ValueType }); } else { - keyType = typeof(object); - valueType = typeof(object); - addMethod = type.GetMethod("Add", new[] { keyType, valueType }); + KeyType = typeof(object); + ValueType = typeof(object); + addMethod = type.GetMethod("Add", new[] { KeyType, ValueType }); } } @@ -110,19 +107,19 @@ public override void Initialize() /// Gets a value indicating whether this instance is generic dictionary. /// /// true if this instance is generic dictionary; otherwise, false. - public bool IsGenericDictionary { get; private set; } + public bool IsGenericDictionary { get; } /// /// Gets the type of the key. /// /// The type of the key. - public Type KeyType { get { return keyType; } } + public Type KeyType { get; } /// /// Gets the type of the value. /// /// The type of the value. - public Type ValueType { get { return valueType; } } + public Type ValueType { get; } /// /// Gets or sets a value indicating whether this instance is pure dictionary. diff --git a/src/SharpYaml/Serialization/Descriptors/FieldDescriptor.cs b/src/SharpYaml/Serialization/Descriptors/FieldDescriptor.cs index 1b5ebb76..a2b2de62 100644 --- a/src/SharpYaml/Serialization/Descriptors/FieldDescriptor.cs +++ b/src/SharpYaml/Serialization/Descriptors/FieldDescriptor.cs @@ -53,7 +53,6 @@ namespace SharpYaml.Serialization.Descriptors /// public class FieldDescriptor : MemberDescriptorBase { - private readonly FieldInfo fieldInfo; /// /// Initializes a new instance of the class. @@ -67,30 +66,30 @@ public FieldDescriptor(FieldInfo fieldInfo, StringComparer defaultNameComparer) if (fieldInfo == null) throw new ArgumentNullException("fieldInfo"); - this.fieldInfo = fieldInfo; + this.FieldInfo = fieldInfo; } /// /// Gets the property information attached to this instance. /// /// The property information. - public FieldInfo FieldInfo { get { return fieldInfo; } } + public FieldInfo FieldInfo { get; } - public override Type Type { get { return fieldInfo.FieldType; } } + public override Type Type { get { return FieldInfo.FieldType; } } public override object Get(object thisObject) { - return fieldInfo.GetValue(thisObject); + return FieldInfo.GetValue(thisObject); } public override void Set(object thisObject, object value) { - fieldInfo.SetValue(thisObject, value); + FieldInfo.SetValue(thisObject, value); } public override bool HasSet { get { return true; } } - public override bool IsPublic { get { return fieldInfo.IsPublic; } } + public override bool IsPublic { get { return FieldInfo.IsPublic; } } /// /// Returns a that represents this instance. diff --git a/src/SharpYaml/Serialization/Descriptors/MemberDescriptorBase.cs b/src/SharpYaml/Serialization/Descriptors/MemberDescriptorBase.cs index c71d8e3f..cc54e8c3 100644 --- a/src/SharpYaml/Serialization/Descriptors/MemberDescriptorBase.cs +++ b/src/SharpYaml/Serialization/Descriptors/MemberDescriptorBase.cs @@ -75,8 +75,8 @@ protected MemberDescriptorBase(MemberInfo memberInfo, StringComparer defaultName } public string Name { get; internal set; } - public string OriginalName { get; private set; } - public StringComparer DefaultNameComparer { get; private set; } + public string OriginalName { get; } + public StringComparer DefaultNameComparer { get; } public abstract Type Type { get; } public int? Order { get; internal set; } @@ -84,7 +84,7 @@ protected MemberDescriptorBase(MemberInfo memberInfo, StringComparer defaultName /// Gets the type of the declaring this member. /// /// The type of the declaring. - public Type DeclaringType { get; private set; } + public Type DeclaringType { get; } public SerializeMemberMode SerializeMemberMode { get; internal set; } public abstract object Get(object thisObject); @@ -103,6 +103,6 @@ protected MemberDescriptorBase(MemberInfo memberInfo, StringComparer defaultName /// Gets the member information. /// /// The member information. - public MemberInfo MemberInfo { get; private set; } + public MemberInfo MemberInfo { get; } } } diff --git a/src/SharpYaml/Serialization/Descriptors/NullableDescriptor.cs b/src/SharpYaml/Serialization/Descriptors/NullableDescriptor.cs index cac9b7b0..a36abe06 100644 --- a/src/SharpYaml/Serialization/Descriptors/NullableDescriptor.cs +++ b/src/SharpYaml/Serialization/Descriptors/NullableDescriptor.cs @@ -77,7 +77,7 @@ public NullableDescriptor(IAttributeRegistry attributeRegistry, Type type, IMemb /// Gets the type underlying type T of the nullable /// /// The type of the element. - public Type UnderlyingType { get; private set; } + public Type UnderlyingType { get; } /// /// Determines whether the specified type is nullable. diff --git a/src/SharpYaml/Serialization/Descriptors/ObjectDescriptor.cs b/src/SharpYaml/Serialization/Descriptors/ObjectDescriptor.cs index a03bc167..e29a308c 100644 --- a/src/SharpYaml/Serialization/Descriptors/ObjectDescriptor.cs +++ b/src/SharpYaml/Serialization/Descriptors/ObjectDescriptor.cs @@ -63,16 +63,12 @@ public class ObjectDescriptor : ITypeDescriptor protected static readonly string SystemCollectionsNamespace = typeof(int).Namespace; private static readonly object[] EmptyObjectArray = Array.Empty(); - private readonly Type type; private List members; private Dictionary mapMembers; private readonly bool emitDefaultValues; private readonly bool respectPrivateSetters; - private readonly YamlStyle style; private bool isSorted; - private readonly IMemberNamingConvention memberNamingConvention; private HashSet remapMembers; - private readonly List attributes; /// /// Initializes a new instance of the class. @@ -93,20 +89,20 @@ public ObjectDescriptor(IAttributeRegistry attributeRegistry, Type type, bool em if (namingConvention == null) throw new ArgumentNullException("namingConvention"); - this.memberNamingConvention = namingConvention; + this.NamingConvention = namingConvention; this.emitDefaultValues = emitDefaultValues; this.respectPrivateSetters = respectPrivateSetters; this.AttributeRegistry = attributeRegistry; - this.type = type; + this.Type = type; - attributes = AttributeRegistry.GetAttributes(type.GetTypeInfo()); + Attributes = AttributeRegistry.GetAttributes(type.GetTypeInfo()); - this.style = YamlStyle.Any; - foreach (var attribute in attributes) + this.Style = YamlStyle.Any; + foreach (var attribute in Attributes) { if (attribute is YamlStyleAttribute styleAttribute) { - style = styleAttribute.Style; + Style = styleAttribute.Style; continue; } if (attribute is CompilerGeneratedAttribute) @@ -119,13 +115,13 @@ public ObjectDescriptor(IAttributeRegistry attributeRegistry, Type type, bool em /// /// Gets attributes attached to this type. /// - public List Attributes { get { return attributes; } } + public List Attributes { get; } /// /// Gets the naming convention. /// /// The naming convention. - public IMemberNamingConvention NamingConvention { get { return memberNamingConvention; } } + public IMemberNamingConvention NamingConvention { get; } /// /// Initializes this instance. @@ -150,7 +146,7 @@ public virtual void Initialize() { if (mapMembers.TryGetValue(member.Name, out IMemberDescriptor existingMember)) { - throw new YamlException($"Failed to get ObjectDescriptor for type [{type.FullName}]. The member [{member}] cannot be registered as a member with the same name is already registered [{existingMember}]"); + throw new YamlException($"Failed to get ObjectDescriptor for type [{Type.FullName}]. The member [{member}] cannot be registered as a member with the same name is already registered [{existingMember}]"); } mapMembers.Add(member.Name, member); @@ -162,7 +158,7 @@ public virtual void Initialize() { if (mapMembers.TryGetValue(alternateName, out existingMember)) { - throw new YamlException($"Failed to get ObjectDescriptor for type [{type.FullName}]. The member [{member}] cannot be registered as a member with the same name [{alternateName}] is already registered [{existingMember}]"); + throw new YamlException($"Failed to get ObjectDescriptor for type [{Type.FullName}]. The member [{member}] cannot be registered as a member with the same name [{alternateName}] is already registered [{existingMember}]"); } else { @@ -179,9 +175,9 @@ public virtual void Initialize() } } - protected IAttributeRegistry AttributeRegistry { get; private set; } + protected IAttributeRegistry AttributeRegistry { get; } - public Type Type { get { return type; } } + public Type Type { get; } public IEnumerable Members { get { return members; } } @@ -191,7 +187,7 @@ public virtual void Initialize() public bool HasMembers { get { return members.Count > 0; } } - public YamlStyle Style { get { return style; } } + public YamlStyle Style { get; } /// /// Sorts the members of this instance with the specified instance. @@ -222,7 +218,7 @@ public bool IsMemberRemapped(string name) return remapMembers != null && remapMembers.Contains(name); } - public bool IsCompilerGenerated { get; private set; } + public bool IsCompilerGenerated { get; } public bool Contains(string memberName) { @@ -236,7 +232,7 @@ protected virtual List PrepareMembers() bindingFlags |= BindingFlags.NonPublic; // Add all public properties with a readable get method - var memberList = (from propertyInfo in type.GetProperties(bindingFlags) + var memberList = (from propertyInfo in Type.GetProperties(bindingFlags) where propertyInfo.CanRead && propertyInfo.GetIndexParameters().Length == 0 select new PropertyDescriptor(propertyInfo, NamingConvention.Comparer, respectPrivateSetters) @@ -245,7 +241,7 @@ where PrepareMember(member) select member).Cast().ToList(); // Add all public fields - foreach (var item in (from fieldInfo in type.GetFields(bindingFlags) + foreach (var item in (from fieldInfo in Type.GetFields(bindingFlags) select new FieldDescriptor(fieldInfo, NamingConvention.Comparer) into member where PrepareMember(member) @@ -323,7 +319,7 @@ protected virtual bool PrepareMember(MemberDescriptorBase member) else { // Else we cannot only assign its content if it is a class - member.SerializeMemberMode = (memberType != typeof(string) && memberType.GetTypeInfo().IsClass) || memberType.GetTypeInfo().IsInterface || type.IsAnonymous() ? SerializeMemberMode.Content : SerializeMemberMode.Never; + member.SerializeMemberMode = (memberType != typeof(string) && memberType.GetTypeInfo().IsClass) || memberType.GetTypeInfo().IsInterface || Type.IsAnonymous() ? SerializeMemberMode.Content : SerializeMemberMode.Never; } // If it's a private member, check it has a YamlMemberAttribute on it @@ -358,9 +354,9 @@ protected virtual bool PrepareMember(MemberDescriptorBase member) if (member.SerializeMemberMode == SerializeMemberMode.Binary) { if (!memberType.IsArray) - throw new InvalidOperationException($"{memberType.FullName} {member.OriginalName} of {type.FullName} is not an array. Can not be serialized as binary."); + throw new InvalidOperationException($"{memberType.FullName} {member.OriginalName} of {Type.FullName} is not an array. Can not be serialized as binary."); if (!memberType.GetElementType().IsPureValueType()) - throw new InvalidOperationException($"{memberType.GetElementType()} is not a pure ValueType. {memberType.FullName} {member.OriginalName} of {type.FullName} can not serialize as binary."); + throw new InvalidOperationException($"{memberType.GetElementType()} is not a pure ValueType. {memberType.FullName} {member.OriginalName} of {Type.FullName} can not serialize as binary."); } // If this member cannot be serialized, remove it from the list @@ -374,7 +370,7 @@ protected virtual bool PrepareMember(MemberDescriptorBase member) // ShouldSerializeSomeProperty => call it // DefaultValueAttribute(default) => compare to it // otherwise => true - var shouldSerialize = type.GetMethod("ShouldSerialize" + member.OriginalName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); + var shouldSerialize = Type.GetMethod("ShouldSerialize" + member.OriginalName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); if (shouldSerialize != null && shouldSerialize.ReturnType == typeof(bool) && member.ShouldSerialize == null) member.ShouldSerialize = obj => (bool)shouldSerialize.Invoke(obj, EmptyObjectArray); @@ -404,7 +400,7 @@ protected virtual bool PrepareMember(MemberDescriptorBase member) public override string ToString() { - return type.ToString(); + return Type.ToString(); } } } diff --git a/src/SharpYaml/Serialization/Descriptors/PropertyDescriptor.cs b/src/SharpYaml/Serialization/Descriptors/PropertyDescriptor.cs index 81aad7ca..468b4583 100644 --- a/src/SharpYaml/Serialization/Descriptors/PropertyDescriptor.cs +++ b/src/SharpYaml/Serialization/Descriptors/PropertyDescriptor.cs @@ -53,7 +53,6 @@ namespace SharpYaml.Serialization.Descriptors /// public class PropertyDescriptor : MemberDescriptorBase { - private readonly PropertyInfo propertyInfo; private readonly MethodInfo getMethod; private readonly MethodInfo setMethod; @@ -70,7 +69,7 @@ public PropertyDescriptor(PropertyInfo propertyInfo, StringComparer defaultNameC if (propertyInfo == null) throw new ArgumentNullException("propertyInfo"); - this.propertyInfo = propertyInfo; + this.PropertyInfo = propertyInfo; getMethod = propertyInfo.GetGetMethod(true); if (propertyInfo.CanWrite && propertyInfo.GetSetMethod(respectPrivateSetters || !IsPublic) != null) @@ -83,9 +82,9 @@ public PropertyDescriptor(PropertyInfo propertyInfo, StringComparer defaultNameC /// Gets the property information attached to this instance. /// /// The property information. - public PropertyInfo PropertyInfo { get { return propertyInfo; } } + public PropertyInfo PropertyInfo { get; } - public override Type Type { get { return propertyInfo.PropertyType; } } + public override Type Type { get { return PropertyInfo.PropertyType; } } public override object Get(object thisObject) { diff --git a/src/SharpYaml/Serialization/Descriptors/TypeDescriptorFactory.cs b/src/SharpYaml/Serialization/Descriptors/TypeDescriptorFactory.cs index 7cf3b0a4..b71d3028 100644 --- a/src/SharpYaml/Serialization/Descriptors/TypeDescriptorFactory.cs +++ b/src/SharpYaml/Serialization/Descriptors/TypeDescriptorFactory.cs @@ -53,7 +53,6 @@ namespace SharpYaml.Serialization.Descriptors /// internal class TypeDescriptorFactory : ITypeDescriptorFactory { - private readonly IAttributeRegistry attributeRegistry; private readonly Dictionary registeredDescriptors = new Dictionary(); private readonly bool emitDefaultValues; private readonly bool respectPrivateSetters; @@ -76,7 +75,7 @@ public TypeDescriptorFactory(IAttributeRegistry attributeRegistry, bool emitDefa this.namingConvention = namingConvention; this.respectPrivateSetters = respectPrivateSetters; this.emitDefaultValues = emitDefaultValues; - this.attributeRegistry = attributeRegistry; + this.AttributeRegistry = attributeRegistry; } public ITypeDescriptor Find(Type type, IComparer memberComparer) @@ -110,7 +109,7 @@ public ITypeDescriptor Find(Type type, IComparer memberComparer) /// Gets the settings. /// /// The settings. - protected IAttributeRegistry AttributeRegistry { get { return attributeRegistry; } } + protected IAttributeRegistry AttributeRegistry { get; } /// /// Creates a type descriptor for the specified type. @@ -124,31 +123,31 @@ protected virtual ITypeDescriptor Create(Type type) if (PrimitiveDescriptor.IsPrimitive(type)) { - descriptor = new PrimitiveDescriptor(attributeRegistry, type, namingConvention); + descriptor = new PrimitiveDescriptor(AttributeRegistry, type, namingConvention); } else if (DictionaryDescriptor.IsDictionary(type)) // resolve dictionary before collections, as they are also collections { // IDictionary - descriptor = new DictionaryDescriptor(attributeRegistry, type, emitDefaultValues, respectPrivateSetters, namingConvention); + descriptor = new DictionaryDescriptor(AttributeRegistry, type, emitDefaultValues, respectPrivateSetters, namingConvention); } else if (CollectionDescriptor.IsCollection(type)) { // ICollection - descriptor = new CollectionDescriptor(attributeRegistry, type, emitDefaultValues, respectPrivateSetters, namingConvention); + descriptor = new CollectionDescriptor(AttributeRegistry, type, emitDefaultValues, respectPrivateSetters, namingConvention); } else if (type.IsArray) { // array[] - descriptor = new ArrayDescriptor(attributeRegistry, type, namingConvention); + descriptor = new ArrayDescriptor(AttributeRegistry, type, namingConvention); } else if (NullableDescriptor.IsNullable(type)) { - descriptor = new NullableDescriptor(attributeRegistry, type, namingConvention); + descriptor = new NullableDescriptor(AttributeRegistry, type, namingConvention); } else { // standard object (class or value type) - descriptor = new ObjectDescriptor(attributeRegistry, type, emitDefaultValues, respectPrivateSetters, namingConvention); + descriptor = new ObjectDescriptor(AttributeRegistry, type, emitDefaultValues, respectPrivateSetters, namingConvention); } // Initialize the descriptor diff --git a/src/SharpYaml/Serialization/EmitterState.cs b/src/SharpYaml/Serialization/EmitterState.cs index 5af22917..c3e9aeaf 100644 --- a/src/SharpYaml/Serialization/EmitterState.cs +++ b/src/SharpYaml/Serialization/EmitterState.cs @@ -52,12 +52,10 @@ namespace SharpYaml.Serialization /// internal class EmitterState { - private readonly HashSet emittedAnchors = new HashSet(); - /// /// Gets the already emitted anchors. /// /// The emitted anchors. - public HashSet EmittedAnchors { get { return emittedAnchors; } } + public HashSet EmittedAnchors { get; } = new HashSet(); } } diff --git a/src/SharpYaml/Serialization/EventInfo.cs b/src/SharpYaml/Serialization/EventInfo.cs index db7c6c6e..bdc06e4f 100644 --- a/src/SharpYaml/Serialization/EventInfo.cs +++ b/src/SharpYaml/Serialization/EventInfo.cs @@ -50,8 +50,8 @@ namespace SharpYaml.Serialization { public abstract class EventInfo { - public object SourceValue { get; private set; } - public Type SourceType { get; private set; } + public object SourceValue { get; } + public Type SourceType { get; } protected EventInfo(object sourceValue, Type sourceType) { diff --git a/src/SharpYaml/Serialization/Serializer.cs b/src/SharpYaml/Serialization/Serializer.cs index 59e5d8dd..e9310c18 100644 --- a/src/SharpYaml/Serialization/Serializer.cs +++ b/src/SharpYaml/Serialization/Serializer.cs @@ -56,8 +56,6 @@ namespace SharpYaml.Serialization /// public sealed class Serializer { - private readonly SerializerSettings settings; - internal readonly IYamlSerializable ObjectSerializer; internal readonly IYamlSerializable RoutingSerializer; internal readonly ITypeDescriptorFactory TypeDescriptorFactory; @@ -84,7 +82,7 @@ public Serializer() : this(null) /// The settings. public Serializer(SerializerSettings settings) { - this.settings = settings ?? new SerializerSettings(); + this.Settings = settings ?? new SerializerSettings(); TypeDescriptorFactory = CreateTypeDescriptorFactory(); ObjectSerializer = CreateProcessor(out RoutingSerializer routingSerializer); RoutingSerializer = routingSerializer; @@ -94,7 +92,7 @@ public Serializer(SerializerSettings settings) /// Gets the settings. /// /// The settings. - public SerializerSettings Settings { get { return settings; } } + public SerializerSettings Settings { get; } /// /// Serializes the specified object to a string. @@ -214,7 +212,7 @@ public void Serialize(IEmitter emitter, object graph, Type type, SerializerConte // This should be improved if (emitter is Emitter defaultEmitter) { - defaultEmitter.ForceIndentLess = settings.IndentLess; + defaultEmitter.ForceIndentLess = Settings.IndentLess; } var context = new SerializerContext(this, contextSettings) { Emitter = emitter, Writer = CreateEmitter(emitter) }; @@ -546,13 +544,13 @@ private IYamlSerializable CreateProcessor(out RoutingSerializer routingSerialize routingSerializer = new RoutingSerializer(); // Add registered serializer - foreach (var typeAndSerializer in settings.serializers) + foreach (var typeAndSerializer in Settings.serializers) { routingSerializer.AddSerializer(typeAndSerializer.Key, typeAndSerializer.Value); } // Add registered factories - foreach (var factory in settings.AssemblyRegistry.SerializableFactories) + foreach (var factory in Settings.AssemblyRegistry.SerializableFactories) { routingSerializer.AddSerializerFactory(factory); } @@ -564,7 +562,7 @@ private IYamlSerializable CreateProcessor(out RoutingSerializer routingSerialize } var typingSerializer = new TagTypeSerializer(routingSerializer); - return settings.EmitAlias ? (IYamlSerializable)new AnchorSerializer(typingSerializer) : typingSerializer; + return Settings.EmitAlias ? (IYamlSerializable)new AnchorSerializer(typingSerializer) : typingSerializer; } private ITypeDescriptorFactory CreateTypeDescriptorFactory() @@ -576,7 +574,7 @@ private IEventEmitter CreateEmitter(IEmitter emitter) { var writer = (IEventEmitter)new WriterEventEmitter(emitter); - if (settings.EmitJsonComptible) + if (Settings.EmitJsonComptible) { writer = new JsonEventEmitter(writer); } diff --git a/src/SharpYaml/Serialization/SerializerContext.cs b/src/SharpYaml/Serialization/SerializerContext.cs index f54cc60d..795bbddc 100644 --- a/src/SharpYaml/Serialization/SerializerContext.cs +++ b/src/SharpYaml/Serialization/SerializerContext.cs @@ -55,11 +55,8 @@ namespace SharpYaml.Serialization /// public class SerializerContext : ITagTypeResolver { - private readonly SerializerSettings settings; private readonly ITagTypeRegistry tagTypeRegistry; private readonly ITypeDescriptorFactory typeDescriptorFactory; - private IEmitter emitter; - private readonly SerializerContextSettings contextSettings; internal int AnchorCount; /// @@ -70,14 +67,14 @@ public class SerializerContext : ITagTypeResolver internal SerializerContext(Serializer serializer, SerializerContextSettings serializerContextSettings) { Serializer = serializer; - settings = serializer.Settings; - tagTypeRegistry = settings.AssemblyRegistry; - ObjectFactory = settings.ObjectFactory; - ObjectSerializerBackend = settings.ObjectSerializerBackend; + Settings = serializer.Settings; + tagTypeRegistry = Settings.AssemblyRegistry; + ObjectFactory = Settings.ObjectFactory; + ObjectSerializerBackend = Settings.ObjectSerializerBackend; Schema = Settings.Schema; ObjectSerializer = serializer.ObjectSerializer; typeDescriptorFactory = serializer.TypeDescriptorFactory; - contextSettings = serializerContextSettings ?? SerializerContextSettings.Default; + ContextSettings = serializerContextSettings ?? SerializerContextSettings.Default; } /// @@ -92,25 +89,25 @@ internal SerializerContext(Serializer serializer, SerializerContextSettings seri /// /// The context settings. /// - public SerializerContextSettings ContextSettings { get { return contextSettings; } } + public SerializerContextSettings ContextSettings { get; } /// /// Gets the settings. /// /// The settings. - public SerializerSettings Settings { get { return settings; } } + public SerializerSettings Settings { get; } /// /// Gets the schema. /// /// The schema. - public IYamlSchema Schema { get; private set; } + public IYamlSchema Schema { get; } /// /// Gets the serializer. /// /// The serializer. - public Serializer Serializer { get; private set; } + public Serializer Serializer { get; } /// /// Gets or sets the reader used while deserializing. @@ -122,7 +119,7 @@ internal SerializerContext(Serializer serializer, SerializerContextSettings seri /// Gets the object serializer backend. /// /// The object serializer backend. - public IObjectSerializerBackend ObjectSerializerBackend { get; private set; } + public IObjectSerializerBackend ObjectSerializerBackend { get; } private IYamlSerializable ObjectSerializer { get; set; } @@ -146,7 +143,7 @@ internal SerializerContext(Serializer serializer, SerializerContextSettings seri /// /// The member mask. /// - public uint MemberMask { get { return contextSettings.MemberMask; } } + public uint MemberMask { get { return ContextSettings.MemberMask; } } /// /// The default function to read an object from the current Yaml stream. @@ -188,7 +185,7 @@ public object ReadYaml(object value, Type expectedType) /// Gets the emitter. /// /// The emitter. - public IEmitter Emitter { get { return emitter; } internal set { emitter = value; } } + public IEmitter Emitter { get; internal set; } /// /// The default function to write an object to Yaml diff --git a/src/SharpYaml/Serialization/SerializerSettings.cs b/src/SharpYaml/Serialization/SerializerSettings.cs index ee36d97f..8adf1d40 100644 --- a/src/SharpYaml/Serialization/SerializerSettings.cs +++ b/src/SharpYaml/Serialization/SerializerSettings.cs @@ -61,7 +61,6 @@ public sealed class SerializerSettings internal readonly Dictionary serializers = new Dictionary(); internal readonly AssemblyRegistry AssemblyRegistry; private IAttributeRegistry attributeRegistry; - private readonly IYamlSchema schema; private IObjectFactory objectFactory; private int preferredIndent; private string specialCollectionMember; @@ -90,7 +89,7 @@ public SerializerSettings(IYamlSchema schema) SpecialCollectionMember = "~Items"; LimitPrimitiveFlowSequence = 0; DefaultStyle = YamlStyle.Block; - this.schema = schema ?? CoreSchema.Instance; + this.Schema = schema ?? CoreSchema.Instance; AssemblyRegistry = new AssemblyRegistry(Schema); attributeRegistry = new AttributeRegistry(); ObjectFactory = new DefaultObjectFactory(); @@ -331,7 +330,7 @@ public IObjectFactory ObjectFactory /// /// The schema. /// value - public IYamlSchema Schema { get { return schema; } } + public IYamlSchema Schema { get; } /// /// Register a mapping between a tag and a type. diff --git a/src/SharpYaml/Serialization/YamlDocument.cs b/src/SharpYaml/Serialization/YamlDocument.cs index ae5266ac..83a0d0a4 100644 --- a/src/SharpYaml/Serialization/YamlDocument.cs +++ b/src/SharpYaml/Serialization/YamlDocument.cs @@ -61,7 +61,7 @@ public class YamlDocument /// Gets or sets the root node. /// /// The root node. - public YamlNode RootNode { get; private set; } + public YamlNode RootNode { get; } /// /// Initializes a new instance of the class. diff --git a/src/SharpYaml/Serialization/YamlMappingNode.cs b/src/SharpYaml/Serialization/YamlMappingNode.cs index dc884fc0..d07853ca 100644 --- a/src/SharpYaml/Serialization/YamlMappingNode.cs +++ b/src/SharpYaml/Serialization/YamlMappingNode.cs @@ -56,13 +56,11 @@ namespace SharpYaml.Serialization /// public class YamlMappingNode : YamlNode, IEnumerable> { - private readonly IOrderedDictionary children = new OrderedDictionary(); - /// /// Gets the children of the current node. /// /// The children. - public IOrderedDictionary Children { get { return children; } } + public IOrderedDictionary Children { get; } = new OrderedDictionary(); /// /// Gets or sets the style of the node. @@ -89,7 +87,7 @@ internal YamlMappingNode(EventReader events, DocumentLoadingState state) try { - children.Add(key, value); + Children.Add(key, value); } catch (ArgumentException err) { @@ -106,7 +104,7 @@ internal YamlMappingNode(EventReader events, DocumentLoadingState state) #if DEBUG else { - foreach (var child in children) + foreach (var child in Children) { if (child.Key is YamlAliasNode) { @@ -145,7 +143,7 @@ public YamlMappingNode(IEnumerable> children) { foreach (var child in children) { - this.children.Add(child); + this.Children.Add(child); } } @@ -186,7 +184,7 @@ public YamlMappingNode(IEnumerable children) /// The value node. public void Add(YamlNode key, YamlNode value) { - children.Add(key, value); + Children.Add(key, value); } /// @@ -196,7 +194,7 @@ public void Add(YamlNode key, YamlNode value) /// The value node. public void Add(string key, YamlNode value) { - children.Add(new YamlScalarNode(key), value); + Children.Add(new YamlScalarNode(key), value); } /// @@ -206,7 +204,7 @@ public void Add(string key, YamlNode value) /// The value node. public void Add(YamlNode key, string value) { - children.Add(key, new YamlScalarNode(value)); + Children.Add(key, new YamlScalarNode(value)); } /// @@ -216,7 +214,7 @@ public void Add(YamlNode key, string value) /// The value node. public void Add(string key, string value) { - children.Add(new YamlScalarNode(key), new YamlScalarNode(value)); + Children.Add(new YamlScalarNode(key), new YamlScalarNode(value)); } /// @@ -227,7 +225,7 @@ internal override void ResolveAliases(DocumentLoadingState state) { Dictionary keysToUpdate = null; Dictionary valuesToUpdate = null; - foreach (var entry in children) + foreach (var entry in Children) { if (entry.Key is YamlAliasNode) { @@ -250,16 +248,16 @@ internal override void ResolveAliases(DocumentLoadingState state) { foreach (var entry in valuesToUpdate) { - children[entry.Key] = entry.Value; + 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); + YamlNode value = Children[entry.Key]; + Children.Remove(entry.Key); + Children.Add(entry.Value, value); } } } @@ -272,7 +270,7 @@ internal override void ResolveAliases(DocumentLoadingState state) internal override void Emit(IEmitter emitter, EmitterState state) { emitter.Emit(new MappingStart(Anchor, Tag, string.IsNullOrEmpty(Tag), Style)); - foreach (var entry in children) + foreach (var entry in Children) { entry.Key.Save(emitter, state); entry.Value.Save(emitter, state); @@ -294,14 +292,14 @@ public override void Accept(IYamlVisitor visitor) /// public override bool Equals(object other) { - if (other is not YamlMappingNode obj || !Equals(obj) || children.Count != obj.children.Count) + if (other is not YamlMappingNode obj || !Equals(obj) || Children.Count != obj.Children.Count) { return false; } - foreach (var entry in children) + foreach (var entry in Children) { - if (!obj.children.TryGetValue(entry.Key, out YamlNode otherNode) || !SafeEquals(entry.Value, otherNode)) + if (!obj.Children.TryGetValue(entry.Key, out YamlNode otherNode) || !SafeEquals(entry.Value, otherNode)) { return false; } @@ -320,7 +318,7 @@ public override int GetHashCode() { var hashCode = base.GetHashCode(); - foreach (var entry in children) + foreach (var entry in Children) { hashCode = CombineHashCodes(hashCode, GetHashCode(entry.Key)); hashCode = CombineHashCodes(hashCode, GetHashCode(entry.Value)); @@ -336,7 +334,7 @@ public override IEnumerable AllNodes get { yield return this; - foreach (var child in children) + foreach (var child in Children) { foreach (var node in child.Key.AllNodes) { @@ -360,7 +358,7 @@ public override string ToString() { var text = new StringBuilder("{ "); - foreach (var child in children) + foreach (var child in Children) { if (text.Length > 2) { @@ -379,7 +377,7 @@ public override string ToString() /// public IEnumerator> GetEnumerator() { - return children.GetEnumerator(); + return Children.GetEnumerator(); } #endregion diff --git a/src/SharpYaml/Serialization/YamlMemberAttribute.cs b/src/SharpYaml/Serialization/YamlMemberAttribute.cs index 122025e5..75d86cae 100644 --- a/src/SharpYaml/Serialization/YamlMemberAttribute.cs +++ b/src/SharpYaml/Serialization/YamlMemberAttribute.cs @@ -55,10 +55,6 @@ public sealed class YamlMemberAttribute : Attribute { public const uint DefaultMask = 1; - private readonly SerializeMemberMode serializeMethod; - private readonly string name; - private uint mask = DefaultMask; - /// /// Initializes a new instance of the class. /// @@ -81,7 +77,7 @@ public YamlMemberAttribute(int order) /// The name. public YamlMemberAttribute(string name) { - this.name = name; + this.Name = name; } /// @@ -91,8 +87,8 @@ public YamlMemberAttribute(string name) /// The serialize method. public YamlMemberAttribute(string name, SerializeMemberMode serializeMethod) { - this.name = name; - this.serializeMethod = serializeMethod; + this.Name = name; + this.SerializeMethod = serializeMethod; } /// @@ -101,20 +97,20 @@ public YamlMemberAttribute(string name, SerializeMemberMode serializeMethod) /// The serialize method. public YamlMemberAttribute(SerializeMemberMode serializeMethod) { - this.serializeMethod = serializeMethod; + this.SerializeMethod = serializeMethod; } /// /// Gets the name. /// /// The name. - public string Name { get { return name; } } + public string Name { get; } /// /// Gets the serialize method1. /// /// The serialize method1. - public SerializeMemberMode SerializeMethod { get { return serializeMethod; } } + public SerializeMemberMode SerializeMethod { get; } /// /// Gets or sets the order. Default is -1 (default to alphabetical) @@ -126,6 +122,6 @@ public YamlMemberAttribute(SerializeMemberMode serializeMethod) /// Gets the mask. /// /// The mask. - public uint Mask { get { return mask; } set { mask = value; } } + public uint Mask { get; set; } = DefaultMask; } } diff --git a/src/SharpYaml/Serialization/YamlRemapAttribute.cs b/src/SharpYaml/Serialization/YamlRemapAttribute.cs index becb7049..c7969da0 100644 --- a/src/SharpYaml/Serialization/YamlRemapAttribute.cs +++ b/src/SharpYaml/Serialization/YamlRemapAttribute.cs @@ -28,7 +28,6 @@ namespace SharpYaml.Serialization [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Enum | AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = true)] public sealed class YamlRemapAttribute : Attribute { - private readonly string name; /// /// Initializes a new instance of the class. @@ -36,13 +35,13 @@ public sealed class YamlRemapAttribute : Attribute /// The previous name. public YamlRemapAttribute(string name) { - this.name = name; + this.Name = name; } /// /// Gets the previous name. /// /// The previous name. - public string Name { get { return name; } } + public string Name { get; } } } diff --git a/src/SharpYaml/Serialization/YamlSequenceNode.cs b/src/SharpYaml/Serialization/YamlSequenceNode.cs index 914c2e46..9cf3447e 100644 --- a/src/SharpYaml/Serialization/YamlSequenceNode.cs +++ b/src/SharpYaml/Serialization/YamlSequenceNode.cs @@ -58,13 +58,11 @@ namespace SharpYaml.Serialization [DebuggerDisplay("Count = {children.Count}")] public class YamlSequenceNode : YamlNode, IEnumerable { - private readonly IList children = new List(); - /// /// Gets the collection of child nodes. /// /// The children. - public IList Children { get { return children; } } + public IList Children { get; } = new List(); /// /// Gets or sets the style of the node. @@ -88,7 +86,7 @@ internal YamlSequenceNode(EventReader events, DocumentLoadingState state) while (!events.Accept()) { YamlNode child = ParseNode(events, state); - children.Add(child); + Children.Add(child); hasUnresolvedAliases |= child is YamlAliasNode; } @@ -99,7 +97,7 @@ internal YamlSequenceNode(EventReader events, DocumentLoadingState state) #if DEBUG else { - foreach (var child in children) + foreach (var child in Children) { if (child is YamlAliasNode) { @@ -134,7 +132,7 @@ public YamlSequenceNode(IEnumerable children) { foreach (var child in children) { - this.children.Add(child); + this.Children.Add(child); } } @@ -144,7 +142,7 @@ public YamlSequenceNode(IEnumerable children) /// The child. public void Add(YamlNode child) { - children.Add(child); + Children.Add(child); } /// @@ -153,7 +151,7 @@ public void Add(YamlNode child) /// The child. public void Add(string child) { - children.Add(new YamlScalarNode(child)); + Children.Add(new YamlScalarNode(child)); } /// @@ -162,11 +160,11 @@ public void Add(string child) /// The state of the document. internal override void ResolveAliases(DocumentLoadingState state) { - for (int i = 0; i < children.Count; ++i) + for (int i = 0; i < Children.Count; ++i) { - if (children[i] is YamlAliasNode) + if (Children[i] is YamlAliasNode) { - children[i] = state.GetNode(children[i].Anchor, true, children[i].Start, children[i].End); + Children[i] = state.GetNode(Children[i].Anchor, true, Children[i].Start, Children[i].End); } } } @@ -179,7 +177,7 @@ internal override void ResolveAliases(DocumentLoadingState state) internal override void Emit(IEmitter emitter, EmitterState state) { emitter.Emit(new SequenceStart(Anchor, Tag, string.IsNullOrEmpty(Tag), Style)); - foreach (var node in children) + foreach (var node in Children) { node.Save(emitter, state); } @@ -200,14 +198,14 @@ public override void Accept(IYamlVisitor visitor) /// public override bool Equals(object other) { - if (other is not YamlSequenceNode obj || !Equals(obj) || children.Count != obj.children.Count) + if (other is not YamlSequenceNode obj || !Equals(obj) || Children.Count != obj.Children.Count) { return false; } - for (int i = 0; i < children.Count; ++i) + for (int i = 0; i < Children.Count; ++i) { - if (!SafeEquals(children[i], obj.children[i])) + if (!SafeEquals(Children[i], obj.Children[i])) { return false; } @@ -226,7 +224,7 @@ public override int GetHashCode() { var hashCode = base.GetHashCode(); - foreach (var item in children) + foreach (var item in Children) { hashCode = CombineHashCodes(hashCode, GetHashCode(item)); } @@ -241,7 +239,7 @@ public override IEnumerable AllNodes get { yield return this; - foreach (var child in children) + foreach (var child in Children) { foreach (var node in child.AllNodes) { @@ -261,7 +259,7 @@ public override string ToString() { var text = new StringBuilder("[ "); - foreach (var child in children) + foreach (var child in Children) { if (text.Length > 2) { diff --git a/src/SharpYaml/Serialization/YamlStream.cs b/src/SharpYaml/Serialization/YamlStream.cs index 8cd62383..33935785 100644 --- a/src/SharpYaml/Serialization/YamlStream.cs +++ b/src/SharpYaml/Serialization/YamlStream.cs @@ -55,13 +55,11 @@ namespace SharpYaml.Serialization /// public class YamlStream : IEnumerable { - private readonly IList documents = new List(); - /// /// Gets the documents inside the stream. /// /// The documents. - public IList Documents { get { return documents; } } + public IList Documents { get; } = new List(); /// /// Initializes a new instance of the class. @@ -85,7 +83,7 @@ public YamlStream(IEnumerable documents) { foreach (var document in documents) { - this.documents.Add(document); + this.Documents.Add(document); } } @@ -95,7 +93,7 @@ public YamlStream(IEnumerable documents) /// The document. public void Add(YamlDocument document) { - documents.Add(document); + Documents.Add(document); } /// @@ -104,7 +102,7 @@ public void Add(YamlDocument document) /// The input. public void Load(TextReader input) { - documents.Clear(); + Documents.Clear(); var parser = Parser.CreateParser(input); @@ -113,7 +111,7 @@ public void Load(TextReader input) while (!events.Accept()) { YamlDocument document = new YamlDocument(events); - documents.Add(document); + Documents.Add(document); } events.Expect(); } @@ -130,8 +128,8 @@ public void Save(TextWriter output, bool isLastDocumentEndImplicit = false, int emitter.Emit(new StreamStart()); - var lastDocument = documents.Count > 0 ? documents[documents.Count - 1] : null; - foreach (var document in documents) + var lastDocument = Documents.Count > 0 ? Documents[Documents.Count - 1] : null; + foreach (var document in Documents) { bool isDocumentEndImplicit = isLastDocumentEndImplicit && document == lastDocument; document.Save(emitter, isDocumentEndImplicit); @@ -156,7 +154,7 @@ public void Accept(IYamlVisitor visitor) /// public IEnumerator GetEnumerator() { - return documents.GetEnumerator(); + return Documents.GetEnumerator(); } #endregion diff --git a/src/SharpYaml/Serialization/YamlStyleAttribute.cs b/src/SharpYaml/Serialization/YamlStyleAttribute.cs index c63a928e..6aec4692 100644 --- a/src/SharpYaml/Serialization/YamlStyleAttribute.cs +++ b/src/SharpYaml/Serialization/YamlStyleAttribute.cs @@ -54,7 +54,6 @@ namespace SharpYaml.Serialization [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field)] public class YamlStyleAttribute : Attribute { - private readonly YamlStyle style; /// /// Initializes a new instance of the class. @@ -62,13 +61,13 @@ public class YamlStyleAttribute : Attribute /// The style. public YamlStyleAttribute(YamlStyle style) { - this.style = style; + this.Style = style; } /// /// Gets the style. /// /// The style. - public YamlStyle Style { get { return style; } } + public YamlStyle Style { get; } } } diff --git a/src/SharpYaml/Serialization/YamlTagAttribute.cs b/src/SharpYaml/Serialization/YamlTagAttribute.cs index 4b50a31a..191a73d1 100644 --- a/src/SharpYaml/Serialization/YamlTagAttribute.cs +++ b/src/SharpYaml/Serialization/YamlTagAttribute.cs @@ -53,7 +53,6 @@ namespace SharpYaml.Serialization [AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Enum)] public class YamlTagAttribute : Attribute { - private readonly string tag; /// /// Initializes a new instance of the class. @@ -61,13 +60,13 @@ public class YamlTagAttribute : Attribute /// The tag. public YamlTagAttribute(string tag) { - this.tag = tag; + this.Tag = tag; } /// /// Gets the tag. /// /// The tag. - public string Tag { get { return tag; } } + public string Tag { get; } } } diff --git a/src/SharpYaml/SimpleKey.cs b/src/SharpYaml/SimpleKey.cs index 9850a4d7..a219022d 100644 --- a/src/SharpYaml/SimpleKey.cs +++ b/src/SharpYaml/SimpleKey.cs @@ -52,10 +52,6 @@ namespace SharpYaml /// internal class SimpleKey { - private bool isPossible; - private readonly bool isRequired; - private readonly int tokenNumber; - private readonly Mark mark; /// /// Gets or sets a value indicating whether this instance is possible. @@ -63,7 +59,7 @@ internal class SimpleKey /// /// true if this instance is possible; otherwise, false. /// - public bool IsPossible { get { return isPossible; } set { isPossible = value; } } + public bool IsPossible { get; set; } /// /// Gets or sets a value indicating whether this instance is required. @@ -71,19 +67,19 @@ internal class SimpleKey /// /// true if this instance is required; otherwise, false. /// - public bool IsRequired { get { return isRequired; } } + public bool IsRequired { get; } /// /// Gets or sets the token number. /// /// The token number. - public int TokenNumber { get { return tokenNumber; } } + public int TokenNumber { get; } /// /// Gets or sets the mark that indicates the location of the simple key. /// /// The mark. - public Mark Mark { get { return mark; } } + public Mark Mark { get; } /// /// Initializes a new instance of the class. @@ -97,10 +93,10 @@ public SimpleKey() /// public SimpleKey(bool isPossible, bool isRequired, int tokenNumber, Mark mark) { - this.isPossible = isPossible; - this.isRequired = isRequired; - this.tokenNumber = tokenNumber; - this.mark = mark; + this.IsPossible = isPossible; + this.IsRequired = isRequired; + this.TokenNumber = tokenNumber; + this.Mark = mark; } } } diff --git a/src/SharpYaml/StringLookAheadBuffer.cs b/src/SharpYaml/StringLookAheadBuffer.cs index 5d350d6c..901eddc6 100644 --- a/src/SharpYaml/StringLookAheadBuffer.cs +++ b/src/SharpYaml/StringLookAheadBuffer.cs @@ -50,18 +50,17 @@ namespace SharpYaml internal class StringLookAheadBuffer : ILookAheadBuffer { private readonly string value; - private int currentIndex; public int Length { get { return value.Length; } } - public int Position { get { return currentIndex; } } + public int Position { get; private set; } private bool IsOutside(int index) { return index >= value.Length; } - public bool EndOfInput { get { return IsOutside(currentIndex); } } + public bool EndOfInput { get { return IsOutside(Position); } } public StringLookAheadBuffer(string value) { @@ -70,7 +69,7 @@ public StringLookAheadBuffer(string value) public char Peek(int offset) { - int index = currentIndex + offset; + int index = Position + offset; return IsOutside(index) ? '\0' : value[index]; } @@ -80,7 +79,7 @@ public void Skip(int length) { throw new ArgumentOutOfRangeException("length", "The length must be positive."); } - currentIndex += length; + Position += length; } public void Cache(int length) { } diff --git a/src/SharpYaml/Tokens/Anchor.cs b/src/SharpYaml/Tokens/Anchor.cs index 76efdcae..038cf900 100644 --- a/src/SharpYaml/Tokens/Anchor.cs +++ b/src/SharpYaml/Tokens/Anchor.cs @@ -52,13 +52,11 @@ namespace SharpYaml.Tokens /// public class Anchor : Token { - private readonly string value; - /// /// Gets the value. /// /// The value. - public string Value { get { return value; } } + public string Value { get; } /// /// Initializes a new instance of the class. @@ -78,7 +76,7 @@ public Anchor(string value) public Anchor(string value, Mark start, Mark end) : base(start, end) { - this.value = value; + this.Value = value; } } } diff --git a/src/SharpYaml/Tokens/AnchorAlias.cs b/src/SharpYaml/Tokens/AnchorAlias.cs index 2e4390ef..b0df238b 100644 --- a/src/SharpYaml/Tokens/AnchorAlias.cs +++ b/src/SharpYaml/Tokens/AnchorAlias.cs @@ -52,12 +52,10 @@ namespace SharpYaml.Tokens /// public class AnchorAlias : Token { - private readonly string value; - /// /// Gets the value of the alias. /// - public string Value { get { return value; } } + public string Value { get; } /// /// Initializes a new instance of the class. @@ -77,7 +75,7 @@ public AnchorAlias(string value) public AnchorAlias(string value, Mark start, Mark end) : base(start, end) { - this.value = value; + this.Value = value; } } } diff --git a/src/SharpYaml/Tokens/Scalar.cs b/src/SharpYaml/Tokens/Scalar.cs index c59ede85..eb2f9251 100644 --- a/src/SharpYaml/Tokens/Scalar.cs +++ b/src/SharpYaml/Tokens/Scalar.cs @@ -52,21 +52,17 @@ namespace SharpYaml.Tokens /// public class Scalar : Token { - private readonly string value; - /// /// Gets the value. /// /// The value. - public string Value { get { return value; } } - - private readonly ScalarStyle style; + public string Value { get; } /// /// Gets the style. /// /// The style. - public ScalarStyle Style { get { return style; } } + public ScalarStyle Style { get; } /// /// Initializes a new instance of the class. @@ -97,8 +93,8 @@ public Scalar(string value, ScalarStyle style) public Scalar(string value, ScalarStyle style, Mark start, Mark end) : base(start, end) { - this.value = value; - this.style = style; + this.Value = value; + this.Style = style; } } } diff --git a/src/SharpYaml/Tokens/Tag.cs b/src/SharpYaml/Tokens/Tag.cs index 26f70575..bfe9dc2d 100644 --- a/src/SharpYaml/Tokens/Tag.cs +++ b/src/SharpYaml/Tokens/Tag.cs @@ -52,20 +52,18 @@ namespace SharpYaml.Tokens /// public class Tag : Token { - private readonly string handle; - private readonly string suffix; /// /// Gets the handle. /// /// The handle. - public string Handle { get { return handle; } } + public string Handle { get; } /// /// Gets the suffix. /// /// The suffix. - public string Suffix { get { return suffix; } } + public string Suffix { get; } /// /// Initializes a new instance of the class. @@ -87,8 +85,8 @@ public Tag(string handle, string suffix) public Tag(string handle, string suffix, Mark start, Mark end) : base(start, end) { - this.handle = handle; - this.suffix = suffix; + this.Handle = handle; + this.Suffix = suffix; } } } diff --git a/src/SharpYaml/Tokens/TagDirective.cs b/src/SharpYaml/Tokens/TagDirective.cs index e0977cc8..26176317 100644 --- a/src/SharpYaml/Tokens/TagDirective.cs +++ b/src/SharpYaml/Tokens/TagDirective.cs @@ -54,20 +54,18 @@ namespace SharpYaml.Tokens /// public class TagDirective : Token { - private readonly string handle; - private readonly string prefix; /// /// Gets the handle. /// /// The handle. - public string Handle { get { return handle; } } + public string Handle { get; } /// /// Gets the prefix. /// /// The prefix. - public string Prefix { get { return prefix; } } + public string Prefix { get; } /// /// Initializes a new instance of the class. @@ -101,14 +99,14 @@ public TagDirective(string handle, string prefix, Mark start, Mark end) throw new ArgumentException("Tag handle must start and end with '!' and contain alphanumerical characters only.", "handle"); } - this.handle = handle; + this.Handle = handle; if (string.IsNullOrEmpty(prefix)) { throw new ArgumentNullException("prefix", "Tag prefix must not be empty."); } - this.prefix = prefix; + this.Prefix = prefix; } /// @@ -120,7 +118,7 @@ public TagDirective(string handle, string prefix, Mark start, Mark end) /// public override bool Equals(object obj) { - return obj is TagDirective other && handle.Equals(other.handle) && prefix.Equals(other.prefix); + return obj is TagDirective other && Handle.Equals(other.Handle) && Prefix.Equals(other.Prefix); } /// @@ -131,13 +129,13 @@ public override bool Equals(object obj) /// public override int GetHashCode() { - return handle.GetHashCode() ^ prefix.GetHashCode(); + return Handle.GetHashCode() ^ Prefix.GetHashCode(); } /// public override string ToString() { - return FormattableString.Invariant($"{handle} => {prefix}"); + return FormattableString.Invariant($"{Handle} => {Prefix}"); } } } diff --git a/src/SharpYaml/Tokens/Token.cs b/src/SharpYaml/Tokens/Token.cs index d4af0a24..36d505d5 100644 --- a/src/SharpYaml/Tokens/Token.cs +++ b/src/SharpYaml/Tokens/Token.cs @@ -52,19 +52,15 @@ namespace SharpYaml.Tokens /// 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; + public Mark Start { get; } /// /// Gets the end of the token in the input stream. /// - public Mark End { get { return end; } } + public Mark End { get; } /// /// Initializes a new instance of the class. @@ -73,8 +69,8 @@ public abstract class Token /// The end position of the token. protected Token(Mark start, Mark end) { - this.start = start; - this.end = end; + this.Start = start; + this.End = end; } } } diff --git a/src/SharpYaml/Tokens/VersionDirective.cs b/src/SharpYaml/Tokens/VersionDirective.cs index 8dd2eced..44f91adb 100644 --- a/src/SharpYaml/Tokens/VersionDirective.cs +++ b/src/SharpYaml/Tokens/VersionDirective.cs @@ -52,13 +52,11 @@ namespace SharpYaml.Tokens /// public class VersionDirective : Token { - private readonly Version version; - /// /// Gets the version. /// /// The version. - public Version Version { get { return version; } } + public Version Version { get; } /// /// Initializes a new instance of the class. @@ -78,7 +76,7 @@ public VersionDirective(Version version) public VersionDirective(Version version, Mark start, Mark end) : base(start, end) { - this.version = version; + this.Version = version; } /// @@ -90,7 +88,7 @@ public VersionDirective(Version version, Mark start, Mark end) /// public override bool Equals(object obj) { - return obj is VersionDirective other && version.Equals(other.version); + return obj is VersionDirective other && Version.Equals(other.Version); } /// @@ -101,7 +99,7 @@ public override bool Equals(object obj) /// public override int GetHashCode() { - return version.GetHashCode(); + return Version.GetHashCode(); } } } diff --git a/src/SharpYaml/Version.cs b/src/SharpYaml/Version.cs index 1dfad5e2..13996945 100644 --- a/src/SharpYaml/Version.cs +++ b/src/SharpYaml/Version.cs @@ -52,19 +52,15 @@ namespace SharpYaml /// public class Version { - private readonly int major; - /// /// Gets the major version number. /// - public int Major { get { return major; } } - - private readonly int minor; + public int Major { get; } /// /// Gets the minor version number. /// - public int Minor { get { return minor; } } + public int Minor { get; } /// /// Initializes a new instance of the class. @@ -73,8 +69,8 @@ public class Version /// The the minor version number. public Version(int major, int minor) { - this.major = major; - this.minor = minor; + this.Major = major; + this.Minor = minor; } /// @@ -86,7 +82,7 @@ public Version(int major, int minor) /// public override bool Equals(object obj) { - return obj is Version other && major == other.major && minor == other.minor; + return obj is Version other && Major == other.Major && Minor == other.Minor; } /// @@ -97,7 +93,7 @@ public override bool Equals(object obj) /// public override int GetHashCode() { - return major.GetHashCode() ^ minor.GetHashCode(); + return Major.GetHashCode() ^ Minor.GetHashCode(); } } } diff --git a/src/SharpYaml/YamlException.cs b/src/SharpYaml/YamlException.cs index 72765520..9dc688a1 100644 --- a/src/SharpYaml/YamlException.cs +++ b/src/SharpYaml/YamlException.cs @@ -55,12 +55,12 @@ 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; } + public Mark Start { get; } /// /// Gets the position in the input stream where the event that originated the exception ends. /// - public Mark End { get; private set; } + public Mark End { get; } /// /// Initializes a new instance of the class. From 768de4db56b810203f0fc6a0263f3f1b3e5a9e7d Mon Sep 17 00:00:00 2001 From: udaken <7896698+udaken@users.noreply.github.com> Date: Mon, 20 Jun 2022 14:02:32 +0900 Subject: [PATCH 4/5] Make use 'var' for local variables. --- src/SharpYaml.Tests/EmitterTests.cs | 2 +- .../Serialization/SerializationTests2.cs | 5 +- src/SharpYaml.Tests/YamlNodeTrackerTest.cs | 6 +- src/SharpYaml/Emitter.cs | 14 ++-- src/SharpYaml/EventReader.cs | 4 +- src/SharpYaml/InsertionQueue.cs | 2 +- src/SharpYaml/Model/PathTrie.cs | 14 ++-- src/SharpYaml/Model/YamlMapping.cs | 8 +-- src/SharpYaml/Model/YamlNodeTracker.cs | 10 +-- src/SharpYaml/Parser.cs | 26 ++++---- src/SharpYaml/Scanner.cs | 66 +++++++++---------- src/SharpYaml/Schemas/SchemaBase.cs | 12 ++-- .../Serialization/AssemblyRegistry.cs | 9 +-- .../Serialization/AttributeRegistry.cs | 6 +- .../Descriptors/ObjectDescriptor.cs | 8 +-- .../Descriptors/PrimitiveDescriptor.cs | 2 +- .../Descriptors/TypeDescriptorFactory.cs | 2 +- .../Serialization/DocumentLoadingState.cs | 2 +- src/SharpYaml/Serialization/Serializer.cs | 4 +- .../Serializers/AnchorSerializer.cs | 2 +- .../Serializers/DictionarySerializer.cs | 2 +- .../Serializers/ObjectSerializer.cs | 4 +- .../Serializers/PrimitiveSerializer.cs | 5 +- .../Serializers/RoutingSerializer.cs | 2 +- src/SharpYaml/Serialization/YamlDocument.cs | 6 +- .../Serialization/YamlMappingNode.cs | 10 +-- src/SharpYaml/Serialization/YamlNode.cs | 2 +- src/SharpYaml/Serialization/YamlScalarNode.cs | 2 +- .../Serialization/YamlSequenceNode.cs | 4 +- src/SharpYaml/Serialization/YamlStream.cs | 4 +- src/SharpYaml/TypeExtensions.cs | 2 +- 31 files changed, 121 insertions(+), 126 deletions(-) diff --git a/src/SharpYaml.Tests/EmitterTests.cs b/src/SharpYaml.Tests/EmitterTests.cs index 77e4fbd3..179e615f 100644 --- a/src/SharpYaml.Tests/EmitterTests.cs +++ b/src/SharpYaml.Tests/EmitterTests.cs @@ -187,7 +187,7 @@ private void ParseAndEmit(string name) var testText = YamlFile(name).ReadToEnd(); var output = new StringWriter(); - IParser parser = Parser.CreateParser(new StringReader(testText)); + var parser = Parser.CreateParser(new StringReader(testText)); IEmitter emitter = new Emitter(output, 2, int.MaxValue, false); Dump.WriteLine("= Parse and emit yaml file [" + name + "] ="); while (parser.MoveNext()) diff --git a/src/SharpYaml.Tests/Serialization/SerializationTests2.cs b/src/SharpYaml.Tests/Serialization/SerializationTests2.cs index 08d42169..e6bc1986 100644 --- a/src/SharpYaml.Tests/Serialization/SerializationTests2.cs +++ b/src/SharpYaml.Tests/Serialization/SerializationTests2.cs @@ -276,8 +276,7 @@ public MyDynamicMember() : base("~Id", typeof(int)) public override object Get(object thisObject) { - int id; - DynamicIds.TryGetValue(thisObject, out id); + DynamicIds.TryGetValue(thisObject, out var id); return id; } @@ -1592,7 +1591,7 @@ public void AnchorWithArrays() settings.RegisterAssembly(typeof(OuterClass).Assembly); var serializer = new Serializer(settings); - string serialString = serializer.Serialize(expected); + var serialString = serializer.Serialize(expected); var actual = serializer.Deserialize(serialString) as OuterClass; Assert.NotNull(actual); Assert.True(ReferenceEquals(actual.InnerObjects[0].Array, actual.InnerObjects[1].Array)); diff --git a/src/SharpYaml.Tests/YamlNodeTrackerTest.cs b/src/SharpYaml.Tests/YamlNodeTrackerTest.cs index 0c1e37cb..74d8f6fc 100644 --- a/src/SharpYaml.Tests/YamlNodeTrackerTest.cs +++ b/src/SharpYaml.Tests/YamlNodeTrackerTest.cs @@ -261,7 +261,7 @@ public void UpdateMappingNextChildrenTest() var stream = YamlStream.Load(fileStream, tracker); var seq = (YamlSequence)((YamlMapping)stream[0].Contents)["a sequence"]; - Path modifiedPath = new Path(); + var modifiedPath = new Path(); tracker.TrackerEvent += (sender, args) => modifiedPath = args.ParentPaths[0]; seq[0] = new YamlValue("New item"); @@ -298,7 +298,7 @@ public void UpdateSequenceNextChildrenTest() var stream = YamlStream.Load(fileStream, tracker); var seq = (YamlSequence)((YamlSequence)stream[0].Contents)[2]; - Path modifiedPath = new Path(); + var modifiedPath = new Path(); tracker.TrackerEvent += (sender, args) => modifiedPath = args.ParentPaths[0]; seq[0] = new YamlValue("New item"); @@ -335,7 +335,7 @@ public void UpdateStreamNextChildrenTest() var stream = YamlStream.Load(fileStream, tracker); var val = (YamlValue)stream[2].Contents; - Path modifiedPath = new Path(); + var modifiedPath = new Path(); tracker.TrackerEvent += (sender, args) => { if (args.ParentPaths.Count > 0) diff --git a/src/SharpYaml/Emitter.cs b/src/SharpYaml/Emitter.cs index 80457337..6e66f08b 100644 --- a/src/SharpYaml/Emitter.cs +++ b/src/SharpYaml/Emitter.cs @@ -239,7 +239,7 @@ public void Emit(ParsingEvent @event) while (!NeedMoreEvents()) { - ParsingEvent current = events.Peek(); + var current = events.Peek(); AnalyzeEvent(current); StateMachine(current); @@ -815,7 +815,7 @@ private static string UrlEncode(string text) { return uriReplacer.Replace(text, delegate (Match match) { - StringBuilder buffer = new StringBuilder(); + var buffer = new StringBuilder(); foreach (var toEncode in Encoding.UTF8.GetBytes(match.Value)) { buffer.AppendFormat("%{0:X02}", toEncode); @@ -952,7 +952,7 @@ private void EmitSequenceStart(ParsingEvent evt) ProcessAnchor(); ProcessTag(); - SequenceStart sequenceStart = (SequenceStart)evt; + var sequenceStart = (SequenceStart)evt; if (flowLevel != 0 || isCanonical || sequenceStart.Style == YamlStyle.Flow || CheckEmptySequence()) { @@ -1026,7 +1026,7 @@ private void EmitMappingStart(ParsingEvent evt) ProcessAnchor(); ProcessTag(); - MappingStart mappingStart = (MappingStart)evt; + var mappingStart = (MappingStart)evt; if (flowLevel != 0 || isCanonical || mappingStart.Style == YamlStyle.Flow || CheckEmptyMapping()) { @@ -1469,9 +1469,9 @@ private void IncreaseIndent(bool isFlow, bool isIndentless) /// private void SelectScalarStyle(ParsingEvent evt) { - Scalar scalar = (Scalar)evt; + var scalar = (Scalar)evt; - ScalarStyle style = scalar.Style; + var style = scalar.Style; bool noTag = tagData.handle == null && tagData.suffix == null; if (noTag && !scalar.IsPlainImplicit && !scalar.IsQuotedImplicit) @@ -1845,7 +1845,7 @@ private void WriteBlockScalarHints(string value) if (analyzer.IsSpace() || analyzer.IsBreak()) { - string indent_hint = FormattableString.Invariant($"{bestIndent}"); + var indent_hint = FormattableString.Invariant($"{bestIndent}"); WriteIndicator(indent_hint, false, false, false); } diff --git a/src/SharpYaml/EventReader.cs b/src/SharpYaml/EventReader.cs index 73846869..18309367 100644 --- a/src/SharpYaml/EventReader.cs +++ b/src/SharpYaml/EventReader.cs @@ -134,7 +134,7 @@ public T Allow() where T : Event { return null; } - T yamlEvent = (T)Parser.Current; + var yamlEvent = (T)Parser.Current; MoveNext(); return yamlEvent; } @@ -150,7 +150,7 @@ public T Peek() where T : Event { return null; } - T yamlEvent = (T)Parser.Current; + var yamlEvent = (T)Parser.Current; return yamlEvent; } diff --git a/src/SharpYaml/InsertionQueue.cs b/src/SharpYaml/InsertionQueue.cs index 793e3f23..0303d67a 100644 --- a/src/SharpYaml/InsertionQueue.cs +++ b/src/SharpYaml/InsertionQueue.cs @@ -82,7 +82,7 @@ public T Dequeue() throw new InvalidOperationException("The queue is empty"); } - T item = items[0]; + var item = items[0]; items.RemoveAt(0); return item; } diff --git a/src/SharpYaml/Model/PathTrie.cs b/src/SharpYaml/Model/PathTrie.cs index b43f02e9..e4485071 100644 --- a/src/SharpYaml/Model/PathTrie.cs +++ b/src/SharpYaml/Model/PathTrie.cs @@ -18,7 +18,7 @@ public void Add(IList indices, int start) return; } - if (!subPaths.TryGetValue(indices[start], out PathTrieNode subPath)) + if (!subPaths.TryGetValue(indices[start], out var subPath)) { subPath = new PathTrieNode(); subPaths[indices[start]] = subPath; @@ -41,7 +41,7 @@ public bool Remove(IList indices, int start, bool removeChildren) return result; } - if (!subPaths.TryGetValue(indices[start], out PathTrieNode subPath)) + if (!subPaths.TryGetValue(indices[start], out var subPath)) return false; if (!subPath.Remove(indices, start + 1, removeChildren)) @@ -63,7 +63,7 @@ public PathTrieNode Find(IList indices, int start) if (start == indices.Count) return this; - if (!subPaths.TryGetValue(indices[start], out PathTrieNode subPath)) + if (!subPaths.TryGetValue(indices[start], out var subPath)) return null; return subPath.Find(indices, start + 1); @@ -89,7 +89,7 @@ public IEnumerable> GetReversePaths() public void Add(Path path) { - if (!roots.TryGetValue(path.Root, out PathTrieNode root)) + if (!roots.TryGetValue(path.Root, out var root)) { root = new PathTrieNode(); roots[path.Root] = root; @@ -100,7 +100,7 @@ public void Add(Path path) public bool Remove(Path path, bool removeChildren) { - if (!roots.TryGetValue(path.Root, out PathTrieNode root)) + if (!roots.TryGetValue(path.Root, out var root)) return false; if (!root.Remove(path.Indices, 0, removeChildren)) @@ -114,7 +114,7 @@ public bool Remove(Path path, bool removeChildren) public bool Contains(Path path, bool orChildren) { - if (!roots.TryGetValue(path.Root, out PathTrieNode root)) + if (!roots.TryGetValue(path.Root, out var root)) return false; var node = root.Find(path.Indices, 0); @@ -126,7 +126,7 @@ public bool Contains(Path path, bool orChildren) public IEnumerable GetSubpaths(Path path) { - if (!roots.TryGetValue(path.Root, out PathTrieNode root)) + if (!roots.TryGetValue(path.Root, out var root)) yield break; var node = root.Find(path.Indices, 0); diff --git a/src/SharpYaml/Model/YamlMapping.cs b/src/SharpYaml/Model/YamlMapping.cs index 2b0af847..bb506e92 100644 --- a/src/SharpYaml/Model/YamlMapping.cs +++ b/src/SharpYaml/Model/YamlMapping.cs @@ -141,8 +141,8 @@ public static YamlMapping Load(EventReader eventReader, YamlNodeTracker tracker) { var mappingStart = eventReader.Allow(); - List keys = new List(); - Dictionary contents = new Dictionary(); + var keys = new List(); + var contents = new Dictionary(); while (!eventReader.Accept()) { var key = ReadElement(eventReader, tracker); @@ -281,7 +281,7 @@ public bool Remove(string key) if (stringKeys == null) stringKeys = Keys.OfType().ToDictionary(k => k.Value, k => k); - if (!stringKeys.TryGetValue(key, out YamlValue yaml)) + if (!stringKeys.TryGetValue(key, out var yaml)) return false; if (Remove(yaml)) @@ -303,7 +303,7 @@ public bool TryGetValue(string key, out YamlElement value) if (stringKeys == null) stringKeys = Keys.OfType().ToDictionary(k => k.Value, k => k); - if (!stringKeys.TryGetValue(key, out YamlValue yamlKey)) + if (!stringKeys.TryGetValue(key, out var yamlKey)) { value = null; return false; diff --git a/src/SharpYaml/Model/YamlNodeTracker.cs b/src/SharpYaml/Model/YamlNodeTracker.cs index fd39b7d0..6bffc447 100644 --- a/src/SharpYaml/Model/YamlNodeTracker.cs +++ b/src/SharpYaml/Model/YamlNodeTracker.cs @@ -432,7 +432,7 @@ void AddChild(YamlNode child, YamlNode parent, ChildIndex relationship) { var pi = new ParentAndIndex(parent, relationship); - if (!parents.TryGetValue(child, out ICollection set)) + if (!parents.TryGetValue(child, out var set)) { set = new[] { pi }; parents.Add(child, set); @@ -456,7 +456,7 @@ void AddChild(YamlNode child, YamlNode parent, ChildIndex relationship) void RemoveChild(YamlNode child, YamlNode parent, ChildIndex relationship) { - if (!parents.TryGetValue(child, out ICollection set)) + if (!parents.TryGetValue(child, out var set)) return; if (set is ParentAndIndex[]) @@ -486,7 +486,7 @@ void RemoveChildSubscribers(IList parentPaths, ChildIndex childIndex) void ShiftChild(YamlNode child, YamlNode parent, ChildIndex relationship, int shift) { - if (!parents.TryGetValue(child, out ICollection set)) + if (!parents.TryGetValue(child, out var set)) return; var newChildIndex = new ChildIndex(relationship.Index + shift, relationship.IsKey); @@ -500,7 +500,7 @@ void ShiftChild(YamlNode child, YamlNode parent, ChildIndex relationship, int sh var newPaths = new List(); foreach (var subpath in pathTrie.GetSubpaths(oldPath)) { - if (!subscribers.TryGetValue(subpath, out Dictionary subs)) + if (!subscribers.TryGetValue(subpath, out var subs)) continue; var newPath = subpath.Clone(); @@ -533,7 +533,7 @@ public IList GetPaths(YamlNode child) if (child is YamlStream) return new Path[0]; - if (!parents.TryGetValue(child, out ICollection relationships)) + if (!parents.TryGetValue(child, out var relationships)) return new Path[0]; var result = new List(); diff --git a/src/SharpYaml/Parser.cs b/src/SharpYaml/Parser.cs index a74dba4f..490f881c 100644 --- a/src/SharpYaml/Parser.cs +++ b/src/SharpYaml/Parser.cs @@ -258,7 +258,7 @@ private Event ParseDocumentStart(bool isImplicit) if (isImplicit && !(GetCurrentToken() is VersionDirective || GetCurrentToken() is TagDirective || GetCurrentToken() is DocumentStart || GetCurrentToken() is StreamEnd)) { - TagDirectiveCollection directives = new TagDirectiveCollection(); + var directives = new TagDirectiveCollection(); ProcessDirectives(directives); states.Push(ParserState.YAML_PARSE_DOCUMENT_END_STATE); @@ -272,9 +272,9 @@ private Event ParseDocumentStart(bool isImplicit) else if (GetCurrentToken() is not StreamEnd) { - Mark start = GetCurrentToken().Start; - TagDirectiveCollection directives = new TagDirectiveCollection(); - VersionDirective versionDirective = ProcessDirectives(directives); + var start = GetCurrentToken().Start; + var directives = new TagDirectiveCollection(); + var versionDirective = ProcessDirectives(directives); var current = GetCurrentToken(); if (current is not DocumentStart) @@ -440,7 +440,7 @@ private Event ParseNode(bool isBlock, bool isIndentlessSequence) return evt; } - Mark start = GetCurrentToken().Start; + var start = GetCurrentToken().Start; Anchor anchor = null; Tag tag = null; @@ -483,7 +483,7 @@ private Event ParseNode(bool isBlock, bool isIndentlessSequence) tagName = null; } - string anchorName = anchor != null ? string.IsNullOrEmpty(anchor.Value) ? null : anchor.Value : null; + var anchorName = anchor != null ? string.IsNullOrEmpty(anchor.Value) ? null : anchor.Value : null; bool isImplicit = string.IsNullOrEmpty(tagName); @@ -570,8 +570,8 @@ private Event ParseNode(bool isBlock, bool isIndentlessSequence) private Event ParseDocumentEnd() { bool isImplicit = true; - Mark start = GetCurrentToken().Start; - Mark end = start; + var start = GetCurrentToken().Start; + var end = start; if (GetCurrentToken() is DocumentEnd) { @@ -601,7 +601,7 @@ private Event ParseBlockSequenceEntry(bool isFirst) if (GetCurrentToken() is BlockEntry) { - Mark mark = GetCurrentToken().End; + var mark = GetCurrentToken().End; Skip(); if (!(GetCurrentToken() is BlockEntry || GetCurrentToken() is BlockEnd)) @@ -640,7 +640,7 @@ private Event ParseIndentlessSequenceEntry() { if (GetCurrentToken() is BlockEntry) { - Mark mark = GetCurrentToken().End; + var mark = GetCurrentToken().End; Skip(); if (!(GetCurrentToken() is BlockEntry || GetCurrentToken() is Key || GetCurrentToken() is Value || GetCurrentToken() is BlockEnd)) @@ -682,7 +682,7 @@ private Event ParseBlockMappingKey(bool isFirst) if (GetCurrentToken() is Key) { - Mark mark = GetCurrentToken().End; + var mark = GetCurrentToken().End; Skip(); if (!(GetCurrentToken() is Key || GetCurrentToken() is Value || GetCurrentToken() is BlockEnd)) { @@ -726,7 +726,7 @@ private Event ParseBlockMappingValue() { if (GetCurrentToken() is Value) { - Mark mark = GetCurrentToken().End; + var mark = GetCurrentToken().End; Skip(); if (!(GetCurrentToken() is Key || GetCurrentToken() is Value || GetCurrentToken() is BlockEnd)) @@ -819,7 +819,7 @@ private Event ParseFlowSequenceEntryMappingKey() } else { - Mark mark = GetCurrentToken().End; + var mark = GetCurrentToken().End; Skip(); state = ParserState.YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE; return ProcessEmptyScalar(mark); diff --git a/src/SharpYaml/Scanner.cs b/src/SharpYaml/Scanner.cs index cc7727d3..59cd7312 100644 --- a/src/SharpYaml/Scanner.cs +++ b/src/SharpYaml/Scanner.cs @@ -698,7 +698,7 @@ private void FetchDirective() // Create the YAML-DIRECTIVE or TAG-DIRECTIVE token. - Token token = ScanDirective(); + var token = ScanDirective(); // Append the token to the queue. @@ -718,13 +718,13 @@ private Token ScanDirective() { // Eat '%'. - Mark start = CurrentPosition; + var start = CurrentPosition; Skip(); // Scan the directive name. - string name = ScanDirectiveName(start); + var name = ScanDirectiveName(start); // Is it a YAML directive? @@ -792,13 +792,13 @@ private void FetchDocumentIndicator(bool isStartToken) // Consume the token. - Mark start = CurrentPosition; + var start = CurrentPosition; Skip(); Skip(); Skip(); - Token token = isStartToken ? (Token)new DocumentStart(start, CurrentPosition) : new DocumentEnd(start, start); + var token = isStartToken ? (Token)new DocumentStart(start, CurrentPosition) : new DocumentEnd(start, start); tokens.Enqueue(token); } @@ -821,7 +821,7 @@ private void FetchFlowCollectionStart(bool isSequenceToken) // Consume the token. - Mark start = CurrentPosition; + var start = CurrentPosition; Skip(); // Create the FLOW-SEQUENCE-START of FLOW-MAPPING-START token. @@ -872,7 +872,7 @@ private void FetchFlowCollectionEnd(bool isSequenceToken) // Consume the token. - Mark start = CurrentPosition; + var start = CurrentPosition; Skip(); Token token; @@ -916,7 +916,7 @@ private void FetchFlowEntry() // Consume the token. - Mark start = CurrentPosition; + var start = CurrentPosition; Skip(); // Create the FLOW-ENTRY token and append it to the queue. @@ -960,7 +960,7 @@ private void FetchBlockEntry() // Consume the token. - Mark start = CurrentPosition; + var start = CurrentPosition; Skip(); // Create the BLOCK-ENTRY token and append it to the queue. @@ -999,7 +999,7 @@ private void FetchKey() // Consume the token. - Mark start = CurrentPosition; + var start = CurrentPosition; Skip(); // Create the KEY token and append it to the queue. @@ -1012,7 +1012,7 @@ private void FetchKey() /// private void FetchValue() { - SimpleKey simpleKey = simpleKeys.Peek(); + var simpleKey = simpleKeys.Peek(); // Have we find a simple key? @@ -1061,7 +1061,7 @@ private void FetchValue() // Consume the token. - Mark start = CurrentPosition; + var start = CurrentPosition; Skip(); // Create the VALUE token and append it to the queue. @@ -1138,13 +1138,13 @@ private Token ScanAnchor(bool isAlias) { // Eat the indicator character. - Mark start = CurrentPosition; + var start = CurrentPosition; Skip(); // Consume the value. - StringBuilder value = new StringBuilder(); + var value = new StringBuilder(); while (analyzer.IsAlpha()) { value.Append(ReadCurrentCharacter()); @@ -1197,7 +1197,7 @@ private void FetchTag() /// Token ScanTag() { - Mark start = CurrentPosition; + var start = CurrentPosition; // Check if the tag is in the canonical form. @@ -1234,7 +1234,7 @@ Token ScanTag() // First, try to scan a handle. - string firstPart = ScanTagHandle(false, start); + var firstPart = ScanTagHandle(false, start); // Check if it is, indeed, handle. @@ -1304,9 +1304,9 @@ private void FetchBlockScalar(bool isLiteral) /// Token ScanBlockScalar(bool isLiteral) { - StringBuilder value = new StringBuilder(); - StringBuilder leadingBreak = new StringBuilder(); - StringBuilder trailingBreaks = new StringBuilder(); + var value = new StringBuilder(); + var leadingBreak = new StringBuilder(); + var trailingBreaks = new StringBuilder(); int chomping = 0; int increment = 0; @@ -1315,7 +1315,7 @@ Token ScanBlockScalar(bool isLiteral) // Eat the indicator '|' or '>'. - Mark start = CurrentPosition; + var start = CurrentPosition; Skip(); @@ -1398,7 +1398,7 @@ Token ScanBlockScalar(bool isLiteral) SkipLine(); } - Mark end = CurrentPosition; + var end = CurrentPosition; // Set the intendation level if it was specified. @@ -1479,7 +1479,7 @@ Token ScanBlockScalar(bool isLiteral) // Create a token. - ScalarStyle style = isLiteral ? ScalarStyle.Literal : ScalarStyle.Folded; + var style = isLiteral ? ScalarStyle.Literal : ScalarStyle.Folded; return new Scalar(value.ToString(), style, start, end); } @@ -1565,8 +1565,8 @@ private Token ScanFlowScalar(bool isSingleQuoted) { // Eat the left quote. - Mark start = CurrentPosition; - Mark end = CurrentPosition; + var start = CurrentPosition; + var end = CurrentPosition; Skip(); @@ -1841,8 +1841,8 @@ private Token ScanPlainScalar() bool hasLeadingBlanks = false; int currentIndent = indent + 1; - Mark start = CurrentPosition; - Mark end = CurrentPosition; + var start = CurrentPosition; + var end = CurrentPosition; // Consume the content of the plain scalar. @@ -1997,7 +1997,7 @@ private Token ScanPlainScalar() /// private void RemoveSimpleKey() { - SimpleKey key = simpleKeys.Peek(); + var key = simpleKeys.Peek(); if (key.IsPossible && key.IsRequired) { @@ -2022,7 +2022,7 @@ private void RemoveSimpleKey() /// private string ScanDirectiveName(Mark start) { - StringBuilder name = new StringBuilder(); + var name = new StringBuilder(); // Consume the directive name. @@ -2102,7 +2102,7 @@ private Token ScanTagDirectiveValue(Mark start) // Scan a handle. - string handle = ScanTagHandle(true, start); + var handle = ScanTagHandle(true, start); // Expect a whitespace. @@ -2115,7 +2115,7 @@ private Token ScanTagDirectiveValue(Mark start) // Scan a prefix. - string prefix = ScanTagUri(null, start); + var prefix = ScanTagUri(null, start); // Expect a whitespace or line break. @@ -2132,7 +2132,7 @@ private Token ScanTagDirectiveValue(Mark start) /// private string ScanTagUri(string head, Mark start) { - StringBuilder tag = new StringBuilder(); + var tag = new StringBuilder(); if (head != null && head.Length > 1) { tag.Append(head.Substring(1)); @@ -2251,7 +2251,7 @@ private string ScanTagHandle(bool isDirective, Mark start) // Copy the '!' character. - StringBuilder tagHandle = new StringBuilder(); + var tagHandle = new StringBuilder(); tagHandle.Append(ReadCurrentCharacter()); // Copy all subsequent alphabetical and numerical characters. @@ -2349,7 +2349,7 @@ private void SaveSimpleKey() if (simpleKeyAllowed) { - SimpleKey key = new SimpleKey(true, isRequired, tokensParsed + tokens.Count, CurrentPosition); + var key = new SimpleKey(true, isRequired, tokensParsed + tokens.Count, CurrentPosition); RemoveSimpleKey(); diff --git a/src/SharpYaml/Schemas/SchemaBase.cs b/src/SharpYaml/Schemas/SchemaBase.cs index 6b25d1c6..8febbc9d 100644 --- a/src/SharpYaml/Schemas/SchemaBase.cs +++ b/src/SharpYaml/Schemas/SchemaBase.cs @@ -92,7 +92,7 @@ public string ExpandTag(string shortTag) if (shortTag == null) return null; - return shortTagToLongTag.TryGetValue(shortTag, out string tagExpanded) ? tagExpanded : shortTag; + return shortTagToLongTag.TryGetValue(shortTag, out var tagExpanded) ? tagExpanded : shortTag; } public string ShortenTag(string longTag) @@ -100,7 +100,7 @@ public string ShortenTag(string longTag) if (longTag == null) return null; - return longTagToShortTag.TryGetValue(longTag, out string tagShortened) ? tagShortened : longTag; + return longTagToShortTag.TryGetValue(longTag, out var tagShortened) ? tagShortened : longTag; } public string GetDefaultTag(NodeEvent nodeEvent) @@ -122,7 +122,7 @@ public string GetDefaultTag(NodeEvent nodeEvent) if (nodeEvent is Scalar scalar) { - TryParse(scalar, false, out string tag, out object value); + TryParse(scalar, false, out var tag, out _); return tag; } @@ -135,7 +135,7 @@ public string GetDefaultTag(Type type) throw new ArgumentNullException("type"); EnsureScalarRules(); - mapTypeToShortTag.TryGetValue(type, out string defaultTag); + mapTypeToShortTag.TryGetValue(type, out var defaultTag); return defaultTag; } @@ -252,7 +252,7 @@ public bool TryParse(Scalar scalar, Type type, out object value) // Parse only values if we have some rules if (mapTypeToScalarResolutionRuleList.Count > 0) { - if (mapTypeToScalarResolutionRuleList.TryGetValue(type, out List rules)) + if (mapTypeToScalarResolutionRuleList.TryGetValue(type, out var rules)) { foreach (var rule in rules) { @@ -277,7 +277,7 @@ public Type GetTypeForDefaultTag(string shortTag) return null; } - mapShortTagToType.TryGetValue(shortTag, out Type type); + mapShortTagToType.TryGetValue(shortTag, out var type); return type; } diff --git a/src/SharpYaml/Serialization/AssemblyRegistry.cs b/src/SharpYaml/Serialization/AssemblyRegistry.cs index 20b003a5..4ce9ad40 100644 --- a/src/SharpYaml/Serialization/AssemblyRegistry.cs +++ b/src/SharpYaml/Serialization/AssemblyRegistry.cs @@ -214,7 +214,7 @@ public virtual Type TypeFromTag(string tag, out bool isAlias) lock (lockCache) { // Else try to find a registered alias - if (tagToType.TryGetValue(shortTag, out MappedType mappedType)) + if (tagToType.TryGetValue(shortTag, out var mappedType)) { isAlias = mappedType.Remapped; return mappedType.Type; @@ -244,12 +244,10 @@ public virtual string TagFromType(Type type) return "!!null"; } - string tagName; - lock (lockCache) { // First try to resolve a tag from registered tag - if (!typeToTag.TryGetValue(type, out tagName)) + if (!typeToTag.TryGetValue(type, out var tagName)) { // Else try to use schema tag for scalars // Else use full name of the type @@ -257,9 +255,8 @@ public virtual string TagFromType(Type type) tagName = schema.GetDefaultTag(type) ?? Uri.EscapeUriString($"!{typeName}"); typeToTag.Add(type, tagName); } + return tagName; } - - return tagName; } public virtual Type ResolveType(string typeName) diff --git a/src/SharpYaml/Serialization/AttributeRegistry.cs b/src/SharpYaml/Serialization/AttributeRegistry.cs index cd0e55f3..2799b8a7 100644 --- a/src/SharpYaml/Serialization/AttributeRegistry.cs +++ b/src/SharpYaml/Serialization/AttributeRegistry.cs @@ -83,7 +83,7 @@ public virtual List GetAttributes(MemberInfo memberInfo, bool inherit lock (globalLock) { // Use a cache of attributes - if (cachedAttributes.TryGetValue(key, out List attributes)) + if (cachedAttributes.TryGetValue(key, out var attributes)) { return attributes; } @@ -93,7 +93,7 @@ public virtual List GetAttributes(MemberInfo memberInfo, bool inherit attributes = defaultAttributes.ToList(); // And add registered attributes - if (registeredAttributes.TryGetValue(memberInfo, out List registered)) + if (registeredAttributes.TryGetValue(memberInfo, out var registered)) { attributes.AddRange(registered); } @@ -124,7 +124,7 @@ public void Register(MemberInfo memberInfo, Attribute attribute) lock (globalLock) { // Use a cache of attributes - if (!cachedAttributes.TryGetValue(new MemberInfoKey(memberInfo, false), out List attributes)) + if (!cachedAttributes.TryGetValue(new MemberInfoKey(memberInfo, false), out var attributes)) { if (!registeredAttributes.TryGetValue(memberInfo, out attributes)) { diff --git a/src/SharpYaml/Serialization/Descriptors/ObjectDescriptor.cs b/src/SharpYaml/Serialization/Descriptors/ObjectDescriptor.cs index e29a308c..fa977517 100644 --- a/src/SharpYaml/Serialization/Descriptors/ObjectDescriptor.cs +++ b/src/SharpYaml/Serialization/Descriptors/ObjectDescriptor.cs @@ -144,7 +144,7 @@ public virtual void Initialize() foreach (var member in members) { - if (mapMembers.TryGetValue(member.Name, out IMemberDescriptor existingMember)) + if (mapMembers.TryGetValue(member.Name, out var existingMember)) { throw new YamlException($"Failed to get ObjectDescriptor for type [{Type.FullName}]. The member [{member}] cannot be registered as a member with the same name is already registered [{existingMember}]"); } @@ -208,7 +208,7 @@ public IMemberDescriptor this[string name] { if (mapMembers == null) throw new KeyNotFoundException(name); - mapMembers.TryGetValue(name, out IMemberDescriptor member); + mapMembers.TryGetValue(name, out var member); return member; } } @@ -376,8 +376,8 @@ protected virtual bool PrepareMember(MemberDescriptorBase member) if (defaultValueAttribute != null && member.ShouldSerialize == null && !emitDefaultValues) { - object defaultValue = defaultValueAttribute.Value; - Type defaultType = defaultValue?.GetType(); + var defaultValue = defaultValueAttribute.Value; + var defaultType = defaultValue?.GetType(); if (defaultType.IsNumeric() && defaultType != memberType) defaultValue = memberType.CastToNumericType(defaultValue); member.ShouldSerialize = obj => !TypeExtensions.AreEqual(defaultValue, member.Get(obj)); diff --git a/src/SharpYaml/Serialization/Descriptors/PrimitiveDescriptor.cs b/src/SharpYaml/Serialization/Descriptors/PrimitiveDescriptor.cs index af8143a5..c2fed86c 100644 --- a/src/SharpYaml/Serialization/Descriptors/PrimitiveDescriptor.cs +++ b/src/SharpYaml/Serialization/Descriptors/PrimitiveDescriptor.cs @@ -119,7 +119,7 @@ public static bool IsPrimitive(Type type) public object ParseEnum(string enumAsText, out bool remapped) { remapped = false; - if (enumRemap != null && enumRemap.TryGetValue(enumAsText, out object value)) + if (enumRemap != null && enumRemap.TryGetValue(enumAsText, out var value)) { remapped = true; return value; diff --git a/src/SharpYaml/Serialization/Descriptors/TypeDescriptorFactory.cs b/src/SharpYaml/Serialization/Descriptors/TypeDescriptorFactory.cs index b71d3028..a99e7edb 100644 --- a/src/SharpYaml/Serialization/Descriptors/TypeDescriptorFactory.cs +++ b/src/SharpYaml/Serialization/Descriptors/TypeDescriptorFactory.cs @@ -86,7 +86,7 @@ public ITypeDescriptor Find(Type type, IComparer memberComparer) lock (registeredDescriptors) { // Caching is integrated in this class, avoiding a ChainedTypeDescriptorFactory - if (registeredDescriptors.TryGetValue(type, out ITypeDescriptor descriptor)) + if (registeredDescriptors.TryGetValue(type, out var descriptor)) { return descriptor; } diff --git a/src/SharpYaml/Serialization/DocumentLoadingState.cs b/src/SharpYaml/Serialization/DocumentLoadingState.cs index 2f34dcc2..d387035d 100644 --- a/src/SharpYaml/Serialization/DocumentLoadingState.cs +++ b/src/SharpYaml/Serialization/DocumentLoadingState.cs @@ -87,7 +87,7 @@ public void AddAnchor(YamlNode node) /// public YamlNode GetNode(string anchor, bool throwException, Mark start, Mark end) { - if (anchors.TryGetValue(anchor, out YamlNode target)) + if (anchors.TryGetValue(anchor, out var target)) { return target; } diff --git a/src/SharpYaml/Serialization/Serializer.cs b/src/SharpYaml/Serialization/Serializer.cs index e9310c18..16bb29bf 100644 --- a/src/SharpYaml/Serialization/Serializer.cs +++ b/src/SharpYaml/Serialization/Serializer.cs @@ -84,7 +84,7 @@ public Serializer(SerializerSettings settings) { this.Settings = settings ?? new SerializerSettings(); TypeDescriptorFactory = CreateTypeDescriptorFactory(); - ObjectSerializer = CreateProcessor(out RoutingSerializer routingSerializer); + ObjectSerializer = CreateProcessor(out var routingSerializer); RoutingSerializer = routingSerializer; } @@ -496,7 +496,7 @@ public T DeserializeInto(EventReader reader, T existingObject, out Serializer /// reader public object Deserialize(EventReader reader, Type expectedType, object existingObject = null, SerializerContextSettings contextSettings = null) { - return Deserialize(reader, expectedType, existingObject, contextSettings, out SerializerContext context); + return Deserialize(reader, expectedType, existingObject, contextSettings, out var context); } /// diff --git a/src/SharpYaml/Serialization/Serializers/AnchorSerializer.cs b/src/SharpYaml/Serialization/Serializers/AnchorSerializer.cs index c5661fe1..25adf675 100644 --- a/src/SharpYaml/Serialization/Serializers/AnchorSerializer.cs +++ b/src/SharpYaml/Serialization/Serializers/AnchorSerializer.cs @@ -125,7 +125,7 @@ public override void WriteYaml(ref ObjectContext objectContext) if (isAnchorable) { - if (objectToAlias.TryGetValue(value, out string alias)) + if (objectToAlias.TryGetValue(value, out var alias)) { objectContext.Writer.Emit(new AliasEventInfo(value, value.GetType()) { Alias = alias }); return; diff --git a/src/SharpYaml/Serialization/Serializers/DictionarySerializer.cs b/src/SharpYaml/Serialization/Serializers/DictionarySerializer.cs index cc19395f..bb73fac0 100644 --- a/src/SharpYaml/Serialization/Serializers/DictionarySerializer.cs +++ b/src/SharpYaml/Serialization/Serializers/DictionarySerializer.cs @@ -83,7 +83,7 @@ protected override void ReadMember(ref ObjectContext objectContext) else if (objectContext.Settings.SerializeDictionaryItemsAsMembers && dictionaryDescriptor.KeyType == typeof(string)) { // Read dictionaries that can be serialized as items - if (!TryReadMember(ref objectContext, out string memberName)) + if (!TryReadMember(ref objectContext, out var memberName)) { var value = ReadMemberValue(ref objectContext, null, null, dictionaryDescriptor.ValueType); dictionaryDescriptor.AddToDictionary(objectContext.Instance, memberName, value); diff --git a/src/SharpYaml/Serialization/Serializers/ObjectSerializer.cs b/src/SharpYaml/Serialization/Serializers/ObjectSerializer.cs index 55fcce83..668274a2 100644 --- a/src/SharpYaml/Serialization/Serializers/ObjectSerializer.cs +++ b/src/SharpYaml/Serialization/Serializers/ObjectSerializer.cs @@ -194,7 +194,7 @@ protected virtual void ReadMembers(ref ObjectContext objectContext /// Unable to deserialize property [{0}] not found in type [{1}].DoFormat(propertyName, typeDescriptor) protected virtual void ReadMember(ref ObjectContext objectContext) { - if (!TryReadMember(ref objectContext, out Scalar memberScalar, out string memberName)) + if (!TryReadMember(ref objectContext, out var memberScalar, out var memberName)) { if (!objectContext.Settings.IgnoreUnmatchedProperties) throw new YamlException(memberScalar.Start, memberScalar.End, $"Unable to deserialize property [{memberName}] not found in type [{objectContext.Descriptor}]"); @@ -209,7 +209,7 @@ protected virtual void ReadMember(ref ObjectContext objectContext) /// true if the member was successfully read, false otherwise. protected bool TryReadMember(ref ObjectContext objectContext, out string memberName) { - return TryReadMember(ref objectContext, out Scalar scalar, out memberName); + return TryReadMember(ref objectContext, out var scalar, out memberName); } /// diff --git a/src/SharpYaml/Serialization/Serializers/PrimitiveSerializer.cs b/src/SharpYaml/Serialization/Serializers/PrimitiveSerializer.cs index 622f4f94..617fdee3 100644 --- a/src/SharpYaml/Serialization/Serializers/PrimitiveSerializer.cs +++ b/src/SharpYaml/Serialization/Serializers/PrimitiveSerializer.cs @@ -94,8 +94,7 @@ public override object ConvertFrom(ref ObjectContext context, Scalar scalar) switch (type.GetTypeCode()) { case TypeCode.Boolean: - object value; - context.SerializerContext.Schema.TryParse(scalar, type, out value); + context.SerializerContext.Schema.TryParse(scalar, type, out var value); return value; case TypeCode.DateTime: return DateTime.Parse(text, CultureInfo.InvariantCulture); @@ -156,7 +155,7 @@ public override object ConvertFrom(ref ObjectContext context, Scalar scalar) if (type == typeof(object)) { // Try to parse the scalar directly - if (context.SerializerContext.Schema.TryParse(scalar, true, out string defaultTag, out object scalarValue)) + if (context.SerializerContext.Schema.TryParse(scalar, true, out var defaultTag, out var scalarValue)) { return scalarValue; } diff --git a/src/SharpYaml/Serialization/Serializers/RoutingSerializer.cs b/src/SharpYaml/Serialization/Serializers/RoutingSerializer.cs index 335f9b3a..d73e2ee5 100644 --- a/src/SharpYaml/Serialization/Serializers/RoutingSerializer.cs +++ b/src/SharpYaml/Serialization/Serializers/RoutingSerializer.cs @@ -89,7 +89,7 @@ public void WriteYaml(ref ObjectContext objectContext) private IYamlSerializable GetSerializer(SerializerContext context, ITypeDescriptor typeDescriptor) { - if (!serializers.TryGetValue(typeDescriptor.Type, out IYamlSerializable serializer)) + if (!serializers.TryGetValue(typeDescriptor.Type, out var serializer)) { foreach (var factory in factories) { diff --git a/src/SharpYaml/Serialization/YamlDocument.cs b/src/SharpYaml/Serialization/YamlDocument.cs index 83a0d0a4..499fede3 100644 --- a/src/SharpYaml/Serialization/YamlDocument.cs +++ b/src/SharpYaml/Serialization/YamlDocument.cs @@ -85,7 +85,7 @@ public YamlDocument(string rootNode) /// The events. internal YamlDocument(EventReader events) { - DocumentLoadingState state = new DocumentLoadingState(); + var state = new DocumentLoadingState(); events.Expect(); @@ -130,7 +130,7 @@ public void AssignAnchors(YamlDocument document) document.Accept(this); - Random random = new Random(); + var random = new Random(); foreach (var visitedNode in visitedNodes) { if (visitedNode.Value) @@ -187,7 +187,7 @@ protected override void Visit(YamlSequenceNode sequence) private void AssignAnchors() { - AnchorAssigningVisitor visitor = new AnchorAssigningVisitor(); + var visitor = new AnchorAssigningVisitor(); visitor.AssignAnchors(this); } diff --git a/src/SharpYaml/Serialization/YamlMappingNode.cs b/src/SharpYaml/Serialization/YamlMappingNode.cs index d07853ca..9d556024 100644 --- a/src/SharpYaml/Serialization/YamlMappingNode.cs +++ b/src/SharpYaml/Serialization/YamlMappingNode.cs @@ -75,15 +75,15 @@ public class YamlMappingNode : YamlNode, IEnumerableThe state. internal YamlMappingNode(EventReader events, DocumentLoadingState state) { - MappingStart mapping = events.Expect(); + var mapping = events.Expect(); Load(mapping, state); Style = mapping.Style; bool hasUnresolvedAliases = false; while (!events.Accept()) { - YamlNode key = ParseNode(events, state); - YamlNode value = ParseNode(events, state); + var key = ParseNode(events, state); + var value = ParseNode(events, state); try { @@ -255,7 +255,7 @@ internal override void ResolveAliases(DocumentLoadingState state) { foreach (var entry in keysToUpdate) { - YamlNode value = Children[entry.Key]; + var value = Children[entry.Key]; Children.Remove(entry.Key); Children.Add(entry.Value, value); } @@ -299,7 +299,7 @@ public override bool Equals(object other) foreach (var entry in Children) { - if (!obj.Children.TryGetValue(entry.Key, out YamlNode otherNode) || !SafeEquals(entry.Value, otherNode)) + if (!obj.Children.TryGetValue(entry.Key, out var otherNode) || !SafeEquals(entry.Value, otherNode)) { return false; } diff --git a/src/SharpYaml/Serialization/YamlNode.cs b/src/SharpYaml/Serialization/YamlNode.cs index 2d412caa..024590e7 100644 --- a/src/SharpYaml/Serialization/YamlNode.cs +++ b/src/SharpYaml/Serialization/YamlNode.cs @@ -119,7 +119,7 @@ internal static YamlNode ParseNode(EventReader events, DocumentLoadingState stat if (events.Accept()) { - AnchorAlias alias = events.Expect(); + var alias = events.Expect(); return state.GetNode(alias.Value, false, alias.Start, alias.End) ?? new YamlAliasNode(alias.Value); } diff --git a/src/SharpYaml/Serialization/YamlScalarNode.cs b/src/SharpYaml/Serialization/YamlScalarNode.cs index ff1ed82c..eaf5c904 100644 --- a/src/SharpYaml/Serialization/YamlScalarNode.cs +++ b/src/SharpYaml/Serialization/YamlScalarNode.cs @@ -76,7 +76,7 @@ public class YamlScalarNode : YamlNode /// The state. internal YamlScalarNode(EventReader events, DocumentLoadingState state) { - Scalar scalar = events.Expect(); + var scalar = events.Expect(); Load(scalar, state); Value = scalar.Value; Style = scalar.Style; diff --git a/src/SharpYaml/Serialization/YamlSequenceNode.cs b/src/SharpYaml/Serialization/YamlSequenceNode.cs index 9cf3447e..dd613c1e 100644 --- a/src/SharpYaml/Serialization/YamlSequenceNode.cs +++ b/src/SharpYaml/Serialization/YamlSequenceNode.cs @@ -78,14 +78,14 @@ public class YamlSequenceNode : YamlNode, IEnumerable /// The state. internal YamlSequenceNode(EventReader events, DocumentLoadingState state) { - SequenceStart sequence = events.Expect(); + var sequence = events.Expect(); Load(sequence, state); Style = sequence.Style; bool hasUnresolvedAliases = false; while (!events.Accept()) { - YamlNode child = ParseNode(events, state); + var child = ParseNode(events, state); Children.Add(child); hasUnresolvedAliases |= child is YamlAliasNode; } diff --git a/src/SharpYaml/Serialization/YamlStream.cs b/src/SharpYaml/Serialization/YamlStream.cs index 33935785..61e84efd 100644 --- a/src/SharpYaml/Serialization/YamlStream.cs +++ b/src/SharpYaml/Serialization/YamlStream.cs @@ -106,11 +106,11 @@ public void Load(TextReader input) var parser = Parser.CreateParser(input); - EventReader events = new EventReader(parser); + var events = new EventReader(parser); events.Expect(); while (!events.Accept()) { - YamlDocument document = new YamlDocument(events); + var document = new YamlDocument(events); Documents.Add(document); } events.Expect(); diff --git a/src/SharpYaml/TypeExtensions.cs b/src/SharpYaml/TypeExtensions.cs index 16fc0001..a9bbe109 100644 --- a/src/SharpYaml/TypeExtensions.cs +++ b/src/SharpYaml/TypeExtensions.cs @@ -101,7 +101,7 @@ public static Type GetInterface(this Type type, Type lookInterfaceType) && interfaceType.GetGenericTypeDefinition() == lookInterfaceType) return interfaceType; - for (Type t = type; t != null; t = t.GetTypeInfo().BaseType) + for (var t = type; t != null; t = t.GetTypeInfo().BaseType) if (t.GetTypeInfo().IsGenericType && t.GetGenericTypeDefinition() == lookInterfaceType) return t; } From 44824bea1ba4bca3ecc8f54835856602c3f0f6e6 Mon Sep 17 00:00:00 2001 From: udaken <7896698+udaken@users.noreply.github.com> Date: Wed, 22 Jun 2022 17:09:07 +0900 Subject: [PATCH 5/5] Add Nullable reference type annotations --- src/SharpYaml/Emitter.cs | 16 ++-- src/SharpYaml/EventReader.cs | 8 +- src/SharpYaml/Events/DocumentStart.cs | 8 +- src/SharpYaml/Events/MappingStart.cs | 4 +- src/SharpYaml/Events/NodeEvent.cs | 8 +- src/SharpYaml/Events/Scalar.cs | 6 +- src/SharpYaml/Events/SequenceStart.cs | 4 +- src/SharpYaml/IParser.cs | 2 +- src/SharpYaml/Model/PathTrie.cs | 2 +- src/SharpYaml/Model/YamlDocument.cs | 14 +-- src/SharpYaml/Model/YamlElement.cs | 4 +- src/SharpYaml/Model/YamlMapping.cs | 82 +++++++++--------- src/SharpYaml/Model/YamlNode.cs | 14 +-- .../Model/YamlNodeEventEnumerator.cs | 10 +-- src/SharpYaml/Model/YamlNodeTracker.cs | 46 +++++----- src/SharpYaml/Model/YamlSequence.cs | 17 ++-- src/SharpYaml/Model/YamlStream.cs | 16 ++-- src/SharpYaml/Model/YamlValue.cs | 14 +-- src/SharpYaml/Parser.cs | 16 ++-- src/SharpYaml/Polyfills/IsExternalInit.cs | 10 +++ src/SharpYaml/Polyfills/NullableAttributes.cs | 85 +++++++++++++++++++ src/SharpYaml/Scanner.cs | 2 + src/SharpYaml/Schemas/FailsafeSchema.cs | 3 +- src/SharpYaml/Schemas/IYamlSchema.cs | 17 ++-- src/SharpYaml/Schemas/SchemaBase.cs | 25 +++--- .../Serialization/AssemblyRegistry.cs | 14 +-- .../Serialization/AttributeRegistry.cs | 6 +- .../Serialization/ChainedObjectFactory.cs | 6 +- .../Serialization/DefaultObjectFactory.cs | 8 +- .../Descriptors/ArrayDescriptor.cs | 2 +- .../Descriptors/CollectionDescriptor.cs | 14 +-- .../Descriptors/DefaultKeyComparer.cs | 2 +- .../Descriptors/DictionaryDescriptor.cs | 19 +++-- .../Descriptors/MemberDescriptorBase.cs | 6 +- .../Descriptors/ObjectDescriptor.cs | 20 +++-- .../Descriptors/PrimitiveDescriptor.cs | 2 +- .../Descriptors/PropertyDescriptor.cs | 4 +- .../Descriptors/TypeDescriptorFactory.cs | 4 +- .../Serialization/DocumentLoadingState.cs | 3 +- .../DynamicMemberDescriptorBase.cs | 6 +- src/SharpYaml/Serialization/EventInfo.cs | 12 +-- .../Serialization/IAttributeRegistry.cs | 6 +- .../Serialization/IMemberDescriptor.cs | 6 +- src/SharpYaml/Serialization/IObjectFactory.cs | 2 +- .../Serialization/IObjectSerializerBackend.cs | 12 +-- .../Serialization/ITagTypeResolver.cs | 4 +- .../Serialization/ITypeDescriptor.cs | 4 +- .../Serialization/ITypeDescriptorFactory.cs | 4 +- .../Serialization/IYamlSerializable.cs | 2 +- .../Serialization/IYamlSerializableFactory.cs | 2 +- .../Serialization/IdentityEqualityComparer.cs | 2 +- .../Serialization/LambdaObjectFactory.cs | 4 +- src/SharpYaml/Serialization/ObjectContext.cs | 12 +-- .../Serialization/OrderedDictionary.cs | 4 +- src/SharpYaml/Serialization/Serializer.cs | 82 +++++++++--------- .../Serialization/SerializerContext.cs | 23 ++--- .../SerializerContextSettings.cs | 2 +- .../Serialization/SerializerSettings.cs | 8 +- .../Serializers/AnchorSerializer.cs | 19 +++-- .../Serializers/ArraySerializer.cs | 4 +- .../Serializers/ChainedSerializer.cs | 2 +- .../Serializers/CollectionSerializer.cs | 4 +- .../DefaultObjectSerializerBackend.cs | 14 +-- .../Serializers/DictionarySerializer.cs | 6 +- .../Serializers/ObjectSerializer.cs | 12 +-- .../Serializers/PrimitiveSerializer.cs | 6 +- .../Serializers/RoutingSerializer.cs | 2 +- .../Serializers/ScalarSerializerBase.cs | 4 +- .../Serializers/TagTypeSerializer.cs | 6 +- src/SharpYaml/Serialization/YamlAliasNode.cs | 2 +- .../Serialization/YamlMappingNode.cs | 10 +-- .../Serialization/YamlMemberAttribute.cs | 2 +- src/SharpYaml/Serialization/YamlNode.cs | 8 +- .../YamlNodeIdentityEqualityComparer.cs | 2 +- src/SharpYaml/Serialization/YamlScalarNode.cs | 2 +- .../Serialization/YamlSequenceNode.cs | 4 +- src/SharpYaml/SharpYaml.csproj | 1 + src/SharpYaml/Tokens/TagDirective.cs | 2 +- src/SharpYaml/Tokens/VersionDirective.cs | 2 +- src/SharpYaml/TypeExtensions.cs | 12 +-- src/SharpYaml/Version.cs | 2 +- src/SharpYaml/YamlException.cs | 2 +- 82 files changed, 504 insertions(+), 366 deletions(-) create mode 100644 src/SharpYaml/Polyfills/IsExternalInit.cs create mode 100644 src/SharpYaml/Polyfills/NullableAttributes.cs diff --git a/src/SharpYaml/Emitter.cs b/src/SharpYaml/Emitter.cs index 6e66f08b..cd302c2c 100644 --- a/src/SharpYaml/Emitter.cs +++ b/src/SharpYaml/Emitter.cs @@ -90,9 +90,9 @@ public class Emitter : IEmitter private class MutableStringLookAheadBuffer : ILookAheadBuffer { - private string value; + private string? value; - public string Value + public string? Value { get { return value; } set @@ -135,7 +135,7 @@ public void Cache(int length) { } private struct AnchorData { - public string anchor; + public string? anchor; public bool isAlias; } @@ -143,8 +143,8 @@ private struct AnchorData private struct TagData { - public string handle; - public string suffix; + public string? handle; + public string? suffix; } private TagData tagData; @@ -313,7 +313,7 @@ private bool NeedMoreEvents() return true; } - private void AnalyzeAnchor(string anchor, bool isAlias) + private void AnalyzeAnchor(string? anchor, bool isAlias) { anchorData.anchor = anchor; anchorData.isAlias = isAlias; @@ -1680,7 +1680,7 @@ private void EmitFlowMappingKey(ParsingEvent evt, bool isFirst) private const int MaxAliasLength = 128; - private static int SafeStringLength(string value) + private static int SafeStringLength(string? value) { return value != null ? value.Length : 0; } @@ -1851,7 +1851,7 @@ private void WriteBlockScalarHints(string value) isOpenEnded = false; - string chomp_hint = null; + string? chomp_hint = null; if (value.Length == 0 || !analyzer.IsBreak(value.Length - 1)) { chomp_hint = "-"; diff --git a/src/SharpYaml/EventReader.cs b/src/SharpYaml/EventReader.cs index 18309367..f358e1fc 100644 --- a/src/SharpYaml/EventReader.cs +++ b/src/SharpYaml/EventReader.cs @@ -128,13 +128,13 @@ public bool Accept() where T : Event /// /// Type of the . /// Returns the current event if it is of type T; otherwise returns null. - public T Allow() where T : Event + public T? Allow() where T : Event { if (!Accept()) { return null; } - var yamlEvent = (T)Parser.Current; + var yamlEvent = (T?)Parser.Current; MoveNext(); return yamlEvent; } @@ -144,13 +144,13 @@ public T Allow() where T : Event /// /// Type of the . /// Returns the current event if it is of type T; otherwise returns null. - public T Peek() where T : Event + public T? Peek() where T : Event { if (!Accept()) { return null; } - var yamlEvent = (T)Parser.Current; + var yamlEvent = (T?)Parser.Current; return yamlEvent; } diff --git a/src/SharpYaml/Events/DocumentStart.cs b/src/SharpYaml/Events/DocumentStart.cs index b15e2394..1dd97557 100644 --- a/src/SharpYaml/Events/DocumentStart.cs +++ b/src/SharpYaml/Events/DocumentStart.cs @@ -70,13 +70,13 @@ public sealed class DocumentStart : ParsingEvent /// Gets the tags. /// /// The tags. - public TagDirectiveCollection Tags { get; } + public TagDirectiveCollection? Tags { get; } /// /// Gets the version. /// /// The version. - public VersionDirective Version { get; } + public VersionDirective? Version { get; } /// /// Gets a value indicating whether this instance is implicit. @@ -94,7 +94,7 @@ public sealed class DocumentStart : ParsingEvent /// 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) + public DocumentStart(VersionDirective? version, TagDirectiveCollection? tags, bool isImplicit, Mark start, Mark end) : base(start, end) { this.Version = version; @@ -108,7 +108,7 @@ public DocumentStart(VersionDirective version, TagDirectiveCollection tags, bool /// The version. /// The tags. /// Indicates whether the event is implicit. - public DocumentStart(VersionDirective version, TagDirectiveCollection tags, bool isImplicit) + public DocumentStart(VersionDirective? version, TagDirectiveCollection? tags, bool isImplicit) : this(version, tags, isImplicit, Mark.Empty, Mark.Empty) { } diff --git a/src/SharpYaml/Events/MappingStart.cs b/src/SharpYaml/Events/MappingStart.cs index 6caf86ad..73224814 100644 --- a/src/SharpYaml/Events/MappingStart.cs +++ b/src/SharpYaml/Events/MappingStart.cs @@ -93,7 +93,7 @@ public sealed class MappingStart : NodeEvent /// 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, YamlStyle style, Mark start, Mark end) + public MappingStart(string? anchor, string? tag, bool isImplicit, YamlStyle style, Mark start, Mark end) : base(anchor, tag, start, end) { this.IsImplicit = isImplicit; @@ -107,7 +107,7 @@ public MappingStart(string anchor, string tag, bool isImplicit, YamlStyle style, /// The tag. /// Indicates whether the event is implicit. /// The style of the mapping. - public MappingStart(string anchor, string tag, bool isImplicit, YamlStyle style) + public MappingStart(string? anchor, string? tag, bool isImplicit, YamlStyle style) : this(anchor, tag, isImplicit, style, Mark.Empty, Mark.Empty) { } diff --git a/src/SharpYaml/Events/NodeEvent.cs b/src/SharpYaml/Events/NodeEvent.cs index 539da44e..9615d0b6 100644 --- a/src/SharpYaml/Events/NodeEvent.cs +++ b/src/SharpYaml/Events/NodeEvent.cs @@ -59,13 +59,13 @@ public abstract class NodeEvent : ParsingEvent /// Gets the anchor. /// /// - public string Anchor { get; } + public string? Anchor { get; } /// /// Gets the tag. /// /// - public string Tag { get; } + public string? Tag { get; } /// /// Gets a value indicating whether this instance is canonical. @@ -80,7 +80,7 @@ public abstract class NodeEvent : ParsingEvent /// The tag. /// The start position of the event. /// The end position of the event. - protected NodeEvent(string anchor, string tag, Mark start, Mark end) + protected NodeEvent(string? anchor, string? tag, Mark start, Mark end) : base(start, end) { if (anchor != null) @@ -108,7 +108,7 @@ protected NodeEvent(string anchor, string tag, Mark start, Mark end) /// /// Initializes a new instance of the class. /// - protected NodeEvent(string anchor, string tag) + protected NodeEvent(string? anchor, string? tag) : this(anchor, tag, Mark.Empty, Mark.Empty) { } diff --git a/src/SharpYaml/Events/Scalar.cs b/src/SharpYaml/Events/Scalar.cs index b4598799..7fd289fd 100644 --- a/src/SharpYaml/Events/Scalar.cs +++ b/src/SharpYaml/Events/Scalar.cs @@ -105,7 +105,7 @@ public sealed class Scalar : NodeEvent /// . /// 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) + 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; @@ -123,7 +123,7 @@ public Scalar(string anchor, string tag, string value, ScalarStyle style, bool i /// The style. /// . /// . - public Scalar(string anchor, string tag, string value, ScalarStyle style, bool isPlainImplicit, bool isQuotedImplicit) + 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) { } @@ -152,7 +152,7 @@ public Scalar(string value, ScalarStyle style) /// /// The tag. /// The value. - public Scalar(string tag, string value) + public Scalar(string? tag, string value) : this(null, tag, value, ScalarStyle.Any, true, true, Mark.Empty, Mark.Empty) { } diff --git a/src/SharpYaml/Events/SequenceStart.cs b/src/SharpYaml/Events/SequenceStart.cs index ab3377de..2f00739f 100644 --- a/src/SharpYaml/Events/SequenceStart.cs +++ b/src/SharpYaml/Events/SequenceStart.cs @@ -101,7 +101,7 @@ public SequenceStart() : base(null, null) /// The style. /// The start position of the event. /// The end position of the event. - public SequenceStart(string anchor, string tag, bool isImplicit, YamlStyle style, Mark start, Mark end) + public SequenceStart(string? anchor, string? tag, bool isImplicit, YamlStyle style, Mark start, Mark end) : base(anchor, tag, start, end) { this.IsImplicit = isImplicit; @@ -111,7 +111,7 @@ public SequenceStart(string anchor, string tag, bool isImplicit, YamlStyle style /// /// Initializes a new instance of the class. /// - public SequenceStart(string anchor, string tag, bool isImplicit, YamlStyle style) + public SequenceStart(string? anchor, string? tag, bool isImplicit, YamlStyle style) : this(anchor, tag, isImplicit, style, Mark.Empty, Mark.Empty) { } diff --git a/src/SharpYaml/IParser.cs b/src/SharpYaml/IParser.cs index 56c590a3..3ad18711 100644 --- a/src/SharpYaml/IParser.cs +++ b/src/SharpYaml/IParser.cs @@ -55,7 +55,7 @@ public interface IParser /// /// Gets the current event. /// - ParsingEvent Current { get; } + ParsingEvent? Current { get; } /// /// Moves to the next event. diff --git a/src/SharpYaml/Model/PathTrie.cs b/src/SharpYaml/Model/PathTrie.cs index e4485071..64b656a1 100644 --- a/src/SharpYaml/Model/PathTrie.cs +++ b/src/SharpYaml/Model/PathTrie.cs @@ -58,7 +58,7 @@ public bool IsEmpty get { return !Self && subPaths.Count == 0; } } - public PathTrieNode Find(IList indices, int start) + public PathTrieNode? Find(IList indices, int start) { if (start == indices.Count) return this; diff --git a/src/SharpYaml/Model/YamlDocument.cs b/src/SharpYaml/Model/YamlDocument.cs index 79718501..4ccf2fd8 100644 --- a/src/SharpYaml/Model/YamlDocument.cs +++ b/src/SharpYaml/Model/YamlDocument.cs @@ -29,7 +29,7 @@ public class YamlDocument : YamlNode { private DocumentStart _documentStart; private DocumentEnd _documentEnd; - private YamlElement _contents; + private YamlElement? _contents; public YamlDocument() { @@ -37,7 +37,7 @@ public YamlDocument() _documentEnd = new DocumentEnd(true); } - YamlDocument(DocumentStart documentStart, DocumentEnd documentEnd, YamlElement contents, YamlNodeTracker tracker) + YamlDocument(DocumentStart documentStart, DocumentEnd documentEnd, YamlElement? contents, YamlNodeTracker? tracker) { Tracker = tracker; @@ -46,7 +46,7 @@ public YamlDocument() Contents = contents; } - public static YamlDocument Load(EventReader eventReader, YamlNodeTracker tracker = null) + public static YamlDocument Load(EventReader eventReader, YamlNodeTracker? tracker = null) { var documentStart = eventReader.Allow(); @@ -85,7 +85,7 @@ public DocumentEnd DocumentEnd } } - public YamlElement Contents + public YamlElement? Contents { get { return _contents; } set @@ -102,7 +102,7 @@ public YamlElement Contents } } - public override YamlNodeTracker Tracker + public override YamlNodeTracker? Tracker { get { return base.Tracker; } internal set @@ -120,9 +120,9 @@ internal set } } - public override YamlNode DeepClone(YamlNodeTracker tracker = null) + public override YamlNode DeepClone(YamlNodeTracker? tracker = null) { - return new YamlDocument(_documentStart, _documentEnd, (YamlElement)Contents?.DeepClone(), tracker); + return new YamlDocument(_documentStart, _documentEnd, (YamlElement?)Contents?.DeepClone(), tracker); } } } diff --git a/src/SharpYaml/Model/YamlElement.cs b/src/SharpYaml/Model/YamlElement.cs index a0204c21..131e709d 100644 --- a/src/SharpYaml/Model/YamlElement.cs +++ b/src/SharpYaml/Model/YamlElement.cs @@ -21,8 +21,8 @@ namespace SharpYaml.Model { public abstract class YamlElement : YamlNode { - public abstract string Anchor { get; set; } - public abstract string Tag { get; set; } + public abstract string? Anchor { get; set; } + public abstract string? Tag { get; set; } public abstract bool IsCanonical { get; } } } diff --git a/src/SharpYaml/Model/YamlMapping.cs b/src/SharpYaml/Model/YamlMapping.cs index bb506e92..9aaa9ea1 100644 --- a/src/SharpYaml/Model/YamlMapping.cs +++ b/src/SharpYaml/Model/YamlMapping.cs @@ -20,28 +20,29 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using SharpYaml.Events; namespace SharpYaml.Model { - public class YamlMapping : YamlContainer, IDictionary, IList> + public class YamlMapping : YamlContainer, IDictionary, IList> { private MappingStart _mappingStart; private readonly List _keys; - private readonly Dictionary _contents; + private readonly Dictionary _contents; - private Dictionary stringKeys; + private Dictionary? stringKeys; public YamlMapping() { _mappingStart = new MappingStart(); MappingEnd = new MappingEnd(); _keys = new List(); - _contents = new Dictionary(); + _contents = new Dictionary(); } - YamlMapping(MappingStart mappingStart, MappingEnd mappingEnd, List keys, Dictionary contents, YamlNodeTracker tracker) + YamlMapping(MappingStart mappingStart, MappingEnd mappingEnd, List keys, Dictionary contents, YamlNodeTracker? tracker) { if (tracker == null) { @@ -51,7 +52,7 @@ public YamlMapping() else { _keys = new List(); - _contents = new Dictionary(); + _contents = new Dictionary(); Tracker = tracker; @@ -66,6 +67,7 @@ public YamlMapping() public MappingStart MappingStart { get => _mappingStart; + [MemberNotNull(nameof(_mappingStart))] set { var oldValue = _mappingStart; @@ -79,7 +81,7 @@ public MappingStart MappingStart internal MappingEnd MappingEnd { get; } - public override string Anchor + public override string? Anchor { get { return _mappingStart.Anchor; } set @@ -93,7 +95,7 @@ public override string Anchor } } - public override string Tag + public override string? Tag { get { return _mappingStart.Tag; } set @@ -137,12 +139,12 @@ public override bool IsImplicit } } - public static YamlMapping Load(EventReader eventReader, YamlNodeTracker tracker) + public static YamlMapping Load(EventReader eventReader, YamlNodeTracker? tracker) { var mappingStart = eventReader.Allow(); var keys = new List(); - var contents = new Dictionary(); + var contents = new Dictionary(); while (!eventReader.Accept()) { var key = ReadElement(eventReader, tracker); @@ -165,12 +167,12 @@ IEnumerator IEnumerable.GetEnumerator() return GetEnumerator(); } - public IEnumerator> GetEnumerator() + public IEnumerator> GetEnumerator() { - return _keys.Select(k => new KeyValuePair(k, _contents[k])).GetEnumerator(); + return _keys.Select(k => new KeyValuePair(k, _contents[k])).GetEnumerator(); } - void ICollection>.Add(KeyValuePair item) + void ICollection>.Add(KeyValuePair item) { Add(item.Key, item.Value); } @@ -191,17 +193,17 @@ public void Clear() } } - bool ICollection>.Contains(KeyValuePair item) + bool ICollection>.Contains(KeyValuePair item) { return _contents.ContainsKey(item.Key); } - void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) + void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) { - ((ICollection>)_contents).CopyTo(array, arrayIndex); + ((ICollection>)_contents).CopyTo(array, arrayIndex); } - bool ICollection>.Remove(KeyValuePair item) + bool ICollection>.Remove(KeyValuePair item) { return Remove(item.Key); } @@ -209,7 +211,7 @@ bool ICollection>.Remove(KeyValuePair(key, value), _keys.Count - 1, null); + Tracker.OnMappingAddPair(this, new KeyValuePair(key, value), _keys.Count - 1, null); } } - public override YamlNodeTracker Tracker + public override YamlNodeTracker? Tracker { get { return base.Tracker; } internal set @@ -245,7 +247,7 @@ internal set _keys[i].Tracker = value; val.Tracker = value; - Tracker.OnMappingAddPair(this, new KeyValuePair(_keys[i], val), i, null); + Tracker.OnMappingAddPair(this, new KeyValuePair(_keys[i], val), i, null); } } } @@ -293,12 +295,12 @@ public bool Remove(string key) return false; } - public bool TryGetValue(YamlElement key, out YamlElement value) + public bool TryGetValue(YamlElement key, [MaybeNullWhen(false)] out YamlElement value) { return _contents.TryGetValue(key, out value); } - public bool TryGetValue(string key, out YamlElement value) + public bool TryGetValue(string key, [MaybeNullWhen(false)] out YamlElement value) { if (stringKeys == null) stringKeys = Keys.OfType().ToDictionary(k => k.Value, k => k); @@ -312,7 +314,7 @@ public bool TryGetValue(string key, out YamlElement value) return TryGetValue(yamlKey, out value); } - public YamlElement this[YamlElement key] + public YamlElement? this[YamlElement key] { get { @@ -334,7 +336,7 @@ public YamlElement this[YamlElement key] } } - YamlElement oldContents = null; + YamlElement? oldContents = null; if (!keyAdded && Tracker != null) { oldContents = _contents[key]; @@ -353,21 +355,21 @@ public YamlElement this[YamlElement key] { key.Tracker = Tracker; value.Tracker = Tracker; - Tracker.OnMappingAddPair(this, new KeyValuePair(key, value), + Tracker.OnMappingAddPair(this, new KeyValuePair(key, value), _keys.Count - 1, null); } else { value.Tracker = Tracker; Tracker.OnMappingPairChanged(this, _keys.IndexOf(key), - new KeyValuePair(key, oldContents), - new KeyValuePair(key, value)); + new KeyValuePair(key, oldContents), + new KeyValuePair(key, value)); } } } } - public YamlElement this[string key] + public YamlElement? this[string key] { get { @@ -392,14 +394,14 @@ public YamlElement this[string key] } public ICollection Keys { get { return _keys; } } - public ICollection Values { get { return _contents.Values; } } + public ICollection Values { get { return _contents.Values; } } - public int IndexOf(KeyValuePair item) + public int IndexOf(KeyValuePair item) { return _keys.IndexOf(item.Key); } - public void Insert(int index, KeyValuePair item) + public void Insert(int index, KeyValuePair item) { if (_contents.ContainsKey(item.Key)) throw new Exception("Key already present."); @@ -417,7 +419,7 @@ public void Insert(int index, KeyValuePair item) item.Key.Tracker = Tracker; item.Value.Tracker = Tracker; - ICollection> nextChildren = null; + ICollection>? nextChildren = null; if (index < _contents.Count - 1) nextChildren = this.Skip(index + 1).ToArray(); @@ -440,17 +442,17 @@ public void RemoveAt(int index) if (Tracker != null) { - IEnumerable> nextChildren = null; + IEnumerable>? nextChildren = null; if (index < _contents.Count) nextChildren = this.Skip(index); - Tracker.OnMappingRemovePair(this, new KeyValuePair(key, value), index, nextChildren); + Tracker.OnMappingRemovePair(this, new KeyValuePair(key, value), index, nextChildren); } } - public KeyValuePair this[int index] + public KeyValuePair this[int index] { - get { return new KeyValuePair(_keys[index], _contents[_keys[index]]); } + get { return new KeyValuePair(_keys[index], _contents[_keys[index]]); } set { if (_keys[index] != value.Key && _contents.ContainsKey(value.Key)) @@ -483,19 +485,19 @@ public KeyValuePair this[int index] value.Key.Tracker = Tracker; value.Value.Tracker = Tracker; Tracker.OnMappingPairChanged(this, index, - new KeyValuePair(oldKey, oldValue), + new KeyValuePair(oldKey, oldValue), value); } } } - public override YamlNode DeepClone(YamlNodeTracker tracker = null) + public override YamlNode DeepClone(YamlNodeTracker? tracker = null) { var keysClone = new List(_keys.Count); for (var i = 0; i < _keys.Count; i++) keysClone.Add((YamlElement)_keys[i].DeepClone()); - var cloneContents = new Dictionary(); + var cloneContents = new Dictionary(); for (var i = 0; i < _keys.Count; i++) cloneContents[keysClone[i]] = (YamlElement)_contents[_keys[i]].DeepClone(); diff --git a/src/SharpYaml/Model/YamlNode.cs b/src/SharpYaml/Model/YamlNode.cs index 7e67e6a0..faf6a586 100644 --- a/src/SharpYaml/Model/YamlNode.cs +++ b/src/SharpYaml/Model/YamlNode.cs @@ -33,9 +33,9 @@ namespace SharpYaml.Model { public abstract class YamlNode { - public virtual YamlNodeTracker Tracker { get; internal set; } + public virtual YamlNodeTracker? Tracker { get; internal set; } - protected static YamlElement ReadElement(EventReader eventReader, YamlNodeTracker tracker = null) + protected static YamlElement? ReadElement(EventReader eventReader, YamlNodeTracker? tracker = null) { if (eventReader.Accept()) return YamlMapping.Load(eventReader, tracker); @@ -92,12 +92,12 @@ public override string ToString() return sb.ToString().Trim(); } - public T ToObject(SerializerSettings settings = null) + public T? ToObject(SerializerSettings? settings = null) { - return (T)ToObject(typeof(T), settings); + return (T?)ToObject(typeof(T), settings); } - public object ToObject(Type type, SerializerSettings settings = null) + public object? ToObject(Type type, SerializerSettings? settings = null) { var s = new Serializer(settings); @@ -115,7 +115,7 @@ public void Emit(ParsingEvent evnt) } } - public static YamlElement FromObject(object value, SerializerSettings settings = null, Type expectedType = null) + public static YamlElement FromObject(object value, SerializerSettings? settings = null, Type? expectedType = null) { var s = new Serializer(settings); @@ -126,6 +126,6 @@ public static YamlElement FromObject(object value, SerializerSettings settings = return ReadElement(new EventReader(new MemoryParser(emitter.Events))); } - public abstract YamlNode DeepClone(YamlNodeTracker tracker = null); + public abstract YamlNode DeepClone(YamlNodeTracker? tracker = null); } } diff --git a/src/SharpYaml/Model/YamlNodeEventEnumerator.cs b/src/SharpYaml/Model/YamlNodeEventEnumerator.cs index 358f53e6..2943bb41 100644 --- a/src/SharpYaml/Model/YamlNodeEventEnumerator.cs +++ b/src/SharpYaml/Model/YamlNodeEventEnumerator.cs @@ -26,10 +26,10 @@ namespace SharpYaml.Model public sealed class YamlNodeEventEnumerator : IEnumerable, IEnumerator { private readonly YamlNode root; - private YamlNode currentNode; + private YamlNode? currentNode; private int currentIndex; - private Stack nodePath; - private Stack indexPath; + private Stack? nodePath; + private Stack? indexPath; public YamlNodeEventEnumerator(YamlNode root) { @@ -184,14 +184,14 @@ void Pop() public void Reset() { - Current = null; + Current = null!; nodePath.Clear(); indexPath.Clear(); currentNode = root; currentIndex = -1; } - public ParsingEvent Current { get; private set; } + public ParsingEvent Current { get; private set; } = null!; object IEnumerator.Current => Current; } diff --git a/src/SharpYaml/Model/YamlNodeTracker.cs b/src/SharpYaml/Model/YamlNodeTracker.cs index 6bffc447..0f1ba38a 100644 --- a/src/SharpYaml/Model/YamlNodeTracker.cs +++ b/src/SharpYaml/Model/YamlNodeTracker.cs @@ -18,7 +18,7 @@ public ChildIndex(int index, bool isKey) IsKey = isKey; } - public YamlNode Resolve(YamlNode parent) + public YamlNode? Resolve(YamlNode parent) { if (parent is YamlStream stream) { @@ -62,7 +62,7 @@ public bool Equals(ChildIndex other) return Index == other.Index && IsKey == other.IsKey; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (ReferenceEquals(null, obj)) return false; return obj is ChildIndex index && Equals(index); @@ -88,7 +88,7 @@ public Path(YamlNode root, ChildIndex[] indices) Indices = indices; } - public YamlNode Resolve() + public YamlNode? Resolve() { var node = Root; foreach (var index in Indices) @@ -107,7 +107,7 @@ public bool Equals(Path other) return Equals(Root, other.Root) && Indices.SequenceEqual(other.Indices); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (ReferenceEquals(null, obj)) return false; return obj is Path path && Equals(path); @@ -200,14 +200,14 @@ public ChildChangedEventArgs(TParent node, IList parentPaths, TChild oldCh } public new TParent Node { get { return (TParent)base.Node; } } - public TChild OldChild { get; } + public TChild? OldChild { get; } public TChild NewChild { get; } public int Index { get; } } public abstract class PropertyChangedEventArgs : TrackerEventArgs where TNode : YamlNode { - public PropertyChangedEventArgs(TNode node, IList parentPaths, TProperty oldValue, TProperty newValue) + public PropertyChangedEventArgs(TNode node, IList parentPaths, TProperty? oldValue, TProperty newValue) : base(node, parentPaths) { OldValue = oldValue; @@ -215,7 +215,7 @@ public PropertyChangedEventArgs(TNode node, IList parentPaths, TProperty o } public new TNode Node { get { return (TNode)base.Node; } } - public TProperty OldValue { get; } + public TProperty? OldValue { get; } public TProperty NewValue { get; } } @@ -254,7 +254,7 @@ public override TrackerEventType EventType public class DocumentStartChanged : PropertyChangedEventArgs { - public DocumentStartChanged(YamlDocument node, IList parentPaths, DocumentStart oldValue, DocumentStart newValue) + public DocumentStartChanged(YamlDocument node, IList parentPaths, DocumentStart? oldValue, DocumentStart newValue) : base(node, parentPaths, oldValue, newValue) { } public override TrackerEventType EventType @@ -375,7 +375,7 @@ public override TrackerEventType EventType public class ScalarPropertiesChanged : PropertyChangedEventArgs { - public ScalarPropertiesChanged(YamlValue node, IList parentPaths, Scalar oldValue, Scalar newValue) : base(node, parentPaths, oldValue, newValue) { } + public ScalarPropertiesChanged(YamlValue node, IList parentPaths, Scalar? oldValue, Scalar newValue) : base(node, parentPaths, oldValue, newValue) { } public override TrackerEventType EventType { @@ -411,7 +411,7 @@ public bool Equals(ParentAndIndex other) return Equals(Parent, other.Parent) && Index.Equals(other.Index); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (ReferenceEquals(null, obj)) return false; return obj is ParentAndIndex index && Equals(index); @@ -558,7 +558,7 @@ public IList GetPaths(YamlNode child) return result; } - internal void OnStreamAddDocument(YamlStream sender, YamlDocument newDocument, int index, ICollection nextChildren) + internal void OnStreamAddDocument(YamlStream sender, YamlDocument newDocument, int index, ICollection? nextChildren) { var paths = GetPaths(sender); AddChild(newDocument, sender, new ChildIndex(index, false)); @@ -574,7 +574,7 @@ internal void OnStreamAddDocument(YamlStream sender, YamlDocument newDocument, i OnTrackerEvent(new StreamDocumentAdded(sender, paths, newDocument, index)); } - internal void OnStreamRemoveDocument(YamlStream sender, YamlDocument removedDocument, int index, IEnumerable nextChildren) + internal void OnStreamRemoveDocument(YamlStream sender, YamlDocument removedDocument, int index, IEnumerable? nextChildren) { var paths = GetPaths(sender); RemoveChild(removedDocument, sender, new ChildIndex(index, false)); @@ -605,7 +605,7 @@ internal void OnStreamDocumentChanged(YamlStream sender, int index, YamlDocument OnTrackerEvent(new StreamDocumentChanged(sender, paths, oldDocument, newDocument, index)); } - internal void OnDocumentStartChanged(YamlDocument sender, DocumentStart oldValue, DocumentStart newValue) + internal void OnDocumentStartChanged(YamlDocument sender, DocumentStart? oldValue, DocumentStart newValue) { if (oldValue == newValue) return; @@ -621,7 +621,7 @@ internal void OnDocumentEndChanged(YamlDocument sender, DocumentEnd oldValue, Do OnTrackerEvent(new DocumentEndChanged(sender, GetPaths(sender), oldValue, newValue)); } - internal void OnDocumentContentsChanged(YamlDocument sender, YamlElement oldValue, YamlElement newValue) + internal void OnDocumentContentsChanged(YamlDocument sender, YamlElement? oldValue, YamlElement newValue) { if (oldValue == newValue) return; @@ -645,7 +645,7 @@ internal void OnSequenceStartChanged(YamlSequence sender, SequenceStart oldValue OnTrackerEvent(new SequenceStartChanged(sender, GetPaths(sender), oldValue, newValue)); } - internal void OnSequenceAddElement(YamlSequence sender, YamlElement newElement, int index, ICollection nextChildren) + internal void OnSequenceAddElement(YamlSequence sender, YamlElement newElement, int index, ICollection? nextChildren) { var paths = GetPaths(sender); AddChild(newElement, sender, new ChildIndex(index, false)); @@ -661,7 +661,7 @@ internal void OnSequenceAddElement(YamlSequence sender, YamlElement newElement, OnTrackerEvent(new SequenceElementAdded(sender, paths, newElement, index)); } - internal void OnSequenceRemoveElement(YamlSequence sender, YamlElement removedElement, int index, IEnumerable nextChildren) + internal void OnSequenceRemoveElement(YamlSequence sender, YamlElement removedElement, int index, IEnumerable? nextChildren) { var paths = GetPaths(sender); RemoveChild(removedElement, sender, new ChildIndex(index, false)); @@ -699,7 +699,7 @@ internal void OnMappingStartChanged(YamlMapping sender, MappingStart oldValue, M OnTrackerEvent(new MappingStartChanged(sender, GetPaths(sender), oldValue, newValue)); } - internal void OnMappingAddPair(YamlMapping sender, KeyValuePair newPair, int index, ICollection> nextChildren) + internal void OnMappingAddPair(YamlMapping sender, KeyValuePair newPair, int index, ICollection>? nextChildren) { var paths = GetPaths(sender); @@ -720,7 +720,7 @@ internal void OnMappingAddPair(YamlMapping sender, KeyValuePair removedPair, int index, IEnumerable> nextChildren) + internal void OnMappingRemovePair(YamlMapping sender, KeyValuePair removedPair, int index, IEnumerable>? nextChildren) { var paths = GetPaths(sender); @@ -764,7 +764,7 @@ internal void OnMappingPairChanged(YamlMapping sender, int index, KeyValuePair TrackerEvent; + public event EventHandler? TrackerEvent; - private Dictionary> subscribers; - private Dictionary noFilterSubscribers; - private PathTrie pathTrie; + private Dictionary>? subscribers; + private Dictionary? noFilterSubscribers; + private PathTrie? pathTrie; void CompactSubscribers() { diff --git a/src/SharpYaml/Model/YamlSequence.cs b/src/SharpYaml/Model/YamlSequence.cs index c0f291df..94403eb2 100644 --- a/src/SharpYaml/Model/YamlSequence.cs +++ b/src/SharpYaml/Model/YamlSequence.cs @@ -19,6 +19,7 @@ // THE SOFTWARE. using System.Collections; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using SharpYaml.Events; @@ -36,7 +37,7 @@ public YamlSequence() _contents = new List(); } - YamlSequence(SequenceStart sequenceStart, SequenceEnd sequenceEnd, List contents, YamlNodeTracker tracker) + YamlSequence(SequenceStart sequenceStart, SequenceEnd sequenceEnd, List contents, YamlNodeTracker? tracker) { if (tracker == null) _contents = contents; @@ -69,7 +70,7 @@ public SequenceStart SequenceStart internal SequenceEnd SequenceEnd { get; } - public override string Anchor + public override string? Anchor { get { return _sequenceStart.Anchor; } set @@ -83,7 +84,7 @@ public override string Anchor } } - public override string Tag + public override string? Tag { get { return _sequenceStart.Tag; } set @@ -127,7 +128,7 @@ public override bool IsImplicit } } - public static YamlSequence Load(EventReader eventReader, YamlNodeTracker tracker = null) + public static YamlSequence Load(EventReader eventReader, YamlNodeTracker? tracker = null) { var sequenceStart = eventReader.Allow(); @@ -165,7 +166,7 @@ public void Add(YamlElement item) } } - public override YamlNodeTracker Tracker + public override YamlNodeTracker? Tracker { get { return base.Tracker; } internal set @@ -236,7 +237,7 @@ public void Insert(int index, YamlElement item) { item.Tracker = Tracker; - ICollection nextChildren = null; + ICollection? nextChildren = null; if (index < _contents.Count - 1) nextChildren = _contents.Skip(index + 1).ToArray(); @@ -252,7 +253,7 @@ public void RemoveAt(int index) if (Tracker != null) { - IEnumerable nextChildren = null; + IEnumerable? nextChildren = null; if (index < _contents.Count) nextChildren = _contents.Skip(index); @@ -277,7 +278,7 @@ public YamlElement this[int index] } } - public override YamlNode DeepClone(YamlNodeTracker tracker = null) + public override YamlNode DeepClone(YamlNodeTracker? tracker = null) { var contentsClone = new List(_contents.Count); for (var i = 0; i < _contents.Count; i++) diff --git a/src/SharpYaml/Model/YamlStream.cs b/src/SharpYaml/Model/YamlStream.cs index d127c26e..1be07526 100644 --- a/src/SharpYaml/Model/YamlStream.cs +++ b/src/SharpYaml/Model/YamlStream.cs @@ -29,7 +29,7 @@ public class YamlStream : YamlNode, IList { private readonly List _documents; - public YamlStream(YamlNodeTracker tracker = null) + public YamlStream(YamlNodeTracker? tracker = null) { StreamStart = new StreamStart(); StreamEnd = new StreamEnd(); @@ -37,7 +37,7 @@ public YamlStream(YamlNodeTracker tracker = null) Tracker = tracker; } - YamlStream(StreamStart streamStart, StreamEnd streamEnd, List documents, YamlNodeTracker tracker = null) + YamlStream(StreamStart streamStart, StreamEnd streamEnd, List documents, YamlNodeTracker? tracker = null) { this.StreamStart = streamStart; this.StreamEnd = streamEnd; @@ -58,12 +58,12 @@ public YamlStream(YamlNodeTracker tracker = null) internal StreamStart StreamStart { get; } internal StreamEnd StreamEnd { get; } - public static YamlStream Load(TextReader stream, YamlNodeTracker tracker = null) + public static YamlStream Load(TextReader stream, YamlNodeTracker? tracker = null) { return Load(new EventReader(Parser.CreateParser(stream)), tracker); } - public static YamlStream Load(EventReader eventReader, YamlNodeTracker tracker = null) + public static YamlStream Load(EventReader eventReader, YamlNodeTracker? tracker = null) { var streamStart = eventReader.Allow(); @@ -97,7 +97,7 @@ public void Add(YamlDocument item) } } - public override YamlNodeTracker Tracker + public override YamlNodeTracker? Tracker { get { return base.Tracker; } internal set @@ -168,7 +168,7 @@ public void Insert(int index, YamlDocument item) { item.Tracker = Tracker; - ICollection nextDocuments = null; + ICollection? nextDocuments = null; if (index < _documents.Count - 1) nextDocuments = _documents.Skip(index + 1).ToArray(); @@ -184,7 +184,7 @@ public void RemoveAt(int index) if (Tracker != null) { - IEnumerable nextDocuments = null; + IEnumerable? nextDocuments = null; if (index < _documents.Count) nextDocuments = _documents.Skip(index); @@ -209,7 +209,7 @@ public YamlDocument this[int index] } } - public override YamlNode DeepClone(YamlNodeTracker tracker = null) + public override YamlNode DeepClone(YamlNodeTracker? tracker = null) { var documentsClone = new List(_documents.Count); for (var i = 0; i < _documents.Count; i++) diff --git a/src/SharpYaml/Model/YamlValue.cs b/src/SharpYaml/Model/YamlValue.cs index f2f5e12f..6d30ed8c 100644 --- a/src/SharpYaml/Model/YamlValue.cs +++ b/src/SharpYaml/Model/YamlValue.cs @@ -20,6 +20,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using SharpYaml.Events; using SharpYaml.Schemas; using SharpYaml.Serialization.Serializers; @@ -30,14 +31,14 @@ public class YamlValue : YamlElement { private Scalar _scalar; - YamlValue(Scalar scalar, YamlNodeTracker tracker) + YamlValue(Scalar scalar, YamlNodeTracker? tracker) { Tracker = tracker; Scalar = scalar ?? throw new ArgumentNullException(nameof(scalar)); } - public YamlValue(object value, IYamlSchema schema = null) + public YamlValue(object value, IYamlSchema? schema = null) { var valueString = PrimitiveSerializer.ConvertValue(value); if (schema == null) @@ -49,6 +50,7 @@ public YamlValue(object value, IYamlSchema schema = null) internal Scalar Scalar { get { return _scalar; } + [MemberNotNull(nameof(_scalar))] set { var oldScalar = _scalar; @@ -60,19 +62,19 @@ internal Scalar Scalar } } - public static YamlValue Load(EventReader eventReader, YamlNodeTracker tracker = null) + public static YamlValue Load(EventReader eventReader, YamlNodeTracker? tracker = null) { var scalar = eventReader.Allow(); return new YamlValue(scalar, tracker); } - public override YamlNode DeepClone(YamlNodeTracker tracker = null) + public override YamlNode DeepClone(YamlNodeTracker? tracker = null) { return new YamlValue(_scalar, tracker); } - public override string Anchor + public override string? Anchor { get { return _scalar.Anchor; } set @@ -88,7 +90,7 @@ public override string Anchor } } - public override string Tag + public override string? Tag { get { return _scalar.Tag; } set diff --git a/src/SharpYaml/Parser.cs b/src/SharpYaml/Parser.cs index 490f881c..0f719155 100644 --- a/src/SharpYaml/Parser.cs +++ b/src/SharpYaml/Parser.cs @@ -81,7 +81,7 @@ public class Parser : IParser where TBuffer : ILookAheadBuffer private ParserState state; private readonly Scanner scanner; - private Token currentToken; + private Token? currentToken; private Token GetCurrentToken() { @@ -92,7 +92,7 @@ private Token GetCurrentToken() currentToken = scanner.Current; } } - return currentToken; + return currentToken!; } /// @@ -107,7 +107,7 @@ public Parser(TBuffer buffer) /// /// Gets the current event. /// - public Event Current { get; private set; } + public Event? Current { get; private set; } /// /// Moves to the next event. @@ -310,9 +310,9 @@ private Event ParseDocumentStart(bool isImplicit) /// /// Parse directives. /// - private VersionDirective ProcessDirectives(TagDirectiveCollection tags) + private VersionDirective? ProcessDirectives(TagDirectiveCollection tags) { - VersionDirective version = null; + VersionDirective? version = null; while (true) { @@ -442,8 +442,8 @@ private Event ParseNode(bool isBlock, bool isIndentlessSequence) var start = GetCurrentToken().Start; - Anchor anchor = null; - Tag tag = null; + Anchor? anchor = null; + Tag? tag = null; // The anchor and the tag can be in any order. This loop repeats at most twice. while (true) @@ -462,7 +462,7 @@ private Event ParseNode(bool isBlock, bool isIndentlessSequence) } } - string tagName = null; + string? tagName = null; if (tag != null) { if (string.IsNullOrEmpty(tag.Handle)) diff --git a/src/SharpYaml/Polyfills/IsExternalInit.cs b/src/SharpYaml/Polyfills/IsExternalInit.cs new file mode 100644 index 00000000..68ea486c --- /dev/null +++ b/src/SharpYaml/Polyfills/IsExternalInit.cs @@ -0,0 +1,10 @@ +namespace System.Runtime.CompilerServices +{ +#if !NET5_0_OR_GREATER + internal static class IsExternalInit + { + } +#endif + + +} diff --git a/src/SharpYaml/Polyfills/NullableAttributes.cs b/src/SharpYaml/Polyfills/NullableAttributes.cs new file mode 100644 index 00000000..b99641b7 --- /dev/null +++ b/src/SharpYaml/Polyfills/NullableAttributes.cs @@ -0,0 +1,85 @@ +// Based on code at located at https://github.com/dotnet/runtime/blob/79ae74f5ca5c8a6fe3a48935e85bd7374959c570/src/libraries/System.Private.CoreLib/src/System/Diagnostics/CodeAnalysis/NullableAttributes.cs + +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace System.Diagnostics.CodeAnalysis +{ +#if !NETSTANDARD2_1_OR_GREATER && !NETCOREAPP3_1_OR_GREATER + [AttributeUsage(AttributeTargets.Method, Inherited = false)] + internal sealed class DoesNotReturnAttribute : Attribute { } + + [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] + internal sealed class DoesNotReturnIfAttribute : Attribute + { + public DoesNotReturnIfAttribute(bool parameterValue) => ParameterValue = parameterValue; + + public bool ParameterValue { get; } + } + + [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] + internal sealed class NotNullWhenAttribute : Attribute + { + public NotNullWhenAttribute(bool returnValue) => ReturnValue = returnValue; + + public bool ReturnValue { get; } + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] + internal sealed class AllowNullAttribute : Attribute { } + + [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] + internal sealed class MaybeNullWhenAttribute : Attribute + { + public MaybeNullWhenAttribute(bool returnValue) => ReturnValue = returnValue; + + public bool ReturnValue { get; } + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] + internal sealed class MaybeNullAttribute : Attribute + { + public MaybeNullAttribute() { } + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] + internal sealed class NotNullIfNotNullAttribute : Attribute + { + public NotNullIfNotNullAttribute(string parameterName) => ParameterName = parameterName; + + public string ParameterName { get; } + } +#endif + +#if !NET5_0_OR_GREATER + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] + internal sealed class MemberNotNullAttribute : Attribute + { + public MemberNotNullAttribute(string member) => Members = new[] { member }; + + public MemberNotNullAttribute(params string[] members) => Members = members; + + public string[] Members { get; } + } + + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] + internal sealed class MemberNotNullWhenAttribute : Attribute + { + public MemberNotNullWhenAttribute(bool returnValue, string member) + { + ReturnValue = returnValue; + Members = new[] { member }; + } + public MemberNotNullWhenAttribute(bool returnValue, params string[] members) + { + ReturnValue = returnValue; + Members = members; + } + + public string[] Members { get; } + public bool ReturnValue { get; } + } +#endif + + +} diff --git a/src/SharpYaml/Scanner.cs b/src/SharpYaml/Scanner.cs index 59cd7312..7f973ecf 100644 --- a/src/SharpYaml/Scanner.cs +++ b/src/SharpYaml/Scanner.cs @@ -43,6 +43,8 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. +#nullable disable + using System; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/SharpYaml/Schemas/FailsafeSchema.cs b/src/SharpYaml/Schemas/FailsafeSchema.cs index a51e5b6e..39e518c9 100644 --- a/src/SharpYaml/Schemas/FailsafeSchema.cs +++ b/src/SharpYaml/Schemas/FailsafeSchema.cs @@ -43,6 +43,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. +using System.Diagnostics.CodeAnalysis; using SharpYaml.Events; namespace SharpYaml.Schemas @@ -105,7 +106,7 @@ protected override string GetDefaultTag(SequenceStart nodeEvent) return SeqShortTag; } - public override bool TryParse(Scalar scalar, bool parseValue, out string defaultTag, out object value) + public override bool TryParse(Scalar scalar, bool parseValue, [NotNullWhen(true)] out string? defaultTag, out object? value) { if (base.TryParse(scalar, parseValue, out defaultTag, out value)) { diff --git a/src/SharpYaml/Schemas/IYamlSchema.cs b/src/SharpYaml/Schemas/IYamlSchema.cs index 29e3e313..4c0c929d 100644 --- a/src/SharpYaml/Schemas/IYamlSchema.cs +++ b/src/SharpYaml/Schemas/IYamlSchema.cs @@ -44,6 +44,7 @@ // SOFTWARE. using System; +using System.Diagnostics.CodeAnalysis; using SharpYaml.Events; namespace SharpYaml.Schemas @@ -58,14 +59,16 @@ public interface IYamlSchema /// /// The tag. /// Expanded version of the tag. - string ExpandTag(string shortTag); + [return: NotNullIfNotNull("shortTag")] + string? ExpandTag(string shortTag); /// /// Shortens the tag. Example, transforms a long tag 'tag:yaml.org,2002:str' to its short version '!!str' /// /// The tag. /// Expanded version of the tag. - string ShortenTag(string tag); + [return: NotNullIfNotNull("tag")] + string? ShortenTag(string tag); /// /// Gets the default tag for the specified . The default tag can be different from a actual tag of this . @@ -78,14 +81,14 @@ public interface IYamlSchema /// Gets the default tag for the specified . This is only valid for scalar, return null if no default tag found. /// /// A short tag. - string GetDefaultTag(Type type); + string? GetDefaultTag(Type type); /// /// Determines whether the short tag implicit (e.g. !!int). /// /// The tag. /// true if [is tag implicit] [the specified tag]; otherwise, false. - bool IsTagImplicit(string tag); + bool IsTagImplicit(string? tag); /// /// Gets the default tag and value for the specified . The default tag can be different from a actual tag of this . @@ -95,7 +98,7 @@ public interface IYamlSchema /// The default tag decoded from the scalar. /// The value extracted from a scalar. /// System.String. - bool TryParse(Scalar scalar, bool decodeValue, out string defaultTag, out object value); + bool TryParse(Scalar scalar, bool decodeValue, [NotNullWhen(true)] out string? defaultTag, out object? value); /// /// Gets the default tag and value for the specified . The default tag can be different from a actual tag of this . @@ -104,14 +107,14 @@ public interface IYamlSchema /// The type. /// The value extracted from a scalar. /// System.String. - bool TryParse(Scalar scalar, Type type, out object value); + bool TryParse(Scalar scalar, Type type, out object? value); /// /// Gets the type for a default tag. /// /// The tag in short form. /// The type for a default tag or null if no default tag associated - Type GetTypeForDefaultTag(string tag); + Type? GetTypeForDefaultTag(string? tag); /// /// Registers a long/short tag association. diff --git a/src/SharpYaml/Schemas/SchemaBase.cs b/src/SharpYaml/Schemas/SchemaBase.cs index 8febbc9d..c29a76de 100644 --- a/src/SharpYaml/Schemas/SchemaBase.cs +++ b/src/SharpYaml/Schemas/SchemaBase.cs @@ -45,6 +45,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; using SharpYaml.Events; @@ -87,7 +88,8 @@ protected SchemaBase() /// public const string StrLongTag = "tag:yaml.org,2002:str"; - public string ExpandTag(string shortTag) + [return: NotNullIfNotNull("shortTag")] + public string? ExpandTag(string? shortTag) { if (shortTag == null) return null; @@ -95,7 +97,8 @@ public string ExpandTag(string shortTag) return shortTagToLongTag.TryGetValue(shortTag, out var tagExpanded) ? tagExpanded : shortTag; } - public string ShortenTag(string longTag) + [return: NotNullIfNotNull("longTag")] + public string? ShortenTag(string? longTag) { if (longTag == null) return null; @@ -129,7 +132,7 @@ public string GetDefaultTag(NodeEvent nodeEvent) throw new NotSupportedException($"NodeEvent [{nodeEvent.GetType().FullName}] not supported"); } - public string GetDefaultTag(Type type) + public string? GetDefaultTag(Type type) { if (type == null) throw new ArgumentNullException("type"); @@ -139,7 +142,7 @@ public string GetDefaultTag(Type type) return defaultTag; } - public bool IsTagImplicit(string tag) + public bool IsTagImplicit(string? tag) { if (tag == null) { @@ -183,7 +186,7 @@ public void RegisterTag(string shortTag, string longTag) /// The default tag for a seq. protected abstract string GetDefaultTag(SequenceStart nodeEvent); - public virtual bool TryParse(Scalar scalar, bool parseValue, out string defaultTag, out object value) + public virtual bool TryParse(Scalar scalar, bool parseValue, [NotNullWhen(true)] out string? defaultTag, out object? value) { if (scalar == null) throw new ArgumentNullException("scalar"); @@ -231,7 +234,7 @@ public virtual bool TryParse(Scalar scalar, bool parseValue, out string defaultT return false; } - public bool TryParse(Scalar scalar, Type type, out object value) + public bool TryParse(Scalar scalar, Type type, out object? value) { if (scalar == null) throw new ArgumentNullException("scalar"); @@ -270,7 +273,7 @@ public bool TryParse(Scalar scalar, Type type, out object value) return false; } - public Type GetTypeForDefaultTag(string shortTag) + public Type? GetTypeForDefaultTag(string? shortTag) { if (shortTag == null) { @@ -309,14 +312,14 @@ protected virtual void PrepareScalarRules() /// Add( ... ); /// EndUpdate(); // automaticall invoke internal calculation method /// - protected void AddScalarRule(string tag, string regex, Func decode, Func encode) + protected void AddScalarRule(string tag, string regex, Func decode, Func? encode) { // Make sure the tag is expanded to its long form var longTag = ShortenTag(tag); scalarTagResolutionRules.Add(new ScalarResolutionRule(longTag, regex, m => decode(m), m => encode((T)m), typeof(T))); } - protected void AddScalarRule(Type[] types, string tag, string regex, Func decode, Func encode) + protected void AddScalarRule(Type[] types, string tag, string regex, Func decode, Func? encode) { // Make sure the tag is expanded to its long form var longTag = ShortenTag(tag); @@ -419,7 +422,7 @@ private void Update() private class ScalarResolutionRule { - public ScalarResolutionRule(string shortTag, string regex, Func decoder, Func encoder, params Type[] types) + public ScalarResolutionRule(string shortTag, string regex, Func decoder, Func? encoder, params Type[] types) { Tag = shortTag; PatternSource = regex; @@ -431,7 +434,7 @@ public ScalarResolutionRule(string shortTag, string regex, Func d private readonly Type[] types; private readonly Func Decoder; - private readonly Func Encoder; + private readonly Func? Encoder; public string Tag { get; protected set; } public Regex Pattern { get; protected set; } diff --git a/src/SharpYaml/Serialization/AssemblyRegistry.cs b/src/SharpYaml/Serialization/AssemblyRegistry.cs index 4ce9ad40..8dcddf93 100644 --- a/src/SharpYaml/Serialization/AssemblyRegistry.cs +++ b/src/SharpYaml/Serialization/AssemblyRegistry.cs @@ -112,7 +112,7 @@ public void RegisterAssembly(Assembly assembly, IAttributeRegistry attributeRegi var attributes = attributeRegistry.GetAttributes(type.GetTypeInfo()); foreach (var attribute in attributes) { - string name = null; + string? name = null; bool isAlias = false; if (attribute is YamlTagAttribute tagAttribute) { @@ -187,7 +187,7 @@ public virtual void RegisterTagMapping(string tag, Type type, bool alias) } } - public virtual Type TypeFromTag(string tag, out bool isAlias) + public virtual Type? TypeFromTag(string? tag, out bool isAlias) { isAlias = false; @@ -198,7 +198,7 @@ public virtual Type TypeFromTag(string tag, out bool isAlias) // Get the default schema type if there is any var shortTag = schema.ShortenTag(tag); - Type type; + Type? type; if (shortTag != tag || shortTag.StartsWith("!!", StringComparison.Ordinal)) { type = schema.GetTypeForDefaultTag(shortTag); @@ -259,12 +259,12 @@ public virtual string TagFromType(Type type) } } - public virtual Type ResolveType(string typeName) + public virtual Type? ResolveType(string typeName) { var type = Type.GetType(typeName); if (type == null) { - string assemblyName = null; + string? assemblyName = null; // Find assembly name start (skip up to one space if needed) // We ignore everything else (version, publickeytoken, etc...) @@ -326,13 +326,13 @@ public virtual Type ResolveType(string typeName) readonly struct MappedType { - public MappedType(Type type, bool remapped) + public MappedType(Type? type, bool remapped) { Type = type; Remapped = remapped; } - public readonly Type Type; + public readonly Type? Type; public readonly bool Remapped; } diff --git a/src/SharpYaml/Serialization/AttributeRegistry.cs b/src/SharpYaml/Serialization/AttributeRegistry.cs index 2799b8a7..cf5578d0 100644 --- a/src/SharpYaml/Serialization/AttributeRegistry.cs +++ b/src/SharpYaml/Serialization/AttributeRegistry.cs @@ -62,13 +62,13 @@ public class AttributeRegistry : IAttributeRegistry private readonly Dictionary> cachedAttributes = new Dictionary>(); private readonly Dictionary> registeredAttributes = new Dictionary>(); - public Action> PrepareMembersCallback { get; set; } + public Action>? PrepareMembersCallback { get; set; } /// /// Gets or sets the attribute remapper. May be null /// /// The remap attribute. - public Func AttributeRemap { get; set; } + public Func? AttributeRemap { get; set; } /// /// Gets the attributes associated with the specified member. @@ -154,7 +154,7 @@ public bool Equals(MemberInfoKey other) return memberInfo.Equals(other.memberInfo) && inherit.Equals(other.inherit); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (ReferenceEquals(null, obj)) return false; diff --git a/src/SharpYaml/Serialization/ChainedObjectFactory.cs b/src/SharpYaml/Serialization/ChainedObjectFactory.cs index 09f3ea3b..251709ec 100644 --- a/src/SharpYaml/Serialization/ChainedObjectFactory.cs +++ b/src/SharpYaml/Serialization/ChainedObjectFactory.cs @@ -52,18 +52,18 @@ namespace SharpYaml.Serialization /// public class ChainedObjectFactory : IObjectFactory { - private readonly IObjectFactory nextFactory; + private readonly IObjectFactory? nextFactory; /// /// Initializes a new instance of the class. /// /// The next factory. - public ChainedObjectFactory(IObjectFactory nextFactory) + public ChainedObjectFactory(IObjectFactory? nextFactory) { this.nextFactory = nextFactory; } - public virtual object Create(Type type) + public virtual object? Create(Type type) { return nextFactory != null ? nextFactory.Create(type) : null; } diff --git a/src/SharpYaml/Serialization/DefaultObjectFactory.cs b/src/SharpYaml/Serialization/DefaultObjectFactory.cs index 957071f6..2844e8f8 100644 --- a/src/SharpYaml/Serialization/DefaultObjectFactory.cs +++ b/src/SharpYaml/Serialization/DefaultObjectFactory.cs @@ -46,6 +46,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Reflection; using SharpYaml.Serialization.Descriptors; @@ -73,7 +74,8 @@ public sealed class DefaultObjectFactory : IObjectFactory /// /// The type. /// The type of the implem or the same type as input if there is no default implementation - public static Type GetDefaultImplementation(Type type) + [return: NotNullIfNotNull("type")] + public static Type? GetDefaultImplementation(Type? type) { if (type == null) return null; @@ -81,7 +83,7 @@ public static Type GetDefaultImplementation(Type type) // TODO change this code. Make it configurable? if (type.GetTypeInfo().IsInterface) { - Type implementationType; + Type? implementationType; if (type.GetTypeInfo().IsGenericType) { if (DefaultInterfaceImplementations.TryGetValue(type.GetGenericTypeDefinition(), out implementationType)) @@ -100,7 +102,7 @@ public static Type GetDefaultImplementation(Type type) return type; } - public object Create(Type type) + public object? Create(Type type) { type = GetDefaultImplementation(type); diff --git a/src/SharpYaml/Serialization/Descriptors/ArrayDescriptor.cs b/src/SharpYaml/Serialization/Descriptors/ArrayDescriptor.cs index 336e20d5..328de2ab 100644 --- a/src/SharpYaml/Serialization/Descriptors/ArrayDescriptor.cs +++ b/src/SharpYaml/Serialization/Descriptors/ArrayDescriptor.cs @@ -74,7 +74,7 @@ public ArrayDescriptor(IAttributeRegistry attributeRegistry, Type type, IMemberN throw new ArgumentException($"Cannot support dimension [{type.GetArrayRank()}] for type [{type.FullName}]. Only supporting dimension of 1"); } - ElementType = type.GetElementType(); + ElementType = type.GetElementType()!; } public override DescriptorCategory Category { get { return DescriptorCategory.Array; } } diff --git a/src/SharpYaml/Serialization/Descriptors/CollectionDescriptor.cs b/src/SharpYaml/Serialization/Descriptors/CollectionDescriptor.cs index 83601419..945177b6 100644 --- a/src/SharpYaml/Serialization/Descriptors/CollectionDescriptor.cs +++ b/src/SharpYaml/Serialization/Descriptors/CollectionDescriptor.cs @@ -47,6 +47,7 @@ using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; using System.Reflection; namespace SharpYaml.Serialization.Descriptors @@ -58,9 +59,9 @@ public class CollectionDescriptor : ObjectDescriptor { private static readonly List ListOfMembersToRemove = new List { "Capacity", "Count", "IsReadOnly", "IsFixedSize", "IsSynchronized", "SyncRoot", "Comparer" }; - private readonly Func IsReadOnlyFunction; - private readonly Func GetCollectionCountFunction; - private readonly Action CollectionAddFunction; + private readonly Func? IsReadOnlyFunction; + private readonly Func? GetCollectionCountFunction; + private readonly Action? CollectionAddFunction; private readonly bool isKeyedCollection = false; /// @@ -83,7 +84,7 @@ public CollectionDescriptor(IAttributeRegistry attributeRegistry, Type type, boo ElementType = (collectionType != null) ? collectionType.GetGenericArguments()[0] : typeof(object); // implements ICollection - Type itype; + Type? itype; if ((itype = type.GetInterface(typeof(ICollection<>))) != null) { var add = itype.GetMethod("Add", new[] { ElementType }); @@ -128,6 +129,7 @@ public override void Initialize() /// Gets a value indicating whether this collection type has add method. /// /// true if this instance has add; otherwise, false. + [MemberNotNullWhen(true, nameof(CollectionAddFunction))] public bool HasAdd { get { return CollectionAddFunction != null; } } /// @@ -145,7 +147,7 @@ public void CollectionAdd(object collection, object value) /// /// The collection. /// true if the specified collection is read only; otherwise, false. - public bool IsReadOnly(object collection) + public bool IsReadOnly(object? collection) { return collection == null || IsReadOnlyFunction == null || IsReadOnlyFunction(collection); } @@ -155,7 +157,7 @@ public bool IsReadOnly(object collection) /// /// The collection. /// The number of elements of a collection, -1 if it cannot determine the number of elements. - public int GetCollectionCount(object collection) + public int GetCollectionCount(object? collection) { return collection == null || GetCollectionCountFunction == null ? -1 : GetCollectionCountFunction(collection); } diff --git a/src/SharpYaml/Serialization/Descriptors/DefaultKeyComparer.cs b/src/SharpYaml/Serialization/Descriptors/DefaultKeyComparer.cs index d539b99d..7b4dddb7 100644 --- a/src/SharpYaml/Serialization/Descriptors/DefaultKeyComparer.cs +++ b/src/SharpYaml/Serialization/Descriptors/DefaultKeyComparer.cs @@ -38,7 +38,7 @@ namespace SharpYaml.Serialization.Descriptors /// public class DefaultKeyComparer : IComparer { - public virtual int Compare(object x, object y) + public virtual int Compare(object? x, object? y) { if (x is IMemberDescriptor left && y is IMemberDescriptor right) { diff --git a/src/SharpYaml/Serialization/Descriptors/DictionaryDescriptor.cs b/src/SharpYaml/Serialization/Descriptors/DictionaryDescriptor.cs index 6cbf75c8..129f0ac2 100644 --- a/src/SharpYaml/Serialization/Descriptors/DictionaryDescriptor.cs +++ b/src/SharpYaml/Serialization/Descriptors/DictionaryDescriptor.cs @@ -46,6 +46,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; @@ -57,8 +58,8 @@ namespace SharpYaml.Serialization.Descriptors public class DictionaryDescriptor : ObjectDescriptor { private static readonly List ListOfMembersToRemove = new List { "Comparer", "Keys", "Values", "Capacity" }; - private readonly MethodInfo getEnumeratorGeneric; - private readonly MethodInfo addMethod; + private readonly MethodInfo? getEnumeratorGeneric; + private readonly MethodInfo? addMethod; /// /// Initializes a new instance of the class. @@ -107,6 +108,7 @@ public override void Initialize() /// Gets a value indicating whether this instance is generic dictionary. /// /// true if this instance is generic dictionary; otherwise, false. + [MemberNotNullWhen(true, nameof(getEnumeratorGeneric))] public bool IsGenericDictionary { get; } /// @@ -144,13 +146,13 @@ public bool IsReadOnly(object thisObject) /// A generic enumerator. /// dictionary /// Key value-pair [{0}] is not supported for IDictionary. Only DictionaryEntry.DoFormat(keyValueObject) - public IEnumerable> GetEnumerator(object dictionary) + public IEnumerable> GetEnumerator(object dictionary) { if (dictionary == null) throw new ArgumentNullException("dictionary"); if (IsGenericDictionary) { - foreach (var item in (IEnumerable>)getEnumeratorGeneric.Invoke(null, new[] { dictionary })) + foreach (var item in (IEnumerable>?)getEnumeratorGeneric.Invoke(null, new[] { dictionary })) { yield return item; } @@ -166,7 +168,7 @@ public IEnumerable> GetEnumerator(object dictionary } else { - yield return new KeyValuePair(entry.Key, entry.Value); + yield return new KeyValuePair(entry.Key, entry.Value); } } } @@ -179,7 +181,7 @@ public IEnumerable> GetEnumerator(object dictionary /// The key. /// The value. /// No Add() method found on dictionary [] - public void AddToDictionary(object dictionary, object key, object value) + public void AddToDictionary(object dictionary, object key, object? value) { if (dictionary == null) throw new ArgumentNullException("dictionary"); @@ -208,9 +210,10 @@ public static bool IsDictionary(Type type) return typeof(IDictionary).IsAssignableFrom(type) || type.HasInterface(typeof(IDictionary<,>)); } - public static IEnumerable> GetGenericEnumerable(IDictionary dictionary) + public static IEnumerable> GetGenericEnumerable(IDictionary dictionary) + where TKey : notnull { - return dictionary.Select(keyValue => new KeyValuePair(keyValue.Key, keyValue.Value)); + return dictionary.Select(keyValue => new KeyValuePair(keyValue.Key, keyValue.Value)); } protected override bool PrepareMember(MemberDescriptorBase member) diff --git a/src/SharpYaml/Serialization/Descriptors/MemberDescriptorBase.cs b/src/SharpYaml/Serialization/Descriptors/MemberDescriptorBase.cs index cc54e8c3..e9bd112a 100644 --- a/src/SharpYaml/Serialization/Descriptors/MemberDescriptorBase.cs +++ b/src/SharpYaml/Serialization/Descriptors/MemberDescriptorBase.cs @@ -93,11 +93,11 @@ protected MemberDescriptorBase(MemberInfo memberInfo, StringComparer defaultName public abstract bool IsPublic { get; } public uint Mask { get; internal set; } public YamlStyle Style { get; internal set; } - public Func ShouldSerialize { get; internal set; } + public Func ShouldSerialize { get; internal set; } - public List AlternativeNames { get; set; } + public List? AlternativeNames { get; set; } - public object Tag { get; set; } + public object? Tag { get; set; } /// /// Gets the member information. diff --git a/src/SharpYaml/Serialization/Descriptors/ObjectDescriptor.cs b/src/SharpYaml/Serialization/Descriptors/ObjectDescriptor.cs index fa977517..8591b5e3 100644 --- a/src/SharpYaml/Serialization/Descriptors/ObjectDescriptor.cs +++ b/src/SharpYaml/Serialization/Descriptors/ObjectDescriptor.cs @@ -47,6 +47,7 @@ using System.Collections; using System.Collections.Generic; using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; @@ -58,17 +59,17 @@ namespace SharpYaml.Serialization.Descriptors /// public class ObjectDescriptor : ITypeDescriptor { - public static readonly Func ShouldSerializeDefault = o => true; + public static readonly Func ShouldSerializeDefault = o => true; protected static readonly string SystemCollectionsNamespace = typeof(int).Namespace; private static readonly object[] EmptyObjectArray = Array.Empty(); - private List members; - private Dictionary mapMembers; + private List? members; + private Dictionary? mapMembers; private readonly bool emitDefaultValues; private readonly bool respectPrivateSetters; private bool isSorted; - private HashSet remapMembers; + private HashSet? remapMembers; /// /// Initializes a new instance of the class. @@ -127,6 +128,7 @@ public ObjectDescriptor(IAttributeRegistry attributeRegistry, Type type, bool em /// Initializes this instance. /// /// Failed to get ObjectDescriptor for type []. The member [{1}] cannot be registered as a member with the same name is already registered [{2}].DoFormat(type.FullName, member, existingMember) + [MemberNotNull(nameof(members))] public virtual void Initialize() { if (members != null) @@ -179,7 +181,7 @@ public virtual void Initialize() public Type Type { get; } - public IEnumerable Members { get { return members; } } + public IEnumerable? Members => members; public int Count { get { return members == null ? 0 : members.Count; } } @@ -202,7 +204,7 @@ public void SortMembers(IComparer keyComparer) } } - public IMemberDescriptor this[string name] + public IMemberDescriptor? this[string name] { get { @@ -269,9 +271,9 @@ protected virtual bool PrepareMember(MemberDescriptorBase member) // Process all attributes just once instead of getting them one by one var attributes = AttributeRegistry.GetAttributes(member.MemberInfo); - YamlStyleAttribute styleAttribute = null; - YamlMemberAttribute memberAttribute = null; - DefaultValueAttribute defaultValueAttribute = null; + YamlStyleAttribute? styleAttribute = null; + YamlMemberAttribute? memberAttribute = null; + DefaultValueAttribute? defaultValueAttribute = null; foreach (var attribute in attributes) { // Member is not displayed if there is a YamlIgnore attribute on it diff --git a/src/SharpYaml/Serialization/Descriptors/PrimitiveDescriptor.cs b/src/SharpYaml/Serialization/Descriptors/PrimitiveDescriptor.cs index c2fed86c..9296bf1b 100644 --- a/src/SharpYaml/Serialization/Descriptors/PrimitiveDescriptor.cs +++ b/src/SharpYaml/Serialization/Descriptors/PrimitiveDescriptor.cs @@ -56,7 +56,7 @@ public class PrimitiveDescriptor : ObjectDescriptor { private static readonly List EmptyMembers = new List(); - private readonly Dictionary enumRemap; + private readonly Dictionary? enumRemap; /// /// Initializes a new instance of the class. diff --git a/src/SharpYaml/Serialization/Descriptors/PropertyDescriptor.cs b/src/SharpYaml/Serialization/Descriptors/PropertyDescriptor.cs index 468b4583..09da31ea 100644 --- a/src/SharpYaml/Serialization/Descriptors/PropertyDescriptor.cs +++ b/src/SharpYaml/Serialization/Descriptors/PropertyDescriptor.cs @@ -44,6 +44,7 @@ // SOFTWARE. using System; +using System.Diagnostics.CodeAnalysis; using System.Reflection; namespace SharpYaml.Serialization.Descriptors @@ -54,7 +55,7 @@ namespace SharpYaml.Serialization.Descriptors public class PropertyDescriptor : MemberDescriptorBase { private readonly MethodInfo getMethod; - private readonly MethodInfo setMethod; + private readonly MethodInfo? setMethod; /// /// Initializes a new instance of the class. @@ -97,6 +98,7 @@ public override void Set(object thisObject, object value) setMethod.Invoke(thisObject, new[] { value }); } + [MemberNotNullWhen(true, nameof(setMethod))] public override bool HasSet { get { return setMethod != null; } } public override bool IsPublic { get { return getMethod.IsPublic; } } diff --git a/src/SharpYaml/Serialization/Descriptors/TypeDescriptorFactory.cs b/src/SharpYaml/Serialization/Descriptors/TypeDescriptorFactory.cs index a99e7edb..006cffbe 100644 --- a/src/SharpYaml/Serialization/Descriptors/TypeDescriptorFactory.cs +++ b/src/SharpYaml/Serialization/Descriptors/TypeDescriptorFactory.cs @@ -45,6 +45,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; namespace SharpYaml.Serialization.Descriptors { @@ -78,7 +79,8 @@ public TypeDescriptorFactory(IAttributeRegistry attributeRegistry, bool emitDefa this.AttributeRegistry = attributeRegistry; } - public ITypeDescriptor Find(Type type, IComparer memberComparer) + [return: NotNullIfNotNull("type")] + public ITypeDescriptor? Find(Type? type, IComparer memberComparer) { if (type == null) return null; diff --git a/src/SharpYaml/Serialization/DocumentLoadingState.cs b/src/SharpYaml/Serialization/DocumentLoadingState.cs index d387035d..abde9079 100644 --- a/src/SharpYaml/Serialization/DocumentLoadingState.cs +++ b/src/SharpYaml/Serialization/DocumentLoadingState.cs @@ -45,6 +45,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using SharpYaml; @@ -85,7 +86,7 @@ public void AddAnchor(YamlNode node) /// The start position. /// The end position. /// - public YamlNode GetNode(string anchor, bool throwException, Mark start, Mark end) + public YamlNode? GetNode(string anchor, [DoesNotReturnIf(true)] bool throwException, Mark start, Mark end) { if (anchors.TryGetValue(anchor, out var target)) { diff --git a/src/SharpYaml/Serialization/DynamicMemberDescriptorBase.cs b/src/SharpYaml/Serialization/DynamicMemberDescriptorBase.cs index 0ea3f490..6dd8c9c8 100644 --- a/src/SharpYaml/Serialization/DynamicMemberDescriptorBase.cs +++ b/src/SharpYaml/Serialization/DynamicMemberDescriptorBase.cs @@ -67,10 +67,10 @@ protected DynamicMemberDescriptorBase(string name, Type type) public YamlStyle Style { get; set; } - public Func ShouldSerialize { get; set; } + public Func ShouldSerialize { get; set; } - public List AlternativeNames { get; set; } + public List? AlternativeNames { get; set; } - public object Tag { get; set; } + public object? Tag { get; set; } } } diff --git a/src/SharpYaml/Serialization/EventInfo.cs b/src/SharpYaml/Serialization/EventInfo.cs index bdc06e4f..5220c6c7 100644 --- a/src/SharpYaml/Serialization/EventInfo.cs +++ b/src/SharpYaml/Serialization/EventInfo.cs @@ -50,10 +50,10 @@ namespace SharpYaml.Serialization { public abstract class EventInfo { - public object SourceValue { get; } + public object? SourceValue { get; } public Type SourceType { get; } - protected EventInfo(object sourceValue, Type sourceType) + protected EventInfo(object? sourceValue, Type sourceType) { SourceValue = sourceValue; SourceType = sourceType; @@ -72,18 +72,18 @@ public AliasEventInfo(object sourceValue, Type sourceType) public class ObjectEventInfo : EventInfo { - protected ObjectEventInfo(object sourceValue, Type sourceType) + protected ObjectEventInfo(object? sourceValue, Type sourceType) : base(sourceValue, sourceType) { } - public string Anchor { get; set; } - public string Tag { get; set; } + public string? Anchor { get; set; } + public string? Tag { get; set; } } public sealed class ScalarEventInfo : ObjectEventInfo { - public ScalarEventInfo(object sourceValue, Type sourceType) + public ScalarEventInfo(object? sourceValue, Type sourceType) : base(sourceValue, sourceType) { } diff --git a/src/SharpYaml/Serialization/IAttributeRegistry.cs b/src/SharpYaml/Serialization/IAttributeRegistry.cs index e08c355a..c8bd74f7 100644 --- a/src/SharpYaml/Serialization/IAttributeRegistry.cs +++ b/src/SharpYaml/Serialization/IAttributeRegistry.cs @@ -60,7 +60,7 @@ public interface IAttributeRegistry /// Gets or sets the attribute remapper. May be null /// /// The remap attribute. - Func AttributeRemap { get; set; } + Func? AttributeRemap { get; set; } /// /// Gets the attributes associated with the specified member. @@ -73,7 +73,7 @@ public interface IAttributeRegistry /// /// Gets or sets the prepare member callback. /// - Action> PrepareMembersCallback { get; set; } + Action>? PrepareMembersCallback { get; set; } /// /// Registers an attribute for the specified member. Restriction: Attributes registered this way cannot be listed in inherited attributes. @@ -109,7 +109,7 @@ public static IEnumerable GetAttributes(this IAttributeRegistry attributeR /// The member information. /// if set to true [inherit]. /// An attribute of type {T} if it was found; otherwise null - public static T GetAttribute(this IAttributeRegistry attributeRegistry, MemberInfo memberInfo, bool inherit = true) where T : Attribute + public static T? GetAttribute(this IAttributeRegistry attributeRegistry, MemberInfo memberInfo, bool inherit = true) where T : Attribute { return attributeRegistry.GetAttributes(memberInfo, inherit).OfType().FirstOrDefault(); } diff --git a/src/SharpYaml/Serialization/IMemberDescriptor.cs b/src/SharpYaml/Serialization/IMemberDescriptor.cs index 4ee6f4c6..a4e7a1fe 100644 --- a/src/SharpYaml/Serialization/IMemberDescriptor.cs +++ b/src/SharpYaml/Serialization/IMemberDescriptor.cs @@ -137,18 +137,18 @@ public interface IMemberDescriptor /// Gets a value indicating whether this member should be serialized. /// /// true if [should serialize]; otherwise, false. - Func ShouldSerialize { get; } + Func ShouldSerialize { get; } /// /// Gets the alternative names that will map back to this member (may be null). /// /// The alternative names that will map back to this member (may be null). - List AlternativeNames { get; } + List? AlternativeNames { get; } /// /// Gets or sets a custom tag to associate with this object. /// /// A custom tag object. - object Tag { get; set; } + object? Tag { get; set; } } } diff --git a/src/SharpYaml/Serialization/IObjectFactory.cs b/src/SharpYaml/Serialization/IObjectFactory.cs index a27dd121..ff0784fe 100644 --- a/src/SharpYaml/Serialization/IObjectFactory.cs +++ b/src/SharpYaml/Serialization/IObjectFactory.cs @@ -58,6 +58,6 @@ public interface IObjectFactory /// /// Creates an instance of the specified type. Returns null if instance cannot be created. /// - object Create(Type type); + object? Create(Type type); } } diff --git a/src/SharpYaml/Serialization/IObjectSerializerBackend.cs b/src/SharpYaml/Serialization/IObjectSerializerBackend.cs index 00daef59..8fac56b5 100644 --- a/src/SharpYaml/Serialization/IObjectSerializerBackend.cs +++ b/src/SharpYaml/Serialization/IObjectSerializerBackend.cs @@ -61,7 +61,7 @@ public interface IObjectSerializerBackend /// /// TODO: Explain memberValue when can be not null /// - object ReadMemberValue(ref ObjectContext objectContext, IMemberDescriptor member, object memberValue, Type memberType); + object? ReadMemberValue(ref ObjectContext objectContext, IMemberDescriptor? member, object? memberValue, Type memberType); /// /// Reads the collection item from the current YAML stream. @@ -71,7 +71,7 @@ public interface IObjectSerializerBackend /// Type of the item. /// /// The collection item read from YAML stream. - object ReadCollectionItem(ref ObjectContext objectContext, object value, Type itemType, int index); + object? ReadCollectionItem(ref ObjectContext objectContext, object? value, Type itemType, int index); /// /// Reads the dictionary item from the current YAML stream. @@ -79,7 +79,7 @@ public interface IObjectSerializerBackend /// The object context. /// Type of the key value. /// The dictionary item (key,value) read from YAML stream. - KeyValuePair ReadDictionaryItem(ref ObjectContext objectContext, KeyValuePair keyValueType); + KeyValuePair ReadDictionaryItem(ref ObjectContext objectContext, KeyValuePair keyValueType); /// /// Writes the name of the member. @@ -87,7 +87,7 @@ public interface IObjectSerializerBackend /// The object context. /// The member. /// Name of the member. - void WriteMemberName(ref ObjectContext objectContext, IMemberDescriptor member, string memberName); + void WriteMemberName(ref ObjectContext objectContext, IMemberDescriptor? member, string memberName); /// /// Writes the member value. @@ -96,7 +96,7 @@ public interface IObjectSerializerBackend /// The member. /// The member value. /// Type of the member. - void WriteMemberValue(ref ObjectContext objectContext, IMemberDescriptor member, object memberValue, Type memberType); + void WriteMemberValue(ref ObjectContext objectContext, IMemberDescriptor member, object? memberValue, Type memberType); /// /// Writes the collection item. @@ -113,6 +113,6 @@ public interface IObjectSerializerBackend /// The object context. /// The key value. /// The types. - void WriteDictionaryItem(ref ObjectContext objectContext, KeyValuePair keyValue, KeyValuePair types); + void WriteDictionaryItem(ref ObjectContext objectContext, KeyValuePair keyValue, KeyValuePair types); } } diff --git a/src/SharpYaml/Serialization/ITagTypeResolver.cs b/src/SharpYaml/Serialization/ITagTypeResolver.cs index ed475068..6d1d51a4 100644 --- a/src/SharpYaml/Serialization/ITagTypeResolver.cs +++ b/src/SharpYaml/Serialization/ITagTypeResolver.cs @@ -13,7 +13,7 @@ public interface ITagTypeResolver /// Name of the tag. /// /// A Type or null if not found - Type TypeFromTag(string tagName, out bool isAlias); + Type? TypeFromTag(string? tagName, out bool isAlias); /// /// Finds a tag from a type, null if not found. @@ -27,6 +27,6 @@ public interface ITagTypeResolver /// /// Name of the type. /// Type found for this typeName - Type ResolveType(string typeName); + Type? ResolveType(string typeName); } } diff --git a/src/SharpYaml/Serialization/ITypeDescriptor.cs b/src/SharpYaml/Serialization/ITypeDescriptor.cs index 1b5e4160..c34897fc 100644 --- a/src/SharpYaml/Serialization/ITypeDescriptor.cs +++ b/src/SharpYaml/Serialization/ITypeDescriptor.cs @@ -63,7 +63,7 @@ public interface ITypeDescriptor /// Gets the members of this type. /// /// The members. - IEnumerable Members { get; } + IEnumerable? Members { get; } /// /// Gets the member count. @@ -88,7 +88,7 @@ public interface ITypeDescriptor /// /// The name. /// The member. - IMemberDescriptor this[string name] { get; } + IMemberDescriptor? this[string name] { get; } /// /// Determines whether the named member is remmaped. diff --git a/src/SharpYaml/Serialization/ITypeDescriptorFactory.cs b/src/SharpYaml/Serialization/ITypeDescriptorFactory.cs index 51e8db0d..aeb480ee 100644 --- a/src/SharpYaml/Serialization/ITypeDescriptorFactory.cs +++ b/src/SharpYaml/Serialization/ITypeDescriptorFactory.cs @@ -45,6 +45,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; namespace SharpYaml.Serialization { @@ -59,6 +60,7 @@ internal interface ITypeDescriptorFactory /// The type. /// /// ITypeDescriptor. - ITypeDescriptor Find(Type type, IComparer memberComparer); + [return: NotNullIfNotNull("type")] + ITypeDescriptor? Find(Type? type, IComparer memberComparer); } } diff --git a/src/SharpYaml/Serialization/IYamlSerializable.cs b/src/SharpYaml/Serialization/IYamlSerializable.cs index 8e3fc690..cea6a38c 100644 --- a/src/SharpYaml/Serialization/IYamlSerializable.cs +++ b/src/SharpYaml/Serialization/IYamlSerializable.cs @@ -55,7 +55,7 @@ public interface IYamlSerializable /// /// /// A instance of the object deserialized from Yaml. - object ReadYaml(ref ObjectContext objectContext); + object? ReadYaml(ref ObjectContext objectContext); /// /// Writes the specified object context to a YAML emitter. diff --git a/src/SharpYaml/Serialization/IYamlSerializableFactory.cs b/src/SharpYaml/Serialization/IYamlSerializableFactory.cs index f31aa434..d3b9ba4f 100644 --- a/src/SharpYaml/Serialization/IYamlSerializableFactory.cs +++ b/src/SharpYaml/Serialization/IYamlSerializableFactory.cs @@ -58,6 +58,6 @@ public interface IYamlSerializableFactory /// /// The typeDescriptor. /// If supported, return an instance of else return null. - IYamlSerializable TryCreate(SerializerContext context, ITypeDescriptor typeDescriptor); + IYamlSerializable? TryCreate(SerializerContext context, ITypeDescriptor typeDescriptor); } } diff --git a/src/SharpYaml/Serialization/IdentityEqualityComparer.cs b/src/SharpYaml/Serialization/IdentityEqualityComparer.cs index 145c5f08..5485a978 100644 --- a/src/SharpYaml/Serialization/IdentityEqualityComparer.cs +++ b/src/SharpYaml/Serialization/IdentityEqualityComparer.cs @@ -50,7 +50,7 @@ namespace SharpYaml.Serialization { internal class IdentityEqualityComparer : IEqualityComparer where T : class { - public bool Equals(T left, T right) + public bool Equals(T? left, T? right) { return ReferenceEquals(left, right); } diff --git a/src/SharpYaml/Serialization/LambdaObjectFactory.cs b/src/SharpYaml/Serialization/LambdaObjectFactory.cs index 0a2589d2..d770df41 100644 --- a/src/SharpYaml/Serialization/LambdaObjectFactory.cs +++ b/src/SharpYaml/Serialization/LambdaObjectFactory.cs @@ -68,7 +68,7 @@ public LambdaObjectFactory(Func factory) : this(factory, null) /// The factory. /// The next factory. /// factory - public LambdaObjectFactory(Func factory, IObjectFactory nextFactory) : base(nextFactory) + public LambdaObjectFactory(Func factory, IObjectFactory? nextFactory) : base(nextFactory) { if (factory == null) { @@ -78,7 +78,7 @@ public LambdaObjectFactory(Func factory, IObjectFactory nextFactor this.factory = factory; } - public override object Create(Type type) + public override object? Create(Type type) { return factory(type) ?? base.Create(type); } diff --git a/src/SharpYaml/Serialization/ObjectContext.cs b/src/SharpYaml/Serialization/ObjectContext.cs index 21e8ce9f..685b7956 100644 --- a/src/SharpYaml/Serialization/ObjectContext.cs +++ b/src/SharpYaml/Serialization/ObjectContext.cs @@ -37,7 +37,7 @@ public struct ObjectContext /// The serializer context. /// The instance. /// The descriptor. - public ObjectContext(SerializerContext serializerContext, object instance, ITypeDescriptor descriptor) : this() + public ObjectContext(SerializerContext serializerContext, object? instance, ITypeDescriptor descriptor) : this() { SerializerContext = serializerContext; Instance = instance; @@ -53,13 +53,13 @@ public ObjectContext(SerializerContext serializerContext, object instance, IType /// Gets the current YAML reader. Equivalent to calling directly . /// /// The current YAML reader. - public EventReader Reader { get { return SerializerContext.Reader; } } + public EventReader? Reader { get { return SerializerContext.Reader; } } /// /// Gets the writer used while deserializing. Equivalent to calling directly . /// /// The writer. - public IEventEmitter Writer { get { return SerializerContext.Writer; } } + public IEventEmitter? Writer { get { return SerializerContext.Writer; } } /// /// Gets the settings. Equivalent to calling directly . @@ -76,7 +76,7 @@ public ObjectContext(SerializerContext serializerContext, object instance, IType /// /// The instance link to this context. /// - public object Instance { get; set; } + public object? Instance { get; set; } /// /// The expected type descriptor. @@ -86,12 +86,12 @@ public ObjectContext(SerializerContext serializerContext, object instance, IType /// /// The tag used when serializing. /// - public string Tag { get; set; } + public string? Tag { get; set; } /// /// The anchor used when serializing. /// - public string Anchor { get; set; } + public string? Anchor { get; set; } /// /// The style used when serializing. diff --git a/src/SharpYaml/Serialization/OrderedDictionary.cs b/src/SharpYaml/Serialization/OrderedDictionary.cs index 607d8a0c..1e49f926 100644 --- a/src/SharpYaml/Serialization/OrderedDictionary.cs +++ b/src/SharpYaml/Serialization/OrderedDictionary.cs @@ -46,11 +46,13 @@ using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; using System.Linq; namespace SharpYaml.Serialization { class OrderedDictionary : IOrderedDictionary, IList> + where TKey : notnull { private readonly KeyedCollection items = new KeyedCollection(); @@ -108,7 +110,7 @@ public bool Remove(TKey key) return items.Remove(key); } - public bool TryGetValue(TKey key, out TValue value) + public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) { if (!items.Contains(key)) { diff --git a/src/SharpYaml/Serialization/Serializer.cs b/src/SharpYaml/Serialization/Serializer.cs index 16bb29bf..1a75abc3 100644 --- a/src/SharpYaml/Serialization/Serializer.cs +++ b/src/SharpYaml/Serialization/Serializer.cs @@ -80,7 +80,7 @@ public Serializer() : this(null) /// Initializes a new instance of the class. /// /// The settings. - public Serializer(SerializerSettings settings) + public Serializer(SerializerSettings? settings) { this.Settings = settings ?? new SerializerSettings(); TypeDescriptorFactory = CreateTypeDescriptorFactory(); @@ -99,7 +99,7 @@ public Serializer(SerializerSettings settings) /// /// The graph. /// A YAML string of the object. - public string Serialize(object graph) + public string Serialize(object? graph) { var stringWriter = new StringWriter(); Serialize(stringWriter, graph); @@ -113,7 +113,7 @@ public string Serialize(object graph) /// The expected type. /// The context settings. /// A YAML string of the object. - public string Serialize(object graph, Type expectedType, SerializerContextSettings contextSettings = null) + public string Serialize(object? graph, Type expectedType, SerializerContextSettings? contextSettings = null) { var stringWriter = new StringWriter(); Serialize(stringWriter, graph, expectedType, contextSettings); @@ -125,7 +125,7 @@ public string Serialize(object graph, Type expectedType, SerializerContextSettin /// /// The stream. /// The object to serialize. - public void Serialize(Stream stream, object graph) + public void Serialize(Stream stream, object? graph) { Serialize(stream, graph, null); } @@ -137,7 +137,7 @@ public void Serialize(Stream stream, object graph) /// The object to serialize. /// The static type of the object to serialize. /// The context settings. - public void Serialize(Stream stream, object graph, Type expectedType, SerializerContextSettings contextSettings = null) + public void Serialize(Stream stream, object? graph, Type? expectedType, SerializerContextSettings? contextSettings = null) { var writer = new StreamWriter(stream); try @@ -161,7 +161,7 @@ public void Serialize(Stream stream, object graph, Type expectedType, Serializer /// /// The where to serialize the object. /// The object to serialize. - public void Serialize(TextWriter writer, object graph) + public void Serialize(TextWriter writer, object? graph) { Serialize(new Emitter(writer, Settings.PreferredIndent, emitKeyQuoted: Settings.EmitJsonComptible), graph); } @@ -173,7 +173,7 @@ public void Serialize(TextWriter writer, object graph) /// The object to serialize. /// The static type of the object to serialize. /// The context settings. - public void Serialize(TextWriter writer, object graph, Type type, SerializerContextSettings contextSettings = null) + public void Serialize(TextWriter writer, object? graph, Type? type, SerializerContextSettings? contextSettings = null) { Serialize(new Emitter(writer, Settings.PreferredIndent, emitKeyQuoted: Settings.EmitJsonComptible), graph, type, contextSettings); } @@ -183,7 +183,7 @@ public void Serialize(TextWriter writer, object graph, Type type, SerializerCont /// /// The where to serialize the object. /// The object to serialize. - public void Serialize(IEmitter emitter, object graph) + public void Serialize(IEmitter emitter, object? graph) { Serialize(emitter, graph, graph == null ? typeof(object) : null); } @@ -195,7 +195,7 @@ public void Serialize(IEmitter emitter, object graph) /// The object to serialize. /// The static type of the object to serialize. /// The context settings. - public void Serialize(IEmitter emitter, object graph, Type type, SerializerContextSettings contextSettings = null) + public void Serialize(IEmitter emitter, object? graph, Type? type, SerializerContextSettings? contextSettings = null) { if (emitter == null) { @@ -230,7 +230,7 @@ public void Serialize(IEmitter emitter, object graph, Type type, SerializerConte /// /// The stream. /// A deserialized object. - public object Deserialize(Stream stream) + public object? Deserialize(Stream stream) { return Deserialize(stream, null); } @@ -240,7 +240,7 @@ public object Deserialize(Stream stream) /// /// The reader. /// A deserialized object. - public object Deserialize(TextReader reader) + public object? Deserialize(TextReader reader) { return Deserialize((TextReader)reader, null); } @@ -253,7 +253,7 @@ public object Deserialize(TextReader reader) /// The context settings. /// A deserialized object. /// stream - public object Deserialize(Stream stream, Type expectedType, SerializerContextSettings contextSettings = null) + public object? Deserialize(Stream stream, Type? expectedType, SerializerContextSettings? contextSettings = null) { if (stream == null) throw new ArgumentNullException("stream"); @@ -270,7 +270,7 @@ public object Deserialize(Stream stream, Type expectedType, SerializerContextSet /// The context used to deserialize this object. /// A deserialized object. /// stream - public object Deserialize(Stream stream, Type expectedType, SerializerContextSettings contextSettings, out SerializerContext context) + public object? Deserialize(Stream stream, Type expectedType, SerializerContextSettings contextSettings, out SerializerContext? context) { if (stream == null) throw new ArgumentNullException("stream"); @@ -285,9 +285,9 @@ public object Deserialize(Stream stream, Type expectedType, SerializerContextSet /// The stream. /// A deserialized object. /// stream - public T Deserialize(Stream stream) + public T? Deserialize(Stream stream) { - return (T)Deserialize(stream, typeof(T)); + return (T?)Deserialize(stream, typeof(T)); } /// @@ -299,7 +299,7 @@ public T Deserialize(Stream stream) /// The context settings. /// A deserialized object. /// reader - public object Deserialize(TextReader reader, Type expectedType, object existingObject = null, SerializerContextSettings contextSettings = null) + public object? Deserialize(TextReader reader, Type? expectedType, object? existingObject = null, SerializerContextSettings? contextSettings = null) { if (reader == null) throw new ArgumentNullException("reader"); @@ -316,7 +316,7 @@ public object Deserialize(TextReader reader, Type expectedType, object existingO /// The context used to deserialize this object. /// A deserialized object. /// reader - public object Deserialize(TextReader reader, Type expectedType, object existingObject, SerializerContextSettings contextSettings, out SerializerContext context) + public object? Deserialize(TextReader reader, Type expectedType, object? existingObject, SerializerContextSettings? contextSettings, out SerializerContext? context) { if (reader == null) throw new ArgumentNullException("reader"); @@ -331,9 +331,9 @@ public object Deserialize(TextReader reader, Type expectedType, object existingO /// The object to deserialize into. If null (the default) then a new object will be created /// A deserialized object. /// reader - public T Deserialize(TextReader reader, object existingObject = null) + public T? Deserialize(TextReader reader, object? existingObject = null) { - return (T)Deserialize(reader, typeof(T), existingObject); + return (T?)Deserialize(reader, typeof(T), existingObject); } /// @@ -342,7 +342,7 @@ public T Deserialize(TextReader reader, object existingObject = null) /// The text. /// The object to deserialize into. If null (the default) then a new object will be created /// A deserialized object. - public object Deserialize(string fromText, object existingObject = null) + public object? Deserialize(string fromText, object? existingObject = null) { return Deserialize(fromText, null, existingObject); } @@ -355,7 +355,7 @@ public object Deserialize(string fromText, object existingObject = null) /// The object to deserialize into. If null (the default) then a new object will be created /// A deserialized object. /// stream - public object Deserialize(string fromText, Type expectedType, object existingObject = null) + public object? Deserialize(string fromText, Type? expectedType, object? existingObject = null) { if (fromText == null) throw new ArgumentNullException("fromText"); @@ -371,7 +371,7 @@ public object Deserialize(string fromText, Type expectedType, object existingObj /// The context used to deserialize this object. /// A deserialized object. /// stream - public object Deserialize(string fromText, Type expectedType, object existingObject, out SerializerContext context) + public object? Deserialize(string fromText, Type expectedType, object? existingObject, out SerializerContext? context) { if (fromText == null) throw new ArgumentNullException("fromText"); @@ -385,9 +385,9 @@ public object Deserialize(string fromText, Type expectedType, object existingObj /// From text. /// A deserialized object. /// stream - public T Deserialize(string fromText) + public T? Deserialize(string fromText) { - return (T)Deserialize(fromText, typeof(T)); + return (T?)Deserialize(fromText, typeof(T)); } /// @@ -397,9 +397,9 @@ public T Deserialize(string fromText) /// The reader. /// A deserialized object. /// reader - public T Deserialize(EventReader reader) + public T? Deserialize(EventReader reader) { - return (T)Deserialize(reader, typeof(T)); + return (T?)Deserialize(reader, typeof(T)); } /// @@ -412,9 +412,9 @@ public T Deserialize(EventReader reader) /// stream /// /// Note: These need a different name, because otherwise they will conflict with existing Deserialize(string,Type). They are new so the difference should not matter - public T DeserializeInto(string fromText, T existingObject) + public T? DeserializeInto(string fromText, T existingObject) { - return (T)Deserialize(fromText, typeof(T), existingObject); + return (T?)Deserialize(fromText, typeof(T), existingObject); } /// @@ -425,9 +425,9 @@ public T DeserializeInto(string fromText, T existingObject) /// The object to deserialize into. /// A deserialized object. /// reader - public T DeserializeInto(EventReader reader, T existingObject) + public T? DeserializeInto(EventReader reader, T existingObject) { - return (T)Deserialize(reader, typeof(T), existingObject); + return (T?)Deserialize(reader, typeof(T), existingObject); } /// @@ -438,9 +438,9 @@ public T DeserializeInto(EventReader reader, T existingObject) /// The context. /// A deserialized object. /// stream - public T Deserialize(string fromText, out SerializerContext context) + public T? Deserialize(string fromText, out SerializerContext? context) { - return (T)Deserialize(fromText, typeof(T), null, out context); + return (T?)Deserialize(fromText, typeof(T), null, out context); } /// @@ -451,9 +451,9 @@ public T Deserialize(string fromText, out SerializerContext context) /// The context used to deserialize this object. /// A deserialized object. /// reader - public T Deserialize(EventReader reader, out SerializerContext context) + public T? Deserialize(EventReader reader, out SerializerContext? context) { - return (T)Deserialize(reader, typeof(T), null, null, out context); + return (T?)Deserialize(reader, typeof(T), null, null, out context); } /// @@ -466,9 +466,9 @@ public T Deserialize(EventReader reader, out SerializerContext context) /// A deserialized object. /// stream /// Note: These need a different name, because otherwise they will conflict with existing Deserialize(string,Type). They are new so the difference should not matter - public T DeserializeInto(string fromText, T existingObject, out SerializerContext context) + public T? DeserializeInto(string fromText, T existingObject, out SerializerContext? context) { - return (T)Deserialize(fromText, typeof(T), existingObject, out context); + return (T?)Deserialize(fromText, typeof(T), existingObject, out context); } /// @@ -480,9 +480,9 @@ public T DeserializeInto(string fromText, T existingObject, out SerializerCon /// The context used to deserialize this object. /// A deserialized object. /// reader - public T DeserializeInto(EventReader reader, T existingObject, out SerializerContext context) + public T? DeserializeInto(EventReader reader, T existingObject, out SerializerContext? context) { - return (T)Deserialize(reader, typeof(T), existingObject, null, out context); + return (T?)Deserialize(reader, typeof(T), existingObject, null, out context); } /// @@ -494,7 +494,7 @@ public T DeserializeInto(EventReader reader, T existingObject, out Serializer /// The context settings. /// A deserialized object. /// reader - public object Deserialize(EventReader reader, Type expectedType, object existingObject = null, SerializerContextSettings contextSettings = null) + public object? Deserialize(EventReader reader, Type? expectedType, object? existingObject = null, SerializerContextSettings? contextSettings = null) { return Deserialize(reader, expectedType, existingObject, contextSettings, out var context); } @@ -509,7 +509,7 @@ public object Deserialize(EventReader reader, Type expectedType, object existing /// The context used to deserialize the object. /// A deserialized object. /// reader - public object Deserialize(EventReader reader, Type expectedType, object existingObject, SerializerContextSettings contextSettings, out SerializerContext context) + public object? Deserialize(EventReader reader, Type? expectedType, object? existingObject, SerializerContextSettings? contextSettings, out SerializerContext? context) { if (reader == null) throw new ArgumentNullException("reader"); @@ -518,7 +518,7 @@ public object Deserialize(EventReader reader, Type expectedType, object existing var hasDocumentStart = reader.Allow() != null; context = null; - object result = null; + object? result = null; if (!reader.Accept() && !reader.Accept()) { context = new SerializerContext(this, contextSettings) { Reader = reader }; diff --git a/src/SharpYaml/Serialization/SerializerContext.cs b/src/SharpYaml/Serialization/SerializerContext.cs index 795bbddc..081a8f0c 100644 --- a/src/SharpYaml/Serialization/SerializerContext.cs +++ b/src/SharpYaml/Serialization/SerializerContext.cs @@ -44,6 +44,7 @@ // SOFTWARE. using System; +using System.Diagnostics.CodeAnalysis; using SharpYaml.Events; using SharpYaml.Schemas; using SharpYaml.Serialization.Descriptors; @@ -64,7 +65,7 @@ public class SerializerContext : ITagTypeResolver /// /// The serializer. /// The serializer context settings. - internal SerializerContext(Serializer serializer, SerializerContextSettings serializerContextSettings) + internal SerializerContext(Serializer serializer, SerializerContextSettings? serializerContextSettings) { Serializer = serializer; Settings = serializer.Settings; @@ -113,7 +114,7 @@ internal SerializerContext(Serializer serializer, SerializerContextSettings seri /// Gets or sets the reader used while deserializing. /// /// The reader. - public EventReader Reader { get; set; } + public EventReader? Reader { get; set; } /// /// Gets the object serializer backend. @@ -151,7 +152,7 @@ internal SerializerContext(Serializer serializer, SerializerContextSettings seri /// The value of the receiving object, may be null. /// The expected type. /// System.Object. - public object ReadYaml(object value, Type expectedType) + public object? ReadYaml(object? value, Type? expectedType) { var node = Reader.Parser.Current; try @@ -179,18 +180,18 @@ public object ReadYaml(object value, Type expectedType) /// Gets or sets the writer used while deserializing. /// /// The writer. - public IEventEmitter Writer { get; set; } + public IEventEmitter? Writer { get; set; } /// /// Gets the emitter. /// /// The emitter. - public IEmitter Emitter { get; internal set; } + public IEmitter? Emitter { get; internal init; } /// /// The default function to write an object to Yaml /// - public void WriteYaml(object value, Type expectedType, YamlStyle style = YamlStyle.Any) + public void WriteYaml(object? value, Type? expectedType, YamlStyle style = YamlStyle.Any) { var objectContext = new ObjectContext(this, value, FindTypeDescriptor(expectedType)) { Style = style }; ObjectSerializer.WriteYaml(ref objectContext); @@ -201,7 +202,8 @@ public void WriteYaml(object value, Type expectedType, YamlStyle style = YamlSty /// /// The type. /// An instance of . - public ITypeDescriptor FindTypeDescriptor(Type type) + [return: NotNullIfNotNull("type")] + public ITypeDescriptor? FindTypeDescriptor(Type? type) { return typeDescriptorFactory.Find(type, Settings.ComparerForKeySorting); } @@ -212,7 +214,8 @@ public ITypeDescriptor FindTypeDescriptor(Type type) /// Name of the tag. /// /// Type. - public Type TypeFromTag(string tagName, out bool isAlias) + [return: NotNullIfNotNull("tagName")] + public Type? TypeFromTag(string? tagName, out bool isAlias) { return tagTypeRegistry.TypeFromTag(tagName, out isAlias); } @@ -232,7 +235,7 @@ public string TagFromType(Type type) /// /// Full name of the type. /// The type of null if not found - public Type ResolveType(string typeFullName) + public Type? ResolveType(string typeFullName) { return tagTypeRegistry.ResolveType(typeFullName); } @@ -244,7 +247,7 @@ public Type ResolveType(string typeFullName) /// The default tag decoded from the scalar. /// The value extracted from a scalar. /// System.String. - public bool TryParseScalar(Scalar scalar, out string defaultTag, out object value) + public bool TryParseScalar(Scalar scalar, out string defaultTag, out object? value) { return Settings.Schema.TryParse(scalar, true, out defaultTag, out value); } diff --git a/src/SharpYaml/Serialization/SerializerContextSettings.cs b/src/SharpYaml/Serialization/SerializerContextSettings.cs index 22b2360b..89590629 100644 --- a/src/SharpYaml/Serialization/SerializerContextSettings.cs +++ b/src/SharpYaml/Serialization/SerializerContextSettings.cs @@ -23,7 +23,7 @@ public SerializerContextSettings() /// /// The logger. /// - public ILogger Logger { get; set; } + public ILogger? Logger { get; set; } /// /// Gets or sets the member mask that will be used to filter . diff --git a/src/SharpYaml/Serialization/SerializerSettings.cs b/src/SharpYaml/Serialization/SerializerSettings.cs index 8adf1d40..17424227 100644 --- a/src/SharpYaml/Serialization/SerializerSettings.cs +++ b/src/SharpYaml/Serialization/SerializerSettings.cs @@ -46,6 +46,7 @@ using System; using System.Collections.Generic; using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; using System.Reflection; using SharpYaml.Schemas; using SharpYaml.Serialization.Descriptors; @@ -77,7 +78,7 @@ public SerializerSettings() : this(null) /// /// Initializes a new instance of the class. /// - public SerializerSettings(IYamlSchema schema) + public SerializerSettings(IYamlSchema? schema) { PreferredIndent = 2; IndentLess = false; @@ -220,6 +221,7 @@ public bool EmitJsonComptible public IMemberNamingConvention NamingConvention { get { return _namingConvention; } + [MemberNotNull(nameof(_namingConvention))] set { if (value == null) @@ -262,6 +264,7 @@ public IMemberNamingConvention NamingConvention public string SpecialCollectionMember { get { return specialCollectionMember; } + [MemberNotNull(nameof(specialCollectionMember))] set { if (value == null) @@ -285,6 +288,7 @@ public string SpecialCollectionMember public IAttributeRegistry Attributes { get { return attributeRegistry; } + [MemberNotNull(nameof(attributeRegistry))] set { if (value == null) @@ -300,6 +304,7 @@ public IAttributeRegistry Attributes public IObjectSerializerBackend ObjectSerializerBackend { get { return objectSerializerBackend; } + [MemberNotNull(nameof(objectSerializerBackend))] set { if (value == null) @@ -316,6 +321,7 @@ public IObjectSerializerBackend ObjectSerializerBackend public IObjectFactory ObjectFactory { get { return objectFactory; } + [MemberNotNull(nameof(objectFactory))] set { if (value == null) diff --git a/src/SharpYaml/Serialization/Serializers/AnchorSerializer.cs b/src/SharpYaml/Serialization/Serializers/AnchorSerializer.cs index 25adf675..e8642e57 100644 --- a/src/SharpYaml/Serialization/Serializers/AnchorSerializer.cs +++ b/src/SharpYaml/Serialization/Serializers/AnchorSerializer.cs @@ -45,6 +45,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using SharpYaml.Events; @@ -53,25 +54,25 @@ namespace SharpYaml.Serialization.Serializers { internal class AnchorSerializer : ChainedSerializer { - private readonly Dictionary aliasToObject; + private readonly Dictionary aliasToObject; private readonly Dictionary objectToAlias; public AnchorSerializer(IYamlSerializable next) : base(next) { - aliasToObject = new Dictionary(); + aliasToObject = new Dictionary(); objectToAlias = new Dictionary(new IdentityEqualityComparer()); } - public bool TryGetAliasValue(string alias, out object value) + public bool TryGetAliasValue(string alias, [MaybeNullWhen(false)] out object? value) { return aliasToObject.TryGetValue(alias, out value); } - public override object ReadYaml(ref ObjectContext objectContext) + public override object? ReadYaml(ref ObjectContext objectContext) { var context = objectContext.SerializerContext; var reader = context.Reader; - object value = null; + object? value = null; // Process Anchor alias (*oxxx) var alias = reader.Allow(); @@ -86,7 +87,7 @@ public override object ReadYaml(ref ObjectContext objectContext) } // Test if current node has an anchor &oxxx - string anchor = null; + string? anchor = null; var nodeEvent = reader.Peek(); if (nodeEvent != null && !string.IsNullOrEmpty(nodeEvent.Anchor)) { @@ -125,15 +126,15 @@ public override void WriteYaml(ref ObjectContext objectContext) if (isAnchorable) { - if (objectToAlias.TryGetValue(value, out var alias)) + if (objectToAlias.TryGetValue(value!, out var alias)) { - objectContext.Writer.Emit(new AliasEventInfo(value, value.GetType()) { Alias = alias }); + objectContext.Writer.Emit(new AliasEventInfo(value!, value!.GetType()) { Alias = alias }); return; } else { alias = FormattableString.Invariant($"o{objectContext.SerializerContext.AnchorCount}"); - objectToAlias.Add(value, alias); + objectToAlias.Add(value!, alias); objectContext.Anchor = alias; objectContext.SerializerContext.AnchorCount++; diff --git a/src/SharpYaml/Serialization/Serializers/ArraySerializer.cs b/src/SharpYaml/Serialization/Serializers/ArraySerializer.cs index 02458022..c56bfe6a 100644 --- a/src/SharpYaml/Serialization/Serializers/ArraySerializer.cs +++ b/src/SharpYaml/Serialization/Serializers/ArraySerializer.cs @@ -52,7 +52,7 @@ namespace SharpYaml.Serialization.Serializers { internal class ArraySerializer : IYamlSerializable, IYamlSerializableFactory { - public IYamlSerializable TryCreate(SerializerContext context, ITypeDescriptor typeDescriptor) + public IYamlSerializable? TryCreate(SerializerContext context, ITypeDescriptor typeDescriptor) { return typeDescriptor is ArrayDescriptor ? this : null; } @@ -63,7 +63,7 @@ public virtual object ReadYaml(ref ObjectContext objectContext) var arrayDescriptor = (ArrayDescriptor)objectContext.Descriptor; bool isArray = objectContext.Instance != null && objectContext.Instance.GetType().IsArray; - var arrayList = (IList)objectContext.Instance; + var arrayList = (IList)objectContext.Instance!; reader.Expect(); int index = 0; diff --git a/src/SharpYaml/Serialization/Serializers/ChainedSerializer.cs b/src/SharpYaml/Serialization/Serializers/ChainedSerializer.cs index 56daf9f0..e5972151 100644 --- a/src/SharpYaml/Serialization/Serializers/ChainedSerializer.cs +++ b/src/SharpYaml/Serialization/Serializers/ChainedSerializer.cs @@ -58,7 +58,7 @@ public ChainedSerializer(IYamlSerializable next) this.next = next; } - public virtual object ReadYaml(ref ObjectContext objectContext) + public virtual object? ReadYaml(ref ObjectContext objectContext) { return next.ReadYaml(ref objectContext); } diff --git a/src/SharpYaml/Serialization/Serializers/CollectionSerializer.cs b/src/SharpYaml/Serialization/Serializers/CollectionSerializer.cs index 1676c224..c3bddf5b 100644 --- a/src/SharpYaml/Serialization/Serializers/CollectionSerializer.cs +++ b/src/SharpYaml/Serialization/Serializers/CollectionSerializer.cs @@ -64,7 +64,7 @@ public CollectionSerializer() { } - public override IYamlSerializable TryCreate(SerializerContext context, ITypeDescriptor typeDescriptor) + public override IYamlSerializable? TryCreate(SerializerContext context, ITypeDescriptor typeDescriptor) { return typeDescriptor is CollectionDescriptor ? this : null; } @@ -205,7 +205,7 @@ protected virtual void ReadAddCollectionItem(ref ObjectContext objectContext, Ty /// Type of the item. /// /// The item to add to the current collection. - protected virtual object ReadCollectionItem(ref ObjectContext objectContext, object value, Type itemType, int index) + protected virtual object ReadCollectionItem(ref ObjectContext objectContext, object? value, Type itemType, int index) { return objectContext.ObjectSerializerBackend.ReadCollectionItem(ref objectContext, value, itemType, index); } diff --git a/src/SharpYaml/Serialization/Serializers/DefaultObjectSerializerBackend.cs b/src/SharpYaml/Serialization/Serializers/DefaultObjectSerializerBackend.cs index f76ba019..d4526fdb 100644 --- a/src/SharpYaml/Serialization/Serializers/DefaultObjectSerializerBackend.cs +++ b/src/SharpYaml/Serialization/Serializers/DefaultObjectSerializerBackend.cs @@ -95,26 +95,26 @@ public virtual string ReadMemberName(ref ObjectContext objectContext, string mem return memberName; } - public virtual object ReadMemberValue(ref ObjectContext objectContext, IMemberDescriptor memberDescriptor, object memberValue, + public virtual object? ReadMemberValue(ref ObjectContext objectContext, IMemberDescriptor? memberDescriptor, object? memberValue, Type memberType) { return objectContext.SerializerContext.ReadYaml(memberValue, memberType); } - public virtual object ReadCollectionItem(ref ObjectContext objectContext, object value, Type itemType, int index) + public virtual object? ReadCollectionItem(ref ObjectContext objectContext, object? value, Type itemType, int index) { return objectContext.SerializerContext.ReadYaml(value, itemType); } - public virtual KeyValuePair ReadDictionaryItem(ref ObjectContext objectContext, KeyValuePair keyValueType) + public virtual KeyValuePair ReadDictionaryItem(ref ObjectContext objectContext, KeyValuePair keyValueType) { var keyResult = objectContext.SerializerContext.ReadYaml(null, keyValueType.Key); var valueResult = objectContext.SerializerContext.ReadYaml(null, keyValueType.Value); - return new KeyValuePair(keyResult, valueResult); + return new KeyValuePair(keyResult, valueResult); } - public virtual void WriteMemberName(ref ObjectContext objectContext, IMemberDescriptor member, string name) + public virtual void WriteMemberName(ref ObjectContext objectContext, IMemberDescriptor? member, string name) { // Emit the key name objectContext.Writer.Emit(new ScalarEventInfo(name, typeof(string)) @@ -125,7 +125,7 @@ public virtual void WriteMemberName(ref ObjectContext objectContext, IMemberDesc }); } - public virtual void WriteMemberValue(ref ObjectContext objectContext, IMemberDescriptor member, object memberValue, + public virtual void WriteMemberValue(ref ObjectContext objectContext, IMemberDescriptor member, object? memberValue, Type memberType) { // Push the style of the current member @@ -137,7 +137,7 @@ public virtual void WriteCollectionItem(ref ObjectContext objectContext, object objectContext.SerializerContext.WriteYaml(item, itemType); } - public virtual void WriteDictionaryItem(ref ObjectContext objectContext, KeyValuePair keyValue, KeyValuePair types) + public virtual void WriteDictionaryItem(ref ObjectContext objectContext, KeyValuePair keyValue, KeyValuePair types) { objectContext.SerializerContext.WriteYaml(keyValue.Key, types.Key); objectContext.SerializerContext.WriteYaml(keyValue.Value, types.Value); diff --git a/src/SharpYaml/Serialization/Serializers/DictionarySerializer.cs b/src/SharpYaml/Serialization/Serializers/DictionarySerializer.cs index bb73fac0..1aab5549 100644 --- a/src/SharpYaml/Serialization/Serializers/DictionarySerializer.cs +++ b/src/SharpYaml/Serialization/Serializers/DictionarySerializer.cs @@ -67,7 +67,7 @@ public DictionarySerializer() } /// - public override IYamlSerializable TryCreate(SerializerContext context, ITypeDescriptor typeDescriptor) + public override IYamlSerializable? TryCreate(SerializerContext context, ITypeDescriptor typeDescriptor) { return typeDescriptor is DictionaryDescriptor ? this : null; } @@ -183,7 +183,7 @@ protected virtual void ReadDictionaryItems(ref ObjectContext objectContext) /// The object context. /// Type of the key value. /// KeyValuePair{System.ObjectSystem.Object}. - protected virtual KeyValuePair ReadDictionaryItem(ref ObjectContext objectContext, KeyValuePair keyValueType) + protected virtual KeyValuePair ReadDictionaryItem(ref ObjectContext objectContext, KeyValuePair keyValueType) { return objectContext.ObjectSerializerBackend.ReadDictionaryItem(ref objectContext, keyValueType); } @@ -218,7 +218,7 @@ protected virtual void WriteDictionaryItems(ref ObjectContext objectContext) /// The object context. /// The key value. /// The types. - protected virtual void WriteDictionaryItem(ref ObjectContext objectContext, KeyValuePair keyValue, KeyValuePair types) + protected virtual void WriteDictionaryItem(ref ObjectContext objectContext, KeyValuePair keyValue, KeyValuePair types) { objectContext.ObjectSerializerBackend.WriteDictionaryItem(ref objectContext, keyValue, types); } diff --git a/src/SharpYaml/Serialization/Serializers/ObjectSerializer.cs b/src/SharpYaml/Serialization/Serializers/ObjectSerializer.cs index 668274a2..a0c81b0e 100644 --- a/src/SharpYaml/Serialization/Serializers/ObjectSerializer.cs +++ b/src/SharpYaml/Serialization/Serializers/ObjectSerializer.cs @@ -63,7 +63,7 @@ public ObjectSerializer() } /// - public virtual IYamlSerializable TryCreate(SerializerContext context, ITypeDescriptor typeDescriptor) + public virtual IYamlSerializable? TryCreate(SerializerContext context, ITypeDescriptor typeDescriptor) { // always accept return this; @@ -90,7 +90,7 @@ protected virtual YamlStyle GetStyle(ref ObjectContext objectContext) return objectContext.ObjectSerializerBackend.GetStyle(ref objectContext); } - public virtual object ReadYaml(ref ObjectContext objectContext) + public virtual object? ReadYaml(ref ObjectContext objectContext) { // Create or transform the value to deserialize // If the new value to serialize is not the same as the one we were expecting to serialize @@ -333,8 +333,8 @@ protected virtual string ReadMemberName(ref ObjectContext objectContext, string return objectContext.ObjectSerializerBackend.ReadMemberName(ref objectContext, memberName, out skipMember); } - protected virtual object ReadMemberValue(ref ObjectContext objectContext, IMemberDescriptor member, - object memberValue, + protected virtual object? ReadMemberValue(ref ObjectContext objectContext, IMemberDescriptor? member, + object? memberValue, Type memberType) { return objectContext.ObjectSerializerBackend.ReadMemberValue(ref objectContext, member, memberValue, memberType); @@ -426,12 +426,12 @@ protected virtual void WriteMember(ref ObjectContext objectContext, IMemberDescr WriteMemberValue(ref objectContext, member, memberValue, memberType); } - protected virtual void WriteMemberName(ref ObjectContext objectContext, IMemberDescriptor member, string name) + protected virtual void WriteMemberName(ref ObjectContext objectContext, IMemberDescriptor? member, string name) { objectContext.ObjectSerializerBackend.WriteMemberName(ref objectContext, member, name); } - protected virtual void WriteMemberValue(ref ObjectContext objectContext, IMemberDescriptor member, object memberValue, + protected virtual void WriteMemberValue(ref ObjectContext objectContext, IMemberDescriptor member, object? memberValue, Type memberType) { objectContext.ObjectSerializerBackend.WriteMemberValue(ref objectContext, member, memberValue, memberType); diff --git a/src/SharpYaml/Serialization/Serializers/PrimitiveSerializer.cs b/src/SharpYaml/Serialization/Serializers/PrimitiveSerializer.cs index 617fdee3..a8883887 100644 --- a/src/SharpYaml/Serialization/Serializers/PrimitiveSerializer.cs +++ b/src/SharpYaml/Serialization/Serializers/PrimitiveSerializer.cs @@ -53,12 +53,12 @@ namespace SharpYaml.Serialization.Serializers { internal class PrimitiveSerializer : ScalarSerializerBase, IYamlSerializableFactory { - public IYamlSerializable TryCreate(SerializerContext context, ITypeDescriptor typeDescriptor) + public IYamlSerializable? TryCreate(SerializerContext context, ITypeDescriptor typeDescriptor) { return typeDescriptor is PrimitiveDescriptor ? this : null; } - public override object ConvertFrom(ref ObjectContext context, Scalar scalar) + public override object? ConvertFrom(ref ObjectContext context, Scalar scalar) { var primitiveType = (PrimitiveDescriptor)context.Descriptor; var type = primitiveType.Type; @@ -197,7 +197,7 @@ public override string ConvertTo(ref ObjectContext objectContext) return ConvertValue(objectContext.Instance); } - public static string ConvertValue(object value) + public static string ConvertValue(object? value) { var text = string.Empty; diff --git a/src/SharpYaml/Serialization/Serializers/RoutingSerializer.cs b/src/SharpYaml/Serialization/Serializers/RoutingSerializer.cs index d73e2ee5..af6a3072 100644 --- a/src/SharpYaml/Serialization/Serializers/RoutingSerializer.cs +++ b/src/SharpYaml/Serialization/Serializers/RoutingSerializer.cs @@ -71,7 +71,7 @@ public void AddSerializerFactory(IYamlSerializableFactory factory) factories.Add(factory); } - public object ReadYaml(ref ObjectContext objectContext) + public object? ReadYaml(ref ObjectContext objectContext) { // If value is not null, use its TypeDescriptor otherwise use expected type descriptor var instance = objectContext.Instance; diff --git a/src/SharpYaml/Serialization/Serializers/ScalarSerializerBase.cs b/src/SharpYaml/Serialization/Serializers/ScalarSerializerBase.cs index 13dd7b62..25b2a9c3 100644 --- a/src/SharpYaml/Serialization/Serializers/ScalarSerializerBase.cs +++ b/src/SharpYaml/Serialization/Serializers/ScalarSerializerBase.cs @@ -50,13 +50,13 @@ namespace SharpYaml.Serialization.Serializers { public abstract class ScalarSerializerBase : IYamlSerializable { - public object ReadYaml(ref ObjectContext objectContext) + public object? ReadYaml(ref ObjectContext objectContext) { var scalar = objectContext.Reader.Expect(); return ConvertFrom(ref objectContext, scalar); } - public abstract object ConvertFrom(ref ObjectContext context, Scalar fromScalar); + public abstract object? ConvertFrom(ref ObjectContext context, Scalar fromScalar); public void WriteYaml(ref ObjectContext objectContext) { diff --git a/src/SharpYaml/Serialization/Serializers/TagTypeSerializer.cs b/src/SharpYaml/Serialization/Serializers/TagTypeSerializer.cs index aa00ce01..820b3e96 100644 --- a/src/SharpYaml/Serialization/Serializers/TagTypeSerializer.cs +++ b/src/SharpYaml/Serialization/Serializers/TagTypeSerializer.cs @@ -56,7 +56,7 @@ public TagTypeSerializer(IYamlSerializable next) : base(next) { } - public override object ReadYaml(ref ObjectContext objectContext) + public override object? ReadYaml(ref ObjectContext objectContext) { var parsingEvent = objectContext.Reader.Peek(); // Can this happen here? @@ -74,7 +74,7 @@ public override object ReadYaml(ref ObjectContext objectContext) var type = objectContext.Descriptor != null ? objectContext.Descriptor.Type : null; // Tries to get a Type from the TagTypes - Type typeFromTag = null; + Type? typeFromTag = null; if (!string.IsNullOrEmpty(node.Tag)) { typeFromTag = objectContext.SerializerContext.TypeFromTag(node.Tag, out bool remapped); @@ -98,7 +98,7 @@ public override object ReadYaml(ref ObjectContext objectContext) if (type == null) type = typeFromTag; - object value = objectContext.Instance; + object? value = objectContext.Instance; // Handle explicit null scalar if (node is Scalar scalar && objectContext.SerializerContext.Schema.TryParse(scalar, typeof(object), out value)) diff --git a/src/SharpYaml/Serialization/YamlAliasNode.cs b/src/SharpYaml/Serialization/YamlAliasNode.cs index 962c7642..809545ea 100644 --- a/src/SharpYaml/Serialization/YamlAliasNode.cs +++ b/src/SharpYaml/Serialization/YamlAliasNode.cs @@ -94,7 +94,7 @@ public override void Accept(IYamlVisitor visitor) } /// - public override bool Equals(object other) + public override bool Equals(object? other) { return other is YamlAliasNode obj && Equals(obj) && SafeEquals(Anchor, obj.Anchor); } diff --git a/src/SharpYaml/Serialization/YamlMappingNode.cs b/src/SharpYaml/Serialization/YamlMappingNode.cs index 9d556024..bd2ebf36 100644 --- a/src/SharpYaml/Serialization/YamlMappingNode.cs +++ b/src/SharpYaml/Serialization/YamlMappingNode.cs @@ -223,8 +223,8 @@ public void Add(string key, string value) /// The state of the document. internal override void ResolveAliases(DocumentLoadingState state) { - Dictionary keysToUpdate = null; - Dictionary valuesToUpdate = null; + Dictionary? keysToUpdate = null; + Dictionary? valuesToUpdate = null; foreach (var entry in Children) { if (entry.Key is YamlAliasNode) @@ -233,7 +233,7 @@ internal override void ResolveAliases(DocumentLoadingState state) { keysToUpdate = new Dictionary(); } - keysToUpdate.Add(entry.Key, state.GetNode(entry.Key.Anchor, true, entry.Key.Start, entry.Key.End)); + keysToUpdate.Add(entry.Key, state.GetNode(entry.Key.Anchor!, true, entry.Key.Start, entry.Key.End)); } if (entry.Value is YamlAliasNode) { @@ -241,7 +241,7 @@ internal override void ResolveAliases(DocumentLoadingState state) { valuesToUpdate = new Dictionary(); } - valuesToUpdate.Add(entry.Key, state.GetNode(entry.Value.Anchor, true, entry.Value.Start, entry.Value.End)); + valuesToUpdate.Add(entry.Key, state.GetNode(entry.Value.Anchor!, true, entry.Value.Start, entry.Value.End)); } } if (valuesToUpdate != null) @@ -290,7 +290,7 @@ public override void Accept(IYamlVisitor visitor) } /// - public override bool Equals(object other) + public override bool Equals(object? other) { if (other is not YamlMappingNode obj || !Equals(obj) || Children.Count != obj.Children.Count) { diff --git a/src/SharpYaml/Serialization/YamlMemberAttribute.cs b/src/SharpYaml/Serialization/YamlMemberAttribute.cs index 75d86cae..8af7dd54 100644 --- a/src/SharpYaml/Serialization/YamlMemberAttribute.cs +++ b/src/SharpYaml/Serialization/YamlMemberAttribute.cs @@ -104,7 +104,7 @@ public YamlMemberAttribute(SerializeMemberMode serializeMethod) /// Gets the name. /// /// The name. - public string Name { get; } + public string? Name { get; } /// /// Gets the serialize method1. diff --git a/src/SharpYaml/Serialization/YamlNode.cs b/src/SharpYaml/Serialization/YamlNode.cs index 024590e7..2a926948 100644 --- a/src/SharpYaml/Serialization/YamlNode.cs +++ b/src/SharpYaml/Serialization/YamlNode.cs @@ -59,13 +59,13 @@ public abstract class YamlNode /// Gets or sets the anchor of the node. /// /// The anchor. - public string Anchor { get; set; } + public string? Anchor { get; set; } /// /// Gets or sets the tag of the node. /// /// The tag. - public string Tag { get; set; } + public string? Tag { get; set; } /// /// Gets the position in the input stream where the event that originated the node starts. @@ -176,7 +176,7 @@ protected bool Equals(YamlNode other) /// /// Gets a value indicating whether two objects are equal. /// - protected static bool SafeEquals(object first, object second) + protected static bool SafeEquals(object? first, object? second) { if (first != null) { @@ -207,7 +207,7 @@ public override int GetHashCode() /// /// Gets the hash code of the specified object, or zero if the object is null. /// - protected static int GetHashCode(object value) + protected static int GetHashCode(object? value) { return value == null ? 0 : value.GetHashCode(); } diff --git a/src/SharpYaml/Serialization/YamlNodeIdentityEqualityComparer.cs b/src/SharpYaml/Serialization/YamlNodeIdentityEqualityComparer.cs index c5822a75..b7b3c43b 100644 --- a/src/SharpYaml/Serialization/YamlNodeIdentityEqualityComparer.cs +++ b/src/SharpYaml/Serialization/YamlNodeIdentityEqualityComparer.cs @@ -55,7 +55,7 @@ public sealed class YamlNodeIdentityEqualityComparer : IEqualityComparer Members /// - public bool Equals(YamlNode x, YamlNode y) + public bool Equals(YamlNode? x, YamlNode? y) { return ReferenceEquals(x, y); } diff --git a/src/SharpYaml/Serialization/YamlScalarNode.cs b/src/SharpYaml/Serialization/YamlScalarNode.cs index eaf5c904..1788b444 100644 --- a/src/SharpYaml/Serialization/YamlScalarNode.cs +++ b/src/SharpYaml/Serialization/YamlScalarNode.cs @@ -129,7 +129,7 @@ public override void Accept(IYamlVisitor visitor) } /// - public override bool Equals(object other) + public override bool Equals(object? other) { return other is YamlScalarNode obj && Equals(obj) && SafeEquals(Value, obj.Value); } diff --git a/src/SharpYaml/Serialization/YamlSequenceNode.cs b/src/SharpYaml/Serialization/YamlSequenceNode.cs index dd613c1e..5928a950 100644 --- a/src/SharpYaml/Serialization/YamlSequenceNode.cs +++ b/src/SharpYaml/Serialization/YamlSequenceNode.cs @@ -164,7 +164,7 @@ internal override void ResolveAliases(DocumentLoadingState state) { if (Children[i] is YamlAliasNode) { - Children[i] = state.GetNode(Children[i].Anchor, true, Children[i].Start, Children[i].End); + Children[i] = state.GetNode(Children[i].Anchor!, true, Children[i].Start, Children[i].End); } } } @@ -196,7 +196,7 @@ public override void Accept(IYamlVisitor visitor) } /// - public override bool Equals(object other) + public override bool Equals(object? other) { if (other is not YamlSequenceNode obj || !Equals(obj) || Children.Count != obj.Children.Count) { diff --git a/src/SharpYaml/SharpYaml.csproj b/src/SharpYaml/SharpYaml.csproj index 9ca781b3..b9fac4b8 100644 --- a/src/SharpYaml/SharpYaml.csproj +++ b/src/SharpYaml/SharpYaml.csproj @@ -18,6 +18,7 @@ true snupkg 10 + annotations diff --git a/src/SharpYaml/Tokens/TagDirective.cs b/src/SharpYaml/Tokens/TagDirective.cs index 26176317..708bf047 100644 --- a/src/SharpYaml/Tokens/TagDirective.cs +++ b/src/SharpYaml/Tokens/TagDirective.cs @@ -116,7 +116,7 @@ public TagDirective(string handle, string prefix, Mark start, Mark end) /// /// true if the specified System.Object is equal to the current System.Object; otherwise, false. /// - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is TagDirective other && Handle.Equals(other.Handle) && Prefix.Equals(other.Prefix); } diff --git a/src/SharpYaml/Tokens/VersionDirective.cs b/src/SharpYaml/Tokens/VersionDirective.cs index 44f91adb..8648b7f8 100644 --- a/src/SharpYaml/Tokens/VersionDirective.cs +++ b/src/SharpYaml/Tokens/VersionDirective.cs @@ -86,7 +86,7 @@ public VersionDirective(Version version, Mark start, Mark end) /// /// true if the specified System.Object is equal to the current System.Object; otherwise, false. /// - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is VersionDirective other && Version.Equals(other.Version); } diff --git a/src/SharpYaml/TypeExtensions.cs b/src/SharpYaml/TypeExtensions.cs index a9bbe109..1c087517 100644 --- a/src/SharpYaml/TypeExtensions.cs +++ b/src/SharpYaml/TypeExtensions.cs @@ -86,7 +86,7 @@ public static bool ExtendsGeneric(this Type type, Type genericType) return false; } - public static Type GetInterface(this Type type, Type lookInterfaceType) + public static Type? GetInterface(this Type type, Type lookInterfaceType) { if (type == null) throw new ArgumentNullException("type"); @@ -156,7 +156,7 @@ private static void DoGetShortAssemblyQualifiedName(Type type, StringBuilder sb, // type var isArray = type.IsArray; if (isArray) - type = type.GetElementType(); + type = type.GetElementType()!; sb.Append(type.Name); // generic arguments if (type.GetTypeInfo().IsGenericType) @@ -280,7 +280,7 @@ public static bool IsNumeric(this Type type) /// /// /// - public static bool AreEqual(object a, object b) + public static bool AreEqual(object? a, object? b) { if (a == null) return b == null; @@ -295,7 +295,7 @@ public static bool AreEqual(object a, object b) /// Any object /// Numric type /// Numeric value or null if the object is not a numeric value. - public static object CastToNumericType(this Type type, object obj) + public static object? CastToNumericType(this Type type, object? obj) { var doubleValue = CastToDouble(obj); if (double.IsNaN(doubleValue)) @@ -304,7 +304,7 @@ public static object CastToNumericType(this Type type, object obj) if (obj is decimal && type == typeof(decimal)) return obj; // do not convert into double - object result = null; + object? result = null; if (type == typeof(sbyte)) result = (sbyte)doubleValue; if (type == typeof(byte)) @@ -335,7 +335,7 @@ public static object CastToNumericType(this Type type, object obj) /// /// boxed numeric value /// Numeric value in double. Double.Nan if obj is not a numeric value. - public static double CastToDouble(object obj) + public static double CastToDouble(object? obj) { switch (obj) { diff --git a/src/SharpYaml/Version.cs b/src/SharpYaml/Version.cs index 13996945..f103a571 100644 --- a/src/SharpYaml/Version.cs +++ b/src/SharpYaml/Version.cs @@ -80,7 +80,7 @@ public Version(int major, int minor) /// /// true if the specified System.Object is equal to the current System.Object; otherwise, false. /// - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is Version other && Major == other.Major && Minor == other.Minor; } diff --git a/src/SharpYaml/YamlException.cs b/src/SharpYaml/YamlException.cs index 9dc688a1..437bb905 100644 --- a/src/SharpYaml/YamlException.cs +++ b/src/SharpYaml/YamlException.cs @@ -89,7 +89,7 @@ public YamlException(Mark start, Mark end, string message) /// /// Initializes a new instance of the class. /// - public YamlException(Mark start, Mark end, string message, Exception innerException) + public YamlException(Mark start, Mark end, string message, Exception? innerException) : base($"({start}) - ({end}): {message}", innerException) { Start = start;