#!/usr/bin/env dart
// An Experimental Lisp Reader in Dart by SUZUKI Hisao on H27.3/3

import "dart:async";
import "dart:io";
import "dart:convert";

class Cell {
  var car;
  var cdr;

  Cell(this.car, this.cdr);

  @override String toString() {
    return "($car . $cdr)";
  }
}

class Reader {
  StreamIterator<String> _rf;
  var _token;
  Iterator<String> _tokens = <String>[].iterator;

  static final _tokenPat = new RegExp('\\s+|;.*\$|(".*?"|,@?|[^()\'`~ ]+|.)');

  Reader(this._rf);

  read() async {
    await _readToken();
    return await _parseExpression();
  }

  _parseExpression() async {
    if (_token == "(") {
      await _readToken();
      return await _parseListBody();
    } else {
      return _token;
    }
  }

  _parseListBody() async {
    if (_token == ")") {
      return null;
    } else {
      var e1 = await _parseExpression();
      await _readToken();
      var e2 = await _parseListBody();
      return new Cell(e1, e2);
    }
  }

  _readToken() async {
    while (! _tokens.moveNext()) {
      bool ok = await _rf.moveNext();
      if (! ok) {
        _token = #EOF;
        return;
      }
      var line = _rf.current;
      var matches = _tokenPat.allMatches(line);
      _tokens = matches
        .map((m) => m.group(1))
        .where((s) => s != null)
        .iterator;
    }
    _token = _tokens.current;
  }
}

Future main() async {
  Stream<String> lineStream
    = stdin.transform(UTF8.decoder).transform(const LineSplitter());
  var lines = new StreamIterator(lineStream);
  var reader = new Reader(lines);
  for (;;) {
    stdout.write("> ");
    var s = await reader.read();
    if (s == #EOF) break;
    print(s);
  }
  print("Goodbye");
}

/*
  Copyright (c) 2015 OKI Software Co., Ltd.

  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.
*/