LispWriter.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /**
  2. * From supertux/tools/tilemanager
  3. */
  4. using System;
  5. using System.IO;
  6. using System.Collections;
  7. using System.Globalization;
  8. public class LispWriter {
  9. private TextWriter stream;
  10. private int IndentDepth;
  11. private Stack lists = new Stack();
  12. public LispWriter(TextWriter stream) {
  13. this.stream = stream;
  14. }
  15. public void WriteComment(string comment) {
  16. stream.WriteLine("; " + comment);
  17. }
  18. public void StartList(string name) {
  19. indent();
  20. stream.WriteLine("(" + name);
  21. IndentDepth += 2;
  22. lists.Push(name);
  23. }
  24. public void EndList(string name) {
  25. if(lists.Count == 0)
  26. throw new Exception("Trying to close list while none is open");
  27. string back = (string) lists.Pop();
  28. if(name != back)
  29. throw new Exception(
  30. String.Format("Trying to close {0} which is not open", name));
  31. IndentDepth -= 2;
  32. indent();
  33. stream.WriteLine(")");
  34. }
  35. public void Write(string name, object value) {
  36. indent();
  37. stream.Write("(" + name);
  38. if(value is string) {
  39. stream.Write(" \"" + value.ToString() + "\"");
  40. } else if(value is IEnumerable) {
  41. foreach(object o in (IEnumerable) value) {
  42. stream.Write(" ");
  43. WriteValue(o);
  44. }
  45. } else {
  46. stream.Write(" ");
  47. WriteValue(value);
  48. }
  49. stream.WriteLine(")");
  50. }
  51. private void WriteValue(object val) {
  52. if(val is bool) {
  53. stream.Write((bool) val ? "#t" : "#f");
  54. } else if(val is int) {
  55. stream.Write(val.ToString());
  56. } else if (val is float) {
  57. stream.Write(((float)val).ToString(new CultureInfo("en-US")));
  58. } else {
  59. stream.Write("\"" + val.ToString() + "\"");
  60. }
  61. }
  62. public void WriteVerbatimLine(string line) {
  63. indent();
  64. stream.WriteLine(line);
  65. }
  66. private void indent() {
  67. for(int i = 0; i < IndentDepth; ++i)
  68. stream.Write(" ");
  69. }
  70. }