<commit_before>#include "parser.h"
#include "color.h"
#include "construct.h"
#include "scanner.h"
#include "stream.h"

#include <iostream>

#ifdef __DEBUG__
#define DEBUG(X) X
#else
#define DEBUG(X)
#endif

static std::string make_expected(char expected) {
  std::string s(1, '\''); s.push_back(expected); s.push_back('\'');
  return s;
}

static std::string make_expected(std::string expected) {
  std::string s(1, '\"'); s.append(expected); s.push_back('\"');
  return s;
}

parser::error::error(char expected, char got, stream::location loc)
  : expected_(make_expected(expected)), got_(got), loc_(loc) {
}
parser::error::error(scanner expected, char got, stream::location loc)
  : expected_(expected.get_id()), got_(got), loc_(loc) {
}
parser::error::error(std::string expected, char got, stream::location loc)
  : expected_(make_expected(expected)), got_(got), loc_(loc) {
}

typedef std::pair<parser, construct*> parser_pair_ty;

template <typename T>
parser& operator>>(parser &prs, T run) {
  // Stop parsing if the stream is invalid.
  if (!prs)
    return prs;

  stream& s = prs.get_stream();
  stream::location before = s.get_loc();

  parser_pair_ty pair = run(prs);
  if ((prs = pair.first) && before != s.get_loc())
    // Clear all the errors located before whatever we just parsed.
    prs.clear_errors(s.get_loc());
  if (pair.second)
    prs.add_construct(pair.second);
  return prs;
}

parser& operator<<(parser &prs, parser new_prs) {
  return prs = new_prs;
}

static std::function<parser_pair_ty(parser)> parse_char(char c) {
  return [c](parser prs) {
    DEBUG(std::cout << "parse_char: " << c << "\n");
    stream &s = prs.get_stream();
    char peek = s.peek();
    if (peek == c) {
      s.next();
    } else {
      prs.add_error(parser::error(c, peek, s.get_loc()));
      prs.set_valid(false);
    }
    return parser_pair_ty(prs, nullptr);
  };
}

static std::function<parser_pair_ty(parser)> parse_string(const char *str) {
  return [str](parser prs) {
    DEBUG(std::cout << "parse_string: " << str << "\n");
    stream &s = prs.get_stream();
    const char *ostr = str;
    while (*ostr && s.peek() == *ostr) { ++ostr; s.next(); }
    if (*ostr) {
      prs.add_error(parser::error(str, s.peek(), s.get_loc()));
      prs.set_valid(false);
    }
    return parser_pair_ty(prs, nullptr);
  };
}

static std::string parse_many(parser& prs, scanner scn) {
  DEBUG(std::cout << "parse_many: " << scn.get_id() << "\n");
  stream &s = prs.get_stream();
  std::string lexeme;
  while (scn(s.peek()))
    lexeme.push_back(s.next());
  if (lexeme.empty()) {
    prs.add_error(parser::error(scn, s.peek(), s.get_loc()));
    prs.set_valid(false);
  }
  return lexeme;
}

template<typename T>
static std::function<parser_pair_ty(parser)> maybe(T run) {
  return [run](parser prs) {
    auto copy_prs = prs;
    if (prs >> run)
      return parser_pair_ty(prs, nullptr);
     return parser_pair_ty(copy_prs, nullptr);
  };
}

template<typename T, typename U>
static std::function<parser_pair_ty(parser)> compose(T first, U second) {
  return [first, second](parser prs) {
    prs >> first >> second;
    return parser_pair_ty(prs, nullptr);
  };
}

template<typename T>
static bool do_try(parser &prs, T run) {
  auto copy_prs = prs;
  if (prs >> run)
    return true;
  copy_prs.merge_errors(prs);
  prs = copy_prs;
  return false;
}

static parser_pair_ty parse_spaces(parser prs) {
  DEBUG(std::cout << "parse_spaces\n");
  auto spaces = parse_many(prs, scanner::is_space);
  return parser_pair_ty(prs, nullptr);
}

static parser_pair_ty parse_maybe_spaces(parser prs) {
  DEBUG(std::cout << "parse_maybe_spaces\n");
  stream &s = prs.get_stream();
  while (scanner::is_space(s.peek())) s.next();
  return parser_pair_ty(prs, nullptr);
}

static parser_pair_ty parse_eof(parser prs) {
  DEBUG(std::cout << "parse_eof\n");
  stream &s = prs.get_stream();
  prs.set_valid(s.peek() == '\0');
  return parser_pair_ty(prs, nullptr);
}

static parser parse_comma_sep(parser &prs,
                              parser_pair_ty (*run)(parser)) {
  DEBUG(std::cout << "parse_comma_sep\n");
  if (prs >> run)
    while (do_try(prs, compose(parse_maybe_spaces, parse_char(','))))
      if (!do_try(prs, compose(parse_maybe_spaces, run)))
        break;
  return prs;
}

static parser parse_space_sep(parser &prs,
                              parser_pair_ty (*run)(parser)) {
  DEBUG(std::cout << "parse_space_sep\n");
  if (prs >> run)
    while (do_try(prs, compose(parse_spaces, run)));
  return prs;
}

static parser_pair_ty parse_id(parser prs) {
  DEBUG(std::cout << "parse_id\n");
  auto id = parse_many(prs, scanner::is_ident);
  return parser_pair_ty(prs, !prs ? nullptr : new construct_id(id));
}

static parser_pair_ty parse_word(parser prs) {
  DEBUG(std::cout << "parse_word\n");
  auto word = parse_many(prs, scanner::is_word);
  prs.set_valid(prs.is_valid() && word != ";");
  return parser_pair_ty(prs, !prs ? nullptr : new construct_word(word));
}

static parser_pair_ty parse_type_id(parser prs) {
  DEBUG(std::cout << "parse_type_id\n");
  auto id = parse_many(prs, scanner::is_ident);
  return parser_pair_ty(prs, !prs ? nullptr : new construct_type_id(id));
}

static parser_pair_ty parse_type_compound(parser prs) {
  DEBUG(std::cout << "parse_type_compound\n");
  auto ret_prs = parse_space_sep(prs, parse_type_id);
  if (ret_prs) {
    auto list = ret_prs.gather_constructs<construct_type_id>();
    return parser_pair_ty(ret_prs, new construct_type_compound(list));
  }
  return parser_pair_ty(ret_prs, nullptr);
}

static parser_pair_ty parse_type_list(parser prs) {
  DEBUG(std::cout << "parse_type_list\n");
  auto ret_prs = parse_comma_sep(prs, parse_type_compound);
  if (ret_prs) {
    auto list = ret_prs.gather_constructs<construct_type_compound>();
    return parser_pair_ty(ret_prs, new construct_type_list(list));
  }
  return parser_pair_ty(ret_prs, nullptr);
}

static parser_pair_ty parse_type_fn(parser prs) {
  if (prs >> parse_char('(')
          >> parse_maybe_spaces >> parse_type_list
          >> parse_maybe_spaces >> parse_string("->")
          >> parse_maybe_spaces >> maybe(parse_type_compound)
          >> parse_maybe_spaces >> parse_char(')')) {
    construct_type_compound *out = prs.get_construct<construct_type_compound>();
    if (!out) out = new construct_type_compound();
    construct_type_list *inp = prs.get_construct<construct_type_list>();
    return parser_pair_ty(prs, new construct_type_fn(inp, out));
  }
  return parser_pair_ty(prs, nullptr);
}

static parser_pair_ty parse_arg_id(parser prs) {
  DEBUG(std::cout << "parse_arg_id\n");
  if (prs >> parse_id) {
    construct_id *cid = prs.get_construct<construct_id>();
    construct_arg_id *ctid = new construct_arg_id(cid->get_str());
    return parser_pair_ty(prs, ctid);
  }
  return parser_pair_ty(prs, nullptr);
}

