1import * as ts from 'typescript'; 2import { forEachComment } from 'tsutils/util/util'; 3import { getLocFor } from './node-utils'; 4import { AST_TOKEN_TYPES, TSESTree } from './ts-estree'; 5 6/** 7 * Convert all comments for the given AST. 8 * @param ast the AST object 9 * @param code the TypeScript code 10 * @returns the converted ESTreeComment 11 * @private 12 */ 13export function convertComments( 14 ast: ts.SourceFile, 15 code: string, 16): TSESTree.Comment[] { 17 const comments: TSESTree.Comment[] = []; 18 19 forEachComment( 20 ast, 21 (_, comment) => { 22 const type = 23 comment.kind == ts.SyntaxKind.SingleLineCommentTrivia 24 ? AST_TOKEN_TYPES.Line 25 : AST_TOKEN_TYPES.Block; 26 const range: TSESTree.Range = [comment.pos, comment.end]; 27 const loc = getLocFor(range[0], range[1], ast); 28 29 // both comments start with 2 characters - /* or // 30 const textStart = range[0] + 2; 31 const textEnd = 32 comment.kind === ts.SyntaxKind.SingleLineCommentTrivia 33 ? // single line comments end at the end 34 range[1] - textStart 35 : // multiline comments end 2 characters early 36 range[1] - textStart - 2; 37 comments.push({ 38 type, 39 value: code.substr(textStart, textEnd), 40 range, 41 loc, 42 }); 43 }, 44 ast, 45 ); 46 47 return comments; 48} 49