Newer
Older
TheVengeance-Project-IADE-Unity2D / Assets / Ink / InkLibs / InkCompiler / InkParser / CommentEliminator.cs
  1. namespace Ink
  2. {
  3. /// <summary>
  4. /// Pre-pass before main ink parser runs. It actually performs two main tasks:
  5. /// - comment elimination to simplify the parse rules in the main parser
  6. /// - Conversion of Windows line endings (\r\n) to the simpler Unix style (\n), so
  7. /// we don't have to worry about them later.
  8. /// </summary>
  9. public class CommentEliminator : StringParser
  10. {
  11. public CommentEliminator (string input) : base(input)
  12. {
  13. }
  14. public string Process()
  15. {
  16. // Make both comments and non-comments optional to handle trivial empty file case (or *only* comments)
  17. var stringList = Interleave<string>(Optional (CommentsAndNewlines), Optional(MainInk));
  18. if (stringList != null) {
  19. return string.Join("", stringList.ToArray());
  20. } else {
  21. return null;
  22. }
  23. }
  24. string MainInk()
  25. {
  26. return ParseUntil (CommentsAndNewlines, _commentOrNewlineStartCharacter, null);
  27. }
  28. string CommentsAndNewlines()
  29. {
  30. var newlines = Interleave<string> (Optional (ParseNewline), Optional (ParseSingleComment));
  31. if (newlines != null) {
  32. return string.Join ("", newlines.ToArray());
  33. } else {
  34. return null;
  35. }
  36. }
  37. // Valid comments always return either an empty string or pure newlines,
  38. // which we want to keep so that line numbers stay the same
  39. string ParseSingleComment()
  40. {
  41. return (string) OneOf (EndOfLineComment, BlockComment);
  42. }
  43. string EndOfLineComment()
  44. {
  45. if (ParseString ("//") == null) {
  46. return null;
  47. }
  48. ParseUntilCharactersFromCharSet (_newlineCharacters);
  49. return "";
  50. }
  51. string BlockComment()
  52. {
  53. if (ParseString ("/*") == null) {
  54. return null;
  55. }
  56. int startLineIndex = lineIndex;
  57. var commentResult = ParseUntil (String("*/"), _commentBlockEndCharacter, null);
  58. if (!endOfInput) {
  59. ParseString ("*/");
  60. }
  61. // Count the number of lines that were inside the block, and replicate them as newlines
  62. // so that the line indexing still works from the original source
  63. if (commentResult != null) {
  64. return new string ('\n', lineIndex - startLineIndex);
  65. }
  66. // No comment at all
  67. else {
  68. return null;
  69. }
  70. }
  71. CharacterSet _commentOrNewlineStartCharacter = new CharacterSet ("/\r\n");
  72. CharacterSet _commentBlockEndCharacter = new CharacterSet("*");
  73. CharacterSet _newlineCharacters = new CharacterSet ("\n\r");
  74. }
  75. }