static parser_pair_ty parse_arg_compound(parser prs) {
  DEBUG(std::cout << "parse_arg_compound\n");
  auto ret_prs = parse_space_sep(prs, parse_arg_id);
  if (ret_prs) {
    auto list = ret_prs.gather_constructs<construct_arg_id>();
    return parser_pair_ty(ret_prs, new construct_arg_compound(list));
  }
  return parser_pair_ty(ret_prs, nullptr);
}

static parser_pair_ty parse_arg_list(parser prs) {
  DEBUG(std::cout << "parse_arg_list\n");
  auto ret_prs = parse_comma_sep(prs, parse_arg_compound);
  if (ret_prs) {
    auto list = ret_prs.gather_constructs<construct_arg_compound>();
    return parser_pair_ty(ret_prs, new construct_arg_list(list));
  }
  return parser_pair_ty(ret_prs, nullptr);
}

static parser_pair_ty parse_args(parser prs) {
  DEBUG(std::cout << "parse_args\n");
  if (prs >> parse_char('(') >> parse_maybe_spaces >> parse_arg_list
          >> parse_maybe_spaces >> parse_char(')')) {
    return parser_pair_ty(prs, prs.get_construct<construct_arg_list>());
  }
  return parser_pair_ty(prs, nullptr);
}

static parser_pair_ty parse_body(parser prs) {
  DEBUG(std::cout << "parse_body\n");
  auto ret_prs = parse_space_sep(prs, parse_word);
  if (ret_prs) {
    auto list = ret_prs.gather_constructs<construct_word>();
    return parser_pair_ty(ret_prs, new construct_body(list));
  }
  return parser_pair_ty(ret_prs, nullptr);
}

static parser_pair_ty parse_def(parser prs) {
  DEBUG(std::cout << "parse_def\n");
  if (!(prs >> parse_word
            >> parse_spaces       >> parse_char(':')
            >> parse_spaces       >> parse_type_fn
            >> maybe(compose(parse_spaces, parse_args))
            >> parse_maybe_spaces >> parse_string("->")
            >> maybe(compose(parse_maybe_spaces, parse_body))))
    return parser_pair_ty(prs, nullptr);

  // With this, unterminated definitions are not incorrectly shown as being
  // on the line after the actual definition. This also avoids unterminated
  // definitions generating two errors each.
  auto errors = prs.get_errors();
  if (!do_try(prs, compose(parse_spaces, parse_char(';')))) {
    prs.set_errors(errors);
    prs.set_valid(false);
  }

  if (prs) {
    auto body = prs.get_construct<construct_body>();
    if (!body) body = new construct_body();
    auto args = prs.get_construct<construct_arg_list>();
    if (!args) args = new construct_arg_list();
    auto type = prs.get_construct<construct_type_fn>();
    return parser_pair_ty(prs, new construct_def(type, args, body));
  }
  return parser_pair_ty(prs, nullptr);
}

void parser::add_error(error err) {
  errors_.insert(err);
}

void parser::merge_errors(parser &prs) {
  auto errors = prs.errors_;
  errors_.insert(errors.begin(), errors.end());
}

void parser::clear_errors() {
  errors_.clear();
}

void parser::clear_errors(stream::location loc) {
  auto it = errors_.begin(), e = errors_.end();
  while (it != e)
    if (it->get_loc() < loc)
      it = errors_.erase(it);
    else
      ++it;
}

void parser::print_error_loc(std::ostream &os, stream::location loc) const {
  os << stream_.get_line(loc.get_line()) << "\n"
     << std::string(loc.get_col() > 1 ? loc.get_col() - 1 : 0, ' ')
     << "^" << "\n";
}

void parser::print_errors(std::ostream &os) const {
  auto it = errors_.begin(), e = errors_.end();
  stream::location loc = it->get_loc();
  os << stream_.get_filename() << ":" << loc.get_line() << ":"
     << loc.get_col() << ": " << color::code::red << "error:"
     << color::code::reset << " expected ";
  if (errors_.size() == 1) {
    os << it->get_expected();
  } else if (errors_.size() == 2) {
    os << it->get_expected() << " or " << (++it)->get_expected();
  } else {
    for (; it != std::prev(e); ++it)
      os << it->get_expected() << ", ";
    os << "or " << it->get_expected();
  }
  os << ", got '" << it->get_got() << "'" << "\n";
  print_error_loc(os, loc);
}

void parser::print_error_unterminated(std::ostream &os,
                                      stream::location loc) const {
  os << stream_.get_filename() << ":" << loc.get_line() << ":"
     << loc.get_col() << ": " << color::code::red << "error:"
     << color::code::reset << " unterminated definition" << "\n";
  print_error_loc(os, loc);
}

void parser::add_construct(construct *c) {
  cons_.push(c);
}

void parser::advance() {
  stream::location loc = stream_.get_loc();
  for (; !(*this << parser(stream_) >> parse_maybe_spaces >> parse_eof);
       stream_.set_loc(loc), stream_.next(), loc = stream_.get_loc()) {

    stream_.set_loc(loc);
    if (*this << parser(stream_) >> parse_spaces >> parse_char(';')
              >> parse_spaces)
      return;

    stream_.set_loc(loc);
    if (*this << parser(stream_) >> parse_spaces >> parse_word
              >> parse_spaces >> parse_char(':') >> parse_spaces) {
      stream_.set_loc(loc);
      print_error_unterminated(std::cerr, loc);
      return;
    }
  }
  print_error_unterminated(std::cerr, loc);
}

bool parser::parse() {
  bool has_error = false;
  while (*this >> parse_maybe_spaces && stream_.peek() != '\0') {
    if (*this >> parse_def) {
      DEBUG(std::cout << "parse_def: " << *get_construct<construct_def>()
                      << "\n");
      continue;
    }
    has_error = true;
    if (!errors_.empty()) {
      print_errors(std::cerr);
      clear_errors();
    }
    advance();
  }
  return !has_error;
}

<commit_msg>parse_{space,comma}_sep now return references<commit_after>#include "parser.h"
#include "color.h"
#include "construct.h"
#include "scanner.h"
#include "stream.h"

#include <iostream>

#ifdef __DEBUG__
#define DEBUG(X) X
#else
#define DEBUG(X)
#endif

static std::string make_expected(char expected) {
  std::string s(1, '\''); s.push_back(expected); s.push_back('\'');
  return s;
}

static std::string make_expected(std::string expected) {
  std::string s(1, '\"'); s.append(expected); s.push_back('\"');
  return s;
}

parser::error::error(char expected, char got, stream::location loc)
  : expected_(make_expected(expected)), got_(got), loc_(loc) {
}
parser::error::error(scanner expected, char got, stream::location loc)
  : expected_(expected.get_id()), got_(got), loc_(loc) {
}
parser::error::error(std::string expected, char got, stream::location loc)
  : expected_(make_expected(expected)), got_(got), loc_(loc) {
}

typedef std::pair<parser, construct*> parser_pair_ty;

template <typename T>
parser& operator>>(parser &prs, T run) {
  // Stop parsing if the stream is invalid.
  if (!prs)
    return prs;

  stream& s = prs.get_stream();
  stream::location before = s.get_loc();

  parser_pair_ty pair = run(prs);
  if ((prs = pair.first) && before != s.get_loc())
    // Clear all the errors located before whatever we just parsed.
    prs.clear_errors(s.get_loc());
  if (pair.second)
    prs.add_construct(pair.second);
  return prs;
}

parser& operator<<(parser &prs, parser new_prs) {
  return prs = new_prs;
}

static std::function<parser_pair_ty(parser)> parse_char(char c) {
  return [c](parser prs) {
    DEBUG(std::cout << "parse_char: " << c << "\n");
    stream &s = prs.get_stream();
    char peek = s.peek();
    if (peek == c) {
      s.next();
    } else {
      prs.add_error(parser::error(c, peek, s.get_loc()));
      prs.set_valid(false);
    }
    return parser_pair_ty(prs, nullptr);
  };
}

