File: json.js

package info (click to toggle)
nodejs 4.8.2~dfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 62,476 kB
  • ctags: 111,183
  • sloc: cpp: 661,544; ansic: 31,406; python: 23,073; makefile: 1,418; sh: 1,384; perl: 255; lisp: 222; ruby: 76; xml: 50
file content (585 lines) | stat: -rw-r--r-- 16,815 bytes parent folder | download | duplicates (3)
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
'use strict';

module.exports = doJSON;

// Take the lexed input, and return a JSON-encoded object
// A module looks like this: https://gist.github.com/1777387

const common = require('./common.js');
const marked = require('marked');

// customized heading without id attribute
var renderer = new marked.Renderer();
renderer.heading = function(text, level) {
  return '<h' + level + '>' + text + '</h' + level + '>\n';
};
marked.setOptions({
  renderer: renderer
});

function doJSON(input, filename, cb) {
  var root = {source: filename};
  var stack = [root];
  var depth = 0;
  var current = root;
  var state = null;
  var lexed = marked.lexer(input);
  lexed.forEach(function(tok) {
    var type = tok.type;
    var text = tok.text;

    // <!-- type = module -->
    // This is for cases where the markdown semantic structure is lacking.
    if (type === 'paragraph' || type === 'html') {
      var metaExpr = /<!--([^=]+)=([^\-]+)-->\n*/g;
      text = text.replace(metaExpr, function(_0, k, v) {
        current[k.trim()] = v.trim();
        return '';
      });
      text = text.trim();
      if (!text) return;
    }

    if (type === 'heading' &&
        !text.trim().match(/^example/i)) {
      if (tok.depth - depth > 1) {
        return;
      }

      // Sometimes we have two headings with a single
      // blob of description.  Treat as a clone.
      if (current &&
          state === 'AFTERHEADING' &&
          depth === tok.depth) {
        var clone = current;
        current = newSection(tok);
        current.clone = clone;
        // don't keep it around on the stack.
        stack.pop();
      } else {
        // if the level is greater than the current depth,
        // then it's a child, so we should just leave the stack
        // as it is.
        // However, if it's a sibling or higher, then it implies
        // the closure of the other sections that came before.
        // root is always considered the level=0 section,
        // and the lowest heading is 1, so this should always
        // result in having a valid parent node.
        var d = tok.depth;
        while (d <= depth) {
          finishSection(stack.pop(), stack[stack.length - 1]);
          d++;
        }
        current = newSection(tok);
      }

      depth = tok.depth;
      stack.push(current);
      state = 'AFTERHEADING';
      return;
    } // heading

    // Immediately after a heading, we can expect the following
    //
    // { type: 'blockquote_start' }
    // { type: 'paragraph', text: 'Stability: ...' },
    // { type: 'blockquote_end' }
    //
    // a list: starting with list_start, ending with list_end,
    // maybe containing other nested lists in each item.
    //
    // If one of these isn't found, then anything that comes between
    // here and the next heading should be parsed as the desc.
    var stability;
    if (state === 'AFTERHEADING') {
      if (type === 'blockquote_start') {
        state = 'AFTERHEADING_BLOCKQUOTE';
        return;
      } else if (type === 'list_start' && !tok.ordered) {
        state = 'AFTERHEADING_LIST';
        current.list = current.list || [];
        current.list.push(tok);
        current.list.level = 1;
      } else if (type === 'html' && common.isYAMLBlock(tok.text)) {
        current.meta = parseYAML(tok.text);
      } else {
        current.desc = current.desc || [];
        if (!Array.isArray(current.desc)) {
          current.shortDesc = current.desc;
          current.desc = [];
        }
        current.desc.links = lexed.links;
        current.desc.push(tok);
        state = 'DESC';
      }
      return;
    }

    if (state === 'AFTERHEADING_LIST') {
      current.list.push(tok);
      if (type === 'list_start') {
        current.list.level++;
      } else if (type === 'list_end') {
        current.list.level--;
      }
      if (current.list.level === 0) {
        state = 'AFTERHEADING';
        processList(current);
      }
      return;
    }

    if (state === 'AFTERHEADING_BLOCKQUOTE') {
      if (type === 'blockquote_end') {
        state = 'AFTERHEADING';
        return;
      }

      if (type === 'paragraph' &&
          (stability = text.match(/^Stability: ([0-5])(?:\s*-\s*)?(.*)$/))) {
        current.stability = parseInt(stability[1], 10);
        current.stabilityText = stability[2].trim();
        return;
      }
    }

    current.desc = current.desc || [];
    current.desc.links = lexed.links;
    current.desc.push(tok);

  });

  // finish any sections left open
  while (root !== (current = stack.pop())) {
    finishSection(current, stack[stack.length - 1]);
  }

  return cb(null, root);
}


