From 63b2ef567c6753e3706221d00884b524442491e6 Mon Sep 17 00:00:00 2001 From: David Chambers Date: Tue, 21 Feb 2023 16:00:49 +0100 Subject: [PATCH] use `CoffeeScript.nodes` to extract comments --- lib/rewriters/coffeescript.js | 36 +++++++++++++++++++++++++---------- 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/lib/rewriters/coffeescript.js b/lib/rewriters/coffeescript.js index 4a0e0d4..4315ef9 100644 --- a/lib/rewriters/coffeescript.js +++ b/lib/rewriters/coffeescript.js @@ -4,19 +4,35 @@ import show from 'sanctuary-show'; import rewrite from '../rewrite.js'; +function comments(node) { + return ( + Object.values (node) + .flatMap (x => { + switch (Object.prototype.toString.call (x)) { + case '[object Array]': return x; + case '[object Object]': return [x]; + default: return []; + } + }) + .flatMap (comments) + .concat (node.comments ?? []) + ); +} + const chunksCoffee = input => { const chunks = {literals: new Map ([]), comments: new Map ([])}; - let number = 0; - for (const text of input.match (/^.*(?=\n)/gm)) { - number += 1; - const match = /^([ \t]*)#(?!##)(.*)$/.exec (text); - if (match == null) { - chunks.literals.set (number, text); - } else { - const [, indent, uncommented] = match; - chunks.comments.set (number, {indent, number, text: uncommented}); - } + let offset = 0; + for (const comment of comments (CoffeeScript.nodes (input))) { + const [start, end] = comment.locationData.range; + chunks.literals.set (offset, input.slice (offset, start)); + chunks.comments.set (start, { + indent: ' '.repeat (comment.locationData.first_column), + number: comment.locationData.first_line + 1, + text: comment.content, + }); + offset = end; } + chunks.literals.set (offset, input.slice (offset)); return chunks; };