static std::function<parser_pair_ty(parser)> parse_string(const char *str) {
  return [str](parser prs) {
    DEBUG(std::cout << "parse_string: " << str << "\n");
    stream &s = prs.get_stream();
    const char *ostr = str;
    while (*ostr && s.peek() == *ostr) { ++ostr; s.next(); }
    if (*ostr) {
      prs.add_error(parser::error(str, s.peek(), s.get_loc()));
      prs.set_valid(false);
    }
    return parser_pair_ty(prs, nullptr);
  };
}

static std::string parse_many(parser& prs, scanner scn) {
  DEBUG(std::cout << "parse_many: " << scn.get_id() << "\n");
  stream &s = prs.get_stream();
  std::string lexeme;
  while (scn(s.peek()))
    lexeme.push_back(s.next());
  if (lexeme.empty()) {
    prs.add_error(parser::error(scn, s.peek(), s.get_loc()));
    prs.set_valid(false);
  }
  return lexeme;
}

template<typename T>
static std::function<parser_pair_ty(parser)> maybe(T run) {
  return [run](parser prs) {
    auto copy_prs = prs;
    if (prs >> run)
      return parser_pair_ty(prs, nullptr);
     return parser_pair_ty(copy_prs, nullptr);
  };
}

template<typename T, typename U>
static std::function<parser_pair_ty(parser)> compose(T first, U second) {
  return [first, second](parser prs) {
    prs >> first >> second;
    return parser_pair_ty(prs, nullptr);
  };
}

template<typename T>
static bool do_try(parser &prs, T run) {
  auto copy_prs = prs;
  if (prs >> run)
    return true;
  copy_prs.merge_errors(prs);
  prs = copy_prs;
  return false;
}

static parser_pair_ty parse_spaces(parser prs) {
  DEBUG(std::cout << "parse_spaces\n");
  auto spaces = parse_many(prs, scanner::is_space);
  return parser_pair_ty(prs, nullptr);
}

static parser_pair_ty parse_maybe_spaces(parser prs) {
  DEBUG(std::cout << "parse_maybe_spaces\n");
  stream &s = prs.get_stream();
  while (scanner::is_space(s.peek())) s.next();
  return parser_pair_ty(prs, nullptr);
}

static parser_pair_ty parse_eof(parser prs) {
  DEBUG(std::cout << "parse_eof\n");
  stream &s = prs.get_stream();
  prs.set_valid(s.peek() == '\0');
  return parser_pair_ty(prs, nullptr);
}

static parser &parse_comma_sep(parser &prs,
                               parser_pair_ty (*run)(parser)) {
  DEBUG(std::cout << "parse_comma_sep\n");
  if (prs >> run)
    while (do_try(prs, compose(parse_maybe_spaces, parse_char(','))))
      if (!do_try(prs, compose(parse_maybe_spaces, run)))
        break;
  return prs;
}

static parser& parse_space_sep(parser &prs,
                               parser_pair_ty (*run)(parser)) {
  DEBUG(std::cout << "parse_space_sep\n");
  if (prs >> run)
    while (do_try(prs, compose(parse_spaces, run)));
  return prs;
}

static parser_pair_ty parse_id(parser prs) {
  DEBUG(std::cout << "parse_id\n");
  auto id = parse_many(prs, scanner::is_ident);
  return parser_pair_ty(prs, !prs ? nullptr : new construct_id(id));
}

static parser_pair_ty parse_word(parser prs) {
  DEBUG(std::cout << "parse_word\n");
  auto word = parse_many(prs, scanner::is_word);
  prs.set_valid(prs.is_valid() && word != ";");
  return parser_pair_ty(prs, !prs ? nullptr : new construct_word(word));
}

static parser_pair_ty parse_type_id(parser prs) {
  DEBUG(std::cout << "parse_type_id\n");
  auto id = parse_many(prs, scanner::is_ident);
  return parser_pair_ty(prs, !prs ? nullptr : new construct_type_id(id));
}

static parser_pair_ty parse_type_compound(parser prs) {
  DEBUG(std::cout << "parse_type_compound\n");
  if (parse_space_sep(prs, parse_type_id)) {
    auto list = prs.gather_constructs<construct_type_id>();
    return parser_pair_ty(prs, new construct_type_compound(list));
  }
  return parser_pair_ty(prs, nullptr);
}

static parser_pair_ty parse_type_list(parser prs) {
  DEBUG(std::cout << "parse_type_list\n");
  if (parse_comma_sep(prs, parse_type_compound)) {
    auto list = prs.gather_constructs<construct_type_compound>();
    return parser_pair_ty(prs, new construct_type_list(list));
  }
  return parser_pair_ty(prs, nullptr);
}

static parser_pair_ty parse_type_fn(parser prs) {
  if (prs >> parse_char('(')
          >> parse_maybe_spaces >> parse_type_list
          >> parse_maybe_spaces >> parse_string("->")
          >> parse_maybe_spaces >> maybe(parse_type_compound)
          >> parse_maybe_spaces >> parse_char(')')) {
    construct_type_compound *out = prs.get_construct<construct_type_compound>();
    if (!out) out = new construct_type_compound();
    construct_type_list *inp = prs.get_construct<construct_type_list>();
    return parser_pair_ty(prs, new construct_type_fn(inp, out));
  }
  return parser_pair_ty(prs, nullptr);
}

static parser_pair_ty parse_arg_id(parser prs) {
  DEBUG(std::cout << "parse_arg_id\n");
  if (prs >> parse_id) {
    construct_id *cid = prs.get_construct<construct_id>();
    construct_arg_id *ctid = new construct_arg_id(cid->get_str());
    return parser_pair_ty(prs, ctid);
  }
  return parser_pair_ty(prs, nullptr);
}

static parser_pair_ty parse_arg_compound(parser prs) {
  DEBUG(std::cout << "parse_arg_compound\n");
  if (parse_space_sep(prs, parse_arg_id)) {
    auto list = prs.gather_constructs<construct_arg_id>();
    return parser_pair_ty(prs, new construct_arg_compound(list));
  }
  return parser_pair_ty(prs, nullptr);
}

static parser_pair_ty parse_arg_list(parser prs) {
  DEBUG(std::cout << "parse_arg_list\n");
  if (parse_comma_sep(prs, parse_arg_compound)) {
    auto list = prs.gather_constructs<construct_arg_compound>();
    return parser_pair_ty(prs, new construct_arg_list(list));
  }
  return parser_pair_ty(prs, nullptr);
}

static parser_pair_ty parse_args(parser prs) {
  DEBUG(std::cout << "parse_args\n");
  if (prs >> parse_char('(') >> parse_maybe_spaces >> parse_arg_list
          >> parse_maybe_spaces >> parse_char(')')) {
    return parser_pair_ty(prs, prs.get_construct<construct_arg_list>());
  }
  return parser_pair_ty(prs, nullptr);
}

static parser_pair_ty parse_body(parser prs) {
  DEBUG(std::cout << "parse_body\n");
  if (parse_space_sep(prs, parse_word)) {
    auto list = prs.gather_constructs<construct_word>();
    return parser_pair_ty(prs, new construct_body(list));
  }
  return parser_pair_ty(prs, nullptr);
}

static parser_pair_ty parse_def(parser prs) {
  DEBUG(std::cout << "parse_def\n");
  if (!(prs >> parse_word
            >> parse_spaces       >> parse_char(':')
            >> parse_spaces       >> parse_type_fn
            >> maybe(compose(parse_spaces, parse_args))
            >> parse_maybe_spaces >> parse_string("->")
            >> maybe(compose(parse_maybe_spaces, parse_body))))
    return parser_pair_ty(prs, nullptr);

  // With this, unterminated definitions are not incorrectly shown as being
  // on the line after the actual definition. This also avoids unterminated
  // definitions generating two errors each.
  auto errors = prs.get_errors();
  if (!do_try(prs, compose(parse_spaces, parse_char(';')))) {
    prs.set_errors(errors);
    prs.set_valid(false);
  }

  if (prs) {
    auto body = prs.get_construct<construct_body>();
    if (!body) body = new construct_body();
    auto args = prs.get_construct<construct_arg_list>();
    if (!args) args = new construct_arg_list();
    auto type = prs.get_construct<construct_type_fn>();
    return parser_pair_ty(prs, new construct_def(type, args, body));
  }
  return parser_pair_ty(prs, nullptr);
}