// go from something like this:
// [ { type: 'list_item_start' },
//   { type: 'text',
//     text: '`settings` Object, Optional' },
//   { type: 'list_start', ordered: false },
//   { type: 'list_item_start' },
//   { type: 'text',
//     text: 'exec: String, file path to worker file.  Default: `__filename`' },
//   { type: 'list_item_end' },
//   { type: 'list_item_start' },
//   { type: 'text',
//     text: 'args: Array, string arguments passed to worker.' },
//   { type: 'text',
//     text: 'Default: `process.argv.slice(2)`' },
//   { type: 'list_item_end' },
//   { type: 'list_item_start' },
//   { type: 'text',
//     text: 'silent: Boolean, whether to send output to parent\'s stdio.' },
//   { type: 'text', text: 'Default: `false`' },
//   { type: 'space' },
//   { type: 'list_item_end' },
//   { type: 'list_end' },
//   { type: 'list_item_end' },
//   { type: 'list_end' } ]
// to something like:
// [ { name: 'settings',
//     type: 'object',
//     optional: true,
//     settings:
//      [ { name: 'exec',
//          type: 'string',
//          desc: 'file path to worker file',
//          default: '__filename' },
//        { name: 'args',
//          type: 'array',
//          default: 'process.argv.slice(2)',
//          desc: 'string arguments passed to worker.' },
//        { name: 'silent',
//          type: 'boolean',
//          desc: 'whether to send output to parent\'s stdio.',
//          default: 'false' } ] } ]

function processList(section) {
  var list = section.list;
  var values = [];
  var current;
  var stack = [];

  // for now, *just* build the heirarchical list
  list.forEach(function(tok) {
    var type = tok.type;
    if (type === 'space') return;
    if (type === 'list_item_start' || type === 'loose_item_start') {
      var n = {};
      if (!current) {
        values.push(n);
        current = n;
      } else {
        current.options = current.options || [];
        stack.push(current);
        current.options.push(n);
        current = n;
      }
      return;
    } else if (type === 'list_item_end') {
      if (!current) {
        throw new Error('invalid list - end without current item\n' +
                        JSON.stringify(tok) + '\n' +
                        JSON.stringify(list));
      }
      current = stack.pop();
    } else if (type === 'text') {
      if (!current) {
        throw new Error('invalid list - text without current item\n' +
                        JSON.stringify(tok) + '\n' +
                        JSON.stringify(list));
      }
      current.textRaw = current.textRaw || '';
      current.textRaw += tok.text + ' ';
    }
  });

  // shove the name in there for properties, since they are always
  // just going to be the value etc.
  if (section.type === 'property' && values[0]) {
    values[0].textRaw = '`' + section.name + '` ' + values[0].textRaw;
  }

  // now pull the actual values out of the text bits.
  values.forEach(parseListItem);

  // Now figure out what this list actually means.
  // depending on the section type, the list could be different things.

  switch (section.type) {
    case 'ctor':
    case 'classMethod':
    case 'method':
      // each item is an argument, unless the name is 'return',
      // in which case it's the return value.
      section.signatures = section.signatures || [];
      var sig = {};
      section.signatures.push(sig);
      sig.params = values.filter(function(v) {
        if (v.name === 'return') {
          sig.return = v;
          return false;
        }
        return true;
      });
      parseSignature(section.textRaw, sig);
      break;

    case 'property':
      // there should be only one item, which is the value.
      // copy the data up to the section.
      var value = values[0] || {};
      delete value.name;
      section.typeof = value.type || section.typeof;
      delete value.type;
      Object.keys(value).forEach(function(k) {
        section[k] = value[k];
      });
      break;

    case 'event':
      // event: each item is an argument.
      section.params = values;
      break;

    default:
      if (section.list.length > 0) {
        section.desc = section.desc || [];
        for (var i = 0; i < section.list.length; i++) {
          section.desc.push(section.list[i]);
        }
      }
  }

  // section.listParsed = values;
  delete section.list;
}

