Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Diagnostics.CodeAnalysis;
- using System.Globalization;
- using System.Linq;
- using System.Text;
- using AutoRest.Core.Model;
- using AutoRest.Core.Properties;
- using AutoRest.Core.Utilities;
- using AutoRest.Core.Utilities.Collections;
- using AutoRest.Core.Validation;
- using static AutoRest.Core.Utilities.DependencyInjection;
- namespace AutoRest.Core
- {
- public class CodeNamer
- {
- private static readonly IDictionary<char, string> basicLaticCharacters = new Dictionary<char, string>
- {
- [(char)32] = "Space",
- [(char)33] = "ExclamationMark",
- [(char)34] = "QuotationMark",
- [(char)35] = "NumberSign",
- [(char)36] = "DollarSign",
- [(char)37] = "PercentSign",
- [(char)38] = "Ampersand",
- [(char)39] = "Apostrophe",
- [(char)40] = "LeftParenthesis",
- [(char)41] = "RightParenthesis",
- [(char)42] = "Asterisk",
- [(char)43] = "PlusSign",
- [(char)44] = "Comma",
- [(char)45] = "HyphenMinus",
- [(char)46] = "FullStop",
- [(char)47] = "Slash",
- [(char)48] = "Zero",
- [(char)49] = "One",
- [(char)50] = "Two",
- [(char)51] = "Three",
- [(char)52] = "Four",
- [(char)53] = "Five",
- [(char)54] = "Six",
- [(char)55] = "Seven",
- [(char)56] = "Eight",
- [(char)57] = "Nine",
- [(char)58] = "Colon",
- [(char)59] = "Semicolon",
- [(char)60] = "LessThanSign",
- [(char)61] = "EqualSign",
- [(char)62] = "GreaterThanSign",
- [(char)63] = "QuestionMark",
- [(char)64] = "AtSign",
- [(char)91] = "LeftSquareBracket",
- [(char)92] = "Backslash",
- [(char)93] = "RightSquareBracket",
- [(char)94] = "CircumflexAccent",
- [(char)96] = "GraveAccent",
- [(char)123] = "LeftCurlyBracket",
- [(char)124] = "VerticalBar",
- [(char)125] = "RightCurlyBracket",
- [(char)126] = "Tilde"
- };
- public CodeNamer()
- {
- }
- public static CodeNamer Instance
- =>
- Singleton<CodeNamer>.HasInstance
- ? Singleton<CodeNamer>.Instance
- : (Singleton<CodeNamer>.Instance = new CodeNamer());
- public HashSet<string> ReservedWords { get; } = new HashSet<string>();
- public virtual string CamelCase(string name)
- {
- if (string.IsNullOrWhiteSpace(name))
- {
- return name;
- }
- if (name[0] == '_')
- {
- return '_' + CamelCase(name.Substring(1));
- }
- return
- name.Split('_', '-', ' ')
- .Where(s => !string.IsNullOrEmpty(s))
- .Select((s, i) => FormatCase(s, i == 0))
- .DefaultIfEmpty("")
- .Aggregate(string.Concat);
- }
- public virtual string PascalCase(string name)
- {
- if (string.IsNullOrWhiteSpace(name))
- {
- return name;
- }
- if (name[0] == '_')
- {
- return '_' + CamelCase(name.Substring(1));
- }
- return
- name.Split('_', '-', ' ')
- .Where(s => !string.IsNullOrEmpty(s))
- .Select(s => FormatCase(s, false))
- .DefaultIfEmpty("")
- .Aggregate(string.Concat);
- }
- [SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")]
- public virtual string QuoteValue(string value, string quoteChar = "\"", string escapeChar = "\\")
- {
- if (quoteChar == null)
- {
- throw new ArgumentNullException(nameof(quoteChar));
- }
- if (escapeChar == null)
- {
- throw new ArgumentNullException(nameof(escapeChar));
- }
- if (string.IsNullOrWhiteSpace(value))
- {
- value = string.Empty;
- }
- return quoteChar + value.Replace(quoteChar, escapeChar + quoteChar) + quoteChar;
- }
- public virtual string EscapeDefaultValue(string defaultValue, IModelType type)
- {
- return defaultValue;
- }
- public virtual string GetEnumMemberName(string name)
- {
- if (string.IsNullOrWhiteSpace(name))
- {
- return name;
- }
- return PascalCase(RemoveInvalidCharacters(name));
- }
- public virtual string GetFieldName(string name)
- {
- if (string.IsNullOrWhiteSpace(name))
- {
- return name;
- }
- return '_' + GetVariableName(name);
- }
- public virtual string GetInterfaceName(string name)
- {
- if (string.IsNullOrWhiteSpace(name))
- {
- return name;
- }
- return $"I{PascalCase(RemoveInvalidCharacters(name))}";
- }
- public virtual string GetMethodName(string name)
- {
- if (string.IsNullOrWhiteSpace(name))
- {
- return name;
- }
- return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Operation")));
- }
- public virtual string GetNamespaceName(string name)
- {
- if (string.IsNullOrWhiteSpace(name))
- {
- return name;
- }
- return PascalCase(RemoveInvalidCharactersNamespace(name));
- }
- public virtual string GetParameterName(string name)
- {
- if (string.IsNullOrWhiteSpace(name))
- {
- return name;
- }
- return GetVariableName(GetEscapedReservedName(name, "Parameter"));
- }
- public virtual string GetPropertyName(string name)
- {
- if (string.IsNullOrWhiteSpace(name))
- {
- return name;
- }
- return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Property")));
- }
- public virtual string GetTypeName(string name)
- {
- if (string.IsNullOrWhiteSpace(name))
- {
- return name;
- }
- return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Model")));
- }
- public virtual string GetMethodGroupName(string name)
- {
- if (string.IsNullOrWhiteSpace(name))
- {
- return name;
- }
- return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Model")));
- }
- public virtual string GetClientName(string name)
- {
- if (string.IsNullOrWhiteSpace(name))
- {
- return name;
- }
- return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Model")));
- }
- public virtual string GetVariableName(string name)
- {
- if (string.IsNullOrWhiteSpace(name))
- {
- return name;
- }
- return CamelCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Variable")));
- }
- private string FormatCase(string name, bool toLower)
- {
- if (!string.IsNullOrEmpty(name))
- {
- if ((name.Length < 2) || ((name.Length == 2) && char.IsUpper(name[0]) && char.IsUpper(name[1])))
- {
- name = toLower ? name.ToLowerInvariant() : name.ToUpperInvariant();
- }
- else
- {
- name =
- (toLower
- ? char.ToLowerInvariant(name[0])
- : char.ToUpperInvariant(name[0])) + name.Substring(1, name.Length - 1);
- }
- }
- return name;
- }
- public virtual string RemoveInvalidCharacters(string name)
- {
- return GetValidName(name, '_', '-');
- }
- protected virtual string RemoveInvalidCharactersNamespace(string name)
- {
- return GetValidName(name, '_', '-', '.');
- }
- public virtual string GetValidName(string name, params char[] allowedCharacters)
- {
- var correctName = RemoveInvalidCharacters(name, allowedCharacters);
- if (string.IsNullOrEmpty(correctName) ||
- basicLaticCharacters.ContainsKey(correctName[0]))
- {
- var sb = new StringBuilder();
- foreach (var symbol in name)
- {
- if (basicLaticCharacters.ContainsKey(symbol))
- {
- sb.Append(basicLaticCharacters[symbol]);
- }
- else
- {
- sb.Append(symbol);
- }
- }
- correctName = RemoveInvalidCharacters(sb.ToString(), allowedCharacters);
- }
- if (correctName.IsNullOrEmpty())
- {
- throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.InvalidIdentifierName,
- name));
- }
- return correctName;
- }
- private string RemoveInvalidCharacters(string name, params char[] allowerCharacters)
- {
- return new string(name.Replace("[]", "Sequence")
- .Where(c => char.IsLetterOrDigit(c) || allowerCharacters.Contains(c))
- .ToArray());
- }
- protected virtual string GetEscapedReservedName(string name, string appendValue)
- {
- if (name == null)
- {
- throw new ArgumentNullException("name");
- }
- if (appendValue == null)
- {
- throw new ArgumentNullException("appendValue");
- }
- if (ReservedWords.Contains(name, StringComparer.OrdinalIgnoreCase))
- {
- name += appendValue;
- }
- return name;
- }
- public virtual string IsNameLegal(string desiredName, IIdentifier whoIsAsking)
- {
- if (string.IsNullOrWhiteSpace(desiredName))
- {
- throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.InvalidIdentifierName,
- desiredName));
- }
- if (ReservedWords.Contains(desiredName))
- {
- return desiredName;
- }
- return null;
- }
- public virtual IIdentifier IsNameAvailable(string desiredName, HashSet<IIdentifier> reservedNames)
- {
- return
- reservedNames.FirstOrDefault(
- each => each.MyReservedNames.WhereNotNull().Any(name => name.Equals(desiredName)));
- }
- public virtual bool IsSpecialCase(IIdentifier whoIsAsking, IIdentifier reservedName)
- {
- if (whoIsAsking is Property && reservedName is CompositeType)
- {
- return true;
- }
- if (whoIsAsking is Parameter && reservedName is Method)
- {
- return true;
- }
- if (whoIsAsking is MethodGroup)
- {
- return true;
- }
- return false;
- }
- public virtual string GetUnique(string desiredName, IIdentifier whoIsAsking,
- IEnumerable<IIdentifier> reservedNames, IEnumerable<IIdentifier> siblingNames,
- HashSet<string> locallyReservedNames = null)
- {
- if (string.IsNullOrEmpty(desiredName))
- {
- return desiredName;
- }
- #if refactoring_out
- // special case: properties can actually have the same name as a composite type
- // as long as that type is not the parent class of the property itself.
- if (whoIsAsking is Property)
- {
- reservedNames = reservedNames.Where(each => !(each is CompositeType));
- var parent = (whoIsAsking as IChild)?.Parent as IIdentifier;
- if (parent != null)
- {
- reservedNames = reservedNames.ConcatSingleItem(parent);
- }
- }
- #endif
- var names = new HashSet<IIdentifier>(reservedNames.Where(each => !IsSpecialCase(whoIsAsking, each)));
- string conflict;
- while ((conflict = IsNameLegal(desiredName, whoIsAsking)) != null)
- {
- desiredName += whoIsAsking.Qualifier;
- }
- IIdentifier confl;
- while (null != (confl = IsNameAvailable(desiredName, names)))
- {
- desiredName += whoIsAsking.Qualifier;
- }
- if (whoIsAsking is CompositeType)
- {
- siblingNames = siblingNames.Where(each => !(each is Property));
- }
- if (whoIsAsking is Property)
- {
- siblingNames = siblingNames.Where(each => !(each is CompositeType));
- }
- names = new HashSet<IIdentifier>(siblingNames);
- var baseName = desiredName;
- var suffix = 0;
- while (IsNameAvailable(desiredName, names) != null)
- {
- desiredName = baseName + ++suffix;
- }
- while (true == locallyReservedNames?.Contains(desiredName))
- {
- desiredName = baseName + ++suffix;
- }
- return desiredName;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment