all files / lib/standard/ jsonparser.js

100% Statements 20/20
100% Branches 0/0
100% Functions 10/10
100% Lines 20/20
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                                          21920×       160× 850× 160×   160×       310× 2152× 310×   310×       3020×                   15×     15×        
/*
 * Parsec
 * https://github.com/d-plaindoux/parsec
 *
 * Copyright (c) 2016 Didier Plaindoux
 * Licensed under the LGPL2 license.
 */
 
 module.exports = (function() {
     
     'use strict';
     
     var parser = require('../parsec/parser.js'),
         genlex = require('../genlex/genlex.js'), 
         token = require('../genlex/token.js');
     
     //
     // Facilities
     // 
     
     var tkNumber = token.parser.number,
         tkString = token.parser.string,
         tkKeyword = token.parser.keyword;
     
     function tkKey(s) {
         return tkKeyword.match(s);
     }
 
     // unit -> Parser ? Token
     function arrayOrNothing() {
         var value    = [],
             addValue = function(e) { value = value.concat(e); },
             getValue = function () { return value; },
             item     = parser.lazy(expr).map(addValue);
         return (item.then(tkKey(',').thenRight(item).optrep())).opt().map(getValue);
     }
 
     // unit -> Parser ? Token
     function objectOrNothing() {
         var value     = {},
             addValue  = function(e) { value[e[0]] = e[1]; },
             getValue  = function () { return value; },
             attribute = tkString.thenLeft(tkKey(':')).then(parser.lazy(expr)).map(addValue);
         return (attribute.thenLeft(tkKey(',').then(attribute).optrep())).opt().map(getValue);
     }
 
     // unit -> Parser ? Token
     function expr() { 
         return tkNumber.
                or(tkString).
                or(tkKey("null").thenReturns(null)).
                or(tkKey("true").thenReturns(true)).
                or(tkKey("false").thenReturns(false)).
                or(tkKey('[').thenRight(parser.lazy(arrayOrNothing)).thenLeft(tkKey(']'))).
                or(tkKey('{').thenRight(parser.lazy(objectOrNothing)).thenLeft(tkKey('}')));
     }
 
     return {
         parse : function (source) {
             var keywords = [ "null", "false", "true", "{", "}", "[", "]", ":", "," ],
                 tokenizer = genlex.generator(keywords).tokenBetweenSpaces(token.builder);
 
             return tokenizer.chain(expr().thenLeft(parser.eos)).parse(source, 0);
         }
     };
 
}());