From 1ab5166e9d4a5422d75d0c36b3a54b8ce7da7f64 Mon Sep 17 00:00:00 2001 From: Chris Connelly Date: Thu, 22 Dec 2016 14:03:48 +0000 Subject: [PATCH] Make changes needed to compile on CoffeeScript 2 There were 4 sources of breakages: - `super` must be called in extended classes with constructors. - Class prototype methods are non-enumerable, so `util.extend` had to be updated to use `Object.getOwnPropertyNames` and `Object.getPrototypeOf`. - Default arguments will only be used for `undefined` values, which broke a test setup in `test/test.coffee`. - Due to `super` needing to be called before `@` parameters are availble, the stack set by `YAMLError#constructor` was calling `#toString` of subclasses whose `@` parameters were not yet available. The chosen fix was to make `#stack` a getter. --- lib/composer.js | 393 +++--- lib/constructor.js | 936 +++++++-------- lib/dumper.js | 47 +- lib/emitter.js | 2111 ++++++++++++++++---------------- lib/errors.js | 114 +- lib/events.js | 165 ++- lib/loader.js | 50 +- lib/nodes.js | 70 +- lib/parser.js | 928 +++++++-------- lib/reader.js | 117 +- lib/representer.js | 358 +++--- lib/resolver.js | 258 ++-- lib/scanner.js | 2314 ++++++++++++++++++------------------ lib/serializer.js | 220 ++-- lib/tokens.js | 201 ++-- lib/util.js | 46 +- lib/yaml.js | 70 +- src/lib/composer.coffee | 7 +- src/lib/constructor.coffee | 11 +- src/lib/dumper.coffee | 4 +- src/lib/emitter.coffee | 4 +- src/lib/errors.coffee | 3 +- src/lib/events.coffee | 18 +- src/lib/loader.coffee | 4 +- src/lib/parser.coffee | 4 +- src/lib/reader.coffee | 4 +- src/lib/representer.coffee | 4 +- src/lib/resolver.coffee | 6 +- src/lib/scanner.coffee | 4 +- src/lib/serializer.coffee | 4 +- src/lib/tokens.coffee | 18 +- src/lib/util.coffee | 10 +- test/test.coffee | 2 +- 33 files changed, 4223 insertions(+), 4282 deletions(-) diff --git a/lib/composer.js b/lib/composer.js index 5f1cf33..9c18e69 100644 --- a/lib/composer.js +++ b/lib/composer.js @@ -1,7 +1,5 @@ (function() { - var MarkedYAMLError, events, nodes, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty; + var MarkedYAMLError, events, nodes; events = require('./events'); @@ -15,11 +13,9 @@ */ this.ComposerError = (function(superClass) { - extend(ComposerError, superClass); + class ComposerError extends superClass {}; - function ComposerError() { - return ComposerError.__super__.constructor.apply(this, arguments); - } + ComposerError.__super__ = superClass.prototype; return ComposerError; @@ -35,225 +31,242 @@ */ this.Composer = (function() { + var ctor; - /* - Construct a new `Composer` instance. - */ - function Composer() { - this.anchors = {}; - } + class Composer { + constructor() { + return ctor.apply(this, arguments); + } - /* - Checks if a document can be composed from the event stream. - - So long as the event stream hasn't ended (no [StreamEndEvent]), another document can be composed. - - @return {Boolean} True if a document can be composed, false otherwise. - */ + /* + Initialise a new `Composer` instance. + */ - Composer.prototype.check_node = function() { - if (this.check_event(events.StreamStartEvent)) { - this.get_event(); + initialise() { + return this.anchors = {}; } - return !this.check_event(events.StreamEndEvent); - }; - /* - Compose a document from the remaining event stream. - - {Composer#check_node} must be called before calling this method. - - @return {Node} The next document in the stream. Returns `undefined` if the event stream has ended. - */ + /* + Checks if a document can be composed from the event stream. + + So long as the event stream hasn't ended (no [StreamEndEvent]), another document can be composed. + + @return {Boolean} True if a document can be composed, false otherwise. + */ - Composer.prototype.get_node = function() { - if (!this.check_event(events.StreamEndEvent)) { - return this.compose_document(); + check_node() { + if (this.check_event(events.StreamStartEvent)) { + this.get_event(); + } + return !this.check_event(events.StreamEndEvent); } - }; - /* - Compose a single document from the entire event stream. - - @throw {ComposerError} if there's more than one document is in the stream. - - @return {Node} The single document in the stream. - */ + /* + Compose a document from the remaining event stream. + + {Composer#check_node} must be called before calling this method. + + @return {Node} The next document in the stream. Returns `undefined` if the event stream has ended. + */ - Composer.prototype.get_single_node = function() { - var document, event; - this.get_event(); - document = null; - if (!this.check_event(events.StreamEndEvent)) { - document = this.compose_document(); - } - if (!this.check_event(events.StreamEndEvent)) { - event = this.get_event(); - throw new exports.ComposerError('expected a single document in the stream', document.start_mark, 'but found another document', event.start_mark); + get_node() { + if (!this.check_event(events.StreamEndEvent)) { + return this.compose_document(); + } } - this.get_event(); - return document; - }; - /* - Compose a document node from the event stream. - - A 'document' node is any single {Node} subclass. {DocumentStart} and {DocumentEnd} events delimit - the events used for composition. - - @private - - @return {Node} The document node. - */ + /* + Compose a single document from the entire event stream. + + @throw {ComposerError} if there's more than one document is in the stream. + + @return {Node} The single document in the stream. + */ - Composer.prototype.compose_document = function() { - var node; - this.get_event(); - node = this.compose_node(); - this.get_event(); - this.anchors = {}; - return node; - }; + get_single_node() { + var document, event; + this.get_event(); + document = null; + if (!this.check_event(events.StreamEndEvent)) { + document = this.compose_document(); + } + if (!this.check_event(events.StreamEndEvent)) { + event = this.get_event(); + throw new exports.ComposerError('expected a single document in the stream', document.start_mark, 'but found another document', event.start_mark); + } + this.get_event(); + return document; + } - /* - Compose a node from the event stream. - - Composes a {ScalarNode}, {SequenceNode}, or {MappingNode} from the event stream, depending on the - first event encountered ({ScalarEvent}, {SequenceStartEvent}, or {MappingStartEvent} - respectively). - - @private - - @param parent {Node} The parent of the new node. - @param index {Number} The index of the new node within the parent's children. - @throw {ComposerError} if an alias is encountered for an undefined anchor. - @throw {ComposerError} if a duplicate anchor is envountered. - @return {Node} The composed node. - */ + /* + Compose a document node from the event stream. + + A 'document' node is any single {Node} subclass. {DocumentStart} and {DocumentEnd} events delimit + the events used for composition. + + @private + + @return {Node} The document node. + */ - Composer.prototype.compose_node = function(parent, index) { - var anchor, event, node; - if (this.check_event(events.AliasEvent)) { - event = this.get_event(); + compose_document() { + var node; + this.get_event(); + node = this.compose_node(); + this.get_event(); + this.anchors = {}; + return node; + } + + + /* + Compose a node from the event stream. + + Composes a {ScalarNode}, {SequenceNode}, or {MappingNode} from the event stream, depending on the + first event encountered ({ScalarEvent}, {SequenceStartEvent}, or {MappingStartEvent} + respectively). + + @private + + @param parent {Node} The parent of the new node. + @param index {Number} The index of the new node within the parent's children. + @throw {ComposerError} if an alias is encountered for an undefined anchor. + @throw {ComposerError} if a duplicate anchor is envountered. + @return {Node} The composed node. + */ + + compose_node(parent, index) { + var anchor, event, node; + if (this.check_event(events.AliasEvent)) { + event = this.get_event(); + anchor = event.anchor; + if (!(anchor in this.anchors)) { + throw new exports.ComposerError(null, null, `found undefined alias ${anchor}`, event.start_mark); + } + return this.anchors[anchor]; + } + event = this.peek_event(); anchor = event.anchor; - if (!(anchor in this.anchors)) { - throw new exports.ComposerError(null, null, "found undefined alias " + anchor, event.start_mark); + if (anchor !== null && anchor in this.anchors) { + throw new exports.ComposerError(`found duplicate anchor ${anchor}; first occurence`, this.anchors[anchor].start_mark, 'second occurrence', event.start_mark); } - return this.anchors[anchor]; - } - event = this.peek_event(); - anchor = event.anchor; - if (anchor !== null && anchor in this.anchors) { - throw new exports.ComposerError("found duplicate anchor " + anchor + "; first occurence", this.anchors[anchor].start_mark, 'second occurrence', event.start_mark); - } - this.descend_resolver(parent, index); - if (this.check_event(events.ScalarEvent)) { - node = this.compose_scalar_node(anchor); - } else if (this.check_event(events.SequenceStartEvent)) { - node = this.compose_sequence_node(anchor); - } else if (this.check_event(events.MappingStartEvent)) { - node = this.compose_mapping_node(anchor); + this.descend_resolver(parent, index); + if (this.check_event(events.ScalarEvent)) { + node = this.compose_scalar_node(anchor); + } else if (this.check_event(events.SequenceStartEvent)) { + node = this.compose_sequence_node(anchor); + } else if (this.check_event(events.MappingStartEvent)) { + node = this.compose_mapping_node(anchor); + } + this.ascend_resolver(); + return node; } - this.ascend_resolver(); - return node; - }; - /* - Compose a {ScalarNode} from the event stream. - - @private - - @param anchor {String} The anchor name for the node (if any). - @return {ScalarNode} The node composed from a {ScalarEvent}. - */ + /* + Compose a {ScalarNode} from the event stream. + + @private + + @param anchor {String} The anchor name for the node (if any). + @return {ScalarNode} The node composed from a {ScalarEvent}. + */ - Composer.prototype.compose_scalar_node = function(anchor) { - var event, node, tag; - event = this.get_event(); - tag = event.tag; - if (tag === null || tag === '!') { - tag = this.resolve(nodes.ScalarNode, event.value, event.implicit); - } - node = new nodes.ScalarNode(tag, event.value, event.start_mark, event.end_mark, event.style); - if (anchor !== null) { - this.anchors[anchor] = node; + compose_scalar_node(anchor) { + var event, node, tag; + event = this.get_event(); + tag = event.tag; + if (tag === null || tag === '!') { + tag = this.resolve(nodes.ScalarNode, event.value, event.implicit); + } + node = new nodes.ScalarNode(tag, event.value, event.start_mark, event.end_mark, event.style); + if (anchor !== null) { + this.anchors[anchor] = node; + } + return node; } - return node; - }; - /* - Compose a {SequenceNode} from the event stream. - - The contents of the node are composed from events between a {SequenceStartEvent} and a - {SequenceEndEvent}. - - @private - - @param anchor {String} The anchor name for the node (if any). - @return {SequenceNode} The composed node. - */ - - Composer.prototype.compose_sequence_node = function(anchor) { - var end_event, index, node, start_event, tag; - start_event = this.get_event(); - tag = start_event.tag; - if (tag === null || tag === '!') { - tag = this.resolve(nodes.SequenceNode, null, start_event.implicit); - } - node = new nodes.SequenceNode(tag, [], start_event.start_mark, null, start_event.flow_style); - if (anchor !== null) { - this.anchors[anchor] = node; + /* + Compose a {SequenceNode} from the event stream. + + The contents of the node are composed from events between a {SequenceStartEvent} and a + {SequenceEndEvent}. + + @private + + @param anchor {String} The anchor name for the node (if any). + @return {SequenceNode} The composed node. + */ + + compose_sequence_node(anchor) { + var end_event, index, node, start_event, tag; + start_event = this.get_event(); + tag = start_event.tag; + if (tag === null || tag === '!') { + tag = this.resolve(nodes.SequenceNode, null, start_event.implicit); + } + node = new nodes.SequenceNode(tag, [], start_event.start_mark, null, start_event.flow_style); + if (anchor !== null) { + this.anchors[anchor] = node; + } + index = 0; + while (!this.check_event(events.SequenceEndEvent)) { + node.value.push(this.compose_node(node, index)); + index++; + } + end_event = this.get_event(); + node.end_mark = end_event.end_mark; + return node; } - index = 0; - while (!this.check_event(events.SequenceEndEvent)) { - node.value.push(this.compose_node(node, index)); - index++; + + + /* + Compose a {MappingNode} from the event stream. + + The contents of the node are composed from events between a {MappingStartEvent} and a + {MappingEndEvent}. + + @private + + @param anchor {String} The anchor name for the node (if any). + @return {MappingNode} The composed node. + */ + + compose_mapping_node(anchor) { + var end_event, item_key, item_value, node, start_event, tag; + start_event = this.get_event(); + tag = start_event.tag; + if (tag === null || tag === '!') { + tag = this.resolve(nodes.MappingNode, null, start_event.implicit); + } + node = new nodes.MappingNode(tag, [], start_event.start_mark, null, start_event.flow_style); + if (anchor !== null) { + this.anchors[anchor] = node; + } + while (!this.check_event(events.MappingEndEvent)) { + item_key = this.compose_node(node); + item_value = this.compose_node(node, item_key); + node.value.push([item_key, item_value]); + } + end_event = this.get_event(); + node.end_mark = end_event.end_mark; + return node; } - end_event = this.get_event(); - node.end_mark = end_event.end_mark; - return node; + }; /* - Compose a {MappingNode} from the event stream. - - The contents of the node are composed from events between a {MappingStartEvent} and a - {MappingEndEvent}. - - @private - - @param anchor {String} The anchor name for the node (if any). - @return {MappingNode} The composed node. + Construct a new `Composer` instance. */ - Composer.prototype.compose_mapping_node = function(anchor) { - var end_event, item_key, item_value, node, start_event, tag; - start_event = this.get_event(); - tag = start_event.tag; - if (tag === null || tag === '!') { - tag = this.resolve(nodes.MappingNode, null, start_event.implicit); - } - node = new nodes.MappingNode(tag, [], start_event.start_mark, null, start_event.flow_style); - if (anchor !== null) { - this.anchors[anchor] = node; - } - while (!this.check_event(events.MappingEndEvent)) { - item_key = this.compose_node(node); - item_value = this.compose_node(node, item_key); - node.value.push([item_key, item_value]); - } - end_event = this.get_event(); - node.end_mark = end_event.end_mark; - return node; - }; + ctor = Composer.prototype.initialise; return Composer; diff --git a/lib/constructor.js b/lib/constructor.js index 3b5aadf..83d6301 100644 --- a/lib/constructor.js +++ b/lib/constructor.js @@ -1,7 +1,5 @@ (function() { var MarkedYAMLError, nodes, util, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty, indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; MarkedYAMLError = require('./errors').MarkedYAMLError; @@ -16,11 +14,9 @@ */ this.ConstructorError = (function(superClass) { - extend(ConstructorError, superClass); + class ConstructorError extends superClass {}; - function ConstructorError() { - return ConstructorError.__super__.constructor.apply(this, arguments); - } + ConstructorError.__super__ = superClass.prototype; return ConstructorError; @@ -37,596 +33,602 @@ */ this.BaseConstructor = (function() { + var ctor; - /* - @property {Object} A map from a YAML tag to a constructor function for data with that tag. - @private - */ - BaseConstructor.prototype.yaml_constructors = {}; - - - /* - @property {Object} A map from a YAML tag prefix to a constructor function for data with that tag - prefix. - @private - */ - - BaseConstructor.prototype.yaml_multi_constructors = {}; - + class BaseConstructor { + constructor() { + return ctor.apply(this, arguments); + } - /* - Add a constructor function for a specific tag. - - The constructor will be used to turn {Node Nodes} with the given tag into a Javascript object. - - @param tag {String} The tag for which the constructor should apply. - @param constructor {Function} A function that turns a {Node} with the given tag into a - Javascript object. - @return {Function} Returns the supplied `constructor`. - */ - BaseConstructor.add_constructor = function(tag, constructor) { - if (!this.prototype.hasOwnProperty('yaml_constructors')) { - this.prototype.yaml_constructors = util.extend({}, this.prototype.yaml_constructors); + /* + Add a constructor function for a specific tag. + + The constructor will be used to turn {Node Nodes} with the given tag into a Javascript object. + + @param tag {String} The tag for which the constructor should apply. + @param constructor {Function} A function that turns a {Node} with the given tag into a + Javascript object. + @return {Function} Returns the supplied `constructor`. + */ + + static add_constructor(tag, constructor) { + if (!this.prototype.hasOwnProperty('yaml_constructors')) { + this.prototype.yaml_constructors = util.clone(this.prototype.yaml_constructors); + } + return this.prototype.yaml_constructors[tag] = constructor; } - return this.prototype.yaml_constructors[tag] = constructor; - }; - /* - Add a constructor function for a tag prefix. - - The constructor will be used to turn {Node Nodes} with the given tag prefix into a Javascript - object. - - @param tag_prefix {String} The tag prefix for which the constructor should apply. - @param multi_constructor {Function} A function that turns a {Node} with the given tag - prefix into a Javascript object. - @return {Function} Returns the supplied `multi_constructor`. - */ - - BaseConstructor.add_multi_constructor = function(tag_prefix, multi_constructor) { - if (!this.prototype.hasOwnProperty('yaml_multi_constructors')) { - this.prototype.yaml_multi_constructors = util.extend({}, this.prototype.yaml_multi_constructors); + /* + Add a constructor function for a tag prefix. + + The constructor will be used to turn {Node Nodes} with the given tag prefix into a Javascript + object. + + @param tag_prefix {String} The tag prefix for which the constructor should apply. + @param multi_constructor {Function} A function that turns a {Node} with the given tag + prefix into a Javascript object. + @return {Function} Returns the supplied `multi_constructor`. + */ + + static add_multi_constructor(tag_prefix, multi_constructor) { + if (!this.prototype.hasOwnProperty('yaml_multi_constructors')) { + this.prototype.yaml_multi_constructors = util.clone(this.prototype.yaml_multi_constructors); + } + return this.prototype.yaml_multi_constructors[tag_prefix] = multi_constructor; } - return this.prototype.yaml_multi_constructors[tag_prefix] = multi_constructor; - }; - /* - Construct a new `Constructor` instance. - */ + /* + Initialise a new `Constructor` instance. + */ - function BaseConstructor() { - this.constructed_objects = {}; - this.constructing_nodes = []; - this.deferred_constructors = []; - } + initialise() { + this.constructed_objects = {}; + this.constructing_nodes = []; + return this.deferred_constructors = []; + } - /* - Checks if a document can be constructed from the representation stream. - - So long as the representation stream hasn't ended, another document can be constructed. - - @return {Boolean} True if a document can be constructed, false otherwise. - */ + /* + Checks if a document can be constructed from the representation stream. + + So long as the representation stream hasn't ended, another document can be constructed. + + @return {Boolean} True if a document can be constructed, false otherwise. + */ - BaseConstructor.prototype.check_data = function() { - return this.check_node(); - }; + check_data() { + return this.check_node(); + } - /* - Construct a document from the remaining representation stream. - - {Constructor#check_data} must be called before calling this method. - - @return {any} The next document in the stream. Returns `undefined` if the stream has ended. - */ + /* + Construct a document from the remaining representation stream. + + {Constructor#check_data} must be called before calling this method. + + @return {any} The next document in the stream. Returns `undefined` if the stream has ended. + */ - BaseConstructor.prototype.get_data = function() { - if (this.check_node()) { - return this.construct_document(this.get_node()); + get_data() { + if (this.check_node()) { + return this.construct_document(this.get_node()); + } } - }; - /* - Construct a single document from the entire representation stream. - - @throw {ComposerError} if there's more than one document is in the stream. - - @return {Node} The single document in the stream. - */ + /* + Construct a single document from the entire representation stream. + + @throw {ComposerError} if there's more than one document is in the stream. + + @return {Node} The single document in the stream. + */ - BaseConstructor.prototype.get_single_data = function() { - var node; - node = this.get_single_node(); - if (node != null) { - return this.construct_document(node); + get_single_data() { + var node; + node = this.get_single_node(); + if (node != null) { + return this.construct_document(node); + } + return null; } - return null; - }; - /* - Construct a document node - - @private - */ + /* + Construct a document node + + @private + */ - BaseConstructor.prototype.construct_document = function(node) { - var data; - data = this.construct_object(node); - while (!util.is_empty(this.deferred_constructors)) { - this.deferred_constructors.pop()(); + construct_document(node) { + var data; + data = this.construct_object(node); + while (!util.is_empty(this.deferred_constructors)) { + this.deferred_constructors.pop()(); + } + return data; } - return data; - }; - BaseConstructor.prototype.defer = function(f) { - return this.deferred_constructors.push(f); - }; + defer(f) { + return this.deferred_constructors.push(f); + } - BaseConstructor.prototype.construct_object = function(node) { - var constructor, object, ref, tag_prefix, tag_suffix; - if (node.unique_id in this.constructed_objects) { - return this.constructed_objects[node.unique_id]; - } - if (ref = node.unique_id, indexOf.call(this.constructing_nodes, ref) >= 0) { - throw new exports.ConstructorError(null, null, 'found unconstructable recursive node', node.start_mark); - } - this.constructing_nodes.push(node.unique_id); - constructor = null; - tag_suffix = null; - if (node.tag in this.yaml_constructors) { - constructor = this.yaml_constructors[node.tag]; - } else { - for (tag_prefix in this.yaml_multi_constructors) { - if (node.tag.indexOf(tag_prefix === 0)) { - tag_suffix = node.tag.slice(tag_prefix.length); - constructor = this.yaml_multi_constructors[tag_prefix]; - break; - } + construct_object(node) { + var constructor, object, ref, tag_prefix, tag_suffix; + if (node.unique_id in this.constructed_objects) { + return this.constructed_objects[node.unique_id]; + } + if (ref = node.unique_id, indexOf.call(this.constructing_nodes, ref) >= 0) { + throw new exports.ConstructorError(null, null, 'found unconstructable recursive node', node.start_mark); } - if (constructor == null) { - if (null in this.yaml_multi_constructors) { - tag_suffix = node.tag; - constructor = this.yaml_multi_constructors[null]; - } else if (null in this.yaml_constructors) { - constructor = this.yaml_constructors[null]; - } else if (node instanceof nodes.ScalarNode) { - constructor = this.construct_scalar; - } else if (node instanceof nodes.SequenceNode) { - constructor = this.construct_sequence; - } else if (node instanceof nodes.MappingNode) { - constructor = this.construct_mapping; + this.constructing_nodes.push(node.unique_id); + constructor = null; + tag_suffix = null; + if (node.tag in this.yaml_constructors) { + constructor = this.yaml_constructors[node.tag]; + } else { + for (tag_prefix in this.yaml_multi_constructors) { + if (node.tag.indexOf(tag_prefix === 0)) { + tag_suffix = node.tag.slice(tag_prefix.length); + constructor = this.yaml_multi_constructors[tag_prefix]; + break; + } + } + if (constructor == null) { + if (null in this.yaml_multi_constructors) { + tag_suffix = node.tag; + constructor = this.yaml_multi_constructors[null]; + } else if (null in this.yaml_constructors) { + constructor = this.yaml_constructors[null]; + } else if (node instanceof nodes.ScalarNode) { + constructor = this.construct_scalar; + } else if (node instanceof nodes.SequenceNode) { + constructor = this.construct_sequence; + } else if (node instanceof nodes.MappingNode) { + constructor = this.construct_mapping; + } } } + object = constructor.call(this, tag_suffix != null ? tag_suffix : node, node); + this.constructed_objects[node.unique_id] = object; + this.constructing_nodes.pop(); + return object; } - object = constructor.call(this, tag_suffix != null ? tag_suffix : node, node); - this.constructed_objects[node.unique_id] = object; - this.constructing_nodes.pop(); - return object; - }; - BaseConstructor.prototype.construct_scalar = function(node) { - if (!(node instanceof nodes.ScalarNode)) { - throw new exports.ConstructorError(null, null, "expected a scalar node but found " + node.id, node.start_mark); + construct_scalar(node) { + if (!(node instanceof nodes.ScalarNode)) { + throw new exports.ConstructorError(null, null, `expected a scalar node but found ${node.id}`, node.start_mark); + } + return node.value; } - return node.value; - }; - BaseConstructor.prototype.construct_sequence = function(node) { - var child, i, len, ref, results; - if (!(node instanceof nodes.SequenceNode)) { - throw new exports.ConstructorError(null, null, "expected a sequence node but found " + node.id, node.start_mark); - } - ref = node.value; - results = []; - for (i = 0, len = ref.length; i < len; i++) { - child = ref[i]; - results.push(this.construct_object(child)); + construct_sequence(node) { + var child, i, len, ref, results; + if (!(node instanceof nodes.SequenceNode)) { + throw new exports.ConstructorError(null, null, `expected a sequence node but found ${node.id}`, node.start_mark); + } + ref = node.value; + results = []; + for (i = 0, len = ref.length; i < len; i++) { + child = ref[i]; + results.push(this.construct_object(child)); + } + return results; } - return results; - }; - BaseConstructor.prototype.construct_mapping = function(node) { - var i, key, key_node, len, mapping, ref, ref1, value, value_node; - if (!(node instanceof nodes.MappingNode)) { - throw new ConstructorError(null, null, "expected a mapping node but found " + node.id, node.start_mark); - } - mapping = {}; - ref = node.value; - for (i = 0, len = ref.length; i < len; i++) { - ref1 = ref[i], key_node = ref1[0], value_node = ref1[1]; - key = this.construct_object(key_node); - if (typeof key === 'object') { - throw new exports.ConstructorError('while constructing a mapping', node.start_mark, 'found unhashable key', key_node.start_mark); + construct_mapping(node) { + var i, key, key_node, len, mapping, ref, ref1, value, value_node; + if (!(node instanceof nodes.MappingNode)) { + throw new ConstructorError(null, null, `expected a mapping node but found ${node.id}`, node.start_mark); + } + mapping = {}; + ref = node.value; + for (i = 0, len = ref.length; i < len; i++) { + ref1 = ref[i], key_node = ref1[0], value_node = ref1[1]; + key = this.construct_object(key_node); + if (typeof key === 'object') { + throw new exports.ConstructorError('while constructing a mapping', node.start_mark, 'found unhashable key', key_node.start_mark); + } + value = this.construct_object(value_node); + mapping[key] = value; } - value = this.construct_object(value_node); - mapping[key] = value; + return mapping; } - return mapping; - }; - BaseConstructor.prototype.construct_pairs = function(node) { - var i, key, key_node, len, pairs, ref, ref1, value, value_node; - if (!(node instanceof nodes.MappingNode)) { - throw new exports.ConstructorError(null, null, "expected a mapping node but found " + node.id, node.start_mark); - } - pairs = []; - ref = node.value; - for (i = 0, len = ref.length; i < len; i++) { - ref1 = ref[i], key_node = ref1[0], value_node = ref1[1]; - key = this.construct_object(key_node); - value = this.construct_object(value_node); - pairs.push([key, value]); + construct_pairs(node) { + var i, key, key_node, len, pairs, ref, ref1, value, value_node; + if (!(node instanceof nodes.MappingNode)) { + throw new exports.ConstructorError(null, null, `expected a mapping node but found ${node.id}`, node.start_mark); + } + pairs = []; + ref = node.value; + for (i = 0, len = ref.length; i < len; i++) { + ref1 = ref[i], key_node = ref1[0], value_node = ref1[1]; + key = this.construct_object(key_node); + value = this.construct_object(value_node); + pairs.push([key, value]); + } + return pairs; } - return pairs; + }; - return BaseConstructor; - })(); + /* + @property {Object} A map from a YAML tag to a constructor function for data with that tag. + @private + */ - this.Constructor = (function(superClass) { - var BOOL_VALUES, TIMESTAMP_PARTS, TIMESTAMP_REGEX; + BaseConstructor.prototype.yaml_constructors = {}; - extend(Constructor, superClass); - function Constructor() { - return Constructor.__super__.constructor.apply(this, arguments); - } + /* + @property {Object} A map from a YAML tag prefix to a constructor function for data with that tag + prefix. + @private + */ - BOOL_VALUES = { - on: true, - off: false, - "true": true, - "false": false, - yes: true, - no: false - }; + BaseConstructor.prototype.yaml_multi_constructors = {}; - TIMESTAMP_REGEX = /^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:(?:[Tt]|[\x20\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\.([0-9]*))?(?:[\x20\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?)?$/; - TIMESTAMP_PARTS = { - year: 1, - month: 2, - day: 3, - hour: 4, - minute: 5, - second: 6, - fraction: 7, - tz: 8, - tz_sign: 9, - tz_hour: 10, - tz_minute: 11 - }; + /* + Construct a new `Constructor` instance. + */ - Constructor.prototype.construct_scalar = function(node) { - var i, key_node, len, ref, ref1, value_node; - if (node instanceof nodes.MappingNode) { - ref = node.value; - for (i = 0, len = ref.length; i < len; i++) { - ref1 = ref[i], key_node = ref1[0], value_node = ref1[1]; - if (key_node.tag === 'tag:yaml.org,2002:value') { - return this.construct_scalar(value_node); + ctor = BaseConstructor.prototype.initialise; + + return BaseConstructor; + + })(); + + this.Constructor = (function(superClass) { + var BOOL_VALUES, TIMESTAMP_PARTS, TIMESTAMP_REGEX; + + class Constructor extends superClass { + construct_scalar(node) { + var i, key_node, len, ref, ref1, value_node; + if (node instanceof nodes.MappingNode) { + ref = node.value; + for (i = 0, len = ref.length; i < len; i++) { + ref1 = ref[i], key_node = ref1[0], value_node = ref1[1]; + if (key_node.tag === 'tag:yaml.org,2002:value') { + return this.construct_scalar(value_node); + } } } + return Constructor.__super__.construct_scalar.call(this, node); } - return Constructor.__super__.construct_scalar.call(this, node); - }; - Constructor.prototype.flatten_mapping = function(node) { - var i, index, j, key_node, len, len1, merge, ref, ref1, submerge, subnode, value, value_node; - merge = []; - index = 0; - while (index < node.value.length) { - ref = node.value[index], key_node = ref[0], value_node = ref[1]; - if (key_node.tag === 'tag:yaml.org,2002:merge') { - node.value.splice(index, 1); - if (value_node instanceof nodes.MappingNode) { - this.flatten_mapping(value_node); - merge = merge.concat(value_node.value); - } else if (value_node instanceof nodes.SequenceNode) { - submerge = []; - ref1 = value_node.value; - for (i = 0, len = ref1.length; i < len; i++) { - subnode = ref1[i]; - if (!(subnode instanceof nodes.MappingNode)) { - throw new exports.ConstructorError('while constructing a mapping', node.start_mark, "expected a mapping for merging, but found " + subnode.id, subnode.start_mark); + flatten_mapping(node) { + var i, index, j, key_node, len, len1, merge, ref, ref1, submerge, subnode, value, value_node; + merge = []; + index = 0; + while (index < node.value.length) { + ref = node.value[index], key_node = ref[0], value_node = ref[1]; + if (key_node.tag === 'tag:yaml.org,2002:merge') { + node.value.splice(index, 1); + if (value_node instanceof nodes.MappingNode) { + this.flatten_mapping(value_node); + merge = merge.concat(value_node.value); + } else if (value_node instanceof nodes.SequenceNode) { + submerge = []; + ref1 = value_node.value; + for (i = 0, len = ref1.length; i < len; i++) { + subnode = ref1[i]; + if (!(subnode instanceof nodes.MappingNode)) { + throw new exports.ConstructorError('while constructing a mapping', node.start_mark, `expected a mapping for merging, but found ${subnode.id}`, subnode.start_mark); + } + this.flatten_mapping(subnode); + submerge.push(subnode.value); } - this.flatten_mapping(subnode); - submerge.push(subnode.value); - } - submerge.reverse(); - for (j = 0, len1 = submerge.length; j < len1; j++) { - value = submerge[j]; - merge = merge.concat(value); + submerge.reverse(); + for (j = 0, len1 = submerge.length; j < len1; j++) { + value = submerge[j]; + merge = merge.concat(value); + } + } else { + throw new exports.ConstructorError('while constructing a mapping', node.start_mark, `expected a mapping or list of mappings for merging but found ${value_node.id}`, value_node.start_mark); } + } else if (key_node.tag === 'tag:yaml.org,2002:value') { + key_node.tag = 'tag:yaml.org,2002:str'; + index++; } else { - throw new exports.ConstructorError('while constructing a mapping', node.start_mark, "expected a mapping or list of mappings for merging but found " + value_node.id, value_node.start_mark); + index++; } - } else if (key_node.tag === 'tag:yaml.org,2002:value') { - key_node.tag = 'tag:yaml.org,2002:str'; - index++; - } else { - index++; + } + if (merge.length) { + return node.value = merge.concat(node.value); } } - if (merge.length) { - return node.value = merge.concat(node.value); - } - }; - Constructor.prototype.construct_mapping = function(node) { - if (node instanceof nodes.MappingNode) { - this.flatten_mapping(node); + construct_mapping(node) { + if (node instanceof nodes.MappingNode) { + this.flatten_mapping(node); + } + return Constructor.__super__.construct_mapping.call(this, node); } - return Constructor.__super__.construct_mapping.call(this, node); - }; - Constructor.prototype.construct_yaml_null = function(node) { - this.construct_scalar(node); - return null; - }; + construct_yaml_null(node) { + this.construct_scalar(node); + return null; + } - Constructor.prototype.construct_yaml_bool = function(node) { - var value; - value = this.construct_scalar(node); - return BOOL_VALUES[value.toLowerCase()]; - }; + construct_yaml_bool(node) { + var value; + value = this.construct_scalar(node); + return BOOL_VALUES[value.toLowerCase()]; + } - Constructor.prototype.construct_yaml_int = function(node) { - var base, digit, digits, i, len, part, ref, sign, value; - value = this.construct_scalar(node); - value = value.replace(/_/g, ''); - sign = value[0] === '-' ? -1 : 1; - if (ref = value[0], indexOf.call('+-', ref) >= 0) { - value = value.slice(1); - } - if (value === '0') { - return 0; - } else if (value.indexOf('0b') === 0) { - return sign * parseInt(value.slice(2), 2); - } else if (value.indexOf('0x') === 0) { - return sign * parseInt(value.slice(2), 16); - } else if (value.indexOf('0o') === 0) { - return sign * parseInt(value.slice(2), 8); - } else if (value[0] === '0') { - return sign * parseInt(value, 8); - } else if (indexOf.call(value, ':') >= 0) { - digits = (function() { - var i, len, ref1, results; - ref1 = value.split(/:/g); - results = []; - for (i = 0, len = ref1.length; i < len; i++) { - part = ref1[i]; - results.push(parseInt(part)); + construct_yaml_int(node) { + var base, digit, digits, i, len, part, ref, sign, value; + value = this.construct_scalar(node); + value = value.replace(/_/g, ''); + sign = value[0] === '-' ? -1 : 1; + if (ref = value[0], indexOf.call('+-', ref) >= 0) { + value = value.slice(1); + } + if (value === '0') { + return 0; + } else if (value.indexOf('0b') === 0) { + return sign * parseInt(value.slice(2), 2); + } else if (value.indexOf('0x') === 0) { + return sign * parseInt(value.slice(2), 16); + } else if (value.indexOf('0o') === 0) { + return sign * parseInt(value.slice(2), 8); + } else if (value[0] === '0') { + return sign * parseInt(value, 8); + } else if (indexOf.call(value, ':') >= 0) { + digits = (function() { + var i, len, ref1, results; + ref1 = value.split(/:/g); + results = []; + for (i = 0, len = ref1.length; i < len; i++) { + part = ref1[i]; + results.push(parseInt(part)); + } + return results; + })(); + digits.reverse(); + base = 1; + value = 0; + for (i = 0, len = digits.length; i < len; i++) { + digit = digits[i]; + value += digit * base; + base *= 60; } - return results; - })(); - digits.reverse(); - base = 1; - value = 0; - for (i = 0, len = digits.length; i < len; i++) { - digit = digits[i]; - value += digit * base; - base *= 60; + return sign * value; + } else { + return sign * parseInt(value); } - return sign * value; - } else { - return sign * parseInt(value); } - }; - Constructor.prototype.construct_yaml_float = function(node) { - var base, digit, digits, i, len, part, ref, sign, value; - value = this.construct_scalar(node); - value = value.replace(/_/g, '').toLowerCase(); - sign = value[0] === '-' ? -1 : 1; - if (ref = value[0], indexOf.call('+-', ref) >= 0) { - value = value.slice(1); - } - if (value === '.inf') { - return sign * Infinity; - } else if (value === '.nan') { - return NaN; - } else if (indexOf.call(value, ':') >= 0) { - digits = (function() { - var i, len, ref1, results; - ref1 = value.split(/:/g); - results = []; - for (i = 0, len = ref1.length; i < len; i++) { - part = ref1[i]; - results.push(parseFloat(part)); + construct_yaml_float(node) { + var base, digit, digits, i, len, part, ref, sign, value; + value = this.construct_scalar(node); + value = value.replace(/_/g, '').toLowerCase(); + sign = value[0] === '-' ? -1 : 1; + if (ref = value[0], indexOf.call('+-', ref) >= 0) { + value = value.slice(1); + } + if (value === '.inf') { + return sign * 2e308; + } else if (value === '.nan') { + return 0/0; + } else if (indexOf.call(value, ':') >= 0) { + digits = (function() { + var i, len, ref1, results; + ref1 = value.split(/:/g); + results = []; + for (i = 0, len = ref1.length; i < len; i++) { + part = ref1[i]; + results.push(parseFloat(part)); + } + return results; + })(); + digits.reverse(); + base = 1; + value = 0.0; + for (i = 0, len = digits.length; i < len; i++) { + digit = digits[i]; + value += digit * base; + base *= 60; } - return results; - })(); - digits.reverse(); - base = 1; - value = 0.0; - for (i = 0, len = digits.length; i < len; i++) { - digit = digits[i]; - value += digit * base; - base *= 60; + return sign * value; + } else { + return sign * parseFloat(value); } - return sign * value; - } else { - return sign * parseFloat(value); } - }; - Constructor.prototype.construct_yaml_binary = function(node) { - var error, value; - value = this.construct_scalar(node); - try { - if (typeof window !== "undefined" && window !== null) { - return atob(value); + construct_yaml_binary(node) { + var error, value; + value = this.construct_scalar(node); + try { + if (typeof window !== "undefined" && window !== null) { + return atob(value); + } + return new Buffer(value, 'base64').toString('ascii'); + } catch (error1) { + error = error1; + throw new exports.ConstructorError(null, null, `failed to decode base64 data: ${error}`, node.start_mark); } - return new Buffer(value, 'base64').toString('ascii'); - } catch (_error) { - error = _error; - throw new exports.ConstructorError(null, null, "failed to decode base64 data: " + error, node.start_mark); } - }; - Constructor.prototype.construct_yaml_timestamp = function(node) { - var date, day, fraction, hour, index, key, match, millisecond, minute, month, second, tz_hour, tz_minute, tz_sign, value, values, year; - value = this.construct_scalar(node); - match = node.value.match(TIMESTAMP_REGEX); - values = {}; - for (key in TIMESTAMP_PARTS) { - index = TIMESTAMP_PARTS[key]; - values[key] = match[index]; - } - year = parseInt(values.year); - month = parseInt(values.month) - 1; - day = parseInt(values.day); - if (!values.hour) { - return new Date(Date.UTC(year, month, day)); - } - hour = parseInt(values.hour); - minute = parseInt(values.minute); - second = parseInt(values.second); - millisecond = 0; - if (values.fraction) { - fraction = values.fraction.slice(0, 6); - while (fraction.length < 6) { - fraction += '0'; + construct_yaml_timestamp(node) { + var date, day, fraction, hour, index, key, match, millisecond, minute, month, second, tz_hour, tz_minute, tz_sign, value, values, year; + value = this.construct_scalar(node); + match = node.value.match(TIMESTAMP_REGEX); + values = {}; + for (key in TIMESTAMP_PARTS) { + index = TIMESTAMP_PARTS[key]; + values[key] = match[index]; } - fraction = parseInt(fraction); - millisecond = Math.round(fraction / 1000); - } - if (values.tz_sign) { - tz_sign = values.tz_sign === '-' ? 1 : -1; - if (tz_hour = parseInt(values.tz_hour)) { - hour += tz_sign * tz_hour; + year = parseInt(values.year); + month = parseInt(values.month) - 1; + day = parseInt(values.day); + if (!values.hour) { + return new Date(Date.UTC(year, month, day)); } - if (tz_minute = parseInt(values.tz_minute)) { - minute += tz_sign * tz_minute; + hour = parseInt(values.hour); + minute = parseInt(values.minute); + second = parseInt(values.second); + millisecond = 0; + if (values.fraction) { + fraction = values.fraction.slice(0, 6); + while (fraction.length < 6) { + fraction += '0'; + } + fraction = parseInt(fraction); + millisecond = Math.round(fraction / 1000); + } + if (values.tz_sign) { + tz_sign = values.tz_sign === '-' ? 1 : -1; + if (tz_hour = parseInt(values.tz_hour)) { + hour += tz_sign * tz_hour; + } + if (tz_minute = parseInt(values.tz_minute)) { + minute += tz_sign * tz_minute; + } } + date = new Date(Date.UTC(year, month, day, hour, minute, second, millisecond)); + return date; } - date = new Date(Date.UTC(year, month, day, hour, minute, second, millisecond)); - return date; - }; - Constructor.prototype.construct_yaml_pair_list = function(type, node) { - var list; - list = []; - if (!(node instanceof nodes.SequenceNode)) { - throw new exports.ConstructorError("while constructing " + type, node.start_mark, "expected a sequence but found " + node.id, node.start_mark); - } - this.defer((function(_this) { - return function() { + construct_yaml_pair_list(type, node) { + var list; + list = []; + if (!(node instanceof nodes.SequenceNode)) { + throw new exports.ConstructorError(`while constructing ${type}`, node.start_mark, `expected a sequence but found ${node.id}`, node.start_mark); + } + this.defer(() => { var i, key, key_node, len, ref, ref1, results, subnode, value, value_node; ref = node.value; results = []; for (i = 0, len = ref.length; i < len; i++) { subnode = ref[i]; if (!(subnode instanceof nodes.MappingNode)) { - throw new exports.ConstructorError("while constructing " + type, node.start_mark, "expected a mapping of length 1 but found " + subnode.id, subnode.start_mark); + throw new exports.ConstructorError(`while constructing ${type}`, node.start_mark, `expected a mapping of length 1 but found ${subnode.id}`, subnode.start_mark); } if (subnode.value.length !== 1) { - throw new exports.ConstructorError("while constructing " + type, node.start_mark, "expected a mapping of length 1 but found " + subnode.id, subnode.start_mark); + throw new exports.ConstructorError(`while constructing ${type}`, node.start_mark, `expected a mapping of length 1 but found ${subnode.id}`, subnode.start_mark); } ref1 = subnode.value[0], key_node = ref1[0], value_node = ref1[1]; - key = _this.construct_object(key_node); - value = _this.construct_object(value_node); + key = this.construct_object(key_node); + value = this.construct_object(value_node); results.push(list.push([key, value])); } return results; - }; - })(this)); - return list; - }; + }); + return list; + } - Constructor.prototype.construct_yaml_omap = function(node) { - return this.construct_yaml_pair_list('an ordered map', node); - }; + construct_yaml_omap(node) { + return this.construct_yaml_pair_list('an ordered map', node); + } - Constructor.prototype.construct_yaml_pairs = function(node) { - return this.construct_yaml_pair_list('pairs', node); - }; + construct_yaml_pairs(node) { + return this.construct_yaml_pair_list('pairs', node); + } - Constructor.prototype.construct_yaml_set = function(node) { - var data; - data = []; - this.defer((function(_this) { - return function() { + construct_yaml_set(node) { + var data; + data = []; + this.defer(() => { var item, results; results = []; - for (item in _this.construct_mapping(node)) { + for (item in this.construct_mapping(node)) { results.push(data.push(item)); } return results; - }; - })(this)); - return data; - }; + }); + return data; + } - Constructor.prototype.construct_yaml_str = function(node) { - return this.construct_scalar(node); - }; + construct_yaml_str(node) { + return this.construct_scalar(node); + } - Constructor.prototype.construct_yaml_seq = function(node) { - var data; - data = []; - this.defer((function(_this) { - return function() { + construct_yaml_seq(node) { + var data; + data = []; + this.defer(() => { var i, item, len, ref, results; - ref = _this.construct_sequence(node); + ref = this.construct_sequence(node); results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(data.push(item)); } return results; - }; - })(this)); - return data; - }; + }); + return data; + } - Constructor.prototype.construct_yaml_map = function(node) { - var data; - data = {}; - this.defer((function(_this) { - return function() { + construct_yaml_map(node) { + var data; + data = {}; + this.defer(() => { var key, ref, results, value; - ref = _this.construct_mapping(node); + ref = this.construct_mapping(node); results = []; for (key in ref) { value = ref[key]; results.push(data[key] = value); } return results; - }; - })(this)); - return data; - }; + }); + return data; + } - Constructor.prototype.construct_yaml_object = function(node, klass) { - var data; - data = new klass; - this.defer((function(_this) { - return function() { + construct_yaml_object(node, klass) { + var data; + data = new klass; + this.defer(() => { var key, ref, results, value; - ref = _this.construct_mapping(node, true); + ref = this.construct_mapping(node, true); results = []; for (key in ref) { value = ref[key]; results.push(data[key] = value); } return results; - }; - })(this)); - return data; + }); + return data; + } + + construct_undefined(node) { + throw new exports.ConstructorError(null, null, `could not determine a constructor for the tag ${node.tag}`, node.start_mark); + } + }; - Constructor.prototype.construct_undefined = function(node) { - throw new exports.ConstructorError(null, null, "could not determine a constructor for the tag " + node.tag, node.start_mark); + Constructor.__super__ = superClass.prototype; + + BOOL_VALUES = { + on: true, + off: false, + "true": true, + "false": false, + yes: true, + no: false + }; + + TIMESTAMP_REGEX = /^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:(?:[Tt]|[\x20\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\.([0-9]*))?(?:[\x20\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?)?$/; + + TIMESTAMP_PARTS = { + year: 1, + month: 2, + day: 3, + hour: 4, + minute: 5, + second: 6, + fraction: 7, + tz: 8, + tz_sign: 9, + tz_hour: 10, + tz_minute: 11 }; return Constructor; diff --git a/lib/dumper.js b/lib/dumper.js index 54e2cce..6118df8 100644 --- a/lib/dumper.js +++ b/lib/dumper.js @@ -1,6 +1,5 @@ (function() { - var emitter, representer, resolver, serializer, util, - slice = [].slice; + var emitter, representer, resolver, serializer, util; util = require('./util'); @@ -12,25 +11,26 @@ resolver = require('./resolver'); - this.make_dumper = function(Emitter, Serializer, Representer, Resolver) { + this.make_dumper = function(Emitter = emitter.Emitter, Serializer = serializer.Serializer, Representer = representer.Representer, Resolver = resolver.Resolver) { var Dumper, components; - if (Emitter == null) { - Emitter = emitter.Emitter; - } - if (Serializer == null) { - Serializer = serializer.Serializer; - } - if (Representer == null) { - Representer = representer.Representer; - } - if (Resolver == null) { - Resolver = resolver.Resolver; - } components = [Emitter, Serializer, Representer, Resolver]; return Dumper = (function() { var component; - util.extend.apply(util, [Dumper.prototype].concat(slice.call((function() { + class Dumper { + constructor(stream, options = {}) { + var i, len, ref; + components[0].prototype.initialise.call(this, stream, options); + ref = components.slice(1); + for (i = 0, len = ref.length; i < len; i++) { + component = ref[i]; + component.prototype.initialise.call(this, options); + } + } + + }; + + util.extend(Dumper.prototype, ...(function() { var i, len, results; results = []; for (i = 0, len = components.length; i < len; i++) { @@ -38,20 +38,7 @@ results.push(component.prototype); } return results; - })()))); - - function Dumper(stream, options) { - var i, len, ref; - if (options == null) { - options = {}; - } - components[0].call(this, stream, options); - ref = components.slice(1); - for (i = 0, len = ref.length; i < len; i++) { - component = ref[i]; - component.call(this, options); - } - } + })()); return Dumper; diff --git a/lib/emitter.js b/lib/emitter.js index bac66bc..fdc5dfa 100644 --- a/lib/emitter.js +++ b/lib/emitter.js @@ -1,6 +1,5 @@ (function() { var ScalarAnalysis, YAMLError, events, util, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty, indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; @@ -11,11 +10,9 @@ YAMLError = require('./errors').YAMLError; this.EmitterError = (function(superClass) { - extend(EmitterError, superClass); + class EmitterError extends superClass {}; - function EmitterError() { - return EmitterError.__super__.constructor.apply(this, arguments); - } + EmitterError.__super__ = superClass.prototype; return EmitterError; @@ -33,1277 +30,1259 @@ */ this.Emitter = (function() { - var C_WHITESPACE, DEFAULT_TAG_PREFIXES, ESCAPE_REPLACEMENTS; - - C_WHITESPACE = '\0 \t\r\n\x85\u2028\u2029'; + var C_WHITESPACE, DEFAULT_TAG_PREFIXES, ESCAPE_REPLACEMENTS, ctor; + + class Emitter { + constructor() { + return ctor.apply(this, arguments); + } + + initialise(stream, options) { + var ref; + this.stream = stream; + this.encoding = null; + this.states = []; + this.state = this.expect_stream_start; + this.events = []; + this.event = null; + this.indents = []; + this.indent = null; + this.flow_level = 0; + this.root_context = false; + this.sequence_context = false; + this.mapping_context = false; + this.simple_key_context = false; + this.line = 0; + this.column = 0; + this.whitespace = true; + this.indentation = true; + this.open_ended = false; + this.canonical = options.canonical, this.allow_unicode = options.allow_unicode; + if (this.canonical == null) { + this.canonical = false; + } + if (this.allow_unicode == null) { + this.allow_unicode = true; + } + this.best_indent = 1 < options.indent && options.indent < 10 ? options.indent : 2; + this.best_width = options.width > this.indent * 2 ? options.width : 80; + this.best_line_break = (ref = options.line_break) === '\r' || ref === '\n' || ref === '\r\n' ? options.line_break : '\n'; + this.tag_prefixes = null; + this.prepared_anchor = null; + this.prepared_tag = null; + this.analysis = null; + return this.style = null; + } - DEFAULT_TAG_PREFIXES = { - '!': '!', - 'tag:yaml.org,2002:': '!!' - }; - ESCAPE_REPLACEMENTS = { - '\0': '0', - '\x07': 'a', - '\x08': 'b', - '\x09': 't', - '\x0A': 'n', - '\x0B': 'v', - '\x0C': 'f', - '\x0D': 'r', - '\x1B': 'e', - '"': '"', - '\\': '\\', - '\x85': 'N', - '\xA0': '_', - '\u2028': 'L', - '\u2029': 'P' - }; + /* + Reset the state attributes (to clear self-references) + */ - function Emitter(stream, options) { - var ref; - this.stream = stream; - this.encoding = null; - this.states = []; - this.state = this.expect_stream_start; - this.events = []; - this.event = null; - this.indents = []; - this.indent = null; - this.flow_level = 0; - this.root_context = false; - this.sequence_context = false; - this.mapping_context = false; - this.simple_key_context = false; - this.line = 0; - this.column = 0; - this.whitespace = true; - this.indentation = true; - this.open_ended = false; - this.canonical = options.canonical, this.allow_unicode = options.allow_unicode; - if (this.canonical == null) { - this.canonical = false; + dispose() { + this.states = []; + return this.state = null; } - if (this.allow_unicode == null) { - this.allow_unicode = true; + + emit(event) { + var results; + this.events.push(event); + results = []; + while (!this.need_more_events()) { + this.event = this.events.shift(); + this.state(); + results.push(this.event = null); + } + return results; } - this.best_indent = 1 < options.indent && options.indent < 10 ? options.indent : 2; - this.best_width = options.width > this.indent * 2 ? options.width : 80; - this.best_line_break = (ref = options.line_break) === '\r' || ref === '\n' || ref === '\r\n' ? options.line_break : '\n'; - this.tag_prefixes = null; - this.prepared_anchor = null; - this.prepared_tag = null; - this.analysis = null; - this.style = null; - } - /* - Reset the state attributes (to clear self-references) - */ + /* + In some cases, we wait for a few next events before emitting. + */ - Emitter.prototype.dispose = function() { - this.states = []; - return this.state = null; - }; + need_more_events() { + var event; + if (this.events.length === 0) { + return true; + } + event = this.events[0]; + if (event instanceof events.DocumentStartEvent) { + return this.need_events(1); + } else if (event instanceof events.SequenceStartEvent) { + return this.need_events(2); + } else if (event instanceof events.MappingStartEvent) { + return this.need_events(3); + } else { + return false; + } + } - Emitter.prototype.emit = function(event) { - var results; - this.events.push(event); - results = []; - while (!this.need_more_events()) { - this.event = this.events.shift(); - this.state(); - results.push(this.event = null); + need_events(count) { + var event, i, len, level, ref; + level = 0; + ref = this.events.slice(1); + for (i = 0, len = ref.length; i < len; i++) { + event = ref[i]; + if (event instanceof events.DocumentStartEvent || event instanceof events.CollectionStartEvent) { + level++; + } else if (event instanceof events.DocumentEndEvent || event instanceof events.CollectionEndEvent) { + level--; + } else if (event instanceof events.StreamEndEvent) { + level = -1; + } + if (level < 0) { + return false; + } + } + return this.events.length < count + 1; } - return results; - }; + increase_indent(options = {}) { + this.indents.push(this.indent); + if (this.indent == null) { + return this.indent = options.flow ? this.best_indent : 0; + } else if (!options.indentless) { + return this.indent += this.best_indent; + } + } - /* - In some cases, we wait for a few next events before emitting. - */ + expect_stream_start() { + if (this.event instanceof events.StreamStartEvent) { + if (this.event.encoding && !('encoding' in this.stream)) { + this.encoding = this.event.encoding; + } + this.write_stream_start(); + return this.state = this.expect_first_document_start; + } else { + return this.error('expected StreamStartEvent, but got', this.event); + } + } - Emitter.prototype.need_more_events = function() { - var event; - if (this.events.length === 0) { - return true; + expect_nothing() { + return this.error('expected nothing, but got', this.event); } - event = this.events[0]; - if (event instanceof events.DocumentStartEvent) { - return this.need_events(1); - } else if (event instanceof events.SequenceStartEvent) { - return this.need_events(2); - } else if (event instanceof events.MappingStartEvent) { - return this.need_events(3); - } else { - return false; + + expect_first_document_start() { + return this.expect_document_start(true); } - }; - Emitter.prototype.need_events = function(count) { - var event, i, len, level, ref; - level = 0; - ref = this.events.slice(1); - for (i = 0, len = ref.length; i < len; i++) { - event = ref[i]; - if (event instanceof events.DocumentStartEvent || event instanceof events.CollectionStartEvent) { - level++; - } else if (event instanceof events.DocumentEndEvent || event instanceof events.CollectionEndEvent) { - level--; - } else if (event instanceof events.StreamEndEvent) { - level = -1; - } - if (level < 0) { - return false; + expect_document_start(first = false) { + var explicit, handle, i, k, len, prefix, ref; + if (this.event instanceof events.DocumentStartEvent) { + if ((this.event.version || this.event.tags) && this.open_ended) { + this.write_indicator('...', true); + this.write_indent(); + } + if (this.event.version) { + this.write_version_directive(this.prepare_version(this.event.version)); + } + this.tag_prefixes = util.clone(DEFAULT_TAG_PREFIXES); + if (this.event.tags) { + ref = ((function() { + var ref, results; + ref = this.event.tags; + results = []; + for (k in ref) { + if (!hasProp.call(ref, k)) continue; + results.push(k); + } + return results; + }).call(this)).sort(); + for (i = 0, len = ref.length; i < len; i++) { + handle = ref[i]; + prefix = this.event.tags[handle]; + this.tag_prefixes[prefix] = handle; + this.write_tag_directive(this.prepare_tag_handle(handle), this.prepare_tag_prefix(prefix)); + } + } + explicit = !first || this.event.explicit || this.canonical || this.event.version || this.event.tags || this.check_empty_document(); + if (explicit) { + this.write_indent(); + this.write_indicator('---', true); + if (this.canonical) { + this.write_indent(); + } + } + return this.state = this.expect_document_root; + } else if (this.event instanceof events.StreamEndEvent) { + if (this.open_ended) { + this.write_indicator('...', true); + this.write_indent(); + } + this.write_stream_end(); + return this.state = this.expect_nothing; + } else { + return this.error('expected DocumentStartEvent, but got', this.event); } } - return this.events.length < count + 1; - }; - Emitter.prototype.increase_indent = function(options) { - if (options == null) { - options = {}; + expect_document_end() { + if (this.event instanceof events.DocumentEndEvent) { + this.write_indent(); + if (this.event.explicit) { + this.write_indicator('...', true); + this.write_indent(); + } + this.flush_stream(); + return this.state = this.expect_document_start; + } else { + return this.error('expected DocumentEndEvent, but got', this.event); + } } - this.indents.push(this.indent); - if (this.indent == null) { - return this.indent = options.flow ? this.best_indent : 0; - } else if (!options.indentless) { - return this.indent += this.best_indent; + + expect_document_root() { + this.states.push(this.expect_document_end); + return this.expect_node({ + root: true + }); } - }; - Emitter.prototype.expect_stream_start = function() { - if (this.event instanceof events.StreamStartEvent) { - if (this.event.encoding && !('encoding' in this.stream)) { - this.encoding = this.event.encoding; + expect_node(expect = {}) { + this.root_context = !!expect.root; + this.sequence_context = !!expect.sequence; + this.mapping_context = !!expect.mapping; + this.simple_key_context = !!expect.simple_key; + if (this.event instanceof events.AliasEvent) { + return this.expect_alias(); + } else if (this.event instanceof events.ScalarEvent || this.event instanceof events.CollectionStartEvent) { + this.process_anchor('&'); + this.process_tag(); + if (this.event instanceof events.ScalarEvent) { + return this.expect_scalar(); + } else if (this.event instanceof events.SequenceStartEvent) { + if (this.flow_level || this.canonical || this.event.flow_style || this.check_empty_sequence()) { + return this.expect_flow_sequence(); + } else { + return this.expect_block_sequence(); + } + } else if (this.event instanceof events.MappingStartEvent) { + if (this.flow_level || this.canonical || this.event.flow_style || this.check_empty_mapping()) { + return this.expect_flow_mapping(); + } else { + return this.expect_block_mapping(); + } + } + } else { + return this.error('expected NodeEvent, but got', this.event); } - this.write_stream_start(); - return this.state = this.expect_first_document_start; - } else { - return this.error('expected StreamStartEvent, but got', this.event); } - }; - Emitter.prototype.expect_nothing = function() { - return this.error('expected nothing, but got', this.event); - }; + expect_alias() { + if (!this.event.anchor) { + this.error('anchor is not specified for alias'); + } + this.process_anchor('*'); + return this.state = this.states.pop(); + } - Emitter.prototype.expect_first_document_start = function() { - return this.expect_document_start(true); - }; + expect_scalar() { + this.increase_indent({ + flow: true + }); + this.process_scalar(); + this.indent = this.indents.pop(); + return this.state = this.states.pop(); + } - Emitter.prototype.expect_document_start = function(first) { - var explicit, handle, i, k, len, prefix, ref; - if (first == null) { - first = false; + expect_flow_sequence() { + this.write_indicator('[', true, { + whitespace: true + }); + this.flow_level++; + this.increase_indent({ + flow: true + }); + return this.state = this.expect_first_flow_sequence_item; } - if (this.event instanceof events.DocumentStartEvent) { - if ((this.event.version || this.event.tags) && this.open_ended) { - this.write_indicator('...', true); - this.write_indent(); - } - if (this.event.version) { - this.write_version_directive(this.prepare_version(this.event.version)); - } - this.tag_prefixes = util.clone(DEFAULT_TAG_PREFIXES); - if (this.event.tags) { - ref = ((function() { - var ref, results; - ref = this.event.tags; - results = []; - for (k in ref) { - if (!hasProp.call(ref, k)) continue; - results.push(k); - } - return results; - }).call(this)).sort(); - for (i = 0, len = ref.length; i < len; i++) { - handle = ref[i]; - prefix = this.event.tags[handle]; - this.tag_prefixes[prefix] = handle; - this.write_tag_directive(this.prepare_tag_handle(handle), this.prepare_tag_prefix(prefix)); + + expect_first_flow_sequence_item() { + if (this.event instanceof events.SequenceEndEvent) { + this.indent = this.indents.pop(); + this.flow_level--; + this.write_indicator(']', false); + return this.state = this.states.pop(); + } else { + if (this.canonical || this.column > this.best_width) { + this.write_indent(); } + this.states.push(this.expect_flow_sequence_item); + return this.expect_node({ + sequence: true + }); } - explicit = !first || this.event.explicit || this.canonical || this.event.version || this.event.tags || this.check_empty_document(); - if (explicit) { - this.write_indent(); - this.write_indicator('---', true); + } + + expect_flow_sequence_item() { + if (this.event instanceof events.SequenceEndEvent) { + this.indent = this.indents.pop(); + this.flow_level--; if (this.canonical) { + this.write_indicator(',', false); this.write_indent(); } + this.write_indicator(']', false); + return this.state = this.states.pop(); + } else { + this.write_indicator(',', false); + if (this.canonical || this.column > this.best_width) { + this.write_indent(); + } + this.states.push(this.expect_flow_sequence_item); + return this.expect_node({ + sequence: true + }); } - return this.state = this.expect_document_root; - } else if (this.event instanceof events.StreamEndEvent) { - if (this.open_ended) { - this.write_indicator('...', true); - this.write_indent(); - } - this.write_stream_end(); - return this.state = this.expect_nothing; - } else { - return this.error('expected DocumentStartEvent, but got', this.event); } - }; - Emitter.prototype.expect_document_end = function() { - if (this.event instanceof events.DocumentEndEvent) { - this.write_indent(); - if (this.event.explicit) { - this.write_indicator('...', true); - this.write_indent(); - } - this.flush_stream(); - return this.state = this.expect_document_start; - } else { - return this.error('expected DocumentEndEvent, but got', this.event); + expect_flow_mapping() { + this.write_indicator('{', true, { + whitespace: true + }); + this.flow_level++; + this.increase_indent({ + flow: true + }); + return this.state = this.expect_first_flow_mapping_key; } - }; - - Emitter.prototype.expect_document_root = function() { - this.states.push(this.expect_document_end); - return this.expect_node({ - root: true - }); - }; - Emitter.prototype.expect_node = function(expect) { - if (expect == null) { - expect = {}; - } - this.root_context = !!expect.root; - this.sequence_context = !!expect.sequence; - this.mapping_context = !!expect.mapping; - this.simple_key_context = !!expect.simple_key; - if (this.event instanceof events.AliasEvent) { - return this.expect_alias(); - } else if (this.event instanceof events.ScalarEvent || this.event instanceof events.CollectionStartEvent) { - this.process_anchor('&'); - this.process_tag(); - if (this.event instanceof events.ScalarEvent) { - return this.expect_scalar(); - } else if (this.event instanceof events.SequenceStartEvent) { - if (this.flow_level || this.canonical || this.event.flow_style || this.check_empty_sequence()) { - return this.expect_flow_sequence(); - } else { - return this.expect_block_sequence(); + expect_first_flow_mapping_key() { + if (this.event instanceof events.MappingEndEvent) { + this.indent = this.indents.pop(); + this.flow_level--; + this.write_indicator('}', false); + return this.state = this.states.pop(); + } else { + if (this.canonical || this.column > this.best_width) { + this.write_indent(); } - } else if (this.event instanceof events.MappingStartEvent) { - if (this.flow_level || this.canonical || this.event.flow_style || this.check_empty_mapping()) { - return this.expect_flow_mapping(); + if (!this.canonical && this.check_simple_key()) { + this.states.push(this.expect_flow_mapping_simple_value); + return this.expect_node({ + mapping: true, + simple_key: true + }); } else { - return this.expect_block_mapping(); + this.write_indicator('?', true); + this.states.push(this.expect_flow_mapping_value); + return this.expect_node({ + mapping: true + }); } } - } else { - return this.error('expected NodeEvent, but got', this.event); } - }; - Emitter.prototype.expect_alias = function() { - if (!this.event.anchor) { - this.error('anchor is not specified for alias'); + expect_flow_mapping_key() { + if (this.event instanceof events.MappingEndEvent) { + this.indent = this.indents.pop(); + this.flow_level--; + if (this.canonical) { + this.write_indicator(',', false); + this.write_indent(); + } + this.write_indicator('}', false); + return this.state = this.states.pop(); + } else { + this.write_indicator(',', false); + if (this.canonical || this.column > this.best_width) { + this.write_indent(); + } + if (!this.canonical && this.check_simple_key()) { + this.states.push(this.expect_flow_mapping_simple_value); + return this.expect_node({ + mapping: true, + simple_key: true + }); + } else { + this.write_indicator('?', true); + this.states.push(this.expect_flow_mapping_value); + return this.expect_node({ + mapping: true + }); + } + } } - this.process_anchor('*'); - return this.state = this.states.pop(); - }; - - Emitter.prototype.expect_scalar = function() { - this.increase_indent({ - flow: true - }); - this.process_scalar(); - this.indent = this.indents.pop(); - return this.state = this.states.pop(); - }; - - Emitter.prototype.expect_flow_sequence = function() { - this.write_indicator('[', true, { - whitespace: true - }); - this.flow_level++; - this.increase_indent({ - flow: true - }); - return this.state = this.expect_first_flow_sequence_item; - }; - Emitter.prototype.expect_first_flow_sequence_item = function() { - if (this.event instanceof events.SequenceEndEvent) { - this.indent = this.indents.pop(); - this.flow_level--; - this.write_indicator(']', false); - return this.state = this.states.pop(); - } else { - if (this.canonical || this.column > this.best_width) { - this.write_indent(); - } - this.states.push(this.expect_flow_sequence_item); + expect_flow_mapping_simple_value() { + this.write_indicator(':', false); + this.states.push(this.expect_flow_mapping_key); return this.expect_node({ - sequence: true + mapping: true }); } - }; - Emitter.prototype.expect_flow_sequence_item = function() { - if (this.event instanceof events.SequenceEndEvent) { - this.indent = this.indents.pop(); - this.flow_level--; - if (this.canonical) { - this.write_indicator(',', false); - this.write_indent(); - } - this.write_indicator(']', false); - return this.state = this.states.pop(); - } else { - this.write_indicator(',', false); + expect_flow_mapping_value() { if (this.canonical || this.column > this.best_width) { this.write_indent(); } - this.states.push(this.expect_flow_sequence_item); + this.write_indicator(':', true); + this.states.push(this.expect_flow_mapping_key); return this.expect_node({ - sequence: true + mapping: true }); } - }; - Emitter.prototype.expect_flow_mapping = function() { - this.write_indicator('{', true, { - whitespace: true - }); - this.flow_level++; - this.increase_indent({ - flow: true - }); - return this.state = this.expect_first_flow_mapping_key; - }; + expect_block_sequence() { + var indentless; + indentless = this.mapping_context && !this.indentation; + this.increase_indent({ + indentless: indentless + }); + return this.state = this.expect_first_block_sequence_item; + } - Emitter.prototype.expect_first_flow_mapping_key = function() { - if (this.event instanceof events.MappingEndEvent) { - this.indent = this.indents.pop(); - this.flow_level--; - this.write_indicator('}', false); - return this.state = this.states.pop(); - } else { - if (this.canonical || this.column > this.best_width) { - this.write_indent(); - } - if (!this.canonical && this.check_simple_key()) { - this.states.push(this.expect_flow_mapping_simple_value); - return this.expect_node({ - mapping: true, - simple_key: true - }); - } else { - this.write_indicator('?', true); - this.states.push(this.expect_flow_mapping_value); - return this.expect_node({ - mapping: true - }); - } + expect_first_block_sequence_item() { + return this.expect_block_sequence_item(true); } - }; - Emitter.prototype.expect_flow_mapping_key = function() { - if (this.event instanceof events.MappingEndEvent) { - this.indent = this.indents.pop(); - this.flow_level--; - if (this.canonical) { - this.write_indicator(',', false); - this.write_indent(); - } - this.write_indicator('}', false); - return this.state = this.states.pop(); - } else { - this.write_indicator(',', false); - if (this.canonical || this.column > this.best_width) { + expect_block_sequence_item(first = false) { + if (!first && this.event instanceof events.SequenceEndEvent) { + this.indent = this.indents.pop(); + return this.state = this.states.pop(); + } else { this.write_indent(); - } - if (!this.canonical && this.check_simple_key()) { - this.states.push(this.expect_flow_mapping_simple_value); - return this.expect_node({ - mapping: true, - simple_key: true + this.write_indicator('-', true, { + indentation: true }); - } else { - this.write_indicator('?', true); - this.states.push(this.expect_flow_mapping_value); + this.states.push(this.expect_block_sequence_item); return this.expect_node({ - mapping: true + sequence: true }); } } - }; - Emitter.prototype.expect_flow_mapping_simple_value = function() { - this.write_indicator(':', false); - this.states.push(this.expect_flow_mapping_key); - return this.expect_node({ - mapping: true - }); - }; - - Emitter.prototype.expect_flow_mapping_value = function() { - if (this.canonical || this.column > this.best_width) { - this.write_indent(); + expect_block_mapping() { + this.increase_indent(); + return this.state = this.expect_first_block_mapping_key; } - this.write_indicator(':', true); - this.states.push(this.expect_flow_mapping_key); - return this.expect_node({ - mapping: true - }); - }; - Emitter.prototype.expect_block_sequence = function() { - var indentless; - indentless = this.mapping_context && !this.indentation; - this.increase_indent({ - indentless: indentless - }); - return this.state = this.expect_first_block_sequence_item; - }; + expect_first_block_mapping_key() { + return this.expect_block_mapping_key(true); + } - Emitter.prototype.expect_first_block_sequence_item = function() { - return this.expect_block_sequence_item(true); - }; + expect_block_mapping_key(first = false) { + if (!first && this.event instanceof events.MappingEndEvent) { + this.indent = this.indents.pop(); + return this.state = this.states.pop(); + } else { + this.write_indent(); + if (this.check_simple_key()) { + this.states.push(this.expect_block_mapping_simple_value); + return this.expect_node({ + mapping: true, + simple_key: true + }); + } else { + this.write_indicator('?', true, { + indentation: true + }); + this.states.push(this.expect_block_mapping_value); + return this.expect_node({ + mapping: true + }); + } + } + } - Emitter.prototype.expect_block_sequence_item = function(first) { - if (first == null) { - first = false; + expect_block_mapping_simple_value() { + this.write_indicator(':', false); + this.states.push(this.expect_block_mapping_key); + return this.expect_node({ + mapping: true + }); } - if (!first && this.event instanceof events.SequenceEndEvent) { - this.indent = this.indents.pop(); - return this.state = this.states.pop(); - } else { + + expect_block_mapping_value() { this.write_indent(); - this.write_indicator('-', true, { + this.write_indicator(':', true, { indentation: true }); - this.states.push(this.expect_block_sequence_item); + this.states.push(this.expect_block_mapping_key); return this.expect_node({ - sequence: true + mapping: true }); } - }; - - Emitter.prototype.expect_block_mapping = function() { - this.increase_indent(); - return this.state = this.expect_first_block_mapping_key; - }; - - Emitter.prototype.expect_first_block_mapping_key = function() { - return this.expect_block_mapping_key(true); - }; - Emitter.prototype.expect_block_mapping_key = function(first) { - if (first == null) { - first = false; - } - if (!first && this.event instanceof events.MappingEndEvent) { - this.indent = this.indents.pop(); - return this.state = this.states.pop(); - } else { - this.write_indent(); - if (this.check_simple_key()) { - this.states.push(this.expect_block_mapping_simple_value); - return this.expect_node({ - mapping: true, - simple_key: true - }); - } else { - this.write_indicator('?', true, { - indentation: true - }); - this.states.push(this.expect_block_mapping_value); - return this.expect_node({ - mapping: true - }); + check_empty_document() { + var event; + if (!(this.event instanceof events.DocumentStartEvent) || this.events.length === 0) { + return false; } + event = this.events[0]; + return event instanceof events.ScalarEvent && (event.anchor == null) && (event.tag == null) && event.implicit && event.value === ''; } - }; - - Emitter.prototype.expect_block_mapping_simple_value = function() { - this.write_indicator(':', false); - this.states.push(this.expect_block_mapping_key); - return this.expect_node({ - mapping: true - }); - }; - - Emitter.prototype.expect_block_mapping_value = function() { - this.write_indent(); - this.write_indicator(':', true, { - indentation: true - }); - this.states.push(this.expect_block_mapping_key); - return this.expect_node({ - mapping: true - }); - }; - Emitter.prototype.check_empty_document = function() { - var event; - if (!(this.event instanceof events.DocumentStartEvent) || this.events.length === 0) { - return false; + check_empty_sequence() { + return this.event instanceof events.SequenceStartEvent && this.events[0] instanceof events.SequenceEndEvent; } - event = this.events[0]; - return event instanceof events.ScalarEvent && (event.anchor == null) && (event.tag == null) && event.implicit && event.value === ''; - }; - Emitter.prototype.check_empty_sequence = function() { - return this.event instanceof events.SequenceStartEvent && this.events[0] instanceof events.SequenceEndEvent; - }; + check_empty_mapping() { + return this.event instanceof events.MappingStartEvent && this.events[0] instanceof events.MappingEndEvent; + } - Emitter.prototype.check_empty_mapping = function() { - return this.event instanceof events.MappingStartEvent && this.events[0] instanceof events.MappingEndEvent; - }; + check_simple_key() { + var length; + length = 0; + if (this.event instanceof events.NodeEvent && (this.event.anchor != null)) { + if (this.prepared_anchor == null) { + this.prepared_anchor = this.prepare_anchor(this.event.anchor); + } + length += this.prepared_anchor.length; + } + if ((this.event.tag != null) && (this.event instanceof events.ScalarEvent || this.event instanceof events.CollectionStartEvent)) { + if (this.prepared_tag == null) { + this.prepared_tag = this.prepare_tag(this.event.tag); + } + length += this.prepared_tag.length; + } + if (this.event instanceof events.ScalarEvent) { + if (this.analysis == null) { + this.analysis = this.analyze_scalar(this.event.value); + } + length += this.analysis.scalar.length; + } + return length < 128 && (this.event instanceof events.AliasEvent || (this.event instanceof events.ScalarEvent && !this.analysis.empty && !this.analysis.multiline) || this.check_empty_sequence() || this.check_empty_mapping()); + } - Emitter.prototype.check_simple_key = function() { - var length; - length = 0; - if (this.event instanceof events.NodeEvent && (this.event.anchor != null)) { + process_anchor(indicator) { + if (this.event.anchor == null) { + this.prepared_anchor = null; + return; + } if (this.prepared_anchor == null) { this.prepared_anchor = this.prepare_anchor(this.event.anchor); } - length += this.prepared_anchor.length; + if (this.prepared_anchor) { + this.write_indicator(`${indicator}${this.prepared_anchor}`, true); + } + return this.prepared_anchor = null; } - if ((this.event.tag != null) && (this.event instanceof events.ScalarEvent || this.event instanceof events.CollectionStartEvent)) { + + process_tag() { + var tag; + tag = this.event.tag; + if (this.event instanceof events.ScalarEvent) { + if (this.style == null) { + this.style = this.choose_scalar_style(); + } + if ((!this.canonical || (tag == null)) && ((this.style === '' && this.event.implicit[0]) || (this.style !== '' && this.event.implicit[1]))) { + this.prepared_tag = null; + return; + } + if (this.event.implicit[0] && (tag == null)) { + tag = '!'; + this.prepared_tag = null; + } + } else if ((!this.canonical || (tag == null)) && this.event.implicit) { + this.prepared_tag = null; + return; + } + if (tag == null) { + this.error('tag is not specified'); + } if (this.prepared_tag == null) { - this.prepared_tag = this.prepare_tag(this.event.tag); + this.prepared_tag = this.prepare_tag(tag); } - length += this.prepared_tag.length; + this.write_indicator(this.prepared_tag, true); + return this.prepared_tag = null; } - if (this.event instanceof events.ScalarEvent) { + + process_scalar() { + var split; if (this.analysis == null) { this.analysis = this.analyze_scalar(this.event.value); } - length += this.analysis.scalar.length; + if (this.style == null) { + this.style = this.choose_scalar_style(); + } + split = !this.simple_key_context; + switch (this.style) { + case '"': + this.write_double_quoted(this.analysis.scalar, split); + break; + case "'": + this.write_single_quoted(this.analysis.scalar, split); + break; + case '>': + this.write_folded(this.analysis.scalar); + break; + case '|': + this.write_literal(this.analysis.scalar); + break; + default: + this.write_plain(this.analysis.scalar, split); + } + this.analysis = null; + return this.style = null; } - return length < 128 && (this.event instanceof events.AliasEvent || (this.event instanceof events.ScalarEvent && !this.analysis.empty && !this.analysis.multiline) || this.check_empty_sequence() || this.check_empty_mapping()); - }; - Emitter.prototype.process_anchor = function(indicator) { - if (this.event.anchor == null) { - this.prepared_anchor = null; - return; - } - if (this.prepared_anchor == null) { - this.prepared_anchor = this.prepare_anchor(this.event.anchor); - } - if (this.prepared_anchor) { - this.write_indicator("" + indicator + this.prepared_anchor, true); - } - return this.prepared_anchor = null; - }; - - Emitter.prototype.process_tag = function() { - var tag; - tag = this.event.tag; - if (this.event instanceof events.ScalarEvent) { - if (this.style == null) { - this.style = this.choose_scalar_style(); + choose_scalar_style() { + var ref; + if (this.analysis == null) { + this.analysis = this.analyze_scalar(this.event.value); } - if ((!this.canonical || (tag == null)) && ((this.style === '' && this.event.implicit[0]) || (this.style !== '' && this.event.implicit[1]))) { - this.prepared_tag = null; - return; + if (this.event.style === '"' || this.canonical) { + return '"'; } - if (this.event.implicit[0] && (tag == null)) { - tag = '!'; - this.prepared_tag = null; + if (!this.event.style && this.event.implicit[0] && !(this.simple_key_context && (this.analysis.empty || this.analysis.multiline)) && ((this.flow_level && this.analysis.allow_flow_plain) || (!this.flow_level && this.analysis.allow_block_plain))) { + return ''; + } + if (this.event.style && (ref = this.event.style, indexOf.call('|>', ref) >= 0) && !this.flow_level && !this.simple_key_context && this.analysis.allow_block) { + return this.event.style; + } + if ((!this.event.style || this.event.style === "'") && this.analysis.allow_single_quoted && !(this.simple_key_context && this.analysis.multiline)) { + return "'"; } - } else if ((!this.canonical || (tag == null)) && this.event.implicit) { - this.prepared_tag = null; - return; - } - if (tag == null) { - this.error('tag is not specified'); - } - if (this.prepared_tag == null) { - this.prepared_tag = this.prepare_tag(tag); - } - this.write_indicator(this.prepared_tag, true); - return this.prepared_tag = null; - }; - - Emitter.prototype.process_scalar = function() { - var split; - if (this.analysis == null) { - this.analysis = this.analyze_scalar(this.event.value); - } - if (this.style == null) { - this.style = this.choose_scalar_style(); - } - split = !this.simple_key_context; - switch (this.style) { - case '"': - this.write_double_quoted(this.analysis.scalar, split); - break; - case "'": - this.write_single_quoted(this.analysis.scalar, split); - break; - case '>': - this.write_folded(this.analysis.scalar); - break; - case '|': - this.write_literal(this.analysis.scalar); - break; - default: - this.write_plain(this.analysis.scalar, split); - } - this.analysis = null; - return this.style = null; - }; - - Emitter.prototype.choose_scalar_style = function() { - var ref; - if (this.analysis == null) { - this.analysis = this.analyze_scalar(this.event.value); - } - if (this.event.style === '"' || this.canonical) { return '"'; } - if (!this.event.style && this.event.implicit[0] && !(this.simple_key_context && (this.analysis.empty || this.analysis.multiline)) && ((this.flow_level && this.analysis.allow_flow_plain) || (!this.flow_level && this.analysis.allow_block_plain))) { - return ''; - } - if (this.event.style && (ref = this.event.style, indexOf.call('|>', ref) >= 0) && !this.flow_level && !this.simple_key_context && this.analysis.allow_block) { - return this.event.style; - } - if ((!this.event.style || this.event.style === "'") && this.analysis.allow_single_quoted && !(this.simple_key_context && this.analysis.multiline)) { - return "'"; - } - return '"'; - }; - Emitter.prototype.prepare_version = function(arg) { - var major, minor, version; - major = arg[0], minor = arg[1]; - version = major + "." + minor; - if (major === 1) { - return version; - } else { - return this.error('unsupported YAML version', version); + prepare_version(arg) { + var major, minor, version; + major = arg[0], minor = arg[1]; + version = `${major}.${minor}`; + if (major === 1) { + return version; + } else { + return this.error('unsupported YAML version', version); + } } - }; - Emitter.prototype.prepare_tag_handle = function(handle) { - var char, i, len, ref; - if (!handle) { - this.error('tag handle must not be empty'); - } - if (handle[0] !== '!' || handle.slice(-1) !== '!') { - this.error("tag handle must start and end with '!':", handle); - } - ref = handle.slice(1, -1); - for (i = 0, len = ref.length; i < len; i++) { - char = ref[i]; - if (!(('0' <= char && char <= '9') || ('A' <= char && char <= 'Z') || ('a' <= char && char <= 'z') || indexOf.call('-_', char) >= 0)) { - this.error("invalid character '" + char + "' in the tag handle:", handle); + prepare_tag_handle(handle) { + var char, i, len, ref; + if (!handle) { + this.error('tag handle must not be empty'); + } + if (handle[0] !== '!' || handle.slice(-1) !== '!') { + this.error("tag handle must start and end with '!':", handle); } + ref = handle.slice(1, -1); + for (i = 0, len = ref.length; i < len; i++) { + char = ref[i]; + if (!(('0' <= char && char <= '9') || ('A' <= char && char <= 'Z') || ('a' <= char && char <= 'z') || indexOf.call('-_', char) >= 0)) { + this.error(`invalid character '${char}' in the tag handle:`, handle); + } + } + return handle; } - return handle; - }; - Emitter.prototype.prepare_tag_prefix = function(prefix) { - var char, chunks, end, start; - if (!prefix) { - this.error('tag prefix must not be empty'); - } - chunks = []; - start = 0; - end = +(prefix[0] === '!'); - while (end < prefix.length) { - char = prefix[end]; - if (('0' <= char && char <= '9') || ('A' <= char && char <= 'Z') || ('a' <= char && char <= 'z') || indexOf.call('-;/?!:@&=+$,_.~*\'()[]', char) >= 0) { - end++; - } else { - if (start < end) { - chunks.push(prefix.slice(start, end)); + prepare_tag_prefix(prefix) { + var char, chunks, end, start; + if (!prefix) { + this.error('tag prefix must not be empty'); + } + chunks = []; + start = 0; + end = +(prefix[0] === '!'); + while (end < prefix.length) { + char = prefix[end]; + if (('0' <= char && char <= '9') || ('A' <= char && char <= 'Z') || ('a' <= char && char <= 'z') || indexOf.call('-;/?!:@&=+$,_.~*\'()[]', char) >= 0) { + end++; + } else { + if (start < end) { + chunks.push(prefix.slice(start, end)); + } + start = end = end + 1; + chunks.push(char); } - start = end = end + 1; - chunks.push(char); } + if (start < end) { + chunks.push(prefix.slice(start, end)); + } + return chunks.join(''); } - if (start < end) { - chunks.push(prefix.slice(start, end)); - } - return chunks.join(''); - }; - Emitter.prototype.prepare_tag = function(tag) { - var char, chunks, end, handle, i, k, len, prefix, ref, start, suffix, suffix_text; - if (!tag) { - this.error('tag must not be empty'); - } - if (tag === '!') { - return tag; - } - handle = null; - suffix = tag; - ref = ((function() { - var ref, results; - ref = this.tag_prefixes; - results = []; - for (k in ref) { - if (!hasProp.call(ref, k)) continue; - results.push(k); + prepare_tag(tag) { + var char, chunks, end, handle, i, k, len, prefix, ref, start, suffix, suffix_text; + if (!tag) { + this.error('tag must not be empty'); } - return results; - }).call(this)).sort(); - for (i = 0, len = ref.length; i < len; i++) { - prefix = ref[i]; - if (tag.indexOf(prefix) === 0 && (prefix === '!' || prefix.length < tag.length)) { - handle = this.tag_prefixes[prefix]; - suffix = tag.slice(prefix.length); + if (tag === '!') { + return tag; } - } - chunks = []; - start = end = 0; - while (end < suffix.length) { - char = suffix[end]; - if (('0' <= char && char <= '9') || ('A' <= char && char <= 'Z') || ('a' <= char && char <= 'z') || indexOf.call('-;/?!:@&=+$,_.~*\'()[]', char) >= 0 || (char === '!' && handle !== '!')) { - end++; - } else { - if (start < end) { - chunks.push(suffix.slice(start, end)); + handle = null; + suffix = tag; + ref = ((function() { + var ref, results; + ref = this.tag_prefixes; + results = []; + for (k in ref) { + if (!hasProp.call(ref, k)) continue; + results.push(k); + } + return results; + }).call(this)).sort(); + for (i = 0, len = ref.length; i < len; i++) { + prefix = ref[i]; + if (tag.indexOf(prefix) === 0 && (prefix === '!' || prefix.length < tag.length)) { + handle = this.tag_prefixes[prefix]; + suffix = tag.slice(prefix.length); } - start = end = end + 1; - chunks.push(char); + } + chunks = []; + start = end = 0; + while (end < suffix.length) { + char = suffix[end]; + if (('0' <= char && char <= '9') || ('A' <= char && char <= 'Z') || ('a' <= char && char <= 'z') || indexOf.call('-;/?!:@&=+$,_.~*\'()[]', char) >= 0 || (char === '!' && handle !== '!')) { + end++; + } else { + if (start < end) { + chunks.push(suffix.slice(start, end)); + } + start = end = end + 1; + chunks.push(char); + } + } + if (start < end) { + chunks.push(suffix.slice(start, end)); + } + suffix_text = chunks.join(''); + if (handle) { + return `${handle}${suffix_text}`; + } else { + return `!<${suffix_text}>`; } } - if (start < end) { - chunks.push(suffix.slice(start, end)); - } - suffix_text = chunks.join(''); - if (handle) { - return "" + handle + suffix_text; - } else { - return "!<" + suffix_text + ">"; - } - }; - Emitter.prototype.prepare_anchor = function(anchor) { - var char, i, len; - if (!anchor) { - this.error('anchor must not be empty'); - } - for (i = 0, len = anchor.length; i < len; i++) { - char = anchor[i]; - if (!(('0' <= char && char <= '9') || ('A' <= char && char <= 'Z') || ('a' <= char && char <= 'z') || indexOf.call('-_', char) >= 0)) { - this.error("invalid character '" + char + "' in the anchor:", anchor); + prepare_anchor(anchor) { + var char, i, len; + if (!anchor) { + this.error('anchor must not be empty'); + } + for (i = 0, len = anchor.length; i < len; i++) { + char = anchor[i]; + if (!(('0' <= char && char <= '9') || ('A' <= char && char <= 'Z') || ('a' <= char && char <= 'z') || indexOf.call('-_', char) >= 0)) { + this.error(`invalid character '${char}' in the anchor:`, anchor); + } } + return anchor; } - return anchor; - }; - Emitter.prototype.analyze_scalar = function(scalar) { - var allow_block, allow_block_plain, allow_double_quoted, allow_flow_plain, allow_single_quoted, block_indicators, break_space, char, flow_indicators, followed_by_whitespace, i, index, leading_break, leading_space, len, line_breaks, preceded_by_whitespace, previous_break, previous_space, ref, ref1, space_break, special_characters, trailing_break, trailing_space, unicode_characters; - if (!scalar) { - new ScalarAnalysis(scalar, true, false, false, true, true, true, false); - } - block_indicators = false; - flow_indicators = false; - line_breaks = false; - special_characters = false; - unicode_characters = false; - leading_space = false; - leading_break = false; - trailing_space = false; - trailing_break = false; - break_space = false; - space_break = false; - if (scalar.indexOf('---') === 0 || scalar.indexOf('...') === 0) { - block_indicators = true; - flow_indicators = true; - } - preceded_by_whitespace = true; - followed_by_whitespace = scalar.length === 1 || (ref = scalar[1], indexOf.call('\0 \t\r\n\x85\u2028\u2029', ref) >= 0); - previous_space = false; - previous_break = false; - index = 0; - for (index = i = 0, len = scalar.length; i < len; index = ++i) { - char = scalar[index]; - if (index === 0) { - if (indexOf.call('#,[]{}&*!|>\'"%@`', char) >= 0 || (char === '-' && followed_by_whitespace)) { - flow_indicators = true; - block_indicators = true; - } else if (indexOf.call('?:', char) >= 0) { - flow_indicators = true; - if (followed_by_whitespace) { + analyze_scalar(scalar) { + var allow_block, allow_block_plain, allow_double_quoted, allow_flow_plain, allow_single_quoted, block_indicators, break_space, char, flow_indicators, followed_by_whitespace, i, index, leading_break, leading_space, len, line_breaks, preceded_by_whitespace, previous_break, previous_space, ref, ref1, space_break, special_characters, trailing_break, trailing_space, unicode_characters; + if (!scalar) { + new ScalarAnalysis(scalar, true, false, false, true, true, true, false); + } + block_indicators = false; + flow_indicators = false; + line_breaks = false; + special_characters = false; + unicode_characters = false; + leading_space = false; + leading_break = false; + trailing_space = false; + trailing_break = false; + break_space = false; + space_break = false; + if (scalar.indexOf('---') === 0 || scalar.indexOf('...') === 0) { + block_indicators = true; + flow_indicators = true; + } + preceded_by_whitespace = true; + followed_by_whitespace = scalar.length === 1 || (ref = scalar[1], indexOf.call('\0 \t\r\n\x85\u2028\u2029', ref) >= 0); + previous_space = false; + previous_break = false; + index = 0; + for (index = i = 0, len = scalar.length; i < len; index = ++i) { + char = scalar[index]; + if (index === 0) { + if (indexOf.call('#,[]{}&*!|>\'"%@`', char) >= 0 || (char === '-' && followed_by_whitespace)) { + flow_indicators = true; block_indicators = true; + } else if (indexOf.call('?:', char) >= 0) { + flow_indicators = true; + if (followed_by_whitespace) { + block_indicators = true; + } } - } - } else { - if (indexOf.call(',?[]{}', char) >= 0) { - flow_indicators = true; - } else if (char === ':') { - flow_indicators = true; - if (followed_by_whitespace) { + } else { + if (indexOf.call(',?[]{}', char) >= 0) { + flow_indicators = true; + } else if (char === ':') { + flow_indicators = true; + if (followed_by_whitespace) { + block_indicators = true; + } + } else if (char === '#' && preceded_by_whitespace) { + flow_indicators = true; block_indicators = true; } - } else if (char === '#' && preceded_by_whitespace) { - flow_indicators = true; - block_indicators = true; } - } - if (indexOf.call('\n\x85\u2028\u2029', char) >= 0) { - line_breaks = true; - } - if (!(char === '\n' || ('\x20' <= char && char <= '\x7e'))) { - if (char !== '\uFEFF' && (char === '\x85' || ('\xA0' <= char && char <= '\uD7FF') || ('\uE000' <= char && char <= '\uFFFD'))) { - unicode_characters = true; - if (!this.allow_unicode) { + if (indexOf.call('\n\x85\u2028\u2029', char) >= 0) { + line_breaks = true; + } + if (!(char === '\n' || ('\x20' <= char && char <= '\x7e'))) { + if (char !== '\uFEFF' && (char === '\x85' || ('\xA0' <= char && char <= '\uD7FF') || ('\uE000' <= char && char <= '\uFFFD'))) { + unicode_characters = true; + if (!this.allow_unicode) { + special_characters = true; + } + } else { special_characters = true; } + } + if (char === ' ') { + if (index === 0) { + leading_space = true; + } + if (index === scalar.length - 1) { + trailing_space = true; + } + if (previous_break) { + break_space = true; + } + previous_break = false; + previous_space = true; + } else if (indexOf.call('\n\x85\u2028\u2029', char) >= 0) { + if (index === 0) { + leading_break = true; + } + if (index === scalar.length - 1) { + trailing_break = true; + } + if (previous_space) { + space_break = true; + } + previous_break = true; + previous_space = false; } else { - special_characters = true; + previous_break = false; + previous_space = false; } + preceded_by_whitespace = indexOf.call(C_WHITESPACE, char) >= 0; + followed_by_whitespace = index + 2 >= scalar.length || (ref1 = scalar[index + 2], indexOf.call(C_WHITESPACE, ref1) >= 0); } - if (char === ' ') { - if (index === 0) { - leading_space = true; - } - if (index === scalar.length - 1) { - trailing_space = true; - } - if (previous_break) { - break_space = true; - } - previous_break = false; - previous_space = true; - } else if (indexOf.call('\n\x85\u2028\u2029', char) >= 0) { - if (index === 0) { - leading_break = true; - } - if (index === scalar.length - 1) { - trailing_break = true; - } - if (previous_space) { - space_break = true; - } - previous_break = true; - previous_space = false; - } else { - previous_break = false; - previous_space = false; + allow_flow_plain = true; + allow_block_plain = true; + allow_single_quoted = true; + allow_double_quoted = true; + allow_block = true; + if (leading_space || leading_break || trailing_space || trailing_break) { + allow_flow_plain = allow_block_plain = false; } - preceded_by_whitespace = indexOf.call(C_WHITESPACE, char) >= 0; - followed_by_whitespace = index + 2 >= scalar.length || (ref1 = scalar[index + 2], indexOf.call(C_WHITESPACE, ref1) >= 0); - } - allow_flow_plain = true; - allow_block_plain = true; - allow_single_quoted = true; - allow_double_quoted = true; - allow_block = true; - if (leading_space || leading_break || trailing_space || trailing_break) { - allow_flow_plain = allow_block_plain = false; - } - if (trailing_space) { - allow_block = false; - } - if (break_space) { - allow_flow_plain = allow_block_plain = allow_single_quoted = false; - } - if (space_break || special_characters) { - allow_flow_plain = allow_block_plain = allow_single_quoted = allow_block = false; - } - if (line_breaks) { - allow_flow_plain = allow_block_plain = false; - } - if (flow_indicators) { - allow_flow_plain = false; - } - if (block_indicators) { - allow_block_plain = false; + if (trailing_space) { + allow_block = false; + } + if (break_space) { + allow_flow_plain = allow_block_plain = allow_single_quoted = false; + } + if (space_break || special_characters) { + allow_flow_plain = allow_block_plain = allow_single_quoted = allow_block = false; + } + if (line_breaks) { + allow_flow_plain = allow_block_plain = false; + } + if (flow_indicators) { + allow_flow_plain = false; + } + if (block_indicators) { + allow_block_plain = false; + } + return new ScalarAnalysis(scalar, false, line_breaks, allow_flow_plain, allow_block_plain, allow_single_quoted, allow_double_quoted, allow_block); } - return new ScalarAnalysis(scalar, false, line_breaks, allow_flow_plain, allow_block_plain, allow_single_quoted, allow_double_quoted, allow_block); - }; - /* - Write BOM if needed. - */ + /* + Write BOM if needed. + */ - Emitter.prototype.write_stream_start = function() { - if (this.encoding && this.encoding.indexOf('utf-16') === 0) { - return this.stream.write('\uFEFF', this.encoding); + write_stream_start() { + if (this.encoding && this.encoding.indexOf('utf-16') === 0) { + return this.stream.write('\uFEFF', this.encoding); + } } - }; - - Emitter.prototype.write_stream_end = function() { - return this.flush_stream(); - }; - Emitter.prototype.write_indicator = function(indicator, need_whitespace, options) { - var data; - if (options == null) { - options = {}; + write_stream_end() { + return this.flush_stream(); } - data = this.whitespace || !need_whitespace ? indicator : ' ' + indicator; - this.whitespace = !!options.whitespace; - this.indentation && (this.indentation = !!options.indentation); - this.column += data.length; - this.open_ended = false; - return this.stream.write(data, this.encoding); - }; - Emitter.prototype.write_indent = function() { - var data, indent, ref; - indent = (ref = this.indent) != null ? ref : 0; - if (!this.indentation || this.column > indent || (this.column === indent && !this.whitespace)) { - this.write_line_break(); - } - if (this.column < indent) { - this.whitespace = true; - data = new Array(indent - this.column + 1).join(' '); - this.column = indent; + write_indicator(indicator, need_whitespace, options = {}) { + var data; + data = this.whitespace || !need_whitespace ? indicator : ' ' + indicator; + this.whitespace = !!options.whitespace; + this.indentation && (this.indentation = !!options.indentation); + this.column += data.length; + this.open_ended = false; return this.stream.write(data, this.encoding); } - }; - - Emitter.prototype.write_line_break = function(data) { - this.whitespace = true; - this.indentation = true; - this.line += 1; - this.column = 0; - return this.stream.write(data != null ? data : this.best_line_break, this.encoding); - }; - - Emitter.prototype.write_version_directive = function(version_text) { - this.stream.write("%YAML " + version_text, this.encoding); - return this.write_line_break(); - }; - - Emitter.prototype.write_tag_directive = function(handle_text, prefix_text) { - this.stream.write("%TAG " + handle_text + " " + prefix_text, this.encoding); - return this.write_line_break(); - }; - Emitter.prototype.write_single_quoted = function(text, split) { - var br, breaks, char, data, end, i, len, ref, spaces, start; - if (split == null) { - split = true; + write_indent() { + var data, indent, ref; + indent = (ref = this.indent) != null ? ref : 0; + if (!this.indentation || this.column > indent || (this.column === indent && !this.whitespace)) { + this.write_line_break(); + } + if (this.column < indent) { + this.whitespace = true; + data = new Array(indent - this.column + 1).join(' '); + this.column = indent; + return this.stream.write(data, this.encoding); + } } - this.write_indicator("'", true); - spaces = false; - breaks = false; - start = end = 0; - while (end <= text.length) { - char = text[end]; - if (spaces) { - if ((char == null) || char !== ' ') { - if (start + 1 === end && this.column > this.best_width && split && start !== 0 && end !== text.length) { - this.write_indent(); - } else { - data = text.slice(start, end); - this.column += data.length; - this.stream.write(data, this.encoding); - } - start = end; - } - } else if (breaks) { - if ((char == null) || indexOf.call('\n\x85\u2028\u2029', char) < 0) { - if (text[start] === '\n') { - this.write_line_break(); + + write_line_break(data) { + this.whitespace = true; + this.indentation = true; + this.line += 1; + this.column = 0; + return this.stream.write(data != null ? data : this.best_line_break, this.encoding); + } + + write_version_directive(version_text) { + this.stream.write(`%YAML ${version_text}`, this.encoding); + return this.write_line_break(); + } + + write_tag_directive(handle_text, prefix_text) { + this.stream.write(`%TAG ${handle_text} ${prefix_text}`, this.encoding); + return this.write_line_break(); + } + + write_single_quoted(text, split = true) { + var br, breaks, char, data, end, i, len, ref, spaces, start; + this.write_indicator("'", true); + spaces = false; + breaks = false; + start = end = 0; + while (end <= text.length) { + char = text[end]; + if (spaces) { + if ((char == null) || char !== ' ') { + if (start + 1 === end && this.column > this.best_width && split && start !== 0 && end !== text.length) { + this.write_indent(); + } else { + data = text.slice(start, end); + this.column += data.length; + this.stream.write(data, this.encoding); + } + start = end; } - ref = text.slice(start, end); - for (i = 0, len = ref.length; i < len; i++) { - br = ref[i]; - if (br === '\n') { + } else if (breaks) { + if ((char == null) || indexOf.call('\n\x85\u2028\u2029', char) < 0) { + if (text[start] === '\n') { this.write_line_break(); - } else { - this.write_line_break(br); } + ref = text.slice(start, end); + for (i = 0, len = ref.length; i < len; i++) { + br = ref[i]; + if (br === '\n') { + this.write_line_break(); + } else { + this.write_line_break(br); + } + } + this.write_indent(); + start = end; } - this.write_indent(); - start = end; - } - } else if (((char == null) || indexOf.call(' \n\x85\u2028\u2029', char) >= 0 || char === "'") && start < end) { - data = text.slice(start, end); - this.column += data.length; - this.stream.write(data, this.encoding); - start = end; - } - if (char === "'") { - this.column += 2; - this.stream.write("''", this.encoding); - start = end + 1; - } - if (char != null) { - spaces = char === ' '; - breaks = indexOf.call('\n\x85\u2028\u2029', char) >= 0; - } - end++; - } - return this.write_indicator("'", false); - }; - - Emitter.prototype.write_double_quoted = function(text, split) { - var char, data, end, start; - if (split == null) { - split = true; - } - this.write_indicator('"', true); - start = end = 0; - while (end <= text.length) { - char = text[end]; - if ((char == null) || indexOf.call('"\\\x85\u2028\u2029\uFEFF', char) >= 0 || !(('\x20' <= char && char <= '\x7E') || (this.allow_unicode && (('\xA0' <= char && char <= '\uD7FF') || ('\uE000' <= char && char <= '\uFFFD'))))) { - if (start < end) { + } else if (((char == null) || indexOf.call(' \n\x85\u2028\u2029', char) >= 0 || char === "'") && start < end) { data = text.slice(start, end); this.column += data.length; this.stream.write(data, this.encoding); start = end; } - if (char != null) { - data = char in ESCAPE_REPLACEMENTS ? '\\' + ESCAPE_REPLACEMENTS[char] : char <= '\xFF' ? "\\x" + (util.pad_left(util.to_hex(char), '0', 2)) : char <= '\uFFFF' ? "\\u" + (util.pad_left(util.to_hex(char), '0', 4)) : "\\U" + (util.pad_left(util.to_hex(char), '0', 16)); - this.column += data.length; - this.stream.write(data, this.encoding); + if (char === "'") { + this.column += 2; + this.stream.write("''", this.encoding); start = end + 1; } - } - if (split && (0 < end && end < text.length - 1) && (char === ' ' || start >= end) && this.column + (end - start) > this.best_width) { - data = text.slice(start, end) + "\\"; - if (start < end) { - start = end; - } - this.column += data.length; - this.stream.write(data, this.encoding); - this.write_indent(); - this.whitespace = false; - this.indentation = false; - if (text[start] === ' ') { - data = '\\'; - this.column += data.length; - this.stream.write(data, this.encoding); + if (char != null) { + spaces = char === ' '; + breaks = indexOf.call('\n\x85\u2028\u2029', char) >= 0; } + end++; } - end++; + return this.write_indicator("'", false); } - return this.write_indicator('"', false); - }; - Emitter.prototype.write_folded = function(text) { - var br, breaks, char, data, end, hints, i, leading_space, len, ref, results, spaces, start; - hints = this.determine_block_hints(text); - this.write_indicator(">" + hints, true); - if (hints.slice(-1) === '+') { - this.open_ended = true; - } - this.write_line_break(); - leading_space = true; - breaks = true; - spaces = false; - start = end = 0; - results = []; - while (end <= text.length) { - char = text[end]; - if (breaks) { - if ((char == null) || indexOf.call('\n\x85\u2028\u2029', char) < 0) { - if (!leading_space && (char != null) && char !== ' ' && text[start] === '\n') { - this.write_line_break(); - } - leading_space = char === ' '; - ref = text.slice(start, end); - for (i = 0, len = ref.length; i < len; i++) { - br = ref[i]; - if (br === '\n') { - this.write_line_break(); - } else { - this.write_line_break(br); - } + write_double_quoted(text, split = true) { + var char, data, end, start; + this.write_indicator('"', true); + start = end = 0; + while (end <= text.length) { + char = text[end]; + if ((char == null) || indexOf.call('"\\\x85\u2028\u2029\uFEFF', char) >= 0 || !(('\x20' <= char && char <= '\x7E') || (this.allow_unicode && (('\xA0' <= char && char <= '\uD7FF') || ('\uE000' <= char && char <= '\uFFFD'))))) { + if (start < end) { + data = text.slice(start, end); + this.column += data.length; + this.stream.write(data, this.encoding); + start = end; } if (char != null) { - this.write_indent(); + data = char in ESCAPE_REPLACEMENTS ? '\\' + ESCAPE_REPLACEMENTS[char] : char <= '\xFF' ? `\\x${util.pad_left(util.to_hex(char), '0', 2)}` : char <= '\uFFFF' ? `\\u${util.pad_left(util.to_hex(char), '0', 4)}` : `\\U${util.pad_left(util.to_hex(char), '0', 16)}`; + this.column += data.length; + this.stream.write(data, this.encoding); + start = end + 1; } - start = end; } - } else if (spaces) { - if (char !== ' ') { - if (start + 1 === end && this.column > this.best_width) { - this.write_indent(); - } else { - data = text.slice(start, end); + if (split && (0 < end && end < text.length - 1) && (char === ' ' || start >= end) && this.column + (end - start) > this.best_width) { + data = `${text.slice(start, end)}\\`; + if (start < end) { + start = end; + } + this.column += data.length; + this.stream.write(data, this.encoding); + this.write_indent(); + this.whitespace = false; + this.indentation = false; + if (text[start] === ' ') { + data = '\\'; this.column += data.length; this.stream.write(data, this.encoding); } - start = end; } - } else if ((char == null) || indexOf.call(' \n\x85\u2028\u2029', char) >= 0) { - data = text.slice(start, end); - this.column += data.length; - this.stream.write(data, this.encoding); - if (char == null) { - this.write_line_break(); - } - start = end; - } - if (char != null) { - breaks = indexOf.call('\n\x85\u2028\u2029', char) >= 0; - spaces = char === ' '; + end++; } - results.push(end++); + return this.write_indicator('"', false); } - return results; - }; - Emitter.prototype.write_literal = function(text) { - var br, breaks, char, data, end, hints, i, len, ref, results, start; - hints = this.determine_block_hints(text); - this.write_indicator("|" + hints, true); - if (hints.slice(-1) === '+') { - this.open_ended = true; - } - this.write_line_break(); - breaks = true; - start = end = 0; - results = []; - while (end <= text.length) { - char = text[end]; - if (breaks) { - if ((char == null) || indexOf.call('\n\x85\u2028\u2029', char) < 0) { - ref = text.slice(start, end); - for (i = 0, len = ref.length; i < len; i++) { - br = ref[i]; - if (br === '\n') { + write_folded(text) { + var br, breaks, char, data, end, hints, i, leading_space, len, ref, results, spaces, start; + hints = this.determine_block_hints(text); + this.write_indicator(`>${hints}`, true); + if (hints.slice(-1) === '+') { + this.open_ended = true; + } + this.write_line_break(); + leading_space = true; + breaks = true; + spaces = false; + start = end = 0; + results = []; + while (end <= text.length) { + char = text[end]; + if (breaks) { + if ((char == null) || indexOf.call('\n\x85\u2028\u2029', char) < 0) { + if (!leading_space && (char != null) && char !== ' ' && text[start] === '\n') { this.write_line_break(); - } else { - this.write_line_break(br); } + leading_space = char === ' '; + ref = text.slice(start, end); + for (i = 0, len = ref.length; i < len; i++) { + br = ref[i]; + if (br === '\n') { + this.write_line_break(); + } else { + this.write_line_break(br); + } + } + if (char != null) { + this.write_indent(); + } + start = end; } - if (char != null) { - this.write_indent(); + } else if (spaces) { + if (char !== ' ') { + if (start + 1 === end && this.column > this.best_width) { + this.write_indent(); + } else { + data = text.slice(start, end); + this.column += data.length; + this.stream.write(data, this.encoding); + } + start = end; } - start = end; - } - } else { - if ((char == null) || indexOf.call('\n\x85\u2028\u2029', char) >= 0) { + } else if ((char == null) || indexOf.call(' \n\x85\u2028\u2029', char) >= 0) { data = text.slice(start, end); + this.column += data.length; this.stream.write(data, this.encoding); if (char == null) { this.write_line_break(); } start = end; } + if (char != null) { + breaks = indexOf.call('\n\x85\u2028\u2029', char) >= 0; + spaces = char === ' '; + } + results.push(end++); } - if (char != null) { - breaks = indexOf.call('\n\x85\u2028\u2029', char) >= 0; - } - results.push(end++); + return results; } - return results; - }; - Emitter.prototype.write_plain = function(text, split) { - var br, breaks, char, data, end, i, len, ref, results, spaces, start; - if (split == null) { - split = true; - } - if (!text) { - return; - } - if (this.root_context) { - this.open_ended = true; - } - if (!this.whitespace) { - data = ' '; - this.column += data.length; - this.stream.write(data, this.encoding); - } - this.whitespace = false; - this.indentation = false; - spaces = false; - breaks = false; - start = end = 0; - results = []; - while (end <= text.length) { - char = text[end]; - if (spaces) { - if (char !== ' ') { - if (start + 1 === end && this.column > this.best_width && split) { - this.write_indent(); - this.whitespace = false; - this.indentation = false; - } else { + write_literal(text) { + var br, breaks, char, data, end, hints, i, len, ref, results, start; + hints = this.determine_block_hints(text); + this.write_indicator(`|${hints}`, true); + if (hints.slice(-1) === '+') { + this.open_ended = true; + } + this.write_line_break(); + breaks = true; + start = end = 0; + results = []; + while (end <= text.length) { + char = text[end]; + if (breaks) { + if ((char == null) || indexOf.call('\n\x85\u2028\u2029', char) < 0) { + ref = text.slice(start, end); + for (i = 0, len = ref.length; i < len; i++) { + br = ref[i]; + if (br === '\n') { + this.write_line_break(); + } else { + this.write_line_break(br); + } + } + if (char != null) { + this.write_indent(); + } + start = end; + } + } else { + if ((char == null) || indexOf.call('\n\x85\u2028\u2029', char) >= 0) { data = text.slice(start, end); - this.column += data.length; this.stream.write(data, this.encoding); + if (char == null) { + this.write_line_break(); + } + start = end; } - start = end; } - } else if (breaks) { - if (indexOf.call('\n\x85\u2028\u2029', char) < 0) { - if (text[start] === '\n') { - this.write_line_break(); + if (char != null) { + breaks = indexOf.call('\n\x85\u2028\u2029', char) >= 0; + } + results.push(end++); + } + return results; + } + + write_plain(text, split = true) { + var br, breaks, char, data, end, i, len, ref, results, spaces, start; + if (!text) { + return; + } + if (this.root_context) { + this.open_ended = true; + } + if (!this.whitespace) { + data = ' '; + this.column += data.length; + this.stream.write(data, this.encoding); + } + this.whitespace = false; + this.indentation = false; + spaces = false; + breaks = false; + start = end = 0; + results = []; + while (end <= text.length) { + char = text[end]; + if (spaces) { + if (char !== ' ') { + if (start + 1 === end && this.column > this.best_width && split) { + this.write_indent(); + this.whitespace = false; + this.indentation = false; + } else { + data = text.slice(start, end); + this.column += data.length; + this.stream.write(data, this.encoding); + } + start = end; } - ref = text.slice(start, end); - for (i = 0, len = ref.length; i < len; i++) { - br = ref[i]; - if (br === '\n') { + } else if (breaks) { + if (indexOf.call('\n\x85\u2028\u2029', char) < 0) { + if (text[start] === '\n') { this.write_line_break(); - } else { - this.write_line_break(br); } + ref = text.slice(start, end); + for (i = 0, len = ref.length; i < len; i++) { + br = ref[i]; + if (br === '\n') { + this.write_line_break(); + } else { + this.write_line_break(br); + } + } + this.write_indent(); + this.whitespace = false; + this.indentation = false; + start = end; + } + } else { + if ((char == null) || indexOf.call(' \n\x85\u2028\u2029', char) >= 0) { + data = text.slice(start, end); + this.column += data.length; + this.stream.write(data, this.encoding); + start = end; } - this.write_indent(); - this.whitespace = false; - this.indentation = false; - start = end; } - } else { - if ((char == null) || indexOf.call(' \n\x85\u2028\u2029', char) >= 0) { - data = text.slice(start, end); - this.column += data.length; - this.stream.write(data, this.encoding); - start = end; + if (char != null) { + spaces = char === ' '; + breaks = indexOf.call('\n\x85\u2028\u2029', char) >= 0; } + results.push(end++); + } + return results; + } + + determine_block_hints(text) { + var first, hints, i, last, penultimate; + hints = ''; + first = text[0], i = text.length - 2, penultimate = text[i++], last = text[i++]; + if (indexOf.call(' \n\x85\u2028\u2029', first) >= 0) { + hints += this.best_indent; } - if (char != null) { - spaces = char === ' '; - breaks = indexOf.call('\n\x85\u2028\u2029', char) >= 0; + if (indexOf.call('\n\x85\u2028\u2029', last) < 0) { + hints += '-'; + } else if (text.length === 1 || indexOf.call('\n\x85\u2028\u2029', penultimate) >= 0) { + hints += '+'; } - results.push(end++); + return hints; } - return results; - }; - Emitter.prototype.determine_block_hints = function(text) { - var first, hints, i, last, penultimate; - hints = ''; - first = text[0], i = text.length - 2, penultimate = text[i++], last = text[i++]; - if (indexOf.call(' \n\x85\u2028\u2029', first) >= 0) { - hints += this.best_indent; + flush_stream() { + var base; + return typeof (base = this.stream).flush === "function" ? base.flush() : void 0; } - if (indexOf.call('\n\x85\u2028\u2029', last) < 0) { - hints += '-'; - } else if (text.length === 1 || indexOf.call('\n\x85\u2028\u2029', penultimate) >= 0) { - hints += '+'; + + + /* + Helper for common error pattern. + */ + + error(message, context) { + var ref, ref1; + if (context) { + context = (ref = context != null ? (ref1 = context.constructor) != null ? ref1.name : void 0 : void 0) != null ? ref : util.inspect(context); + } + throw new exports.EmitterError(`${message}${(context ? ` ${context}` : '')}`); } - return hints; - }; - Emitter.prototype.flush_stream = function() { - var base; - return typeof (base = this.stream).flush === "function" ? base.flush() : void 0; }; + C_WHITESPACE = '\0 \t\r\n\x85\u2028\u2029'; - /* - Helper for common error pattern. - */ + DEFAULT_TAG_PREFIXES = { + '!': '!', + 'tag:yaml.org,2002:': '!!' + }; - Emitter.prototype.error = function(message, context) { - var ref, ref1; - if (context) { - context = (ref = context != null ? (ref1 = context.constructor) != null ? ref1.name : void 0 : void 0) != null ? ref : util.inspect(context); - } - throw new exports.EmitterError("" + message + (context ? " " + context : '')); + ESCAPE_REPLACEMENTS = { + '\0': '0', + '\x07': 'a', + '\x08': 'b', + '\x09': 't', + '\x0A': 'n', + '\x0B': 'v', + '\x0C': 'f', + '\x0D': 'r', + '\x1B': 'e', + '"': '"', + '\\': '\\', + '\x85': 'N', + '\xA0': '_', + '\u2028': 'L', + '\u2029': 'P' }; + ctor = Emitter.prototype.initialise; + return Emitter; })(); - ScalarAnalysis = (function() { - function ScalarAnalysis(scalar1, empty, multiline, allow_flow_plain1, allow_block_plain1, allow_single_quoted1, allow_double_quoted1, allow_block1) { + ScalarAnalysis = class ScalarAnalysis { + constructor(scalar1, empty, multiline, allow_flow_plain1, allow_block_plain1, allow_single_quoted1, allow_double_quoted1, allow_block1) { this.scalar = scalar1; this.empty = empty; this.multiline = multiline; @@ -1314,8 +1293,6 @@ this.allow_block = allow_block1; } - return ScalarAnalysis; - - })(); + }; }).call(this); diff --git a/lib/errors.js b/lib/errors.js index e76f94b..f9ba2ee 100644 --- a/lib/errors.js +++ b/lib/errors.js @@ -1,24 +1,16 @@ (function() { - var indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty; + var indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; - this.Mark = (function() { - function Mark(line, column, buffer, pointer) { + this.Mark = class Mark { + constructor(line, column, buffer, pointer) { this.line = line; this.column = column; this.buffer = buffer; this.pointer = pointer; } - Mark.prototype.get_snippet = function(indent, max_length) { + get_snippet(indent = 4, max_length = 75) { var break_chars, end, head, ref, ref1, start, tail; - if (indent == null) { - indent = 4; - } - if (max_length == null) { - max_length = 75; - } if (this.buffer == null) { return null; } @@ -43,74 +35,82 @@ break; } } - return "" + ((new Array(indent)).join(' ')) + head + this.buffer.slice(start, end) + tail + "\n" + ((new Array(indent + this.pointer - start + head.length)).join(' ')) + "^"; - }; + return `${(new Array(indent)).join(' ')}${head}${this.buffer.slice(start, end)}${tail}\n${(new Array(indent + this.pointer - start + head.length)).join(' ')}^`; + } - Mark.prototype.toString = function() { + toString() { var snippet, where; snippet = this.get_snippet(); - where = " on line " + (this.line + 1) + ", column " + (this.column + 1); + where = ` on line ${this.line + 1}, column ${this.column + 1}`; if (snippet) { return where; } else { - return where + ":\n" + snippet; + return `${where}:\n${snippet}`; } - }; - - return Mark; + } - })(); + }; this.YAMLError = (function(superClass) { - extend(YAMLError, superClass); + class YAMLError extends superClass { + constructor(message) { + super(); + this.message = message; + Object.defineProperty(this, 'stack', { + get: function() { + return this.toString() + '\n' + (new Error).stack.split('\n').slice(1).join('\n'); + } + }); + } - function YAMLError(message) { - this.message = message; - YAMLError.__super__.constructor.call(this); - this.stack = this.toString() + '\n' + (new Error).stack.split('\n').slice(1).join('\n'); - } + toString() { + return this.message; + } - YAMLError.prototype.toString = function() { - return this.message; }; + YAMLError.__super__ = superClass.prototype; + return YAMLError; })(Error); this.MarkedYAMLError = (function(superClass) { - extend(MarkedYAMLError, superClass); - - function MarkedYAMLError(context, context_mark, problem, problem_mark, note) { - this.context = context; - this.context_mark = context_mark; - this.problem = problem; - this.problem_mark = problem_mark; - this.note = note; - MarkedYAMLError.__super__.constructor.call(this); - } - - MarkedYAMLError.prototype.toString = function() { - var lines; - lines = []; - if (this.context != null) { - lines.push(this.context); - } - if ((this.context_mark != null) && ((this.problem == null) || (this.problem_mark == null) || this.context_mark.line !== this.problem_mark.line || this.context_mark.column !== this.problem_mark.column)) { - lines.push(this.context_mark.toString()); - } - if (this.problem != null) { - lines.push(this.problem); + class MarkedYAMLError extends superClass { + constructor(context, context_mark, problem, problem_mark, note) { + super(); + this.context = context; + this.context_mark = context_mark; + this.problem = problem; + this.problem_mark = problem_mark; + this.note = note; } - if (this.problem_mark != null) { - lines.push(this.problem_mark.toString()); - } - if (this.note != null) { - lines.push(this.note); + + toString() { + var lines; + lines = []; + if (this.context != null) { + lines.push(this.context); + } + if ((this.context_mark != null) && ((this.problem == null) || (this.problem_mark == null) || this.context_mark.line !== this.problem_mark.line || this.context_mark.column !== this.problem_mark.column)) { + lines.push(this.context_mark.toString()); + } + if (this.problem != null) { + lines.push(this.problem); + } + if (this.problem_mark != null) { + lines.push(this.problem_mark.toString()); + } + if (this.note != null) { + lines.push(this.note); + } + return lines.join('\n'); } - return lines.join('\n'); + }; + MarkedYAMLError.__super__ = superClass.prototype; + return MarkedYAMLError; })(this.YAMLError); diff --git a/lib/events.js b/lib/events.js index 3fc1a63..2b9adda 100644 --- a/lib/events.js +++ b/lib/events.js @@ -1,176 +1,169 @@ (function() { - var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty; - - this.Event = (function() { - function Event(start_mark, end_mark) { - this.start_mark = start_mark; - this.end_mark = end_mark; + this.Event = class Event { + constructor(start_mark1, end_mark1) { + this.start_mark = start_mark1; + this.end_mark = end_mark1; } - return Event; - - })(); + }; this.NodeEvent = (function(superClass) { - extend(NodeEvent, superClass); + class NodeEvent extends superClass { + constructor(anchor, start_mark, end_mark) { + super(start_mark, end_mark); + this.anchor = anchor; + } - function NodeEvent(anchor, start_mark, end_mark) { - this.anchor = anchor; - this.start_mark = start_mark; - this.end_mark = end_mark; - } + }; + + NodeEvent.__super__ = superClass.prototype; return NodeEvent; })(this.Event); this.CollectionStartEvent = (function(superClass) { - extend(CollectionStartEvent, superClass); - - function CollectionStartEvent(anchor, tag, implicit, start_mark, end_mark, flow_style) { - this.anchor = anchor; - this.tag = tag; - this.implicit = implicit; - this.start_mark = start_mark; - this.end_mark = end_mark; - this.flow_style = flow_style; - } + class CollectionStartEvent extends superClass { + constructor(anchor, tag, implicit, start_mark, end_mark, flow_style) { + super(start_mark, end_mark); + this.anchor = anchor; + this.tag = tag; + this.implicit = implicit; + this.flow_style = flow_style; + } + + }; + + CollectionStartEvent.__super__ = superClass.prototype; return CollectionStartEvent; })(this.NodeEvent); this.CollectionEndEvent = (function(superClass) { - extend(CollectionEndEvent, superClass); + class CollectionEndEvent extends superClass {}; - function CollectionEndEvent() { - return CollectionEndEvent.__super__.constructor.apply(this, arguments); - } + CollectionEndEvent.__super__ = superClass.prototype; return CollectionEndEvent; })(this.Event); this.StreamStartEvent = (function(superClass) { - extend(StreamStartEvent, superClass); + class StreamStartEvent extends superClass { + constructor(start_mark, end_mark, encoding) { + super(start_mark, end_mark); + this.encoding = encoding; + } - function StreamStartEvent(start_mark, end_mark, encoding) { - this.start_mark = start_mark; - this.end_mark = end_mark; - this.encoding = encoding; - } + }; + + StreamStartEvent.__super__ = superClass.prototype; return StreamStartEvent; })(this.Event); this.StreamEndEvent = (function(superClass) { - extend(StreamEndEvent, superClass); + class StreamEndEvent extends superClass {}; - function StreamEndEvent() { - return StreamEndEvent.__super__.constructor.apply(this, arguments); - } + StreamEndEvent.__super__ = superClass.prototype; return StreamEndEvent; })(this.Event); this.DocumentStartEvent = (function(superClass) { - extend(DocumentStartEvent, superClass); - - function DocumentStartEvent(start_mark, end_mark, explicit, version, tags) { - this.start_mark = start_mark; - this.end_mark = end_mark; - this.explicit = explicit; - this.version = version; - this.tags = tags; - } + class DocumentStartEvent extends superClass { + constructor(start_mark, end_mark, explicit, version, tags) { + super(start_mark, end_mark); + this.explicit = explicit; + this.version = version; + this.tags = tags; + } + + }; + + DocumentStartEvent.__super__ = superClass.prototype; return DocumentStartEvent; })(this.Event); this.DocumentEndEvent = (function(superClass) { - extend(DocumentEndEvent, superClass); + class DocumentEndEvent extends superClass { + constructor(start_mark, end_mark, explicit) { + super(start_mark, end_mark); + this.explicit = explicit; + } - function DocumentEndEvent(start_mark, end_mark, explicit) { - this.start_mark = start_mark; - this.end_mark = end_mark; - this.explicit = explicit; - } + }; + + DocumentEndEvent.__super__ = superClass.prototype; return DocumentEndEvent; })(this.Event); this.AliasEvent = (function(superClass) { - extend(AliasEvent, superClass); + class AliasEvent extends superClass {}; - function AliasEvent() { - return AliasEvent.__super__.constructor.apply(this, arguments); - } + AliasEvent.__super__ = superClass.prototype; return AliasEvent; })(this.NodeEvent); this.ScalarEvent = (function(superClass) { - extend(ScalarEvent, superClass); - - function ScalarEvent(anchor, tag, implicit, value, start_mark, end_mark, style) { - this.anchor = anchor; - this.tag = tag; - this.implicit = implicit; - this.value = value; - this.start_mark = start_mark; - this.end_mark = end_mark; - this.style = style; - } + class ScalarEvent extends superClass { + constructor(anchor, tag, implicit, value, start_mark, end_mark, style) { + super(start_mark, end_mark); + this.anchor = anchor; + this.tag = tag; + this.implicit = implicit; + this.value = value; + this.style = style; + } + + }; + + ScalarEvent.__super__ = superClass.prototype; return ScalarEvent; })(this.NodeEvent); this.SequenceStartEvent = (function(superClass) { - extend(SequenceStartEvent, superClass); + class SequenceStartEvent extends superClass {}; - function SequenceStartEvent() { - return SequenceStartEvent.__super__.constructor.apply(this, arguments); - } + SequenceStartEvent.__super__ = superClass.prototype; return SequenceStartEvent; })(this.CollectionStartEvent); this.SequenceEndEvent = (function(superClass) { - extend(SequenceEndEvent, superClass); + class SequenceEndEvent extends superClass {}; - function SequenceEndEvent() { - return SequenceEndEvent.__super__.constructor.apply(this, arguments); - } + SequenceEndEvent.__super__ = superClass.prototype; return SequenceEndEvent; })(this.CollectionEndEvent); this.MappingStartEvent = (function(superClass) { - extend(MappingStartEvent, superClass); + class MappingStartEvent extends superClass {}; - function MappingStartEvent() { - return MappingStartEvent.__super__.constructor.apply(this, arguments); - } + MappingStartEvent.__super__ = superClass.prototype; return MappingStartEvent; })(this.CollectionStartEvent); this.MappingEndEvent = (function(superClass) { - extend(MappingEndEvent, superClass); + class MappingEndEvent extends superClass {}; - function MappingEndEvent() { - return MappingEndEvent.__super__.constructor.apply(this, arguments); - } + MappingEndEvent.__super__ = superClass.prototype; return MappingEndEvent; diff --git a/lib/loader.js b/lib/loader.js index ab5548e..4792a66 100644 --- a/lib/loader.js +++ b/lib/loader.js @@ -1,6 +1,5 @@ (function() { - var composer, constructor, parser, reader, resolver, scanner, util, - slice = [].slice; + var composer, constructor, parser, reader, resolver, scanner, util; util = require('./util'); @@ -16,31 +15,26 @@ constructor = require('./constructor'); - this.make_loader = function(Reader, Scanner, Parser, Composer, Resolver, Constructor) { + this.make_loader = function(Reader = reader.Reader, Scanner = scanner.Scanner, Parser = parser.Parser, Composer = composer.Composer, Resolver = resolver.Resolver, Constructor = constructor.Constructor) { var Loader, components; - if (Reader == null) { - Reader = reader.Reader; - } - if (Scanner == null) { - Scanner = scanner.Scanner; - } - if (Parser == null) { - Parser = parser.Parser; - } - if (Composer == null) { - Composer = composer.Composer; - } - if (Resolver == null) { - Resolver = resolver.Resolver; - } - if (Constructor == null) { - Constructor = constructor.Constructor; - } components = [Reader, Scanner, Parser, Composer, Resolver, Constructor]; return Loader = (function() { var component; - util.extend.apply(util, [Loader.prototype].concat(slice.call((function() { + class Loader { + constructor(stream) { + var i, len, ref; + components[0].prototype.initialise.call(this, stream); + ref = components.slice(1); + for (i = 0, len = ref.length; i < len; i++) { + component = ref[i]; + component.prototype.initialise.call(this); + } + } + + }; + + util.extend(Loader.prototype, ...(function() { var i, len, results; results = []; for (i = 0, len = components.length; i < len; i++) { @@ -48,17 +42,7 @@ results.push(component.prototype); } return results; - })()))); - - function Loader(stream) { - var i, len, ref; - components[0].call(this, stream); - ref = components.slice(1); - for (i = 0, len = ref.length; i < len; i++) { - component = ref[i]; - component.call(this); - } - } + })()); return Loader; diff --git a/lib/nodes.js b/lib/nodes.js index 2d4cfc2..f2250ef 100644 --- a/lib/nodes.js +++ b/lib/nodes.js @@ -1,63 +1,63 @@ (function() { - var unique_id, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty; + var unique_id; unique_id = 0; - this.Node = (function() { - function Node(tag, value, start_mark, end_mark) { + this.Node = class Node { + constructor(tag, value, start_mark, end_mark) { this.tag = tag; this.value = value; this.start_mark = start_mark; this.end_mark = end_mark; - this.unique_id = "node_" + (unique_id++); + this.unique_id = `node_${unique_id++}`; } - return Node; - - })(); + }; this.ScalarNode = (function(superClass) { - extend(ScalarNode, superClass); + class ScalarNode extends superClass { + constructor(tag, value, start_mark, end_mark, style) { + super(...arguments); + this.tag = tag; + this.value = value; + this.start_mark = start_mark; + this.end_mark = end_mark; + this.style = style; + } - ScalarNode.prototype.id = 'scalar'; + }; - function ScalarNode(tag, value, start_mark, end_mark, style) { - this.tag = tag; - this.value = value; - this.start_mark = start_mark; - this.end_mark = end_mark; - this.style = style; - ScalarNode.__super__.constructor.apply(this, arguments); - } + ScalarNode.__super__ = superClass.prototype; + + ScalarNode.prototype.id = 'scalar'; return ScalarNode; })(this.Node); this.CollectionNode = (function(superClass) { - extend(CollectionNode, superClass); + class CollectionNode extends superClass { + constructor(tag, value, start_mark, end_mark, flow_style) { + super(...arguments); + this.tag = tag; + this.value = value; + this.start_mark = start_mark; + this.end_mark = end_mark; + this.flow_style = flow_style; + } - function CollectionNode(tag, value, start_mark, end_mark, flow_style) { - this.tag = tag; - this.value = value; - this.start_mark = start_mark; - this.end_mark = end_mark; - this.flow_style = flow_style; - CollectionNode.__super__.constructor.apply(this, arguments); - } + }; + + CollectionNode.__super__ = superClass.prototype; return CollectionNode; })(this.Node); this.SequenceNode = (function(superClass) { - extend(SequenceNode, superClass); + class SequenceNode extends superClass {}; - function SequenceNode() { - return SequenceNode.__super__.constructor.apply(this, arguments); - } + SequenceNode.__super__ = superClass.prototype; SequenceNode.prototype.id = 'sequence'; @@ -66,11 +66,9 @@ })(this.CollectionNode); this.MappingNode = (function(superClass) { - extend(MappingNode, superClass); + class MappingNode extends superClass {}; - function MappingNode() { - return MappingNode.__super__.constructor.apply(this, arguments); - } + MappingNode.__super__ = superClass.prototype; MappingNode.prototype.id = 'mapping'; diff --git a/lib/parser.js b/lib/parser.js index 707af58..182212b 100644 --- a/lib/parser.js +++ b/lib/parser.js @@ -1,8 +1,6 @@ (function() { var MarkedYAMLError, events, tokens, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty, - slice = [].slice; + hasProp = {}.hasOwnProperty; events = require('./events'); @@ -11,596 +9,590 @@ tokens = require('./tokens'); this.ParserError = (function(superClass) { - extend(ParserError, superClass); + class ParserError extends superClass {}; - function ParserError() { - return ParserError.__super__.constructor.apply(this, arguments); - } + ParserError.__super__ = superClass.prototype; return ParserError; })(MarkedYAMLError); this.Parser = (function() { - var DEFAULT_TAGS; + var DEFAULT_TAGS, ctor; - DEFAULT_TAGS = { - '!': '!', - '!!': 'tag:yaml.org,2002:' - }; + class Parser { + constructor() { + return ctor.apply(this, arguments); + } - function Parser() { - this.current_event = null; - this.yaml_version = null; - this.tag_handles = {}; - this.states = []; - this.marks = []; - this.state = 'parse_stream_start'; - } + initialise() { + this.current_event = null; + this.yaml_version = null; + this.tag_handles = {}; + this.states = []; + this.marks = []; + return this.state = 'parse_stream_start'; + } - /* - Reset the state attributes. - */ + /* + Reset the state attributes. + */ - Parser.prototype.dispose = function() { - this.states = []; - return this.state = null; - }; + dispose() { + this.states = []; + return this.state = null; + } - /* - Check the type of the next event. - */ + /* + Check the type of the next event. + */ - Parser.prototype.check_event = function() { - var choice, choices, i, len; - choices = 1 <= arguments.length ? slice.call(arguments, 0) : []; - if (this.current_event === null) { - if (this.state != null) { - this.current_event = this[this.state](); - } - } - if (this.current_event !== null) { - if (choices.length === 0) { - return true; + check_event(...choices) { + var choice, i, len; + if (this.current_event === null) { + if (this.state != null) { + this.current_event = this[this.state](); + } } - for (i = 0, len = choices.length; i < len; i++) { - choice = choices[i]; - if (this.current_event instanceof choice) { + if (this.current_event !== null) { + if (choices.length === 0) { return true; } + for (i = 0, len = choices.length; i < len; i++) { + choice = choices[i]; + if (this.current_event instanceof choice) { + return true; + } + } } + return false; } - return false; - }; - /* - Get the next event. - */ + /* + Get the next event. + */ - Parser.prototype.peek_event = function() { - if (this.current_event === null && (this.state != null)) { - this.current_event = this[this.state](); + peek_event() { + if (this.current_event === null && (this.state != null)) { + this.current_event = this[this.state](); + } + return this.current_event; } - return this.current_event; - }; - /* - Get the event and proceed further. - */ + /* + Get the event and proceed further. + */ - Parser.prototype.get_event = function() { - var event; - if (this.current_event === null && (this.state != null)) { - this.current_event = this[this.state](); + get_event() { + var event; + if (this.current_event === null && (this.state != null)) { + this.current_event = this[this.state](); + } + event = this.current_event; + this.current_event = null; + return event; } - event = this.current_event; - this.current_event = null; - return event; - }; - /* - Parse the stream start. - */ + /* + Parse the stream start. + */ - Parser.prototype.parse_stream_start = function() { - var event, token; - token = this.get_token(); - event = new events.StreamStartEvent(token.start_mark, token.end_mark); - this.state = 'parse_implicit_document_start'; - return event; - }; + parse_stream_start() { + var event, token; + token = this.get_token(); + event = new events.StreamStartEvent(token.start_mark, token.end_mark); + this.state = 'parse_implicit_document_start'; + return event; + } - /* - Parse an implicit document. - */ + /* + Parse an implicit document. + */ - Parser.prototype.parse_implicit_document_start = function() { - var end_mark, event, start_mark, token; - if (!this.check_token(tokens.DirectiveToken, tokens.DocumentStartToken, tokens.StreamEndToken)) { - this.tag_handles = DEFAULT_TAGS; - token = this.peek_token(); - start_mark = end_mark = token.start_mark; - event = new events.DocumentStartEvent(start_mark, end_mark, false); - this.states.push('parse_document_end'); - this.state = 'parse_block_node'; - return event; - } else { - return this.parse_document_start(); + parse_implicit_document_start() { + var end_mark, event, start_mark, token; + if (!this.check_token(tokens.DirectiveToken, tokens.DocumentStartToken, tokens.StreamEndToken)) { + this.tag_handles = DEFAULT_TAGS; + token = this.peek_token(); + start_mark = end_mark = token.start_mark; + event = new events.DocumentStartEvent(start_mark, end_mark, false); + this.states.push('parse_document_end'); + this.state = 'parse_block_node'; + return event; + } else { + return this.parse_document_start(); + } } - }; - /* - Parse an explicit document. - */ + /* + Parse an explicit document. + */ - Parser.prototype.parse_document_start = function() { - var end_mark, event, ref, start_mark, tags, token, version; - while (this.check_token(tokens.DocumentEndToken)) { - this.get_token(); - } - if (!this.check_token(tokens.StreamEndToken)) { - start_mark = this.peek_token().start_mark; - ref = this.process_directives(), version = ref[0], tags = ref[1]; - if (!this.check_token(tokens.DocumentStartToken)) { - throw new exports.ParserError("expected '', but found " + (this.peek_token().id), this.peek_token().start_mark); - } - token = this.get_token(); - end_mark = token.end_mark; - event = new events.DocumentStartEvent(start_mark, end_mark, true, version, tags); - this.states.push('parse_document_end'); - this.state = 'parse_document_content'; - } else { - token = this.get_token(); - event = new events.StreamEndEvent(token.start_mark, token.end_mark); - if (this.states.length !== 0) { - throw new Error('assertion error, states should be empty'); + parse_document_start() { + var end_mark, event, ref, start_mark, tags, token, version; + while (this.check_token(tokens.DocumentEndToken)) { + this.get_token(); } - if (this.marks.length !== 0) { - throw new Error('assertion error, marks should be empty'); + if (!this.check_token(tokens.StreamEndToken)) { + start_mark = this.peek_token().start_mark; + ref = this.process_directives(), version = ref[0], tags = ref[1]; + if (!this.check_token(tokens.DocumentStartToken)) { + throw new exports.ParserError(`expected '', but found ${(this.peek_token().id)}`, this.peek_token().start_mark); + } + token = this.get_token(); + end_mark = token.end_mark; + event = new events.DocumentStartEvent(start_mark, end_mark, true, version, tags); + this.states.push('parse_document_end'); + this.state = 'parse_document_content'; + } else { + token = this.get_token(); + event = new events.StreamEndEvent(token.start_mark, token.end_mark); + if (this.states.length !== 0) { + throw new Error('assertion error, states should be empty'); + } + if (this.marks.length !== 0) { + throw new Error('assertion error, marks should be empty'); + } + this.state = null; } - this.state = null; + return event; } - return event; - }; - /* - Parse the document end. - */ + /* + Parse the document end. + */ - Parser.prototype.parse_document_end = function() { - var end_mark, event, explicit, start_mark, token; - token = this.peek_token(); - start_mark = end_mark = token.start_mark; - explicit = false; - if (this.check_token(tokens.DocumentEndToken)) { - token = this.get_token(); - end_mark = token.end_mark; - explicit = true; + parse_document_end() { + var end_mark, event, explicit, start_mark, token; + token = this.peek_token(); + start_mark = end_mark = token.start_mark; + explicit = false; + if (this.check_token(tokens.DocumentEndToken)) { + token = this.get_token(); + end_mark = token.end_mark; + explicit = true; + } + event = new events.DocumentEndEvent(start_mark, end_mark, explicit); + this.state = 'parse_document_start'; + return event; } - event = new events.DocumentEndEvent(start_mark, end_mark, explicit); - this.state = 'parse_document_start'; - return event; - }; - Parser.prototype.parse_document_content = function() { - var event; - if (this.check_token(tokens.DirectiveToken, tokens.DocumentStartToken, tokens.DocumentEndToken, tokens.StreamEndToken)) { - event = this.process_empty_scalar(this.peek_token().start_mark); - this.state = this.states.pop(); - return event; - } else { - return this.parse_block_node(); + parse_document_content() { + var event; + if (this.check_token(tokens.DirectiveToken, tokens.DocumentStartToken, tokens.DocumentEndToken, tokens.StreamEndToken)) { + event = this.process_empty_scalar(this.peek_token().start_mark); + this.state = this.states.pop(); + return event; + } else { + return this.parse_block_node(); + } } - }; - Parser.prototype.process_directives = function() { - var handle, major, minor, prefix, ref, ref1, ref2, tag_handles_copy, token, value; - this.yaml_version = null; - this.tag_handles = {}; - while (this.check_token(tokens.DirectiveToken)) { - token = this.get_token(); - if (token.name === 'YAML') { - if (this.yaml_version !== null) { - throw new exports.ParserError(null, null, 'found duplicate YAML directive', token.start_mark); - } - ref = token.value, major = ref[0], minor = ref[1]; - if (major !== 1) { - throw new exports.ParserError(null, null, 'found incompatible YAML document (version 1.* is required)', token.start_mark); - } - this.yaml_version = token.value; - } else if (token.name === 'TAG') { - ref1 = token.value, handle = ref1[0], prefix = ref1[1]; - if (handle in this.tag_handles) { - throw new exports.ParserError(null, null, "duplicate tag handle " + handle, token.start_mark); + process_directives() { + var handle, major, minor, prefix, ref, ref1, ref2, tag_handles_copy, token, value; + this.yaml_version = null; + this.tag_handles = {}; + while (this.check_token(tokens.DirectiveToken)) { + token = this.get_token(); + if (token.name === 'YAML') { + if (this.yaml_version !== null) { + throw new exports.ParserError(null, null, 'found duplicate YAML directive', token.start_mark); + } + ref = token.value, major = ref[0], minor = ref[1]; + if (major !== 1) { + throw new exports.ParserError(null, null, 'found incompatible YAML document (version 1.* is required)', token.start_mark); + } + this.yaml_version = token.value; + } else if (token.name === 'TAG') { + ref1 = token.value, handle = ref1[0], prefix = ref1[1]; + if (handle in this.tag_handles) { + throw new exports.ParserError(null, null, `duplicate tag handle ${handle}`, token.start_mark); + } + this.tag_handles[handle] = prefix; } - this.tag_handles[handle] = prefix; } - } - tag_handles_copy = null; - ref2 = this.tag_handles; - for (handle in ref2) { - if (!hasProp.call(ref2, handle)) continue; - prefix = ref2[handle]; - if (tag_handles_copy == null) { - tag_handles_copy = {}; + tag_handles_copy = null; + ref2 = this.tag_handles; + for (handle in ref2) { + if (!hasProp.call(ref2, handle)) continue; + prefix = ref2[handle]; + if (tag_handles_copy == null) { + tag_handles_copy = {}; + } + tag_handles_copy[handle] = prefix; } - tag_handles_copy[handle] = prefix; - } - value = [this.yaml_version, tag_handles_copy]; - for (handle in DEFAULT_TAGS) { - if (!hasProp.call(DEFAULT_TAGS, handle)) continue; - prefix = DEFAULT_TAGS[handle]; - if (!(prefix in this.tag_handles)) { - this.tag_handles[handle] = prefix; + value = [this.yaml_version, tag_handles_copy]; + for (handle in DEFAULT_TAGS) { + if (!hasProp.call(DEFAULT_TAGS, handle)) continue; + prefix = DEFAULT_TAGS[handle]; + if (!(prefix in this.tag_handles)) { + this.tag_handles[handle] = prefix; + } } + return value; } - return value; - }; - - Parser.prototype.parse_block_node = function() { - return this.parse_node(true); - }; - Parser.prototype.parse_flow_node = function() { - return this.parse_node(); - }; - - Parser.prototype.parse_block_node_or_indentless_sequence = function() { - return this.parse_node(true, true); - }; + parse_block_node() { + return this.parse_node(true); + } - Parser.prototype.parse_node = function(block, indentless_sequence) { - var anchor, end_mark, event, handle, implicit, node, start_mark, suffix, tag, tag_mark, token; - if (block == null) { - block = false; + parse_flow_node() { + return this.parse_node(); } - if (indentless_sequence == null) { - indentless_sequence = false; + + parse_block_node_or_indentless_sequence() { + return this.parse_node(true, true); } - if (this.check_token(tokens.AliasToken)) { - token = this.get_token(); - event = new events.AliasEvent(token.value, token.start_mark, token.end_mark); - this.state = this.states.pop(); - } else { - anchor = null; - tag = null; - start_mark = end_mark = tag_mark = null; - if (this.check_token(tokens.AnchorToken)) { - token = this.get_token(); - start_mark = token.start_mark; - end_mark = token.end_mark; - anchor = token.value; - if (this.check_token(tokens.TagToken)) { - token = this.get_token(); - tag_mark = token.start_mark; - end_mark = token.end_mark; - tag = token.value; - } - } else if (this.check_token(tokens.TagToken)) { + + parse_node(block = false, indentless_sequence = false) { + var anchor, end_mark, event, handle, implicit, node, start_mark, suffix, tag, tag_mark, token; + if (this.check_token(tokens.AliasToken)) { token = this.get_token(); - start_mark = tag_mark = token.start_mark; - end_mark = token.end_mark; - tag = token.value; + event = new events.AliasEvent(token.value, token.start_mark, token.end_mark); + this.state = this.states.pop(); + } else { + anchor = null; + tag = null; + start_mark = end_mark = tag_mark = null; if (this.check_token(tokens.AnchorToken)) { token = this.get_token(); + start_mark = token.start_mark; end_mark = token.end_mark; anchor = token.value; - } - } - if (tag !== null) { - handle = tag[0], suffix = tag[1]; - if (handle !== null) { - if (!(handle in this.tag_handles)) { - throw new exports.ParserError('while parsing a node', start_mark, "found undefined tag handle " + handle, tag_mark); + if (this.check_token(tokens.TagToken)) { + token = this.get_token(); + tag_mark = token.start_mark; + end_mark = token.end_mark; + tag = token.value; } - tag = this.tag_handles[handle] + suffix; - } else { - tag = suffix; - } - } - if (start_mark === null) { - start_mark = end_mark = this.peek_token().start_mark; - } - event = null; - implicit = tag === null || tag === '!'; - if (indentless_sequence && this.check_token(tokens.BlockEntryToken)) { - end_mark = this.peek_token().end_mark; - event = new events.SequenceStartEvent(anchor, tag, implicit, start_mark, end_mark); - this.state = 'parse_indentless_sequence_entry'; - } else { - if (this.check_token(tokens.ScalarToken)) { + } else if (this.check_token(tokens.TagToken)) { token = this.get_token(); + start_mark = tag_mark = token.start_mark; end_mark = token.end_mark; - if ((token.plain && tag === null) || tag === '!') { - implicit = [true, false]; - } else if (tag === null) { - implicit = [false, true]; + tag = token.value; + if (this.check_token(tokens.AnchorToken)) { + token = this.get_token(); + end_mark = token.end_mark; + anchor = token.value; + } + } + if (tag !== null) { + handle = tag[0], suffix = tag[1]; + if (handle !== null) { + if (!(handle in this.tag_handles)) { + throw new exports.ParserError('while parsing a node', start_mark, `found undefined tag handle ${handle}`, tag_mark); + } + tag = this.tag_handles[handle] + suffix; } else { - implicit = [false, false]; + tag = suffix; } - event = new events.ScalarEvent(anchor, tag, implicit, token.value, start_mark, end_mark, token.style); - this.state = this.states.pop(); - } else if (this.check_token(tokens.FlowSequenceStartToken)) { - end_mark = this.peek_token().end_mark; - event = new events.SequenceStartEvent(anchor, tag, implicit, start_mark, end_mark, true); - this.state = 'parse_flow_sequence_first_entry'; - } else if (this.check_token(tokens.FlowMappingStartToken)) { - end_mark = this.peek_token().end_mark; - event = new events.MappingStartEvent(anchor, tag, implicit, start_mark, end_mark, true); - this.state = 'parse_flow_mapping_first_key'; - } else if (block && this.check_token(tokens.BlockSequenceStartToken)) { - end_mark = this.peek_token().end_mark; - event = new events.SequenceStartEvent(anchor, tag, implicit, start_mark, end_mark, false); - this.state = 'parse_block_sequence_first_entry'; - } else if (block && this.check_token(tokens.BlockMappingStartToken)) { + } + if (start_mark === null) { + start_mark = end_mark = this.peek_token().start_mark; + } + event = null; + implicit = tag === null || tag === '!'; + if (indentless_sequence && this.check_token(tokens.BlockEntryToken)) { end_mark = this.peek_token().end_mark; - event = new events.MappingStartEvent(anchor, tag, implicit, start_mark, end_mark, false); - this.state = 'parse_block_mapping_first_key'; - } else if (anchor !== null || tag !== null) { - event = new events.ScalarEvent(anchor, tag, [implicit, false], '', start_mark, end_mark); - this.state = this.states.pop(); + event = new events.SequenceStartEvent(anchor, tag, implicit, start_mark, end_mark); + this.state = 'parse_indentless_sequence_entry'; } else { - if (block) { - node = 'block'; + if (this.check_token(tokens.ScalarToken)) { + token = this.get_token(); + end_mark = token.end_mark; + if ((token.plain && tag === null) || tag === '!') { + implicit = [true, false]; + } else if (tag === null) { + implicit = [false, true]; + } else { + implicit = [false, false]; + } + event = new events.ScalarEvent(anchor, tag, implicit, token.value, start_mark, end_mark, token.style); + this.state = this.states.pop(); + } else if (this.check_token(tokens.FlowSequenceStartToken)) { + end_mark = this.peek_token().end_mark; + event = new events.SequenceStartEvent(anchor, tag, implicit, start_mark, end_mark, true); + this.state = 'parse_flow_sequence_first_entry'; + } else if (this.check_token(tokens.FlowMappingStartToken)) { + end_mark = this.peek_token().end_mark; + event = new events.MappingStartEvent(anchor, tag, implicit, start_mark, end_mark, true); + this.state = 'parse_flow_mapping_first_key'; + } else if (block && this.check_token(tokens.BlockSequenceStartToken)) { + end_mark = this.peek_token().end_mark; + event = new events.SequenceStartEvent(anchor, tag, implicit, start_mark, end_mark, false); + this.state = 'parse_block_sequence_first_entry'; + } else if (block && this.check_token(tokens.BlockMappingStartToken)) { + end_mark = this.peek_token().end_mark; + event = new events.MappingStartEvent(anchor, tag, implicit, start_mark, end_mark, false); + this.state = 'parse_block_mapping_first_key'; + } else if (anchor !== null || tag !== null) { + event = new events.ScalarEvent(anchor, tag, [implicit, false], '', start_mark, end_mark); + this.state = this.states.pop(); } else { - node = 'flow'; + if (block) { + node = 'block'; + } else { + node = 'flow'; + } + token = this.peek_token(); + throw new exports.ParserError(`while parsing a ${node} node`, start_mark, `expected the node content, but found ${token.id}`, token.start_mark); } - token = this.peek_token(); - throw new exports.ParserError("while parsing a " + node + " node", start_mark, "expected the node content, but found " + token.id, token.start_mark); } } + return event; } - return event; - }; - Parser.prototype.parse_block_sequence_first_entry = function() { - var token; - token = this.get_token(); - this.marks.push(token.start_mark); - return this.parse_block_sequence_entry(); - }; - - Parser.prototype.parse_block_sequence_entry = function() { - var event, token; - if (this.check_token(tokens.BlockEntryToken)) { + parse_block_sequence_first_entry() { + var token; token = this.get_token(); - if (!this.check_token(tokens.BlockEntryToken, tokens.BlockEndToken)) { - this.states.push('parse_block_sequence_entry'); - return this.parse_block_node(); - } else { - this.state = 'parse_block_sequence_entry'; - return this.process_empty_scalar(token.end_mark); + this.marks.push(token.start_mark); + return this.parse_block_sequence_entry(); + } + + parse_block_sequence_entry() { + var event, token; + if (this.check_token(tokens.BlockEntryToken)) { + token = this.get_token(); + if (!this.check_token(tokens.BlockEntryToken, tokens.BlockEndToken)) { + this.states.push('parse_block_sequence_entry'); + return this.parse_block_node(); + } else { + this.state = 'parse_block_sequence_entry'; + return this.process_empty_scalar(token.end_mark); + } } + if (!this.check_token(tokens.BlockEndToken)) { + token = this.peek_token(); + throw new exports.ParserError('while parsing a block collection', this.marks.slice(-1)[0], `expected , but found ${token.id}`, token.start_mark); + } + token = this.get_token(); + event = new events.SequenceEndEvent(token.start_mark, token.end_mark); + this.state = this.states.pop(); + this.marks.pop(); + return event; } - if (!this.check_token(tokens.BlockEndToken)) { + + parse_indentless_sequence_entry() { + var event, token; + if (this.check_token(tokens.BlockEntryToken)) { + token = this.get_token(); + if (!this.check_token(tokens.BlockEntryToken, tokens.KeyToken, tokens.ValueToken, tokens.BlockEndToken)) { + this.states.push('parse_indentless_sequence_entry'); + return this.parse_block_node(); + } else { + this.state = 'parse_indentless_sequence_entry'; + return this.process_empty_scalar(token.end_mark); + } + } token = this.peek_token(); - throw new exports.ParserError('while parsing a block collection', this.marks.slice(-1)[0], "expected , but found " + token.id, token.start_mark); + event = new events.SequenceEndEvent(token.start_mark, token.start_mark); + this.state = this.states.pop(); + return event; } - token = this.get_token(); - event = new events.SequenceEndEvent(token.start_mark, token.end_mark); - this.state = this.states.pop(); - this.marks.pop(); - return event; - }; - Parser.prototype.parse_indentless_sequence_entry = function() { - var event, token; - if (this.check_token(tokens.BlockEntryToken)) { + parse_block_mapping_first_key() { + var token; token = this.get_token(); - if (!this.check_token(tokens.BlockEntryToken, tokens.KeyToken, tokens.ValueToken, tokens.BlockEndToken)) { - this.states.push('parse_indentless_sequence_entry'); - return this.parse_block_node(); - } else { - this.state = 'parse_indentless_sequence_entry'; - return this.process_empty_scalar(token.end_mark); - } + this.marks.push(token.start_mark); + return this.parse_block_mapping_key(); } - token = this.peek_token(); - event = new events.SequenceEndEvent(token.start_mark, token.start_mark); - this.state = this.states.pop(); - return event; - }; - Parser.prototype.parse_block_mapping_first_key = function() { - var token; - token = this.get_token(); - this.marks.push(token.start_mark); - return this.parse_block_mapping_key(); - }; - - Parser.prototype.parse_block_mapping_key = function() { - var event, token; - if (this.check_token(tokens.KeyToken)) { - token = this.get_token(); - if (!this.check_token(tokens.KeyToken, tokens.ValueToken, tokens.BlockEndToken)) { - this.states.push('parse_block_mapping_value'); - return this.parse_block_node_or_indentless_sequence(); - } else { - this.state = 'parse_block_mapping_value'; - return this.process_empty_scalar(token.end_mark); + parse_block_mapping_key() { + var event, token; + if (this.check_token(tokens.KeyToken)) { + token = this.get_token(); + if (!this.check_token(tokens.KeyToken, tokens.ValueToken, tokens.BlockEndToken)) { + this.states.push('parse_block_mapping_value'); + return this.parse_block_node_or_indentless_sequence(); + } else { + this.state = 'parse_block_mapping_value'; + return this.process_empty_scalar(token.end_mark); + } } + if (!this.check_token(tokens.BlockEndToken)) { + token = this.peek_token(); + throw new exports.ParserError('while parsing a block mapping', this.marks.slice(-1)[0], `expected , but found ${token.id}`, token.start_mark); + } + token = this.get_token(); + event = new events.MappingEndEvent(token.start_mark, token.end_mark); + this.state = this.states.pop(); + this.marks.pop(); + return event; } - if (!this.check_token(tokens.BlockEndToken)) { - token = this.peek_token(); - throw new exports.ParserError('while parsing a block mapping', this.marks.slice(-1)[0], "expected , but found " + token.id, token.start_mark); - } - token = this.get_token(); - event = new events.MappingEndEvent(token.start_mark, token.end_mark); - this.state = this.states.pop(); - this.marks.pop(); - return event; - }; - Parser.prototype.parse_block_mapping_value = function() { - var token; - if (this.check_token(tokens.ValueToken)) { - token = this.get_token(); - if (!this.check_token(tokens.KeyToken, tokens.ValueToken, tokens.BlockEndToken)) { - this.states.push('parse_block_mapping_key'); - return this.parse_block_node_or_indentless_sequence(); + parse_block_mapping_value() { + var token; + if (this.check_token(tokens.ValueToken)) { + token = this.get_token(); + if (!this.check_token(tokens.KeyToken, tokens.ValueToken, tokens.BlockEndToken)) { + this.states.push('parse_block_mapping_key'); + return this.parse_block_node_or_indentless_sequence(); + } else { + this.state = 'parse_block_mapping_key'; + return this.process_empty_scalar(token.end_mark); + } } else { this.state = 'parse_block_mapping_key'; - return this.process_empty_scalar(token.end_mark); + token = this.peek_token(); + return this.process_empty_scalar(token.start_mark); } - } else { - this.state = 'parse_block_mapping_key'; - token = this.peek_token(); - return this.process_empty_scalar(token.start_mark); } - }; - - Parser.prototype.parse_flow_sequence_first_entry = function() { - var token; - token = this.get_token(); - this.marks.push(token.start_mark); - return this.parse_flow_sequence_entry(true); - }; - Parser.prototype.parse_flow_sequence_entry = function(first) { - var event, token; - if (first == null) { - first = false; + parse_flow_sequence_first_entry() { + var token; + token = this.get_token(); + this.marks.push(token.start_mark); + return this.parse_flow_sequence_entry(true); } - if (!this.check_token(tokens.FlowSequenceEndToken)) { - if (!first) { - if (this.check_token(tokens.FlowEntryToken)) { - this.get_token(); - } else { + + parse_flow_sequence_entry(first = false) { + var event, token; + if (!this.check_token(tokens.FlowSequenceEndToken)) { + if (!first) { + if (this.check_token(tokens.FlowEntryToken)) { + this.get_token(); + } else { + token = this.peek_token(); + throw new exports.ParserError('while parsing a flow sequence', this.marks.slice(-1)[0], `expected ',' or ']', but got ${token.id}`, token.start_mark); + } + } + if (this.check_token(tokens.KeyToken)) { token = this.peek_token(); - throw new exports.ParserError('while parsing a flow sequence', this.marks.slice(-1)[0], "expected ',' or ']', but got " + token.id, token.start_mark); + event = new events.MappingStartEvent(null, null, true, token.start_mark, token.end_mark, true); + this.state = 'parse_flow_sequence_entry_mapping_key'; + return event; + } else if (!this.check_token(tokens.FlowSequenceEndToken)) { + this.states.push('parse_flow_sequence_entry'); + return this.parse_flow_node(); } } - if (this.check_token(tokens.KeyToken)) { - token = this.peek_token(); - event = new events.MappingStartEvent(null, null, true, token.start_mark, token.end_mark, true); - this.state = 'parse_flow_sequence_entry_mapping_key'; - return event; - } else if (!this.check_token(tokens.FlowSequenceEndToken)) { - this.states.push('parse_flow_sequence_entry'); - return this.parse_flow_node(); - } - } - token = this.get_token(); - event = new events.SequenceEndEvent(token.start_mark, token.end_mark); - this.state = this.states.pop(); - this.marks.pop(); - return event; - }; - - Parser.prototype.parse_flow_sequence_entry_mapping_key = function() { - var token; - token = this.get_token(); - if (!this.check_token(tokens.ValueToken, tokens.FlowEntryToken, tokens.FlowSequenceEndToken)) { - this.states.push('parse_flow_sequence_entry_mapping_value'); - return this.parse_flow_node(); - } else { - this.state = 'parse_flow_sequence_entry_mapping_value'; - return this.process_empty_scalar(token.end_mark); + token = this.get_token(); + event = new events.SequenceEndEvent(token.start_mark, token.end_mark); + this.state = this.states.pop(); + this.marks.pop(); + return event; } - }; - Parser.prototype.parse_flow_sequence_entry_mapping_value = function() { - var token; - if (this.check_token(tokens.ValueToken)) { + parse_flow_sequence_entry_mapping_key() { + var token; token = this.get_token(); - if (!this.check_token(tokens.FlowEntryToken, tokens.FlowSequenceEndToken)) { - this.states.push('parse_flow_sequence_entry_mapping_end'); + if (!this.check_token(tokens.ValueToken, tokens.FlowEntryToken, tokens.FlowSequenceEndToken)) { + this.states.push('parse_flow_sequence_entry_mapping_value'); return this.parse_flow_node(); } else { - this.state = 'parse_flow_sequence_entry_mapping_end'; + this.state = 'parse_flow_sequence_entry_mapping_value'; return this.process_empty_scalar(token.end_mark); } - } else { - this.state = 'parse_flow_sequence_entry_mapping_end'; - token = this.peek_token(); - return this.process_empty_scalar(token.start_mark); } - }; - Parser.prototype.parse_flow_sequence_entry_mapping_end = function() { - var token; - this.state = 'parse_flow_sequence_entry'; - token = this.peek_token(); - return new events.MappingEndEvent(token.start_mark, token.start_mark); - }; + parse_flow_sequence_entry_mapping_value() { + var token; + if (this.check_token(tokens.ValueToken)) { + token = this.get_token(); + if (!this.check_token(tokens.FlowEntryToken, tokens.FlowSequenceEndToken)) { + this.states.push('parse_flow_sequence_entry_mapping_end'); + return this.parse_flow_node(); + } else { + this.state = 'parse_flow_sequence_entry_mapping_end'; + return this.process_empty_scalar(token.end_mark); + } + } else { + this.state = 'parse_flow_sequence_entry_mapping_end'; + token = this.peek_token(); + return this.process_empty_scalar(token.start_mark); + } + } - Parser.prototype.parse_flow_mapping_first_key = function() { - var token; - token = this.get_token(); - this.marks.push(token.start_mark); - return this.parse_flow_mapping_key(true); - }; + parse_flow_sequence_entry_mapping_end() { + var token; + this.state = 'parse_flow_sequence_entry'; + token = this.peek_token(); + return new events.MappingEndEvent(token.start_mark, token.start_mark); + } - Parser.prototype.parse_flow_mapping_key = function(first) { - var event, token; - if (first == null) { - first = false; + parse_flow_mapping_first_key() { + var token; + token = this.get_token(); + this.marks.push(token.start_mark); + return this.parse_flow_mapping_key(true); } - if (!this.check_token(tokens.FlowMappingEndToken)) { - if (!first) { - if (this.check_token(tokens.FlowEntryToken)) { - this.get_token(); - } else { - token = this.peek_token(); - throw new exports.ParserError('while parsing a flow mapping', this.marks.slice(-1)[0], "expected ',' or '}', but got " + token.id, token.start_mark); + + parse_flow_mapping_key(first = false) { + var event, token; + if (!this.check_token(tokens.FlowMappingEndToken)) { + if (!first) { + if (this.check_token(tokens.FlowEntryToken)) { + this.get_token(); + } else { + token = this.peek_token(); + throw new exports.ParserError('while parsing a flow mapping', this.marks.slice(-1)[0], `expected ',' or '}', but got ${token.id}`, token.start_mark); + } + } + if (this.check_token(tokens.KeyToken)) { + token = this.get_token(); + if (!this.check_token(tokens.ValueToken, tokens.FlowEntryToken, tokens.FlowMappingEndToken)) { + this.states.push('parse_flow_mapping_value'); + return this.parse_flow_node(); + } else { + this.state = 'parse_flow_mapping_value'; + return this.process_empty_scalar(token.end_mark); + } + } else if (!this.check_token(tokens.FlowMappingEndToken)) { + this.states.push('parse_flow_mapping_empty_value'); + return this.parse_flow_node(); } } - if (this.check_token(tokens.KeyToken)) { + token = this.get_token(); + event = new events.MappingEndEvent(token.start_mark, token.end_mark); + this.state = this.states.pop(); + this.marks.pop(); + return event; + } + + parse_flow_mapping_value() { + var token; + if (this.check_token(tokens.ValueToken)) { token = this.get_token(); - if (!this.check_token(tokens.ValueToken, tokens.FlowEntryToken, tokens.FlowMappingEndToken)) { - this.states.push('parse_flow_mapping_value'); + if (!this.check_token(tokens.FlowEntryToken, tokens.FlowMappingEndToken)) { + this.states.push('parse_flow_mapping_key'); return this.parse_flow_node(); } else { - this.state = 'parse_flow_mapping_value'; + this.state = 'parse_flow_mapping_key'; return this.process_empty_scalar(token.end_mark); } - } else if (!this.check_token(tokens.FlowMappingEndToken)) { - this.states.push('parse_flow_mapping_empty_value'); - return this.parse_flow_node(); - } - } - token = this.get_token(); - event = new events.MappingEndEvent(token.start_mark, token.end_mark); - this.state = this.states.pop(); - this.marks.pop(); - return event; - }; - - Parser.prototype.parse_flow_mapping_value = function() { - var token; - if (this.check_token(tokens.ValueToken)) { - token = this.get_token(); - if (!this.check_token(tokens.FlowEntryToken, tokens.FlowMappingEndToken)) { - this.states.push('parse_flow_mapping_key'); - return this.parse_flow_node(); } else { this.state = 'parse_flow_mapping_key'; - return this.process_empty_scalar(token.end_mark); + token = this.peek_token(); + return this.process_empty_scalar(token.start_mark); } - } else { + } + + parse_flow_mapping_empty_value() { this.state = 'parse_flow_mapping_key'; - token = this.peek_token(); - return this.process_empty_scalar(token.start_mark); + return this.process_empty_scalar(this.peek_token().start_mark); + } + + process_empty_scalar(mark) { + return new events.ScalarEvent(null, null, [true, false], '', mark, mark); } - }; - Parser.prototype.parse_flow_mapping_empty_value = function() { - this.state = 'parse_flow_mapping_key'; - return this.process_empty_scalar(this.peek_token().start_mark); }; - Parser.prototype.process_empty_scalar = function(mark) { - return new events.ScalarEvent(null, null, [true, false], '', mark, mark); + DEFAULT_TAGS = { + '!': '!', + '!!': 'tag:yaml.org,2002:' }; + ctor = Parser.prototype.initialise; + return Parser; })(); diff --git a/lib/reader.js b/lib/reader.js index a5d1734..f8f3d3e 100644 --- a/lib/reader.js +++ b/lib/reader.js @@ -1,25 +1,26 @@ (function() { var Mark, YAMLError, ref, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty, indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; ref = require('./errors'), Mark = ref.Mark, YAMLError = ref.YAMLError; this.ReaderError = (function(superClass) { - extend(ReaderError, superClass); + class ReaderError extends superClass { + constructor(position1, character1, reason) { + super(); + this.position = position1; + this.character = character1; + this.reason = reason; + } - function ReaderError(position1, character1, reason) { - this.position = position1; - this.character = character1; - this.reason = reason; - ReaderError.__super__.constructor.call(this); - } + toString() { + return `unacceptable character ${this.character.charCodeAt()}: ${this.reason}\n position ${this.position}`; + } - ReaderError.prototype.toString = function() { - return "unacceptable character " + (this.character.charCodeAt()) + ": " + this.reason + "\n position " + this.position; }; + ReaderError.__super__ = superClass.prototype; + return ReaderError; })(YAMLError); @@ -32,67 +33,67 @@ */ this.Reader = (function() { - var NON_PRINTABLE; + var NON_PRINTABLE, ctor; - NON_PRINTABLE = /[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD]/; + class Reader { + constructor() { + return ctor.apply(this, arguments); + } - function Reader(string) { - this.string = string; - this.line = 0; - this.column = 0; - this.index = 0; - this.check_printable(); - this.string += '\x00'; - } - - Reader.prototype.peek = function(index) { - if (index == null) { - index = 0; + initialise(string) { + this.string = string; + this.line = 0; + this.column = 0; + this.index = 0; + this.check_printable(); + return this.string += '\x00'; } - return this.string[this.index + index]; - }; - Reader.prototype.prefix = function(length) { - if (length == null) { - length = 1; + peek(index = 0) { + return this.string[this.index + index]; } - return this.string.slice(this.index, this.index + length); - }; - Reader.prototype.forward = function(length) { - var char, results; - if (length == null) { - length = 1; + prefix(length = 1) { + return this.string.slice(this.index, this.index + length); } - results = []; - while (length) { - char = this.string[this.index]; - this.index++; - if (indexOf.call('\n\x85\u2082\u2029', char) >= 0 || (char === '\r' && this.string[this.index] !== '\n')) { - this.line++; - this.column = 0; - } else { - this.column++; + + forward(length = 1) { + var char, results; + results = []; + while (length) { + char = this.string[this.index]; + this.index++; + if (indexOf.call('\n\x85\u2082\u2029', char) >= 0 || (char === '\r' && this.string[this.index] !== '\n')) { + this.line++; + this.column = 0; + } else { + this.column++; + } + results.push(length--); } - results.push(length--); + return results; } - return results; - }; - Reader.prototype.get_mark = function() { - return new Mark(this.line, this.column, this.string, this.index); - }; + get_mark() { + return new Mark(this.line, this.column, this.string, this.index); + } - Reader.prototype.check_printable = function() { - var character, match, position; - match = NON_PRINTABLE.exec(this.string); - if (match) { - character = match[0]; - position = (this.string.length - this.index) + match.index; - throw new exports.ReaderError(position, character.charCodeAt(), 'special characters are not allowed'); + check_printable() { + var character, match, position; + match = NON_PRINTABLE.exec(this.string); + if (match) { + character = match[0]; + position = (this.string.length - this.index) + match.index; + throw new exports.ReaderError(position, character.charCodeAt(), 'special characters are not allowed'); + } } + }; + NON_PRINTABLE = /[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD]/; + + ctor = Reader.prototype.initialise; + return Reader; })(); diff --git a/lib/representer.js b/lib/representer.js index 104a63a..e5d4abe 100644 --- a/lib/representer.js +++ b/lib/representer.js @@ -1,6 +1,5 @@ (function() { var YAMLError, nodes, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; nodes = require('./nodes'); @@ -8,231 +7,238 @@ YAMLError = require('./errors').YAMLError; this.RepresenterError = (function(superClass) { - extend(RepresenterError, superClass); + class RepresenterError extends superClass {}; - function RepresenterError() { - return RepresenterError.__super__.constructor.apply(this, arguments); - } + RepresenterError.__super__ = superClass.prototype; return RepresenterError; })(YAMLError); this.BaseRepresenter = (function() { - BaseRepresenter.prototype.yaml_representers_types = []; - - BaseRepresenter.prototype.yaml_representers_handlers = []; - - BaseRepresenter.prototype.yaml_multi_representers_types = []; + var ctor; - BaseRepresenter.prototype.yaml_multi_representers_handlers = []; - - BaseRepresenter.add_representer = function(data_type, handler) { - if (!this.prototype.hasOwnProperty('yaml_representers_types')) { - this.prototype.yaml_representers_types = [].concat(this.prototype.yaml_representers_types); - } - if (!this.prototype.hasOwnProperty('yaml_representers_handlers')) { - this.prototype.yaml_representers_handlers = [].concat(this.prototype.yaml_representers_handlers); + class BaseRepresenter { + constructor() { + return ctor.apply(this, arguments); } - this.prototype.yaml_representers_types.push(data_type); - return this.prototype.yaml_representers_handlers.push(handler); - }; - BaseRepresenter.add_multi_representer = function(data_type, handler) { - if (!this.prototype.hasOwnProperty('yaml_multi_representers_types')) { - this.prototype.yaml_multi_representers_types = [].concat(this.prototype.yaml_multi_representers_types); - } - if (!this.prototype.hasOwnProperty('yaml_multi_representers_handlers')) { - this.prototype.yaml_multi_representers_handlers = [].concat(this.prototype.yaml_multi_representers_handlers); + static add_representer(data_type, handler) { + if (!this.prototype.hasOwnProperty('yaml_representers_types')) { + this.prototype.yaml_representers_types = [].concat(this.prototype.yaml_representers_types); + } + if (!this.prototype.hasOwnProperty('yaml_representers_handlers')) { + this.prototype.yaml_representers_handlers = [].concat(this.prototype.yaml_representers_handlers); + } + this.prototype.yaml_representers_types.push(data_type); + return this.prototype.yaml_representers_handlers.push(handler); } - this.prototype.yaml_multi_representers_types.push(data_type); - return this.prototype.yaml_multi_representers_handlers.push(handler); - }; - - function BaseRepresenter(arg) { - var ref; - ref = arg != null ? arg : {}, this.default_style = ref.default_style, this.default_flow_style = ref.default_flow_style; - this.represented_objects = {}; - this.object_keeper = []; - this.alias_key = null; - } - - BaseRepresenter.prototype.represent = function(data) { - var node; - node = this.represent_data(data); - this.serialize(node); - this.represented_objects = {}; - this.object_keeper = []; - return this.alias_key = null; - }; - BaseRepresenter.prototype.represent_data = function(data) { - var data_type, i, j, len, ref, representer, type; - if (this.ignore_aliases(data)) { - this.alias_key = null; - } else if ((i = this.object_keeper.indexOf(data)) !== -1) { - this.alias_key = i; - if (this.alias_key in this.represented_objects) { - return this.represented_objects[this.alias_key]; + static add_multi_representer(data_type, handler) { + if (!this.prototype.hasOwnProperty('yaml_multi_representers_types')) { + this.prototype.yaml_multi_representers_types = [].concat(this.prototype.yaml_multi_representers_types); } - } else { - this.alias_key = this.object_keeper.length; - this.object_keeper.push(data); + if (!this.prototype.hasOwnProperty('yaml_multi_representers_handlers')) { + this.prototype.yaml_multi_representers_handlers = [].concat(this.prototype.yaml_multi_representers_handlers); + } + this.prototype.yaml_multi_representers_types.push(data_type); + return this.prototype.yaml_multi_representers_handlers.push(handler); } - representer = null; - data_type = data === null ? 'null' : typeof data; - if (data_type === 'object') { - data_type = data.constructor; + + initialise(arg) { + var arg, default_flow_style, default_style, ref; + ref = arg != null ? arg : {}, default_style = ref.default_style, default_flow_style = ref.default_flow_style; + this.default_style = default_style; + this.default_flow_style = default_flow_style; + this.represented_objects = {}; + this.object_keeper = []; + return this.alias_key = null; } - if ((i = this.yaml_representers_types.lastIndexOf(data_type)) !== -1) { - representer = this.yaml_representers_handlers[i]; + + represent(data) { + var node; + node = this.represent_data(data); + this.serialize(node); + this.represented_objects = {}; + this.object_keeper = []; + return this.alias_key = null; } - if (representer == null) { - ref = this.yaml_multi_representers_types; - for (i = j = 0, len = ref.length; j < len; i = ++j) { - type = ref[i]; - if (!(data instanceof type)) { - continue; + + represent_data(data) { + var data_type, i, j, len, ref, representer, type; + if (this.ignore_aliases(data)) { + this.alias_key = null; + } else if ((i = this.object_keeper.indexOf(data)) !== -1) { + this.alias_key = i; + if (this.alias_key in this.represented_objects) { + return this.represented_objects[this.alias_key]; } - representer = this.yaml_multi_representers_handlers[i]; - break; + } else { + this.alias_key = this.object_keeper.length; + this.object_keeper.push(data); } - } - if (representer == null) { - if ((i = this.yaml_multi_representers_types.lastIndexOf(void 0)) !== -1) { - representer = this.yaml_multi_representers_handlers[i]; - } else if ((i = this.yaml_representers_types.lastIndexOf(void 0)) !== -1) { + representer = null; + data_type = data === null ? 'null' : typeof data; + if (data_type === 'object') { + data_type = data.constructor; + } + if ((i = this.yaml_representers_types.lastIndexOf(data_type)) !== -1) { representer = this.yaml_representers_handlers[i]; } + if (representer == null) { + ref = this.yaml_multi_representers_types; + for (i = j = 0, len = ref.length; j < len; i = ++j) { + type = ref[i]; + if (!(data instanceof type)) { + continue; + } + representer = this.yaml_multi_representers_handlers[i]; + break; + } + } + if (representer == null) { + if ((i = this.yaml_multi_representers_types.lastIndexOf(void 0)) !== -1) { + representer = this.yaml_multi_representers_handlers[i]; + } else if ((i = this.yaml_representers_types.lastIndexOf(void 0)) !== -1) { + representer = this.yaml_representers_handlers[i]; + } + } + if (representer != null) { + return representer.call(this, data); + } else { + return new nodes.ScalarNode(null, `${data}`); + } } - if (representer != null) { - return representer.call(this, data); - } else { - return new nodes.ScalarNode(null, "" + data); - } - }; - BaseRepresenter.prototype.represent_scalar = function(tag, value, style) { - var node; - if (style == null) { - style = this.default_style; - } - node = new nodes.ScalarNode(tag, value, null, null, style); - if (this.alias_key != null) { - this.represented_objects[this.alias_key] = node; + represent_scalar(tag, value, style = this.default_style) { + var node; + node = new nodes.ScalarNode(tag, value, null, null, style); + if (this.alias_key != null) { + this.represented_objects[this.alias_key] = node; + } + return node; } - return node; - }; - BaseRepresenter.prototype.represent_sequence = function(tag, sequence, flow_style) { - var best_style, item, j, len, node, node_item, ref, value; - value = []; - node = new nodes.SequenceNode(tag, value, null, null, flow_style); - if (this.alias_key != null) { - this.represented_objects[this.alias_key] = node; - } - best_style = true; - for (j = 0, len = sequence.length; j < len; j++) { - item = sequence[j]; - node_item = this.represent_data(item); - if (!(node_item instanceof nodes.ScalarNode || node_item.style)) { - best_style = false; + represent_sequence(tag, sequence, flow_style) { + var best_style, item, j, len, node, node_item, ref, value; + value = []; + node = new nodes.SequenceNode(tag, value, null, null, flow_style); + if (this.alias_key != null) { + this.represented_objects[this.alias_key] = node; } - value.push(node_item); - } - if (flow_style == null) { - node.flow_style = (ref = this.default_flow_style) != null ? ref : best_style; + best_style = true; + for (j = 0, len = sequence.length; j < len; j++) { + item = sequence[j]; + node_item = this.represent_data(item); + if (!(node_item instanceof nodes.ScalarNode || node_item.style)) { + best_style = false; + } + value.push(node_item); + } + if (flow_style == null) { + node.flow_style = (ref = this.default_flow_style) != null ? ref : best_style; + } + return node; } - return node; - }; - BaseRepresenter.prototype.represent_mapping = function(tag, mapping, flow_style) { - var best_style, item_key, item_value, node, node_key, node_value, ref, value; - value = []; - node = new nodes.MappingNode(tag, value, flow_style); - if (this.alias_key) { - this.represented_objects[this.alias_key] = node; - } - best_style = true; - for (item_key in mapping) { - if (!hasProp.call(mapping, item_key)) continue; - item_value = mapping[item_key]; - node_key = this.represent_data(item_key); - node_value = this.represent_data(item_value); - if (!(node_key instanceof nodes.ScalarNode || node_key.style)) { - best_style = false; + represent_mapping(tag, mapping, flow_style) { + var best_style, item_key, item_value, node, node_key, node_value, ref, value; + value = []; + node = new nodes.MappingNode(tag, value, flow_style); + if (this.alias_key) { + this.represented_objects[this.alias_key] = node; } - if (!(node_value instanceof nodes.ScalarNode || node_value.style)) { - best_style = false; + best_style = true; + for (item_key in mapping) { + if (!hasProp.call(mapping, item_key)) continue; + item_value = mapping[item_key]; + node_key = this.represent_data(item_key); + node_value = this.represent_data(item_value); + if (!(node_key instanceof nodes.ScalarNode || node_key.style)) { + best_style = false; + } + if (!(node_value instanceof nodes.ScalarNode || node_value.style)) { + best_style = false; + } + value.push([node_key, node_value]); } - value.push([node_key, node_value]); + if (!flow_style) { + node.flow_style = (ref = this.default_flow_style) != null ? ref : best_style; + } + return node; } - if (!flow_style) { - node.flow_style = (ref = this.default_flow_style) != null ? ref : best_style; + + ignore_aliases(data) { + return false; } - return node; - }; - BaseRepresenter.prototype.ignore_aliases = function(data) { - return false; }; + BaseRepresenter.prototype.yaml_representers_types = []; + + BaseRepresenter.prototype.yaml_representers_handlers = []; + + BaseRepresenter.prototype.yaml_multi_representers_types = []; + + BaseRepresenter.prototype.yaml_multi_representers_handlers = []; + + ctor = BaseRepresenter.prototype.initialise; + return BaseRepresenter; })(); this.Representer = (function(superClass) { - extend(Representer, superClass); + class Representer extends superClass { + represent_boolean(data) { + return this.represent_scalar('tag:yaml.org,2002:bool', (data ? 'true' : 'false')); + } - function Representer() { - return Representer.__super__.constructor.apply(this, arguments); - } + represent_null(data) { + return this.represent_scalar('tag:yaml.org,2002:null', 'null'); + } - Representer.prototype.represent_boolean = function(data) { - return this.represent_scalar('tag:yaml.org,2002:bool', (data ? 'true' : 'false')); - }; + represent_number(data) { + var tag, value; + tag = `tag:yaml.org,2002:${(data % 1 === 0 ? 'int' : 'float')}`; + value = data !== data ? '.nan' : data === 2e308 ? '.inf' : data === -2e308 ? '-.inf' : data.toString(); + return this.represent_scalar(tag, value); + } - Representer.prototype.represent_null = function(data) { - return this.represent_scalar('tag:yaml.org,2002:null', 'null'); - }; + represent_string(data) { + return this.represent_scalar('tag:yaml.org,2002:str', data); + } - Representer.prototype.represent_number = function(data) { - var tag, value; - tag = "tag:yaml.org,2002:" + (data % 1 === 0 ? 'int' : 'float'); - value = data !== data ? '.nan' : data === Infinity ? '.inf' : data === -Infinity ? '-.inf' : data.toString(); - return this.represent_scalar(tag, value); - }; + represent_array(data) { + return this.represent_sequence('tag:yaml.org,2002:seq', data); + } - Representer.prototype.represent_string = function(data) { - return this.represent_scalar('tag:yaml.org,2002:str', data); - }; + represent_date(data) { + return this.represent_scalar('tag:yaml.org,2002:timestamp', data.toISOString()); + } - Representer.prototype.represent_array = function(data) { - return this.represent_sequence('tag:yaml.org,2002:seq', data); - }; + represent_object(data) { + return this.represent_mapping('tag:yaml.org,2002:map', data); + } - Representer.prototype.represent_date = function(data) { - return this.represent_scalar('tag:yaml.org,2002:timestamp', data.toISOString()); - }; + represent_undefined(data) { + throw new exports.RepresenterError(`cannot represent an onbject: ${data}`); + } - Representer.prototype.represent_object = function(data) { - return this.represent_mapping('tag:yaml.org,2002:map', data); - }; + ignore_aliases(data) { + var ref; + if (data == null) { + return true; + } + if ((ref = typeof data) === 'boolean' || ref === 'number' || ref === 'string') { + return true; + } + return false; + } - Representer.prototype.represent_undefined = function(data) { - throw new exports.RepresenterError("cannot represent an onbject: " + data); }; - Representer.prototype.ignore_aliases = function(data) { - var ref; - if (data == null) { - return true; - } - if ((ref = typeof data) === 'boolean' || ref === 'number' || ref === 'string') { - return true; - } - return false; - }; + Representer.__super__ = superClass.prototype; return Representer; diff --git a/lib/resolver.js b/lib/resolver.js index 839c150..b792c77 100644 --- a/lib/resolver.js +++ b/lib/resolver.js @@ -1,7 +1,5 @@ (function() { var YAMLError, nodes, util, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty, indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; nodes = require('./nodes'); @@ -11,176 +9,178 @@ YAMLError = require('./errors').YAMLError; this.ResolverError = (function(superClass) { - extend(ResolverError, superClass); + class ResolverError extends superClass {}; - function ResolverError() { - return ResolverError.__super__.constructor.apply(this, arguments); - } + ResolverError.__super__ = superClass.prototype; return ResolverError; })(YAMLError); this.BaseResolver = (function() { - var DEFAULT_MAPPING_TAG, DEFAULT_SCALAR_TAG, DEFAULT_SEQUENCE_TAG; + var DEFAULT_MAPPING_TAG, DEFAULT_SCALAR_TAG, DEFAULT_SEQUENCE_TAG, ctor; - DEFAULT_SCALAR_TAG = 'tag:yaml.org,2002:str'; - - DEFAULT_SEQUENCE_TAG = 'tag:yaml.org,2002:seq'; - - DEFAULT_MAPPING_TAG = 'tag:yaml.org,2002:map'; - - BaseResolver.prototype.yaml_implicit_resolvers = {}; - - BaseResolver.prototype.yaml_path_resolvers = {}; - - BaseResolver.add_implicit_resolver = function(tag, regexp, first) { - var base, char, i, len, results; - if (first == null) { - first = [null]; - } - if (!this.prototype.hasOwnProperty('yaml_implicit_resolvers')) { - this.prototype.yaml_implicit_resolvers = util.extend({}, this.prototype.yaml_implicit_resolvers); + class BaseResolver { + constructor() { + return ctor.apply(this, arguments); } - results = []; - for (i = 0, len = first.length; i < len; i++) { - char = first[i]; - results.push(((base = this.prototype.yaml_implicit_resolvers)[char] != null ? base[char] : base[char] = []).push([tag, regexp])); - } - return results; - }; - function BaseResolver() { - this.resolver_exact_paths = []; - this.resolver_prefix_paths = []; - } + static add_implicit_resolver(tag, regexp, first = [null]) { + var base, char, i, len, results; + if (!this.prototype.hasOwnProperty('yaml_implicit_resolvers')) { + this.prototype.yaml_implicit_resolvers = util.clone(this.prototype.yaml_implicit_resolvers); + } + results = []; + for (i = 0, len = first.length; i < len; i++) { + char = first[i]; + results.push(((base = this.prototype.yaml_implicit_resolvers)[char] != null ? base[char] : base[char] = []).push([tag, regexp])); + } + return results; + } - BaseResolver.prototype.descend_resolver = function(current_node, current_index) { - var depth, exact_paths, i, j, kind, len, len1, path, prefix_paths, ref, ref1, ref2, ref3; - if (util.is_empty(this.yaml_path_resolvers)) { - return; + initialise() { + this.resolver_exact_paths = []; + return this.resolver_prefix_paths = []; } - exact_paths = {}; - prefix_paths = []; - if (current_node) { - depth = this.resolver_prefix_paths.length; - ref = this.resolver_prefix_paths.slice(-1)[0]; - for (i = 0, len = ref.length; i < len; i++) { - ref1 = ref[i], path = ref1[0], kind = ref1[1]; - if (this.check_resolver_prefix(depth, path, kind, current_node, current_index)) { - if (path.length > depth) { - prefix_paths.push([path, kind]); - } else { - exact_paths[kind] = this.yaml_path_resolvers[path][kind]; + + descend_resolver(current_node, current_index) { + var depth, exact_paths, i, j, kind, len, len1, path, prefix_paths, ref, ref1, ref2, ref3; + if (util.is_empty(this.yaml_path_resolvers)) { + return; + } + exact_paths = {}; + prefix_paths = []; + if (current_node) { + depth = this.resolver_prefix_paths.length; + ref = this.resolver_prefix_paths.slice(-1)[0]; + for (i = 0, len = ref.length; i < len; i++) { + ref1 = ref[i], path = ref1[0], kind = ref1[1]; + if (this.check_resolver_prefix(depth, path, kind, current_node, current_index)) { + if (path.length > depth) { + prefix_paths.push([path, kind]); + } else { + exact_paths[kind] = this.yaml_path_resolvers[path][kind]; + } } } - } - } else { - ref2 = this.yaml_path_resolvers; - for (j = 0, len1 = ref2.length; j < len1; j++) { - ref3 = ref2[j], path = ref3[0], kind = ref3[1]; - if (!path) { - exact_paths[kind] = this.yaml_path_resolvers[path][kind]; - } else { - prefix_paths.push([path, kind]); + } else { + ref2 = this.yaml_path_resolvers; + for (j = 0, len1 = ref2.length; j < len1; j++) { + ref3 = ref2[j], path = ref3[0], kind = ref3[1]; + if (!path) { + exact_paths[kind] = this.yaml_path_resolvers[path][kind]; + } else { + prefix_paths.push([path, kind]); + } } } + this.resolver_exact_paths.push(exact_paths); + return this.resolver_prefix_paths.push(prefix_paths); } - this.resolver_exact_paths.push(exact_paths); - return this.resolver_prefix_paths.push(prefix_paths); - }; - BaseResolver.prototype.ascend_resolver = function() { - if (util.is_empty(this.yaml_path_resolvers)) { - return; + ascend_resolver() { + if (util.is_empty(this.yaml_path_resolvers)) { + return; + } + this.resolver_exact_paths.pop(); + return this.resolver_prefix_paths.pop(); } - this.resolver_exact_paths.pop(); - return this.resolver_prefix_paths.pop(); - }; - BaseResolver.prototype.check_resolver_prefix = function(depth, path, kind, current_node, current_index) { - var index_check, node_check, ref; - ref = path[depth - 1], node_check = ref[0], index_check = ref[1]; - if (typeof node_check === 'string') { - if (current_node.tag !== node_check) { - return; + check_resolver_prefix(depth, path, kind, current_node, current_index) { + var index_check, node_check, ref; + ref = path[depth - 1], node_check = ref[0], index_check = ref[1]; + if (typeof node_check === 'string') { + if (current_node.tag !== node_check) { + return; + } + } else if (node_check !== null) { + if (!(current_node instanceof node_check)) { + return; + } } - } else if (node_check !== null) { - if (!(current_node instanceof node_check)) { + if (index_check === true && current_index !== null) { return; } - } - if (index_check === true && current_index !== null) { - return; - } - if ((index_check === false || index_check === null) && current_index === null) { - return; - } - if (typeof index_check === 'string') { - if (!(current_index instanceof nodes.ScalarNode) && index_check === current_index.value) { + if ((index_check === false || index_check === null) && current_index === null) { return; } - } else if (typeof index_check === 'number') { - if (index_check !== current_index) { - return; + if (typeof index_check === 'string') { + if (!(current_index instanceof nodes.ScalarNode) && index_check === current_index.value) { + return; + } + } else if (typeof index_check === 'number') { + if (index_check !== current_index) { + return; + } } + return true; } - return true; - }; - BaseResolver.prototype.resolve = function(kind, value, implicit) { - var empty, exact_paths, i, k, len, ref, ref1, ref2, ref3, regexp, resolvers, tag; - if (kind === nodes.ScalarNode && implicit[0]) { - if (value === '') { - resolvers = (ref = this.yaml_implicit_resolvers['']) != null ? ref : []; - } else { - resolvers = (ref1 = this.yaml_implicit_resolvers[value[0]]) != null ? ref1 : []; + resolve(kind, value, implicit) { + var empty, exact_paths, i, k, len, ref, ref1, ref2, ref3, regexp, resolvers, tag; + if (kind === nodes.ScalarNode && implicit[0]) { + if (value === '') { + resolvers = (ref = this.yaml_implicit_resolvers['']) != null ? ref : []; + } else { + resolvers = (ref1 = this.yaml_implicit_resolvers[value[0]]) != null ? ref1 : []; + } + resolvers = resolvers.concat((ref2 = this.yaml_implicit_resolvers[null]) != null ? ref2 : []); + for (i = 0, len = resolvers.length; i < len; i++) { + ref3 = resolvers[i], tag = ref3[0], regexp = ref3[1]; + if (value.match(regexp)) { + return tag; + } + } + implicit = implicit[1]; } - resolvers = resolvers.concat((ref2 = this.yaml_implicit_resolvers[null]) != null ? ref2 : []); - for (i = 0, len = resolvers.length; i < len; i++) { - ref3 = resolvers[i], tag = ref3[0], regexp = ref3[1]; - if (value.match(regexp)) { - return tag; + empty = true; + for (k in this.yaml_path_resolvers) { + if ({}[k] == null) { + empty = false; } } - implicit = implicit[1]; - } - empty = true; - for (k in this.yaml_path_resolvers) { - if ({}[k] == null) { - empty = false; + if (!empty) { + exact_paths = this.resolver_exact_paths.slice(-1)[0]; + if (indexOf.call(exact_paths, kind) >= 0) { + return exact_paths[kind]; + } + if (indexOf.call(exact_paths, null) >= 0) { + return exact_paths[null]; + } } - } - if (!empty) { - exact_paths = this.resolver_exact_paths.slice(-1)[0]; - if (indexOf.call(exact_paths, kind) >= 0) { - return exact_paths[kind]; + if (kind === nodes.ScalarNode) { + return DEFAULT_SCALAR_TAG; } - if (indexOf.call(exact_paths, null) >= 0) { - return exact_paths[null]; + if (kind === nodes.SequenceNode) { + return DEFAULT_SEQUENCE_TAG; + } + if (kind === nodes.MappingNode) { + return DEFAULT_MAPPING_TAG; } } - if (kind === nodes.ScalarNode) { - return DEFAULT_SCALAR_TAG; - } - if (kind === nodes.SequenceNode) { - return DEFAULT_SEQUENCE_TAG; - } - if (kind === nodes.MappingNode) { - return DEFAULT_MAPPING_TAG; - } + }; + DEFAULT_SCALAR_TAG = 'tag:yaml.org,2002:str'; + + DEFAULT_SEQUENCE_TAG = 'tag:yaml.org,2002:seq'; + + DEFAULT_MAPPING_TAG = 'tag:yaml.org,2002:map'; + + BaseResolver.prototype.yaml_implicit_resolvers = {}; + + BaseResolver.prototype.yaml_path_resolvers = {}; + + ctor = BaseResolver.prototype.initialise; + return BaseResolver; })(); this.Resolver = (function(superClass) { - extend(Resolver, superClass); + class Resolver extends superClass {}; - function Resolver() { - return Resolver.__super__.constructor.apply(this, arguments); - } + Resolver.__super__ = superClass.prototype; return Resolver; diff --git a/lib/scanner.js b/lib/scanner.js index e3ac367..80dc50e 100644 --- a/lib/scanner.js +++ b/lib/scanner.js @@ -1,8 +1,6 @@ (function() { var MarkedYAMLError, SimpleKey, tokens, util, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty, - slice = [].slice, indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; MarkedYAMLError = require('./errors').MarkedYAMLError; @@ -17,11 +15,9 @@ */ this.ScannerError = (function(superClass) { - extend(ScannerError, superClass); + class ScannerError extends superClass {}; - function ScannerError() { - return ScannerError.__super__.constructor.apply(this, arguments); - } + ScannerError.__super__ = superClass.prototype; return ScannerError; @@ -32,8 +28,8 @@ Represents a possible simple key. */ - SimpleKey = (function() { - function SimpleKey(token_number1, required1, index, line, column1, mark1) { + SimpleKey = class SimpleKey { + constructor(token_number1, required1, index, line, column1, mark1) { this.token_number = token_number1; this.required = required1; this.index = index; @@ -42,9 +38,7 @@ this.mark = mark1; } - return SimpleKey; - - })(); + }; /* @@ -52,456 +46,400 @@ */ this.Scanner = (function() { - var C_LB, C_NUMBERS, C_WS, ESCAPE_CODES, ESCAPE_REPLACEMENTS; - - C_LB = '\r\n\x85\u2028\u2029'; - - C_WS = '\t '; - - C_NUMBERS = '0123456789'; + var C_LB, C_NUMBERS, C_WS, ESCAPE_CODES, ESCAPE_REPLACEMENTS, ctor; - ESCAPE_REPLACEMENTS = { - '0': '\x00', - 'a': '\x07', - 'b': '\x08', - 't': '\x09', - '\t': '\x09', - 'n': '\x0A', - 'v': '\x0B', - 'f': '\x0C', - 'r': '\x0D', - 'e': '\x1B', - ' ': '\x20', - '"': '"', - '\\': '\\', - 'N': '\x85', - '_': '\xA0', - 'L': '\u2028', - 'P': '\u2029' - }; + class Scanner { + constructor() { + return ctor.apply(this, arguments); + } - ESCAPE_CODES = { - 'x': 2, - 'u': 4, - 'U': 8 - }; + /* + Initialise the Scanner + */ - /* - Initialise the Scanner - */ - - function Scanner() { - this.done = false; - this.flow_level = 0; - this.tokens = []; - this.fetch_stream_start(); - this.tokens_taken = 0; - this.indent = -1; - this.indents = []; - this.allow_simple_key = true; - this.possible_simple_keys = {}; - } + initialise() { + this.done = false; + this.flow_level = 0; + this.tokens = []; + this.fetch_stream_start(); + this.tokens_taken = 0; + this.indent = -1; + this.indents = []; + this.allow_simple_key = true; + return this.possible_simple_keys = {}; + } - /* - Check if the next token is one of the given types. - */ + /* + Check if the next token is one of the given types. + */ - Scanner.prototype.check_token = function() { - var choice, choices, i, len; - choices = 1 <= arguments.length ? slice.call(arguments, 0) : []; - while (this.need_more_tokens()) { - this.fetch_more_tokens(); - } - if (this.tokens.length !== 0) { - if (choices.length === 0) { - return true; + check_token(...choices) { + var choice, i, len; + while (this.need_more_tokens()) { + this.fetch_more_tokens(); } - for (i = 0, len = choices.length; i < len; i++) { - choice = choices[i]; - if (this.tokens[0] instanceof choice) { + if (this.tokens.length !== 0) { + if (choices.length === 0) { return true; } + for (i = 0, len = choices.length; i < len; i++) { + choice = choices[i]; + if (this.tokens[0] instanceof choice) { + return true; + } + } } + return false; } - return false; - }; - /* - Return the next token, but do not delete it from the queue. - */ + /* + Return the next token, but do not delete it from the queue. + */ - Scanner.prototype.peek_token = function() { - while (this.need_more_tokens()) { - this.fetch_more_tokens(); - } - if (this.tokens.length !== 0) { - return this.tokens[0]; + peek_token() { + while (this.need_more_tokens()) { + this.fetch_more_tokens(); + } + if (this.tokens.length !== 0) { + return this.tokens[0]; + } } - }; - /* - Return the next token, and remove it from the queue. - */ + /* + Return the next token, and remove it from the queue. + */ - Scanner.prototype.get_token = function() { - while (this.need_more_tokens()) { - this.fetch_more_tokens(); - } - if (this.tokens.length !== 0) { - this.tokens_taken++; - return this.tokens.shift(); + get_token() { + while (this.need_more_tokens()) { + this.fetch_more_tokens(); + } + if (this.tokens.length !== 0) { + this.tokens_taken++; + return this.tokens.shift(); + } } - }; - Scanner.prototype.need_more_tokens = function() { - if (this.done) { + need_more_tokens() { + if (this.done) { + return false; + } + if (this.tokens.length === 0) { + return true; + } + this.stale_possible_simple_keys(); + if (this.next_possible_simple_key() === this.tokens_taken) { + return true; + } return false; } - if (this.tokens.length === 0) { - return true; - } - this.stale_possible_simple_keys(); - if (this.next_possible_simple_key() === this.tokens_taken) { - return true; - } - return false; - }; - Scanner.prototype.fetch_more_tokens = function() { - var char; - this.scan_to_next_token(); - this.stale_possible_simple_keys(); - this.unwind_indent(this.column); - char = this.peek(); - if (char === '\x00') { - return this.fetch_stream_end(); - } - if (char === '%' && this.check_directive()) { - return this.fetch_directive(); - } - if (char === '-' && this.check_document_start()) { - return this.fetch_document_start(); - } - if (char === '.' && this.check_document_end()) { - return this.fetch_document_end(); - } - if (char === '[') { - return this.fetch_flow_sequence_start(); - } - if (char === '{') { - return this.fetch_flow_mapping_start(); - } - if (char === ']') { - return this.fetch_flow_sequence_end(); - } - if (char === '}') { - return this.fetch_flow_mapping_end(); - } - if (char === ',') { - return this.fetch_flow_entry(); - } - if (char === '-' && this.check_block_entry()) { - return this.fetch_block_entry(); - } - if (char === '?' && this.check_key()) { - return this.fetch_key(); - } - if (char === ':' && this.check_value()) { - return this.fetch_value(); - } - if (char === '*') { - return this.fetch_alias(); - } - if (char === '&') { - return this.fetch_anchor(); - } - if (char === '!') { - return this.fetch_tag(); - } - if (char === '|' && this.flow_level === 0) { - return this.fetch_literal(); - } - if (char === '>' && this.flow_level === 0) { - return this.fetch_folded(); - } - if (char === '\'') { - return this.fetch_single(); - } - if (char === '"') { - return this.fetch_double(); + fetch_more_tokens() { + var char; + this.scan_to_next_token(); + this.stale_possible_simple_keys(); + this.unwind_indent(this.column); + char = this.peek(); + if (char === '\x00') { + return this.fetch_stream_end(); + } + if (char === '%' && this.check_directive()) { + return this.fetch_directive(); + } + if (char === '-' && this.check_document_start()) { + return this.fetch_document_start(); + } + if (char === '.' && this.check_document_end()) { + return this.fetch_document_end(); + } + if (char === '[') { + return this.fetch_flow_sequence_start(); + } + if (char === '{') { + return this.fetch_flow_mapping_start(); + } + if (char === ']') { + return this.fetch_flow_sequence_end(); + } + if (char === '}') { + return this.fetch_flow_mapping_end(); + } + if (char === ',') { + return this.fetch_flow_entry(); + } + if (char === '-' && this.check_block_entry()) { + return this.fetch_block_entry(); + } + if (char === '?' && this.check_key()) { + return this.fetch_key(); + } + if (char === ':' && this.check_value()) { + return this.fetch_value(); + } + if (char === '*') { + return this.fetch_alias(); + } + if (char === '&') { + return this.fetch_anchor(); + } + if (char === '!') { + return this.fetch_tag(); + } + if (char === '|' && this.flow_level === 0) { + return this.fetch_literal(); + } + if (char === '>' && this.flow_level === 0) { + return this.fetch_folded(); + } + if (char === '\'') { + return this.fetch_single(); + } + if (char === '"') { + return this.fetch_double(); + } + if (this.check_plain()) { + return this.fetch_plain(); + } + throw new exports.ScannerError('while scanning for the next token', null, `found character ${char} that cannot start any token`, this.get_mark()); } - if (this.check_plain()) { - return this.fetch_plain(); + + + /* + Return the number of the nearest possible simple key. + */ + + next_possible_simple_key() { + var key, level, min_token_number, ref; + min_token_number = null; + ref = this.possible_simple_keys; + for (level in ref) { + if (!hasProp.call(ref, level)) continue; + key = ref[level]; + if (min_token_number === null || key.token_number < min_token_number) { + min_token_number = key.token_number; + } + } + return min_token_number; + } + + + /* + Remove entries that are no longer possible simple keys. According to the + YAML spec, simple keys: + should be limited to a single line + should be no longer than 1024 characters + Disabling this procedure will allow simple keys of any length and height + (may cause problems if indentation is broken though). + */ + + stale_possible_simple_keys() { + var key, level, ref, results; + ref = this.possible_simple_keys; + results = []; + for (level in ref) { + if (!hasProp.call(ref, level)) continue; + key = ref[level]; + if (key.line === this.line && this.index - key.index <= 1024) { + continue; + } + if (!key.required) { + results.push(delete this.possible_simple_keys[level]); + } else { + throw new exports.ScannerError('while scanning a simple key', key.mark, 'could not find expected \':\'', this.get_mark()); + } + } + return results; } - throw new exports.ScannerError('while scanning for the next token', null, "found character " + char + " that cannot start any token", this.get_mark()); - }; - /* - Return the number of the nearest possible simple key. - */ + /* + The next token may start a simple key. We check if it's possible and save + its position. This function is called for ALIAS, ANCHOR, TAG, + SCALAR (flow),'[' and '{'. + */ - Scanner.prototype.next_possible_simple_key = function() { - var key, level, min_token_number, ref; - min_token_number = null; - ref = this.possible_simple_keys; - for (level in ref) { - if (!hasProp.call(ref, level)) continue; - key = ref[level]; - if (min_token_number === null || key.token_number < min_token_number) { - min_token_number = key.token_number; + save_possible_simple_key() { + var required, token_number; + required = this.flow_level === 0 && this.indent === this.column; + if (required && !this.allow_simple_key) { + throw new Error('logic failure'); + } + if (!this.allow_simple_key) { + return; } + this.remove_possible_simple_key(); + token_number = this.tokens_taken + this.tokens.length; + return this.possible_simple_keys[this.flow_level] = new SimpleKey(token_number, required, this.index, this.line, this.column, this.get_mark()); } - return min_token_number; - }; - /* - Remove entries that are no longer possible simple keys. According to the - YAML spec, simple keys: - should be limited to a single line - should be no longer than 1024 characters - Disabling this procedure will allow simple keys of any length and height - (may cause problems if indentation is broken though). - */ - - Scanner.prototype.stale_possible_simple_keys = function() { - var key, level, ref, results; - ref = this.possible_simple_keys; - results = []; - for (level in ref) { - if (!hasProp.call(ref, level)) continue; - key = ref[level]; - if (key.line === this.line && this.index - key.index <= 1024) { - continue; + /* + Remove the saved possible simple key at the current flow level. + */ + + remove_possible_simple_key() { + var key; + if (!(key = this.possible_simple_keys[this.flow_level])) { + return; } if (!key.required) { - results.push(delete this.possible_simple_keys[level]); + return delete this.possible_simple_keys[this.flow_level]; } else { throw new exports.ScannerError('while scanning a simple key', key.mark, 'could not find expected \':\'', this.get_mark()); } } - return results; - }; - /* - The next token may start a simple key. We check if it's possible and save - its position. This function is called for ALIAS, ANCHOR, TAG, - SCALAR (flow),'[' and '{'. - */ + /* + In flow context, tokens should respect indentation. + Actually the condition should be `self.indent >= column` according to + the spec. But this condition will prohibit intuitively correct + constructions such as + key : { + } + */ - Scanner.prototype.save_possible_simple_key = function() { - var required, token_number; - required = this.flow_level === 0 && this.indent === this.column; - if (required && !this.allow_simple_key) { - throw new Error('logic failure'); - } - if (!this.allow_simple_key) { - return; + unwind_indent(column) { + var mark, results; + if (this.flow_level !== 0) { + return; + } + results = []; + while (this.indent > column) { + mark = this.get_mark(); + this.indent = this.indents.pop(); + results.push(this.tokens.push(new tokens.BlockEndToken(mark, mark))); + } + return results; } - this.remove_possible_simple_key(); - token_number = this.tokens_taken + this.tokens.length; - return this.possible_simple_keys[this.flow_level] = new SimpleKey(token_number, required, this.index, this.line, this.column, this.get_mark()); - }; - /* - Remove the saved possible simple key at the current flow level. - */ + /* + Check if we need to increase indentation. + */ - Scanner.prototype.remove_possible_simple_key = function() { - var key; - if (!(key = this.possible_simple_keys[this.flow_level])) { - return; - } - if (!key.required) { - return delete this.possible_simple_keys[this.flow_level]; - } else { - throw new exports.ScannerError('while scanning a simple key', key.mark, 'could not find expected \':\'', this.get_mark()); + add_indent(column) { + if (!(column > this.indent)) { + return false; + } + this.indents.push(this.indent); + this.indent = column; + return true; } - }; - - /* - In flow context, tokens should respect indentation. - Actually the condition should be `self.indent >= column` according to - the spec. But this condition will prohibit intuitively correct - constructions such as - key : { + fetch_stream_start() { + var mark; + mark = this.get_mark(); + return this.tokens.push(new tokens.StreamStartToken(mark, mark, this.encoding)); } - */ - Scanner.prototype.unwind_indent = function(column) { - var mark, results; - if (this.flow_level !== 0) { - return; - } - results = []; - while (this.indent > column) { + fetch_stream_end() { + var mark; + this.unwind_indent(-1); + this.remove_possible_simple_key(); + this.allow_possible_simple_key = false; + this.possible_simple_keys = {}; mark = this.get_mark(); - this.indent = this.indents.pop(); - results.push(this.tokens.push(new tokens.BlockEndToken(mark, mark))); + this.tokens.push(new tokens.StreamEndToken(mark, mark)); + return this.done = true; } - return results; - }; - - - /* - Check if we need to increase indentation. - */ - Scanner.prototype.add_indent = function(column) { - if (!(column > this.indent)) { - return false; + fetch_directive() { + this.unwind_indent(-1); + this.remove_possible_simple_key(); + this.allow_simple_key = false; + return this.tokens.push(this.scan_directive()); } - this.indents.push(this.indent); - this.indent = column; - return true; - }; - - Scanner.prototype.fetch_stream_start = function() { - var mark; - mark = this.get_mark(); - return this.tokens.push(new tokens.StreamStartToken(mark, mark, this.encoding)); - }; - - Scanner.prototype.fetch_stream_end = function() { - var mark; - this.unwind_indent(-1); - this.remove_possible_simple_key(); - this.allow_possible_simple_key = false; - this.possible_simple_keys = {}; - mark = this.get_mark(); - this.tokens.push(new tokens.StreamEndToken(mark, mark)); - return this.done = true; - }; - Scanner.prototype.fetch_directive = function() { - this.unwind_indent(-1); - this.remove_possible_simple_key(); - this.allow_simple_key = false; - return this.tokens.push(this.scan_directive()); - }; - - Scanner.prototype.fetch_document_start = function() { - return this.fetch_document_indicator(tokens.DocumentStartToken); - }; - - Scanner.prototype.fetch_document_end = function() { - return this.fetch_document_indicator(tokens.DocumentEndToken); - }; - - Scanner.prototype.fetch_document_indicator = function(TokenClass) { - var start_mark; - this.unwind_indent(-1); - this.remove_possible_simple_key(); - this.allow_simple_key = false; - start_mark = this.get_mark(); - this.forward(3); - return this.tokens.push(new TokenClass(start_mark, this.get_mark())); - }; + fetch_document_start() { + return this.fetch_document_indicator(tokens.DocumentStartToken); + } - Scanner.prototype.fetch_flow_sequence_start = function() { - return this.fetch_flow_collection_start(tokens.FlowSequenceStartToken); - }; + fetch_document_end() { + return this.fetch_document_indicator(tokens.DocumentEndToken); + } - Scanner.prototype.fetch_flow_mapping_start = function() { - return this.fetch_flow_collection_start(tokens.FlowMappingStartToken); - }; + fetch_document_indicator(TokenClass) { + var start_mark; + this.unwind_indent(-1); + this.remove_possible_simple_key(); + this.allow_simple_key = false; + start_mark = this.get_mark(); + this.forward(3); + return this.tokens.push(new TokenClass(start_mark, this.get_mark())); + } - Scanner.prototype.fetch_flow_collection_start = function(TokenClass) { - var start_mark; - this.save_possible_simple_key(); - this.flow_level++; - this.allow_simple_key = true; - start_mark = this.get_mark(); - this.forward(); - return this.tokens.push(new TokenClass(start_mark, this.get_mark())); - }; + fetch_flow_sequence_start() { + return this.fetch_flow_collection_start(tokens.FlowSequenceStartToken); + } - Scanner.prototype.fetch_flow_sequence_end = function() { - return this.fetch_flow_collection_end(tokens.FlowSequenceEndToken); - }; + fetch_flow_mapping_start() { + return this.fetch_flow_collection_start(tokens.FlowMappingStartToken); + } - Scanner.prototype.fetch_flow_mapping_end = function() { - return this.fetch_flow_collection_end(tokens.FlowMappingEndToken); - }; + fetch_flow_collection_start(TokenClass) { + var start_mark; + this.save_possible_simple_key(); + this.flow_level++; + this.allow_simple_key = true; + start_mark = this.get_mark(); + this.forward(); + return this.tokens.push(new TokenClass(start_mark, this.get_mark())); + } - Scanner.prototype.fetch_flow_collection_end = function(TokenClass) { - var start_mark; - this.remove_possible_simple_key(); - this.flow_level--; - this.allow_simple_key = false; - start_mark = this.get_mark(); - this.forward(); - return this.tokens.push(new TokenClass(start_mark, this.get_mark())); - }; + fetch_flow_sequence_end() { + return this.fetch_flow_collection_end(tokens.FlowSequenceEndToken); + } - Scanner.prototype.fetch_flow_entry = function() { - var start_mark; - this.allow_simple_key = true; - this.remove_possible_simple_key(); - start_mark = this.get_mark(); - this.forward(); - return this.tokens.push(new tokens.FlowEntryToken(start_mark, this.get_mark())); - }; + fetch_flow_mapping_end() { + return this.fetch_flow_collection_end(tokens.FlowMappingEndToken); + } - Scanner.prototype.fetch_block_entry = function() { - var mark, start_mark; - if (this.flow_level === 0) { - if (!this.allow_simple_key) { - throw new exports.ScannerError(null, null, 'sequence entries are not allowed here', this.get_mark()); - } - if (this.add_indent(this.column)) { - mark = this.get_mark(); - this.tokens.push(new tokens.BlockSequenceStartToken(mark, mark)); - } + fetch_flow_collection_end(TokenClass) { + var start_mark; + this.remove_possible_simple_key(); + this.flow_level--; + this.allow_simple_key = false; + start_mark = this.get_mark(); + this.forward(); + return this.tokens.push(new TokenClass(start_mark, this.get_mark())); } - this.allow_simple_key = true; - this.remove_possible_simple_key(); - start_mark = this.get_mark(); - this.forward(); - return this.tokens.push(new tokens.BlockEntryToken(start_mark, this.get_mark())); - }; - Scanner.prototype.fetch_key = function() { - var mark, start_mark; - if (this.flow_level === 0) { - if (!this.allow_simple_key) { - throw new exports.ScannerError(null, null, 'mapping keys are not allowed here', this.get_mark()); - } - if (this.add_indent(this.column)) { - mark = this.get_mark(); - this.tokens.push(new tokens.BlockMappingStartToken(mark, mark)); - } + fetch_flow_entry() { + var start_mark; + this.allow_simple_key = true; + this.remove_possible_simple_key(); + start_mark = this.get_mark(); + this.forward(); + return this.tokens.push(new tokens.FlowEntryToken(start_mark, this.get_mark())); } - this.allow_simple_key = !this.flow_level; - this.remove_possible_simple_key(); - start_mark = this.get_mark(); - this.forward(); - return this.tokens.push(new tokens.KeyToken(start_mark, this.get_mark())); - }; - Scanner.prototype.fetch_value = function() { - var key, mark, start_mark; - if (key = this.possible_simple_keys[this.flow_level]) { - delete this.possible_simple_keys[this.flow_level]; - this.tokens.splice(key.token_number - this.tokens_taken, 0, new tokens.KeyToken(key.mark, key.mark)); + fetch_block_entry() { + var mark, start_mark; if (this.flow_level === 0) { - if (this.add_indent(key.column)) { - this.tokens.splice(key.token_number - this.tokens_taken, 0, new tokens.BlockMappingStartToken(key.mark, key.mark)); + if (!this.allow_simple_key) { + throw new exports.ScannerError(null, null, 'sequence entries are not allowed here', this.get_mark()); + } + if (this.add_indent(this.column)) { + mark = this.get_mark(); + this.tokens.push(new tokens.BlockSequenceStartToken(mark, mark)); } } - this.allow_simple_key = false; - } else { + this.allow_simple_key = true; + this.remove_possible_simple_key(); + start_mark = this.get_mark(); + this.forward(); + return this.tokens.push(new tokens.BlockEntryToken(start_mark, this.get_mark())); + } + + fetch_key() { + var mark, start_mark; if (this.flow_level === 0) { if (!this.allow_simple_key) { - throw new exports.ScannerError(null, null, 'mapping values are not allowed here', this.get_mark()); + throw new exports.ScannerError(null, null, 'mapping keys are not allowed here', this.get_mark()); } if (this.add_indent(this.column)) { mark = this.get_mark(); @@ -510,969 +448,1033 @@ } this.allow_simple_key = !this.flow_level; this.remove_possible_simple_key(); + start_mark = this.get_mark(); + this.forward(); + return this.tokens.push(new tokens.KeyToken(start_mark, this.get_mark())); } - start_mark = this.get_mark(); - this.forward(); - return this.tokens.push(new tokens.ValueToken(start_mark, this.get_mark())); - }; - - Scanner.prototype.fetch_alias = function() { - this.save_possible_simple_key(); - this.allow_simple_key = false; - return this.tokens.push(this.scan_anchor(tokens.AliasToken)); - }; - Scanner.prototype.fetch_anchor = function() { - this.save_possible_simple_key(); - this.allow_simple_key = false; - return this.tokens.push(this.scan_anchor(tokens.AnchorToken)); - }; - - Scanner.prototype.fetch_tag = function() { - this.save_possible_simple_key(); - this.allow_simple_key = false; - return this.tokens.push(this.scan_tag()); - }; + fetch_value() { + var key, mark, start_mark; + if (key = this.possible_simple_keys[this.flow_level]) { + delete this.possible_simple_keys[this.flow_level]; + this.tokens.splice(key.token_number - this.tokens_taken, 0, new tokens.KeyToken(key.mark, key.mark)); + if (this.flow_level === 0) { + if (this.add_indent(key.column)) { + this.tokens.splice(key.token_number - this.tokens_taken, 0, new tokens.BlockMappingStartToken(key.mark, key.mark)); + } + } + this.allow_simple_key = false; + } else { + if (this.flow_level === 0) { + if (!this.allow_simple_key) { + throw new exports.ScannerError(null, null, 'mapping values are not allowed here', this.get_mark()); + } + if (this.add_indent(this.column)) { + mark = this.get_mark(); + this.tokens.push(new tokens.BlockMappingStartToken(mark, mark)); + } + } + this.allow_simple_key = !this.flow_level; + this.remove_possible_simple_key(); + } + start_mark = this.get_mark(); + this.forward(); + return this.tokens.push(new tokens.ValueToken(start_mark, this.get_mark())); + } - Scanner.prototype.fetch_literal = function() { - return this.fetch_block_scalar('|'); - }; + fetch_alias() { + this.save_possible_simple_key(); + this.allow_simple_key = false; + return this.tokens.push(this.scan_anchor(tokens.AliasToken)); + } - Scanner.prototype.fetch_folded = function() { - return this.fetch_block_scalar('>'); - }; + fetch_anchor() { + this.save_possible_simple_key(); + this.allow_simple_key = false; + return this.tokens.push(this.scan_anchor(tokens.AnchorToken)); + } - Scanner.prototype.fetch_block_scalar = function(style) { - this.allow_simple_key = true; - this.remove_possible_simple_key(); - return this.tokens.push(this.scan_block_scalar(style)); - }; + fetch_tag() { + this.save_possible_simple_key(); + this.allow_simple_key = false; + return this.tokens.push(this.scan_tag()); + } - Scanner.prototype.fetch_single = function() { - return this.fetch_flow_scalar('\''); - }; + fetch_literal() { + return this.fetch_block_scalar('|'); + } - Scanner.prototype.fetch_double = function() { - return this.fetch_flow_scalar('"'); - }; + fetch_folded() { + return this.fetch_block_scalar('>'); + } - Scanner.prototype.fetch_flow_scalar = function(style) { - this.save_possible_simple_key(); - this.allow_simple_key = false; - return this.tokens.push(this.scan_flow_scalar(style)); - }; + fetch_block_scalar(style) { + this.allow_simple_key = true; + this.remove_possible_simple_key(); + return this.tokens.push(this.scan_block_scalar(style)); + } - Scanner.prototype.fetch_plain = function() { - this.save_possible_simple_key(); - this.allow_simple_key = false; - return this.tokens.push(this.scan_plain()); - }; + fetch_single() { + return this.fetch_flow_scalar('\''); + } + fetch_double() { + return this.fetch_flow_scalar('"'); + } - /* - DIRECTIVE: ^ '%' - */ + fetch_flow_scalar(style) { + this.save_possible_simple_key(); + this.allow_simple_key = false; + return this.tokens.push(this.scan_flow_scalar(style)); + } - Scanner.prototype.check_directive = function() { - if (this.column === 0) { - return true; + fetch_plain() { + this.save_possible_simple_key(); + this.allow_simple_key = false; + return this.tokens.push(this.scan_plain()); } - return false; - }; - /* - DOCUMENT-START: ^ '---' (' '|'\n') - */ + /* + DIRECTIVE: ^ '%' + */ - Scanner.prototype.check_document_start = function() { - var ref; - if (this.column === 0 && this.prefix(3) === '---' && (ref = this.peek(3), indexOf.call(C_LB + C_WS + '\x00', ref) >= 0)) { - return true; + check_directive() { + if (this.column === 0) { + return true; + } + return false; } - return false; - }; - /* - DOCUMENT-END: ^ '...' (' '|'\n') - */ + /* + DOCUMENT-START: ^ '---' (' '|'\n') + */ - Scanner.prototype.check_document_end = function() { - var ref; - if (this.column === 0 && this.prefix(3) === '...' && (ref = this.peek(3), indexOf.call(C_LB + C_WS + '\x00', ref) >= 0)) { - return true; + check_document_start() { + var ref; + if (this.column === 0 && this.prefix(3) === '---' && (ref = this.peek(3), indexOf.call(C_LB + C_WS + '\x00', ref) >= 0)) { + return true; + } + return false; } - return false; - }; - /* - BLOCK-ENTRY: '-' (' '|'\n') - */ + /* + DOCUMENT-END: ^ '...' (' '|'\n') + */ - Scanner.prototype.check_block_entry = function() { - var ref; - return ref = this.peek(1), indexOf.call(C_LB + C_WS + '\x00', ref) >= 0; - }; + check_document_end() { + var ref; + if (this.column === 0 && this.prefix(3) === '...' && (ref = this.peek(3), indexOf.call(C_LB + C_WS + '\x00', ref) >= 0)) { + return true; + } + return false; + } - /* - KEY (flow context): '?' - KEY (block context): '?' (' '|'\n') - */ + /* + BLOCK-ENTRY: '-' (' '|'\n') + */ - Scanner.prototype.check_key = function() { - var ref; - if (this.flow_level !== 0) { - return true; + check_block_entry() { + var ref; + return ref = this.peek(1), indexOf.call(C_LB + C_WS + '\x00', ref) >= 0; } - return ref = this.peek(1), indexOf.call(C_LB + C_WS + '\x00', ref) >= 0; - }; - /* - VALUE (flow context): ':' - VALUE (block context): ':' (' '|'\n') - */ + /* + KEY (flow context): '?' + KEY (block context): '?' (' '|'\n') + */ - Scanner.prototype.check_value = function() { - var ref; - if (this.flow_level !== 0) { - return true; + check_key() { + var ref; + if (this.flow_level !== 0) { + return true; + } + return ref = this.peek(1), indexOf.call(C_LB + C_WS + '\x00', ref) >= 0; } - return ref = this.peek(1), indexOf.call(C_LB + C_WS + '\x00', ref) >= 0; - }; - - /* - A plain scalar may start with any non-space character except: - '-', '?', ':', ',', '[', ']', '{', '}', - '#', '&', '*', '!', '|', '>', '\'', '"', - '%', '@', '`'. - - It may also start with - '-', '?', ':' - if it is followed by a non-space character. - - Note that we limit the last rule to the block context (except the '-' - character) because we want the flow context to be space independent. - */ - - Scanner.prototype.check_plain = function() { - var char, ref; - char = this.peek(); - return indexOf.call(C_LB + C_WS + '\x00-?:,[]{}#&*!|>\'"%@`', char) < 0 || ((ref = this.peek(1), indexOf.call(C_LB + C_WS + '\x00', ref) < 0) && (char === '-' || (this.flow_level === 0 && indexOf.call('?:', char) >= 0))); - }; + /* + VALUE (flow context): ':' + VALUE (block context): ':' (' '|'\n') + */ - /* - We ignore spaces, line breaks and comments. - If we find a line break in the block context, we set the flag - `allow_simple_key` on. - The byte order mark is stripped if it's the first character in the stream. - We do not yet support BOM inside the stream as the specification requires. - Any such mark will be considered as a part of the document. - - TODO: We need to make tab handling rules more sane. A good rule is - Tabs cannot precede tokens BLOCK-SEQUENCE-START, BLOCK-MAPPING-START, - BLOCK-END, KEY (block context), VALUE (block context), BLOCK-ENTRY - So the tab checking code is - @allow_simple_key = off if - We also need to add the check for `allow_simple_key is on` to - `unwind_indent` before issuing BLOCK-END. Scanners for block, flow and - plain scalars need to be modified. - */ - - Scanner.prototype.scan_to_next_token = function() { - var found, ref, results; - if (this.index === 0 && this.peek() === '\uFEFF') { - this.forward(); - } - found = false; - results = []; - while (!found) { - while (this.peek() === ' ') { + check_value() { + var ref; + if (this.flow_level !== 0) { + return true; + } + return ref = this.peek(1), indexOf.call(C_LB + C_WS + '\x00', ref) >= 0; + } + + + /* + A plain scalar may start with any non-space character except: + '-', '?', ':', ',', '[', ']', '{', '}', + '#', '&', '*', '!', '|', '>', '\'', '"', + '%', '@', '`'. + + It may also start with + '-', '?', ':' + if it is followed by a non-space character. + + Note that we limit the last rule to the block context (except the '-' + character) because we want the flow context to be space independent. + */ + + check_plain() { + var char, ref; + char = this.peek(); + return indexOf.call(C_LB + C_WS + '\x00-?:,[]{}#&*!|>\'"%@`', char) < 0 || ((ref = this.peek(1), indexOf.call(C_LB + C_WS + '\x00', ref) < 0) && (char === '-' || (this.flow_level === 0 && indexOf.call('?:', char) >= 0))); + } + + + /* + We ignore spaces, line breaks and comments. + If we find a line break in the block context, we set the flag + `allow_simple_key` on. + The byte order mark is stripped if it's the first character in the stream. + We do not yet support BOM inside the stream as the specification requires. + Any such mark will be considered as a part of the document. + + TODO: We need to make tab handling rules more sane. A good rule is + Tabs cannot precede tokens BLOCK-SEQUENCE-START, BLOCK-MAPPING-START, + BLOCK-END, KEY (block context), VALUE (block context), BLOCK-ENTRY + So the tab checking code is + @allow_simple_key = off if + We also need to add the check for `allow_simple_key is on` to + `unwind_indent` before issuing BLOCK-END. Scanners for block, flow and + plain scalars need to be modified. + */ + + scan_to_next_token() { + var found, ref, results; + if (this.index === 0 && this.peek() === '\uFEFF') { this.forward(); } - if (this.peek() === '#') { - while (ref = this.peek(), indexOf.call(C_LB + '\x00', ref) < 0) { + found = false; + results = []; + while (!found) { + while (this.peek() === ' ') { this.forward(); } - } - if (this.scan_line_break()) { - if (this.flow_level === 0) { - results.push(this.allow_simple_key = true); + if (this.peek() === '#') { + while (ref = this.peek(), indexOf.call(C_LB + '\x00', ref) < 0) { + this.forward(); + } + } + if (this.scan_line_break()) { + if (this.flow_level === 0) { + results.push(this.allow_simple_key = true); + } else { + results.push(void 0); + } } else { - results.push(void 0); + results.push(found = true); } - } else { - results.push(found = true); } + return results; } - return results; - }; - /* - See the specification for details. - */ + /* + See the specification for details. + */ - Scanner.prototype.scan_directive = function() { - var end_mark, name, ref, start_mark, value; - start_mark = this.get_mark(); - this.forward(); - name = this.scan_directive_name(start_mark); - value = null; - if (name === 'YAML') { - value = this.scan_yaml_directive_value(start_mark); - end_mark = this.get_mark(); - } else if (name === 'TAG') { - value = this.scan_tag_directive_value(start_mark); - end_mark = this.get_mark(); - } else { - end_mark = this.get_mark(); - while (ref = this.peek(), indexOf.call(C_LB + '\x00', ref) < 0) { - this.forward(); + scan_directive() { + var end_mark, name, ref, start_mark, value; + start_mark = this.get_mark(); + this.forward(); + name = this.scan_directive_name(start_mark); + value = null; + if (name === 'YAML') { + value = this.scan_yaml_directive_value(start_mark); + end_mark = this.get_mark(); + } else if (name === 'TAG') { + value = this.scan_tag_directive_value(start_mark); + end_mark = this.get_mark(); + } else { + end_mark = this.get_mark(); + while (ref = this.peek(), indexOf.call(C_LB + '\x00', ref) < 0) { + this.forward(); + } } + this.scan_directive_ignored_line(start_mark); + return new tokens.DirectiveToken(name, value, start_mark, end_mark); } - this.scan_directive_ignored_line(start_mark); - return new tokens.DirectiveToken(name, value, start_mark, end_mark); - }; - /* - See the specification for details. - */ + /* + See the specification for details. + */ - Scanner.prototype.scan_directive_name = function(start_mark) { - var char, length, value; - length = 0; - char = this.peek(length); - while (('0' <= char && char <= '9') || ('A' <= char && char <= 'Z') || ('a' <= char && char <= 'z') || indexOf.call('-_', char) >= 0) { - length++; + scan_directive_name(start_mark) { + var char, length, value; + length = 0; char = this.peek(length); + while (('0' <= char && char <= '9') || ('A' <= char && char <= 'Z') || ('a' <= char && char <= 'z') || indexOf.call('-_', char) >= 0) { + length++; + char = this.peek(length); + } + if (length === 0) { + throw new exports.ScannerError('while scanning a directive', start_mark, `expected alphanumeric or numeric character but found ${char}`, this.get_mark()); + } + value = this.prefix(length); + this.forward(length); + char = this.peek(); + if (indexOf.call(C_LB + '\x00 ', char) < 0) { + throw new exports.ScannerError('while scanning a directive', start_mark, `expected alphanumeric or numeric character but found ${char}`, this.get_mark()); + } + return value; } - if (length === 0) { - throw new exports.ScannerError('while scanning a directive', start_mark, "expected alphanumeric or numeric character but found " + char, this.get_mark()); - } - value = this.prefix(length); - this.forward(length); - char = this.peek(); - if (indexOf.call(C_LB + '\x00 ', char) < 0) { - throw new exports.ScannerError('while scanning a directive', start_mark, "expected alphanumeric or numeric character but found " + char, this.get_mark()); - } - return value; - }; - /* - See the specification for details. - */ + /* + See the specification for details. + */ - Scanner.prototype.scan_yaml_directive_value = function(start_mark) { - var major, minor, ref; - while (this.peek() === ' ') { + scan_yaml_directive_value(start_mark) { + var major, minor, ref; + while (this.peek() === ' ') { + this.forward(); + } + major = this.scan_yaml_directive_number(start_mark); + if (this.peek() !== '.') { + throw new exports.ScannerError('while scanning a directive', start_mark, `expected a digit or '.' but found ${this.peek()}`, this.get_mark()); + } this.forward(); + minor = this.scan_yaml_directive_number(start_mark); + if (ref = this.peek(), indexOf.call(C_LB + '\x00 ', ref) < 0) { + throw new exports.ScannerError('while scanning a directive', start_mark, `expected a digit or ' ' but found ${this.peek()}`, this.get_mark()); + } + return [major, minor]; } - major = this.scan_yaml_directive_number(start_mark); - if (this.peek() !== '.') { - throw new exports.ScannerError('while scanning a directive', start_mark, "expected a digit or '.' but found " + (this.peek()), this.get_mark()); - } - this.forward(); - minor = this.scan_yaml_directive_number(start_mark); - if (ref = this.peek(), indexOf.call(C_LB + '\x00 ', ref) < 0) { - throw new exports.ScannerError('while scanning a directive', start_mark, "expected a digit or ' ' but found " + (this.peek()), this.get_mark()); - } - return [major, minor]; - }; - /* - See the specification for details. - */ + /* + See the specification for details. + */ - Scanner.prototype.scan_yaml_directive_number = function(start_mark) { - var char, length, ref, value; - char = this.peek(); - if (!(('0' <= char && char <= '9'))) { - throw new exports.ScannerError('while scanning a directive', start_mark, "expected a digit but found " + char, this.get_mark()); - } - length = 0; - while (('0' <= (ref = this.peek(length)) && ref <= '9')) { - length++; + scan_yaml_directive_number(start_mark) { + var char, length, ref, value; + char = this.peek(); + if (!(('0' <= char && char <= '9'))) { + throw new exports.ScannerError('while scanning a directive', start_mark, `expected a digit but found ${char}`, this.get_mark()); + } + length = 0; + while (('0' <= (ref = this.peek(length)) && ref <= '9')) { + length++; + } + value = parseInt(this.prefix(length)); + this.forward(length); + return value; } - value = parseInt(this.prefix(length)); - this.forward(length); - return value; - }; - /* - See the specification for details. - */ + /* + See the specification for details. + */ - Scanner.prototype.scan_tag_directive_value = function(start_mark) { - var handle, prefix; - while (this.peek() === ' ') { - this.forward(); - } - handle = this.scan_tag_directive_handle(start_mark); - while (this.peek() === ' ') { - this.forward(); + scan_tag_directive_value(start_mark) { + var handle, prefix; + while (this.peek() === ' ') { + this.forward(); + } + handle = this.scan_tag_directive_handle(start_mark); + while (this.peek() === ' ') { + this.forward(); + } + prefix = this.scan_tag_directive_prefix(start_mark); + return [handle, prefix]; } - prefix = this.scan_tag_directive_prefix(start_mark); - return [handle, prefix]; - }; - /* - See the specification for details. - */ + /* + See the specification for details. + */ - Scanner.prototype.scan_tag_directive_handle = function(start_mark) { - var char, value; - value = this.scan_tag_handle('directive', start_mark); - char = this.peek(); - if (char !== ' ') { - throw new exports.ScannerError('while scanning a directive', start_mark, "expected ' ' but found " + char, this.get_mark()); + scan_tag_directive_handle(start_mark) { + var char, value; + value = this.scan_tag_handle('directive', start_mark); + char = this.peek(); + if (char !== ' ') { + throw new exports.ScannerError('while scanning a directive', start_mark, `expected ' ' but found ${char}`, this.get_mark()); + } + return value; } - return value; - }; - /* - See the specification for details. - */ + /* + See the specification for details. + */ - Scanner.prototype.scan_tag_directive_prefix = function(start_mark) { - var char, value; - value = this.scan_tag_uri('directive', start_mark); - char = this.peek(); - if (indexOf.call(C_LB + '\x00 ', char) < 0) { - throw new exports.ScannerError('while scanning a directive', start_mark, "expected ' ' but found " + char, this.get_mark()); + scan_tag_directive_prefix(start_mark) { + var char, value; + value = this.scan_tag_uri('directive', start_mark); + char = this.peek(); + if (indexOf.call(C_LB + '\x00 ', char) < 0) { + throw new exports.ScannerError('while scanning a directive', start_mark, `expected ' ' but found ${char}`, this.get_mark()); + } + return value; } - return value; - }; - /* - See the specification for details. - */ + /* + See the specification for details. + */ - Scanner.prototype.scan_directive_ignored_line = function(start_mark) { - var char, ref; - while (this.peek() === ' ') { - this.forward(); - } - if (this.peek() === '#') { - while (ref = this.peek(), indexOf.call(C_LB + '\x00', ref) < 0) { + scan_directive_ignored_line(start_mark) { + var char, ref; + while (this.peek() === ' ') { this.forward(); } - } - char = this.peek(); - if (indexOf.call(C_LB + '\x00', char) < 0) { - throw new exports.ScannerError('while scanning a directive', start_mark, "expected a comment or a line break but found " + char, this.get_mark()); - } - return this.scan_line_break(); - }; - - - /* - The specification does not restrict characters for anchors and aliases. - This may lead to problems, for instance, the document: - [ *alias, value ] - can be interpteted in two ways, as - [ "value" ] - and - [ *alias , "value" ] - Therefore we restrict aliases to numbers and ASCII letters. - */ - - Scanner.prototype.scan_anchor = function(TokenClass) { - var char, indicator, length, name, start_mark, value; - start_mark = this.get_mark(); - indicator = this.peek(); - if (indicator === '*') { - name = 'alias'; - } else { - name = 'anchor'; - } - this.forward(); - length = 0; - char = this.peek(length); - while (('0' <= char && char <= '9') || ('A' <= char && char <= 'Z') || ('a' <= char && char <= 'z') || indexOf.call('-_', char) >= 0) { - length++; + if (this.peek() === '#') { + while (ref = this.peek(), indexOf.call(C_LB + '\x00', ref) < 0) { + this.forward(); + } + } + char = this.peek(); + if (indexOf.call(C_LB + '\x00', char) < 0) { + throw new exports.ScannerError('while scanning a directive', start_mark, `expected a comment or a line break but found ${char}`, this.get_mark()); + } + return this.scan_line_break(); + } + + + /* + The specification does not restrict characters for anchors and aliases. + This may lead to problems, for instance, the document: + [ *alias, value ] + can be interpteted in two ways, as + [ "value" ] + and + [ *alias , "value" ] + Therefore we restrict aliases to numbers and ASCII letters. + */ + + scan_anchor(TokenClass) { + var char, indicator, length, name, start_mark, value; + start_mark = this.get_mark(); + indicator = this.peek(); + if (indicator === '*') { + name = 'alias'; + } else { + name = 'anchor'; + } + this.forward(); + length = 0; char = this.peek(length); + while (('0' <= char && char <= '9') || ('A' <= char && char <= 'Z') || ('a' <= char && char <= 'z') || indexOf.call('-_', char) >= 0) { + length++; + char = this.peek(length); + } + if (length === 0) { + throw new exports.ScannerError(`while scanning an ${name}`, start_mark, `expected alphabetic or numeric character but found '${char}'`, this.get_mark()); + } + value = this.prefix(length); + this.forward(length); + char = this.peek(); + if (indexOf.call(C_LB + C_WS + '\x00' + '?:,]}%@`', char) < 0) { + throw new exports.ScannerError(`while scanning an ${name}`, start_mark, `expected alphabetic or numeric character but found '${char}'`, this.get_mark()); + } + return new TokenClass(value, start_mark, this.get_mark()); } - if (length === 0) { - throw new exports.ScannerError("while scanning an " + name, start_mark, "expected alphabetic or numeric character but found '" + char + "'", this.get_mark()); - } - value = this.prefix(length); - this.forward(length); - char = this.peek(); - if (indexOf.call(C_LB + C_WS + '\x00' + '?:,]}%@`', char) < 0) { - throw new exports.ScannerError("while scanning an " + name, start_mark, "expected alphabetic or numeric character but found '" + char + "'", this.get_mark()); - } - return new TokenClass(value, start_mark, this.get_mark()); - }; - /* - See the specification for details. - */ + /* + See the specification for details. + */ - Scanner.prototype.scan_tag = function() { - var char, handle, length, start_mark, suffix, use_handle; - start_mark = this.get_mark(); - char = this.peek(1); - if (char === '<') { - handle = null; - this.forward(2); - suffix = this.scan_tag_uri('tag', start_mark); - if (this.peek() !== '>') { - throw new exports.ScannerError('while parsing a tag', start_mark, "expected '>' but found " + (this.peek()), this.get_mark()); - } - this.forward(); - } else if (indexOf.call(C_LB + C_WS + '\x00', char) >= 0) { - handle = null; - suffix = '!'; - this.forward(); - } else { - length = 1; - use_handle = false; - while (indexOf.call(C_LB + '\x00 ', char) < 0) { - if (char === '!') { - use_handle = true; - break; + scan_tag() { + var char, handle, length, start_mark, suffix, use_handle; + start_mark = this.get_mark(); + char = this.peek(1); + if (char === '<') { + handle = null; + this.forward(2); + suffix = this.scan_tag_uri('tag', start_mark); + if (this.peek() !== '>') { + throw new exports.ScannerError('while parsing a tag', start_mark, `expected '>' but found ${this.peek()}`, this.get_mark()); } - length++; - char = this.peek(length); - } - if (use_handle) { - handle = this.scan_tag_handle('tag', start_mark); - } else { - handle = '!'; this.forward(); + } else if (indexOf.call(C_LB + C_WS + '\x00', char) >= 0) { + handle = null; + suffix = '!'; + this.forward(); + } else { + length = 1; + use_handle = false; + while (indexOf.call(C_LB + '\x00 ', char) < 0) { + if (char === '!') { + use_handle = true; + break; + } + length++; + char = this.peek(length); + } + if (use_handle) { + handle = this.scan_tag_handle('tag', start_mark); + } else { + handle = '!'; + this.forward(); + } + suffix = this.scan_tag_uri('tag', start_mark); } - suffix = this.scan_tag_uri('tag', start_mark); - } - char = this.peek(); - if (indexOf.call(C_LB + '\x00 ', char) < 0) { - throw new exports.ScannerError('while scanning a tag', start_mark, "expected ' ' but found " + char, this.get_mark()); + char = this.peek(); + if (indexOf.call(C_LB + '\x00 ', char) < 0) { + throw new exports.ScannerError('while scanning a tag', start_mark, `expected ' ' but found ${char}`, this.get_mark()); + } + return new tokens.TagToken([handle, suffix], start_mark, this.get_mark()); } - return new tokens.TagToken([handle, suffix], start_mark, this.get_mark()); - }; - /* - See the specification for details. - */ - - Scanner.prototype.scan_block_scalar = function(style) { - var breaks, chomping, chunks, end_mark, folded, increment, indent, leading_non_space, length, line_break, max_indent, min_indent, ref, ref1, ref2, ref3, ref4, ref5, ref6, start_mark; - folded = style === '>'; - chunks = []; - start_mark = this.get_mark(); - this.forward(); - ref = this.scan_block_scalar_indicators(start_mark), chomping = ref[0], increment = ref[1]; - this.scan_block_scalar_ignored_line(start_mark); - min_indent = this.indent + 1; - if (min_indent < 1) { - min_indent = 1; - } - if (increment == null) { - ref1 = this.scan_block_scalar_indentation(), breaks = ref1[0], max_indent = ref1[1], end_mark = ref1[2]; - indent = Math.max(min_indent, max_indent); - } else { - indent = min_indent + increment - 1; - ref2 = this.scan_block_scalar_breaks(indent), breaks = ref2[0], end_mark = ref2[1]; - } - line_break = ''; - while (this.column === indent && this.peek() !== '\x00') { - chunks = chunks.concat(breaks); - leading_non_space = (ref3 = this.peek(), indexOf.call(' \t', ref3) < 0); - length = 0; - while (ref4 = this.peek(length), indexOf.call(C_LB + '\x00', ref4) < 0) { - length++; + /* + See the specification for details. + */ + + scan_block_scalar(style) { + var breaks, chomping, chunks, end_mark, folded, increment, indent, leading_non_space, length, line_break, max_indent, min_indent, ref, ref1, ref2, ref3, ref4, ref5, ref6, start_mark; + folded = style === '>'; + chunks = []; + start_mark = this.get_mark(); + this.forward(); + ref = this.scan_block_scalar_indicators(start_mark), chomping = ref[0], increment = ref[1]; + this.scan_block_scalar_ignored_line(start_mark); + min_indent = this.indent + 1; + if (min_indent < 1) { + min_indent = 1; } - chunks.push(this.prefix(length)); - this.forward(length); - line_break = this.scan_line_break(); - ref5 = this.scan_block_scalar_breaks(indent), breaks = ref5[0], end_mark = ref5[1]; - if (this.column === indent && this.peek() !== '\x00') { - if (folded && line_break === '\n' && leading_non_space && (ref6 = this.peek(), indexOf.call(' \t', ref6) < 0)) { - if (util.is_empty(breaks)) { - chunks.push(' '); + if (increment == null) { + ref1 = this.scan_block_scalar_indentation(), breaks = ref1[0], max_indent = ref1[1], end_mark = ref1[2]; + indent = Math.max(min_indent, max_indent); + } else { + indent = min_indent + increment - 1; + ref2 = this.scan_block_scalar_breaks(indent), breaks = ref2[0], end_mark = ref2[1]; + } + line_break = ''; + while (this.column === indent && this.peek() !== '\x00') { + chunks = chunks.concat(breaks); + leading_non_space = (ref3 = this.peek(), indexOf.call(' \t', ref3) < 0); + length = 0; + while (ref4 = this.peek(length), indexOf.call(C_LB + '\x00', ref4) < 0) { + length++; + } + chunks.push(this.prefix(length)); + this.forward(length); + line_break = this.scan_line_break(); + ref5 = this.scan_block_scalar_breaks(indent), breaks = ref5[0], end_mark = ref5[1]; + if (this.column === indent && this.peek() !== '\x00') { + if (folded && line_break === '\n' && leading_non_space && (ref6 = this.peek(), indexOf.call(' \t', ref6) < 0)) { + if (util.is_empty(breaks)) { + chunks.push(' '); + } + } else { + chunks.push(line_break); } } else { - chunks.push(line_break); + break; } - } else { - break; } + if (chomping !== false) { + chunks.push(line_break); + } + if (chomping === true) { + chunks = chunks.concat(breaks); + } + return new tokens.ScalarToken(chunks.join(''), false, start_mark, end_mark, style); } - if (chomping !== false) { - chunks.push(line_break); - } - if (chomping === true) { - chunks = chunks.concat(breaks); - } - return new tokens.ScalarToken(chunks.join(''), false, start_mark, end_mark, style); - }; - /* - See the specification for details. - */ + /* + See the specification for details. + */ - Scanner.prototype.scan_block_scalar_indicators = function(start_mark) { - var char, chomping, increment; - chomping = null; - increment = null; - char = this.peek(); - if (indexOf.call('+-', char) >= 0) { - chomping = char === '+'; - this.forward(); + scan_block_scalar_indicators(start_mark) { + var char, chomping, increment; + chomping = null; + increment = null; char = this.peek(); - if (indexOf.call(C_NUMBERS, char) >= 0) { + if (indexOf.call('+-', char) >= 0) { + chomping = char === '+'; + this.forward(); + char = this.peek(); + if (indexOf.call(C_NUMBERS, char) >= 0) { + increment = parseInt(char); + if (increment === 0) { + throw new exports.ScannerError('while scanning a block scalar', start_mark, 'expected indentation indicator in the range 1-9 but found 0', this.get_mark()); + } + this.forward(); + } + } else if (indexOf.call(C_NUMBERS, char) >= 0) { increment = parseInt(char); if (increment === 0) { throw new exports.ScannerError('while scanning a block scalar', start_mark, 'expected indentation indicator in the range 1-9 but found 0', this.get_mark()); } this.forward(); + char = this.peek(); + if (indexOf.call('+-', char) >= 0) { + chomping = char === '+'; + this.forward(); + } } - } else if (indexOf.call(C_NUMBERS, char) >= 0) { - increment = parseInt(char); - if (increment === 0) { - throw new exports.ScannerError('while scanning a block scalar', start_mark, 'expected indentation indicator in the range 1-9 but found 0', this.get_mark()); - } - this.forward(); char = this.peek(); - if (indexOf.call('+-', char) >= 0) { - chomping = char === '+'; - this.forward(); + if (indexOf.call(C_LB + '\x00 ', char) < 0) { + throw new exports.ScannerError('while scanning a block scalar', start_mark, `expected chomping or indentation indicators, but found ${char}`, this.get_mark()); } + return [chomping, increment]; } - char = this.peek(); - if (indexOf.call(C_LB + '\x00 ', char) < 0) { - throw new exports.ScannerError('while scanning a block scalar', start_mark, "expected chomping or indentation indicators, but found " + char, this.get_mark()); - } - return [chomping, increment]; - }; - /* - See the specification for details. - */ + /* + See the specification for details. + */ - Scanner.prototype.scan_block_scalar_ignored_line = function(start_mark) { - var char, ref; - while (this.peek() === ' ') { - this.forward(); - } - if (this.peek() === '#') { - while (ref = this.peek(), indexOf.call(C_LB + '\x00', ref) < 0) { + scan_block_scalar_ignored_line(start_mark) { + var char, ref; + while (this.peek() === ' ') { this.forward(); } + if (this.peek() === '#') { + while (ref = this.peek(), indexOf.call(C_LB + '\x00', ref) < 0) { + this.forward(); + } + } + char = this.peek(); + if (indexOf.call(C_LB + '\x00', char) < 0) { + throw new exports.ScannerError('while scanning a block scalar', start_mark, `expected a comment or a line break but found ${char}`, this.get_mark()); + } + return this.scan_line_break(); } - char = this.peek(); - if (indexOf.call(C_LB + '\x00', char) < 0) { - throw new exports.ScannerError('while scanning a block scalar', start_mark, "expected a comment or a line break but found " + char, this.get_mark()); - } - return this.scan_line_break(); - }; - /* - See the specification for details. - */ + /* + See the specification for details. + */ - Scanner.prototype.scan_block_scalar_indentation = function() { - var chunks, end_mark, max_indent, ref; - chunks = []; - max_indent = 0; - end_mark = this.get_mark(); - while (ref = this.peek(), indexOf.call(C_LB + ' ', ref) >= 0) { - if (this.peek() !== ' ') { - chunks.push(this.scan_line_break()); - end_mark = this.get_mark(); - } else { - this.forward(); - if (this.column > max_indent) { - max_indent = this.column; + scan_block_scalar_indentation() { + var chunks, end_mark, max_indent, ref; + chunks = []; + max_indent = 0; + end_mark = this.get_mark(); + while (ref = this.peek(), indexOf.call(C_LB + ' ', ref) >= 0) { + if (this.peek() !== ' ') { + chunks.push(this.scan_line_break()); + end_mark = this.get_mark(); + } else { + this.forward(); + if (this.column > max_indent) { + max_indent = this.column; + } } } + return [chunks, max_indent, end_mark]; } - return [chunks, max_indent, end_mark]; - }; - /* - See the specification for details. - */ + /* + See the specification for details. + */ - Scanner.prototype.scan_block_scalar_breaks = function(indent) { - var chunks, end_mark, ref; - chunks = []; - end_mark = this.get_mark(); - while (this.column < indent && this.peek() === ' ') { - this.forward(); - } - while (ref = this.peek(), indexOf.call(C_LB, ref) >= 0) { - chunks.push(this.scan_line_break()); + scan_block_scalar_breaks(indent) { + var chunks, end_mark, ref; + chunks = []; end_mark = this.get_mark(); while (this.column < indent && this.peek() === ' ') { this.forward(); } + while (ref = this.peek(), indexOf.call(C_LB, ref) >= 0) { + chunks.push(this.scan_line_break()); + end_mark = this.get_mark(); + while (this.column < indent && this.peek() === ' ') { + this.forward(); + } + } + return [chunks, end_mark]; } - return [chunks, end_mark]; - }; - /* - See the specification for details. - Note that we loose indentation rules for quoted scalars. Quoted scalars - don't need to adhere indentation because " and ' clearly mark the beginning - and the end of them. Therefore we are less restrictive than the - specification requires. We only need to check that document separators are - not included in scalars. - */ - - Scanner.prototype.scan_flow_scalar = function(style) { - var chunks, double, quote, start_mark; - double = style === '"'; - chunks = []; - start_mark = this.get_mark(); - quote = this.peek(); - this.forward(); - chunks = chunks.concat(this.scan_flow_scalar_non_spaces(double, start_mark)); - while (this.peek() !== quote) { - chunks = chunks.concat(this.scan_flow_scalar_spaces(double, start_mark)); + /* + See the specification for details. + Note that we loose indentation rules for quoted scalars. Quoted scalars + don't need to adhere indentation because " and ' clearly mark the beginning + and the end of them. Therefore we are less restrictive than the + specification requires. We only need to check that document separators are + not included in scalars. + */ + + scan_flow_scalar(style) { + var chunks, double, quote, start_mark; + double = style === '"'; + chunks = []; + start_mark = this.get_mark(); + quote = this.peek(); + this.forward(); chunks = chunks.concat(this.scan_flow_scalar_non_spaces(double, start_mark)); + while (this.peek() !== quote) { + chunks = chunks.concat(this.scan_flow_scalar_spaces(double, start_mark)); + chunks = chunks.concat(this.scan_flow_scalar_non_spaces(double, start_mark)); + } + this.forward(); + return new tokens.ScalarToken(chunks.join(''), false, start_mark, this.get_mark(), style); } - this.forward(); - return new tokens.ScalarToken(chunks.join(''), false, start_mark, this.get_mark(), style); - }; - /* - See the specification for details. - */ + /* + See the specification for details. + */ - Scanner.prototype.scan_flow_scalar_non_spaces = function(double, start_mark) { - var char, chunks, code, i, k, length, ref, ref1, ref2; - chunks = []; - while (true) { - length = 0; - while (ref = this.peek(length), indexOf.call(C_LB + C_WS + '\'"\\\x00', ref) < 0) { - length++; - } - if (length !== 0) { - chunks.push(this.prefix(length)); - this.forward(length); - } - char = this.peek(); - if (!double && char === '\'' && this.peek(1) === '\'') { - chunks.push('\''); - this.forward(2); - } else if ((double && char === '\'') || (!double && indexOf.call('"\\', char) >= 0)) { - chunks.push(char); - this.forward(); - } else if (double && char === '\\') { - this.forward(); + scan_flow_scalar_non_spaces(double, start_mark) { + var char, chunks, code, i, k, length, ref, ref1, ref2; + chunks = []; + while (true) { + length = 0; + while (ref = this.peek(length), indexOf.call(C_LB + C_WS + '\'"\\\x00', ref) < 0) { + length++; + } + if (length !== 0) { + chunks.push(this.prefix(length)); + this.forward(length); + } char = this.peek(); - if (char in ESCAPE_REPLACEMENTS) { - chunks.push(ESCAPE_REPLACEMENTS[char]); + if (!double && char === '\'' && this.peek(1) === '\'') { + chunks.push('\''); + this.forward(2); + } else if ((double && char === '\'') || (!double && indexOf.call('"\\', char) >= 0)) { + chunks.push(char); this.forward(); - } else if (char in ESCAPE_CODES) { - length = ESCAPE_CODES[char]; + } else if (double && char === '\\') { this.forward(); - for (k = i = 0, ref1 = length; 0 <= ref1 ? i < ref1 : i > ref1; k = 0 <= ref1 ? ++i : --i) { - if (ref2 = this.peek(k), indexOf.call(C_NUMBERS + "ABCDEFabcdef", ref2) < 0) { - throw new exports.ScannerError('while scanning a double-quoted scalar', start_mark, "expected escape sequence of " + length + " hexadecimal numbers, but found " + (this.peek(k)), this.get_mark()); + char = this.peek(); + if (char in ESCAPE_REPLACEMENTS) { + chunks.push(ESCAPE_REPLACEMENTS[char]); + this.forward(); + } else if (char in ESCAPE_CODES) { + length = ESCAPE_CODES[char]; + this.forward(); + for (k = i = 0, ref1 = length; 0 <= ref1 ? i < ref1 : i > ref1; k = 0 <= ref1 ? ++i : --i) { + if (ref2 = this.peek(k), indexOf.call(`${C_NUMBERS}ABCDEFabcdef`, ref2) < 0) { + throw new exports.ScannerError('while scanning a double-quoted scalar', start_mark, `expected escape sequence of ${length} hexadecimal numbers, but found ${this.peek(k)}`, this.get_mark()); + } } + code = parseInt(this.prefix(length), 16); + chunks.push(String.fromCharCode(code)); + this.forward(length); + } else if (indexOf.call(C_LB, char) >= 0) { + this.scan_line_break(); + chunks = chunks.concat(this.scan_flow_scalar_breaks(double, start_mark)); + } else { + throw new exports.ScannerError('while scanning a double-quoted scalar', start_mark, `found unknown escape character ${char}`, this.get_mark()); } - code = parseInt(this.prefix(length), 16); - chunks.push(String.fromCharCode(code)); - this.forward(length); - } else if (indexOf.call(C_LB, char) >= 0) { - this.scan_line_break(); - chunks = chunks.concat(this.scan_flow_scalar_breaks(double, start_mark)); } else { - throw new exports.ScannerError('while scanning a double-quoted scalar', start_mark, "found unknown escape character " + char, this.get_mark()); + return chunks; } - } else { - return chunks; } } - }; - /* - See the specification for details. - */ + /* + See the specification for details. + */ - Scanner.prototype.scan_flow_scalar_spaces = function(double, start_mark) { - var breaks, char, chunks, length, line_break, ref, whitespaces; - chunks = []; - length = 0; - while (ref = this.peek(length), indexOf.call(C_WS, ref) >= 0) { - length++; - } - whitespaces = this.prefix(length); - this.forward(length); - char = this.peek(); - if (char === '\x00') { - throw new exports.ScannerError('while scanning a quoted scalar', start_mark, 'found unexpected end of stream', this.get_mark()); - } - if (indexOf.call(C_LB, char) >= 0) { - line_break = this.scan_line_break(); - breaks = this.scan_flow_scalar_breaks(double, start_mark); - if (line_break !== '\n') { - chunks.push(line_break); - } else if (breaks.length === 0) { - chunks.push(' '); + scan_flow_scalar_spaces(double, start_mark) { + var breaks, char, chunks, length, line_break, ref, whitespaces; + chunks = []; + length = 0; + while (ref = this.peek(length), indexOf.call(C_WS, ref) >= 0) { + length++; } - chunks = chunks.concat(breaks); - } else { - chunks.push(whitespaces); + whitespaces = this.prefix(length); + this.forward(length); + char = this.peek(); + if (char === '\x00') { + throw new exports.ScannerError('while scanning a quoted scalar', start_mark, 'found unexpected end of stream', this.get_mark()); + } + if (indexOf.call(C_LB, char) >= 0) { + line_break = this.scan_line_break(); + breaks = this.scan_flow_scalar_breaks(double, start_mark); + if (line_break !== '\n') { + chunks.push(line_break); + } else if (breaks.length === 0) { + chunks.push(' '); + } + chunks = chunks.concat(breaks); + } else { + chunks.push(whitespaces); + } + return chunks; } - return chunks; - }; - /* - See the specification for details. - */ + /* + See the specification for details. + */ - Scanner.prototype.scan_flow_scalar_breaks = function(double, start_mark) { - var chunks, prefix, ref, ref1, ref2; - chunks = []; - while (true) { - prefix = this.prefix(3); - if (prefix === '---' || prefix === '...' && (ref = this.peek(3), indexOf.call(C_LB + C_WS + '\x00', ref) >= 0)) { - throw new exports.ScannerError('while scanning a quoted scalar', start_mark, 'found unexpected document separator', this.get_mark()); - } - while (ref1 = this.peek(), indexOf.call(C_WS, ref1) >= 0) { - this.forward(); - } - if (ref2 = this.peek(), indexOf.call(C_LB, ref2) >= 0) { - chunks.push(this.scan_line_break()); - } else { - return chunks; + scan_flow_scalar_breaks(double, start_mark) { + var chunks, prefix, ref, ref1, ref2; + chunks = []; + while (true) { + prefix = this.prefix(3); + if (prefix === '---' || prefix === '...' && (ref = this.peek(3), indexOf.call(C_LB + C_WS + '\x00', ref) >= 0)) { + throw new exports.ScannerError('while scanning a quoted scalar', start_mark, 'found unexpected document separator', this.get_mark()); + } + while (ref1 = this.peek(), indexOf.call(C_WS, ref1) >= 0) { + this.forward(); + } + if (ref2 = this.peek(), indexOf.call(C_LB, ref2) >= 0) { + chunks.push(this.scan_line_break()); + } else { + return chunks; + } } } - }; - /* - See the specification for details. - We add an additional restriction for the flow context: - plain scalars in the flow context cannot contain ',', ':' and '?'. - We also keep track of the `allow_simple_key` flag here. - Indentation rules are loosed for the flow context. - */ - - Scanner.prototype.scan_plain = function() { - var char, chunks, end_mark, indent, length, ref, ref1, spaces, start_mark; - chunks = []; - start_mark = end_mark = this.get_mark(); - indent = this.indent + 1; - spaces = []; - while (true) { - length = 0; - if (this.peek() === '#') { - break; - } + /* + See the specification for details. + We add an additional restriction for the flow context: + plain scalars in the flow context cannot contain ',', ':' and '?'. + We also keep track of the `allow_simple_key` flag here. + Indentation rules are loosed for the flow context. + */ + + scan_plain() { + var char, chunks, end_mark, indent, length, ref, ref1, spaces, start_mark; + chunks = []; + start_mark = end_mark = this.get_mark(); + indent = this.indent + 1; + spaces = []; while (true) { - char = this.peek(length); - if (indexOf.call(C_LB + C_WS + '\x00', char) >= 0 || (this.flow_level === 0 && char === ':' && (ref = this.peek(length + 1), indexOf.call(C_LB + C_WS + '\x00', ref) >= 0)) || (this.flow_level !== 0 && indexOf.call(',:?[]{}', char) >= 0)) { + length = 0; + if (this.peek() === '#') { break; } - length++; - } - if (this.flow_level !== 0 && char === ':' && (ref1 = this.peek(length + 1), indexOf.call(C_LB + C_WS + '\x00,[]{}', ref1) < 0)) { + while (true) { + char = this.peek(length); + if (indexOf.call(C_LB + C_WS + '\x00', char) >= 0 || (this.flow_level === 0 && char === ':' && (ref = this.peek(length + 1), indexOf.call(C_LB + C_WS + '\x00', ref) >= 0)) || (this.flow_level !== 0 && indexOf.call(',:?[]{}', char) >= 0)) { + break; + } + length++; + } + if (this.flow_level !== 0 && char === ':' && (ref1 = this.peek(length + 1), indexOf.call(C_LB + C_WS + '\x00,[]{}', ref1) < 0)) { + this.forward(length); + throw new exports.ScannerError('while scanning a plain scalar', start_mark, 'found unexpected \':\'', this.get_mark(), 'Please check http://pyyaml.org/wiki/YAMLColonInFlowContext'); + } + if (length === 0) { + break; + } + this.allow_simple_key = false; + chunks = chunks.concat(spaces); + chunks.push(this.prefix(length)); this.forward(length); - throw new exports.ScannerError('while scanning a plain scalar', start_mark, 'found unexpected \':\'', this.get_mark(), 'Please check http://pyyaml.org/wiki/YAMLColonInFlowContext'); - } - if (length === 0) { - break; - } - this.allow_simple_key = false; - chunks = chunks.concat(spaces); - chunks.push(this.prefix(length)); - this.forward(length); - end_mark = this.get_mark(); - spaces = this.scan_plain_spaces(indent, start_mark); - if ((spaces == null) || spaces.length === 0 || this.peek() === '#' || (this.flow_level === 0 && this.column < indent)) { - break; + end_mark = this.get_mark(); + spaces = this.scan_plain_spaces(indent, start_mark); + if ((spaces == null) || spaces.length === 0 || this.peek() === '#' || (this.flow_level === 0 && this.column < indent)) { + break; + } } + return new tokens.ScalarToken(chunks.join(''), true, start_mark, end_mark); } - return new tokens.ScalarToken(chunks.join(''), true, start_mark, end_mark); - }; - /* - See the specification for details. - The specification is really confusing about tabs in plain scalars. - We just forbid them completely. Do not use tabs in YAML! - */ - - Scanner.prototype.scan_plain_spaces = function(indent, start_mark) { - var breaks, char, chunks, length, line_break, prefix, ref, ref1, ref2, ref3, whitespaces; - chunks = []; - length = 0; - while (ref = this.peek(length), indexOf.call(' ', ref) >= 0) { - length++; - } - whitespaces = this.prefix(length); - this.forward(length); - char = this.peek(); - if (indexOf.call(C_LB, char) >= 0) { - line_break = this.scan_line_break(); - this.allow_simple_key = true; - prefix = this.prefix(3); - if (prefix === '---' || prefix === '...' && (ref1 = this.peek(3), indexOf.call(C_LB + C_WS + '\x00', ref1) >= 0)) { - return; + /* + See the specification for details. + The specification is really confusing about tabs in plain scalars. + We just forbid them completely. Do not use tabs in YAML! + */ + + scan_plain_spaces(indent, start_mark) { + var breaks, char, chunks, length, line_break, prefix, ref, ref1, ref2, ref3, whitespaces; + chunks = []; + length = 0; + while (ref = this.peek(length), indexOf.call(' ', ref) >= 0) { + length++; } - breaks = []; - while (ref3 = this.peek(), indexOf.call(C_LB + ' ', ref3) >= 0) { - if (this.peek() === ' ') { - this.forward(); - } else { - breaks.push(this.scan_line_break()); - prefix = this.prefix(3); - if (prefix === '---' || prefix === '...' && (ref2 = this.peek(3), indexOf.call(C_LB + C_WS + '\x00', ref2) >= 0)) { - return; + whitespaces = this.prefix(length); + this.forward(length); + char = this.peek(); + if (indexOf.call(C_LB, char) >= 0) { + line_break = this.scan_line_break(); + this.allow_simple_key = true; + prefix = this.prefix(3); + if (prefix === '---' || prefix === '...' && (ref1 = this.peek(3), indexOf.call(C_LB + C_WS + '\x00', ref1) >= 0)) { + return; + } + breaks = []; + while (ref3 = this.peek(), indexOf.call(C_LB + ' ', ref3) >= 0) { + if (this.peek() === ' ') { + this.forward(); + } else { + breaks.push(this.scan_line_break()); + prefix = this.prefix(3); + if (prefix === '---' || prefix === '...' && (ref2 = this.peek(3), indexOf.call(C_LB + C_WS + '\x00', ref2) >= 0)) { + return; + } } } + if (line_break !== '\n') { + chunks.push(line_break); + } else if (breaks.length === 0) { + chunks.push(' '); + } + chunks = chunks.concat(breaks); + } else if (whitespaces) { + chunks.push(whitespaces); } - if (line_break !== '\n') { - chunks.push(line_break); - } else if (breaks.length === 0) { - chunks.push(' '); - } - chunks = chunks.concat(breaks); - } else if (whitespaces) { - chunks.push(whitespaces); + return chunks; } - return chunks; - }; - /* - See the specification for details. - For some strange reasons, the specification does not allow '_' in tag - handles. I have allowed it anyway. - */ + /* + See the specification for details. + For some strange reasons, the specification does not allow '_' in tag + handles. I have allowed it anyway. + */ - Scanner.prototype.scan_tag_handle = function(name, start_mark) { - var char, length, value; - char = this.peek(); - if (char !== '!') { - throw new exports.ScannerError("while scanning a " + name, start_mark, "expected '!' but found " + char, this.get_mark()); - } - length = 1; - char = this.peek(length); - if (char !== ' ') { - while (('0' <= char && char <= '9') || ('A' <= char && char <= 'Z') || ('a' <= char && char <= 'z') || indexOf.call('-_', char) >= 0) { - length++; - char = this.peek(length); - } + scan_tag_handle(name, start_mark) { + var char, length, value; + char = this.peek(); if (char !== '!') { - this.forward(length); - throw new exports.ScannerError("while scanning a " + name, start_mark, "expected '!' but found " + char, this.get_mark()); + throw new exports.ScannerError(`while scanning a ${name}`, start_mark, `expected '!' but found ${char}`, this.get_mark()); + } + length = 1; + char = this.peek(length); + if (char !== ' ') { + while (('0' <= char && char <= '9') || ('A' <= char && char <= 'Z') || ('a' <= char && char <= 'z') || indexOf.call('-_', char) >= 0) { + length++; + char = this.peek(length); + } + if (char !== '!') { + this.forward(length); + throw new exports.ScannerError(`while scanning a ${name}`, start_mark, `expected '!' but found ${char}`, this.get_mark()); + } + length++; } - length++; + value = this.prefix(length); + this.forward(length); + return value; } - value = this.prefix(length); - this.forward(length); - return value; - }; - /* - See the specification for details. - Note: we do not check if URI is well-formed. - */ + /* + See the specification for details. + Note: we do not check if URI is well-formed. + */ - Scanner.prototype.scan_tag_uri = function(name, start_mark) { - var char, chunks, length; - chunks = []; - length = 0; - char = this.peek(length); - while (('0' <= char && char <= '9') || ('A' <= char && char <= 'Z') || ('a' <= char && char <= 'z') || indexOf.call('-;/?:@&=+$,_.!~*\'()[]%', char) >= 0) { - if (char === '%') { + scan_tag_uri(name, start_mark) { + var char, chunks, length; + chunks = []; + length = 0; + char = this.peek(length); + while (('0' <= char && char <= '9') || ('A' <= char && char <= 'Z') || ('a' <= char && char <= 'z') || indexOf.call('-;/?:@&=+$,_.!~*\'()[]%', char) >= 0) { + if (char === '%') { + chunks.push(this.prefix(length)); + this.forward(length); + length = 0; + chunks.push(this.scan_uri_escapes(name, start_mark)); + } else { + length++; + } + char = this.peek(length); + } + if (length !== 0) { chunks.push(this.prefix(length)); this.forward(length); length = 0; - chunks.push(this.scan_uri_escapes(name, start_mark)); - } else { - length++; } - char = this.peek(length); - } - if (length !== 0) { - chunks.push(this.prefix(length)); - this.forward(length); - length = 0; - } - if (chunks.length === 0) { - throw new exports.ScannerError("while parsing a " + name, start_mark, "expected URI but found " + char, this.get_mark()); + if (chunks.length === 0) { + throw new exports.ScannerError(`while parsing a ${name}`, start_mark, `expected URI but found ${char}`, this.get_mark()); + } + return chunks.join(''); } - return chunks.join(''); - }; - /* - See the specification for details. - */ + /* + See the specification for details. + */ - Scanner.prototype.scan_uri_escapes = function(name, start_mark) { - var bytes, i, k, mark; - bytes = []; - mark = this.get_mark(); - while (this.peek() === '%') { - this.forward(); - for (k = i = 0; i <= 2; k = ++i) { - throw new exports.ScannerError("while scanning a " + name, start_mark, "expected URI escape sequence of 2 hexadecimal numbers but found " + (this.peek(k)), this.get_mark()); + scan_uri_escapes(name, start_mark) { + var bytes, i, k, mark; + bytes = []; + mark = this.get_mark(); + while (this.peek() === '%') { + this.forward(); + for (k = i = 0; i <= 2; k = ++i) { + throw new exports.ScannerError(`while scanning a ${name}`, start_mark, `expected URI escape sequence of 2 hexadecimal numbers but found ${this.peek(k)}`, this.get_mark()); + } + bytes.push(String.fromCharCode(parseInt(this.prefix(2), 16))); + this.forward(2); } - bytes.push(String.fromCharCode(parseInt(this.prefix(2), 16))); - this.forward(2); + return bytes.join(''); } - return bytes.join(''); - }; - /* - Transforms: - '\r\n' : '\n' - '\r' : '\n' - '\n' : '\n' - '\x85' : '\n' - '\u2028' : '\u2028' - '\u2029 : '\u2029' - default : '' - */ - - Scanner.prototype.scan_line_break = function() { - var char; - char = this.peek(); - if (indexOf.call('\r\n\x85', char) >= 0) { - if (this.prefix(2) === '\r\n') { - this.forward(2); - } else { + /* + Transforms: + '\r\n' : '\n' + '\r' : '\n' + '\n' : '\n' + '\x85' : '\n' + '\u2028' : '\u2028' + '\u2029 : '\u2029' + default : '' + */ + + scan_line_break() { + var char; + char = this.peek(); + if (indexOf.call('\r\n\x85', char) >= 0) { + if (this.prefix(2) === '\r\n') { + this.forward(2); + } else { + this.forward(); + } + return '\n'; + } else if (indexOf.call('\u2028\u2029', char) >= 0) { this.forward(); + return char; } - return '\n'; - } else if (indexOf.call('\u2028\u2029', char) >= 0) { - this.forward(); - return char; + return ''; } - return ''; + + }; + + C_LB = '\r\n\x85\u2028\u2029'; + + C_WS = '\t '; + + C_NUMBERS = '0123456789'; + + ESCAPE_REPLACEMENTS = { + '0': '\x00', + 'a': '\x07', + 'b': '\x08', + 't': '\x09', + '\t': '\x09', + 'n': '\x0A', + 'v': '\x0B', + 'f': '\x0C', + 'r': '\x0D', + 'e': '\x1B', + ' ': '\x20', + '"': '"', + '\\': '\\', + 'N': '\x85', + '_': '\xA0', + 'L': '\u2028', + 'P': '\u2029' }; + ESCAPE_CODES = { + 'x': 2, + 'u': 4, + 'U': 8 + }; + + ctor = Scanner.prototype.initialise; + return Scanner; })(); diff --git a/lib/serializer.js b/lib/serializer.js index 467b833..395bf55 100644 --- a/lib/serializer.js +++ b/lib/serializer.js @@ -1,7 +1,5 @@ (function() { - var YAMLError, events, nodes, util, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty; + var YAMLError, events, nodes, util; events = require('./events'); @@ -12,131 +10,145 @@ YAMLError = require('./errors').YAMLError; this.SerializerError = (function(superClass) { - extend(SerializerError, superClass); + class SerializerError extends superClass {}; - function SerializerError() { - return SerializerError.__super__.constructor.apply(this, arguments); - } + SerializerError.__super__ = superClass.prototype; return SerializerError; })(YAMLError); this.Serializer = (function() { - function Serializer(arg) { - var ref; - ref = arg != null ? arg : {}, this.encoding = ref.encoding, this.explicit_start = ref.explicit_start, this.explicit_end = ref.explicit_end, this.version = ref.version, this.tags = ref.tags; - this.serialized_nodes = {}; - this.anchors = {}; - this.last_anchor_id = 0; - this.closed = null; - } - - Serializer.prototype.open = function() { - if (this.closed === null) { - this.emit(new events.StreamStartEvent(this.encoding)); - return this.closed = false; - } else if (this.closed) { - throw new SerializerError('serializer is closed'); - } else { - throw new SerializerError('serializer is already open'); + var ctor; + + class Serializer { + constructor() { + return ctor.apply(this, arguments); } - }; - Serializer.prototype.close = function() { - if (this.closed === null) { - throw new SerializerError('serializer is not opened'); - } else if (!this.closed) { - this.emit(new events.StreamEndEvent); - return this.closed = true; + initialise(arg) { + var arg, encoding, explicit_end, explicit_start, ref, tags, version; + ref = arg != null ? arg : {}, encoding = ref.encoding, explicit_start = ref.explicit_start, explicit_end = ref.explicit_end, version = ref.version, tags = ref.tags; + this.encoding = encoding; + this.explicit_start = explicit_start; + this.explicit_end = explicit_end; + this.version = version; + this.tags = tags; + this.serialized_nodes = {}; + this.anchors = {}; + this.last_anchor_id = 0; + return this.closed = null; } - }; - Serializer.prototype.serialize = function(node) { - if (this.closed === null) { - throw new SerializerError('serializer is not opened'); - } else if (this.closed) { - throw new SerializerError('serializer is closed'); + open() { + if (this.closed === null) { + this.emit(new events.StreamStartEvent(this.encoding)); + return this.closed = false; + } else if (this.closed) { + throw new SerializerError('serializer is closed'); + } else { + throw new SerializerError('serializer is already open'); + } } - if (node != null) { - this.emit(new events.DocumentStartEvent(void 0, void 0, this.explicit_start, this.version, this.tags)); - this.anchor_node(node); - this.serialize_node(node); - this.emit(new events.DocumentEndEvent(void 0, void 0, this.explicit_end)); + + close() { + if (this.closed === null) { + throw new SerializerError('serializer is not opened'); + } else if (!this.closed) { + this.emit(new events.StreamEndEvent); + return this.closed = true; + } } - this.serialized_nodes = {}; - this.anchors = {}; - return this.last_anchor_id = 0; - }; - Serializer.prototype.anchor_node = function(node) { - var base, i, item, j, key, len, len1, name, ref, ref1, ref2, results, results1, value; - if (node.unique_id in this.anchors) { - return (base = this.anchors)[name = node.unique_id] != null ? base[name] : base[name] = this.generate_anchor(node); - } else { - this.anchors[node.unique_id] = null; - if (node instanceof nodes.SequenceNode) { - ref = node.value; - results = []; - for (i = 0, len = ref.length; i < len; i++) { - item = ref[i]; - results.push(this.anchor_node(item)); - } - return results; - } else if (node instanceof nodes.MappingNode) { - ref1 = node.value; - results1 = []; - for (j = 0, len1 = ref1.length; j < len1; j++) { - ref2 = ref1[j], key = ref2[0], value = ref2[1]; - this.anchor_node(key); - results1.push(this.anchor_node(value)); + serialize(node) { + if (this.closed === null) { + throw new SerializerError('serializer is not opened'); + } else if (this.closed) { + throw new SerializerError('serializer is closed'); + } + if (node != null) { + this.emit(new events.DocumentStartEvent(void 0, void 0, this.explicit_start, this.version, this.tags)); + this.anchor_node(node); + this.serialize_node(node); + this.emit(new events.DocumentEndEvent(void 0, void 0, this.explicit_end)); + } + this.serialized_nodes = {}; + this.anchors = {}; + return this.last_anchor_id = 0; + } + + anchor_node(node) { + var base, i, item, j, key, len, len1, name, ref, ref1, ref2, results, results1, value; + if (node.unique_id in this.anchors) { + return (base = this.anchors)[name = node.unique_id] != null ? base[name] : base[name] = this.generate_anchor(node); + } else { + this.anchors[node.unique_id] = null; + if (node instanceof nodes.SequenceNode) { + ref = node.value; + results = []; + for (i = 0, len = ref.length; i < len; i++) { + item = ref[i]; + results.push(this.anchor_node(item)); + } + return results; + } else if (node instanceof nodes.MappingNode) { + ref1 = node.value; + results1 = []; + for (j = 0, len1 = ref1.length; j < len1; j++) { + ref2 = ref1[j], key = ref2[0], value = ref2[1]; + this.anchor_node(key); + results1.push(this.anchor_node(value)); + } + return results1; } - return results1; } } - }; - Serializer.prototype.generate_anchor = function(node) { - return "id" + (util.pad_left(++this.last_anchor_id, '0', 4)); - }; + generate_anchor(node) { + return `id${util.pad_left(++this.last_anchor_id, '0', 4)}`; + } - Serializer.prototype.serialize_node = function(node, parent, index) { - var alias, default_tag, detected_tag, i, implicit, item, j, key, len, len1, ref, ref1, ref2, value; - alias = this.anchors[node.unique_id]; - if (node.unique_id in this.serialized_nodes) { - return this.emit(new events.AliasEvent(alias)); - } else { - this.serialized_nodes[node.unique_id] = true; - this.descend_resolver(parent, index); - if (node instanceof nodes.ScalarNode) { - detected_tag = this.resolve(nodes.ScalarNode, node.value, [true, false]); - default_tag = this.resolve(nodes.ScalarNode, node.value, [false, true]); - implicit = [node.tag === detected_tag, node.tag === default_tag]; - this.emit(new events.ScalarEvent(alias, node.tag, implicit, node.value, void 0, void 0, node.style)); - } else if (node instanceof nodes.SequenceNode) { - implicit = node.tag === this.resolve(nodes.SequenceNode, node.value, true); - this.emit(new events.SequenceStartEvent(alias, node.tag, implicit, void 0, void 0, node.flow_style)); - ref = node.value; - for (index = i = 0, len = ref.length; i < len; index = ++i) { - item = ref[index]; - this.serialize_node(item, node, index); - } - this.emit(new events.SequenceEndEvent); - } else if (node instanceof nodes.MappingNode) { - implicit = node.tag === this.resolve(nodes.MappingNode, node.value, true); - this.emit(new events.MappingStartEvent(alias, node.tag, implicit, void 0, void 0, node.flow_style)); - ref1 = node.value; - for (j = 0, len1 = ref1.length; j < len1; j++) { - ref2 = ref1[j], key = ref2[0], value = ref2[1]; - this.serialize_node(key, node, null); - this.serialize_node(value, node, key); + serialize_node(node, parent, index) { + var alias, default_tag, detected_tag, i, implicit, item, j, key, len, len1, ref, ref1, ref2, value; + alias = this.anchors[node.unique_id]; + if (node.unique_id in this.serialized_nodes) { + return this.emit(new events.AliasEvent(alias)); + } else { + this.serialized_nodes[node.unique_id] = true; + this.descend_resolver(parent, index); + if (node instanceof nodes.ScalarNode) { + detected_tag = this.resolve(nodes.ScalarNode, node.value, [true, false]); + default_tag = this.resolve(nodes.ScalarNode, node.value, [false, true]); + implicit = [node.tag === detected_tag, node.tag === default_tag]; + this.emit(new events.ScalarEvent(alias, node.tag, implicit, node.value, void 0, void 0, node.style)); + } else if (node instanceof nodes.SequenceNode) { + implicit = node.tag === this.resolve(nodes.SequenceNode, node.value, true); + this.emit(new events.SequenceStartEvent(alias, node.tag, implicit, void 0, void 0, node.flow_style)); + ref = node.value; + for (index = i = 0, len = ref.length; i < len; index = ++i) { + item = ref[index]; + this.serialize_node(item, node, index); + } + this.emit(new events.SequenceEndEvent); + } else if (node instanceof nodes.MappingNode) { + implicit = node.tag === this.resolve(nodes.MappingNode, node.value, true); + this.emit(new events.MappingStartEvent(alias, node.tag, implicit, void 0, void 0, node.flow_style)); + ref1 = node.value; + for (j = 0, len1 = ref1.length; j < len1; j++) { + ref2 = ref1[j], key = ref2[0], value = ref2[1]; + this.serialize_node(key, node, null); + this.serialize_node(value, node, key); + } + this.emit(new events.MappingEndEvent); } - this.emit(new events.MappingEndEvent); + return this.ascend_resolver(); } - return this.ascend_resolver(); } + }; + ctor = Serializer.prototype.initialise; + return Serializer; })(); diff --git a/lib/tokens.js b/lib/tokens.js index 02c834f..1fb184f 100644 --- a/lib/tokens.js +++ b/lib/tokens.js @@ -1,39 +1,34 @@ (function() { - var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty; - - this.Token = (function() { - function Token(start_mark, end_mark) { - this.start_mark = start_mark; - this.end_mark = end_mark; + this.Token = class Token { + constructor(start_mark1, end_mark1) { + this.start_mark = start_mark1; + this.end_mark = end_mark1; } - return Token; - - })(); + }; this.DirectiveToken = (function(superClass) { - extend(DirectiveToken, superClass); + class DirectiveToken extends superClass { + constructor(name, value, start_mark, end_mark) { + super(start_mark, end_mark); + this.name = name; + this.value = value; + } - DirectiveToken.prototype.id = ''; + }; - function DirectiveToken(name, value, start_mark, end_mark) { - this.name = name; - this.value = value; - this.start_mark = start_mark; - this.end_mark = end_mark; - } + DirectiveToken.__super__ = superClass.prototype; + + DirectiveToken.prototype.id = ''; return DirectiveToken; })(this.Token); this.DocumentStartToken = (function(superClass) { - extend(DocumentStartToken, superClass); + class DocumentStartToken extends superClass {}; - function DocumentStartToken() { - return DocumentStartToken.__super__.constructor.apply(this, arguments); - } + DocumentStartToken.__super__ = superClass.prototype; DocumentStartToken.prototype.id = ''; @@ -42,11 +37,9 @@ })(this.Token); this.DocumentEndToken = (function(superClass) { - extend(DocumentEndToken, superClass); + class DocumentEndToken extends superClass {}; - function DocumentEndToken() { - return DocumentEndToken.__super__.constructor.apply(this, arguments); - } + DocumentEndToken.__super__ = superClass.prototype; DocumentEndToken.prototype.id = ''; @@ -55,26 +48,26 @@ })(this.Token); this.StreamStartToken = (function(superClass) { - extend(StreamStartToken, superClass); + class StreamStartToken extends superClass { + constructor(start_mark, end_mark, encoding) { + super(start_mark, end_mark); + this.encoding = encoding; + } - StreamStartToken.prototype.id = ''; + }; - function StreamStartToken(start_mark, end_mark, encoding) { - this.start_mark = start_mark; - this.end_mark = end_mark; - this.encoding = encoding; - } + StreamStartToken.__super__ = superClass.prototype; + + StreamStartToken.prototype.id = ''; return StreamStartToken; })(this.Token); this.StreamEndToken = (function(superClass) { - extend(StreamEndToken, superClass); + class StreamEndToken extends superClass {}; - function StreamEndToken() { - return StreamEndToken.__super__.constructor.apply(this, arguments); - } + StreamEndToken.__super__ = superClass.prototype; StreamEndToken.prototype.id = ''; @@ -83,11 +76,9 @@ })(this.Token); this.BlockSequenceStartToken = (function(superClass) { - extend(BlockSequenceStartToken, superClass); + class BlockSequenceStartToken extends superClass {}; - function BlockSequenceStartToken() { - return BlockSequenceStartToken.__super__.constructor.apply(this, arguments); - } + BlockSequenceStartToken.__super__ = superClass.prototype; BlockSequenceStartToken.prototype.id = ''; @@ -96,11 +87,9 @@ })(this.Token); this.BlockMappingStartToken = (function(superClass) { - extend(BlockMappingStartToken, superClass); + class BlockMappingStartToken extends superClass {}; - function BlockMappingStartToken() { - return BlockMappingStartToken.__super__.constructor.apply(this, arguments); - } + BlockMappingStartToken.__super__ = superClass.prototype; BlockMappingStartToken.prototype.id = ''; @@ -109,11 +98,9 @@ })(this.Token); this.BlockEndToken = (function(superClass) { - extend(BlockEndToken, superClass); + class BlockEndToken extends superClass {}; - function BlockEndToken() { - return BlockEndToken.__super__.constructor.apply(this, arguments); - } + BlockEndToken.__super__ = superClass.prototype; BlockEndToken.prototype.id = ''; @@ -122,11 +109,9 @@ })(this.Token); this.FlowSequenceStartToken = (function(superClass) { - extend(FlowSequenceStartToken, superClass); + class FlowSequenceStartToken extends superClass {}; - function FlowSequenceStartToken() { - return FlowSequenceStartToken.__super__.constructor.apply(this, arguments); - } + FlowSequenceStartToken.__super__ = superClass.prototype; FlowSequenceStartToken.prototype.id = '['; @@ -135,11 +120,9 @@ })(this.Token); this.FlowMappingStartToken = (function(superClass) { - extend(FlowMappingStartToken, superClass); + class FlowMappingStartToken extends superClass {}; - function FlowMappingStartToken() { - return FlowMappingStartToken.__super__.constructor.apply(this, arguments); - } + FlowMappingStartToken.__super__ = superClass.prototype; FlowMappingStartToken.prototype.id = '{'; @@ -148,11 +131,9 @@ })(this.Token); this.FlowSequenceEndToken = (function(superClass) { - extend(FlowSequenceEndToken, superClass); + class FlowSequenceEndToken extends superClass {}; - function FlowSequenceEndToken() { - return FlowSequenceEndToken.__super__.constructor.apply(this, arguments); - } + FlowSequenceEndToken.__super__ = superClass.prototype; FlowSequenceEndToken.prototype.id = ']'; @@ -161,11 +142,9 @@ })(this.Token); this.FlowMappingEndToken = (function(superClass) { - extend(FlowMappingEndToken, superClass); + class FlowMappingEndToken extends superClass {}; - function FlowMappingEndToken() { - return FlowMappingEndToken.__super__.constructor.apply(this, arguments); - } + FlowMappingEndToken.__super__ = superClass.prototype; FlowMappingEndToken.prototype.id = '}'; @@ -174,11 +153,9 @@ })(this.Token); this.KeyToken = (function(superClass) { - extend(KeyToken, superClass); + class KeyToken extends superClass {}; - function KeyToken() { - return KeyToken.__super__.constructor.apply(this, arguments); - } + KeyToken.__super__ = superClass.prototype; KeyToken.prototype.id = '?'; @@ -187,11 +164,9 @@ })(this.Token); this.ValueToken = (function(superClass) { - extend(ValueToken, superClass); + class ValueToken extends superClass {}; - function ValueToken() { - return ValueToken.__super__.constructor.apply(this, arguments); - } + ValueToken.__super__ = superClass.prototype; ValueToken.prototype.id = ':'; @@ -200,11 +175,9 @@ })(this.Token); this.BlockEntryToken = (function(superClass) { - extend(BlockEntryToken, superClass); + class BlockEntryToken extends superClass {}; - function BlockEntryToken() { - return BlockEntryToken.__super__.constructor.apply(this, arguments); - } + BlockEntryToken.__super__ = superClass.prototype; BlockEntryToken.prototype.id = '-'; @@ -213,11 +186,9 @@ })(this.Token); this.FlowEntryToken = (function(superClass) { - extend(FlowEntryToken, superClass); + class FlowEntryToken extends superClass {}; - function FlowEntryToken() { - return FlowEntryToken.__super__.constructor.apply(this, arguments); - } + FlowEntryToken.__super__ = superClass.prototype; FlowEntryToken.prototype.id = ','; @@ -226,62 +197,70 @@ })(this.Token); this.AliasToken = (function(superClass) { - extend(AliasToken, superClass); + class AliasToken extends superClass { + constructor(value, start_mark, end_mark) { + super(start_mark, end_mark); + this.value = value; + } - AliasToken.prototype.id = ''; + }; - function AliasToken(value, start_mark, end_mark) { - this.value = value; - this.start_mark = start_mark; - this.end_mark = end_mark; - } + AliasToken.__super__ = superClass.prototype; + + AliasToken.prototype.id = ''; return AliasToken; })(this.Token); this.AnchorToken = (function(superClass) { - extend(AnchorToken, superClass); + class AnchorToken extends superClass { + constructor(value, start_mark, end_mark) { + super(start_mark, end_mark); + this.value = value; + } - AnchorToken.prototype.id = ''; + }; - function AnchorToken(value, start_mark, end_mark) { - this.value = value; - this.start_mark = start_mark; - this.end_mark = end_mark; - } + AnchorToken.__super__ = superClass.prototype; + + AnchorToken.prototype.id = ''; return AnchorToken; })(this.Token); this.TagToken = (function(superClass) { - extend(TagToken, superClass); + class TagToken extends superClass { + constructor(value, start_mark, end_mark) { + super(start_mark, end_mark); + this.value = value; + } - TagToken.prototype.id = ''; + }; - function TagToken(value, start_mark, end_mark) { - this.value = value; - this.start_mark = start_mark; - this.end_mark = end_mark; - } + TagToken.__super__ = superClass.prototype; + + TagToken.prototype.id = ''; return TagToken; })(this.Token); this.ScalarToken = (function(superClass) { - extend(ScalarToken, superClass); + class ScalarToken extends superClass { + constructor(value, plain, start_mark, end_mark, style) { + super(start_mark, end_mark); + this.value = value; + this.plain = plain; + this.style = style; + } - ScalarToken.prototype.id = ''; + }; - function ScalarToken(value, plain, start_mark, end_mark, style) { - this.value = value; - this.plain = plain; - this.start_mark = start_mark; - this.end_mark = end_mark; - this.style = style; - } + ScalarToken.__super__ = superClass.prototype; + + ScalarToken.prototype.id = ''; return ScalarToken; diff --git a/lib/util.js b/lib/util.js index 1f5b117..7a86548 100644 --- a/lib/util.js +++ b/lib/util.js @@ -5,36 +5,38 @@ A small class to stand-in for a stream when you simply want to write to a string (function() { var ref, ref1, ref2, - slice = [].slice, hasProp = {}.hasOwnProperty; - this.StringStream = (function() { - function StringStream() { + this.StringStream = class StringStream { + constructor() { this.string = ''; } - StringStream.prototype.write = function(chunk) { + write(chunk) { return this.string += chunk; - }; - - return StringStream; + } - })(); + }; - this.clone = (function(_this) { - return function(obj) { - return _this.extend({}, obj); - }; - })(this); + this.clone = function(obj) { + return Object.assign({}, obj); + }; - this.extend = function() { - var destination, i, k, len, source, sources, v; - destination = arguments[0], sources = 2 <= arguments.length ? slice.call(arguments, 1) : []; + this.extend = function(destination, ...sources) { + var i, j, len, len1, name, ref, source; for (i = 0, len = sources.length; i < len; i++) { source = sources[i]; - for (k in source) { - v = source[k]; - destination[k] = v; + while (source !== Object.prototype) { + ref = Object.getOwnPropertyNames(source); + for (j = 0, len1 = ref.length; j < len1; j++) { + name = ref[j]; + if (name !== 'constructor') { + if (destination[name] == null) { + destination[name] = source[name]; + } + } + } + source = Object.getPrototypeOf(source); } } return destination; @@ -53,7 +55,7 @@ A small class to stand-in for a stream when you simply want to write to a string }; this.inspect = (ref = (ref1 = (ref2 = require('util')) != null ? ref2.inspect : void 0) != null ? ref1 : global.inspect) != null ? ref : function(a) { - return "" + a; + return `${a}`; }; this.pad_left = function(str, char, length) { @@ -61,9 +63,9 @@ A small class to stand-in for a stream when you simply want to write to a string if (str.length >= length) { return str; } else if (str.length + 1 === length) { - return "" + char + str; + return `${char}${str}`; } else { - return "" + (new Array(length - str.length + 1).join(char)) + str; + return `${new Array(length - str.length + 1).join(char)}${str}`; } }; diff --git a/lib/yaml.js b/lib/yaml.js index 53fece9..d657a5f 100644 --- a/lib/yaml.js +++ b/lib/yaml.js @@ -32,11 +32,8 @@ Scan a YAML stream and produce scanning tokens. */ - this.scan = function(stream, Loader) { + this.scan = function(stream, Loader = loader.Loader) { var _loader, results; - if (Loader == null) { - Loader = loader.Loader; - } _loader = new Loader(stream); results = []; while (_loader.check_token()) { @@ -50,11 +47,8 @@ Parse a YAML stream and produce parsing events. */ - this.parse = function(stream, Loader) { + this.parse = function(stream, Loader = loader.Loader) { var _loader, results; - if (Loader == null) { - Loader = loader.Loader; - } _loader = new Loader(stream); results = []; while (_loader.check_event()) { @@ -69,11 +63,8 @@ representation tree. */ - this.compose = function(stream, Loader) { + this.compose = function(stream, Loader = loader.Loader) { var _loader; - if (Loader == null) { - Loader = loader.Loader; - } _loader = new Loader(stream); return _loader.get_single_node(); }; @@ -84,11 +75,8 @@ trees. */ - this.compose_all = function(stream, Loader) { + this.compose_all = function(stream, Loader = loader.Loader) { var _loader, results; - if (Loader == null) { - Loader = loader.Loader; - } _loader = new Loader(stream); results = []; while (_loader.check_node()) { @@ -103,11 +91,8 @@ Javascript object. */ - this.load = function(stream, Loader) { + this.load = function(stream, Loader = loader.Loader) { var _loader; - if (Loader == null) { - Loader = loader.Loader; - } _loader = new Loader(stream); return _loader.get_single_data(); }; @@ -118,11 +103,8 @@ object. */ - this.load_all = function(stream, Loader) { + this.load_all = function(stream, Loader = loader.Loader) { var _loader, results; - if (Loader == null) { - Loader = loader.Loader; - } _loader = new Loader(stream); results = []; while (_loader.check_data()) { @@ -137,14 +119,8 @@ If stream is falsey, return the produced string instead. */ - this.emit = function(events, stream, Dumper, options) { + this.emit = function(events, stream, Dumper = dumper.Dumper, options = {}) { var _dumper, dest, event, i, len; - if (Dumper == null) { - Dumper = dumper.Dumper; - } - if (options == null) { - options = {}; - } dest = stream || new util.StringStream; _dumper = new Dumper(dest, options); try { @@ -164,13 +140,7 @@ If stream is falsey, return the produced string instead. */ - this.serialize = function(node, stream, Dumper, options) { - if (Dumper == null) { - Dumper = dumper.Dumper; - } - if (options == null) { - options = {}; - } + this.serialize = function(node, stream, Dumper = dumper.Dumper, options = {}) { return exports.serialize_all([node], stream, Dumper, options); }; @@ -180,14 +150,8 @@ If stream is falsey, return the produced string instead. */ - this.serialize_all = function(nodes, stream, Dumper, options) { + this.serialize_all = function(nodes, stream, Dumper = dumper.Dumper, options = {}) { var _dumper, dest, i, len, node; - if (Dumper == null) { - Dumper = dumper.Dumper; - } - if (options == null) { - options = {}; - } dest = stream || new util.StringStream; _dumper = new Dumper(dest, options); try { @@ -209,13 +173,7 @@ If stream is falsey, return the produced string instead. */ - this.dump = function(data, stream, Dumper, options) { - if (Dumper == null) { - Dumper = dumper.Dumper; - } - if (options == null) { - options = {}; - } + this.dump = function(data, stream, Dumper = dumper.Dumper, options = {}) { return exports.dump_all([data], stream, Dumper, options); }; @@ -225,14 +183,8 @@ If stream is falsey, return the produced string instead. */ - this.dump_all = function(documents, stream, Dumper, options) { + this.dump_all = function(documents, stream, Dumper = dumper.Dumper, options = {}) { var _dumper, dest, document, i, len; - if (Dumper == null) { - Dumper = dumper.Dumper; - } - if (options == null) { - options = {}; - } dest = stream || new util.StringStream; _dumper = new Dumper(dest, options); try { diff --git a/src/lib/composer.coffee b/src/lib/composer.coffee index b523bd4..c46c39a 100644 --- a/src/lib/composer.coffee +++ b/src/lib/composer.coffee @@ -19,7 +19,12 @@ class @Composer ### Construct a new `Composer` instance. ### - constructor: -> + constructor: @::initialise + + ### + Initialise a new `Composer` instance. + ### + initialise: -> # @property {Object} A mapping from anchor names to nodes. @anchors = {} diff --git a/src/lib/constructor.coffee b/src/lib/constructor.coffee index 8e63b0f..e1360b6 100644 --- a/src/lib/constructor.coffee +++ b/src/lib/constructor.coffee @@ -42,7 +42,7 @@ class @BaseConstructor ### @add_constructor: (tag, constructor) -> unless @::hasOwnProperty 'yaml_constructors' - @::yaml_constructors = util.extend {}, @::yaml_constructors + @::yaml_constructors = util.clone @::yaml_constructors @::yaml_constructors[tag] = constructor ### @@ -58,13 +58,18 @@ class @BaseConstructor ### @add_multi_constructor: (tag_prefix, multi_constructor) -> unless @::hasOwnProperty 'yaml_multi_constructors' - @::yaml_multi_constructors = util.extend {}, @::yaml_multi_constructors + @::yaml_multi_constructors = util.clone @::yaml_multi_constructors @::yaml_multi_constructors[tag_prefix] = multi_constructor ### Construct a new `Constructor` instance. ### - constructor: -> + constructor: @::initialise + + ### + Initialise a new `Constructor` instance. + ### + initialise: -> # @param {Object} A map from {Node#unique_id} to the constructed Javascript object for the node. @constructed_objects = {} diff --git a/src/lib/dumper.coffee b/src/lib/dumper.coffee index 445cdf9..eef2897 100644 --- a/src/lib/dumper.coffee +++ b/src/lib/dumper.coffee @@ -11,7 +11,7 @@ resolver = require './resolver' util.extend @prototype, (component.prototype for component in components)... constructor: (stream, options = {}) -> - components[0].call @, stream, options - component.call @, options for component in components[1..] + components[0]::initialise.call @, stream, options + component::initialise.call @, options for component in components[1..] @Dumper = @make_dumper() \ No newline at end of file diff --git a/src/lib/emitter.coffee b/src/lib/emitter.coffee index 04fd647..f29ba47 100644 --- a/src/lib/emitter.coffee +++ b/src/lib/emitter.coffee @@ -37,7 +37,9 @@ class @Emitter '\u2028': 'L' '\u2029': 'P' - constructor: (@stream, options) -> + constructor: @::initialise + + initialise: (@stream, options) -> # Encoding can be overriden by STREAM-START @encoding = null diff --git a/src/lib/errors.coffee b/src/lib/errors.coffee index db80d26..3038e2f 100644 --- a/src/lib/errors.coffee +++ b/src/lib/errors.coffee @@ -36,7 +36,8 @@ class @YAMLError extends Error super() # Hack to get the stack on the error somehow - @stack = @toString() + '\n' + (new Error).stack.split('\n')[1..].join('\n') + Object.defineProperty @, 'stack', get: -> + @toString() + '\n' + (new Error).stack.split('\n')[1..].join('\n') toString: -> @message diff --git a/src/lib/events.coffee b/src/lib/events.coffee index 6fb4d60..7355b30 100644 --- a/src/lib/events.coffee +++ b/src/lib/events.coffee @@ -2,28 +2,34 @@ class @Event constructor: (@start_mark, @end_mark) -> class @NodeEvent extends @Event - constructor: (@anchor, @start_mark, @end_mark) -> + constructor: (@anchor, start_mark, end_mark) -> + super start_mark, end_mark class @CollectionStartEvent extends @NodeEvent - constructor: (@anchor, @tag, @implicit, @start_mark, @end_mark, @flow_style) -> + constructor: (@anchor, @tag, @implicit, start_mark, end_mark, @flow_style) -> + super start_mark, end_mark class @CollectionEndEvent extends @Event class @StreamStartEvent extends @Event - constructor: (@start_mark, @end_mark, @encoding) -> + constructor: (start_mark, end_mark, @encoding) -> + super start_mark, end_mark class @StreamEndEvent extends @Event class @DocumentStartEvent extends @Event - constructor: (@start_mark, @end_mark, @explicit, @version, @tags) -> + constructor: (start_mark, end_mark, @explicit, @version, @tags) -> + super start_mark, end_mark class @DocumentEndEvent extends @Event - constructor: (@start_mark, @end_mark, @explicit) -> + constructor: (start_mark, end_mark, @explicit) -> + super start_mark, end_mark class @AliasEvent extends @NodeEvent class @ScalarEvent extends @NodeEvent - constructor: (@anchor, @tag, @implicit, @value, @start_mark, @end_mark, @style) -> + constructor: (@anchor, @tag, @implicit, @value, start_mark, end_mark, @style) -> + super start_mark, end_mark class @SequenceStartEvent extends @CollectionStartEvent diff --git a/src/lib/loader.coffee b/src/lib/loader.coffee index 36244d8..65be4b2 100644 --- a/src/lib/loader.coffee +++ b/src/lib/loader.coffee @@ -14,7 +14,7 @@ constructor = require './constructor' util.extend @prototype, (component.prototype for component in components)... constructor: (stream) -> - components[0].call @, stream - component.call @ for component in components[1..] + components[0]::initialise.call @, stream + component::initialise.call @ for component in components[1..] @Loader = @make_loader() \ No newline at end of file diff --git a/src/lib/parser.coffee b/src/lib/parser.coffee index 3e7e209..b2acedb 100644 --- a/src/lib/parser.coffee +++ b/src/lib/parser.coffee @@ -10,7 +10,9 @@ class @Parser '!' : '!', '!!': 'tag:yaml.org,2002:' - constructor: -> + constructor: @::initialise + + initialise: -> @current_event = null @yaml_version = null @tag_handles = {} diff --git a/src/lib/reader.coffee b/src/lib/reader.coffee index 08e6b4c..0a3e0b0 100644 --- a/src/lib/reader.coffee +++ b/src/lib/reader.coffee @@ -18,7 +18,9 @@ Reader: class @Reader NON_PRINTABLE = /[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD]/ - constructor: (@string) -> + constructor: @::initialise + + initialise: (@string) -> @line = 0 @column = 0 @index = 0 diff --git a/src/lib/representer.coffee b/src/lib/representer.coffee index ceb54dc..05c1043 100644 --- a/src/lib/representer.coffee +++ b/src/lib/representer.coffee @@ -28,7 +28,9 @@ class @BaseRepresenter @::yaml_multi_representers_types.push data_type @::yaml_multi_representers_handlers.push handler - constructor: ({ @default_style, @default_flow_style } = {}) -> + constructor: @::initialise + + initialise: ({ @default_style, @default_flow_style } = {}) -> @represented_objects = {} @object_keeper = [] @alias_key = null diff --git a/src/lib/resolver.coffee b/src/lib/resolver.coffee index 749727b..c3fba6a 100644 --- a/src/lib/resolver.coffee +++ b/src/lib/resolver.coffee @@ -15,11 +15,13 @@ class @BaseResolver @add_implicit_resolver: (tag, regexp, first = [null]) -> unless @::hasOwnProperty 'yaml_implicit_resolvers' - @::yaml_implicit_resolvers = util.extend {}, @::yaml_implicit_resolvers + @::yaml_implicit_resolvers = util.clone @::yaml_implicit_resolvers for char in first (@::yaml_implicit_resolvers[char] ?= []).push [tag, regexp] - constructor: -> + constructor: @::initialise + + initialise: -> @resolver_exact_paths = [] @resolver_prefix_paths = [] diff --git a/src/lib/scanner.coffee b/src/lib/scanner.coffee index 95fe906..178ca69 100644 --- a/src/lib/scanner.coffee +++ b/src/lib/scanner.coffee @@ -45,10 +45,12 @@ class @Scanner 'u': 4 'U': 8 + constructor: @::initialise + ### Initialise the Scanner ### - constructor: -> + initialise: -> # Have we reached the end of the stream? @done = no diff --git a/src/lib/serializer.coffee b/src/lib/serializer.coffee index 275ad13..209ef99 100644 --- a/src/lib/serializer.coffee +++ b/src/lib/serializer.coffee @@ -6,7 +6,9 @@ util = require './util' class @SerializerError extends YAMLError class @Serializer - constructor: ({ @encoding, @explicit_start, @explicit_end, @version, @tags } = {}) -> + constructor: @::initialise + + initialise: ({ @encoding, @explicit_start, @explicit_end, @version, @tags } = {}) -> @serialized_nodes = {} @anchors = {} @last_anchor_id = 0 diff --git a/src/lib/tokens.coffee b/src/lib/tokens.coffee index 3c80e75..3939c09 100644 --- a/src/lib/tokens.coffee +++ b/src/lib/tokens.coffee @@ -3,7 +3,8 @@ class @Token class @DirectiveToken extends @Token id: '' - constructor: (@name, @value, @start_mark, @end_mark) -> + constructor: (@name, @value, start_mark, end_mark) -> + super start_mark, end_mark class @DocumentStartToken extends @Token id: '' @@ -13,7 +14,8 @@ class @DocumentEndToken extends @Token class @StreamStartToken extends @Token id: '' - constructor: (@start_mark, @end_mark, @encoding) -> + constructor: (start_mark, end_mark, @encoding) -> + super start_mark, end_mark class @StreamEndToken extends @Token id: '' @@ -53,16 +55,20 @@ class @FlowEntryToken extends @Token class @AliasToken extends @Token id: '' - constructor: (@value, @start_mark, @end_mark) -> + constructor: (@value, start_mark, end_mark) -> + super start_mark, end_mark class @AnchorToken extends @Token id: '' - constructor: (@value, @start_mark, @end_mark) -> + constructor: (@value, start_mark, end_mark) -> + super start_mark, end_mark class @TagToken extends @Token id: '' - constructor: (@value, @start_mark, @end_mark) -> + constructor: (@value, start_mark, end_mark) -> + super start_mark, end_mark class @ScalarToken extends @Token id: '' - constructor: (@value, @plain, @start_mark, @end_mark, @style) -> \ No newline at end of file + constructor: (@value, @plain, start_mark, end_mark, @style) -> + super start_mark, end_mark diff --git a/src/lib/util.coffee b/src/lib/util.coffee index b41c5c2..0724da0 100644 --- a/src/lib/util.coffee +++ b/src/lib/util.coffee @@ -8,11 +8,15 @@ class @StringStream write: (chunk) -> @string += chunk -@clone = (obj) => - @extend {}, obj +@clone = (obj) -> + Object.assign {}, obj @extend = (destination, sources...) -> - destination[k] = v for k, v of source for source in sources + for source in sources + while source != Object.prototype + for name in Object.getOwnPropertyNames source when name isnt 'constructor' + destination[name] ?= source[name] + source = Object.getPrototypeOf source destination @is_empty = (obj) -> diff --git a/test/test.coffee b/test/test.coffee index c51f98c..0263042 100644 --- a/test/test.coffee +++ b/test/test.coffee @@ -41,4 +41,4 @@ describe 'dump (formatting)', -> for { input, output }, i in examples then do (input, output, i) -> for [ options, result ], j in output then do (options, result, j) -> it "input #{i} options #{j}", -> - expect_equal yaml.dump(yaml.load(input), null, null, options), result \ No newline at end of file + expect_equal yaml.dump(yaml.load(input), undefined, undefined, options), result