all files / lib/parsec/ parser.js

99.38% Statements 159/160
100% Branches 30/30
100% Functions 91/91
99.35% Lines 152/153
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 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421                                            148031×         43306×   39160×               4146×                 22901× 60378×   43306×     17072×             19001× 191024×   47829×     143195× 43×   143152× 143152×                     22901×       66997×   66997× 157584×         21924×   21924× 8024×         21922× 8017×         22897× 43292× 39154×           6736× 17448×         9063×       15307× 15694×         19001×       494×       617× 30165×         30165× 94504× 94504× 94504×   94504×     30165× 26047×     4118×         4844×       11×       92633×       17×   17× 17×                       6529× 3491×         9563× 5608×         19× 4679×         39× 37×             227× 140535× 100500×   40035×           30× 365×   56×     309×             19× 187×         18×       6614×                         4660×         144×     143× 9107×             70919×         44× 48809×         116×         200× 124921× 5755×   119166×                       4086×           871× 1110×       557×           555×     555×                                                        
/*
 * Parsec
 * https://github.com/d-plaindoux/parsec
 *
 * Copyright (c) 2016 Didier Plaindoux
 * Licensed under the LGPL2 license.
 */
 
 /*
  * Parsec: Direct Style Monadic Parser Combinators For The Real World
  * 
  * http://research.microsoft.com/en-us/um/people/daan/download/papers/parsec-paper.pdf
  */
 
