platform/packages/combinator/example/main.dart

39 lines
987 B
Dart
Raw Normal View History

2021-03-17 23:04:36 +00:00
import 'dart:io';
2021-05-14 06:11:50 +00:00
import 'package:angel3_combinator/angel3_combinator.dart';
2021-03-17 23:04:36 +00:00
import 'package:string_scanner/string_scanner.dart';
final Parser minus = match('-');
final Parser<int> digit =
2021-05-14 06:11:50 +00:00
match(RegExp(r'[0-9]'), errorMessage: 'Expected a number');
2021-03-17 23:04:36 +00:00
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
2021-05-18 13:15:28 +00:00
void main() {
2021-03-17 23:04:36 +00:00
while (true) {
stdout.write('Enter a number: ');
2021-03-18 00:00:56 +00:00
var line = stdin.readLineSync()!;
2021-05-14 06:11:50 +00:00
var scanner = 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
}
2021-05-18 13:15:28 +00:00
} else {
2021-03-17 23:04:36 +00:00
print(result.value);
2021-05-18 13:15:28 +00:00
}
2021-03-17 23:04:36 +00:00
}
}