Skip to content

Commit

Permalink
Make use pattern matching.
Browse files Browse the repository at this point in the history
  • Loading branch information
udaken committed Jun 23, 2022
1 parent ae4e3bd commit 585579a
Show file tree
Hide file tree
Showing 24 changed files with 69 additions and 104 deletions.
10 changes: 5 additions & 5 deletions src/SharpYaml.Tests/ParserTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
4 changes: 1 addition & 3 deletions src/SharpYaml.Tests/SchemaTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
6 changes: 2 additions & 4 deletions src/SharpYaml.Tests/Serialization/SerializationTests2.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1111,8 +1111,7 @@ public override KeyValuePair<object, object> ReadDictionaryItem(ref ObjectContex

public override void WriteDictionaryItem(ref ObjectContext objectContext, KeyValuePair<object, object> keyValue, KeyValuePair<Type, Type> 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<object, object>(itemKey + "!", keyValue.Value);
}
Expand Down Expand Up @@ -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>(@"!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);
Expand Down
4 changes: 2 additions & 2 deletions src/SharpYaml.Tests/YamlNodeTrackerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down
2 changes: 1 addition & 1 deletion src/SharpYaml/Emitter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -679,7 +679,7 @@ private void StateMachine(ParsingEvent evt)
/// </summary>
private void EmitStreamStart(ParsingEvent evt)
{
if (!(evt is StreamStart))
if (evt is not StreamStart)
{
throw new ArgumentException("Expected STREAM-START.", "evt");
}
Expand Down
4 changes: 2 additions & 2 deletions src/SharpYaml/Model/YamlNode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
43 changes: 16 additions & 27 deletions src/SharpYaml/Parser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<StringLookAheadBuffer>(new StringLookAheadBuffer(stringReader.ReadToEnd()));

else return new Parser<LookAheadBuffer>(new LookAheadBuffer(reader, Scanner<LookAheadBuffer>.MaxBufferLength));
Expand Down Expand Up @@ -227,8 +226,7 @@ private void Skip()
/// </summary>
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 <stream-start>.");
Expand Down Expand Up @@ -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 <document start>.");
}
Expand Down Expand Up @@ -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)
{
Expand All @@ -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))
{
Expand Down Expand Up @@ -439,8 +434,7 @@ private static Event ProcessEmptyScalar(Mark position)
/// </summary>
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);
Expand Down Expand Up @@ -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;
Expand All @@ -531,31 +524,27 @@ 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);
}

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);
Expand Down Expand Up @@ -783,7 +772,7 @@ private Event ParseFlowSequenceEntry(bool isFirst)
}

Event evt;
if (!(GetCurrentToken() is FlowSequenceEnd))
if (GetCurrentToken() is not FlowSequenceEnd)
{
if (!isFirst)
{
Expand All @@ -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);
Expand Down Expand Up @@ -891,7 +880,7 @@ private Event ParseFlowMappingKey(bool isFirst)
Skip();
}

if (!(GetCurrentToken() is FlowMappingEnd))
if (GetCurrentToken() is not FlowMappingEnd)
{
if (!isFirst)
{
Expand Down Expand Up @@ -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);
Expand Down
9 changes: 3 additions & 6 deletions src/SharpYaml/Schemas/SchemaBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
10 changes: 3 additions & 7 deletions src/SharpYaml/Serialization/Descriptors/DefaultKeyComparer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,7 @@ public class DefaultKeyComparer : IComparer<object>
{
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)
Expand All @@ -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;
}
}
}
11 changes: 6 additions & 5 deletions src/SharpYaml/Serialization/Descriptors/DictionaryDescriptor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -163,12 +163,14 @@ public IEnumerable<KeyValuePair<object, object>> 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<object, object>(entry.Key, entry.Value);
else
{
yield return new KeyValuePair<object, object>(entry.Key, entry.Value);
}
}
}
}
Expand All @@ -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);
}
Expand Down
18 changes: 8 additions & 10 deletions src/SharpYaml/Serialization/Descriptors/ObjectDescriptor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,7 @@ public ITypeDescriptor Find(Type type, IComparer<object> memberComparer)

descriptor = Create(type);

var objectDescriptor = descriptor as ObjectDescriptor;
if (objectDescriptor != null)
if (descriptor is ObjectDescriptor objectDescriptor)
{
objectDescriptor.SortMembers(memberComparer);
}
Expand Down
Loading

0 comments on commit 585579a

Please sign in to comment.