module.exports = (function () {
    
    'use strict';
    
    var response = require('./response.js'),
        stream = require('../stream/index.js'),
        unit = require('../data/unit.js'),
        option = require('../data/option.js');
    
    // (Stream 'c -> number -> Response 'a 'c) -> Parser 'a 'c
    function Parser(parse) {
        this.parse = parse;
    }
    
    
    // Response 'a 'c -> ('a -> Parser 'b 'c) -> Response 'b 'c
    function bindAccepted(accept_a, f) {
        return f(accept_a.value).parse(accept_a.input,accept_a.offset).fold(
            function(accept_b) {
                return response.accept(
                    accept_b.value, 
                    accept_b.input, 
                    accept_b.offset, 
                    accept_a.consumed || accept_b.consumed
                ); 
            },
            function(reject_b) {
                return response.reject(
                    accept_a.input.location(reject_b.offset), 
                    accept_a.consumed || reject_b.consumed
                );
            }                       
        );
    }
    
    // Parser 'a 'c -> ('a -> Parser 'b 'c) -> Parser 'b 'c
    function bind(self, f) {
        return new Parser(function(input,index) {
           return self.parse(input,index).fold(
               function(accept_a) {
                   return bindAccepted(accept_a, f);
               },
               function(reject_a) {
                   return reject_a;
               }
           ); 
        });
    }
    
    // Parser 'a 'c -> Parser 'a 'c -> Parser 'a 'c
    function choice(self, f) {
        return new Parser(function(input,index) {
            return self.parse(input, index).fold(
                function (accept) {
                    return accept;
                },
                function (reject) {
                    if (reject.consumed) {
                        return reject;
                    } else {                    
                        try {
                            return f.parse(input,index);
                        } catch(e) {
                            throw e;
                        }
                    }
                }
            );
        });
    }
    
    // Parser 'a 'c => ('a -> Parser 'b 'c) -> Parser 'b 'c
    Parser.prototype.flatmap = function(f) {
      return bind(this, f);  
    };
 
    // Parser 'a 'c => ('a -> 'b) -> Parser 'b 'c
    Parser.prototype.map = function(f) {
        var self = this;
        
        return new Parser(function(input,index) {
           return self.parse(input,index).map(f); 
        });
    };
    
    // Parser 'a 'c => ('a -> boolean) -> Parser 'a 'c
    Parser.prototype.filter = function(p) {
        var self = this;
        
        return new Parser(function(input,index) {
           return self.parse(input,index).filter(p); 
        });
    };
    
    // Parser 'a 'c => Comparable 'a -> Parser 'a 'c
    Parser.prototype.match = function(v) {
        return this.filter(function(a) {
            return a === v;
        });
    };
    
    // Parser 'a 'c => Parser 'b 'c -> Parser ('a,'b) 'c
    Parser.prototype.then = function(p) {
        return this.flatmap(function(a) {
            return p.map(function(b) {
                return [a,b];
            });
        });
    };
    
    // Parser 'a 'c => Parser 'b 'c -> Parser 'a 'c
    Parser.prototype.thenLeft = function(p) {
        return this.then(p).map(function(r) {
           return r[0]; 
        });
    };
    
    // Parser 'a 'c => 'b -> Parser 'b 'c
    Parser.prototype.thenReturns = function(v) {
        return this.thenRight(returns(v));
    };    
    
    // Parser 'a 'c => Parser 'b 'c -> Parser 'b 'c
    Parser.prototype.thenRight = function(p) {
        return this.then(p).map(function(r) {
           return r[1]; 
        });
    };
    
    // Parser 'a 'c -> Parser 'a 'c
    Parser.prototype.or = function(p) {
        return choice(this, p);
    };
    
    // Parser 'a 'c => unit -> Parser (Option 'a) 'c
    Parser.prototype.opt = function() {
        return this.map(option.some).or(returns(option.none()));
    };
    
    // Parser 'a 'c -> unit -> Parser (List 'a) 'c
    function repeatable(self, occurrences, accept) {
        return new Parser(function(input, index) {
            var consumed = false,
                value = [],
                offset = index,
                current = self.parse(input, index);
        
            while(current.isAccepted() && occurrences(value.length)) {
                value.push(current.value);
                consumed = consumed || current.consumed;
                offset = current.offset;
                
                current = self.parse(input, offset);
            }
            
            if (accept(value.length)) {
                return response.accept(value, input, offset, consumed);
            }
            
            return response.reject(offset, consumed);
        });
    }
    
    // Parser 'a 'c => unit -> Parser (List 'a) 'c
    Parser.prototype.rep = function() {
        return repeatable(this, function() { return true; }, function(l) { return l !== 0; });
    };
    
    // Parser 'a 'c => number -> Parser (List 'a) 'c
    Parser.prototype.occ = function(occurrence) {
        return repeatable(this, function(l) { return l < occurrence; }, function(l) { return l === occurrence; });
    };
    
    // Parser 'a 'c => unit -> Parser (List 'a) 'c
    Parser.prototype.optrep = function() {
        return repeatable(this, function() { return true; }, function() { return true; });
    };
        
    // Parser 'a 'c => Parser 'b 'a -> Parser 'b 'c
    Parser.prototype.chain = function(p) {
        var self = this;
        
        return new Parser(function(input,index) {
            return p.parse(stream.buffered(stream.ofParser(self,input)), index);
        });
    };
    
    /*
     * Builders
     */
    
    // (Stream 'c -> number -> Response 'a 'c) -> Parser 'a 'c
    function parse(p) { 
        return new Parser(p); 
    }
    
    // (('b -> Parser 'a 'c) * 'b)-> Parser 'a 'c
    function lazy(p, parameters) {
        return new Parser(function(input,index) {
            return p.apply(null, parameters).parse(input,index);
        });        
    }
    
    // 'a -> Parser 'a 'c
    function returns(v) {
        return new Parser(function(input,index) {
            return response.accept(v, input, index, false);
        });
    }
 
    // unit -> Parser 'a 'c
    function error() {
        return new Parser(function(input, index) {
            return response.reject(input.location(index), false);
        });
    }
    
    // unit -> Parser unit 'c
    function eos() {
        return new Parser(function(input,index) {
            if (input.endOfStream(index)) {
                return response.accept(unit, input, index, false);   
            } else {
                return response.reject(input.location(index), false);                
            }
        });        
    }
        
    // ('a -> boolean) -> Parser a 'c
    function satisfy(predicate) {
        return new Parser(function(input,index) {
            return input.get(index).filter(predicate).map(function(value) {
                return response.accept(value, input, index+1, true);
            }).lazyRecoverWith(function() {
                return response.reject(input.location(index), false); 
            });            
        });
    }
        
    // Parser 'a 'c -> Parser 'a 'c
    function doTry(p) {
        return new Parser(function(input,index) {
            return p.parse(input,index).fold(
                function(accept) {
                    return accept;
                },
                function(reject) {
                    return response.reject(input.location(reject.offset), false);
                }
            );
        });
    }    
        
    // unit -> Parser 'a 'c
    function any() {
        return satisfy(function() {
           return true; 
        });
    }
 
    // Parser 'a ? -> Parser 'a 'a
    function not(p) {
        return doTry(p).then(error()).or(any());
    }
   
    // unit -> Parser char char
    function digit() {
        return satisfy(function(v) {
            return '0' <= v && v <= '9'; 
        });
    }
     
    // unit -> Parser char char
    function lowerCase() {
        return satisfy(function(v) {
            return 'a' <= v && v <= 'z'; 
        });
    }
    
    // unit -> Parser char char
    function upperCase() {
        return satisfy(function(v) {
            return 'A' <= v && v <= 'Z'; 
        });
    }
        
    // unit -> Parser char char
    function letter() {
        return satisfy(function(v) {
            return ('a' <= v && v <= 'z') || ('A' <= v && v <= 'Z'); 
        });
    }
    
    // char -> Parser char char
    function char(c) {
        if (c.length !== 1) {
            throw new Error("Char parser must contains one character");
        }
        
        return satisfy(function(v) {
           return c === v; 
        });
    }
    
    // char -> Parser char char
    function notChar(c) {
        if (c.length !== 1) {
            throw new Error("Char parser must contains one character");
        }
 
        return satisfy(function(v) {
           return c !== v; 
        });
    }
    
    // string -> Parser char char
    function charIn(c) {
        return satisfy(function(v) {
           return c.indexOf(v) !== -1;
        });
    }
    
    // string -> Parser char char
    function charNotIn(c) {
        return satisfy(function(v) {
           return c.indexOf(v) === -1;
        });
    }
    
    // string -> Parser string char
    function string(s) {
        return new Parser(function (input, index) {
            if (input.subStreamAt(s.split(''), index)) {
                return response.accept(s, input, index + s.length, true);
            } else {
                return response.reject(input.location(index), false);
            }
        });
    }
 
    // string -> Parser string char
    function notString(s) {
        return not(string(s));
    }
        
    // unit -> Parser char char
    function charLiteral() {
        var anyChar = string("\\'").or(notChar("'"));
        return char("'").thenRight(anyChar).thenLeft(char("'"));
    }
    
    // unit -> Parser string char
    function stringLiteral() {
        var anyChar = string('\\"').or(notChar('"'));
        return char('"').thenRight(anyChar.optrep()).thenLeft(char('"')).map(function(r){
           return r.join('');
        });
    }
    
    // unit -> Parser number char
    function numberLiteral() {
        // [-+]?\d+([.]\d+)?([eE][+-]?\d+)?
        var join = function (r) { return r.join(''); },
            joinOrEmpty = function(r) { return r.map(join).orElse(''); },
            digits = digit().rep().map(join),
            integer = charIn("+-").opt().then(digits).
                        map(function(r) { 
                            return r[0].orElse('') + r[1]; 
                        }),
            float = integer.
                        then(char('.').then(digits).opt().map(joinOrEmpty)).
                        then(charIn('eE').then(integer).opt().map(joinOrEmpty)).
                        map(function(r) {
                            return r[0][0] + r[0][1] + r[1]; 
                        });
        
        return float.map(function(r) {
            return parseFloat(r, 10);
        });
    }
    
    return {
        parse: parse,
        lazy: lazy,
        returns: returns,
        error: error(),
        eos: eos(),
        satisfy: satisfy,
        try: doTry,
        any : any(),
        digit: digit(),
        lowerCase:lowerCase(),
        upperCase:upperCase(),
        not: not,
        letter: letter(),
        notChar: notChar,
        char: char,
        charIn: charIn,
        charNotIn: charNotIn,
        string: string,
        notString: notString,
        charLiteral: charLiteral(),
        stringLiteral : stringLiteral(),
        numberLiteral : numberLiteral()
    };
    
}());