Initial commit
[yaffs-website] / 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_SPACE                = 0x20; /* Space */
16 var CHAR_EXCLAMATION          = 0x21; /* ! */
17 var CHAR_DOUBLE_QUOTE         = 0x22; /* " */
18 var CHAR_SHARP                = 0x23; /* # */
19 var CHAR_PERCENT              = 0x25; /* % */
20 var CHAR_AMPERSAND            = 0x26; /* & */
21 var CHAR_SINGLE_QUOTE         = 0x27; /* ' */
22 var CHAR_ASTERISK             = 0x2A; /* * */
23 var CHAR_COMMA                = 0x2C; /* , */
24 var CHAR_MINUS                = 0x2D; /* - */
25 var CHAR_COLON                = 0x3A; /* : */
26 var CHAR_GREATER_THAN         = 0x3E; /* > */
27 var CHAR_QUESTION             = 0x3F; /* ? */
28 var CHAR_COMMERCIAL_AT        = 0x40; /* @ */
29 var CHAR_LEFT_SQUARE_BRACKET  = 0x5B; /* [ */
30 var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */
31 var CHAR_GRAVE_ACCENT         = 0x60; /* ` */
32 var CHAR_LEFT_CURLY_BRACKET   = 0x7B; /* { */
33 var CHAR_VERTICAL_LINE        = 0x7C; /* | */
34 var CHAR_RIGHT_CURLY_BRACKET  = 0x7D; /* } */
35
36 var ESCAPE_SEQUENCES = {};
37
38 ESCAPE_SEQUENCES[0x00]   = '\\0';
39 ESCAPE_SEQUENCES[0x07]   = '\\a';
40 ESCAPE_SEQUENCES[0x08]   = '\\b';
41 ESCAPE_SEQUENCES[0x09]   = '\\t';
42 ESCAPE_SEQUENCES[0x0A]   = '\\n';
43 ESCAPE_SEQUENCES[0x0B]   = '\\v';
44 ESCAPE_SEQUENCES[0x0C]   = '\\f';
45 ESCAPE_SEQUENCES[0x0D]   = '\\r';
46 ESCAPE_SEQUENCES[0x1B]   = '\\e';
47 ESCAPE_SEQUENCES[0x22]   = '\\"';
48 ESCAPE_SEQUENCES[0x5C]   = '\\\\';
49 ESCAPE_SEQUENCES[0x85]   = '\\N';
50 ESCAPE_SEQUENCES[0xA0]   = '\\_';
51 ESCAPE_SEQUENCES[0x2028] = '\\L';
52 ESCAPE_SEQUENCES[0x2029] = '\\P';
53
54 var DEPRECATED_BOOLEANS_SYNTAX = [
55   'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',
56   'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'
57 ];
58
59 function compileStyleMap(schema, map) {
60   var result, keys, index, length, tag, style, type;
61
62   if (map === null) return {};
63
64   result = {};
65   keys = Object.keys(map);
66
67   for (index = 0, length = keys.length; index < length; index += 1) {
68     tag = keys[index];
69     style = String(map[tag]);
70
71     if (tag.slice(0, 2) === '!!') {
72       tag = 'tag:yaml.org,2002:' + tag.slice(2);
73     }
74     type = schema.compiledTypeMap['fallback'][tag];
75
76     if (type && _hasOwnProperty.call(type.styleAliases, style)) {
77       style = type.styleAliases[style];
78     }
79
80     result[tag] = style;
81   }
82
83   return result;
84 }
85
86 function encodeHex(character) {
87   var string, handle, length;
88
89   string = character.toString(16).toUpperCase();
90
91   if (character <= 0xFF) {
92     handle = 'x';
93     length = 2;
94   } else if (character <= 0xFFFF) {
95     handle = 'u';
96     length = 4;
97   } else if (character <= 0xFFFFFFFF) {
98     handle = 'U';
99     length = 8;
100   } else {
101     throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF');
102   }
103
104   return '\\' + handle + common.repeat('0', length - string.length) + string;
105 }
106
107 function State(options) {
108   this.schema       = options['schema'] || DEFAULT_FULL_SCHEMA;
109   this.indent       = Math.max(1, (options['indent'] || 2));
110   this.skipInvalid  = options['skipInvalid'] || false;
111   this.flowLevel    = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);
112   this.styleMap     = compileStyleMap(this.schema, options['styles'] || null);
113   this.sortKeys     = options['sortKeys'] || false;
114   this.lineWidth    = options['lineWidth'] || 80;
115   this.noRefs       = options['noRefs'] || false;
116   this.noCompatMode = options['noCompatMode'] || false;
117
118   this.implicitTypes = this.schema.compiledImplicit;
119   this.explicitTypes = this.schema.compiledExplicit;
120
121   this.tag = null;
122   this.result = '';
123
124   this.duplicates = [];
125   this.usedDuplicates = null;
126 }
127
128 // Indents every line in a string. Empty lines (\n only) are not indented.
129 function indentString(string, spaces) {
130   var ind = common.repeat(' ', spaces),
131       position = 0,
132       next = -1,
133       result = '',
134       line,
135       length = string.length;
136
137   while (position < length) {
138     next = string.indexOf('\n', position);
139     if (next === -1) {
140       line = string.slice(position);
141       position = length;
142     } else {
143       line = string.slice(position, next + 1);
144       position = next + 1;
145     }
146
147     if (line.length && line !== '\n') result += ind;
148
149     result += line;
150   }
151
152   return result;
153 }
154
155 function generateNextLine(state, level) {
156   return '\n' + common.repeat(' ', state.indent * level);
157 }
158
159 function testImplicitResolving(state, str) {
160   var index, length, type;
161
162   for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
163     type = state.implicitTypes[index];
164
165     if (type.resolve(str)) {
166       return true;
167     }
168   }
169
170   return false;
171 }
172
173 // [33] s-white ::= s-space | s-tab
174 function isWhitespace(c) {
175   return c === CHAR_SPACE || c === CHAR_TAB;
176 }
177
178 // Returns true if the character can be printed without escaping.
179 // From YAML 1.2: "any allowed characters known to be non-printable
180 // should also be escaped. [However,] This isn’t mandatory"
181 // Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029.
182 function isPrintable(c) {
183   return  (0x00020 <= c && c <= 0x00007E)
184       || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029)
185       || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */)
186       ||  (0x10000 <= c && c <= 0x10FFFF);
187 }
188
189 // Simplified test for values allowed after the first character in plain style.
190 function isPlainSafe(c) {
191   // Uses a subset of nb-char - c-flow-indicator - ":" - "#"
192   // where nb-char ::= c-printable - b-char - c-byte-order-mark.
193   return isPrintable(c) && c !== 0xFEFF
194     // - c-flow-indicator
195     && c !== CHAR_COMMA
196     && c !== CHAR_LEFT_SQUARE_BRACKET
197     && c !== CHAR_RIGHT_SQUARE_BRACKET
198     && c !== CHAR_LEFT_CURLY_BRACKET
199     && c !== CHAR_RIGHT_CURLY_BRACKET
200     // - ":" - "#"
201     && c !== CHAR_COLON
202     && c !== CHAR_SHARP;
203 }
204
205 // Simplified test for values allowed as the first character in plain style.
206 function isPlainSafeFirst(c) {
207   // Uses a subset of ns-char - c-indicator
208   // where ns-char = nb-char - s-white.
209   return isPrintable(c) && c !== 0xFEFF
210     && !isWhitespace(c) // - s-white
211     // - (c-indicator ::=
212     // â€ś-” | â€ś?” | â€ś:” | â€ś,” | â€ś[” | â€ś]” | â€ś{” | â€ś}”
213     && c !== CHAR_MINUS
214     && c !== CHAR_QUESTION
215     && c !== CHAR_COLON
216     && c !== CHAR_COMMA
217     && c !== CHAR_LEFT_SQUARE_BRACKET
218     && c !== CHAR_RIGHT_SQUARE_BRACKET
219     && c !== CHAR_LEFT_CURLY_BRACKET
220     && c !== CHAR_RIGHT_CURLY_BRACKET
221     // | â€ś#” | â€ś&” | â€ś*” | â€ś!” | â€ś|” | â€ś>” | â€ś'” | â€ś"”
222     && c !== CHAR_SHARP
223     && c !== CHAR_AMPERSAND
224     && c !== CHAR_ASTERISK
225     && c !== CHAR_EXCLAMATION
226     && c !== CHAR_VERTICAL_LINE
227     && c !== CHAR_GREATER_THAN
228     && c !== CHAR_SINGLE_QUOTE
229     && c !== CHAR_DOUBLE_QUOTE
230     // | â€ś%” | â€ś@” | â€ś`”)
231     && c !== CHAR_PERCENT
232     && c !== CHAR_COMMERCIAL_AT
233     && c !== CHAR_GRAVE_ACCENT;
234 }
235
236 var STYLE_PLAIN   = 1,
237     STYLE_SINGLE  = 2,
238     STYLE_LITERAL = 3,
239     STYLE_FOLDED  = 4,
240     STYLE_DOUBLE  = 5;
241
242 // Determines which scalar styles are possible and returns the preferred style.
243 // lineWidth = -1 => no limit.
244 // Pre-conditions: str.length > 0.
245 // Post-conditions:
246 //    STYLE_PLAIN or STYLE_SINGLE => no \n are in the string.
247 //    STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).
248 //    STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).
249 function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) {
250   var i;
251   var char;
252   var hasLineBreak = false;
253   var hasFoldableLine = false; // only checked if shouldTrackWidth
254   var shouldTrackWidth = lineWidth !== -1;
255   var previousLineBreak = -1; // count the first line correctly
256   var plain = isPlainSafeFirst(string.charCodeAt(0))
257           && !isWhitespace(string.charCodeAt(string.length - 1));
258
259   if (singleLineOnly) {
260     // Case: no block styles.
261     // Check for disallowed characters to rule out plain and single.
262     for (i = 0; i < string.length; i++) {
263       char = string.charCodeAt(i);
264       if (!isPrintable(char)) {
265         return STYLE_DOUBLE;
266       }
267       plain = plain && isPlainSafe(char);
268     }
269   } else {
270     // Case: block styles permitted.
271     for (i = 0; i < string.length; i++) {
272       char = string.charCodeAt(i);
273       if (char === CHAR_LINE_FEED) {
274         hasLineBreak = true;
275         // Check if any line can be folded.
276         if (shouldTrackWidth) {
277           hasFoldableLine = hasFoldableLine ||
278             // Foldable line = too long, and not more-indented.
279             (i - previousLineBreak - 1 > lineWidth &&
280              string[previousLineBreak + 1] !== ' ');
281           previousLineBreak = i;
282         }
283       } else if (!isPrintable(char)) {
284         return STYLE_DOUBLE;
285       }
286       plain = plain && isPlainSafe(char);
287     }
288     // in case the end is missing a \n
289     hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&
290       (i - previousLineBreak - 1 > lineWidth &&
291        string[previousLineBreak + 1] !== ' '));
292   }
293   // Although every style can represent \n without escaping, prefer block styles
294   // for multiline, since they're more readable and they don't add empty lines.
295   // Also prefer folding a super-long line.
296   if (!hasLineBreak && !hasFoldableLine) {
297     // Strings interpretable as another type have to be quoted;
298     // e.g. the string 'true' vs. the boolean true.
299     return plain && !testAmbiguousType(string)
300       ? STYLE_PLAIN : STYLE_SINGLE;
301   }
302   // Edge case: block indentation indicator can only have one digit.
303   if (string[0] === ' ' && indentPerLevel > 9) {
304     return STYLE_DOUBLE;
305   }
306   // At this point we know block styles are valid.
307   // Prefer literal style unless we want to fold.
308   return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
309 }
310
311 // Note: line breaking/folding is implemented for only the folded style.
312 // NB. We drop the last trailing newline (if any) of a returned block scalar
313 //  since the dumper adds its own newline. This always works:
314 //    â€˘ No ending newline => unaffected; already using strip "-" chomping.
315 //    â€˘ Ending newline    => removed then restored.
316 //  Importantly, this keeps the "+" chomp indicator from gaining an extra line.
317 function writeScalar(state, string, level, iskey) {
318   state.dump = (function () {
319     if (string.length === 0) {
320       return "''";
321     }
322     if (!state.noCompatMode &&
323         DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) {
324       return "'" + string + "'";
325     }
326
327     var indent = state.indent * Math.max(1, level); // no 0-indent scalars
328     // As indentation gets deeper, let the width decrease monotonically
329     // to the lower bound min(state.lineWidth, 40).
330     // Note that this implies
331     //  state.lineWidth â‰¤ 40 + state.indent: width is fixed at the lower bound.
332     //  state.lineWidth > 40 + state.indent: width decreases until the lower bound.
333     // This behaves better than a constant minimum width which disallows narrower options,
334     // or an indent threshold which causes the width to suddenly increase.
335     var lineWidth = state.lineWidth === -1
336       ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
337
338     // Without knowing if keys are implicit/explicit, assume implicit for safety.
339     var singleLineOnly = iskey
340       // No block styles in flow mode.
341       || (state.flowLevel > -1 && level >= state.flowLevel);
342     function testAmbiguity(string) {
343       return testImplicitResolving(state, string);
344     }
345
346     switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) {
347       case STYLE_PLAIN:
348         return string;
349       case STYLE_SINGLE:
350         return "'" + string.replace(/'/g, "''") + "'";
351       case STYLE_LITERAL:
352         return '|' + blockHeader(string, state.indent)
353           + dropEndingNewline(indentString(string, indent));
354       case STYLE_FOLDED:
355         return '>' + blockHeader(string, state.indent)
356           + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
357       case STYLE_DOUBLE:
358         return '"' + escapeString(string, lineWidth) + '"';
359       default:
360         throw new YAMLException('impossible error: invalid scalar style');
361     }
362   }());
363 }
364
365 // Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.
366 function blockHeader(string, indentPerLevel) {
367   var indentIndicator = (string[0] === ' ') ? String(indentPerLevel) : '';
368
369   // note the special case: the string '\n' counts as a "trailing" empty line.
370   var clip =          string[string.length - 1] === '\n';
371   var keep = clip && (string[string.length - 2] === '\n' || string === '\n');
372   var chomp = keep ? '+' : (clip ? '' : '-');
373
374   return indentIndicator + chomp + '\n';
375 }
376
377 // (See the note for writeScalar.)
378 function dropEndingNewline(string) {
379   return string[string.length - 1] === '\n' ? string.slice(0, -1) : string;
380 }
381
382 // Note: a long line without a suitable break point will exceed the width limit.
383 // Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.
384 function foldString(string, width) {
385   // In folded style, $k$ consecutive newlines output as $k+1$ newlines—
386   // unless they're before or after a more-indented line, or at the very
387   // beginning or end, in which case $k$ maps to $k$.
388   // Therefore, parse each chunk as newline(s) followed by a content line.
389   var lineRe = /(\n+)([^\n]*)/g;
390
391   // first line (possibly an empty line)
392   var result = (function () {
393     var nextLF = string.indexOf('\n');
394     nextLF = nextLF !== -1 ? nextLF : string.length;
395     lineRe.lastIndex = nextLF;
396     return foldLine(string.slice(0, nextLF), width);
397   }());
398   // If we haven't reached the first content line yet, don't add an extra \n.
399   var prevMoreIndented = string[0] === '\n' || string[0] === ' ';
400   var moreIndented;
401
402   // rest of the lines
403   var match;
404   while ((match = lineRe.exec(string))) {
405     var prefix = match[1], line = match[2];
406     moreIndented = (line[0] === ' ');
407     result += prefix
408       + (!prevMoreIndented && !moreIndented && line !== ''
409         ? '\n' : '')
410       + foldLine(line, width);
411     prevMoreIndented = moreIndented;
412   }
413
414   return result;
415 }
416
417 // Greedy line breaking.
418 // Picks the longest line under the limit each time,
419 // otherwise settles for the shortest line over the limit.
420 // NB. More-indented lines *cannot* be folded, as that would add an extra \n.
421 function foldLine(line, width) {
422   if (line === '' || line[0] === ' ') return line;
423
424   // Since a more-indented line adds a \n, breaks can't be followed by a space.
425   var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.
426   var match;
427   // start is an inclusive index. end, curr, and next are exclusive.
428   var start = 0, end, curr = 0, next = 0;
429   var result = '';
430
431   // Invariants: 0 <= start <= length-1.
432   //   0 <= curr <= next <= max(0, length-2). curr - start <= width.
433   // Inside the loop:
434   //   A match implies length >= 2, so curr and next are <= length-2.
435   while ((match = breakRe.exec(line))) {
436     next = match.index;
437     // maintain invariant: curr - start <= width
438     if (next - start > width) {
439       end = (curr > start) ? curr : next; // derive end <= length-2
440       result += '\n' + line.slice(start, end);
441       // skip the space that was output as \n
442       start = end + 1;                    // derive start <= length-1
443     }
444     curr = next;
445   }
446
447   // By the invariants, start <= length-1, so there is something left over.
448   // It is either the whole string or a part starting from non-whitespace.
449   result += '\n';
450   // Insert a break if the remainder is too long and there is a break available.
451   if (line.length - start > width && curr > start) {
452     result += line.slice(start, curr) + '\n' + line.slice(curr + 1);
453   } else {
454     result += line.slice(start);
455   }
456
457   return result.slice(1); // drop extra \n joiner
458 }
459
460 // Escapes a double-quoted string.
461 function escapeString(string) {
462   var result = '';
463   var char;
464   var escapeSeq;
465
466   for (var i = 0; i < string.length; i++) {
467     char = string.charCodeAt(i);
468     escapeSeq = ESCAPE_SEQUENCES[char];
469     result += !escapeSeq && isPrintable(char)
470       ? string[i]
471       : escapeSeq || encodeHex(char);
472   }
473
474   return result;
475 }
476
477 function writeFlowSequence(state, level, object) {
478   var _result = '',
479       _tag    = state.tag,
480       index,
481       length;
482
483   for (index = 0, length = object.length; index < length; index += 1) {
484     // Write only valid elements.
485     if (writeNode(state, level, object[index], false, false)) {
486       if (index !== 0) _result += ', ';
487       _result += state.dump;
488     }
489   }
490
491   state.tag = _tag;
492   state.dump = '[' + _result + ']';
493 }
494
495 function writeBlockSequence(state, level, object, compact) {
496   var _result = '',
497       _tag    = state.tag,
498       index,
499       length;
500
501   for (index = 0, length = object.length; index < length; index += 1) {
502     // Write only valid elements.
503     if (writeNode(state, level + 1, object[index], true, true)) {
504       if (!compact || index !== 0) {
505         _result += generateNextLine(state, level);
506       }
507       _result += '- ' + state.dump;
508     }
509   }
510
511   state.tag = _tag;
512   state.dump = _result || '[]'; // Empty sequence if no valid values.
513 }
514
515 function writeFlowMapping(state, level, object) {
516   var _result       = '',
517       _tag          = state.tag,
518       objectKeyList = Object.keys(object),
519       index,
520       length,
521       objectKey,
522       objectValue,
523       pairBuffer;
524
525   for (index = 0, length = objectKeyList.length; index < length; index += 1) {
526     pairBuffer = '';
527
528     if (index !== 0) pairBuffer += ', ';
529
530     objectKey = objectKeyList[index];
531     objectValue = object[objectKey];
532
533     if (!writeNode(state, level, objectKey, false, false)) {
534       continue; // Skip this pair because of invalid key;
535     }
536
537     if (state.dump.length > 1024) pairBuffer += '? ';
538
539     pairBuffer += state.dump + ': ';
540
541     if (!writeNode(state, level, objectValue, false, false)) {
542       continue; // Skip this pair because of invalid value.
543     }
544
545     pairBuffer += state.dump;
546
547     // Both key and value are valid.
548     _result += pairBuffer;
549   }
550
551   state.tag = _tag;
552   state.dump = '{' + _result + '}';
553 }
554
555 function writeBlockMapping(state, level, object, compact) {
556   var _result       = '',
557       _tag          = state.tag,
558       objectKeyList = Object.keys(object),
559       index,
560       length,
561       objectKey,
562       objectValue,
563       explicitPair,
564       pairBuffer;
565
566   // Allow sorting keys so that the output file is deterministic
567   if (state.sortKeys === true) {
568     // Default sorting
569     objectKeyList.sort();
570   } else if (typeof state.sortKeys === 'function') {
571     // Custom sort function
572     objectKeyList.sort(state.sortKeys);
573   } else if (state.sortKeys) {
574     // Something is wrong
575     throw new YAMLException('sortKeys must be a boolean or a function');
576   }
577
578   for (index = 0, length = objectKeyList.length; index < length; index += 1) {
579     pairBuffer = '';
580
581     if (!compact || index !== 0) {
582       pairBuffer += generateNextLine(state, level);
583     }
584
585     objectKey = objectKeyList[index];
586     objectValue = object[objectKey];
587
588     if (!writeNode(state, level + 1, objectKey, true, true, true)) {
589       continue; // Skip this pair because of invalid key.
590     }
591
592     explicitPair = (state.tag !== null && state.tag !== '?') ||
593                    (state.dump && state.dump.length > 1024);
594
595     if (explicitPair) {
596       if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
597         pairBuffer += '?';
598       } else {
599         pairBuffer += '? ';
600       }
601     }
602
603     pairBuffer += state.dump;
604
605     if (explicitPair) {
606       pairBuffer += generateNextLine(state, level);
607     }
608
609     if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
610       continue; // Skip this pair because of invalid value.
611     }
612
613     if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
614       pairBuffer += ':';
615     } else {
616       pairBuffer += ': ';
617     }
618
619     pairBuffer += state.dump;
620
621     // Both key and value are valid.
622     _result += pairBuffer;
623   }
624
625   state.tag = _tag;
626   state.dump = _result || '{}'; // Empty mapping if no valid pairs.
627 }
628
629 function detectType(state, object, explicit) {
630   var _result, typeList, index, length, type, style;
631
632   typeList = explicit ? state.explicitTypes : state.implicitTypes;
633
634   for (index = 0, length = typeList.length; index < length; index += 1) {
635     type = typeList[index];
636
637     if ((type.instanceOf  || type.predicate) &&
638         (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&
639         (!type.predicate  || type.predicate(object))) {
640
641       state.tag = explicit ? type.tag : '?';
642
643       if (type.represent) {
644         style = state.styleMap[type.tag] || type.defaultStyle;
645
646         if (_toString.call(type.represent) === '[object Function]') {
647           _result = type.represent(object, style);
648         } else if (_hasOwnProperty.call(type.represent, style)) {
649           _result = type.represent[style](object, style);
650         } else {
651           throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');
652         }
653
654         state.dump = _result;
655       }
656
657       return true;
658     }
659   }
660
661   return false;
662 }
663
664 // Serializes `object` and writes it to global `result`.
665 // Returns true on success, or false on invalid object.
666 //
667 function writeNode(state, level, object, block, compact, iskey) {
668   state.tag = null;
669   state.dump = object;
670
671   if (!detectType(state, object, false)) {
672     detectType(state, object, true);
673   }
674
675   var type = _toString.call(state.dump);
676
677   if (block) {
678     block = (state.flowLevel < 0 || state.flowLevel > level);
679   }
680
681   var objectOrArray = type === '[object Object]' || type === '[object Array]',
682       duplicateIndex,
683       duplicate;
684
685   if (objectOrArray) {
686     duplicateIndex = state.duplicates.indexOf(object);
687     duplicate = duplicateIndex !== -1;
688   }
689
690   if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {
691     compact = false;
692   }
693
694   if (duplicate && state.usedDuplicates[duplicateIndex]) {
695     state.dump = '*ref_' + duplicateIndex;
696   } else {
697     if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
698       state.usedDuplicates[duplicateIndex] = true;
699     }
700     if (type === '[object Object]') {
701       if (block && (Object.keys(state.dump).length !== 0)) {
702         writeBlockMapping(state, level, state.dump, compact);
703         if (duplicate) {
704           state.dump = '&ref_' + duplicateIndex + state.dump;
705         }
706       } else {
707         writeFlowMapping(state, level, state.dump);
708         if (duplicate) {
709           state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
710         }
711       }
712     } else if (type === '[object Array]') {
713       if (block && (state.dump.length !== 0)) {
714         writeBlockSequence(state, level, state.dump, compact);
715         if (duplicate) {
716           state.dump = '&ref_' + duplicateIndex + state.dump;
717         }
718       } else {
719         writeFlowSequence(state, level, state.dump);
720         if (duplicate) {
721           state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
722         }
723       }
724     } else if (type === '[object String]') {
725       if (state.tag !== '?') {
726         writeScalar(state, state.dump, level, iskey);
727       }
728     } else {
729       if (state.skipInvalid) return false;
730       throw new YAMLException('unacceptable kind of an object to dump ' + type);
731     }
732
733     if (state.tag !== null && state.tag !== '?') {
734       state.dump = '!<' + state.tag + '> ' + state.dump;
735     }
736   }
737
738   return true;
739 }
740
741 function getDuplicateReferences(object, state) {
742   var objects = [],
743       duplicatesIndexes = [],
744       index,
745       length;
746
747   inspectNode(object, objects, duplicatesIndexes);
748
749   for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
750     state.duplicates.push(objects[duplicatesIndexes[index]]);
751   }
752   state.usedDuplicates = new Array(length);
753 }
754
755 function inspectNode(object, objects, duplicatesIndexes) {
756   var objectKeyList,
757       index,
758       length;
759
760   if (object !== null && typeof object === 'object') {
761     index = objects.indexOf(object);
762     if (index !== -1) {
763       if (duplicatesIndexes.indexOf(index) === -1) {
764         duplicatesIndexes.push(index);
765       }
766     } else {
767       objects.push(object);
768
769       if (Array.isArray(object)) {
770         for (index = 0, length = object.length; index < length; index += 1) {
771           inspectNode(object[index], objects, duplicatesIndexes);
772         }
773       } else {
774         objectKeyList = Object.keys(object);
775
776         for (index = 0, length = objectKeyList.length; index < length; index += 1) {
777           inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
778         }
779       }
780     }
781   }
782 }
783
784 function dump(input, options) {
785   options = options || {};
786
787   var state = new State(options);
788
789   if (!state.noRefs) getDuplicateReferences(input, state);
790
791   if (writeNode(state, 0, input, true, true)) return state.dump + '\n';
792
793   return '';
794 }
795
796 function safeDump(input, options) {
797   return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
798 }
799
800 module.exports.dump     = dump;
801 module.exports.safeDump = safeDump;