File size: 2,053 Bytes
6851d40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// RUN: %verify "%s"

include "../Wrappers.dfy"
include "../BoundedInts.dfy"
include "Utils/Str.dfy"

module {:options "-functionSyntax:4"} JSON.Errors {
  import Wrappers
  import opened BoundedInts
  import Utils.Str

  datatype DeserializationError =
    | UnterminatedSequence
    | UnsupportedEscape(str: string)
    | EscapeAtEOS
    | EmptyNumber
    | ExpectingEOF
    | IntOverflow
    | ReachedEOF
    | ExpectingByte(expected: byte, b: opt_byte)
    | ExpectingAnyByte(expected_sq: seq<byte>, b: opt_byte)
    | InvalidUnicode
  {
    function ToString() : string {
      match this
      case UnterminatedSequence => "Unterminated sequence"
      case UnsupportedEscape(str) => "Unsupported escape sequence: " + str
      case EscapeAtEOS => "Escape character at end of string"
      case EmptyNumber => "Number must contain at least one digit"
      case ExpectingEOF => "Expecting EOF"
      case IntOverflow => "Input length does not fit in a 32-bit counter"
      case ReachedEOF => "Reached EOF"
      case ExpectingByte(b0, b) =>
        var c := if b > 0 then "'" + [b as char] + "'" else "EOF";
        "Expecting '" + [b0 as char] + "', read " + c
      case ExpectingAnyByte(bs0, b) =>
        var c := if b > 0 then "'" + [b as char] + "'" else "EOF";
        var c0s := seq(|bs0|, idx requires 0 <= idx < |bs0| => bs0[idx] as char);
        "Expecting one of '" + c0s + "', read " + c
      case InvalidUnicode => "Invalid Unicode sequence"
    }
  }

  datatype SerializationError =
    | OutOfMemory
    | IntTooLarge(i: int)
    | StringTooLong(s: string)
    | InvalidUnicode
  {
    function ToString() : string {
      match this
      case OutOfMemory => "Out of memory"
      case IntTooLarge(i: int) => "Integer too large: " + Str.OfInt(i)
      case StringTooLong(s: string) => "String too long: " + s
      case InvalidUnicode => "Invalid Unicode sequence"
    }
  }

  type SerializationResult<+T> = Wrappers.Result<T, SerializationError>
  type DeserializationResult<+T> = Wrappers.Result<T, DeserializationError>
}