Hacker News new | ask | show | jobs
by JacobCarlborg 1953 days ago
In D, all semantic analysis is performed eagerly (I think), except for templates. D also supports CTFE (Compile Time Function Evaluation), `static if`, `static assert` and a few other language constructs that are evaluated at compile time.

I experimented a bit at how D's documentation generator behaves using these language constructs. Here's a snippet of some D code:

  /// some struct description
  struct Foo(T) // template
  {
      /// some alias description
      alias Result = int;
  
      /// some method description
      Result foo()
      {
          string a = 3; // this does not normally compile
      }
  
      static if (is(T == int)) // evaluated at compile time
      {
          /// some method description 2
          void bar() {}
      }
  
      version (Windows)
      {
          /// some method description for Windows
          void bazWindows() {}
      }
  
      else version (Posix)
      {
          /// some method description for Posix
          void bazPosix() {}
      }
  
      else
          static assert(false, "Unsupported platform"); // evaluated at compile time
  }
When generating documentation for the above code, and `Foo` has not been instantiated, the generated docs will include `Foo`, `Result`, `foo`, `bar`, and `bazWindows`. This is regardless of platform. The return type of `foo` will be `Result` and not `int`. This clearly shows that the D compiler doesn't perform semantic analysis when generating documentation. When doing a regular compilation and `Foo` is instantiated, `bar` will only be included if `T` is an `int`. `bazWindows` will only be compiled on Windows and `bazPosix` will only be compiled on Posix platforms.

Looking at the implementation, the compiler will generate the docs after semantic analysis and only if there are no errors. But, if `Foo` is never instantiated no errors have occurred so it will continue to generate the docs.

On the other hand, if `Foo` is instantiated (and compiles) the compiler will generate docs for the AST after semantic analysis has been performed and `bazWindows` will only be included if the docs were generated on Windows and `bazPosix` will only be included on Posix platforms. What's weird though, is that it seems `bar` will be included regardless of what type `T` is.