llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
28.31k stars 11.69k forks source link

NSString Warning Not Needed #89323

Open RuiCuco opened 5 months ago

RuiCuco commented 5 months ago

I'm doing my own string class in Objective-C called 'kString'. If I compile the project with the compiler option '-fconstant-string-class=kString', I get the following warning:

test.m:43:11: warning: incompatible pointer types initializing 'kString *' with an expression of type 'NSString *' [-Wincompatible-pointer-types]
   43 |         kString *k = @"Hello!\n";
      |                  ^   ~~~~~~~~~~~

clang shouldn't issue any warning because it works everytime I use the @"" literal. The pointer types are not incompatible: I tested it and it simply works! No warning needed!

By the way, how about implementing a similar mechanism for the other @ literals? I could say, for example:

@interface kObject
{
    Class isa;
}
@end

@interface kInt : kObject
{
    int i;
}
@end

@interface kFloat : kObject
{
    float f;
}
@end

int main(void)
{
    kInt *myInt = @42;
    kFloat *myFloat = @3.14f;

    return 0;
}

and then compile with the compiler options '-fconstant-int-class=kInt' and '-fconstant-float-class=kFloat' to generate the correct code. Why am I asking you to go to all this trouble? Because it's coherent with the string mechanism mentioned above and because the Objective-C language should't expect anything from its libraries, no class names and no method names, as much as possible. That is, only the structure of data is important, like a string object being expected to have a 'Class isa', a 'char* cString', and an 'unsigned int length'. The rest should be at the programmer's discretion. It's good design, I think.

shafik commented 5 months ago

CC @rjmccall @Bigcheese

rjmccall commented 5 months ago

As I understand it, @"string" produces a CF string literal unless you pass -mno-constant-cfstrings, which means that the object won't actually be of your class. ObjC is pretty lax as long as classes provide the same methods, but I don't think it's unreasonable for the compiler to not just assume that all string classes provide essentially the same methods. If you pass -mno-constant-cfstrings, it should change the type of the string literal to the -fconstant-string-class class.

As for your general point, I'd say Clang is open to patches that allow the compiler's use of the standard library to be configured. I'm not aware of anyone who's currently interested in doing that work, though.