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.

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
1 participant