JavaScript Parser monad (2)

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
function Parser(){
  this.f = function(s,f){ return f(s); };
};

// Start the parser passing a final `id' continuation.
Parser.prototype.runParser = function(s){
  return this.f(s,function(x){
    return x; // Should always be id
  });  
};

// Inject a continuation to run after the previous continuation
Parser.prototype.continueP = function(cont){
  var self = this;
  var f = self.f;
  self.f = function(s,f_){
    return f.call(self,s,function(s_){
      return cont(s_,f_);
    });
  };
  return self;
};

// Stop the parser and throw an error
Parser.prototype.error = function(msg){
  return this.continueP(function(s_,_f){
    s_.error = msg;
    return s_;
  });
};

// Parse some text
Parser.prototype.parse = function(i){
  return this.runParser({unit:null,input:i});
};

// This allows us to pass values between parsers.
Parser.prototype.unit = function(x){
  return this.continueP(function(s,f){
    s.unit = x;
    return f(s);
  });
};

// Consume and drop a character from input
Parser.prototype.drop = function(){
  return this.continueP(function(s,f){
    s.input = s.input.substr(1);
    return f(s);
  })
};

// Lets us consume a character for inspection.
Parser.prototype.consume = function(bind){
  return this.continueP(function(s_,f_){
    if (s_.input == '') {
      s_.error = 'Unexpected end of input';
      return s_;
    } else {
      // Pass unit to the bind continuation
      var p = bind.call(new Parser(),s_.input[0]);
      var s__ = p.runParser(s_); // Run the sub-parser
      if (s__.error) return s__; // Don't continue on error
      else return f_(s__); // Otherwise good to go
    }
  });
};

// Create a combinator
Parser.combinator = function(f){
  return function(){
    var args = arguments;
    if (this.constructor == Parser) {
      return f.apply(this,args);
    }
    else return function(){
      return f.apply(this,args);
    };
  };
};

// This allows us to insert arbitrary parsers and access the unit value.
Parser.prototype.bind = function(bind){
  return this.continueP(function(s_,f_){
    // Pass unit to the bind continuation
    var p = bind.call(new Parser(),s_.unit);
    var s__ = p.runParser(s_); // Run the sub-parser
    if (s__.error) return s__; // Don't continue on error
    else return f_(s__); // Otherwise good to go
  });
};

// This allows us to insert arbitrary parsers.
var inject = Parser.prototype.inject = Parser.combinator(function(bind){
  return this.continueP(function(s_,f_){
    var p = bind.call(new Parser());
    var s__ = p.runParser(s_); // Run the sub-parser
    if (s__.error) return s__; // Don't continue on error
    else return f_(s__); // Otherwise good to go
  });
});

// A parser that consumes if a predicate is satisfied, or errors.
var satisfy = Parser.prototype.satisfy = Parser.combinator(function(p,ex){
  return this.consume(function(c){
    return p(c)? this.drop().unit(c) :
      this.drop().error(ex? 'Expecting ' + ex + ', but found: ' + c :
                        'Unexpected: ' + c);
  });
});

// Parser something zero or more times
Parser.prototype._many = function(parser,required){
  return this.continueP(function(s,f){
    var p = new Parser();
    parser.call(p);
    var input = s.input;
    var unit = s.unit;
    var s_ = p.runParser(s);
    if (s_.error) {
      if (!required)
        delete s_.error;
      s_.input = input;
      s_.unit = [];
      if (required)
        return s_;
      else
        return f(s_);
    } else {
      var nextP = new Parser();
      var s__ = Parser.prototype.many.call(nextP,parser);
      var unit = s_.unit;
      var s__ = nextP.runParser(s_);
      s__.unit = unit.concat(s__.unit);
      return f(s__);
    }
  });
};

var many = Parser.prototype.many = Parser.combinator(function(parser){
  return this._many(parser,false);
});

var many1 = Parser.prototype.many1 = Parser.combinator(function(parser){
  return this._many(parser,true);
});

// This tries (and thus backtracks) by default, lazy, I know.
var or = Parser.prototype.or = Parser.combinator(function() {
  var ps = arguments;
  return this.continueP(function(s,f){
    var parser = ps[0]
    var p = new Parser();
    parser.call(p);
    var unit = s.unit, input = s.input;
    var s_ = p.runParser(s);
    if (s_.error) {
      if (ps[1]) {
        delete s.error;
        s.unit = unit, s.input = input;
        var nextP = new Parser();
        Parser.prototype.or.apply(nextP,Array.prototype.slice.call(ps,1));
        var s__ = nextP.runParser(s);
        if (s__.error) {
          return s__;
        } else {
          return f(s__);
        }
      } else {
        return s_;
      }
    } else {
      return f(s_);
    }
  });
});

var eof = Parser.prototype.eof = Parser.combinator(function(){
  return this.continueP(function(s,f){
    if (s.input == '') {
      s.unit = null;
      return f(s);
    } else {
      s.error = 'Expected end of input';
      return s;
    }
  });
});

var string = Parser.prototype.string = Parser.combinator(function(chars){
  return this.continueP(function(s,f){
    var i = s.input;
    if (i.length >= chars.length) {
      var sub = i.substr(0,chars.length);
      if (sub == chars) {
        s.input = i.substr(chars.length);
        s.unit = chars;
        return f(s);
      } else {
        s.error = 'Expecting ' + chars + ', but found ' + sub;
        return s;
      }
    } else {
      s.error = 'Unexpected end of input, expected: ' +
        chars.substr(i.length);
      return s;
    }
  });
});

// Parse a letter
var letter = Parser.prototype.letter = Parser.combinator(function(p){
  return typeof p == 'undefined'?
    this.satisfy(function(c){ return !!c.match(/[a-zA-Z]/); },'letter')
  : this.satisfy(function(c){ return p == c; },p);
});

// Parse a digit
var digit = Parser.prototype.digit = Parser.combinator(function(n){
  return typeof n == 'number'?
    this.satisfy(function(c){ return c.match(/[0-9]/) && c*1 == n },n.toString())
  : this.satisfy(function(c){ return !!c.match(/[0-9]/); },'0-9');
});

(function(){

  function FieldParser(){};

  FieldParser.prototype = new Parser;

  var field = FieldParser.prototype.field = Parser.combinator(function(){
    return this
      .many(letter('*'))
      .bind(function(required){
        return this
          .many(satisfy(function(c){ return c.match(/[^:]/); }))
          .bind(function(title){
            return this
              .letter(':')
              .many1(letter(' '))
              .letter('[')
              .many(satisfy(function(c){ return c.match(/[^\]]/); }))
              .bind(function(def){
                return this
                  .letter(']')
                  .or(inject(function(){
                    return this
                      .many1(letter(' '))
                      .string('(must be: ')
                      .many1(satisfy(function(c){ return c.match(/[^\)]/); }))
                      .bind(function(type){
                        return this
                          .letter(')')
                          .eof()
                          .unit({required: required == '*',
                                 title: title,
                                 def: def,
                                 type:type});
                      });
                  }),eof);
              });
          });
      });
  });

  console.log(new FieldParser().field().parse('*Name: [ ] (must be: email)'));

})();