Skip to content

Commit

Permalink
Fix typo. Optimize codes.
Browse files Browse the repository at this point in the history
  • Loading branch information
BearOffice committed Dec 8, 2023
1 parent 461a4ff commit 9ebdbc7
Show file tree
Hide file tree
Showing 19 changed files with 144 additions and 149 deletions.
6 changes: 3 additions & 3 deletions BearMarkupLanguage/BearML.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public class BearML
/// </summary>
public BearML()
{
_rootBlock = RootBlockInterpreter.Interprete(new ReferList<string>(Array.Empty<string>())).Value;
_rootBlock = RootBlockInterpreter.Interpret(new ReferList<string>(Array.Empty<string>())).Value;
_writer = null;
_providers = Array.Empty<IConversionProvider>();
}
Expand All @@ -49,7 +49,7 @@ public BearML()
/// <param name="providers">Provides methods to convert the specified types.</param>
public BearML(IConversionProvider[] providers)
{
_rootBlock = RootBlockInterpreter.Interprete(new ReferList<string>(Array.Empty<string>())).Value;
_rootBlock = RootBlockInterpreter.Interpret(new ReferList<string>(Array.Empty<string>())).Value;
_writer = null;
_providers = providers;
}
Expand Down Expand Up @@ -1281,7 +1281,7 @@ public static T Deserialize<T>(string literal, IConversionProvider[] providers =
providers ??= Array.Empty<IConversionProvider>();

var literals = new ReferList<string>(literal.SplitByLF());
var result = ContextInterpreter.ContentInterprete(literals, out _);
var result = ContextInterpreter.InterpretContent(literals, out _);

if (!result.IsSuccess)
ThrowParseException(literals[result.Error.LineIndex], result.Error);
Expand Down
2 changes: 1 addition & 1 deletion BearMarkupLanguage/BearMarkupLanguage.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Version>5.0.11</Version>
<Version>5.0.12</Version>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<Authors>Bear</Authors>
<Company>Bear Office</Company>
Expand Down
85 changes: 42 additions & 43 deletions BearMarkupLanguage/Conversion/TypeConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,60 +10,30 @@ internal static class TypeConverter
{
internal static string ConvertToLiteral(object source, IConversionProvider[] providers = null)
{
var sourcetype = source.GetType();

if (providers is not null)
{
foreach (var provider in providers)
{
if (provider.Type == typeof(object))
return provider.ConvertToLiteral(source);

if (provider.Type.IsGenericTypeDefinition && sourcetype.IsGenericType)
{
if (provider.Type == sourcetype.GetGenericTypeDefinition())
return provider.ConvertToLiteral(source);
}
var sourceType = source.GetType();

if (provider.Type == sourcetype)
return provider.ConvertToLiteral(source);
}
}
if (TryGetProvider(sourceType, providers, out var provider))
return ConvertToLiteralByProvider(source, provider);

if (TryConvert(source, typeof(string), out var target))
return (string)target;
else
throw new TypeNotSupportException($"Cannot convert {sourcetype}. " +
throw new TypeNotSupportException($"Cannot convert {sourceType}. " +
$"Consider add IConvertProvider to support such a type.");
}

internal static object ConvertFromLiteral(string source, Type targetType, IConversionProvider[] providers = null)
{
if (providers is not null)
{
foreach (var provider in providers)
{
if (provider.Type == typeof(object))
return provider.ConvertFromLiteral(source);

if (provider.Type.IsGenericTypeDefinition && targetType.IsGenericType)
{
if (provider.Type == targetType.GetGenericTypeDefinition())
return provider.ConvertFromLiteral(source);
}

if (provider.Type == targetType)
return provider.ConvertFromLiteral(source);
}
}
if (TryGetProvider(targetType, providers, out var provider))
return ConvertFromLiteralByProvider(source, provider);

if (TryConvert(source, targetType, out var target))
return target;
else
throw new TypeNotSupportException($"Cannot convert {targetType}. " +
$"Consider add IConvertProvider to support such a type.");
}

private static bool TryConvert(object source, Type targetType, out object target)
{
var sourceType = source.GetType();
Expand All @@ -74,22 +44,51 @@ private static bool TryConvert(object source, Type targetType, out object target
return true;
}

var targetconverter = TypeDescriptor.GetConverter(targetType);
if (targetconverter != null && targetconverter.CanConvertFrom(sourceType))
var targetConverter = TypeDescriptor.GetConverter(targetType);
if (targetConverter != null && targetConverter.CanConvertFrom(sourceType))
{
target = targetconverter.ConvertFrom(source);
target = targetConverter.ConvertFrom(source);
return true;
}

var sourceconverter = TypeDescriptor.GetConverter(sourceType);
if (sourceconverter != null && sourceconverter.CanConvertTo(targetType))
var sourceConverter = TypeDescriptor.GetConverter(sourceType);
if (sourceConverter != null && sourceConverter.CanConvertTo(targetType))
{
target = sourceconverter.ConvertTo(source, targetType);
target = sourceConverter.ConvertTo(source, targetType);

return true;
}

target = default;
return false;
}

internal static bool TryGetProvider(Type type, IConversionProvider[] providers, out IConversionProvider provider)
{
if (providers is not null)
{
foreach (var p in providers)
{
if (p.Type == typeof(object) || p.Type == type ||
(type.IsGenericType && p.Type == type.GetGenericTypeDefinition()))
{
provider = p;
return true;
}
}
}

provider = null;
return false;
}

internal static string ConvertToLiteralByProvider(object source, IConversionProvider provider)
{
return provider.ConvertToLiteral(source);
}

internal static object ConvertFromLiteralByProvider(string source, IConversionProvider provider)
{
return provider.ConvertFromLiteral(source);
}
}
2 changes: 1 addition & 1 deletion BearMarkupLanguage/Core/Reader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,6 @@ internal RootBlockResult Read(out string[] lines)
}

lines = tempList.ToArray();
return RootBlockInterpreter.Interprete(new ReferList<string>(lines));
return RootBlockInterpreter.Interpret(new ReferList<string>(lines));
}
}
2 changes: 1 addition & 1 deletion BearMarkupLanguage/Elements/BlockKey.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

