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