IdentifierParser.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using System.Globalization;
  3. namespace Avalonia.Utilities
  4. {
  5. #if !BUILDTASK
  6. public
  7. #endif
  8. static class IdentifierParser
  9. {
  10. public static ReadOnlySpan<char> ParseIdentifier(this scoped ref CharacterReader r)
  11. {
  12. if (IsValidIdentifierStart(r.Peek))
  13. {
  14. return r.TakeWhile(c => IsValidIdentifierChar(c));
  15. }
  16. else
  17. {
  18. return ReadOnlySpan<char>.Empty;
  19. }
  20. }
  21. private static bool IsValidIdentifierStart(char c)
  22. {
  23. return char.IsLetter(c) || c == '_';
  24. }
  25. private static bool IsValidIdentifierChar(char c)
  26. {
  27. if (IsValidIdentifierStart(c))
  28. {
  29. return true;
  30. }
  31. else
  32. {
  33. var cat = CharUnicodeInfo.GetUnicodeCategory(c);
  34. return cat == UnicodeCategory.NonSpacingMark ||
  35. cat == UnicodeCategory.SpacingCombiningMark ||
  36. cat == UnicodeCategory.ConnectorPunctuation ||
  37. cat == UnicodeCategory.Format ||
  38. cat == UnicodeCategory.DecimalDigitNumber;
  39. }
  40. }
  41. }
  42. }