Giter Club home page Giter Club logo

Comments (5)

venkatd avatar venkatd commented on August 10, 2024 1

@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.

renggli avatar renggli commented on August 10, 2024

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.

venkatd avatar venkatd commented on August 10, 2024

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.

renggli avatar renggli commented on August 10, 2024

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.

renggli avatar renggli commented on August 10, 2024

An idea, to make this a bit more simple could be to add to Parser<T> the following helpers:

  1. Parser<R> flatMap<R>(Result<R> Function(T value) callback), or
  2. Parser<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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.