855edfc9e63c3cba51e5ff493fb8eaf4c16f3541
[yaffs-website] / node_modules / grunt / node_modules / js-yaml / lib / js-yaml / dumper.js
1 'use strict';
2
3 /*eslint-disable no-use-before-define*/
4
5 var common              = require('./common');
6 var YAMLException       = require('./exception');
7 var DEFAULT_FULL_SCHEMA = require('./schema/default_full');
8 var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe');
9
10 var _toString       = Object.prototype.toString;
11 var _hasOwnProperty = Object.prototype.hasOwnProperty;
12
13 var CHAR_TAB                  = 0x09; /* Tab */
14 var CHAR_LINE_FEED            = 0x0A; /* LF */
15 var CHAR_CARRIAGE_RETURN      = 0x0D; /* CR */
16 var CHAR_SPACE                = 0x20; /* Space */
17 var CHAR_EXCLAMATION          = 0x21; /* ! */
18 var CHAR_DOUBLE_QUOTE         = 0x22; /* " */
19 var CHAR_SHARP                = 0x23; /* # */
20 var CHAR_PERCENT              = 0x25; /* % */
21 var CHAR_AMPERSAND            = 0x26; /* & */
22 var CHAR_SINGLE_QUOTE         = 0x27; /* ' */
23 var CHAR_ASTERISK             = 0x2A; /* * */
24 var CHAR_COMMA                = 0x2C; /* , */
25 var CHAR_MINUS                = 0x2D; /* - */
26 var CHAR_COLON                = 0x3A; /* : */
27 var CHAR_GREATER_THAN         = 0x3E; /* > */
28 var CHAR_QUESTION             = 0x3F; /* ? */
29 var CHAR_COMMERCIAL_AT        = 0x40; /* @ */
30 var CHAR_LEFT_SQUARE_BRACKET  = 0x5B; /* [ */
31 var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */
32 var CHAR_GRAVE_ACCENT         = 0x60; /* ` */
33 var CHAR_LEFT_CURLY_BRACKET   = 0x7B; /* { */
34 var CHAR_VERTICAL_LINE        = 0x7C; /* | */
35 var CHAR_RIGHT_CURLY_BRACKET  = 0x7D; /* } */
36
37 var ESCAPE_SEQUENCES = {};
38
39 ESCAPE_SEQUENCES[0x00]   = '\\0';
40 ESCAPE_SEQUENCES[0x07]   = '\\a';
41 ESCAPE_SEQUENCES[0x08]   = '\\b';
42 ESCAPE_SEQUENCES[0x09]   = '\\t';
43 ESCAPE_SEQUENCES[0x0A]   = '\\n';
44 ESCAPE_SEQUENCES[0x0B]   = '\\v';
45 ESCAPE_SEQUENCES[0x0C]   = '\\f';
46 ESCAPE_SEQUENCES[0x0D]   = '\\r';
47 ESCAPE_SEQUENCES[0x1B]   = '\\e';
48 ESCAPE_SEQUENCES[0x22]   = '\\"';
49 ESCAPE_SEQUENCES[0x5C]   = '\\\\';
50 ESCAPE_SEQUENCES[0x85]   = '\\N';
51 ESCAPE_SEQUENCES[0xA0]   = '\\_';
52 ESCAPE_SEQUENCES[0x2028] = '\\L';
53 ESCAPE_SEQUENCES[0x2029] = '\\P';
54
55 var DEPRECATED_BOOLEANS_SYNTAX = [
56   'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',
57   'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'
58 ];
59
60 function compileStyleMap(schema, map) {
61   var result, keys, index, length, tag, style, type;
62
63   if (map === null) return {};
64
65   result = {};
66   keys = Object.keys(map);
67
68   for (index = 0, length = keys.length; index < length; index += 1) {
69     tag = keys[index];
70     style = String(map[tag]);
71
72     if (tag.slice(0, 2) === '!!') {
73       tag = 'tag:yaml.org,2002:' + tag.slice(2);
74     }
75
76     type = schema.compiledTypeMap[tag];
77
78     if (type && _hasOwnProperty.call(type.styleAliases, style)) {
79       style = type.styleAliases[style];
80     }
81
82     result[tag] = style;
83   }
84
85   return result;
86 }
87
88 function encodeHex(character) {
89   var string, handle, length;
90
91   string = character.toString(16).toUpperCase();
92
93   if (character <= 0xFF) {
94     handle = 'x';
95     length = 2;
96   } else if (character <= 0xFFFF) {
97     handle = 'u';
98     length = 4;
99   } else if (character <= 0xFFFFFFFF) {
100     handle = 'U';
101     length = 8;
102   } else {
103     throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF');
104   }
105
106   return '\\' + handle + common.repeat('0', length - string.length) + string;
107 }
108
109 function State(options) {
110   this.schema       = options['schema'] || DEFAULT_FULL_SCHEMA;
111   this.indent       = Math.max(1, (options['indent'] || 2));
112   this.skipInvalid  = options['skipInvalid'] || false;
113   this.flowLevel    = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);
114   this.styleMap     = compileStyleMap(this.schema, options['styles'] || null);
115   this.sortKeys     = options['sortKeys'] || false;
116   this.lineWidth    = options['lineWidth'] || 80;
117   this.noRefs       = options['noRefs'] || false;
118   this.noCompatMode = options['noCompatMode'] || false;
119
120   this.implicitTypes = this.schema.compiledImplicit;
121   this.explicitTypes = this.schema.compiledExplicit;
122
123   this.tag = null;
124   this.result = '';
125
126   this.duplicates = [];
127   this.usedDuplicates = null;
128 }
129
130 function indentString(string, spaces) {
131   var ind = common.repeat(' ', spaces),
132       position = 0,
133       next = -1,
134       result = '',
135       line,
136       length = string.length;
137
138   while (position < length) {
139     next = string.indexOf('\n', position);
140     if (next === -1) {
141       line = string.slice(position);
142       position = length;
143     } else {
144       line = string.slice(position, next + 1);
145       position = next + 1;
146     }
147
148     if (line.length && line !== '\n') result += ind;
149
150     result += line;
151   }
152
153   return result;
154 }
155
156 function generateNextLine(state, level) {
157   return '\n' + common.repeat(' ', state.indent * level);
158 }
159
160 function testImplicitResolving(state, str) {
161   var index, length, type;
162
163   for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
164     type = state.implicitTypes[index];
165
166     if (type.resolve(str)) {
167       return true;
168     }
169   }
170
171   return false;
172 }
173
174 function StringBuilder(source) {
175   this.source = source;
176   this.result = '';
177   this.checkpoint = 0;
178 }
179
180 StringBuilder.prototype.takeUpTo = function (position) {
181   var er;
182
183   if (position < this.checkpoint) {
184     er = new Error('position should be > checkpoint');
185     er.position = position;
186     er.checkpoint = this.checkpoint;
187     throw er;
188   }
189
190   this.result += this.source.slice(this.checkpoint, position);
191   this.checkpoint = position;
192   return this;
193 };
194
195 StringBuilder.prototype.escapeChar = function () {
196   var character, esc;
197
198   character = this.source.charCodeAt(this.checkpoint);
199   esc = ESCAPE_SEQUENCES[character] || encodeHex(character);
200   this.result += esc;
201   this.checkpoint += 1;
202
203   return this;
204 };
205
206 StringBuilder.prototype.finish = function () {
207   if (this.source.length > this.checkpoint) {
208     this.takeUpTo(this.source.length);
209   }
210 };
211
212 function writeScalar(state, object, level, iskey) {
213   var simple, first, spaceWrap, folded, literal, single, double,
214       sawLineFeed, linePosition, longestLine, indent, max, character,
215       position, escapeSeq, hexEsc, previous, lineLength, modifier,
216       trailingLineBreaks, result;
217
218   if (object.length === 0) {
219     state.dump = "''";
220     return;
221   }
222
223   if (!state.noCompatMode &&
224       DEPRECATED_BOOLEANS_SYNTAX.indexOf(object) !== -1) {
225     state.dump = "'" + object + "'";
226     return;
227   }
228
229   simple = true;
230   first = object.length ? object.charCodeAt(0) : 0;
231   spaceWrap = (CHAR_SPACE === first ||
232                CHAR_SPACE === object.charCodeAt(object.length - 1));
233
234   // Simplified check for restricted first characters
235   // http://www.yaml.org/spec/1.2/spec.html#ns-plain-first%28c%29
236   if (CHAR_MINUS         === first ||
237       CHAR_QUESTION      === first ||
238       CHAR_COMMERCIAL_AT === first ||
239       CHAR_GRAVE_ACCENT  === first) {
240     simple = false;
241   }
242
243   // Can only use > and | if not wrapped in spaces or is not a key.
244   // Also, don't use if in flow mode.
245   if (spaceWrap || (state.flowLevel > -1 && state.flowLevel <= level)) {
246     if (spaceWrap) simple = false;
247
248     folded = false;
249     literal = false;
250   } else {
251     folded = !iskey;
252     literal = !iskey;
253   }
254
255   single = true;
256   double = new StringBuilder(object);
257
258   sawLineFeed = false;
259   linePosition = 0;
260   longestLine = 0;
261
262   indent = state.indent * level;
263   max = state.lineWidth;
264
265   // Replace -1 with biggest ingeger number according to
266   // http://ecma262-5.com/ELS5_HTML.htm#Section_8.5
267   if (max === -1) max = 9007199254740991;
268
269   if (indent < 40) max -= indent;
270   else max = 40;
271
272   for (position = 0; position < object.length; position++) {
273     character = object.charCodeAt(position);
274     if (simple) {
275       // Characters that can never appear in the simple scalar
276       if (!simpleChar(character)) {
277         simple = false;
278       } else {
279         // Still simple.  If we make it all the way through like
280         // this, then we can just dump the string as-is.
281         continue;
282       }
283     }
284
285     if (single && character === CHAR_SINGLE_QUOTE) {
286       single = false;
287     }
288
289     escapeSeq = ESCAPE_SEQUENCES[character];
290     hexEsc = needsHexEscape(character);
291
292     if (!escapeSeq && !hexEsc) {
293       continue;
294     }
295
296     if (character !== CHAR_LINE_FEED &&
297         character !== CHAR_DOUBLE_QUOTE &&
298         character !== CHAR_SINGLE_QUOTE) {
299       folded = false;
300       literal = false;
301     } else if (character === CHAR_LINE_FEED) {
302       sawLineFeed = true;
303       single = false;
304       if (position > 0) {
305         previous = object.charCodeAt(position - 1);
306         if (previous === CHAR_SPACE) {
307           literal = false;
308           folded = false;
309         }
310       }
311       if (folded) {
312         lineLength = position - linePosition;
313         linePosition = position;
314         if (lineLength > longestLine) longestLine = lineLength;
315       }
316     }
317
318     if (character !== CHAR_DOUBLE_QUOTE) single = false;
319
320     double.takeUpTo(position);
321     double.escapeChar();
322   }
323
324   if (simple && testImplicitResolving(state, object)) simple = false;
325
326   modifier = '';
327   if (folded || literal) {
328     trailingLineBreaks = 0;
329     if (object.charCodeAt(object.length - 1) === CHAR_LINE_FEED) {
330       trailingLineBreaks += 1;
331       if (object.charCodeAt(object.length - 2) === CHAR_LINE_FEED) {
332         trailingLineBreaks += 1;
333       }
334     }
335
336     if (trailingLineBreaks === 0) modifier = '-';
337     else if (trailingLineBreaks === 2) modifier = '+';
338   }
339
340   if (literal && longestLine < max || state.tag !== null) {
341     folded = false;
342   }
343
344   // If it's literally one line, then don't bother with the literal.
345   // We may still want to do a fold, though, if it's a super long line.
346   if (!sawLineFeed) literal = false;
347
348   if (simple) {
349     state.dump = object;
350   } else if (single) {
351     state.dump = '\'' + object + '\'';
352   } else if (folded) {
353     result = fold(object, max);
354     state.dump = '>' + modifier + '\n' + indentString(result, indent);
355   } else if (literal) {
356     if (!modifier) object = object.replace(/\n$/, '');
357     state.dump = '|' + modifier + '\n' + indentString(object, indent);
358   } else if (double) {
359     double.finish();
360     state.dump = '"' + double.result + '"';
361   } else {
362     throw new Error('Failed to dump scalar value');
363   }
364
365   return;
366 }
367
368 // The `trailing` var is a regexp match of any trailing `\n` characters.
369 //
370 // There are three cases we care about:
371 //
372 // 1. One trailing `\n` on the string.  Just use `|` or `>`.
373 //    This is the assumed default. (trailing = null)
374 // 2. No trailing `\n` on the string.  Use `|-` or `>-` to "chomp" the end.
375 // 3. More than one trailing `\n` on the string.  Use `|+` or `>+`.
376 //
377 // In the case of `>+`, these line breaks are *not* doubled (like the line
378 // breaks within the string), so it's important to only end with the exact
379 // same number as we started.
380 function fold(object, max) {
381   var result = '',
382       position = 0,
383       length = object.length,
384       trailing = /\n+$/.exec(object),
385       newLine;
386
387   if (trailing) {
388     length = trailing.index + 1;
389   }
390
391   while (position < length) {
392     newLine = object.indexOf('\n', position);
393     if (newLine > length || newLine === -1) {
394       if (result) result += '\n\n';
395       result += foldLine(object.slice(position, length), max);
396       position = length;
397
398     } else {
399       if (result) result += '\n\n';
400       result += foldLine(object.slice(position, newLine), max);
401       position = newLine + 1;
402     }
403   }
404
405   if (trailing && trailing[0] !== '\n') result += trailing[0];
406
407   return result;
408 }
409
410 function foldLine(line, max) {
411   if (line === '') return line;
412
413   var foldRe = /[^\s] [^\s]/g,
414       result = '',
415       prevMatch = 0,
416       foldStart = 0,
417       match = foldRe.exec(line),
418       index,
419       foldEnd,
420       folded;
421
422   while (match) {
423     index = match.index;
424
425     // when we cross the max len, if the previous match would've
426     // been ok, use that one, and carry on.  If there was no previous
427     // match on this fold section, then just have a long line.
428     if (index - foldStart > max) {
429       if (prevMatch !== foldStart) foldEnd = prevMatch;
430       else foldEnd = index;
431
432       if (result) result += '\n';
433       folded = line.slice(foldStart, foldEnd);
434       result += folded;
435       foldStart = foldEnd + 1;
436     }
437     prevMatch = index + 1;
438     match = foldRe.exec(line);
439   }
440
441   if (result) result += '\n';
442
443   // if we end up with one last word at the end, then the last bit might
444   // be slightly bigger than we wanted, because we exited out of the loop.
445   if (foldStart !== prevMatch && line.length - foldStart > max) {
446     result += line.slice(foldStart, prevMatch) + '\n' +
447               line.slice(prevMatch + 1);
448   } else {
449     result += line.slice(foldStart);
450   }
451
452   return result;
453 }
454
455 // Returns true if character can be found in a simple scalar
456 function simpleChar(character) {
457   return CHAR_TAB                  !== character &&
458          CHAR_LINE_FEED            !== character &&
459          CHAR_CARRIAGE_RETURN      !== character &&
460          CHAR_COMMA                !== character &&
461          CHAR_LEFT_SQUARE_BRACKET  !== character &&
462          CHAR_RIGHT_SQUARE_BRACKET !== character &&
463          CHAR_LEFT_CURLY_BRACKET   !== character &&
464          CHAR_RIGHT_CURLY_BRACKET  !== character &&
465          CHAR_SHARP                !== character &&
466          CHAR_AMPERSAND            !== character &&
467          CHAR_ASTERISK             !== character &&
468          CHAR_EXCLAMATION          !== character &&
469          CHAR_VERTICAL_LINE        !== character &&
470          CHAR_GREATER_THAN         !== character &&
471          CHAR_SINGLE_QUOTE         !== character &&
472          CHAR_DOUBLE_QUOTE         !== character &&
473          CHAR_PERCENT              !== character &&
474          CHAR_COLON                !== character &&
475          !ESCAPE_SEQUENCES[character]            &&
476          !needsHexEscape(character);
477 }
478
479 // Returns true if the character code needs to be escaped.
480 function needsHexEscape(character) {
481   return !((0x00020 <= character && character <= 0x00007E) ||
482            (character === 0x00085)                         ||
483            (0x000A0 <= character && character <= 0x00D7FF) ||
484            (0x0E000 <= character && character <= 0x00FFFD) ||
485            (0x10000 <= character && character <= 0x10FFFF));
486 }
487
488 function writeFlowSequence(state, level, object) {
489   var _result = '',
490       _tag    = state.tag,
491       index,
492       length;
493
494   for (index = 0, length = object.length; index < length; index += 1) {
495     // Write only valid elements.
496     if (writeNode(state, level, object[index], false, false)) {
497       if (index !== 0) _result += ', ';
498       _result += state.dump;
499     }
500   }
501
502   state.tag = _tag;
503   state.dump = '[' + _result + ']';
504 }
505
506 function writeBlockSequence(state, level, object, compact) {
507   var _result = '',
508       _tag    = state.tag,
509       index,
510       length;
511
512   for (index = 0, length = object.length; index < length; index += 1) {
513     // Write only valid elements.
514     if (writeNode(state, level + 1, object[index], true, true)) {
515       if (!compact || index !== 0) {
516         _result += generateNextLine(state, level);
517       }
518       _result += '- ' + state.dump;
519     }
520   }
521
522   state.tag = _tag;
523   state.dump = _result || '[]'; // Empty sequence if no valid values.
524 }
525
526 function writeFlowMapping(state, level, object) {
527   var _result       = '',
528       _tag          = state.tag,
529       objectKeyList = Object.keys(object),
530       index,
531       length,
532       objectKey,
533       objectValue,
534       pairBuffer;
535
536   for (index = 0, length = objectKeyList.length; index < length; index += 1) {
537     pairBuffer = '';
538
539     if (index !== 0) pairBuffer += ', ';
540
541     objectKey = objectKeyList[index];
542     objectValue = object[objectKey];
543
544     if (!writeNode(state, level, objectKey, false, false)) {
545       continue; // Skip this pair because of invalid key;
546     }
547
548     if (state.dump.length > 1024) pairBuffer += '? ';
549
550     pairBuffer += state.dump + ': ';
551
552     if (!writeNode(state, level, objectValue, false, false)) {
553       continue; // Skip this pair because of invalid value.
554     }
555
556     pairBuffer += state.dump;
557
558     // Both key and value are valid.
559     _result += pairBuffer;
560   }
561
562   state.tag = _tag;
563   state.dump = '{' + _result + '}';
564 }
565
566 function writeBlockMapping(state, level, object, compact) {
567   var _result       = '',
568       _tag          = state.tag,
569       objectKeyList = Object.keys(object),
570       index,
571       length,
572       objectKey,
573       objectValue,
574       explicitPair,
575       pairBuffer;
576
577   // Allow sorting keys so that the output file is deterministic
578   if (state.sortKeys === true) {
579     // Default sorting
580     objectKeyList.sort();
581   } else if (typeof state.sortKeys === 'function') {
582     // Custom sort function
583     objectKeyList.sort(state.sortKeys);
584   } else if (state.sortKeys) {
585     // Something is wrong
586     throw new YAMLException('sortKeys must be a boolean or a function');
587   }
588
589   for (index = 0, length = objectKeyList.length; index < length; index += 1) {
590     pairBuffer = '';
591
592     if (!compact || index !== 0) {
593       pairBuffer += generateNextLine(state, level);
594     }
595
596     objectKey = objectKeyList[index];
597     objectValue = object[objectKey];
598
599     if (!writeNode(state, level + 1, objectKey, true, true, true)) {
600       continue; // Skip this pair because of invalid key.
601     }
602
603     explicitPair = (state.tag !== null && state.tag !== '?') ||
604                    (state.dump && state.dump.length > 1024);
605
606     if (explicitPair) {
607       if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
608         pairBuffer += '?';
609       } else {
610         pairBuffer += '? ';
611       }
612     }
613
614     pairBuffer += state.dump;
615
616     if (explicitPair) {
617       pairBuffer += generateNextLine(state, level);
618     }
619
620     if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
621       continue; // Skip this pair because of invalid value.
622     }
623
624     if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
625       pairBuffer += ':';
626     } else {
627       pairBuffer += ': ';
628     }
629
630     pairBuffer += state.dump;
631
632     // Both key and value are valid.
633     _result += pairBuffer;
634   }
635
636   state.tag = _tag;
637   state.dump = _result || '{}'; // Empty mapping if no valid pairs.
638 }
639
640 function detectType(state, object, explicit) {
641   var _result, typeList, index, length, type, style;
642
643   typeList = explicit ? state.explicitTypes : state.implicitTypes;
644
645   for (index = 0, length = typeList.length; index < length; index += 1) {
646     type = typeList[index];
647
648     if ((type.instanceOf  || type.predicate) &&
649         (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&
650         (!type.predicate  || type.predicate(object))) {
651
652       state.tag = explicit ? type.tag : '?';
653
654       if (type.represent) {
655         style = state.styleMap[type.tag] || type.defaultStyle;
656
657         if (_toString.call(type.represent) === '[object Function]') {
658           _result = type.represent(object, style);
659         } else if (_hasOwnProperty.call(type.represent, style)) {
660           _result = type.represent[style](object, style);
661         } else {
662           throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');
663         }
664
665         state.dump = _result;
666       }
667
668       return true;
669     }
670   }
671
672   return false;
673 }
674
675 // Serializes `object` and writes it to global `result`.
676 // Returns true on success, or false on invalid object.
677 //
678 function writeNode(state, level, object, block, compact, iskey) {
679   state.tag = null;
680   state.dump = object;
681
682   if (!detectType(state, object, false)) {
683     detectType(state, object, true);
684   }
685
686   var type = _toString.call(state.dump);
687
688   if (block) {
689     block = (state.flowLevel < 0 || state.flowLevel > level);
690   }
691
692   var objectOrArray = type === '[object Object]' || type === '[object Array]',
693       duplicateIndex,
694       duplicate;
695
696   if (objectOrArray) {
697     duplicateIndex = state.duplicates.indexOf(object);
698     duplicate = duplicateIndex !== -1;
699   }
700
701   if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {
702     compact = false;
703   }
704
705   if (duplicate && state.usedDuplicates[duplicateIndex]) {
706     state.dump = '*ref_' + duplicateIndex;
707   } else {
708     if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
709       state.usedDuplicates[duplicateIndex] = true;
710     }
711     if (type === '[object Object]') {
712       if (block && (Object.keys(state.dump).length !== 0)) {
713         writeBlockMapping(state, level, state.dump, compact);
714         if (duplicate) {
715           state.dump = '&ref_' + duplicateIndex + state.dump;
716         }
717       } else {
718         writeFlowMapping(state, level, state.dump);
719         if (duplicate) {
720           state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
721         }
722       }
723     } else if (type === '[object Array]') {
724       if (block && (state.dump.length !== 0)) {
725         writeBlockSequence(state, level, state.dump, compact);
726         if (duplicate) {
727           state.dump = '&ref_' + duplicateIndex + state.dump;
728         }
729       } else {
730         writeFlowSequence(state, level, state.dump);
731         if (duplicate) {
732           state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
733         }
734       }
735     } else if (type === '[object String]') {
736       if (state.tag !== '?') {
737         writeScalar(state, state.dump, level, iskey);
738       }
739     } else {
740       if (state.skipInvalid) return false;
741       throw new YAMLException('unacceptable kind of an object to dump ' + type);
742     }
743
744     if (state.tag !== null && state.tag !== '?') {
745       state.dump = '!<' + state.tag + '> ' + state.dump;
746     }
747   }
748
749   return true;
750 }
751
752 function getDuplicateReferences(object, state) {
753   var objects = [],
754       duplicatesIndexes = [],
755       index,
756       length;
757
758   inspectNode(object, objects, duplicatesIndexes);
759
760   for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
761     state.duplicates.push(objects[duplicatesIndexes[index]]);
762   }
763   state.usedDuplicates = new Array(length);
764 }
765
766 function inspectNode(object, objects, duplicatesIndexes) {
767   var objectKeyList,
768       index,
769       length;
770
771   if (object !== null && typeof object === 'object') {
772     index = objects.indexOf(object);
773     if (index !== -1) {
774       if (duplicatesIndexes.indexOf(index) === -1) {
775         duplicatesIndexes.push(index);
776       }
777     } else {
778       objects.push(object);
779
780       if (Array.isArray(object)) {
781         for (index = 0, length = object.length; index < length; index += 1) {
782           inspectNode(object[index], objects, duplicatesIndexes);
783         }
784       } else {
785         objectKeyList = Object.keys(object);
786
787         for (index = 0, length = objectKeyList.length; index < length; index += 1) {
788           inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
789         }
790       }
791     }
792   }
793 }
794
795 function dump(input, options) {
796   options = options || {};
797
798   var state = new State(options);
799
800   if (!state.noRefs) getDuplicateReferences(input, state);
801
802   if (writeNode(state, 0, input, true, true)) return state.dump + '\n';
803
804   return '';
805 }
806
807 function safeDump(input, options) {
808   return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
809 }
810
811 module.exports.dump     = dump;
812 module.exports.safeDump = safeDump;