OLD | NEW |
(Empty) | |
| 1 library petitparser.example.lispshell; |
| 2 |
| 3 import 'dart:io'; |
| 4 import 'dart:async'; |
| 5 import 'dart:convert'; |
| 6 |
| 7 import 'package:petitparser/petitparser.dart'; |
| 8 import 'package:petitparser/lisp.dart'; |
| 9 |
| 10 /// Read, evaluate, print loop. |
| 11 void evalInteractive(Parser parser, Environment env, Stream<String> input, |
| 12 IOSink output, IOSink error) { |
| 13 output.write('>> '); |
| 14 input.listen((String line) { |
| 15 try { |
| 16 output.writeln('=> ${evalString(parser, env, line)}'); |
| 17 } on ParserError catch (exception) { |
| 18 error.writeln('Parser error: ' + exception.toString()); |
| 19 } on Error catch (exception) { |
| 20 error.writeln(exception.toString()); |
| 21 } |
| 22 output.write('>> '); |
| 23 }); |
| 24 } |
| 25 |
| 26 /// Entry point for the command line interpreter. |
| 27 void main(List<String> arguments) { |
| 28 |
| 29 // default options |
| 30 var standardLibrary = true; |
| 31 var interactiveMode = false; |
| 32 var files = new List(); |
| 33 |
| 34 // parse arguments |
| 35 for (var option in arguments) { |
| 36 if (option.startsWith('-') && files.isEmpty) { |
| 37 if (option == '-n') { |
| 38 standardLibrary = false; |
| 39 } else if (option == '-i') { |
| 40 interactiveMode = true; |
| 41 } else if (option == '-?') { |
| 42 print('${Platform.executable} lisp.dart -n -i [files]'); |
| 43 print(' -i enforces the interactive mode'); |
| 44 print(' -n does not load the standard library'); |
| 45 exit(0); |
| 46 } else { |
| 47 print('Unknown option: $option'); |
| 48 exit(1); |
| 49 } |
| 50 } else { |
| 51 var file = new File(option); |
| 52 if (file.existsSync()) { |
| 53 files.add(file); |
| 54 } else { |
| 55 print('File not found: $option'); |
| 56 exit(2); |
| 57 } |
| 58 } |
| 59 } |
| 60 |
| 61 // evaluation context |
| 62 var environment = Natives.import(new Environment()); |
| 63 |
| 64 // add additional primitives |
| 65 environment.define(new Name('exit'), (env, args) => exit(args == null ? 0 : ar
gs.head)); |
| 66 environment.define(new Name('sleep'), (env, args) => sleep(new Duration(millis
econds: args.head))); |
| 67 |
| 68 // process standard library |
| 69 if (standardLibrary) { |
| 70 environment = Standard.import(environment.create()); |
| 71 } |
| 72 |
| 73 // create empty context |
| 74 environment = environment.create(); |
| 75 |
| 76 // process files given as argument |
| 77 files.forEach((file) { |
| 78 evalString(lispParser, environment, file.readAsStringSync()); |
| 79 }); |
| 80 |
| 81 // process console input |
| 82 if (interactiveMode || files.isEmpty) { |
| 83 var input = stdin |
| 84 .transform(SYSTEM_ENCODING.decoder) |
| 85 .transform(new LineSplitter()); |
| 86 evalInteractive(lispParser, environment, input, stdout, stderr); |
| 87 } |
| 88 } |
OLD | NEW |