% Jay Krell
% jay.krell@cornell.edu
% October 18, 2006 in Windows cmd
% ported to Quake December 31, 2006 so it might be run at the right time in a build (ie: the first package, before m3core)
% Possibly also for a hypothetical Windows targeted non-Windows hosted build.
% 
% This is the second stage in producing Windows import .libs.
% Given Quake code snippets output by make-lib-1.cmd, produce
% .c and .def files and compile and link them. The .c files just
% contain empty functions with the right names and the Signatures --
% Signatures just being the right number of bytes of parameters, the
% right types are not needed.
%

%
% Historically CM3 (e.g. 5.2.6) was distributed with import libs that paralleled the Windows SDK import .libs,
% such ask kernel32.lib, user32.lib.
% The CM3 files had some special code in them for garbage collection purposes.
% The .libs only work in a small number situations -- such as particular linker versions.
% The special code is no longer needed, due to garbage collector changes.
% As well, SOME UNUSUAL toolset versions/configurations lack the import .libs.
% GENERALLY you will get them with the "w32api" package (available in Cygwin), or non-Express Visual C++,
% or the free (beer) Windows SDK download.
% Deleting the old CM3 import .libs is the important thing to achieve here, trivial.
% As well, one can avoid linking to them.
% Replacing the files is only rarely useful.
%
% All that is needed to produce import .libs is, roughly, a list of function names.
%  (Data can also be exported, but this is discouraged.)
% The number of bytes of parameters also needs to be known for x86 __stdcall functions,
% which are the common case. With this information in hand, one merely needs to write out
% dummy source files like:
%   void __stdcall Foo(int a, int b) { }
%
% where the number of bytes of parameters needs to be correct, but their types don't matter,
% the body of the functions don't matter and can be all void, and the return types don't matter.
%
% and a .def file:
% EXPORTS
%   Foo
%
% This quake code, along with associated data, generates such .c and .def files.
% This is a bit roundabount.
%
% Again, the critical step is deletion or non-use of the CM3 .libs that don't work with most linkers
% and contain unneeded garbage collection related code. The work done here to
% replace the files is redundant in most scenarios.
%


%
% Older versions of this file detail the various incompatibilities of the 5.2.6 import .libs
%

local Files = {
    "advapi32",
    "comctl32",
    "comdlg32",
    "gdi32",
    "glu32",
    "kernel32",
    "netapi32",
    "odbc32",
    "opengl32",
    "user32",
    "winspool",
    "wsock32",
}

local M3_WIN_IMPORT_LIBS_CC = ""
M3_WIN_IMPORT_LIBS_CC = "gcc"
M3_WIN_IMPORT_LIBS_CC = "cl"
if defined("SYSTEM_CC")
    M3_WIN_IMPORT_LIBS_CC = SYSTEM_CC
end

local Stale = [ ]
local AnyStale = FALSE

foreach File in Files
    deriveds(File, [ ".def", ".lib", ".dll", ".drv", ".exp", ".m3x" ])
end
deriveds("a", [ ".c", ".o", ".obj" ])
deriveds("", [".M3WEB"])
delete_file(INSTALL_ROOT & SL & "lib" & SL & "odbccp32.lib")

%
% Older Modula-3 toolsets, such as 5.1.3 from 2001, don't set M3_MODE.
% That is ok, we don't /really/ care about it, it just let's us
% implement "clean" correctly.
%
if not defined("M3_MODE")
    M3_MODE = ""
end
%
% neuter the data rather than indent the whole rest of the file
%
if equal(M3_MODE, "clean")
    Files = { }
end
if not equal(TARGET, "NT386")
    Files = { }
end
if defined("C_COMPILER")
  if not equal(C_COMPILER, "MS")
    Files = { }
  end
end
if defined("LINKER")
  if not equal(LINKER, "MS")
    Files = { }
  end
end

%
% Quake can't do math. We simulate it badly.
%

%
% These don't actually have be numbers. Using letters nets us valid C identifiers.
%
local readonly Integers = [
"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S"
]

% map an integer to an array of integers from 0 to that integer mins 1
% (Or at least that many unique values.)
local UpTo = { }

%
% The values here really do have to be increasing multiples of 4.
%
local readonly Times4 = {
"A":"0","B":"4","C":"8","D":"12","E":"16","F":"20","G":"24","H":"28","I":"32","J":"36",
"K":"40","L":"44","M":"48","N":"52","O":"56","P":"60","Q":"64","R":"68","S":"72",
}
local Divide4 = { }

