CodeEmitUtils.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace SharpGLTF.CodeGen
  6. {
  7. /// <summary>
  8. /// Text processing extensions to facilitate source code emission.
  9. /// </summary>
  10. static class CodeEmitUtils
  11. {
  12. public static string Indent(this string text, int indent)
  13. {
  14. while (indent > 0) { text = $"\t{text}"; --indent; }
  15. return text;
  16. }
  17. public static void EmitLine(this StringBuilder sb, int indent, string text)
  18. {
  19. text = text.Indent(indent);
  20. sb.AppendLine(text);
  21. }
  22. public static void EmitBlock(this StringBuilder sb, int indent, string body)
  23. {
  24. sb.EmitLine(indent, "{");
  25. var lines = body.Split(new[] { "\r\n", "\r", "\n" },StringSplitOptions.None);
  26. foreach (var line in lines)
  27. {
  28. sb.EmitLine(indent + 1, line);
  29. }
  30. sb.EmitLine(indent, "}");
  31. }
  32. public static IEnumerable<string> AsCodeBlock(this IEnumerable<string> lines)
  33. {
  34. yield return "{";
  35. foreach (var l in lines) yield return $"\t{l}";
  36. yield return "}";
  37. }
  38. public static IEnumerable<string> Indent(this IEnumerable<string> lines, int indent)
  39. {
  40. foreach (var l in lines) yield return l.Indent(indent);
  41. }
  42. public static IEnumerable<string> EmitSummary(this string description, int indent)
  43. {
  44. if (string.IsNullOrWhiteSpace(description)) yield break;
  45. description = _ReplaceDescriptionKeywords(description);
  46. var lines = description
  47. .Split(" ")
  48. .Select(item => item.Trim())
  49. .ToList();
  50. yield return "/// <summary>".Indent(indent);
  51. foreach(var l in lines) yield return $"/// {l}";
  52. yield return "/// </summary>".Indent(indent);
  53. }
  54. private static string _ReplaceDescriptionKeywords(string description)
  55. {
  56. while(true)
  57. {
  58. var (start, len) = _FindDescriptionKeyword(description);
  59. if (start < 0) return description;
  60. var block = description.Substring(start , len);
  61. var name = block.Substring(2, block.Length - 4);
  62. description = description.Replace(block, $"<see cref=\"{name}\"/>", StringComparison.Ordinal);
  63. }
  64. }
  65. private static (int start,int len) _FindDescriptionKeyword(string description)
  66. {
  67. int start = description.IndexOf("`\"");
  68. var end = description.IndexOf("\"`");
  69. if (start < 0 || end < 0 || start >= end) return (-1, -1);
  70. return (start, end - start + 2);
  71. }
  72. }
  73. }