Namespaced function names in CMake

I can declare a qualified function:

function(my::func)
    message(STATUS "Hi!")
endfunction()

And I can call it qualified… this way, which works as expected:

cmake_language(CALL my::func)

but not this way

my::func() # Parse error.  Expected a command name, got unquoted argument with text "my::func"

The same idea is true for using a . instead of ::, any punctuation basically.

Is this a fundamental parser limitation that it cannot interpret my::func as a command name?

Basically it’s just a question of whether I need to be declaring all my functions my::func (or my.func) or resorting to the C-style my_func to avoid collisions. Since CMake encourages colons in targets, I think it’d be nice if we could do it for functions too.

2 Likes

For what it’s worth, just making this change in the lexer:

- [A-Za-z_][A-Za-z0-9_]* {
+ ([A-Za-z_][A-Za-z0-9_]*::)*[A-Za-z_][A-Za-z0-9_]* {
     lexer->token.type = cmListFileLexer_Token_Identifier;
     cmListFileLexerSetToken(lexer, yytext, yyleng);
     lexer->column += yyleng;

Lets my::func be usable as an identifier and thus makes my::func(1 2 3) work as desired.

2 Likes

I’d recommend sticking with myproj_do_something form for function names, at least for now. The ability to both define a function using myproj::do_something and being able to call it using cmake_language(CALL) was something I didn’t expect. But that does give me some more things to think about for a proposal I put up a little while back related to project namespaces: https://gitlab.kitware.com/cmake/cmake/-/issues/22687 (this is a strong reason to avoid trying to use myproj::do_something right now, it may gain meaning if that proposal moves forward and is expanded to cover functions as well).

2 Likes