-
-
Notifications
You must be signed in to change notification settings - Fork 4.9k
Description
I've been doing some thinking about how this would work. I know that JSCS is pursuing using a concrete syntax tree (CST) for this purpose, and that might be useful for some fixes, but waiting for that effort to complete and then getting a working implementation for us to use would likely take a whole lot of time. So, I've been trying to figure out how to get autofixing in the short-term and came up with a plan. The basic plan is:
- Have autofixing run in a separate mode. You'd need to pass
--fixon the command line and in that mode, you will not receive linting errors output (but you will receive parsing error output). This mode will only apply fixes and not lint the code otherwise because a change from one fix might alter the results of the linting. - Have autofixing not available to plugins, at least initially. I want to make sure that if we expose something to plugins that it's our long-term approach and I'm just not sure enough right now.
- Allow autofixing to happen inside of rules in order to avoid duplicate logic.
So how would I achieve this?
First, I'd create a new object called Fixer that would be passed in as the second argument to a rule function when ESLint is running in autofix mode, such as:
module.exports = function(context, fixer) {
};The fixer object will have these methods:
insert(index, text)- inserts the given text at the given range index in the sourceremove([start, end])- removes the text in the given range (an array, so you can pass innode.range)replace([start, end], text)- removes the text in the given range and replaces it with the given text
So the fixer object will collect all of the requested changes into an array and then do a reverse sort by range index. It can then apply the changes from the end of the string towards the beginning so that it will be accurate.
This approach should work for:
semiindent*-spacingquotes
I'm not sure, maybe there are others. The functionality is obviously limited to non-intersecting ranges of changes, so we'd be unlikely to do more complex fixes like changing a function expression to an arrow function, but we could at least get the stylistic stuff fixed fairly easily.
I think this will end up being a small amount of work to get a really useful feature, so at least we'll be able to autofix some of the more nitpicky things and maybe consider a CST once it has developed more fully.
Thoughts?