Skip to content

Commit

Permalink
refactor: simplify closeTag method
Browse files Browse the repository at this point in the history
  • Loading branch information
lddubeau committed Aug 16, 2018
1 parent 2363ff8 commit 4ffe5ed
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 26 deletions.
44 changes: 18 additions & 26 deletions lib/saxes.js
Original file line number Diff line number Diff line change
Expand Up @@ -1713,47 +1713,39 @@ ${XMLNS_NAMESPACE}.`);
* @private
*/
closeTag() {
if (!this.tagName) {
const { tags, tagName } = this;

// Our state after this will be S_TEXT, no matter what, and we can clear
// tagName now.
this.state = S_TEXT;
this.tagName = "";

if (!tagName) {
this.fail("weird empty close tag.");
this.textNode += "</>";
this.state = S_TEXT;
return;
}

const { tags } = this;
// first make sure that the closing tag actually exists.
// <a><b></c></b></a> will close everything, otherwise.
let t = tags.length;
const { tagName } = this;
const closeTo = tagName;
while (t--) {
const close = tags[t];
if (close.name !== closeTo) {
let l = tags.length;
while (l-- > 0) {
const tag = this.tag = tags.pop();
this.emitNode("onclosetag", tag);
if (tag.name !== tagName) {
this.fail("unexpected close tag.");
}
else {
break;
}
}

if (t < 0) {
this.fail(`unmatched closing tag: ${tagName}.`);
this.textNode += `</${tagName}>`;
this.state = S_TEXT;
return;
}
let s = this.tags.length;
while (s-- > t) {
const tag = this.tag = tags.pop();
this.emitNode("onclosetag", tag);
}
if (t === 0) {
if (l === 0) {
this.inRoot = false;
this.closedRoot = true;
}
this.tagName = this.attribValue = this.attribName = "";
this.attribList = [];
this.state = S_TEXT;
else if (l < 0) {
this.fail(`unmatched closing tag: ${tagName}.`);
this.textNode += `</${tagName}>`;
}
}

/**
Expand Down
16 changes: 16 additions & 0 deletions test/close-without-open.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"use strict";

const { test } = require(".");

test({
name: "close a tag that was not opened",
xml: "</root>",
expect: [
["error", "undefined:1:7: unmatched closing tag: root."],
["error", "undefined:1:7: document must contain a root element."],
["text", "</root>"],
],
opt: {
xmlns: true,
},
});

0 comments on commit 4ffe5ed

Please sign in to comment.