namespace BearMarkupLanguage.Elements;

internal struct BlockKey : IEquatable<BlockKey>
internal readonly struct BlockKey : IEquatable<BlockKey>
{
internal string Name { get; init; }
internal string Comment { get; init; }
Expand Down
18 changes: 8 additions & 10 deletions BearMarkupLanguage/Elements/DictionaryElement.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,11 @@ public object ConvertTo(Type targetType, IConversionProvider[] providers)
{
if (targetType.IsDictionaryType())
{
return ConvertIDictionaryTo(targetType, providers);
return ConvertDictionaryTypeTo(targetType, providers);
}
else if (targetType.IsSerializableObject())
{
return ConvertObjectTo(targetType, providers);
return ConvertObjectTypeTo(targetType, providers);
}
else
{
Expand All @@ -67,7 +67,7 @@ public object ConvertTo(Type targetType, IConversionProvider[] providers)
}
}

private object ConvertIDictionaryTo(Type targetType, IConversionProvider[] providers)
private object ConvertDictionaryTypeTo(Type targetType, IConversionProvider[] providers)
{
// IDictionary contains two generic arguments
var arguments = targetType.GetGenericArguments();
Expand Down Expand Up @@ -102,24 +102,22 @@ private object ConvertIDictionaryTo(Type targetType, IConversionProvider[] provi
if (values[i].GetType() != preferredValueType && values[i].GetType() != typeof(EmptyElement))
throw new TypeNotMatchException($"Type of value not match.");

var keyValuePairconsInfo = keyValueType.GetConstructor(new[] { keyType, valueType });
var keyValuePair = keyValuePairconsInfo.Invoke(new[] {
var keyValuePairConsInfo = keyValueType.GetConstructor(new[] { keyType, valueType });
var keyValuePair = keyValuePairConsInfo.Invoke(new[] {
keys[i].ConvertTo(keyType, providers),
values[i].ConvertTo(valueType, providers)
});

targetArr.SetValue(keyValuePair, i);
}

var consInfo = targetType.GetConstructor(new[] { targetArr.GetType() });

if (consInfo is null)
throw new TypeNotMatchException($"No constructor found for Type {targetType}.");
var consInfo = targetType.GetConstructor(new[] { targetArr.GetType() })
?? throw new TypeNotMatchException($"No constructor found for Type {targetType}.");

return consInfo.Invoke(new[] { targetArr });
}

private object ConvertObjectTo(Type targetType, IConversionProvider[] providers)
private object ConvertObjectTypeTo(Type targetType, IConversionProvider[] providers)
{
var target = Activator.CreateInstance(targetType);
var count = 0;
Expand Down
2 changes: 1 addition & 1 deletion BearMarkupLanguage/Elements/Key.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

namespace BearMarkupLanguage.Elements;

internal struct Key : IEquatable<Key>
internal readonly struct Key : IEquatable<Key>
{
internal string Name { get; init; }
internal string[] Aliases { get; init; }
Expand Down
6 changes: 2 additions & 4 deletions BearMarkupLanguage/Elements/ListElement.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,8 @@ private object ConvertIListTo(Type targetType, IConversionProvider[] providers)
}
else
{
var consInfo = targetType.GetConstructor(new[] { targetArr.GetType() });

if (consInfo is null)
throw new TypeNotMatchException($"No constructor found for Type {targetType}.");
var consInfo = targetType.GetConstructor(new[] { targetArr.GetType() })
?? throw new TypeNotMatchException($"No constructor found for Type {targetType}.");

return consInfo.Invoke(new[] { targetArr });
}
Expand Down
30 changes: 15 additions & 15 deletions BearMarkupLanguage/Helpers/OrderedDictionary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,23 @@ namespace BearMarkupLanguage.Helpers;
internal class OrderedDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
private readonly Dictionary<TKey, TValue> _dictionary;
private readonly List<TKey> _orderKeyList;
private readonly List<TKey> _orderedKeys;

internal OrderedDictionary()
{
_dictionary = new Dictionary<TKey, TValue>();
_orderKeyList = new List<TKey>();
_orderedKeys = new List<TKey>();
}

internal OrderedDictionary(KeyValuePair<TKey, TValue>[] keyValuePairs)
{
_dictionary = new Dictionary<TKey, TValue>();
_orderKeyList = new List<TKey>();
_orderedKeys = new List<TKey>();

foreach ((var key, var value) in keyValuePairs)
{
_dictionary.Add(key, value);
_orderKeyList.Add(key);
_orderedKeys.Add(key);
}
}

Expand All @@ -35,21 +35,21 @@ public TValue this[TKey key]
set => _dictionary[key] = value;
}

public ICollection<TKey> Keys => _orderKeyList;
public ICollection<TValue> Values => _orderKeyList.Select(key => _dictionary[key]).ToList();
public ICollection<TKey> Keys => _orderedKeys;
public ICollection<TValue> Values => _orderedKeys.Select(key => _dictionary[key]).ToList();
public int Count => _dictionary.Count;
public bool IsReadOnly => false;

public void Add(TKey key, TValue value)
{
_dictionary.Add(key, value);
_orderKeyList.Add(key);
_orderedKeys.Add(key);
}

public void Add(KeyValuePair<TKey, TValue> item)
{
_dictionary.Add(item.Key, item.Value);
_orderKeyList.Add(item.Key);
_orderedKeys.Add(item.Key);
}

public bool ChangeKey(TKey oldKey, TKey newKey)
Expand All @@ -61,16 +61,16 @@ public bool ChangeKey(TKey oldKey, TKey newKey)
_dictionary.Remove(oldKey);
_dictionary.Add(newKey, value);

var index = _orderKeyList.IndexOf(oldKey);
_orderKeyList[index] = newKey;
var index = _orderedKeys.IndexOf(oldKey);
_orderedKeys[index] = newKey;

return true;
}

public void Clear()
{
_dictionary.Clear();
_orderKeyList.Clear();
_orderedKeys.Clear();
}

public bool Contains(KeyValuePair<TKey, TValue> item)
Expand All @@ -85,23 +85,23 @@ public bool ContainsKey(TKey key)

public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
_orderKeyList.Select(key => new KeyValuePair<TKey, TValue>(key, _dictionary[key]))
_orderedKeys.Select(key => new KeyValuePair<TKey, TValue>(key, _dictionary[key]))
.ToList()
.CopyTo(array, arrayIndex);
}

public bool Remove(TKey key)
{
var result = _dictionary.Remove(key);
_orderKeyList.Remove(key);
_orderedKeys.Remove(key);

return result;
}

public bool Remove(KeyValuePair<TKey, TValue> item)
{
var result = _dictionary.Remove(item.Key);
_orderKeyList.Remove(item.Key);
_orderedKeys.Remove(item.Key);

return result;
}
Expand All @@ -113,7 +113,7 @@ public bool TryGetValue(TKey key, out TValue value)

public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return new OrderedDictionaryEnumerator<TKey, TValue>(_dictionary, _orderKeyList);
return new OrderedDictionaryEnumerator<TKey, TValue>(_dictionary, _orderedKeys);
}

IEnumerator IEnumerable.GetEnumerator()
Expand Down
10 changes: 5 additions & 5 deletions BearMarkupLanguage/Interpretation/BasicElementInterpreter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,23 @@ namespace BearMarkupLanguage.Interpretation;

internal class BasicElementInterpreter : IInterpreter
{
public ElementResult Interprete(string[] lines, ParseMode mode)
public ElementResult Interpret(string[] lines, ParseMode mode)
{
return mode switch
{
ParseMode.Collapse => CollapsedInterprete(lines[0]),
ParseMode.Expand => ExpandedInterprete(lines),
ParseMode.Collapse => InterpretCollapsed(lines[0]),
ParseMode.Expand => InterpretExpanded(lines),
_ => throw new NotImplementedException(),
};
}

private static ElementResult CollapsedInterprete(string line)
private static ElementResult InterpretCollapsed(string line)
{
var literal = line.Unescape();
return ElementResult.Success(new BasicElement(literal));
}

private static ElementResult ExpandedInterprete(string[] lines)
private static ElementResult InterpretExpanded(string[] lines)
{
return ElementResult.Success(new BasicElement(lines.ConcatWithLF()));
}
Expand Down
Loading

0 comments on commit 9ebdbc7

Please sign in to comment.