util.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. // SExp - A S-Expression Parser for C++
  2. // Copyright (C) 2006 Matthias Braun <matze@braunis.de>
  3. // 2015 Ingo Ruhnke <grumbel@gmail.com>
  4. //
  5. // This program is free software: you can redistribute it and/or modify
  6. // it under the terms of the GNU General Public License as published by
  7. // the Free Software Foundation, either version 3 of the License, or
  8. // (at your option) any later version.
  9. //
  10. // This program is distributed in the hope that it will be useful,
  11. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. // GNU General Public License for more details.
  14. //
  15. // You should have received a copy of the GNU General Public License
  16. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. #include "sexp/util.hpp"
  18. #include <sstream>
  19. #include <stdexcept>
  20. #include "sexp/io.hpp"
  21. namespace sexp {
  22. bool
  23. is_list(Value const& sx)
  24. {
  25. if (sx.is_nil())
  26. {
  27. return true;
  28. }
  29. else if (sx.is_cons())
  30. {
  31. return is_list(sx.get_cdr());
  32. }
  33. else
  34. {
  35. return false;
  36. }
  37. }
  38. int
  39. list_length(Value const& sx)
  40. {
  41. if (sx.is_nil())
  42. {
  43. return 0;
  44. }
  45. else if (sx.is_cons())
  46. {
  47. return 1 + list_length(sx.get_cdr());
  48. }
  49. else
  50. {
  51. // silently ignoring malformed list content
  52. return 0;
  53. }
  54. }
  55. Value const&
  56. list_ref(Value const& sx, int index)
  57. {
  58. if (index == 0)
  59. {
  60. return sx.get_car();
  61. }
  62. else
  63. {
  64. return list_ref(sx.get_cdr(), index - 1);
  65. }
  66. }
  67. Value const&
  68. assoc_ref(Value const& sx, std::string const& key)
  69. {
  70. if (sx.is_nil())
  71. {
  72. return Value::nil_ref();
  73. }
  74. else if (sx.is_cons())
  75. {
  76. Value const& pair = sx.get_car();
  77. if (pair.is_cons() &&
  78. pair.get_car().is_symbol() &&
  79. pair.get_car().as_string() == key)
  80. {
  81. return pair.get_cdr();
  82. }
  83. else
  84. {
  85. return assoc_ref(sx.get_cdr(), key);
  86. }
  87. }
  88. else
  89. {
  90. std::ostringstream msg;
  91. msg << "malformed input to sexp::assoc_ref(): sx:\"" << sx << "\" key:\"" << key << "\"";
  92. throw std::runtime_error(msg.str());
  93. }
  94. }
  95. } // namespace sexp
  96. /* EOF */