void parser::add_error(error err) {
  errors_.insert(err);
}

void parser::merge_errors(parser &prs) {
  auto errors = prs.errors_;
  errors_.insert(errors.begin(), errors.end());
}

void parser::clear_errors() {
  errors_.clear();
}

void parser::clear_errors(stream::location loc) {
  auto it = errors_.begin(), e = errors_.end();
  while (it != e)
    if (it->get_loc() < loc)
      it = errors_.erase(it);
    else
      ++it;
}

void parser::print_error_loc(std::ostream &os, stream::location loc) const {
  os << stream_.get_line(loc.get_line()) << "\n"
     << std::string(loc.get_col() > 1 ? loc.get_col() - 1 : 0, ' ')
     << "^" << "\n";
}

void parser::print_errors(std::ostream &os) const {
  auto it = errors_.begin(), e = errors_.end();
  stream::location loc = it->get_loc();
  os << stream_.get_filename() << ":" << loc.get_line() << ":"
     << loc.get_col() << ": " << color::code::red << "error:"
     << color::code::reset << " expected ";
  if (errors_.size() == 1) {
    os << it->get_expected();
  } else if (errors_.size() == 2) {
    os << it->get_expected() << " or " << (++it)->get_expected();
  } else {
    for (; it != std::prev(e); ++it)
      os << it->get_expected() << ", ";
    os << "or " << it->get_expected();
  }
  os << ", got '" << it->get_got() << "'" << "\n";
  print_error_loc(os, loc);
}

void parser::print_error_unterminated(std::ostream &os,
                                      stream::location loc) const {
  os << stream_.get_filename() << ":" << loc.get_line() << ":"
     << loc.get_col() << ": " << color::code::red << "error:"
     << color::code::reset << " unterminated definition" << "\n";
  print_error_loc(os, loc);
}

void parser::add_construct(construct *c) {
  cons_.push(c);
}

void parser::advance() {
  stream::location loc = stream_.get_loc();
  for (; !(*this << parser(stream_) >> parse_maybe_spaces >> parse_eof);
       stream_.set_loc(loc), stream_.next(), loc = stream_.get_loc()) {

    stream_.set_loc(loc);
    if (*this << parser(stream_) >> parse_spaces >> parse_char(';')
              >> parse_spaces)
      return;

    stream_.set_loc(loc);
    if (*this << parser(stream_) >> parse_spaces >> parse_word
              >> parse_spaces >> parse_char(':') >> parse_spaces) {
      stream_.set_loc(loc);
      print_error_unterminated(std::cerr, loc);
      return;
    }
  }
  print_error_unterminated(std::cerr, loc);
}

bool parser::parse() {
  bool has_error = false;
  while (*this >> parse_maybe_spaces && stream_.peek() != '\0') {
    if (*this >> parse_def) {
      DEBUG(std::cout << "parse_def: " << *get_construct<construct_def>()
                      << "\n");
      continue;
    }
    has_error = true;
    if (!errors_.empty()) {
      print_errors(std::cerr);
      clear_errors();
    }
    advance();
  }
  return !has_error;
}

<|endoftext|>


<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE. */

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3326
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from  3326 to 3327<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE. */

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3327
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|endoftext|>


<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE. */

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3450
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from  3450 to 3451<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE. */

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3451
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|endoftext|>


<commit_before>#include <regex>
#include <string>
#include "parser.h"

static ast_type_t identifier_type(const std::string &s)
{
    static const std::regex float_re("^-?(\\d+\\.\\d*|\\d*\\.\\d+)$");
    static const std::regex int_re("^-?\\d+$");
    if(std::regex_match(s, int_re))
        return ast_type_t::INT;
    if(std::regex_match(s, float_re))
        return ast_type_t::FLOAT;
    return ast_type_t::NAME;
}

static int skip_whitespace(std::istream &is)
{
    int c;
    while(true)
    {
        c = is.peek();
        while(c != EOF && isspace(c))
        {
            is.get();
            c = is.peek();
        }
        if(c == ';')
        {
            while(c != EOF && c != '\n')
            {
                c = is.get();
            }
        }
        else
            return c;
    }
}

std::shared_ptr<ASTNode> readObject(std::istream &is)
{
    auto o = std::make_shared<ASTNode>();
    skip_whitespace(is);
    int c = is.get();
    if(c == EOF)
        throw end_of_input("");
    if(c == ')')
        throw parse_error("Invalid syntax");
    if(c == '"')
    {
        o->type = ast_type_t::STRING;
        c = is.get();
        while(c != EOF && c != '"')
        {
            o->value.push_back(c);
            c = is.get();
        }
        if(c == EOF)
            throw parse_error("Unclosed string literal");
        return o;
    }
    if(c == '(')
    {
        o->type = ast_type_t::LIST;
        skip_whitespace(is);
        c = is.peek();
        while(c != EOF && c != ')')
        {
            o->list.push_back(readObject(is));
            c = skip_whitespace(is);
        }
        if(c == EOF)
            throw parse_error("Unclosed list literal");
        is.get();
        return o;
    }
    if(c == '\'')
    {
        auto quote = std::make_shared<ASTNode>();
        quote->type = ast_type_t::NAME;
        quote->value = "quote";
        o->type = ast_type_t::LIST;
        o->list.push_back(quote);
        o->list.push_back(readObject(is));
        return o;
    }
    o->value.push_back(c);
    c = is.peek();
    while(c != EOF && c != '(' && c != ')' && !isspace(c))
    {
        o->value.push_back(c);
        is.get();
        c = is.peek();
    }
    o->type = identifier_type(o->value);
    return o;
}<commit_msg>Разделители<commit_after>#include <regex>
#include <string>
#include "parser.h"

static ast_type_t identifier_type(const std::string &s)
{
    static const std::regex float_re("^-?(\\d+\\.\\d*|\\d*\\.\\d+)$");
    static const std::regex int_re("^-?\\d+$");
    if(std::regex_match(s, int_re))
        return ast_type_t::INT;
    if(std::regex_match(s, float_re))
        return ast_type_t::FLOAT;
    return ast_type_t::NAME;
}

static bool is_delimiter(int c)
{
    return (c == '(' || c == ')' || c == ';' || c == '"' || c == '\'' || c == '`' ||
            c == '|' || c == '[' || c == ']' || c == '{' || c == '}' || c == EOF || isspace(c));
}

static int skip_whitespace(std::istream &is)
{
    int c;
    while(true)
    {
        c = is.peek();
        while(c != EOF && isspace(c))
        {
            is.get();
            c = is.peek();
        }
        if(c == ';')
        {
            while(c != EOF && c != '\n')
            {
                c = is.get();
            }
        }
        else
            return c;
    }
}

std::shared_ptr<ASTNode> readObject(std::istream &is)
{
    auto o = std::make_shared<ASTNode>();
    skip_whitespace(is);
    int c = is.get();
    if(c == EOF)
        throw end_of_input("");
    if(c == ')')
        throw parse_error("Invalid syntax");
    if(c == '"')
    {
        o->type = ast_type_t::STRING;
        c = is.get();
        while(c != EOF && c != '"')
        {
            o->value.push_back(c);
            c = is.get();
        }
        if(c == EOF)
            throw parse_error("Unclosed string literal");
        return o;
    }
    if(c == '(')
    {
        o->type = ast_type_t::LIST;
        skip_whitespace(is);
        c = is.peek();
        while(c != EOF && c != ')')
        {
            o->list.push_back(readObject(is));
            c = skip_whitespace(is);
        }
        if(c == EOF)
            throw parse_error("Unclosed list literal");
        is.get();
        return o;
    }
    if(c == '\'')
    {
        auto quote = std::make_shared<ASTNode>();
        quote->type = ast_type_t::NAME;
        quote->value = "quote";
        o->type = ast_type_t::LIST;
        o->list.push_back(quote);
        o->list.push_back(readObject(is));
        return o;
    }
    o->value.push_back(c);
    c = is.peek();
    while(!is_delimiter(c))
    {
        o->value.push_back(c);
        is.get();
        c = is.peek();
    }
    o->type = identifier_type(o->value);
    return o;
}<|endoftext|>