function parseYAML(text) {
  return common.extractAndParseYAML(text);
}

// textRaw = "someobject.someMethod(a[, b=100][, c])"
function parseSignature(text, sig) {
  var params = text.match(paramExpr);
  if (!params) return;
  params = params[1];
  params = params.split(/,/);
  var optionalLevel = 0;
  var optionalCharDict = {'[': 1, ' ': 0, ']': -1};
  params.forEach(function(p, i, _) {
    p = p.trim();
    if (!p) return;
    var param = sig.params[i];
    var optional = false;
    var def;

    // for grouped optional params such as someMethod(a[, b[, c]])
    var pos;
    for (pos = 0; pos < p.length; pos++) {
      if (optionalCharDict[p[pos]] === undefined) { break; }
      optionalLevel += optionalCharDict[p[pos]];
    }
    p = p.substring(pos);
    optional = (optionalLevel > 0);
    for (pos = p.length - 1; pos >= 0; pos--) {
      if (optionalCharDict[p[pos]] === undefined) { break; }
      optionalLevel += optionalCharDict[p[pos]];
    }
    p = p.substring(0, pos + 1);

    var eq = p.indexOf('=');
    if (eq !== -1) {
      def = p.substr(eq + 1);
      p = p.substr(0, eq);
    }
    if (!param) {
      param = sig.params[i] = { name: p };
    }
    // at this point, the name should match.
    if (p !== param.name) {
      console.error('Warning: invalid param "%s"', p);
      console.error(' > ' + JSON.stringify(param));
      console.error(' > ' + text);
    }
    if (optional) param.optional = true;
    if (def !== undefined) param.default = def;
  });
}


