17

I've made the example in Java but I think (not tested) that it works in other (all?) languages.

You have 2 files. First, M.java:

public class MType {
    XType x;
    MType() {x = null;}
}

Second, another file (in the same directory), XType.java:

public class XType {
   MType m;
   public XType(MType m) {this.m = m;}
}

Ok it's bad programming, but if you run javac XType it compiles: compiles even MType because XType needs it. But ... MType needs XType ... how does that work? How does the compiler know what is happening?

I would like to know how the compiler (javac or any other compilers you know) manages that situation, not how to avoid it.

I'm asking because I'm writing a precompiler and I would like to manage that situation.

2 Answers 2

9

You need to take a 2-pass, or multi-pass approach:

Languages like Java require a multi-pass compiler since the definition of x would not be required to come before the use:

public class Example {  
public static void main(String [] args) {
    assert(x==0);           
    x++;
    assert(x==1);
}
static int x=0;
}

There are various approaches, for example you could do the following:

The first pass could look for all variable declarations, the second for method declarations, etc. until the last pass uses all this information to compile the final code.

2
  • So when it compiles the second file the compiler already knows what the first is? Jun 13, 2010 at 16:38
  • 1
    @Fabio - Each pass of the compiler processes all the files gathering the information needed for the next pass.
    – ChrisF
    Jun 13, 2010 at 16:57
4

The first file doesn't need to know anything about XType except that it is a type, and similarly for MType in the second file. Also, in Java, all objects are effectively the same size (because everything is accessed through references), so the size of the object is not needed. This is not so in other languages - your code as it stands would not compile in C++, for example (language syntax apart).

3
  • 2
    but if use a method of XType? It must know methods of Xtype.. no? Jun 13, 2010 at 16:35
  • also, I'm not sure what you mean by "all objects are effectively the same size".
    – asgs
    Jun 18, 2016 at 17:32
  • 1
    He is referring to the fact that (for example) m holds a reference, and all references have the same size. But that's not the only information that is required about a type. It is also necessary to know its members and lots of information about its super-type hierarchy.
    – Stephen C
    Nov 18, 2016 at 5:50

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.