<commit_before>#include "parser.hpp"

//////////////
// Includes //
#include <istream>
#include <string>
#include <vector>
#include <tuple>

#include "parsestream.hpp"
#include "streamutils.hpp"
#include "json.hpp"

//////////
// Code //

// Creating a parse exception.
ParseException::ParseException(std::string type) {
    this->type = type;
}

// Returning a string to refer to this exception.
const char* ParseException::what() const throw() {
    return ("Failed to parse a " + this->type + " piece of JSON.").c_str();
}

//// Trying to specifically parse out a JSON object.
//JValue parseJSONObject(ParseStream& ps) throw(ParseException) {
    //throw ParseException("JObject");
//}

//// Trying to specifically parse out a JSON array.
//JValue parseJSONArray(ParseStream& ps) throw(ParseException) {
    //if (str[0] == '[' && str[str.size() - 1] == ']') {
        //std::string useStr = str.substr(1, str.size() - 2);
        //if (useStr.compare("") == 0)
            //return JValue();

        //std::vector<JValue> jValues;
        //std::tuple<std::string, std::string> tup;
        //for (tup = untilChar(useStr, ','); std::get<0>(tup).compare("") != 0; tup = untilChar(std::get<1>(tup), ','))
            //jValues.push_back(parseJSON(stripWhitespace(std::get<0>(tup))));

        //return JValue(jValues);
    //}

    //throw ParseException("parseJSONArray");
//}

#include <iostream>

// Trying to specifically parse out a JSON array.
JValue parseJSONArray(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);

    if (ps.consume() == '[') {
        std::vector<JValue> values;
        while (true) {
            consumeWhitespace(ps);
            values.push_back(parseJSON(ps));
            consumeWhitespace(ps);

            char c = ps.consume();
            if (c == ']')
                break;
            else if (c != ',') {
                std::cout << "Failing thataway.\n";
                throw ParseException("parseJSONArray");
            }
        }

        return JValue(values);
    }

    throw ParseException("parseJSONArray");
}

// Trying to specifically parse out a JSON number.
JValue parseJSONNumber(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);

    std::string str;
    bool first = true;
    while (!ps.eof() && !isDelimiter(ps.peek())) {
        char c = ps.consume();

        if (first && c == '-') {
            str.push_back(c);
            first = false;
        } else if (('0' <= c && c <= '9') || c == '.')
            str.push_back(c);
        else
            throw ParseException("parseJSONNumber");
    }

    return JValue(stod(str));
}

// Trying to specifically parse out a JSON string.
JValue parseJSONString(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);
    if (ps.peek() == '"') {
        ps.consume();

        std::string str;
        while (ps.peek() != '"') {
            char c = ps.consume();
            if (c == '\n')
                throw ParseException("parseJSONString");

            if (c == '\\') {
                char c2 = ps.consume();

                switch (c2) {
                case '"':
                    str.push_back('"');
                    break;
                case '\\':
                    str.push_back('\\');
                    break;
                case '/':
                    str.push_back('/');
                case 'b':
                    str.push_back('\b');
                    break;
                case 'f':
                    str.push_back('\f');
                    break;
                case 't':
                    str.push_back('\t');
                    break;
                case 'r':
                    str.push_back('\r');
                    break;
                case 'n':
                    str.push_back('\n');
                    break;
                default:
                    throw ParseException("parseJSONString");
                    break;
                }
            } else
                str.push_back(c);
        }

        ps.consume();
        return JValue(str);
    }

    throw ParseException("parseJSONString");
}

// Trying to specifically parse out a JSON boolean.
JValue parseJSONBool(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);
    std::string str;

    while (!ps.eof() && !isDelimiter(ps.peek()))
        str.push_back(ps.consume());

    if (str.compare("true") == 0)
        return JValue(true);
    else if (str.compare("false") == 0)
        return JValue(false);

    throw ParseException("JSONBool");
}

// Trying to specifically parse out the null JSON value.
JValue parseJSONNull(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);
    std::string str;

    while (!ps.eof() && !isDelimiter(ps.peek()))
        str.push_back(ps.consume());

    if (str.compare("null") == 0)
        return JValue();
    throw ParseException("parseJSONNull");
}

// Attempting to perform a parse - and then backing up on an error.
JValue attemptParse(ParseStream& ps, JValue (*parseFn)(ParseStream&)) throw(ParseException) {
    int sl = ps.getLoc();
    try { return parseFn(ps); }
    catch (const ParseException& e) {
        ps.back(ps.getLoc() - sl);
        throw e;
    }
}

// Parsing out a block of JSON from a ParseStream.
JValue parseJSON(ParseStream& ps) throw(ParseException) {
    std::vector<JValue (*)(ParseStream&)> fns;
    fns.push_back(&parseJSONArray);
    fns.push_back(&parseJSONNumber);
    fns.push_back(&parseJSONString);
    fns.push_back(&parseJSONBool);
    fns.push_back(&parseJSONNull);

    for (auto it = fns.begin(); it != fns.end(); it++) {
        try { return attemptParse(ps, *it); }
        catch (const ParseException& e) { }
    }

    throw ParseException("parseJSON");
}

// Parsing out a block of JSON from a string.
JValue parseJSON(const std::string& str) throw(ParseException) {
    ParseStream ps(str);
    return parseJSON(ps);
}

// Parsing out a block of JSON from an istream.
JValue parseJSON(std::istream& stream) throw(ParseException) {
    std::string line, all;

    while (!stream.eof()) {
        std::getline(stream, line);
        all += line;
    }

    return parseJSON(all);
}
<commit_msg>Removed an <iostream><commit_after>#include "parser.hpp"

//////////////
// Includes //
#include <istream>
#include <string>
#include <vector>
#include <tuple>

#include "parsestream.hpp"
#include "streamutils.hpp"
#include "json.hpp"

//////////
// Code //

// Creating a parse exception.
ParseException::ParseException(std::string type) {
    this->type = type;
}

// Returning a string to refer to this exception.
const char* ParseException::what() const throw() {
    return ("Failed to parse a " + this->type + " piece of JSON.").c_str();
}

//// Trying to specifically parse out a JSON object.
//JValue parseJSONObject(ParseStream& ps) throw(ParseException) {
    //throw ParseException("JObject");
//}

//// Trying to specifically parse out a JSON array.
//JValue parseJSONArray(ParseStream& ps) throw(ParseException) {
    //if (str[0] == '[' && str[str.size() - 1] == ']') {
        //std::string useStr = str.substr(1, str.size() - 2);
        //if (useStr.compare("") == 0)
            //return JValue();

        //std::vector<JValue> jValues;
        //std::tuple<std::string, std::string> tup;
        //for (tup = untilChar(useStr, ','); std::get<0>(tup).compare("") != 0; tup = untilChar(std::get<1>(tup), ','))
            //jValues.push_back(parseJSON(stripWhitespace(std::get<0>(tup))));

        //return JValue(jValues);
    //}

    //throw ParseException("parseJSONArray");
//}

// Trying to specifically parse out a JSON array.
JValue parseJSONArray(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);

    if (ps.consume() == '[') {
        std::vector<JValue> values;
        while (true) {
            consumeWhitespace(ps);
            values.push_back(parseJSON(ps));
            consumeWhitespace(ps);

            char c = ps.consume();
            if (c == ']')
                break;
            else if (c != ',')
                throw ParseException("parseJSONArray");
        }

        return JValue(values);
    }

    throw ParseException("parseJSONArray");
}

