user3612132
user3612132

Reputation: 93

Is it allowed to have two structs with the same name?

I have the following code in some e file:

<'
package my_package;

struct packet {
    foo() is {
        print "Hello";
    };
};

'>

And my top file imports several files, including this one, and at some point it calls the foo() method.

Now, by mistake I added this code:

struct packet {};

in some other file (I just forgot that I already had a struct called “packet”), which is imported by top before the above file.

Strangely, when I tried to load the top file, I got this error:

*** Error: 'p' (of type main::packet) does not have 'foo()' method.
                at line 9 in top.e
        p.foo();

But why didn’t it fail already on the file that defines foo()?

It has a struct declaration for packet, but packet was already (mistakenly) declared in an earlier file, so why didn’t it give a duplicate type name error? Is it allowed to have two structs with the same name??

Upvotes: 1

Views: 130

Answers (2)

Tudor Timi
Tudor Timi

Reputation: 7573

You are allowed to have the same name for different structs, but they must be defined in different packages. In your case you first define packet in the my_package package. I'm guessing the other code you added was in some other file that did not have the line package my_package; in it. This means you defined another struct called packet in the main package. This effectively means that you have two different types: my_package::struct and main::struct. In main::packet you didn't define any foo() function (as you can see also from the error message). As Yuti mentions, in your top.e file you probably don't have a package declared, so the main package takes precedence over any other package.

As an exercise, if you change your code in top.e to my_package::packet instead of simply packet it's going to work. You can anyway see something is wrong from the error message. You know you expected my_package::packet, but you were creating a main::packet.

Have a look in the Specman e Language Reference, section 28, Encapsulation Constructs for more info on packages.

Upvotes: 2

Yuri Tsoglin
Yuri Tsoglin

Reputation: 963

Actually, it's not that the main package takes precedence. But when a type name is used in some file, the same package to which this file belongs, takes precedence. In this case, the top.e file probably didn't have any "package" statement, so it also belonged to package main. If top.e had "package my_package", then "packet" in it would resolve to my_package::packet (and not to main::packet), and there would be no error.

Upvotes: 3

Related Questions