Comments (5)
@renggli worked for me, thanks! Wasn't aware of callCC
. Agree on not adding those helpers for now. Better to err on the side of keeping the API surface area small.
If anyone is curious as they're learning pasting in my full implementation below:
Parser<String> _iso8601DateTime() {
Parser<String> num2Digit({int min, int max}) =>
digit().repeat(2).flatten().callCC(
(continuation, context) {
final result = continuation(context);
if (result.isFailure) return result;
final intValue = int.parse(result.value);
if (max != null && intValue > max)
return context.failure('Greater than $max');
if (min != null && intValue < min)
return context.failure('Less than $min');
return result;
},
);
final dateFullYear = digit().repeat(4).flatten();
final dateMonth = num2Digit(min: 1, max: 12);
final dateMday = num2Digit(min: 1, max: 31);
final timeHour = num2Digit(max: 23);
final timeMinute = num2Digit(max: 59);
final timeSecond = num2Digit(max: 59);
final timeSecFrac = (char('.') & digit().plus()).flatten();
final timeOffset = char('Z');
final partialTime = (timeHour &
char(':') &
timeMinute &
char(':') &
timeSecond &
timeSecFrac.optional());
final fullDate = dateFullYear & char('-') & dateMonth & char('-') & dateMday;
final fullTime = partialTime & timeOffset;
return (fullDate & char('T') & fullTime).flatten();
}
final iso8601DateTime = _iso8601DateTime();
import "package:test/test.dart";
import 'iso8601.dart';
import 'package:petitparser/petitparser.dart';
void main() {
group('iso8601', () {
test('valid time', () {
final res = iso8601DateTime.parse('2020-10-08T21:57:50.118523Z');
expect(res.value, '2020-10-08T21:57:50.118523Z');
});
test('time with month out of range', () {
final res = iso8601DateTime.parse('2020-15-08T21:57:50.118523Z');
expect(res.isSuccess, false);
});
test('skips over invalid times', () {
final res = iso8601DateTime.matchesSkipping(
'hi 2020-10-08T21:57:50.118523Z 2020-15-08T21:57:50.118523Z 2020-12-08T21:57:50.118523Z yay cool');
expect(
res, ['2020-10-08T21:57:50.118523Z', '2020-12-08T21:57:50.118523Z']);
});
});
}
from dart-petitparser.
The validation of data is typically done in a second pass, but you can of course also do it while parsing:
Parser<String> num2Digit(int n) => digit().repeat(2).flatten().map((str) {
final value = int.parse(str);
if (value > n) throw InvalidArgument(str);
return value;
});
from dart-petitparser.
Thanks! The high level behavior I am currently after is:
List<DocumentToken> tokenizeBody(
String message, {
Iterable<User> users = const [],
}) =>
documentTokenParser(users).matchesSkipping(message);
Where message
is a custom markup internal to our app.
Each object is a subclass of the abstract DocumentToken
class. I have UserToken, MentionToken, LinkToken, DateTimeToken, and so on. This works 99% of the time but sometimes our parser deals with invalid tokens with an invalid ISO8601 format and so on.
If something doesn't match, I'd prefer to fall back to a catch-all StringToken
so in our UI it would just render the text as-is. If I were to throw InvalidArgument
would the parser decide to fail the match and try the next pattern?
P.S. Thanks for the great library. I always found parsers intimidating and resorted to RegEx to avoid writing parsers. This library makes writing parsers a lot more accessible :)
from dart-petitparser.
You can achieve that with the continuation parser:
Parser<String> num2Digit(int n) => digit().repeat(2).flatten().callCC((continuation, context) {
final result = continuation(context);
if (result.isSuccess && int.parse(result.value) > n) {
return context.failure('Larger than $n');
} else {
return result;
}
});
from dart-petitparser.
An idea, to make this a bit more simple could be to add to Parser<T>
the following helpers:
Parser<R> flatMap<R>(Result<R> Function(T value) callback)
, orParser<T> where(bool Function(T value) predicate, String errorMessage)
The reasons not to add those are that they are both specializations of the existing callCC
. Also the need to provide an errorMessage is kind of unusual in terms of adopting an existing API terminology.
from dart-petitparser.
Related Issues (20)
- Translate JS/TS to Dart? HOT 5
- Alternative to trim parser or how to discard HOT 2
- Relevance of `refX`? HOT 1
- Broken link for linter rules HOT 1
- Eliminate dynamic calls
- How to upgrade? HOT 7
- Getting line and colone in the code. HOT 2
- Improve error reporting of `ExpressionPaser` HOT 1
- Consider rolling meta back to ^1.8.0 HOT 1
- Greedy parse problem HOT 2
- Higher Unicode planes support? HOT 2
- Collecting Parsed result and passing it to next product HOT 1
- Possible alternative use of switch that might be fast enough HOT 3
- ReferenceParser prevents repeatString optimization HOT 1
- Projects that are using PetitParser HOT 1
- Parsing Latin1 characters HOT 4
- Alternative to deprecated `separatedBy(separator, includeSeparators: false)` HOT 2
- Choice parser behavior HOT 2
- use petitparser to recognize jsonDecode output HOT 1
- Question: parse any word or term HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from dart-petitparser.