// Trying to specifically parse out a JSON number.
JValue parseJSONNumber(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);

    std::string str;
    bool first = true;
    while (!ps.eof() && !isDelimiter(ps.peek())) {
        char c = ps.consume();

        if (first && c == '-') {
            str.push_back(c);
            first = false;
        } else if (('0' <= c && c <= '9') || c == '.')
            str.push_back(c);
        else
            throw ParseException("parseJSONNumber");
    }

    return JValue(stod(str));
}

// Trying to specifically parse out a JSON string.
JValue parseJSONString(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);
    if (ps.peek() == '"') {
        ps.consume();

        std::string str;
        while (ps.peek() != '"') {
            char c = ps.consume();
            if (c == '\n')
                throw ParseException("parseJSONString");

            if (c == '\\') {
                char c2 = ps.consume();

                switch (c2) {
                case '"':
                    str.push_back('"');
                    break;
                case '\\':
                    str.push_back('\\');
                    break;
                case '/':
                    str.push_back('/');
                case 'b':
                    str.push_back('\b');
                    break;
                case 'f':
                    str.push_back('\f');
                    break;
                case 't':
                    str.push_back('\t');
                    break;
                case 'r':
                    str.push_back('\r');
                    break;
                case 'n':
                    str.push_back('\n');
                    break;
                default:
                    throw ParseException("parseJSONString");
                    break;
                }
            } else
                str.push_back(c);
        }

        ps.consume();
        return JValue(str);
    }

    throw ParseException("parseJSONString");
}

// Trying to specifically parse out a JSON boolean.
JValue parseJSONBool(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);
    std::string str;

    while (!ps.eof() && !isDelimiter(ps.peek()))
        str.push_back(ps.consume());

    if (str.compare("true") == 0)
        return JValue(true);
    else if (str.compare("false") == 0)
        return JValue(false);

    throw ParseException("JSONBool");
}

// Trying to specifically parse out the null JSON value.
JValue parseJSONNull(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);
    std::string str;

    while (!ps.eof() && !isDelimiter(ps.peek()))
        str.push_back(ps.consume());

    if (str.compare("null") == 0)
        return JValue();
    throw ParseException("parseJSONNull");
}

// Attempting to perform a parse - and then backing up on an error.
JValue attemptParse(ParseStream& ps, JValue (*parseFn)(ParseStream&)) throw(ParseException) {
    int sl = ps.getLoc();
    try { return parseFn(ps); }
    catch (const ParseException& e) {
        ps.back(ps.getLoc() - sl);
        throw e;
    }
}

// Parsing out a block of JSON from a ParseStream.
JValue parseJSON(ParseStream& ps) throw(ParseException) {
    std::vector<JValue (*)(ParseStream&)> fns;
    fns.push_back(&parseJSONArray);
    fns.push_back(&parseJSONNumber);
    fns.push_back(&parseJSONString);
    fns.push_back(&parseJSONBool);
    fns.push_back(&parseJSONNull);

    for (auto it = fns.begin(); it != fns.end(); it++) {
        try { return attemptParse(ps, *it); }
        catch (const ParseException& e) { }
    }

    throw ParseException("parseJSON");
}

// Parsing out a block of JSON from a string.
JValue parseJSON(const std::string& str) throw(ParseException) {
    ParseStream ps(str);
    return parseJSON(ps);
}

