platform/packages/combinator/example/main.dart

38 lines
968 B
Dart
Raw Normal View History

2021-03-17 23:04:36 +00:00
import 'dart:io';
import 'package:combinator/combinator.dart';
import 'package:string_scanner/string_scanner.dart';
final Parser minus = match('-');
final Parser<int> digit =
match(new RegExp(r'[0-9]'), errorMessage: 'Expected a number');
final Parser digits = digit.plus();
final Parser dot = match('.');
final Parser decimal = ( // digits, (dot, digits)?
digits & (dot & digits).opt() //
);
final Parser number = //
(minus.opt() & decimal) // minus?, decimal
2021-03-18 00:00:56 +00:00
.map<num>((r) => num.parse(r.span!.text));
2021-03-17 23:04:36 +00:00
main() {
while (true) {
stdout.write('Enter a number: ');
2021-03-18 00:00:56 +00:00
var line = stdin.readLineSync()!;
2021-03-17 23:04:36 +00:00
var scanner = new SpanScanner(line, sourceUrl: 'stdin');
2021-05-02 04:12:43 +00:00
var result = number.parse(scanner);
2021-03-17 23:04:36 +00:00
if (!result.successful) {
for (var error in result.errors) {
stderr.writeln(error.toolString);
2021-03-18 00:00:56 +00:00
stderr.writeln(error.span!.highlight(color: true));
2021-03-17 23:04:36 +00:00
}
} else
print(result.value);
}
}