PageRenderTime 87ms CodeModel.GetById 37ms RepoModel.GetById 1ms app.codeStats 0ms

/synopsis-0.12/src/Synopsis/PTree/Writer.cc

#
C++ | 84 lines | 69 code | 9 blank | 6 comment | 13 complexity | 88a4f98b6711fe7ee23deeb9adc04b95 MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0
  1. //
  2. // Copyright (C) 2004 Stefan Seefeld
  3. // All rights reserved.
  4. // Licensed to the public under the terms of the GNU LGPL (>= 2),
  5. // see the file COPYING for details.
  6. //
  7. #include <Synopsis/PTree/Writer.hh>
  8. #include <stdexcept>
  9. using namespace Synopsis;
  10. using namespace PTree;
  11. Writer::Writer(std::ostream &os)
  12. : my_os(os),
  13. my_indent(0),
  14. my_lines(0)
  15. {
  16. }
  17. unsigned long Writer::write(Node const *n)
  18. {
  19. const_cast<Node *>(n)->accept(this);
  20. unsigned long lines = my_lines;
  21. my_lines = 0;
  22. return lines;
  23. }
  24. void Writer::visit(Atom *a)
  25. {
  26. const char *ptr = a->position();
  27. size_t len = a->length();
  28. while(len-- > 0)
  29. {
  30. char c = *ptr++;
  31. if(c == '\n') newline();
  32. else my_os.put(c);
  33. }
  34. }
  35. void Writer::visit(List *l)
  36. {
  37. Node *p = l;
  38. while(true)
  39. {
  40. Node *head = p->car();
  41. if(head != 0) head->accept(this);
  42. p = p->cdr();
  43. if(!p) break;
  44. else if(p->is_atom())
  45. throw std::runtime_error("Writer::visit(List *): not list");
  46. else my_os.put(' ');
  47. }
  48. }
  49. void Writer::visit(Brace *l)
  50. {
  51. my_os << '{';
  52. ++my_indent;
  53. Node *p = cadr(l);
  54. while(p)
  55. {
  56. if(p->is_atom())
  57. throw std::runtime_error("Writer::visit(Brace *): non list");
  58. else
  59. {
  60. newline();
  61. Node *q = p->car();
  62. p = p->cdr();
  63. if(q) q->accept(this);
  64. }
  65. }
  66. --my_indent;
  67. newline();
  68. my_os << '}';
  69. }
  70. void Writer::newline()
  71. {
  72. my_os.put('\n');
  73. for(size_t i = 0; i != my_indent; ++i) my_os.put(' ');
  74. ++my_lines;
  75. }