All files / src/comments/handlers handleContractDefinitionComments.js

100% Statements 15/15
100% Branches 15/15
100% Functions 1/1
100% Lines 15/15

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              54x                   1892x 1284x               608x         608x           18x 10x 10x           8x 8x         590x 20x 20x     570x     54x  
const {
  util: {
    addLeadingComment,
    addTrailingComment,
    addDanglingComment,
    getNextNonSpaceNonCommentCharacterIndex
  }
} = require('prettier');
 
function handleContractDefinitionComments({
  text,
  precedingNode,
  enclosingNode,
  followingNode,
  comment,
  options
}) {
  if (!enclosingNode || enclosingNode.type !== 'ContractDefinition') {
    return false;
  }
 
  // We unfortunately have no way using the AST or location of nodes to know
  // if the comment is positioned before the Contract's body:
  //   contract a is abc /* comment */ {}
  // 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 Block `{}` or behind a base contract
  if (
    (followingNode && followingNode.type === 'InheritanceSpecifier') ||
    nextCharacter === '{'
  ) {
    // In this scenario the comment belongs to a base contract.
    //   contract A is B, /* comment for B */ C /* comment for C */ {}
    if (precedingNode && precedingNode.type === 'InheritanceSpecifier') {
      addTrailingComment(precedingNode, comment);
      return true;
    }
 
    // In this scenario the comment belongs to the contract's name.
    //   contract A /* comment for A */ is B, C {}
    // TODO: at the moment we prepended it but this should be kept after the name.
    addLeadingComment(enclosingNode, comment);
    return true;
  }
 
  // When the contract is empty and contain comments.
  // Most likely disabling a linter rule.
  if (enclosingNode.subNodes.length === 0) {
    addDanglingComment(enclosingNode, comment);
    return true;
  }
 
  return false;
}
 
module.exports = handleContractDefinitionComments;