attachComments.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. "use strict";
  2. // comment fixes
  3. module.exports = function(ast, comments, tokens) {
  4. if (comments.length) {
  5. var firstComment = comments[0];
  6. var lastComment = comments[comments.length - 1];
  7. // fixup program start
  8. if (!tokens.length) {
  9. // if no tokens, the program starts at the end of the last comment
  10. ast.start = lastComment.end;
  11. ast.loc.start.line = lastComment.loc.end.line;
  12. ast.loc.start.column = lastComment.loc.end.column;
  13. if (ast.leadingComments === null && ast.innerComments.length) {
  14. ast.leadingComments = ast.innerComments;
  15. }
  16. } else if (firstComment.start < tokens[0].start) {
  17. // if there are comments before the first token, the program starts at the first token
  18. var token = tokens[0];
  19. // ast.start = token.start;
  20. // ast.loc.start.line = token.loc.start.line;
  21. // ast.loc.start.column = token.loc.start.column;
  22. // estraverse do not put leading comments on first node when the comment
  23. // appear before the first token
  24. if (ast.body.length) {
  25. var node = ast.body[0];
  26. node.leadingComments = [];
  27. var firstTokenStart = token.start;
  28. var len = comments.length;
  29. for (var i = 0; i < len && comments[i].start < firstTokenStart; i++) {
  30. node.leadingComments.push(comments[i]);
  31. }
  32. }
  33. }
  34. // fixup program end
  35. if (tokens.length) {
  36. var lastToken = tokens[tokens.length - 1];
  37. if (lastComment.end > lastToken.end) {
  38. // If there is a comment after the last token, the program ends at the
  39. // last token and not the comment
  40. // ast.end = lastToken.end;
  41. ast.range[1] = lastToken.end;
  42. ast.loc.end.line = lastToken.loc.end.line;
  43. ast.loc.end.column = lastToken.loc.end.column;
  44. }
  45. }
  46. } else {
  47. if (!tokens.length) {
  48. ast.loc.start.line = 1;
  49. ast.loc.end.line = 1;
  50. }
  51. }
  52. if (ast.body && ast.body.length > 0) {
  53. ast.loc.start.line = ast.body[0].loc.start.line;
  54. ast.range[0] = ast.body[0].start;
  55. }
  56. };