diff --git a/lib/rules/validate-jsdoc.js b/lib/rules/validate-jsdoc.js index 58fac1b..bdb3239 100644 --- a/lib/rules/validate-jsdoc.js +++ b/lib/rules/validate-jsdoc.js @@ -213,7 +213,6 @@ function patchNodesInFile(file) { } // jsdoc property for nodes - var fileComments = file.getComments(); file.iterateNodesByType([ 'FunctionDeclaration', 'FunctionExpression' ], function(node) { @@ -230,27 +229,38 @@ function patchNodesInFile(file) { */ function getJsdoc() { if (!this.hasOwnProperty('_jsdoc')) { - var res = findDocCommentBeforeLine(this.loc.start.line); + var node = this.type === 'FunctionExpression' ? findFirstNodeInLine(this) : this; + var res = findDocCommentBeforeNode(node); this._jsdoc = res ? jsdoc.createDocCommentByCommentNode(res) : null; } return this._jsdoc; } + /** + * Finds the first node on the same line as passed node + * + * @param {?module:esprima/Node} node + * @returns {?module:esprima/Node} + */ + function findFirstNodeInLine(node) { + var parent = node.parentNode; + if (!parent || parent.loc.start.line !== node.loc.start.line) { + return node; + } + return findFirstNodeInLine(parent); + } + /** * Finds DocComment in file before passed line number * - * @param {number} line + * @param {?module:esprima/Node} node * @returns {?module:esprima/Node} */ - function findDocCommentBeforeLine(line) { - line--; // todo: buggy behaviour, can't jump back over empty lines - for (var i = 0, l = fileComments.length; i < l; i++) { - var commentNode = fileComments[i]; - // v.substr(jsdoc.loc.start.column); - if (commentNode.loc.end.line === line && commentNode.type === 'Block' && - commentNode.value.charAt(0) === '*') { - return commentNode; - } + function findDocCommentBeforeNode(node) { + var res = file.getPrevToken(file.getFirstNodeToken(node), {includeComments: true}); + if (res && res.type === 'Block' && res.value.charAt(0) === '*' && + res.loc.start.column === node.loc.start.column) { + return res; } return null; } diff --git a/test/lib/rules/validate-jsdoc.js b/test/lib/rules/validate-jsdoc.js index 24df18b..76e3a08 100644 --- a/test/lib/rules/validate-jsdoc.js +++ b/test/lib/rules/validate-jsdoc.js @@ -52,6 +52,26 @@ describe('lib/rules/validate-jsdoc', function () { // doesn't mean } } + }, { + it: 'should find docblock after a blank line', + rules: {enforceExistence: true}, + code: function() { + /** + * Foo + */ + + function foo () {} + } + }, { + it: 'should not stick docblock with diff indent', + rules: {enforceExistence: true}, + code: function() { + /** + * Foo + */ + function foo () {} + }, + errors: 1 } /* jshint ignore:end */ ]);