summaryrefslogtreecommitdiff
path: root/tools/builder.nim
blob: 4207bf21c2f41a2f6b5ed9e6e01ad503ed61765d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
import os
import osproc
import sequtils
import strformat
import strutils

type
    Compiler* {.pure.} = enum
        Gcc
        Vcc
        Clang

    CompilerInfo* = tuple[
        name: string,
        compilerC: string,
        compilerCxx: string,
        compileTmpl: string,
        linkStaticTmpl: string,
        includeTmpl: string,
        defineTmpl: string,
    ]

    PublicHeader = ref object
        destination: string
        source: string

    StaticLibrary* = ref object of RootObj
        name*: string
        sources*: seq[string]
        defines*: seq[string]
        compilerOptions*: seq[string]
        includeDirectories*: seq[string]
        buildDirectory*: string
        publicHeaders*: seq[PublicHeader]

template compiler(name, settings: untyped): untyped =
    proc name: CompilerInfo {.compileTime.} = settings

compiler(gcc):
    result = (
        name: "gcc",
        compilerC: "gcc",
        compilerCxx: "g++",
        compileTmpl: "$compiler -c $options $includes -o $obj $source",
        linkStaticTmpl: "ar rcs $library $obj",
        includeTmpl: " -I$path",
        defineTmpl: " -D$define"
    )

compiler(vcc):
    result = (
        name: "vcc",
        compilerC: "cl",
        compilerCxx: "cl",
        compileTmpl: "$compiler /c $options $includes /Fo$obj $source",
        linkStaticTmpl: "lib /OUT:$library $obj",
        includeTmpl: " /I$path",
        defineTmpl: " /D$define"
    )

compiler(clang):
    result = gcc()
    result.name = "clang"
    result.compilerC = "clang"
    result.compilerCxx = "clang++"

const
    Compilers* = [
        gcc(),
        vcc(),
        clang(),
    ]

proc getCompiler*(): CompilerInfo {.compileTime.} =
    ## Return the compiler info.
    when hostOS == "windows":
        result = Compilers[Compiler.Vcc.int]
    elif hostOS == "macosx":
        result = Compilers[Compiler.Clang.int]
    else:
        result = Compilers[Compiler.Gcc.int]

proc newStaticLibrary*(name: string,
                       sourceDir: string): StaticLibrary =
    ## Initialize a new static library.
    ##
    ## Args:
    ##      name: The logical name of the library. The platform specific
    ##          filename is built from this name.
    ##      sourceDir: The source directory of the library. Relative filenames
    ##          are resolved relating to this directory.
    new(result)
    result.name = name
    result.sources = @[]
    result.defines = @[]
    result.compilerOptions = @[]
    result.includeDirectories = @[]
    result.buildDirectory = getTempDir() / &"build-{name}"
    result.publicHeaders = @[]

proc addIncludeDirectory*(library: StaticLibrary, dir: string) =
    ## Add an include directory for the library.
    add(library.includeDirectories, dir)

proc addSourceFiles*(library: StaticLibrary, sources: varargs[string]) =
    for source in sources:
        var source = source
        if not isAbsolute(source):
            source = expandFilename(source)
        add(library.sources, source)

proc addSourceFilesWithPattern*(library: StaticLibrary, pattern: string) =
    for file in walkFiles(pattern):
        addSourceFiles(library, file)

proc addPublicHeaders*(library: StaticLibrary, destination: string,
    headers: varargs[string]) =
    for header in headers:
        add(library.publicHeaders, PublicHeader(destination: destination,
            source: header))

proc prefix(library: StaticLibrary): string =
    ## Return the static library prefix.
    when defined(windows):
        result = ""
    else:
        result = "lib"

proc suffix(library: StaticLibrary): string =
    ## Return the static library suffix (extension).
    when defined(windows):
        result = ".lib"
    else:
        result = ".a"

proc fullName(library: StaticLibrary): string =
    ## Return the full name of a static library.
    result = &"{library.prefix}{library.name}{library.suffix}"

proc fullPath(library: StaticLibrary): string =
    ## Return the full path of a static library
    result = library.buildDirectory / fullName(library)

proc relativePath(path, start: string): string =
    ## Return the relative version of path.
    ##
    ## The returned path is relative to start. The procedure is translated into
    ## Nim from Python's relpath() from posixpath.py.
    let separators = { DirSep, AltSep }

    var startList: seq[string] = @[]
    for part in split(expandFilename(start), separators):
        add(startList, part)

    var pathList: seq[string] = @[]
    for part in split(expandFilename(path), separators):
        add(pathList, part)

    let minLen = min(len(startList), len(pathList))

    var commonLen = 0

    for value in zip(startList, pathList):
        if value.a == value.b:
            inc(commonLen)
        else:
            break

    let relList = cycle([ParDir], len(startList) - commonLen) & pathList[commonLen..^1]

    if len(relList) == 0:
        return $CurDir

    result = joinPath(relList)

proc objectFilename(library: StaticLibrary, source: string): string =
    ## Return the absolute object file path of a source file.
    var source = relativePath(source, getAppDir())
    source = changeFileExt(source, "obj")
    source = replace(source, "..", "__")
    result = library.buildDirectory / source

proc createParentDir(filename: string) =
    ## Create the parent directory of a file.
    let parent = parentDir(filename)
    createDir(parent)

proc echoAndExec(command: string): int =
    echo(command)
    result = execCmd(command)

proc compile(library: StaticLibrary): bool =
    ## Compile the sources of a static library.
    var includes = ""
    for path in library.includeDirectories:
        includes &= getCompiler().includeTmpl % ["path", path]

    var defines = ""
    for define in library.defines:
        defines &= getCompiler().defineTmpl % ["define", define]

    var options = ""
    for option in library.compilerOptions:
        options &= " " & option

    for source in library.sources:
        let obj = objectFilename(library, source)

        createParentDir(obj)

        let (_, _, ext) = splitFile(source)

        let compilerExe =
            if ext == ".c":
                getCompiler().compilerC
            else:
                getCompiler().compilerCxx

        let tmpl = getCompiler().compileTmpl

        let command = tmpl % [
            "compiler", compilerExe,
            "options", defines & options,
            "includes", includes,
            "obj", obj,
            "source", source
        ]

        if echoAndExec(command) != 0:
            return false

    result = true

proc link(library: StaticLibrary): bool =
    ## Link the static library.
    let outputPath = fullPath(library)

    for source in library.sources:
        let obj = objectFilename(library, source)

        let command =  getCompiler().linkStaticTmpl % [
            "library", outputPath,
            "obj", obj
        ]

        if echoAndExec(command) != 0:
            return false

    result = true

proc build*(library: StaticLibrary): bool =
    result = false
    if compile(library):
        result = link(library)

proc install*(library: StaticLibrary, destdir: string) =
    createDir(destdir / "lib")
    copyFile(fullPath(library), destdir / "lib" / fullName(library))

    for header in library.publicHeaders:
        let filename = extractFilename(header.source)
        createDir(destdir / header.destination)
        copyFile(header.source, destdir / header.destination / filename)