34

The Situation

In our current project we've had some recurring problems with people using 'asMutable' from seamless-immutable where it isn't actually necessary. This has resulted in 'search project for string "asMutable"' becoming part of every pull request. To speed this up we would like to add a rule warning that to our eslint. But I haven't figured out how.

The Question

What seems like the best solution to me right now, though I'm open to suggestions, is a rule that allows me to specify a function name to forbid. Does ESlint, or a plugin therefore, have that sort of functionality?

Additional Notes

I've looked a little into writing our own, but I was intimidated by AST and the startup difficulty to writing my first rule. I may take the plunge if I can't find a better answer, yes we're getting this enough in PRs to warrant it. This seems like something someone much smarter than me has already solved though, so I'd rather follow in their footsteps then build my own.

3 Answers 3

43

You can do some very fancy things when you combine ESLint's no-restricted-syntax rule with selectors. In your case you should be able to achieve the linting you want without writing your own plugin. The rule would look something like:

{
  rules: {
    'no-restricted-syntax': [
      'error',
      {
        message: "Please don't use asMutable. We don't like it!",
        selector:
          'MemberExpression > Identifier[name="asMutable"]'
      }
    ]
  }
}

Study the documentation page for selectors; it is very flexible!

4
  • 7
    Seems far simpler than creating a new plugin. I had to write the selector as CallExpression[callee.name='asMutable'] to get it to work.
    – wlf
    Commented Jun 14, 2021 at 6:30
  • 3
    In case you don't know what your selectors are, you can use the AST Explorer linked in the accepted answer to find out
    – panepeter
    Commented Sep 1, 2021 at 10:37
  • 2
    MemberExpression[property.name='asMutable'] should work for you
    – Alejandro
    Commented Sep 8, 2022 at 20:08
  • Is there a way to copy the selector path out of the AST Explorer? Commented Feb 17, 2023 at 14:10
28

I had the same problem not so long ago so I can help you with writing your own.

So, first, let's explain some basic structures:

  1. ESLint has plugins, and each plugin has rules.
  2. ESLint uses AST which is a syntax tree to find specific parts in the code. This helps ESLint find what each rule is looking for.

So, let's start by creating a plugin with a rule in it:


1. Use The ESLint Generator for Yeoman

This makes things a lot easier. Check it out here.

After you install yeoman and the yeoman eslint generator:

  • go into the folder you want to create your project in
  • run yo eslint:plugin to create a new ESLint plugin
  • after creating the plugin, run yo eslint:rule in the same folder

I used suni as the plugin name, and check-as-mutable as the rule name. Now we have all the initial files we need to write the rule.


2. Know what you need to look for using AST Explorer

AST Explorer Can help us find what type of thing we're looking for. This is important so we can tell ESLint what in the code we want our function to run on.

When you paste code into AST Explorer, it shows you what ESLint is seeing. We want to target all MemberExpressions:

something.asMutable();

Inside that, we want the Identifier node to check the function name


3. Write the plugin itself

Open lib/rules/check-as-mutable.js and check it out. All the data you provided for Yeoman was used to fill some fields here.

Inside the rule, you have a create attribute. Here, we write our code. This function should return an object, with what we want our rules to run on as attributes. So, in this case, it will look like so:

create: function(context) {

    return {
      MemberExpression: function(node)...

    };
}

While writing the rule, you should check which fields you need using the AST Explorer.

here is the implementation:

create: function(context) {
  var UNWANTED_FUNCTION_NAME = 'asMutable';
  return {
    MemberExpression: function reportUnwantedName(node) {
      var functionName = node.property.name;

      if (functionName === UNWANTED_FUNCTION_NAME) {
        context.report({
          node: node,
          message: [
            'Please don\'t use ',
            UNWANTED_FUNCTION_NAME,
            '. We don\'t like it!'].join('')
        });
      }
    }
  };
}

After that, you need to install the plugin in your project. To do that, upload it to GitHub, and install it using npm:

npm install --save-dev <user_name>/<repository_name>

And include the rule in your .eslintrc file as well:

{
    'plugins': ['suni'],
    'rules': {
      'suni/check-as-mutable': 1
    }
}

Notice that I gave it the value 1. This makes this rule show as a Warning and not as an Error

enter image description here

Notice that the warning highlights the Immutable itself, since that is the node we pass to context.report. You can tweak that to highlight the id node instead.

Here's the plugin I created for this answer

Good luck!

3
  • 2
    This is extremely helpful, and gets me quite a bit of the ways there. I'm about to start following the instructions (having read them first) but I notice you're looking at function declarations, I'm going to be looking for function invocations (asMutable is a function seamless-immutable provides which has tiny niche applications and gets abused by some devs). I'm assuming there is a FunctionInvocation variation like FunctionDecleration, though I'm still googling it. That change would help this address the question a little more perfectly.
    – Suni
    Commented Dec 5, 2016 at 19:04
  • 1
    Thanks both for the thorough and accurate answer, but also for updating it. That's perfect, and it looks like this is exactly what we'll be doing! ^_^
    – Suni
    Commented Dec 6, 2016 at 14:13
  • Hi @Suni! Thanks for the comment and sorry for the delayed answer :-) Glad I could help. If you need further details, don't hesitate to write another comment :-) Commented Jul 5, 2017 at 8:19
10

On top of @Eric Simonton's answer, since ESLint 3.5.0 we have the purpose-built no-restricted-properties:

"no-restricted-properties": [ "error", {
    "object": "Immutable",
    "property": "asMutable",
    "message": "optional explanation to the recurring problems we've had"
}]

If anyone comes here looking for ways to block functions that aren't class methods, you can similarly use no-restricted-globals

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.