LispWriter.cs 1.9 KB

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