Skip to content

Conversation

liamjpeters
Copy link
Contributor

PR Summary

Adds a new rule that warns when reserved words are used as function names.

function function {}

function if {
    function else {}
}

function global:try {}

function private:catch {}

Fixes #2099

I wrote a blog post about putting this together 😀

PR Checklist

@liamjpeters
Copy link
Contributor Author

liamjpeters commented Sep 3, 2025

Just as a note...

I did attempt to use reflection rather than a hard-coded list of keywords. The keyword list is in the Tokenizer.

public static HashSet<string> GetReservedWordsFromTokenizer()
{
    // Get the assembly containing Tokenizer
    var asm = typeof(Token).Assembly;

    // Get the internal Tokenizer type
    var tokenizerType = asm.GetType("System.Management.Automation.Language.Tokenizer");

    // Get the private static readonly field s_keywordTokenKind
    var field = tokenizerType.GetField("s_keywordTokenKind", BindingFlags.NonPublic | BindingFlags.Static);

    // Get the TokenKind[] value
    var tokenKinds = field.GetValue(null) as Array;

    var reservedWords = new HashSet<string>(
        tokenKinds.Cast<Enum>().Select(tk => tk.ToString()),
        StringComparer.OrdinalIgnoreCase
    );

    return reservedWords;
}

With similar on the PowerShell side for the tests.

This worked fine in PS7 but I can't seem to get it to work in PS5.1 - I can't access the s_keywordTokenKind or s_keywordText field.

@andyleejordan
Copy link
Member

This worked fine in PS7 but I can't seem to get it to work in PS5.1 - I can't access the s_keywordTokenKind or s_keywordText field.

That makes sense to me. We've run into similar issues in PSES because the visibility of some of them changed making them available through reflection in PS7 but still not in PS5.1. Oh well 🫠

@andyleejordan andyleejordan force-pushed the #2099PSAvoidReservedWordsAsFunctionNames branch from 6672621 to 1e5c1b2 Compare October 15, 2025 23:23
Copy link
Member

@andyleejordan andyleejordan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@SeeminglyScience can you take a look at this too? Seems pretty good to me and reasonable to add as a default.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Rule request: Avoid reserved words for functions names

2 participants