context.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. 'use strict';
  2. var codeContext = require('parse-code-context');
  3. /**
  4. * Create a new Context object for the given comment.
  5. *
  6. * @param {String} `str` string of JavaScript
  7. * @param {Object} `comment` Block comment instance
  8. */
  9. function Context(str, comment) {
  10. var start = comment.range[1];
  11. var lineno = comment.loc.end.line;
  12. var afterComment = str.slice(start);
  13. var len = afterComment.length, i = 0;
  14. var newlines = 0;
  15. var col = null;
  16. this.context = {};
  17. this.value = '';
  18. this.line = null;
  19. /**
  20. * Loop until we get to a non-whitespace, non-newline character
  21. * If codeContext returns a parsed object, it's used as context,
  22. * otherwise we assume that no code follows the comment.
  23. */
  24. while (++i < len) {
  25. var ch = afterComment[i];
  26. if (ch === '/' || ch === '*') {
  27. break;
  28. }
  29. if (ch !== '\n' && ch !== ' ' && ch !== '\t') {
  30. col = start + i;
  31. var line = str.slice(col, str.indexOf('\n', col));
  32. var res = codeContext(line);
  33. if (res) {
  34. this.context = res;
  35. this.value = line;
  36. this.line = lineno + newlines + 1;
  37. }
  38. break;
  39. }
  40. if (ch === '\n') {
  41. newlines++;
  42. }
  43. }
  44. /**
  45. * Create location stats
  46. */
  47. var end = col !== null
  48. ? col + (this.value || '').length
  49. : null;
  50. this.loc = {
  51. start: {
  52. line: this.line,
  53. column: col
  54. },
  55. end: {
  56. line: this.line,
  57. column: end
  58. }
  59. };
  60. }
  61. /**
  62. * Expose `Context`
  63. */
  64. module.exports = Context;