All files / src/comments/handlers handleModifierInvocationComments.js

100% Statements 18/18
100% Branches 12/12
100% Functions 1/1
100% Lines 18/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70              54x                 1855x 1819x               36x         36x         12x 12x     24x 19x     10x 10x     9x           4x 4x             5x 5x     5x     54x  
const {
  util: {
    addLeadingComment,
    addTrailingComment,
    addDanglingComment,
    getNextNonSpaceNonCommentCharacterIndex
  }
} = require('prettier');
 
function handleModifierInvocationComments({
  text,
  precedingNode,
  enclosingNode,
  comment,
  options
}) {
  if (!enclosingNode || enclosingNode.type !== 'ModifierInvocation') {
    return false;
  }
 
  // We unfortunately have no way using the AST or location of nodes to know
  // if the comment is positioned after the modifier's name:
  //    function a() public modifier /* comment 1 */ ( /* comment 2 */ ) /* comment 3 */
  // The only workaround I found is to look at the next character to see if
  // it is a ().
  const nextCharacter = text.charAt(
    getNextNonSpaceNonCommentCharacterIndex(text, comment, options.locEnd)
  );
 
  // The comment is behind the start of the Parentheses `()`
  if (nextCharacter === '(') {
    // In this scenario the comment is between the modifier's name and the
    // parentheses so it's placed as a leading comment.
    //    function a() public modifier // comment
    //        ()
    addLeadingComment(enclosingNode, comment);
    return true;
  }
 
  if (nextCharacter === ')') {
    if (precedingNode) {
      // In this scenario the comment belongs to an argument passed to the modifier.
      //    function a() public modifier(argument /* comment for the argument */)
      addTrailingComment(precedingNode, comment);
      return true;
    }
 
    if (comment.type === 'LineComment') {
      // In this scenario there's no arguments and the parentheses should either be
      // together or dismissed so the comment is placed as a leading comment.
      //    function a() public modifier(
      //        // weird place to put a line comment
      //    )
      addLeadingComment(enclosingNode, comment);
      return true;
    }
 
    // In this scenario there's no arguments but since the comment is a block
    // comment, we assume there's an explicit reason for it to be placed there
    // so we respect it here.
    //    function a() public modifier(/* block comment */)
    addDanglingComment(enclosingNode, comment);
    return true;
  }
 
  return false;
}
 
module.exports = handleModifierInvocationComments;