// Parsing out a block of JSON from an istream.
JValue parseJSON(std::istream& stream) throw(ParseException) {
    std::string line, all;

    while (!stream.eof()) {
        std::getline(stream, line);
        all += line;
    }

    return parseJSON(all);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2002 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2002 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _L10N_TRANSLITERATION_CHARTONUM_HXX_
#define _L10N_TRANSLITERATION_CHARTONUM_HXX_

#include <transliteration_Numeric.hxx>

namespace com { namespace sun { namespace star { namespace i18n {

class CharToNum : public transliteration_Numeric {
public:
    CharToNum();

    virtual rtl::OUString SAL_CALL transliterate( const rtl::OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, com::sun::star::uno::Sequence< sal_Int32 >& offset  ) throw(com::sun::star::uno::RuntimeException);
protected:
    sal_Int16 number;
};

#define TRANSLITERATION_CHARTONUM( name ) \
class CharToNum##name : public CharToNum \
{ \
public: \
    CharToNum##name (); \
};

#ifdef TRANSLITERATION_ALL
TRANSLITERATION_CHARTONUM(Lower_zh_CN)
TRANSLITERATION_CHARTONUM(Upper_zh_CN)
TRANSLITERATION_CHARTONUM(Lower_zh_TW)
TRANSLITERATION_CHARTONUM(Upper_zh_TW)
TRANSLITERATION_CHARTONUM(Upper_ko)
TRANSLITERATION_CHARTONUM(Hangul_ko)
TRANSLITERATION_CHARTONUM(Lower_ko)
TRANSLITERATION_CHARTONUM(KanjiShort_ja_JP)
TRANSLITERATION_CHARTONUM(KanjiTraditional_ja_JP)
TRANSLITERATION_CHARTONUM(Fullwidth)
TRANSLITERATION_CHARTONUM(Indic_ar)
TRANSLITERATION_CHARTONUM(EastIndic_ar)
TRANSLITERATION_CHARTONUM(Indic_hi)
TRANSLITERATION_CHARTONUM(_th)
#endif
#undef TRANSLITERATION_CHARTONUM

} } } }

#endif // _L10N_TRANSLITERATION_CHARTONUM_HXX_
<commit_msg>INTEGRATION: CWS calc06 (1.2.44); FILE MERGED 2003/03/21 22:23:22 khong 1.2.44.1: #106680# Implementing new XExtendedTransliteration interface<commit_after>/*************************************************************************
 *
 *  $RCSfile: chartonum.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2003-04-08 15:43:11 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _L10N_TRANSLITERATION_CHARTONUM_HXX_
#define _L10N_TRANSLITERATION_CHARTONUM_HXX_

#include <transliteration_Numeric.hxx>

namespace com { namespace sun { namespace star { namespace i18n {

#define TRANSLITERATION_CHARTONUM( name ) \
class CharToNum##name : public transliteration_Numeric \
{ \
public: \
        CharToNum##name (); \
};

#ifdef TRANSLITERATION_ALL
TRANSLITERATION_CHARTONUM(Lower_zh_CN)
TRANSLITERATION_CHARTONUM(Upper_zh_CN)
TRANSLITERATION_CHARTONUM(Lower_zh_TW)
TRANSLITERATION_CHARTONUM(Upper_zh_TW)
TRANSLITERATION_CHARTONUM(Upper_ko)
TRANSLITERATION_CHARTONUM(Hangul_ko)
TRANSLITERATION_CHARTONUM(Lower_ko)
TRANSLITERATION_CHARTONUM(KanjiShort_ja_JP)
TRANSLITERATION_CHARTONUM(KanjiTraditional_ja_JP)
TRANSLITERATION_CHARTONUM(Fullwidth)
TRANSLITERATION_CHARTONUM(Indic_ar)
TRANSLITERATION_CHARTONUM(EastIndic_ar)
TRANSLITERATION_CHARTONUM(Indic_hi)
TRANSLITERATION_CHARTONUM(_th)
#endif
#undef TRANSLITERATION_CHARTONUM

} } } }

#endif // _L10N_TRANSLITERATION_CHARTONUM_HXX_
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: lbseldlg.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: dr $ $Date: 2001-05-17 15:17:52 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

//------------------------------------------------------------------

#include <vcl/msgbox.hxx>

#include "lbseldlg.hxx"
#include "scresid.hxx"
#include "miscdlgs.hrc"

//==================================================================

ScSelEntryDlg::ScSelEntryDlg(      Window*  pParent,
                                   USHORT   nResId,
                             const String&  aTitle,
                             const String&  aLbTitle,
                                   List&    aEntryList ) :
    ModalDialog     ( pParent, ScResId( nResId ) ),
    //
    aFlLbTitle      ( this, ScResId( FL_ENTRYLIST ) ),
    aLb             ( this, ScResId( LB_ENTRYLIST ) ),
    aBtnOk          ( this, ScResId( BTN_OK ) ),
    aBtnCancel      ( this, ScResId( BTN_CANCEL ) ),
    aBtnHelp        ( this, ScResId( BTN_HELP ) )
{
    SetText( aTitle );
    aFlLbTitle.SetText( aLbTitle );
    aLb.Clear();
    aLb.SetDoubleClickHdl( LINK( this, ScSelEntryDlg, DblClkHdl ) );

    void*   pListEntry = aEntryList.First();
    while ( pListEntry )
    {
        aLb.InsertEntry( *((String*)pListEntry ) );
        pListEntry = aEntryList.Next();
    }

    if ( aLb.GetEntryCount() > 0 )
        aLb.SelectEntryPos( 0 );

    //-------------
    FreeResource();
}

//------------------------------------------------------------------------

String ScSelEntryDlg::GetSelectEntry() const
{
    return aLb.GetSelectEntry();
}

//------------------------------------------------------------------------

USHORT ScSelEntryDlg::GetSelectEntryPos() const
{
    return aLb.GetSelectEntryPos();
}

//------------------------------------------------------------------------

IMPL_LINK_INLINE_START( ScSelEntryDlg, DblClkHdl, void *, EMPTYARG )
{
    EndDialog( RET_OK );
    return 0;
}
IMPL_LINK_INLINE_END( ScSelEntryDlg, DblClkHdl, void *, EMPTYARG )

//------------------------------------------------------------------------

__EXPORT ScSelEntryDlg::~ScSelEntryDlg()
{
}

<commit_msg>INTEGRATION: CWS tune03 (1.2.518); FILE MERGED 2004/07/08 16:45:13 mhu 1.2.518.1: #i29979# Added SC_DLLPUBLIC/PRIVATE (see scdllapi.h) to exported symbols/classes.<commit_after>/*************************************************************************
 *
 *  $RCSfile: lbseldlg.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2004-08-23 09:37:21 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#undef SC_DLLIMPLEMENTATION

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

//------------------------------------------------------------------

#include <vcl/msgbox.hxx>

#include "lbseldlg.hxx"
#include "scresid.hxx"
#include "miscdlgs.hrc"

//==================================================================

ScSelEntryDlg::ScSelEntryDlg(      Window*  pParent,
                                   USHORT   nResId,
                             const String&  aTitle,
                             const String&  aLbTitle,
                                   List&    aEntryList ) :
    ModalDialog     ( pParent, ScResId( nResId ) ),
    //
    aFlLbTitle      ( this, ScResId( FL_ENTRYLIST ) ),
    aLb             ( this, ScResId( LB_ENTRYLIST ) ),
    aBtnOk          ( this, ScResId( BTN_OK ) ),
    aBtnCancel      ( this, ScResId( BTN_CANCEL ) ),
    aBtnHelp        ( this, ScResId( BTN_HELP ) )
{
    SetText( aTitle );
    aFlLbTitle.SetText( aLbTitle );
    aLb.Clear();
    aLb.SetDoubleClickHdl( LINK( this, ScSelEntryDlg, DblClkHdl ) );

    void*   pListEntry = aEntryList.First();
    while ( pListEntry )
    {
        aLb.InsertEntry( *((String*)pListEntry ) );
        pListEntry = aEntryList.Next();
    }

    if ( aLb.GetEntryCount() > 0 )
        aLb.SelectEntryPos( 0 );

    //-------------
    FreeResource();
}

//------------------------------------------------------------------------

String ScSelEntryDlg::GetSelectEntry() const
{
    return aLb.GetSelectEntry();
}

//------------------------------------------------------------------------

USHORT ScSelEntryDlg::GetSelectEntryPos() const
{
    return aLb.GetSelectEntryPos();
}

//------------------------------------------------------------------------

IMPL_LINK_INLINE_START( ScSelEntryDlg, DblClkHdl, void *, EMPTYARG )
{
    EndDialog( RET_OK );
    return 0;
}
IMPL_LINK_INLINE_END( ScSelEntryDlg, DblClkHdl, void *, EMPTYARG )

//------------------------------------------------------------------------

__EXPORT ScSelEntryDlg::~ScSelEntryDlg()
{
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: mvtabdlg.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: dr $ $Date: 2001-05-23 10:50:15 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

//------------------------------------------------------------------

#include <vcl/msgbox.hxx>

#include "mvtabdlg.hxx"
#include "document.hxx"
#include "docsh.hxx"
#include "miscdlgs.hrc"
#include "global.hxx"
#include "scresid.hxx"
#include "globstr.hrc"

//==================================================================

ScMoveTableDlg::ScMoveTableDlg( Window* pParent )

    :   ModalDialog ( pParent, ScResId( RID_SCDLG_MOVETAB ) ),
        //
        aFtDoc      ( this, ScResId( FT_DEST ) ),
        aLbDoc      ( this, ScResId( LB_DEST ) ),
        aFtTable    ( this, ScResId( FT_INSERT ) ),
        aLbTable    ( this, ScResId( LB_INSERT ) ),
        aBtnCopy    ( this, ScResId( BTN_COPY ) ),
        aBtnOk      ( this, ScResId( BTN_OK ) ),
        aBtnCancel  ( this, ScResId( BTN_CANCEL ) ),
        aBtnHelp    ( this, ScResId( BTN_HELP ) ),
        //
        nDocument   ( 0 ),
        nTable      ( 0 ),
        bCopyTable  ( FALSE )
{
    Init();
    FreeResource();
}

//------------------------------------------------------------------------

__EXPORT ScMoveTableDlg::~ScMoveTableDlg()
{
}

//------------------------------------------------------------------------

USHORT ScMoveTableDlg::GetSelectedDocument () const { return nDocument;  }

USHORT ScMoveTableDlg::GetSelectedTable    () const { return nTable;     }

BOOL   ScMoveTableDlg::GetCopyTable        () const { return bCopyTable; }

void ScMoveTableDlg::SetCopyTable(BOOL bFlag)
{
    aBtnCopy.Check(bFlag);
}
void ScMoveTableDlg::EnableCopyTable(BOOL bFlag)
{
    if(bFlag)
        aBtnCopy.Enable();
    else
        aBtnCopy.Disable();
}

//------------------------------------------------------------------------

void __EXPORT ScMoveTableDlg::Init()
{
    aBtnOk.SetClickHdl   ( LINK( this, ScMoveTableDlg, OkHdl ) );
    aLbDoc.SetSelectHdl  ( LINK( this, ScMoveTableDlg, SelHdl ) );
    aBtnCopy.Check( FALSE );
    InitDocListBox();
    SelHdl( &aLbDoc );
}

//------------------------------------------------------------------------

void ScMoveTableDlg::InitDocListBox()
{
    SfxObjectShell* pSh     = SfxObjectShell::GetFirst();
    ScDocShell*     pScSh   = NULL;
    ScDocument*     pDoc    = NULL;
    USHORT          nSelPos = 0;
    USHORT          i       = 0;

    aLbDoc.Clear();
    aLbDoc.SetUpdateMode( FALSE );

    while ( pSh )
    {
        pScSh = PTR_CAST( ScDocShell, pSh );

        if ( pScSh )
        {
            if ( pScSh == SfxObjectShell::Current() )
                nSelPos = i;

            aLbDoc.InsertEntry( pScSh->GetTitle(), i );
            aLbDoc.SetEntryData( i, (void*)pScSh->GetDocument() );

            i++;
        }
        pSh = SfxObjectShell::GetNext( *pSh );
    }

    aLbDoc.SetUpdateMode( TRUE );
    aLbDoc.InsertEntry( String( ScResId( STR_NEWDOC ) ) );
    aLbDoc.SelectEntryPos( nSelPos );
}

//------------------------------------------------------------------------
// Handler:

IMPL_LINK( ScMoveTableDlg, OkHdl, void *, EMPTYARG )
{
    USHORT  nDocSel     = aLbDoc.GetSelectEntryPos();
    USHORT  nDocLast    = aLbDoc.GetEntryCount()-1;
    USHORT  nTabSel     = aLbTable.GetSelectEntryPos();
    USHORT  nTabLast    = aLbTable.GetEntryCount()-1;

    nDocument   = (nDocSel != nDocLast) ? nDocSel : SC_DOC_NEW;
    nTable      = (nTabSel != nTabLast) ? nTabSel : SC_TAB_APPEND;
    bCopyTable  = aBtnCopy.IsChecked();
    EndDialog( RET_OK );

    return 0;
}

//------------------------------------------------------------------------

IMPL_LINK( ScMoveTableDlg, SelHdl, ListBox *, pLb )
{
    if ( pLb == &aLbDoc )
    {
        ScDocument* pDoc   = (ScDocument*)
                             aLbDoc.GetEntryData( aLbDoc.GetSelectEntryPos() );
        USHORT      nLast  = 0;
        String      aName;

        aLbTable.Clear();
        aLbTable.SetUpdateMode( FALSE );
        if ( pDoc )
        {
            nLast = pDoc->GetTableCount()-1;
            for ( USHORT i=0; i<=nLast; i++ )
            {
                pDoc->GetName( i, aName );
                aLbTable.InsertEntry( aName, i );
            }
        }
        aLbTable.InsertEntry( ScGlobal::GetRscString(STR_MOVE_TO_END) );
        aLbTable.SetUpdateMode( TRUE );
        aLbTable.SelectEntryPos( 0 );
    }

    return 0;
}

<commit_msg>INTEGRATION: CWS rowlimit (1.2.332); FILE MERGED 2004/02/26 11:46:59 er 1.2.332.2: #i1967# type correctness 2004/01/14 17:23:38 er 1.2.332.1: #i1967# SCCOL,SCROW,SCTAB replace USHORT; SCsCOL,SCsROW,SCsTAB replace short<commit_after>/*************************************************************************
 *
 *  $RCSfile: mvtabdlg.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2004-06-04 11:47:48 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

//------------------------------------------------------------------

#include <vcl/msgbox.hxx>

#include "mvtabdlg.hxx"
#include "document.hxx"
#include "docsh.hxx"
#include "miscdlgs.hrc"
#include "global.hxx"
#include "scresid.hxx"
#include "globstr.hrc"

//==================================================================

ScMoveTableDlg::ScMoveTableDlg( Window* pParent )

    :   ModalDialog ( pParent, ScResId( RID_SCDLG_MOVETAB ) ),
        //
        aFtDoc      ( this, ScResId( FT_DEST ) ),
        aLbDoc      ( this, ScResId( LB_DEST ) ),
        aFtTable    ( this, ScResId( FT_INSERT ) ),
        aLbTable    ( this, ScResId( LB_INSERT ) ),
        aBtnCopy    ( this, ScResId( BTN_COPY ) ),
        aBtnOk      ( this, ScResId( BTN_OK ) ),
        aBtnCancel  ( this, ScResId( BTN_CANCEL ) ),
        aBtnHelp    ( this, ScResId( BTN_HELP ) ),
        //
        nDocument   ( 0 ),
        nTable      ( 0 ),
        bCopyTable  ( FALSE )
{
    Init();
    FreeResource();
}

//------------------------------------------------------------------------

__EXPORT ScMoveTableDlg::~ScMoveTableDlg()
{
}

//------------------------------------------------------------------------

USHORT ScMoveTableDlg::GetSelectedDocument () const { return nDocument;  }

SCTAB ScMoveTableDlg::GetSelectedTable    () const { return nTable;     }

BOOL   ScMoveTableDlg::GetCopyTable        () const { return bCopyTable; }

void ScMoveTableDlg::SetCopyTable(BOOL bFlag)
{
    aBtnCopy.Check(bFlag);
}
void ScMoveTableDlg::EnableCopyTable(BOOL bFlag)
{
    if(bFlag)
        aBtnCopy.Enable();
    else
        aBtnCopy.Disable();
}

//------------------------------------------------------------------------

void __EXPORT ScMoveTableDlg::Init()
{
    aBtnOk.SetClickHdl   ( LINK( this, ScMoveTableDlg, OkHdl ) );
    aLbDoc.SetSelectHdl  ( LINK( this, ScMoveTableDlg, SelHdl ) );
    aBtnCopy.Check( FALSE );
    InitDocListBox();
    SelHdl( &aLbDoc );
}

//------------------------------------------------------------------------

void ScMoveTableDlg::InitDocListBox()
{
    SfxObjectShell* pSh     = SfxObjectShell::GetFirst();
    ScDocShell*     pScSh   = NULL;
    ScDocument*     pDoc    = NULL;
    USHORT          nSelPos = 0;
    USHORT          i       = 0;

    aLbDoc.Clear();
    aLbDoc.SetUpdateMode( FALSE );

    while ( pSh )
    {
        pScSh = PTR_CAST( ScDocShell, pSh );

        if ( pScSh )
        {
            if ( pScSh == SfxObjectShell::Current() )
                nSelPos = i;

            aLbDoc.InsertEntry( pScSh->GetTitle(), i );
            aLbDoc.SetEntryData( i, (void*)pScSh->GetDocument() );

            i++;
        }
        pSh = SfxObjectShell::GetNext( *pSh );
    }

    aLbDoc.SetUpdateMode( TRUE );
    aLbDoc.InsertEntry( String( ScResId( STR_NEWDOC ) ) );
    aLbDoc.SelectEntryPos( nSelPos );
}

//------------------------------------------------------------------------
// Handler:

IMPL_LINK( ScMoveTableDlg, OkHdl, void *, EMPTYARG )
{
    USHORT  nDocSel     = aLbDoc.GetSelectEntryPos();
    USHORT  nDocLast    = aLbDoc.GetEntryCount()-1;
    USHORT  nTabSel     = aLbTable.GetSelectEntryPos();
    USHORT  nTabLast    = aLbTable.GetEntryCount()-1;

    nDocument   = (nDocSel != nDocLast) ? nDocSel : SC_DOC_NEW;
    nTable      = (nTabSel != nTabLast) ? static_cast<SCTAB>(nTabSel) : SC_TAB_APPEND;
    bCopyTable  = aBtnCopy.IsChecked();
    EndDialog( RET_OK );

    return 0;
}

//------------------------------------------------------------------------

IMPL_LINK( ScMoveTableDlg, SelHdl, ListBox *, pLb )
{
    if ( pLb == &aLbDoc )
    {
        ScDocument* pDoc   = (ScDocument*)
                             aLbDoc.GetEntryData( aLbDoc.GetSelectEntryPos() );
        SCTAB      nLast  = 0;
        String      aName;

        aLbTable.Clear();
        aLbTable.SetUpdateMode( FALSE );
        if ( pDoc )
        {
            nLast = pDoc->GetTableCount()-1;
            for ( SCTAB i=0; i<=nLast; i++ )
            {
                pDoc->GetName( i, aName );
                aLbTable.InsertEntry( aName, static_cast<sal_uInt16>(i) );
            }
        }
        aLbTable.InsertEntry( ScGlobal::GetRscString(STR_MOVE_TO_END) );
        aLbTable.SetUpdateMode( TRUE );
        aLbTable.SelectEntryPos( 0 );
    }

    return 0;
}

<|endoftext|>


<commit_before><commit_msg>loplugin:cstylecast: nop between pointer types of exactly same spelling<commit_after><|endoftext|>