CSharpCodeHelpers.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using System;
  2. using System.Linq;
  3. using System.Text;
  4. ////REVIEW: this seems like it should be #if UNITY_EDITOR
  5. namespace UnityEngine.InputSystem.Utilities
  6. {
  7. internal static class CSharpCodeHelpers
  8. {
  9. public static bool IsProperIdentifier(string name)
  10. {
  11. if (string.IsNullOrEmpty(name))
  12. return false;
  13. if (char.IsDigit(name[0]))
  14. return false;
  15. for (var i = 0; i < name.Length; ++i)
  16. {
  17. var ch = name[i];
  18. if (!char.IsLetterOrDigit(ch) && ch != '_')
  19. return false;
  20. }
  21. return true;
  22. }
  23. public static bool IsEmptyOrProperIdentifier(string name)
  24. {
  25. if (string.IsNullOrEmpty(name))
  26. return true;
  27. return IsProperIdentifier(name);
  28. }
  29. public static bool IsEmptyOrProperNamespaceName(string name)
  30. {
  31. if (string.IsNullOrEmpty(name))
  32. return true;
  33. return name.Split('.').All(IsProperIdentifier);
  34. }
  35. ////TODO: this one should add the @escape automatically so no other code has to worry
  36. public static string MakeIdentifier(string name, string suffix = "")
  37. {
  38. if (string.IsNullOrEmpty(name))
  39. throw new ArgumentNullException(nameof(name));
  40. if (char.IsDigit(name[0]))
  41. name = "_" + name;
  42. // See if we have invalid characters in the name.
  43. var nameHasInvalidCharacters = false;
  44. for (var i = 0; i < name.Length; ++i)
  45. {
  46. var ch = name[i];
  47. if (!char.IsLetterOrDigit(ch) && ch != '_')
  48. {
  49. nameHasInvalidCharacters = true;
  50. break;
  51. }
  52. }
  53. // If so, create a new string where we remove them.
  54. if (nameHasInvalidCharacters)
  55. {
  56. var buffer = new StringBuilder();
  57. for (var i = 0; i < name.Length; ++i)
  58. {
  59. var ch = name[i];
  60. if (char.IsLetterOrDigit(ch) || ch == '_')
  61. buffer.Append(ch);
  62. }
  63. name = buffer.ToString();
  64. }
  65. return name + suffix;
  66. }
  67. public static string MakeTypeName(string name, string suffix = "")
  68. {
  69. var symbolName = MakeIdentifier(name, suffix);
  70. if (char.IsLower(symbolName[0]))
  71. symbolName = char.ToUpper(symbolName[0]) + symbolName.Substring(1);
  72. return symbolName;
  73. }
  74. }
  75. }