function parseListItem(item) {
  if (item.options) item.options.forEach(parseListItem);
  if (!item.textRaw) return;

  // the goal here is to find the name, type, default, and optional.
  // anything left over is 'desc'
  var text = item.textRaw.trim();
  // text = text.replace(/^(Argument|Param)s?\s*:?\s*/i, '');

  text = text.replace(/^, /, '').trim();
  var retExpr = /^returns?\s*:?\s*/i;
  var ret = text.match(retExpr);
  if (ret) {
    item.name = 'return';
    text = text.replace(retExpr, '');
  } else {
    var nameExpr = /^['`"]?([^'`": \{]+)['`"]?\s*:?\s*/;
    var name = text.match(nameExpr);
    if (name) {
      item.name = name[1];
      text = text.replace(nameExpr, '');
    }
  }

  text = text.trim();
  var defaultExpr = /\(default\s*[:=]?\s*['"`]?([^, '"`]*)['"`]?\)/i;
  var def = text.match(defaultExpr);
  if (def) {
    item.default = def[1];
    text = text.replace(defaultExpr, '');
  }

  text = text.trim();
  var typeExpr = /^\{([^\}]+)\}/;
  var type = text.match(typeExpr);
  if (type) {
    item.type = type[1];
    text = text.replace(typeExpr, '');
  }

  text = text.trim();
  var optExpr = /^Optional\.|(?:, )?Optional$/;
  var optional = text.match(optExpr);
  if (optional) {
    item.optional = true;
    text = text.replace(optExpr, '');
  }

  text = text.replace(/^\s*-\s*/, '');
  text = text.trim();
  if (text) item.desc = text;
}


function finishSection(section, parent) {
  if (!section || !parent) {
    throw new Error('Invalid finishSection call\n' +
                    JSON.stringify(section) + '\n' +
                    JSON.stringify(parent));
  }

  if (!section.type) {
    section.type = 'module';
    if (parent && (parent.type === 'misc')) {
      section.type = 'misc';
    }
    section.displayName = section.name;
    section.name = section.name.toLowerCase()
      .trim().replace(/\s+/g, '_');
  }

  if (section.desc && Array.isArray(section.desc)) {
    section.desc.links = section.desc.links || [];
    section.desc = marked.parser(section.desc);
  }

  if (!section.list) section.list = [];
  processList(section);

  // classes sometimes have various 'ctor' children
  // which are actually just descriptions of a constructor
  // class signature.
  // Merge them into the parent.
  if (section.type === 'class' && section.ctors) {
    section.signatures = section.signatures || [];
    var sigs = section.signatures;
    section.ctors.forEach(function(ctor) {
      ctor.signatures = ctor.signatures || [{}];
      ctor.signatures.forEach(function(sig) {
        sig.desc = ctor.desc;
      });
      sigs.push.apply(sigs, ctor.signatures);
    });
    delete section.ctors;
  }

  // properties are a bit special.
  // their "type" is the type of object, not "property"
  if (section.properties) {
    section.properties.forEach(function(p) {
      if (p.typeof) p.type = p.typeof;
      else delete p.type;
      delete p.typeof;
    });
  }

  // handle clones
  if (section.clone) {
    var clone = section.clone;
    delete section.clone;
    delete clone.clone;
    deepCopy(section, clone);
    finishSection(clone, parent);
  }

  var plur;
  if (section.type.slice(-1) === 's') {
    plur = section.type + 'es';
  } else if (section.type.slice(-1) === 'y') {
    plur = section.type.replace(/y$/, 'ies');
  } else {
    plur = section.type + 's';
  }

  // if the parent's type is 'misc', then it's just a random
  // collection of stuff, like the "globals" section.
  // Make the children top-level items.
  if (section.type === 'misc') {
    Object.keys(section).forEach(function(k) {
      switch (k) {
        case 'textRaw':
        case 'name':
        case 'type':
        case 'desc':
        case 'miscs':
          return;
        default:
          if (parent.type === 'misc') {
            return;
          }
          if (Array.isArray(k) && parent[k]) {
            parent[k] = parent[k].concat(section[k]);
          } else if (!parent[k]) {
            parent[k] = section[k];
          } else {
            // parent already has, and it's not an array.
            return;
          }
      }
    });
  }

  parent[plur] = parent[plur] || [];
  parent[plur].push(section);
}


// Not a general purpose deep copy.
// But sufficient for these basic things.
function deepCopy(src, dest) {
  Object.keys(src).filter(function(k) {
    return !dest.hasOwnProperty(k);
  }).forEach(function(k) {
    dest[k] = deepCopy_(src[k]);
  });
}

function deepCopy_(src) {
  if (!src) return src;
  if (Array.isArray(src)) {
    const c = new Array(src.length);
    src.forEach(function(v, i) {
      c[i] = deepCopy_(v);
    });
    return c;
  }
  if (typeof src === 'object') {
    const c = {};
    Object.keys(src).forEach(function(k) {
      c[k] = deepCopy_(src[k]);
    });
    return c;
  }
  return src;
}


// these parse out the contents of an H# tag
var eventExpr = /^Event(?::|\s)+['"]?([^"']+).*$/i;
var classExpr = /^Class:\s*([^ ]+).*?$/i;
var propExpr = /^(?:property:?\s*)?[^.]+\.([^ .()]+)\s*?$/i;
var braceExpr = /^(?:property:?\s*)?[^.\[]+(\[[^\]]+\])\s*?$/i;
var classMethExpr =
  /^class\s*method\s*:?[^.]+\.([^ .()]+)\([^)]*\)\s*?$/i;
var methExpr =
  /^(?:method:?\s*)?(?:[^.]+\.)?([^ .()]+)\([^)]*\)\s*?$/i;
var newExpr = /^new ([A-Z][a-zA-Z]+)\([^\)]*\)\s*?$/;
var paramExpr = /\((.*)\);?$/;

function newSection(tok) {
  var section = {};
  // infer the type from the text.
  var text = section.textRaw = tok.text;
  if (text.match(eventExpr)) {
    section.type = 'event';
    section.name = text.replace(eventExpr, '$1');
  } else if (text.match(classExpr)) {
    section.type = 'class';
    section.name = text.replace(classExpr, '$1');
  } else if (text.match(braceExpr)) {
    section.type = 'property';
    section.name = text.replace(braceExpr, '$1');
  } else if (text.match(propExpr)) {
    section.type = 'property';
    section.name = text.replace(propExpr, '$1');
  } else if (text.match(classMethExpr)) {
    section.type = 'classMethod';
    section.name = text.replace(classMethExpr, '$1');
  } else if (text.match(methExpr)) {
    section.type = 'method';
    section.name = text.replace(methExpr, '$1');
  } else if (text.match(newExpr)) {
    section.type = 'ctor';
    section.name = text.replace(newExpr, '$1');
  } else {
    section.name = text;
  }
  return section;
}