local proc InitMath() is
    local u = [ ]
    foreach i in Integers
        %
        % Arrays have reference semantics. We must manually copy elements.
        %
        UpTo{i} = [ ]
        foreach j in u
            UpTo{i} += j
        end
        u += i
        Divide4{Times4{i}} = i
    end
end

InitMath()

local proc SourceFilePath(a) is
    return ".." & SL & "src" & SL & a
end

%
% This should be built-in.
%
local proc FileExists(a) is
  return not stale (a, a)
end

local proc PickExists(a, b) is
    if FileExists(a)
        return a
    end
    return b
end

local proc ObjFile(a) is
    return PickExists(a & ".obj", a & ".o")
end

foreach File in Files

    local readonly QuakeFileName = File & ".quake"
    local readonly LibFilePath = File & ".lib"

    LibdExport(LibFilePath)

    if stale(LibFilePath, SourceFilePath(QuakeFileName))

        AnyStale = TRUE
        Stale += File
        local readonly DefFilePath = File & ".def"
        local Extension = "dll"

        include(QuakeFileName)

        > DefFilePath in

            write("EXPORTS" & CR)

            foreach FunctionName in Files{File}
                if equal(FunctionName, "Extension")
                    Extension = Files{File}{"Extension"}
                else
                    local Signature = Files{File}{FunctionName}
                    if equal(Signature, "__cdecl")
                        write(" " & FunctionName & " = Z" & CR)
                    else
                        write(" " & FunctionName & " = " & Divide4{Signature} & CR)
                    end
                end
            end

            if not equal(Extension, "dll")
                write("LIBRARY " & File & "." & Extension & CR)
            end
        end

        %
        % .m3x files needed but not otherwise produced.
        %
        > File & ".m3x" in 
          write("")
        end
    end
end

if AnyStale

    local readonly CFilePath = "a.c"

    > CFilePath in
        write("typedef unsigned U;" & CR)
        write("void __cdecl Z(void) { }" & CR)

        foreach NumberOfParameters in Integers
            local ArgsIn = ""
            if equal(NumberOfParameters, "0")
                ArgsIn = "void"
            else
                foreach Parameter in UpTo{NumberOfParameters}
                    if not equal(Parameter, Integers[0])
                        ArgsIn = ArgsIn & ","
                    end
                    ArgsIn = ArgsIn & "U " & Parameter
                end
            end
            %
            % This is unavoidably confusing.
            % We end up with the symbols F0@0, F4@4, F8@8, etc.
            %
            write("void __stdcall " & NumberOfParameters & "(" & ArgsIn & ") { }" & CR)
        end
    end

    exec(M3_WIN_IMPORT_LIBS_CC, "-c", CFilePath)

    foreach File in Stale
        %
        % dlltool produces import .libs that don't quite work, at least with link.
        % ld produces import .libs that really don't work.
        % link produces import .libs that don't quite work with ld.
        %
        % Specifically ld does not seem to support the usage where
        % the symbols are __stdcall but the exports are plain.
        % Thus you either fail to link or fail to load.
        % Perhaps I couldn't find the right switches.
        %
        % Specifically with dlltool produced .libs, imports often
        % get dropped, leading to crashes.
        %
        % Specifically with ld consuming link .libs, same thing, imports are dropped.
        %
        % The problem is being seen with winspool.drv, so maybe it is about the non-.dll extension?
        %

        %
        % The .obj file is needed to match plain function names up with stdcall signatures.
        % Thus the import .lib has two strings, Foo, and _Foo@4 (and possibly __imp__Foo@4).
        % The compiler generates referenes to _Foo@4 (or __imp__Foo@4), which resolve to
        % import .lib entries that cause just "Foo" to be written in the .dll or .exe.
        %
        % Achieving this requires "source code", barely, and a .def file.
        % "Source code" is merely __stdcall functions with the right signatures --
        %  the right number of parameters, the functions can all be empty.
        %
        exec(
            "link",
            "-lib",
            "-nologo",
            "-nodefaultlib",
            "-def:" & File & ".def",
            ObjFile("a"),
            )
    end
end

if not equal(M3_MODE, "clean")
    %
    % .M3WEB needed but not otherwise produced.
    %
    > ".M3WEB" in 
      write("")
    end
end
